New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@decathlon/moon

Package Overview
Dependencies
Maintainers
4
Versions
45
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@decathlon/moon - npm Package Compare versions

Comparing version 4.0.0-beta.13 to 4.0.0-beta.14

lib/hooks.js

1068

dist/index.js

@@ -1,589 +0,591 @@

'use strict';
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react-query'), require('react'), require('react-query/hydration')) :
typeof define === 'function' && define.amd ? define(['exports', 'react-query', 'react', 'react-query/hydration'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Moon = {}, global.reactQuery, global.React, global.hydration));
}(this, (function (exports, reactQuery, React, hydration) { 'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
var reactQuery = require('react-query');
var React = require('react');
var hydration = require('react-query/hydration');
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
return __assign.apply(this, arguments);
};
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
/* eslint-disable import/prefer-default-export */
var queryClient;
function getClients(links, clientFactory) {
return links.reduce(function (clients, link) {
var linkClientFactory = link.clientFactory || clientFactory;
if (!linkClientFactory) {
throw new Error("A link client factory must be defined!");
}
clients[link.id] = linkClientFactory(link.config, link.interceptors);
return clients;
}, {});
}
function getMoonStore(store) {
if (store) {
queryClient = store;
return store;
}
return t;
}
/* eslint-disable import/prefer-default-export */
var queryClient;
function getClients(links, clientFactory) {
return links.reduce(function (clients, link) {
var linkClientFactory = link.clientFactory || clientFactory;
if (!linkClientFactory) {
throw new Error("A link client factory must be defined!");
if (queryClient) {
return queryClient;
}
clients[link.id] = linkClientFactory(link.config, link.interceptors);
return clients;
}, {});
}
function getMoonStore(store) {
if (store) {
queryClient = store;
return store;
}
if (queryClient) {
var queryCache = new reactQuery.QueryCache();
var mutationCache = new reactQuery.MutationCache();
queryClient = new reactQuery.QueryClient({
queryCache: queryCache,
mutationCache: mutationCache,
defaultOptions: {
queries: { refetchOnWindowFocus: false }
}
});
return queryClient;
}
var queryCache = new reactQuery.QueryCache();
var mutationCache = new reactQuery.MutationCache();
queryClient = new reactQuery.QueryClient({
queryCache: queryCache,
mutationCache: mutationCache,
defaultOptions: {
queries: { refetchOnWindowFocus: false }
}
});
return queryClient;
}
(function (MutateType) {
MutateType["Delete"] = "DELETE";
MutateType["Post"] = "POST";
MutateType["Put"] = "PUT";
})(exports.MutateType || (exports.MutateType = {}));
var MoonClient = /** @class */ (function () {
function MoonClient(links, clientFactory) {
this.clients = getClients(links, clientFactory);
}
MoonClient.prototype.getClientInstance = function (source) {
var clientsIds = Object.keys(this.clients);
if (clientsIds.length === 1) {
return this.clients[clientsIds[0]];
(function (MutateType) {
MutateType["Delete"] = "DELETE";
MutateType["Post"] = "POST";
MutateType["Put"] = "PUT";
})(exports.MutateType || (exports.MutateType = {}));
var MoonClient = /** @class */ (function () {
function MoonClient(links, clientFactory) {
this.clients = getClients(links, clientFactory);
}
return source !== undefined ? this.clients[source] : undefined;
};
MoonClient.prototype.query = function (source, endPoint, variables, options) {
var client = this.getClientInstance(source);
if (client) {
return client.get(endPoint || "", __assign(__assign({}, options), { params: __assign(__assign({}, options === null || options === void 0 ? void 0 : options.params), variables) }));
}
return new Promise(function (reject) { return reject(undefined); });
};
MoonClient.prototype.mutate = function (source, endPoint, type, variables, options) {
if (type === void 0) { type = exports.MutateType.Post; }
var client = this.getClientInstance(source);
var clientEndPoint = endPoint || "";
if (client) {
switch (type) {
case exports.MutateType.Delete: {
var mutationOptions = __assign(__assign({}, options), { params: __assign(__assign({}, options === null || options === void 0 ? void 0 : options.params), variables) });
return client.delete(clientEndPoint, mutationOptions);
MoonClient.prototype.getClientInstance = function (source) {
var clientsIds = Object.keys(this.clients);
if (clientsIds.length === 1) {
return this.clients[clientsIds[0]];
}
return source !== undefined ? this.clients[source] : undefined;
};
MoonClient.prototype.query = function (source, endPoint, variables, options) {
var client = this.getClientInstance(source);
if (client) {
return client.get(endPoint || "", __assign(__assign({}, options), { params: __assign(__assign({}, options === null || options === void 0 ? void 0 : options.params), variables) }));
}
return new Promise(function (reject) { return reject(undefined); });
};
MoonClient.prototype.mutate = function (source, endPoint, type, variables, options) {
if (type === void 0) { type = exports.MutateType.Post; }
var client = this.getClientInstance(source);
var clientEndPoint = endPoint || "";
if (client) {
switch (type) {
case exports.MutateType.Delete: {
var mutationOptions = __assign(__assign({}, options), { params: __assign(__assign({}, options === null || options === void 0 ? void 0 : options.params), variables) });
return client.delete(clientEndPoint, mutationOptions);
}
case exports.MutateType.Put:
return client.put(clientEndPoint, variables, options);
default:
return client.post(clientEndPoint, variables, options);
}
case exports.MutateType.Put:
return client.put(clientEndPoint, variables, options);
default:
return client.post(clientEndPoint, variables, options);
}
return new Promise(function (reject) { return reject(undefined); });
};
return MoonClient;
}());
var MoonContext = React.createContext({
client: null,
store: null
});
var MoonProvider = /** @class */ (function (_super) {
__extends(MoonProvider, _super);
function MoonProvider(props) {
var _this = _super.call(this, props) || this;
var _a = _this.props, links = _a.links, clientFactory = _a.clientFactory;
_this.client = new MoonClient(links, clientFactory);
return _this;
}
return new Promise(function (reject) { return reject(undefined); });
};
return MoonClient;
}());
MoonProvider.prototype.render = function () {
var _a = this.props, children = _a.children, hydrate = _a.hydrate, store = _a.store;
var queryClient = getMoonStore(store);
return (React.createElement(reactQuery.QueryClientProvider, { client: queryClient },
React.createElement(hydration.Hydrate, __assign({}, hydrate),
React.createElement(MoonContext.Provider, { value: { client: this.client, store: queryClient } }, children))));
};
return MoonProvider;
}(React.Component));
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function withMoon(WrappedComponent) {
var WithMoonComponent = function (_a) {
var forwardedRef = _a.forwardedRef, rest = __rest(_a, ["forwardedRef"]);
return (React.createElement(MoonContext.Consumer, null, function (_a) {
var client = _a.client, store = _a.store;
var componentProps = __assign({ client: client, store: store }, rest);
return React.createElement(WrappedComponent, __assign({ ref: forwardedRef }, componentProps));
}));
};
return React.forwardRef(function (props, ref) {
// @ts-ignore I don't know how to implement this without breaking out of the types.
return React.createElement(WithMoonComponent, __assign({ forwardedRef: ref }, props));
});
}
var MoonContext = React.createContext({
client: null,
store: null
});
var MoonProvider = /** @class */ (function (_super) {
__extends(MoonProvider, _super);
function MoonProvider(props) {
var _this = _super.call(this, props) || this;
var _a = _this.props, links = _a.links, clientFactory = _a.clientFactory;
_this.client = new MoonClient(links, clientFactory);
return _this;
}
MoonProvider.prototype.render = function () {
var _a = this.props, children = _a.children, hydrate = _a.hydrate, store = _a.store;
var queryClient = getMoonStore(store);
return (React.createElement(reactQuery.QueryClientProvider, { client: queryClient },
React.createElement(hydration.Hydrate, __assign({}, hydrate),
React.createElement(MoonContext.Provider, { value: { client: this.client, store: queryClient } }, children))));
/* eslint-disable import/prefer-default-export */
var isServer = typeof window === "undefined";
var hasOwn = Object.prototype.hasOwnProperty;
var getId = function (params) {
return params.id !== undefined ? params.id : stableStringify(params);
};
return MoonProvider;
}(React.Component));
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function withMoon(WrappedComponent) {
var WithMoonComponent = function (_a) {
var forwardedRef = _a.forwardedRef, rest = __rest(_a, ["forwardedRef"]);
return (React.createElement(MoonContext.Consumer, null, function (_a) {
var client = _a.client, store = _a.store;
var componentProps = __assign({ client: client, store: store }, rest);
return React.createElement(WrappedComponent, __assign({ ref: forwardedRef }, componentProps));
}));
};
return React.forwardRef(function (props, ref) {
// @ts-ignore I don't know how to implement this without breaking out of the types.
return React.createElement(WithMoonComponent, __assign({ forwardedRef: ref }, props));
});
}
/* eslint-disable import/prefer-default-export */
var isServer = typeof window === "undefined";
var hasOwn = Object.prototype.hasOwnProperty;
var getId = function (params) {
return params.id !== undefined ? params.id : stableStringify(params);
};
function stableStringify(value) {
return JSON.stringify(value, stableStringifyReplacer).replace(/(\r\n|\n|\r| )/gm, "");
}
function equal(objA, objB, deep) {
if (deep === void 0) { deep = false; }
if (is(objA, objB))
return true;
if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
return false;
function stableStringify(value) {
return JSON.stringify(value, stableStringifyReplacer).replace(/(\r\n|\n|\r| )/gm, "");
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length)
return false;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || !compare(objA[keysA[i]], objB[keysA[i]], deep)) {
function equal(objA, objB, deep) {
if (deep === void 0) { deep = false; }
if (is(objA, objB))
return true;
if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length)
return false;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || !compare(objA[keysA[i]], objB[keysA[i]], deep)) {
return false;
}
}
return true;
}
return true;
}
function compare(objA, objB, deep) {
return deep ? equal(objA, objB, deep) : is(objA, objB);
}
function is(x, y) {
if (x === y) {
return x !== 0 || y !== 0 || 1 / x === 1 / y;
function compare(objA, objB, deep) {
return deep ? equal(objA, objB, deep) : is(objA, objB);
}
return x !== x && y !== y;
}
// Copied from: https://github.com/jonschlinkert/is-plain-object
// eslint-disable-next-line @typescript-eslint/ban-types
function isPlainObject(o) {
if (!hasObjectPrototype(o)) {
return false;
function is(x, y) {
if (x === y) {
return x !== 0 || y !== 0 || 1 / x === 1 / y;
}
return x !== x && y !== y;
}
// If has modified constructor
var ctor = o.constructor;
if (typeof ctor === "undefined") {
// Copied from: https://github.com/jonschlinkert/is-plain-object
// eslint-disable-next-line @typescript-eslint/ban-types
function isPlainObject(o) {
if (!hasObjectPrototype(o)) {
return false;
}
// If has modified constructor
var ctor = o.constructor;
if (typeof ctor === "undefined") {
return true;
}
// If has modified prototype
var prot = ctor.prototype;
if (!hasObjectPrototype(prot)) {
return false;
}
// If constructor does not have an Object-specific method
// eslint-disable-next-line no-prototype-builtins
if (!prot.hasOwnProperty("isPrototypeOf")) {
return false;
}
// Most likely a plain Object
return true;
}
// If has modified prototype
var prot = ctor.prototype;
if (!hasObjectPrototype(prot)) {
return false;
function hasObjectPrototype(o) {
return Object.prototype.toString.call(o) === "[object Object]";
}
// If constructor does not have an Object-specific method
// eslint-disable-next-line no-prototype-builtins
if (!prot.hasOwnProperty("isPrototypeOf")) {
return false;
//Adapted from: https://github.com/tannerlinsley/react-query/blob/master/src/core/utils.ts
function stableStringifyReplacer(_key, value) {
if (typeof value === "function") {
return "function";
}
if (isPlainObject(value)) {
return Object.keys(value)
.sort()
.reduce(function (result, key) {
result[key] = JSON.stringify(value[key], stableStringifyReplacer);
return result;
}, {});
}
return value;
}
// Most likely a plain Object
return true;
}
function hasObjectPrototype(o) {
return Object.prototype.toString.call(o) === "[object Object]";
}
//Adapted from: https://github.com/tannerlinsley/react-query/blob/master/src/core/utils.ts
function stableStringifyReplacer(_key, value) {
if (typeof value === "function") {
return "function";
}
if (isPlainObject(value)) {
return Object.keys(value)
.sort()
.reduce(function (result, key) {
result[key] = JSON.stringify(value[key], stableStringifyReplacer);
return result;
}, {});
}
return value;
}
function getAdaptedQueryState(query) {
if (!query) {
return undefined;
function getAdaptedQueryState(query) {
if (!query) {
return undefined;
}
var networkOnly = (query === null || query === void 0 ? void 0 : query.cacheTime) === 0;
var state = query.state;
var isFetching = state.isFetching, data = state.data;
var queryData = isFetching && networkOnly ? undefined : data;
return __assign(__assign({}, state), { data: queryData });
}
var networkOnly = (query === null || query === void 0 ? void 0 : query.cacheTime) === 0;
var state = query.state;
var isFetching = state.isFetching, data = state.data;
var queryData = isFetching && networkOnly ? undefined : data;
return __assign(__assign({}, state), { data: queryData });
}
function useQueryObserver(queryId, getState, isInfinite) {
if (isInfinite === void 0) { isInfinite = false; }
var store = useMoon().store;
var isMounted = useIsMounted();
var query = store.getQueryCache().get(reactQuery.hashQueryKey(queryId));
var initialSate = getState(query);
var _a = React.useState(initialSate), state = _a[0], setState = _a[1];
var observerRef = React.useRef();
var defaultOptions = React.useMemo(function () { return store.defaultQueryObserverOptions({ queryKey: queryId, enabled: false }); }, [queryId]);
var createObserver = React.useCallback(function () {
return isInfinite ? new reactQuery.InfiniteQueryObserver(store, defaultOptions) : new reactQuery.QueryObserver(store, defaultOptions);
}, [isInfinite, store, defaultOptions]);
var observer = observerRef.current || createObserver();
observerRef.current = observer;
if (observer.hasListeners()) {
observer.setOptions(defaultOptions);
}
var listener = React.useCallback(function () {
if (isMounted()) {
var queryState = getState(query);
if (!equal(state || null, queryState || null)) {
setState(queryState);
function useQueryObserver(queryId, getState, isInfinite) {
if (isInfinite === void 0) { isInfinite = false; }
var store = useMoon().store;
var isMounted = useIsMounted();
var query = store.getQueryCache().get(reactQuery.hashQueryKey(queryId));
var initialSate = getState(query);
var _a = React.useState(initialSate), state = _a[0], setState = _a[1];
var observerRef = React.useRef();
var defaultOptions = React.useMemo(function () { return store.defaultQueryObserverOptions({ queryKey: queryId, enabled: false }); }, [queryId]);
var createObserver = React.useCallback(function () {
return isInfinite ? new reactQuery.InfiniteQueryObserver(store, defaultOptions) : new reactQuery.QueryObserver(store, defaultOptions);
}, [isInfinite, store, defaultOptions]);
var observer = observerRef.current || createObserver();
observerRef.current = observer;
if (observer.hasListeners()) {
observer.setOptions(defaultOptions);
}
var listener = React.useCallback(function () {
if (isMounted()) {
var queryState = getState(query);
if (!equal(state || null, queryState || null)) {
setState(queryState);
}
}
}
}, [queryId]);
React.useEffect(function () {
return observer.subscribe(reactQuery.notifyManager.batchCalls(listener));
}, [queryId]);
return state;
}
function useQueriesObserver(queriesIds, getState) {
var currentQueriesIds = usePrevValue(queriesIds).value;
var store = useMoon().store;
var isMounted = useIsMounted();
var queriesResults = React.useMemo(function () {
return currentQueriesIds.reduce(function (result, queryId) {
var query = store.getQueryCache().get(reactQuery.hashQueryKey(queryId));
result[queryId] = getState(query);
return result;
}, {});
}, [currentQueriesIds, store]);
var _a = React.useState(queriesResults), states = _a[0], setStates = _a[1];
var queries = React.useMemo(function () {
return queriesIds.map(function (queryId) { return store.defaultQueryObserverOptions({ queryKey: queryId, enabled: false }); });
}, [currentQueriesIds]);
var observerRef = React.useRef();
var observer = observerRef.current || new reactQuery.QueriesObserver(store, queries);
observerRef.current = observer;
if (observer.hasListeners()) {
observer.setQueries(queries);
}, [queryId]);
React.useEffect(function () {
return observer.subscribe(reactQuery.notifyManager.batchCalls(listener));
}, [queryId]);
return state;
}
var listener = React.useCallback(function () {
if (isMounted()) {
queriesIds.forEach(function (queryId) {
var _a;
function useQueriesObserver(queriesIds, getState) {
var currentQueriesIds = usePrevValue(queriesIds).value;
var store = useMoon().store;
var isMounted = useIsMounted();
var queriesResults = React.useMemo(function () {
return currentQueriesIds.reduce(function (result, queryId) {
var query = store.getQueryCache().get(reactQuery.hashQueryKey(queryId));
var queryState = getState(query);
if (!equal(states[queryId] || null, queryState || null)) {
setStates((_a = {}, _a[queryId] = queryState, _a));
}
});
result[queryId] = getState(query);
return result;
}, {});
}, [currentQueriesIds, store]);
var _a = React.useState(queriesResults), states = _a[0], setStates = _a[1];
var queries = React.useMemo(function () {
return queriesIds.map(function (queryId) { return store.defaultQueryObserverOptions({ queryKey: queryId, enabled: false }); });
}, [currentQueriesIds]);
var observerRef = React.useRef();
var observer = observerRef.current || new reactQuery.QueriesObserver(store, queries);
observerRef.current = observer;
if (observer.hasListeners()) {
observer.setQueries(queries);
}
}, [currentQueriesIds]);
React.useEffect(function () {
return observer.subscribe(reactQuery.notifyManager.batchCalls(listener));
}, [currentQueriesIds]);
return states;
}
function useQueryResult(queryId, resultToProps, isInfinite) {
if (isInfinite === void 0) { isInfinite = false; }
var getState = function (query) {
var queryState = getAdaptedQueryState(query);
return queryState === null || queryState === void 0 ? void 0 : queryState.data;
};
var queryResult = useQueryObserver(queryId, getState, isInfinite);
return resultToProps ? resultToProps(queryResult) : queryResult;
}
function useQueriesResults(queriesIds, resultsToProps) {
var getState = function (query) {
var queryState = getAdaptedQueryState(query);
return queryState === null || queryState === void 0 ? void 0 : queryState.data;
};
var queriesResult = useQueriesObserver(queriesIds, getState);
return resultsToProps ? resultsToProps(queriesResult) : queriesResult;
}
function useQueryState(queryId, stateToProps, isInfinite) {
if (isInfinite === void 0) { isInfinite = false; }
var queryResult = useQueryObserver(queryId, getAdaptedQueryState, isInfinite);
return stateToProps ? stateToProps(queryResult) : queryResult;
}
function useQueriesStates(queriesIds, statesToProps) {
var queriesResult = useQueriesObserver(queriesIds, getAdaptedQueryState);
return statesToProps ? statesToProps(queriesResult) : queriesResult;
}
function usePrevValue(value) {
var valueRef = React.useRef(value);
var prevValue = valueRef.current;
//@ts-ignore prevValue is an object
if (typeof prevValue === "object" && typeof value === "object" && !equal(prevValue, value, true)) {
valueRef.current = value;
var listener = React.useCallback(function () {
if (isMounted()) {
queriesIds.forEach(function (queryId) {
var _a;
var query = store.getQueryCache().get(reactQuery.hashQueryKey(queryId));
var queryState = getState(query);
if (!equal(states[queryId] || null, queryState || null)) {
setStates((_a = {}, _a[queryId] = queryState, _a));
}
});
}
}, [currentQueriesIds]);
React.useEffect(function () {
return observer.subscribe(reactQuery.notifyManager.batchCalls(listener));
}, [currentQueriesIds]);
return states;
}
return { value: valueRef.current, prevValue: prevValue };
}
function useMoon() {
var moonContext = React.useContext(MoonContext);
var client = moonContext.client, store = moonContext.store;
if (!client || !store) {
throw new Error("Invariant Violation: Please wrap the root component in a <MoonProvider>");
function useQueryResult(queryId, resultToProps, isInfinite) {
if (isInfinite === void 0) { isInfinite = false; }
var getState = function (query) {
var queryState = getAdaptedQueryState(query);
return queryState === null || queryState === void 0 ? void 0 : queryState.data;
};
var queryResult = useQueryObserver(queryId, getState, isInfinite);
return resultToProps ? resultToProps(queryResult) : queryResult;
}
return moonContext;
}
function useIsMounted() {
var mountedRef = React.useRef(false);
var isMounted = React.useCallback(function () { return mountedRef.current; }, []);
var useEffect = isServer ? React.useEffect : React.useLayoutEffect;
useEffect(function () {
mountedRef.current = true;
return function () {
mountedRef.current = false;
function useQueriesResults(queriesIds, resultsToProps) {
var getState = function (query) {
var queryState = getAdaptedQueryState(query);
return queryState === null || queryState === void 0 ? void 0 : queryState.data;
};
}, []);
return isMounted;
}
(function (FetchPolicy) {
// always try reading data from your cache first
FetchPolicy["CacheFirst"] = "cache-first";
// first trying to read data from your cache
FetchPolicy["CacheAndNetwork"] = "cache-and-network";
// never return you initial data from the cache
FetchPolicy["NetworkOnly"] = "network-only";
})(exports.FetchPolicy || (exports.FetchPolicy = {}));
var getQueryId = function (queryProps) {
return getId(queryProps);
};
function useQuery(_a) {
var id = _a.id, source = _a.source, endPoint = _a.endPoint, variables = _a.variables, options = _a.options, _b = _a.fetchPolicy, fetchPolicy = _b === void 0 ? exports.FetchPolicy.CacheAndNetwork : _b, queryConfig = _a.queryConfig;
var _c = useMoon(), client = _c.client, store = _c.store;
var isInitialMount = React.useRef(true);
var clientProps = { source: source, endPoint: endPoint, variables: variables };
var queryId = getQueryId(__assign({ id: id }, clientProps));
var _d = usePrevValue({ queryId: queryId, clientProps: clientProps }), value = _d.value, prevValue = _d.prevValue;
var cacheOnly = fetchPolicy === exports.FetchPolicy.CacheFirst;
var networkOnly = fetchPolicy === exports.FetchPolicy.NetworkOnly;
var queryOptions = React.useMemo(function () {
return store.defaultQueryObserverOptions(__assign(__assign({}, queryConfig), {
// to fix (react-query)
cacheTime: networkOnly ? 0 : queryConfig === null || queryConfig === void 0 ? void 0 : queryConfig.cacheTime }));
}, [queryConfig, networkOnly, store]);
if (isInitialMount.current && networkOnly) {
// remove cache if networkOnly
store.setQueryData(queryId, queryConfig === null || queryConfig === void 0 ? void 0 : queryConfig.initialData);
var queriesResult = useQueriesObserver(queriesIds, getState);
return resultsToProps ? resultsToProps(queriesResult) : queriesResult;
}
function fetch() {
var cachedResult = store.getQueryData(queryId, { exact: true });
return cacheOnly && cachedResult
? cachedResult
: client.query(source, endPoint, variables, options);
function useQueryState(queryId, stateToProps, isInfinite) {
if (isInfinite === void 0) { isInfinite = false; }
var queryResult = useQueryObserver(queryId, getAdaptedQueryState, isInfinite);
return stateToProps ? stateToProps(queryResult) : queryResult;
}
var queryResult = reactQuery.useQuery(queryId, fetch, queryOptions);
var refetch = queryResult.refetch, remove = queryResult.remove, others = __rest(queryResult, ["refetch", "remove"]);
React.useEffect(function () {
if (prevValue.queryId === value.queryId && !isInitialMount.current && (queryOptions === null || queryOptions === void 0 ? void 0 : queryOptions.enabled)) {
// refetch on update and when only client options have been changed
refetch();
function useQueriesStates(queriesIds, statesToProps) {
var queriesResult = useQueriesObserver(queriesIds, getAdaptedQueryState);
return statesToProps ? statesToProps(queriesResult) : queriesResult;
}
function usePrevValue(value) {
var valueRef = React.useRef(value);
var prevValue = valueRef.current;
//@ts-ignore prevValue is an object
if (typeof prevValue === "object" && typeof value === "object" && !equal(prevValue, value, true)) {
valueRef.current = value;
}
}, [value.clientProps]);
React.useEffect(function () {
isInitialMount.current = false;
}, []);
function cancel() {
store.cancelQueries(queryId, { exact: true });
return { value: valueRef.current, prevValue: prevValue };
}
var data = networkOnly && others.isFetching ? undefined : others.data;
return [
__assign(__assign({}, others), { data: data }),
{ refetch: refetch, remove: remove, cancel: cancel }
];
}
function useMoon() {
var moonContext = React.useContext(MoonContext);
var client = moonContext.client, store = moonContext.store;
if (!client || !store) {
throw new Error("Invariant Violation: Please wrap the root component in a <MoonProvider>");
}
return moonContext;
}
function useIsMounted() {
var mountedRef = React.useRef(false);
var isMounted = React.useCallback(function () { return mountedRef.current; }, []);
var useEffect = isServer ? React.useEffect : React.useLayoutEffect;
useEffect(function () {
mountedRef.current = true;
return function () {
mountedRef.current = false;
};
}, []);
return isMounted;
}
function Query(props
// eslint-disable-next-line no-undef
) {
var children = props.children, queryProps = __rest(props, ["children"]);
var _a = useQuery(queryProps), state = _a[0], actions = _a[1];
return children ? children(__assign(__assign({}, state), { actions: actions })) : null;
}
Query.defaultProps = {
fetchPolicy: exports.FetchPolicy.CacheAndNetwork
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function withQueryResult(queryId, resutToProps) {
return function (WrappedComponent) {
var WithQueryComponent = function (props) {
var forwardedRef = props.forwardedRef, rest = __rest(props, ["forwardedRef"]);
var queryResult = useQueryResult(queryId, resutToProps);
var queryProps = resutToProps
? queryResult
: { queryResult: queryResult };
var componentProps = __assign(__assign({}, queryProps), rest);
return React.createElement(WrappedComponent, __assign({ ref: forwardedRef }, componentProps));
};
return React.forwardRef(function (props, ref) {
// @ts-ignore I don't know how to implement this without breaking out of the types.
return React.createElement(WithQueryComponent, __assign({ forwardedRef: ref }, props));
});
(function (FetchPolicy) {
// always try reading data from your cache first
FetchPolicy["CacheFirst"] = "cache-first";
// first trying to read data from your cache
FetchPolicy["CacheAndNetwork"] = "cache-and-network";
// never return you initial data from the cache
FetchPolicy["NetworkOnly"] = "network-only";
})(exports.FetchPolicy || (exports.FetchPolicy = {}));
var getQueryId = function (queryProps) {
return getId(queryProps);
};
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function withQueriesResults(queriesIds, resultsToProps) {
return function (WrappedComponent) {
var WithQueryComponent = function (props) {
var forwardedRef = props.forwardedRef, rest = __rest(props, ["forwardedRef"]);
var queriesResults = useQueriesResults(queriesIds, resultsToProps);
var componentProps = __assign({ queriesResults: queriesResults }, rest);
return React.createElement(WrappedComponent, __assign({ ref: forwardedRef }, componentProps));
function useQuery(_a) {
var id = _a.id, source = _a.source, endPoint = _a.endPoint, variables = _a.variables, options = _a.options, _b = _a.fetchPolicy, fetchPolicy = _b === void 0 ? exports.FetchPolicy.CacheAndNetwork : _b, queryConfig = _a.queryConfig;
var _c = useMoon(), client = _c.client, store = _c.store;
var isInitialMount = React.useRef(true);
var clientProps = { source: source, endPoint: endPoint, variables: variables };
var queryId = getQueryId(__assign({ id: id }, clientProps));
var _d = usePrevValue({ queryId: queryId, clientProps: clientProps }), value = _d.value, prevValue = _d.prevValue;
var cacheOnly = fetchPolicy === exports.FetchPolicy.CacheFirst;
var networkOnly = fetchPolicy === exports.FetchPolicy.NetworkOnly;
var queryOptions = React.useMemo(function () {
return store.defaultQueryObserverOptions(__assign(__assign({}, queryConfig), {
// to fix (react-query)
cacheTime: networkOnly ? 0 : queryConfig === null || queryConfig === void 0 ? void 0 : queryConfig.cacheTime }));
}, [queryConfig, networkOnly, store]);
if (isInitialMount.current && networkOnly) {
// remove cache if networkOnly
store.setQueryData(queryId, queryConfig === null || queryConfig === void 0 ? void 0 : queryConfig.initialData);
}
function fetch() {
var cachedResult = store.getQueryData(queryId, { exact: true });
return cacheOnly && cachedResult
? cachedResult
: client.query(source, endPoint, variables, options);
}
var queryResult = reactQuery.useQuery(queryId, fetch, queryOptions);
var refetch = queryResult.refetch, remove = queryResult.remove, others = __rest(queryResult, ["refetch", "remove"]);
React.useEffect(function () {
if (prevValue.queryId === value.queryId && !isInitialMount.current && (queryOptions === null || queryOptions === void 0 ? void 0 : queryOptions.enabled)) {
// refetch on update and when only client options have been changed
refetch();
}
}, [value.clientProps]);
React.useEffect(function () {
isInitialMount.current = false;
}, []);
function cancel() {
store.cancelQueries(queryId, { exact: true });
}
var data = networkOnly && others.isFetching ? undefined : others.data;
return [
__assign(__assign({}, others), { data: data }),
{ refetch: refetch, remove: remove, cancel: cancel }
];
}
function Query(props
// eslint-disable-next-line no-undef
) {
var children = props.children, queryProps = __rest(props, ["children"]);
var _a = useQuery(queryProps), state = _a[0], actions = _a[1];
return children ? children(__assign(__assign({}, state), { actions: actions })) : null;
}
Query.defaultProps = {
fetchPolicy: exports.FetchPolicy.CacheAndNetwork
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function withQueryResult(queryId, resutToProps) {
return function (WrappedComponent) {
var WithQueryComponent = function (props) {
var forwardedRef = props.forwardedRef, rest = __rest(props, ["forwardedRef"]);
var queryResult = useQueryResult(queryId, resutToProps);
var queryProps = resutToProps
? queryResult
: { queryResult: queryResult };
var componentProps = __assign(__assign({}, queryProps), rest);
return React.createElement(WrappedComponent, __assign({ ref: forwardedRef }, componentProps));
};
return React.forwardRef(function (props, ref) {
// @ts-ignore I don't know how to implement this without breaking out of the types.
return React.createElement(WithQueryComponent, __assign({ forwardedRef: ref }, props));
});
};
return React.forwardRef(function (props, ref) {
// @ts-ignore I don't know how to implement this without breaking out of the types.
return React.createElement(WithQueryComponent, __assign({ forwardedRef: ref }, props));
});
};
}
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function withQueriesResults(queriesIds, resultsToProps) {
return function (WrappedComponent) {
var WithQueryComponent = function (props) {
var forwardedRef = props.forwardedRef, rest = __rest(props, ["forwardedRef"]);
var queriesResults = useQueriesResults(queriesIds, resultsToProps);
var componentProps = __assign({ queriesResults: queriesResults }, rest);
return React.createElement(WrappedComponent, __assign({ ref: forwardedRef }, componentProps));
};
return React.forwardRef(function (props, ref) {
// @ts-ignore I don't know how to implement this without breaking out of the types.
return React.createElement(WithQueryComponent, __assign({ forwardedRef: ref }, props));
});
};
}
function useMutation(_a) {
var source = _a.source, endPoint = _a.endPoint, type = _a.type, variables = _a.variables, options = _a.options, mutationConfig = _a.mutationConfig;
var client = useMoon().client;
function mutation() {
return client.mutate(source, endPoint, type, variables, options);
function useMutation(_a) {
var source = _a.source, endPoint = _a.endPoint, type = _a.type, variables = _a.variables, options = _a.options, mutationConfig = _a.mutationConfig;
var client = useMoon().client;
function mutation() {
return client.mutate(source, endPoint, type, variables, options);
}
var _b = reactQuery.useMutation(mutation, mutationConfig), reactQueryMutate = _b.mutate, reactQueryMutateAsync = _b.mutateAsync, reset = _b.reset, others = __rest(_b, ["mutate", "mutateAsync", "reset"]);
var mutate = React.useCallback(function () {
return reactQueryMutate(variables);
}, [variables]);
var mutateAsync = React.useCallback(function () {
return reactQueryMutateAsync(variables);
}, [variables]);
return [others, { mutate: mutate, mutateAsync: mutateAsync, reset: reset }];
}
var _b = reactQuery.useMutation(mutation, mutationConfig), reactQueryMutate = _b.mutate, reactQueryMutateAsync = _b.mutateAsync, reset = _b.reset, others = __rest(_b, ["mutate", "mutateAsync", "reset"]);
var mutate = React.useCallback(function () {
return reactQueryMutate(variables);
}, [variables]);
var mutateAsync = React.useCallback(function () {
return reactQueryMutateAsync(variables);
}, [variables]);
return [others, { mutate: mutate, mutateAsync: mutateAsync, reset: reset }];
}
function Mutation(props
// eslint-disable-next-line no-undef
) {
var children = props.children, mutationProps = __rest(props, ["children"]);
var _a = useMutation(mutationProps), state = _a[0], actions = _a[1];
return children ? children(__assign(__assign({}, state), { actions: actions })) : null;
}
Mutation.defaultProps = {
type: exports.MutateType.Post
};
function Mutation(props
// eslint-disable-next-line no-undef
) {
var children = props.children, mutationProps = __rest(props, ["children"]);
var _a = useMutation(mutationProps), state = _a[0], actions = _a[1];
return children ? children(__assign(__assign({}, state), { actions: actions })) : null;
}
Mutation.defaultProps = {
type: exports.MutateType.Post
};
function useInfiniteQuery(_a) {
var id = _a.id, source = _a.source, endPoint = _a.endPoint, variables = _a.variables, options = _a.options, queryConfig = _a.queryConfig;
var _b = useMoon(), client = _b.client, store = _b.store;
var isInitialMount = React.useRef(true);
var clientProps = { source: source, endPoint: endPoint, variables: variables };
var queryId = getQueryId(__assign({ id: id }, clientProps));
var _c = usePrevValue({ queryId: queryId, clientProps: clientProps }), value = _c.value, prevValue = _c.prevValue;
var queryOptions = React.useMemo(function () { return store.defaultQueryObserverOptions(queryConfig); }, [queryConfig, store]);
function fetch(_a) {
var pageParam = _a.pageParam;
var queryVariables = __assign(__assign({}, variables), pageParam);
return client.query(source, endPoint, queryVariables, options);
}
var queryResult = reactQuery.useInfiniteQuery(queryId, fetch, queryOptions);
var fetchNextPage = queryResult.fetchNextPage, fetchPreviousPage = queryResult.fetchPreviousPage, refetch = queryResult.refetch, remove = queryResult.remove, others = __rest(queryResult, ["fetchNextPage", "fetchPreviousPage", "refetch", "remove"]);
React.useEffect(function () {
if (prevValue.queryId === value.queryId && !isInitialMount.current && (queryOptions === null || queryOptions === void 0 ? void 0 : queryOptions.enabled)) {
// refetch on update and when only client options have been changed
refetch();
function useInfiniteQuery(_a) {
var id = _a.id, source = _a.source, endPoint = _a.endPoint, variables = _a.variables, options = _a.options, queryConfig = _a.queryConfig;
var _b = useMoon(), client = _b.client, store = _b.store;
var isInitialMount = React.useRef(true);
var clientProps = { source: source, endPoint: endPoint, variables: variables };
var queryId = getQueryId(__assign({ id: id }, clientProps));
var _c = usePrevValue({ queryId: queryId, clientProps: clientProps }), value = _c.value, prevValue = _c.prevValue;
var queryOptions = React.useMemo(function () { return store.defaultQueryObserverOptions(queryConfig); }, [queryConfig, store]);
function fetch(_a) {
var pageParam = _a.pageParam;
var queryVariables = __assign(__assign({}, variables), pageParam);
return client.query(source, endPoint, queryVariables, options);
}
}, [value.clientProps]);
React.useEffect(function () {
isInitialMount.current = false;
}, []);
function cancel() {
store.cancelQueries(queryId, { exact: true });
var queryResult = reactQuery.useInfiniteQuery(queryId, fetch, queryOptions);
var fetchNextPage = queryResult.fetchNextPage, fetchPreviousPage = queryResult.fetchPreviousPage, refetch = queryResult.refetch, remove = queryResult.remove, others = __rest(queryResult, ["fetchNextPage", "fetchPreviousPage", "refetch", "remove"]);
React.useEffect(function () {
if (prevValue.queryId === value.queryId && !isInitialMount.current && (queryOptions === null || queryOptions === void 0 ? void 0 : queryOptions.enabled)) {
// refetch on update and when only client options have been changed
refetch();
}
}, [value.clientProps]);
React.useEffect(function () {
isInitialMount.current = false;
}, []);
function cancel() {
store.cancelQueries(queryId, { exact: true });
}
return [others, { fetchNextPage: fetchNextPage, fetchPreviousPage: fetchPreviousPage, remove: remove, refetch: refetch, cancel: cancel }];
}
return [others, { fetchNextPage: fetchNextPage, fetchPreviousPage: fetchPreviousPage, remove: remove, refetch: refetch, cancel: cancel }];
}
function InfiniteQuery(props
// eslint-disable-next-line no-undef
) {
var children = props.children, queryProps = __rest(props, ["children"]);
var _a = useInfiniteQuery(queryProps), state = _a[0], actions = _a[1];
return children ? children(__assign(__assign({}, state), { actions: actions })) : null;
}
function InfiniteQuery(props
// eslint-disable-next-line no-undef
) {
var children = props.children, queryProps = __rest(props, ["children"]);
var _a = useInfiniteQuery(queryProps), state = _a[0], actions = _a[1];
return children ? children(__assign(__assign({}, state), { actions: actions })) : null;
}
Object.keys(reactQuery).forEach(function (k) {
if (k !== 'default') Object.defineProperty(exports, k, {
enumerable: true,
get: function () {
return reactQuery[k];
}
Object.keys(reactQuery).forEach(function (k) {
if (k !== 'default') Object.defineProperty(exports, k, {
enumerable: true,
get: function () {
return reactQuery[k];
}
});
});
});
exports.InfiniteQuery = InfiniteQuery;
exports.MoonClient = MoonClient;
exports.MoonContext = MoonContext;
exports.MoonProvider = MoonProvider;
exports.Mutation = Mutation;
exports.Query = Query;
exports.equal = equal;
exports.getAdaptedQueryState = getAdaptedQueryState;
exports.getClients = getClients;
exports.getId = getId;
exports.getMoonStore = getMoonStore;
exports.getQueryId = getQueryId;
exports.isServer = isServer;
exports.stableStringify = stableStringify;
exports.useInfiniteQuery = useInfiniteQuery;
exports.useIsMounted = useIsMounted;
exports.useMoon = useMoon;
exports.useMutation = useMutation;
exports.usePrevValue = usePrevValue;
exports.useQueriesObserver = useQueriesObserver;
exports.useQueriesResults = useQueriesResults;
exports.useQueriesStates = useQueriesStates;
exports.useQuery = useQuery;
exports.useQueryObserver = useQueryObserver;
exports.useQueryResult = useQueryResult;
exports.useQueryState = useQueryState;
exports.withMoon = withMoon;
exports.withQueriesResults = withQueriesResults;
exports.withQueryResult = withQueryResult;
exports.InfiniteQuery = InfiniteQuery;
exports.MoonClient = MoonClient;
exports.MoonContext = MoonContext;
exports.MoonProvider = MoonProvider;
exports.Mutation = Mutation;
exports.Query = Query;
exports.equal = equal;
exports.getAdaptedQueryState = getAdaptedQueryState;
exports.getClients = getClients;
exports.getId = getId;
exports.getMoonStore = getMoonStore;
exports.getQueryId = getQueryId;
exports.isServer = isServer;
exports.stableStringify = stableStringify;
exports.useInfiniteQuery = useInfiniteQuery;
exports.useIsMounted = useIsMounted;
exports.useMoon = useMoon;
exports.useMutation = useMutation;
exports.usePrevValue = usePrevValue;
exports.useQueriesObserver = useQueriesObserver;
exports.useQueriesResults = useQueriesResults;
exports.useQueriesStates = useQueriesStates;
exports.useQuery = useQuery;
exports.useQueryObserver = useQueryObserver;
exports.useQueryResult = useQueryResult;
exports.useQueryState = useQueryState;
exports.withMoon = withMoon;
exports.withQueriesResults = withQueriesResults;
exports.withQueryResult = withQueryResult;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=index.js.map
{
"name": "@decathlon/moon",
"version": "4.0.0-beta.13",
"version": "4.0.0-beta.14",
"description": "A featured, production ready caching REST client for every React UI",
"author": "Decathlon",
"license": "Apache-2.0",
"main": "dist/index.js",
"main": "lib/index.js",
"module": "dist/index.es.js",

@@ -20,3 +20,4 @@ "jsnext:main": "dist/index.es.js",

"files": [
"dist"
"dist",
"lib"
],

@@ -28,3 +29,4 @@ "peerDependencies": {

"scripts": {
"build": "rimraf dist && rollup -c",
"build": "rimraf dist && rollup -c && npm run build:lib",
"build:lib": "rimraf ./lib && tsc --project tsconfig.es.json --module 'CommonJS' --outDir ./lib",
"pack": "npm pack",

@@ -58,3 +60,3 @@ "prepublish": "npm run build",

},
"gitHead": "1ed91ae8c0bba58671c2cab1bcb18e43cafe9619"
"gitHead": "7f07547169c8036d64994235b59f4b4bf3de008d"
}

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc