@acrool/react-fetcher 0.0.7-alpha.1 → 0.0.7-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -542,543 +542,269 @@ function D(e2, t2) {
542
542
  };
543
543
  return !w(e2, r2);
544
544
  }
545
- class FetcherException extends Error {
546
- constructor(response) {
547
- super(response.message);
548
- __publicField(this, "code");
549
- __publicField(this, "args");
550
- __publicField(this, "path");
551
- this.response = response;
552
- this.code = response.code;
553
- this.args = response.args;
554
- this.path = response.path;
555
- this.name = this.constructor.name;
556
- Object.setPrototypeOf(this, FetcherException.prototype);
545
+ function bind(fn, thisArg) {
546
+ return function wrap() {
547
+ return fn.apply(thisArg, arguments);
548
+ };
549
+ }
550
+ const { toString } = Object.prototype;
551
+ const { getPrototypeOf } = Object;
552
+ const { iterator, toStringTag } = Symbol;
553
+ const kindOf = /* @__PURE__ */ ((cache) => (thing) => {
554
+ const str = toString.call(thing);
555
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
556
+ })(/* @__PURE__ */ Object.create(null));
557
+ const kindOfTest = (type) => {
558
+ type = type.toLowerCase();
559
+ return (thing) => kindOf(thing) === type;
560
+ };
561
+ const typeOfTest = (type) => (thing) => typeof thing === type;
562
+ const { isArray } = Array;
563
+ const isUndefined = typeOfTest("undefined");
564
+ function isBuffer(val) {
565
+ return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
566
+ }
567
+ const isArrayBuffer = kindOfTest("ArrayBuffer");
568
+ function isArrayBufferView(val) {
569
+ let result;
570
+ if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
571
+ result = ArrayBuffer.isView(val);
572
+ } else {
573
+ result = val && val.buffer && isArrayBuffer(val.buffer);
557
574
  }
575
+ return result;
558
576
  }
559
- const AuthStateContext = createContext({
560
- lastUpdateTimestamp: 0,
561
- isAuth: false,
562
- getTokens: () => {
563
- u.warning("AuthStateContext", "getTokens not yet ready");
564
- return null;
565
- },
566
- updateTokens: () => u.warning("AuthStateContext", "updateTokens not yet ready"),
567
- forceLogout: () => u.warning("AuthStateContext", "forceLogout not yet ready"),
568
- refreshTokens: async () => {
569
- u.warning("AuthStateContext", "refreshToken not yet ready");
570
- return void 0;
577
+ const isString = typeOfTest("string");
578
+ const isFunction = typeOfTest("function");
579
+ const isNumber = typeOfTest("number");
580
+ const isObject = (thing) => thing !== null && typeof thing === "object";
581
+ const isBoolean = (thing) => thing === true || thing === false;
582
+ const isPlainObject = (val) => {
583
+ if (kindOf(val) !== "object") {
584
+ return false;
571
585
  }
572
- });
573
- const useAuthState = () => useContext(AuthStateContext);
574
- const AuthStateProvider = ({
575
- children,
576
- onGetTokens,
577
- onSetTokens,
578
- onRefreshTokens,
579
- onForceLogout,
580
- isDebug = false
581
- }) => {
582
- const [lastUpdateTimestamp, setLastUpdateTimestamp] = useState(0);
583
- const [isAuth, setIsAuth] = useState(() => {
584
- return D(onGetTokens());
585
- });
586
- const updateTokens = (tokensOrUpdater) => {
587
- let nextTokens;
588
- if (typeof tokensOrUpdater === "function") {
589
- nextTokens = tokensOrUpdater(onGetTokens());
590
- } else {
591
- nextTokens = tokensOrUpdater;
592
- }
593
- onSetTokens(nextTokens);
594
- setIsAuth(D(nextTokens));
595
- setLastUpdateTimestamp(Date.now());
596
- };
597
- const handleOnForceLogout = () => {
598
- updateTokens(null);
599
- if (onForceLogout) {
600
- onForceLogout();
601
- }
602
- };
603
- const handleOnRefreshTokens = async () => {
604
- var _a;
605
- const refreshToken = (_a = onGetTokens()) == null ? void 0 : _a.refreshToken;
606
- if (!refreshToken || !onRefreshTokens) {
607
- if (isDebug) u.danger("[AuthStateProvider] handleOnRefreshTokens", "refreshToken|onRefreshTokens empty");
608
- throw new FetcherException({ message: "refreshToken|onRefreshTokens empty", code: "REFRESH_TOKEN_EMPTY" });
609
- }
610
- try {
611
- const authTokens = await onRefreshTokens(refreshToken);
612
- if (w(authTokens)) {
613
- if (isDebug) u.danger("[AuthStateProvider] handleOnRefreshTokens", "new refresh token fail");
614
- throw new FetcherException({ message: "new refresh token fail", code: "NEW_REFRESH_TOKEN_EMPTY" });
615
- }
616
- updateTokens(authTokens);
617
- return;
618
- } catch (err) {
619
- handleOnForceLogout();
620
- throw new FetcherException({ message: "refresh token fail", code: "REFRESH_TOKEN_CATCH" });
621
- }
622
- };
623
- return /* @__PURE__ */ jsxRuntimeExports.jsx(AuthStateContext.Provider, { value: {
624
- lastUpdateTimestamp,
625
- isAuth,
626
- getTokens: onGetTokens,
627
- updateTokens,
628
- refreshTokens: handleOnRefreshTokens,
629
- forceLogout: handleOnForceLogout
630
- }, children });
586
+ const prototype2 = getPrototypeOf(val);
587
+ return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(toStringTag in val) && !(iterator in val);
631
588
  };
632
- class AxiosCancelException extends Error {
633
- constructor(response) {
634
- super(response.message);
635
- __publicField(this, "code");
636
- __publicField(this, "devInfo");
637
- __publicField(this, "args");
638
- __publicField(this, "path");
639
- this.response = response;
640
- this.code = response.code;
641
- this.args = response.args;
642
- this.path = response.path;
643
- this.initName();
589
+ const isDate = kindOfTest("Date");
590
+ const isFile = kindOfTest("File");
591
+ const isBlob = kindOfTest("Blob");
592
+ const isFileList = kindOfTest("FileList");
593
+ const isStream = (val) => isObject(val) && isFunction(val.pipe);
594
+ const isFormData = (thing) => {
595
+ let kind;
596
+ return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
597
+ kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]"));
598
+ };
599
+ const isURLSearchParams = kindOfTest("URLSearchParams");
600
+ const [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
601
+ const trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
602
+ function forEach(obj, fn, { allOwnKeys = false } = {}) {
603
+ if (obj === null || typeof obj === "undefined") {
604
+ return;
644
605
  }
645
- initName() {
646
- this.name = this.constructor.name;
606
+ let i2;
607
+ let l2;
608
+ if (typeof obj !== "object") {
609
+ obj = [obj];
647
610
  }
648
- getInfo() {
649
- return {
650
- message: this.response.message,
651
- code: this.response.code,
652
- args: this.response.args,
653
- path: this.response.path
654
- };
611
+ if (isArray(obj)) {
612
+ for (i2 = 0, l2 = obj.length; i2 < l2; i2++) {
613
+ fn.call(null, obj[i2], i2, obj);
614
+ }
615
+ } else {
616
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
617
+ const len = keys.length;
618
+ let key;
619
+ for (i2 = 0; i2 < len; i2++) {
620
+ key = keys[i2];
621
+ fn.call(null, obj[key], key, obj);
622
+ }
655
623
  }
656
624
  }
657
- const getGraphQLResponseFormatError = (axiosError) => {
658
- var _a, _b, _c;
659
- const responseData = (_a = axiosError == null ? void 0 : axiosError.response) == null ? void 0 : _a.data;
660
- if ((_b = responseData.errors) == null ? void 0 : _b[0]) {
661
- return (_c = responseData.errors) == null ? void 0 : _c[0];
662
- }
663
- if (axiosError == null ? void 0 : axiosError.isAxiosError) {
664
- return {
665
- message: axiosError.message,
666
- code: axiosError.code
667
- };
625
+ function findKey(obj, key) {
626
+ key = key.toLowerCase();
627
+ const keys = Object.keys(obj);
628
+ let i2 = keys.length;
629
+ let _key;
630
+ while (i2-- > 0) {
631
+ _key = keys[i2];
632
+ if (key === _key.toLowerCase()) {
633
+ return _key;
634
+ }
668
635
  }
669
- return {
670
- message: "Axios error",
671
- code: "ERR_SYS_BAD_RESPONSE"
636
+ return null;
637
+ }
638
+ const _global = (() => {
639
+ if (typeof globalThis !== "undefined") return globalThis;
640
+ return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
641
+ })();
642
+ const isContextDefined = (context) => !isUndefined(context) && context !== _global;
643
+ function merge() {
644
+ const { caseless } = isContextDefined(this) && this || {};
645
+ const result = {};
646
+ const assignValue = (val, key) => {
647
+ const targetKey = caseless && findKey(result, key) || key;
648
+ if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
649
+ result[targetKey] = merge(result[targetKey], val);
650
+ } else if (isPlainObject(val)) {
651
+ result[targetKey] = merge({}, val);
652
+ } else if (isArray(val)) {
653
+ result[targetKey] = val.slice();
654
+ } else {
655
+ result[targetKey] = val;
656
+ }
672
657
  };
673
- };
674
- const getRestFulResponseFormatError = (axiosError) => {
675
- var _a;
676
- const responseData = (_a = axiosError == null ? void 0 : axiosError.response) == null ? void 0 : _a.data;
677
- if (responseData) {
678
- return responseData;
658
+ for (let i2 = 0, l2 = arguments.length; i2 < l2; i2++) {
659
+ arguments[i2] && forEach(arguments[i2], assignValue);
679
660
  }
680
- if (axiosError == null ? void 0 : axiosError.isAxiosError) {
681
- return {
682
- message: axiosError.message,
683
- code: axiosError.code
684
- };
661
+ return result;
662
+ }
663
+ const extend = (a2, b, thisArg, { allOwnKeys } = {}) => {
664
+ forEach(b, (val, key) => {
665
+ if (thisArg && isFunction(val)) {
666
+ a2[key] = bind(val, thisArg);
667
+ } else {
668
+ a2[key] = val;
669
+ }
670
+ }, { allOwnKeys });
671
+ return a2;
672
+ };
673
+ const stripBOM = (content) => {
674
+ if (content.charCodeAt(0) === 65279) {
675
+ content = content.slice(1);
685
676
  }
686
- return {
687
- message: "Axios error",
688
- code: "ERR_SYS_BAD_RESPONSE"
689
- };
677
+ return content;
690
678
  };
691
- let isTokenRefreshing = false;
692
- let pendingRequestQueues = [];
693
- const AxiosClientContext = createContext(null);
694
- const FetcherProvider = ({
695
- children,
696
- axiosInstance,
697
- locale = "en-US",
698
- getResponseFormatError = getRestFulResponseFormatError,
699
- onResponseError,
700
- checkIsRefreshTokenRequest,
701
- checkIsErrorResponse,
702
- authorizationPrefix = "Bearer",
703
- isDebug = false
704
- }) => {
705
- const {
706
- getTokens,
707
- updateTokens,
708
- refreshTokens,
709
- forceLogout
710
- } = useAuthState();
711
- useLayoutEffect(() => {
712
- const interceptorReq = axiosInstance.interceptors.request.use(interceptorsRequest);
713
- const interceptorRes = axiosInstance.interceptors.response.use(interceptorsResponseSuccess, interceptorsResponseError);
714
- return () => {
715
- axiosInstance.interceptors.request.eject(interceptorReq);
716
- axiosInstance.interceptors.response.eject(interceptorRes);
717
- };
718
- }, [getTokens, refreshTokens, updateTokens, forceLogout]);
719
- const runPendingRequest = (isSuccess) => {
720
- if (isDebug) u.warning("[FetcherProvider] runPendingRequest", { isSuccess });
721
- isTokenRefreshing = false;
722
- for (const cb of pendingRequestQueues) {
723
- cb(isSuccess);
724
- }
725
- pendingRequestQueues = [];
726
- };
727
- const pushPendingRequestQueues = (resolve, reject) => {
728
- return (originConfig) => {
729
- if (isDebug) u.info("[FetcherProvider] Request add pending queue", { originConfig });
730
- pendingRequestQueues.push((isTokenRefreshOK) => {
731
- if (isTokenRefreshOK) {
732
- originConfig.pendingRequest = true;
733
- resolve(axiosInstance(originConfig));
734
- } else {
735
- reject(new FetcherException({
736
- message: "Please login before continuing",
737
- code: "UNAUTHORIZED",
738
- path: "AxiosClientProvider.pushPendingRequestQueues"
739
- }));
740
- }
741
- });
742
- };
743
- };
744
- const interceptorsRequest = (originConfig) => {
745
- return new Promise((resolve, reject) => {
746
- var _a, _b;
747
- originConfig.headers["Accept-Language"] = locale;
748
- const accessTokens = (_a = getTokens()) == null ? void 0 : _a.accessToken;
749
- const forceGuest = (_b = originConfig.fetchOptions) == null ? void 0 : _b.forceGuest;
750
- if (!forceGuest && accessTokens) {
751
- originConfig.headers["Authorization"] = [authorizationPrefix, accessTokens].filter((str) => str).join(" ");
752
- }
753
- const isRefreshTokenAPI = originConfig && checkIsRefreshTokenRequest ? checkIsRefreshTokenRequest(originConfig) : false;
754
- if (!isRefreshTokenAPI && isTokenRefreshing) {
755
- pushPendingRequestQueues(resolve, reject)(originConfig);
756
- reject(new AxiosCancelException({
757
- message: "Token refreshing, so request save queues not send",
758
- code: "REFRESHING_TOKEN"
759
- }));
760
- return;
679
+ const inherits = (constructor, superConstructor, props, descriptors2) => {
680
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
681
+ constructor.prototype.constructor = constructor;
682
+ Object.defineProperty(constructor, "super", {
683
+ value: superConstructor.prototype
684
+ });
685
+ props && Object.assign(constructor.prototype, props);
686
+ };
687
+ const toFlatObject = (sourceObj, destObj, filter2, propFilter) => {
688
+ let props;
689
+ let i2;
690
+ let prop;
691
+ const merged = {};
692
+ destObj = destObj || {};
693
+ if (sourceObj == null) return destObj;
694
+ do {
695
+ props = Object.getOwnPropertyNames(sourceObj);
696
+ i2 = props.length;
697
+ while (i2-- > 0) {
698
+ prop = props[i2];
699
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
700
+ destObj[prop] = sourceObj[prop];
701
+ merged[prop] = true;
761
702
  }
762
- resolve(originConfig);
763
- });
764
- };
765
- const interceptorsResponseSuccess = (response) => {
766
- if (isDebug) u.info("[FetcherProvider] interceptorsResponseSuccess", { response });
767
- if (checkIsErrorResponse && checkIsErrorResponse(response)) {
768
- return Promise.reject(response);
769
703
  }
770
- return response;
704
+ sourceObj = filter2 !== false && getPrototypeOf(sourceObj);
705
+ } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype);
706
+ return destObj;
707
+ };
708
+ const endsWith = (str, searchString, position) => {
709
+ str = String(str);
710
+ if (position === void 0 || position > str.length) {
711
+ position = str.length;
712
+ }
713
+ position -= searchString.length;
714
+ const lastIndex = str.indexOf(searchString, position);
715
+ return lastIndex !== -1 && lastIndex === position;
716
+ };
717
+ const toArray = (thing) => {
718
+ if (!thing) return null;
719
+ if (isArray(thing)) return thing;
720
+ let i2 = thing.length;
721
+ if (!isNumber(i2)) return null;
722
+ const arr = new Array(i2);
723
+ while (i2-- > 0) {
724
+ arr[i2] = thing[i2];
725
+ }
726
+ return arr;
727
+ };
728
+ const isTypedArray = /* @__PURE__ */ ((TypedArray) => {
729
+ return (thing) => {
730
+ return TypedArray && thing instanceof TypedArray;
771
731
  };
772
- const interceptorsResponseError = (axiosError) => {
773
- if (isDebug) u.danger("[FetcherProvider] interceptorsResponseError", { axiosError });
774
- const response = axiosError.response;
775
- const originalConfig = axiosError.config;
776
- const status = axiosError.status;
777
- const responseFirstError = getResponseFormatError(axiosError);
778
- if (isDebug) u.warning("[FetcherProvider] interceptorsResponseError(2)", { status, responseFirstError });
779
- if (onResponseError && originalConfig.ignoreErrorCallback !== true) {
780
- onResponseError(responseFirstError);
732
+ })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
733
+ const forEachEntry = (obj, fn) => {
734
+ const generator = obj && obj[iterator];
735
+ const _iterator = generator.call(obj);
736
+ let result;
737
+ while ((result = _iterator.next()) && !result.done) {
738
+ const pair = result.value;
739
+ fn.call(obj, pair[0], pair[1]);
740
+ }
741
+ };
742
+ const matchAll = (regExp, str) => {
743
+ let matches;
744
+ const arr = [];
745
+ while ((matches = regExp.exec(str)) !== null) {
746
+ arr.push(matches);
747
+ }
748
+ return arr;
749
+ };
750
+ const isHTMLForm = kindOfTest("HTMLFormElement");
751
+ const toCamelCase = (str) => {
752
+ return str.toLowerCase().replace(
753
+ /[-_\s]([a-z\d])(\w*)/g,
754
+ function replacer(m, p1, p2) {
755
+ return p1.toUpperCase() + p2;
781
756
  }
782
- const isRefresh = originalConfig && checkIsRefreshTokenRequest ? checkIsRefreshTokenRequest(originalConfig) : false;
783
- if (response && originalConfig) {
784
- if (status === 401 || responseFirstError.code === "UNAUTHENTICATED") {
785
- const tokens = getTokens();
786
- if (isDebug) u.warning("[FetcherProvider] enter refresh token flow", { refreshToken: tokens == null ? void 0 : tokens.refreshToken });
787
- if (w(tokens == null ? void 0 : tokens.refreshToken) || isRefresh || originalConfig.pendingRequest) {
788
- isTokenRefreshing = false;
789
- if (isDebug) u.warning("[FetcherProvider] no refreshToken/refreshAPI|pendingRequest fail, force logout");
790
- forceLogout();
791
- return Promise.reject(new FetcherException(responseFirstError));
792
- }
793
- if (!isTokenRefreshing) {
794
- isTokenRefreshing = true;
795
- if (isDebug) u.warning("[FetcherProvider] refreshTokens");
796
- refreshTokens().then(() => {
797
- if (isDebug) u.info("[FetcherProvider] refreshTokens success");
798
- runPendingRequest(true);
799
- }).catch(() => {
800
- if (isDebug) u.danger("[FetcherProvider] refreshTokens fail");
801
- runPendingRequest(false);
802
- });
803
- }
804
- return new Promise((resolve, reject) => {
805
- pushPendingRequestQueues(resolve, reject)(originalConfig);
806
- });
807
- }
757
+ );
758
+ };
759
+ const hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
760
+ const isRegExp = kindOfTest("RegExp");
761
+ const reduceDescriptors = (obj, reducer) => {
762
+ const descriptors2 = Object.getOwnPropertyDescriptors(obj);
763
+ const reducedDescriptors = {};
764
+ forEach(descriptors2, (descriptor, name) => {
765
+ let ret;
766
+ if ((ret = reducer(descriptor, name, obj)) !== false) {
767
+ reducedDescriptors[name] = ret || descriptor;
808
768
  }
809
- return Promise.reject(new FetcherException(responseFirstError));
810
- };
811
- return /* @__PURE__ */ jsxRuntimeExports.jsx(
812
- AxiosClientContext.Provider,
813
- {
814
- value: axiosInstance,
815
- children
769
+ });
770
+ Object.defineProperties(obj, reducedDescriptors);
771
+ };
772
+ const freezeMethods = (obj) => {
773
+ reduceDescriptors(obj, (descriptor, name) => {
774
+ if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) {
775
+ return false;
816
776
  }
817
- );
777
+ const value = obj[name];
778
+ if (!isFunction(value)) return;
779
+ descriptor.enumerable = false;
780
+ if ("writable" in descriptor) {
781
+ descriptor.writable = false;
782
+ return;
783
+ }
784
+ if (!descriptor.set) {
785
+ descriptor.set = () => {
786
+ throw Error("Can not rewrite read-only method '" + name + "'");
787
+ };
788
+ }
789
+ });
818
790
  };
819
- function bind(fn, thisArg) {
820
- return function wrap() {
821
- return fn.apply(thisArg, arguments);
791
+ const toObjectSet = (arrayOrString, delimiter) => {
792
+ const obj = {};
793
+ const define = (arr) => {
794
+ arr.forEach((value) => {
795
+ obj[value] = true;
796
+ });
822
797
  };
823
- }
824
- const { toString } = Object.prototype;
825
- const { getPrototypeOf } = Object;
826
- const { iterator, toStringTag } = Symbol;
827
- const kindOf = /* @__PURE__ */ ((cache) => (thing) => {
828
- const str = toString.call(thing);
829
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
830
- })(/* @__PURE__ */ Object.create(null));
831
- const kindOfTest = (type) => {
832
- type = type.toLowerCase();
833
- return (thing) => kindOf(thing) === type;
798
+ isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
799
+ return obj;
834
800
  };
835
- const typeOfTest = (type) => (thing) => typeof thing === type;
836
- const { isArray } = Array;
837
- const isUndefined = typeOfTest("undefined");
838
- function isBuffer(val) {
839
- return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
840
- }
841
- const isArrayBuffer = kindOfTest("ArrayBuffer");
842
- function isArrayBufferView(val) {
843
- let result;
844
- if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
845
- result = ArrayBuffer.isView(val);
846
- } else {
847
- result = val && val.buffer && isArrayBuffer(val.buffer);
848
- }
849
- return result;
850
- }
851
- const isString = typeOfTest("string");
852
- const isFunction = typeOfTest("function");
853
- const isNumber = typeOfTest("number");
854
- const isObject = (thing) => thing !== null && typeof thing === "object";
855
- const isBoolean = (thing) => thing === true || thing === false;
856
- const isPlainObject = (val) => {
857
- if (kindOf(val) !== "object") {
858
- return false;
859
- }
860
- const prototype2 = getPrototypeOf(val);
861
- return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(toStringTag in val) && !(iterator in val);
862
- };
863
- const isDate = kindOfTest("Date");
864
- const isFile = kindOfTest("File");
865
- const isBlob = kindOfTest("Blob");
866
- const isFileList = kindOfTest("FileList");
867
- const isStream = (val) => isObject(val) && isFunction(val.pipe);
868
- const isFormData = (thing) => {
869
- let kind;
870
- return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
871
- kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]"));
872
- };
873
- const isURLSearchParams = kindOfTest("URLSearchParams");
874
- const [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
875
- const trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
876
- function forEach(obj, fn, { allOwnKeys = false } = {}) {
877
- if (obj === null || typeof obj === "undefined") {
878
- return;
879
- }
880
- let i2;
881
- let l2;
882
- if (typeof obj !== "object") {
883
- obj = [obj];
884
- }
885
- if (isArray(obj)) {
886
- for (i2 = 0, l2 = obj.length; i2 < l2; i2++) {
887
- fn.call(null, obj[i2], i2, obj);
888
- }
889
- } else {
890
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
891
- const len = keys.length;
892
- let key;
893
- for (i2 = 0; i2 < len; i2++) {
894
- key = keys[i2];
895
- fn.call(null, obj[key], key, obj);
896
- }
897
- }
898
- }
899
- function findKey(obj, key) {
900
- key = key.toLowerCase();
901
- const keys = Object.keys(obj);
902
- let i2 = keys.length;
903
- let _key;
904
- while (i2-- > 0) {
905
- _key = keys[i2];
906
- if (key === _key.toLowerCase()) {
907
- return _key;
908
- }
909
- }
910
- return null;
911
- }
912
- const _global = (() => {
913
- if (typeof globalThis !== "undefined") return globalThis;
914
- return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
915
- })();
916
- const isContextDefined = (context) => !isUndefined(context) && context !== _global;
917
- function merge() {
918
- const { caseless } = isContextDefined(this) && this || {};
919
- const result = {};
920
- const assignValue = (val, key) => {
921
- const targetKey = caseless && findKey(result, key) || key;
922
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
923
- result[targetKey] = merge(result[targetKey], val);
924
- } else if (isPlainObject(val)) {
925
- result[targetKey] = merge({}, val);
926
- } else if (isArray(val)) {
927
- result[targetKey] = val.slice();
928
- } else {
929
- result[targetKey] = val;
930
- }
931
- };
932
- for (let i2 = 0, l2 = arguments.length; i2 < l2; i2++) {
933
- arguments[i2] && forEach(arguments[i2], assignValue);
934
- }
935
- return result;
936
- }
937
- const extend = (a2, b, thisArg, { allOwnKeys } = {}) => {
938
- forEach(b, (val, key) => {
939
- if (thisArg && isFunction(val)) {
940
- a2[key] = bind(val, thisArg);
941
- } else {
942
- a2[key] = val;
943
- }
944
- }, { allOwnKeys });
945
- return a2;
946
- };
947
- const stripBOM = (content) => {
948
- if (content.charCodeAt(0) === 65279) {
949
- content = content.slice(1);
950
- }
951
- return content;
952
- };
953
- const inherits = (constructor, superConstructor, props, descriptors2) => {
954
- constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
955
- constructor.prototype.constructor = constructor;
956
- Object.defineProperty(constructor, "super", {
957
- value: superConstructor.prototype
958
- });
959
- props && Object.assign(constructor.prototype, props);
960
- };
961
- const toFlatObject = (sourceObj, destObj, filter2, propFilter) => {
962
- let props;
963
- let i2;
964
- let prop;
965
- const merged = {};
966
- destObj = destObj || {};
967
- if (sourceObj == null) return destObj;
968
- do {
969
- props = Object.getOwnPropertyNames(sourceObj);
970
- i2 = props.length;
971
- while (i2-- > 0) {
972
- prop = props[i2];
973
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
974
- destObj[prop] = sourceObj[prop];
975
- merged[prop] = true;
976
- }
977
- }
978
- sourceObj = filter2 !== false && getPrototypeOf(sourceObj);
979
- } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype);
980
- return destObj;
981
- };
982
- const endsWith = (str, searchString, position) => {
983
- str = String(str);
984
- if (position === void 0 || position > str.length) {
985
- position = str.length;
986
- }
987
- position -= searchString.length;
988
- const lastIndex = str.indexOf(searchString, position);
989
- return lastIndex !== -1 && lastIndex === position;
990
- };
991
- const toArray = (thing) => {
992
- if (!thing) return null;
993
- if (isArray(thing)) return thing;
994
- let i2 = thing.length;
995
- if (!isNumber(i2)) return null;
996
- const arr = new Array(i2);
997
- while (i2-- > 0) {
998
- arr[i2] = thing[i2];
999
- }
1000
- return arr;
1001
- };
1002
- const isTypedArray = /* @__PURE__ */ ((TypedArray) => {
1003
- return (thing) => {
1004
- return TypedArray && thing instanceof TypedArray;
1005
- };
1006
- })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
1007
- const forEachEntry = (obj, fn) => {
1008
- const generator = obj && obj[iterator];
1009
- const _iterator = generator.call(obj);
1010
- let result;
1011
- while ((result = _iterator.next()) && !result.done) {
1012
- const pair = result.value;
1013
- fn.call(obj, pair[0], pair[1]);
1014
- }
1015
- };
1016
- const matchAll = (regExp, str) => {
1017
- let matches;
1018
- const arr = [];
1019
- while ((matches = regExp.exec(str)) !== null) {
1020
- arr.push(matches);
1021
- }
1022
- return arr;
1023
- };
1024
- const isHTMLForm = kindOfTest("HTMLFormElement");
1025
- const toCamelCase = (str) => {
1026
- return str.toLowerCase().replace(
1027
- /[-_\s]([a-z\d])(\w*)/g,
1028
- function replacer(m, p1, p2) {
1029
- return p1.toUpperCase() + p2;
1030
- }
1031
- );
1032
- };
1033
- const hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
1034
- const isRegExp = kindOfTest("RegExp");
1035
- const reduceDescriptors = (obj, reducer) => {
1036
- const descriptors2 = Object.getOwnPropertyDescriptors(obj);
1037
- const reducedDescriptors = {};
1038
- forEach(descriptors2, (descriptor, name) => {
1039
- let ret;
1040
- if ((ret = reducer(descriptor, name, obj)) !== false) {
1041
- reducedDescriptors[name] = ret || descriptor;
1042
- }
1043
- });
1044
- Object.defineProperties(obj, reducedDescriptors);
1045
- };
1046
- const freezeMethods = (obj) => {
1047
- reduceDescriptors(obj, (descriptor, name) => {
1048
- if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) {
1049
- return false;
1050
- }
1051
- const value = obj[name];
1052
- if (!isFunction(value)) return;
1053
- descriptor.enumerable = false;
1054
- if ("writable" in descriptor) {
1055
- descriptor.writable = false;
1056
- return;
1057
- }
1058
- if (!descriptor.set) {
1059
- descriptor.set = () => {
1060
- throw Error("Can not rewrite read-only method '" + name + "'");
1061
- };
1062
- }
1063
- });
1064
- };
1065
- const toObjectSet = (arrayOrString, delimiter) => {
1066
- const obj = {};
1067
- const define = (arr) => {
1068
- arr.forEach((value) => {
1069
- obj[value] = true;
1070
- });
1071
- };
1072
- isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
1073
- return obj;
1074
- };
1075
- const noop = () => {
1076
- };
1077
- const toFiniteNumber = (value, defaultValue) => {
1078
- return value != null && Number.isFinite(value = +value) ? value : defaultValue;
1079
- };
1080
- function isSpecCompliantForm(thing) {
1081
- return !!(thing && isFunction(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
801
+ const noop = () => {
802
+ };
803
+ const toFiniteNumber = (value, defaultValue) => {
804
+ return value != null && Number.isFinite(value = +value) ? value : defaultValue;
805
+ };
806
+ function isSpecCompliantForm(thing) {
807
+ return !!(thing && isFunction(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
1082
808
  }
1083
809
  const toJSONObject = (obj) => {
1084
810
  const stack = new Array(10);
@@ -1302,6 +1028,9 @@ function toFormData$1(obj, formData, options) {
1302
1028
  if (utils$1.isDate(value)) {
1303
1029
  return value.toISOString();
1304
1030
  }
1031
+ if (utils$1.isBoolean(value)) {
1032
+ return value.toString();
1033
+ }
1305
1034
  if (!useBlob && utils$1.isBlob(value)) {
1306
1035
  throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");
1307
1036
  }
@@ -2605,7 +2334,7 @@ const fetchAdapter = isFetchSupported && (async (config) => {
2605
2334
  duplex: "half",
2606
2335
  credentials: isCredentialsSupported ? withCredentials : void 0
2607
2336
  });
2608
- let response = await fetch(request);
2337
+ let response = await fetch(request, fetchOptions);
2609
2338
  const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
2610
2339
  if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
2611
2340
  const options = {};
@@ -2746,7 +2475,7 @@ function dispatchRequest(config) {
2746
2475
  return Promise.reject(reason);
2747
2476
  });
2748
2477
  }
2749
- const VERSION$1 = "1.9.0";
2478
+ const VERSION$1 = "1.10.0";
2750
2479
  const validators$1 = {};
2751
2480
  ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i2) => {
2752
2481
  validators$1[type] = function validator2(thing) {
@@ -3198,6 +2927,291 @@ const {
3198
2927
  getAdapter,
3199
2928
  mergeConfig
3200
2929
  } = axios;
2930
+ class FetcherException extends Error {
2931
+ constructor(response) {
2932
+ super(response.message);
2933
+ __publicField(this, "code");
2934
+ __publicField(this, "args");
2935
+ __publicField(this, "path");
2936
+ this.response = response;
2937
+ this.code = response.code;
2938
+ this.args = response.args;
2939
+ this.path = response.path;
2940
+ this.name = this.constructor.name;
2941
+ Object.setPrototypeOf(this, FetcherException.prototype);
2942
+ }
2943
+ }
2944
+ const AuthStateContext = createContext({
2945
+ lastUpdateTimestamp: 0,
2946
+ isAuth: false,
2947
+ getTokens: () => {
2948
+ u.warning("AuthStateContext", "getTokens not yet ready");
2949
+ return null;
2950
+ },
2951
+ updateTokens: () => u.warning("AuthStateContext", "updateTokens not yet ready"),
2952
+ forceLogout: () => u.warning("AuthStateContext", "forceLogout not yet ready"),
2953
+ refreshTokens: async () => {
2954
+ u.warning("AuthStateContext", "refreshToken not yet ready");
2955
+ return void 0;
2956
+ }
2957
+ });
2958
+ const useAuthState = () => useContext(AuthStateContext);
2959
+ const AuthStateProvider = ({
2960
+ children,
2961
+ onGetTokens,
2962
+ onSetTokens,
2963
+ onRefreshTokens,
2964
+ onForceLogout,
2965
+ isDebug = false
2966
+ }) => {
2967
+ const [lastUpdateTimestamp, setLastUpdateTimestamp] = useState(0);
2968
+ const [isAuth, setIsAuth] = useState(() => {
2969
+ return D(onGetTokens());
2970
+ });
2971
+ const updateTokens = (tokensOrUpdater) => {
2972
+ let nextTokens;
2973
+ if (typeof tokensOrUpdater === "function") {
2974
+ nextTokens = tokensOrUpdater(onGetTokens());
2975
+ } else {
2976
+ nextTokens = tokensOrUpdater;
2977
+ }
2978
+ onSetTokens(nextTokens);
2979
+ setIsAuth(D(nextTokens));
2980
+ setLastUpdateTimestamp(Date.now());
2981
+ };
2982
+ const handleOnForceLogout = () => {
2983
+ updateTokens(null);
2984
+ if (onForceLogout) {
2985
+ onForceLogout();
2986
+ }
2987
+ };
2988
+ const handleOnRefreshTokens = async () => {
2989
+ var _a;
2990
+ const refreshToken = (_a = onGetTokens()) == null ? void 0 : _a.refreshToken;
2991
+ if (!refreshToken || !onRefreshTokens) {
2992
+ if (isDebug) u.danger("[AuthStateProvider] handleOnRefreshTokens", "refreshToken|onRefreshTokens empty");
2993
+ throw new FetcherException({ message: "refreshToken|onRefreshTokens empty", code: "REFRESH_TOKEN_EMPTY" });
2994
+ }
2995
+ try {
2996
+ const authTokens = await onRefreshTokens(refreshToken);
2997
+ if (w(authTokens)) {
2998
+ if (isDebug) u.danger("[AuthStateProvider] handleOnRefreshTokens", "new refresh token fail");
2999
+ throw new FetcherException({ message: "new refresh token fail", code: "NEW_REFRESH_TOKEN_EMPTY" });
3000
+ }
3001
+ updateTokens(authTokens);
3002
+ return;
3003
+ } catch (err) {
3004
+ handleOnForceLogout();
3005
+ throw new FetcherException({ message: "refresh token fail", code: "REFRESH_TOKEN_CATCH" });
3006
+ }
3007
+ };
3008
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(AuthStateContext.Provider, { value: {
3009
+ lastUpdateTimestamp,
3010
+ isAuth,
3011
+ getTokens: onGetTokens,
3012
+ updateTokens,
3013
+ refreshTokens: handleOnRefreshTokens,
3014
+ forceLogout: handleOnForceLogout
3015
+ }, children });
3016
+ };
3017
+ class AxiosCancelException extends Error {
3018
+ constructor(response) {
3019
+ super(response.message);
3020
+ __publicField(this, "code");
3021
+ __publicField(this, "devInfo");
3022
+ __publicField(this, "args");
3023
+ __publicField(this, "path");
3024
+ this.response = response;
3025
+ this.code = response.code;
3026
+ this.args = response.args;
3027
+ this.path = response.path;
3028
+ this.initName();
3029
+ }
3030
+ initName() {
3031
+ this.name = this.constructor.name;
3032
+ }
3033
+ getInfo() {
3034
+ return {
3035
+ message: this.response.message,
3036
+ code: this.response.code,
3037
+ args: this.response.args,
3038
+ path: this.response.path
3039
+ };
3040
+ }
3041
+ }
3042
+ const getGraphQLResponseFormatError = (axiosError) => {
3043
+ var _a, _b, _c;
3044
+ const responseData = (_a = axiosError == null ? void 0 : axiosError.response) == null ? void 0 : _a.data;
3045
+ if ((_b = responseData.errors) == null ? void 0 : _b[0]) {
3046
+ return (_c = responseData.errors) == null ? void 0 : _c[0];
3047
+ }
3048
+ if (axiosError == null ? void 0 : axiosError.isAxiosError) {
3049
+ return {
3050
+ message: axiosError.message,
3051
+ code: axiosError.code
3052
+ };
3053
+ }
3054
+ return {
3055
+ message: "Axios error",
3056
+ code: "ERR_SYS_BAD_RESPONSE"
3057
+ };
3058
+ };
3059
+ const getRestFulResponseFormatError = (axiosError) => {
3060
+ var _a;
3061
+ const responseData = (_a = axiosError == null ? void 0 : axiosError.response) == null ? void 0 : _a.data;
3062
+ if (responseData) {
3063
+ return responseData;
3064
+ }
3065
+ if (axiosError == null ? void 0 : axiosError.isAxiosError) {
3066
+ return {
3067
+ message: axiosError.message,
3068
+ code: axiosError.code
3069
+ };
3070
+ }
3071
+ return {
3072
+ message: "Axios error",
3073
+ code: "ERR_SYS_BAD_RESPONSE"
3074
+ };
3075
+ };
3076
+ let isTokenRefreshing = false;
3077
+ let pendingRequestQueues = [];
3078
+ const AxiosClientContext = createContext(null);
3079
+ const FetcherProvider = ({
3080
+ children,
3081
+ axiosInstance,
3082
+ locale = "en-US",
3083
+ getResponseFormatError = getRestFulResponseFormatError,
3084
+ onResponseError,
3085
+ checkIsRefreshTokenRequest,
3086
+ checkIsErrorResponse,
3087
+ checkErrorIs401,
3088
+ authorizationPrefix = "Bearer",
3089
+ isDebug = false
3090
+ }) => {
3091
+ const {
3092
+ getTokens,
3093
+ updateTokens,
3094
+ refreshTokens,
3095
+ forceLogout
3096
+ } = useAuthState();
3097
+ useLayoutEffect(() => {
3098
+ const interceptorReq = axiosInstance.interceptors.request.use(interceptorsRequest);
3099
+ const interceptorRes = axiosInstance.interceptors.response.use(interceptorsResponseSuccess, interceptorsResponseError);
3100
+ return () => {
3101
+ axiosInstance.interceptors.request.eject(interceptorReq);
3102
+ axiosInstance.interceptors.response.eject(interceptorRes);
3103
+ };
3104
+ }, [getTokens, refreshTokens, updateTokens, forceLogout]);
3105
+ const runPendingRequest = (isSuccess) => {
3106
+ if (isDebug) u.warning("[FetcherProvider] runPendingRequest", { isSuccess });
3107
+ isTokenRefreshing = false;
3108
+ for (const cb of pendingRequestQueues) {
3109
+ cb(isSuccess);
3110
+ }
3111
+ pendingRequestQueues = [];
3112
+ };
3113
+ const pushPendingRequestQueues = (resolve, reject) => {
3114
+ return (originConfig) => {
3115
+ if (isDebug) u.info("[FetcherProvider] Request add pending queue", { originConfig });
3116
+ pendingRequestQueues.push((isTokenRefreshOK) => {
3117
+ if (isTokenRefreshOK) {
3118
+ originConfig.pendingRequest = true;
3119
+ resolve(axiosInstance(originConfig));
3120
+ } else {
3121
+ reject(new FetcherException({
3122
+ message: "Please login before continuing",
3123
+ code: "UNAUTHORIZED",
3124
+ path: "AxiosClientProvider.pushPendingRequestQueues"
3125
+ }));
3126
+ }
3127
+ });
3128
+ };
3129
+ };
3130
+ const interceptorsRequest = (originConfig) => {
3131
+ return new Promise((resolve, reject) => {
3132
+ var _a, _b;
3133
+ originConfig.headers["Accept-Language"] = locale;
3134
+ const accessTokens = (_a = getTokens()) == null ? void 0 : _a.accessToken;
3135
+ const forceGuest = (_b = originConfig.fetchOptions) == null ? void 0 : _b.forceGuest;
3136
+ if (!forceGuest && accessTokens) {
3137
+ originConfig.headers["Authorization"] = [authorizationPrefix, accessTokens].filter((str) => str).join(" ");
3138
+ }
3139
+ const isRefreshTokenAPI = originConfig && checkIsRefreshTokenRequest ? checkIsRefreshTokenRequest(originConfig) : false;
3140
+ if (!isRefreshTokenAPI && isTokenRefreshing) {
3141
+ pushPendingRequestQueues(resolve, reject)(originConfig);
3142
+ reject(new AxiosCancelException({
3143
+ message: "Token refreshing, so request save queues not send",
3144
+ code: "REFRESHING_TOKEN"
3145
+ }));
3146
+ return;
3147
+ }
3148
+ resolve(originConfig);
3149
+ });
3150
+ };
3151
+ const interceptorsResponseSuccess = (response) => {
3152
+ if (isDebug) u.info("[FetcherProvider] interceptorsResponseSuccess", { response });
3153
+ if (checkIsErrorResponse && checkIsErrorResponse(response)) {
3154
+ return interceptorsResponseError(new AxiosError(
3155
+ response.data.message,
3156
+ "ERR_BAD_RESPONSE",
3157
+ response.config,
3158
+ response.request,
3159
+ response
3160
+ ));
3161
+ }
3162
+ return response;
3163
+ };
3164
+ const handleOnResponseError = (responseFirstError) => {
3165
+ if (onResponseError) {
3166
+ onResponseError(responseFirstError);
3167
+ }
3168
+ };
3169
+ const interceptorsResponseError = (axiosError) => {
3170
+ if (isDebug) u.danger("[FetcherProvider] interceptorsResponseError", { axiosError });
3171
+ const response = axiosError.response;
3172
+ const originalConfig = axiosError.config;
3173
+ const status = axiosError.status;
3174
+ const responseFirstError = getResponseFormatError(axiosError);
3175
+ if (isDebug) u.warning("[FetcherProvider] interceptorsResponseError(2)", { status, responseFirstError });
3176
+ const isRefresh = originalConfig && checkIsRefreshTokenRequest ? checkIsRefreshTokenRequest(originalConfig) : false;
3177
+ if (response && originalConfig) {
3178
+ if (status === 401 || checkErrorIs401 && checkErrorIs401(responseFirstError)) {
3179
+ const tokens = getTokens();
3180
+ if (isDebug) u.warning("[FetcherProvider] enter refresh token flow", { refreshToken: tokens == null ? void 0 : tokens.refreshToken });
3181
+ if (w(tokens == null ? void 0 : tokens.refreshToken) || isRefresh || originalConfig.pendingRequest) {
3182
+ isTokenRefreshing = false;
3183
+ if (isDebug) u.warning("[FetcherProvider] no refreshToken/refreshAPI|pendingRequest fail, force logout");
3184
+ forceLogout();
3185
+ if (originalConfig.ignoreErrorCallback !== true) handleOnResponseError(responseFirstError);
3186
+ return Promise.reject(new FetcherException(responseFirstError));
3187
+ }
3188
+ if (!isTokenRefreshing) {
3189
+ isTokenRefreshing = true;
3190
+ if (isDebug) u.warning("[FetcherProvider] refreshTokens");
3191
+ refreshTokens().then(() => {
3192
+ if (isDebug) u.info("[FetcherProvider] refreshTokens success");
3193
+ runPendingRequest(true);
3194
+ }).catch(() => {
3195
+ if (isDebug) u.danger("[FetcherProvider] refreshTokens fail");
3196
+ runPendingRequest(false);
3197
+ });
3198
+ }
3199
+ return new Promise((resolve, reject) => {
3200
+ pushPendingRequestQueues(resolve, reject)(originalConfig);
3201
+ });
3202
+ }
3203
+ }
3204
+ if (originalConfig.ignoreErrorCallback !== true) handleOnResponseError(responseFirstError);
3205
+ return Promise.reject(new FetcherException(responseFirstError));
3206
+ };
3207
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(
3208
+ AxiosClientContext.Provider,
3209
+ {
3210
+ value: axiosInstance,
3211
+ children
3212
+ }
3213
+ );
3214
+ };
3201
3215
  const createAxiosInstance = (config) => {
3202
3216
  return axios.create({
3203
3217
  timeout: 2 * 60 * 1e3,