@pinia/colada-plugin-retry 0.1.2 → 0.2.0

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.
package/dist/index.cjs CHANGED
@@ -1,115 +1,78 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
1
 
19
- // src/index.ts
20
- var index_exports = {};
21
- __export(index_exports, {
22
- PiniaColadaRetry: () => PiniaColadaRetry
23
- });
24
- module.exports = __toCommonJS(index_exports);
25
-
26
- // src/retry.ts
27
- var RETRY_OPTIONS_DEFAULTS = {
28
- delay: (attempt) => {
29
- const time = Math.min(
30
- 2 ** attempt * 1e3,
31
- // never more than 30 seconds
32
- 3e4
33
- );
34
- console.log(`\u23F2\uFE0F delaying attempt #${attempt + 1} by ${time}ms`);
35
- return time;
36
- },
37
- retry: (count) => {
38
- console.log(`\u{1F504} Retrying ${"\u{1F7E8}".repeat(count + 1)}${"\u2B1C\uFE0F".repeat(2 - count)}`);
39
- return count < 2;
40
- }
2
+ //#region src/retry.ts
3
+ const RETRY_OPTIONS_DEFAULTS = {
4
+ delay: (attempt) => {
5
+ const time = Math.min(2 ** attempt * 1e3, 3e4);
6
+ console.log(`⏲️ delaying attempt #${attempt + 1} by ${time}ms`);
7
+ return time;
8
+ },
9
+ retry: (count) => {
10
+ console.log(`🔄 Retrying ${"🟨".repeat(count + 1)}${"⬜️".repeat(2 - count)}`);
11
+ return count < 2;
12
+ }
41
13
  };
14
+ /**
15
+ * Plugin that adds the ability to retry failed queries.
16
+ *
17
+ * @param globalOptions - global options for the retries
18
+ */
42
19
  function PiniaColadaRetry(globalOptions) {
43
- const defaults = { ...RETRY_OPTIONS_DEFAULTS, ...globalOptions };
44
- return ({ queryCache }) => {
45
- const retryMap = /* @__PURE__ */ new Map();
46
- let isInternalCall = false;
47
- queryCache.$onAction(({ name, args, after, onError }) => {
48
- if (name === "remove") {
49
- const [cacheEntry] = args;
50
- const key2 = cacheEntry.key.join("/");
51
- const entry = retryMap.get(key2);
52
- if (entry) {
53
- clearTimeout(entry.timeoutId);
54
- retryMap.delete(key2);
55
- }
56
- }
57
- if (name !== "fetch") return;
58
- const [queryEntry] = args;
59
- const localOptions = queryEntry.options?.retry;
60
- const options = {
61
- ...typeof localOptions === "object" ? localOptions : {
62
- retry: localOptions
63
- }
64
- };
65
- const retry = options.retry ?? defaults.retry;
66
- const delay = options.delay ?? defaults.delay;
67
- if (retry === 0) return;
68
- const key = queryEntry.key.join("/");
69
- clearTimeout(retryMap.get(key)?.timeoutId);
70
- if (!isInternalCall) {
71
- retryMap.delete(key);
72
- }
73
- const retryFetch = () => {
74
- if (queryEntry.state.value.status === "error") {
75
- const error = queryEntry.state.value.error;
76
- let entry = retryMap.get(key);
77
- if (!entry) {
78
- entry = { retryCount: 0 };
79
- retryMap.set(key, entry);
80
- }
81
- const shouldRetry = typeof retry === "number" ? retry > entry.retryCount : retry(entry.retryCount, error);
82
- if (shouldRetry) {
83
- const delayTime = typeof delay === "function" ? delay(entry.retryCount) : delay;
84
- entry.timeoutId = setTimeout(() => {
85
- if (!queryEntry.active) {
86
- retryMap.delete(key);
87
- return;
88
- }
89
- isInternalCall = true;
90
- Promise.resolve(queryCache.fetch(queryEntry)).catch(
91
- process.env.NODE_ENV !== "test" ? console.error : () => {
92
- }
93
- );
94
- isInternalCall = false;
95
- if (entry) {
96
- entry.retryCount++;
97
- }
98
- }, delayTime);
99
- } else {
100
- retryMap.delete(key);
101
- }
102
- } else {
103
- retryMap.delete(key);
104
- }
105
- };
106
- onError(retryFetch);
107
- after(retryFetch);
108
- });
109
- };
20
+ const defaults = {
21
+ ...RETRY_OPTIONS_DEFAULTS,
22
+ ...globalOptions
23
+ };
24
+ return ({ queryCache }) => {
25
+ const retryMap = /* @__PURE__ */ new Map();
26
+ let isInternalCall = false;
27
+ queryCache.$onAction(({ name, args, after, onError }) => {
28
+ if (name === "remove") {
29
+ const [cacheEntry] = args;
30
+ const key$1 = cacheEntry.key.join("/");
31
+ const entry = retryMap.get(key$1);
32
+ if (entry) {
33
+ clearTimeout(entry.timeoutId);
34
+ retryMap.delete(key$1);
35
+ }
36
+ }
37
+ if (name !== "fetch") return;
38
+ const [queryEntry] = args;
39
+ const localOptions = queryEntry.options?.retry;
40
+ const options = { ...typeof localOptions === "object" ? localOptions : { retry: localOptions } };
41
+ const retry = options.retry ?? defaults.retry;
42
+ const delay = options.delay ?? defaults.delay;
43
+ if (retry === 0) return;
44
+ const key = queryEntry.key.join("/");
45
+ clearTimeout(retryMap.get(key)?.timeoutId);
46
+ if (!isInternalCall) retryMap.delete(key);
47
+ const retryFetch = () => {
48
+ if (queryEntry.state.value.status === "error") {
49
+ const error = queryEntry.state.value.error;
50
+ let entry = retryMap.get(key);
51
+ if (!entry) {
52
+ entry = { retryCount: 0 };
53
+ retryMap.set(key, entry);
54
+ }
55
+ if (typeof retry === "number" ? retry > entry.retryCount : retry(entry.retryCount, error)) {
56
+ const delayTime = typeof delay === "function" ? delay(entry.retryCount) : delay;
57
+ entry.timeoutId = setTimeout(() => {
58
+ if (!queryEntry.active) {
59
+ retryMap.delete(key);
60
+ return;
61
+ }
62
+ isInternalCall = true;
63
+ Promise.resolve(queryCache.fetch(queryEntry)).catch(process.env.NODE_ENV !== "test" ? console.error : () => {});
64
+ isInternalCall = false;
65
+ if (entry) entry.retryCount++;
66
+ }, delayTime);
67
+ } else retryMap.delete(key);
68
+ } else retryMap.delete(key);
69
+ };
70
+ onError(retryFetch);
71
+ after(retryFetch);
72
+ });
73
+ };
110
74
  }
111
- // Annotate the CommonJS export names for ESM import in node:
112
- 0 && (module.exports = {
113
- PiniaColadaRetry
114
- });
75
+
76
+ //#endregion
77
+ exports.PiniaColadaRetry = PiniaColadaRetry;
115
78
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/retry.ts"],"sourcesContent":["export * from './retry'\n","/**\n * Pinia Colada Retry plugin.\n *\n * Adds the ability to retry failed queries.\n *\n * @module @pinia/colada-plugin-retry\n */\nimport type { PiniaColadaPluginContext } from '@pinia/colada'\n\n/**\n * Options for the Pinia Colada Retry plugin.\n */\nexport interface RetryOptions {\n /**\n * The delay between retries. Can be a duration in ms or a function that\n * receives the attempt number (starts at 0) and returns a duration in ms. By\n * default, it will wait 2^attempt * 1000 ms, but never more than 30 seconds.\n *\n * @param attempt -\n * @returns\n */\n delay?: number | ((attempt: number) => number)\n\n /**\n * The maximum number of times to retry the operation. Set to 0 to disable or\n * to Infinity to retry forever. It can also be a function that receives the\n * failure count and the error and returns if it should retry. Defaults to 3.\n * **Must be a positive number**.\n */\n retry?: number | ((failureCount: number, error: unknown) => boolean)\n}\n\nexport interface RetryEntry {\n retryCount: number\n timeoutId?: ReturnType<typeof setTimeout>\n}\n\nconst RETRY_OPTIONS_DEFAULTS = {\n delay: (attempt: number) => {\n const time = Math.min(\n 2 ** attempt * 1000,\n // never more than 30 seconds\n 30_000,\n )\n // oxlint-disable-next-line no-console\n console.log(`⏲️ delaying attempt #${attempt + 1} by ${time}ms`)\n return time\n },\n retry: (count) => {\n // oxlint-disable-next-line no-console\n console.log(`🔄 Retrying ${'🟨'.repeat(count + 1)}${'⬜️'.repeat(2 - count)}`)\n return count < 2\n },\n} satisfies Required<RetryOptions>\n\n/**\n * Plugin that adds the ability to retry failed queries.\n *\n * @param globalOptions - global options for the retries\n */\nexport function PiniaColadaRetry(\n globalOptions?: RetryOptions,\n): (context: PiniaColadaPluginContext) => void {\n const defaults = { ...RETRY_OPTIONS_DEFAULTS, ...globalOptions }\n\n return ({ queryCache }) => {\n const retryMap = new Map<string, RetryEntry>()\n\n let isInternalCall = false\n queryCache.$onAction(({ name, args, after, onError }) => {\n // cleanup all pending retries when data is deleted (means the data is not needed anymore)\n if (name === 'remove') {\n const [cacheEntry] = args\n const key = cacheEntry.key.join('/')\n const entry = retryMap.get(key)\n if (entry) {\n clearTimeout(entry.timeoutId)\n retryMap.delete(key)\n }\n }\n\n if (name !== 'fetch') return\n const [queryEntry] = args\n const localOptions = queryEntry.options?.retry\n\n const options = {\n ...(typeof localOptions === 'object'\n ? localOptions\n : {\n retry: localOptions,\n }),\n } satisfies RetryOptions\n\n const retry = options.retry ?? defaults.retry\n const delay = options.delay ?? defaults.delay\n // avoid setting up anything at all\n if (retry === 0) return\n\n const key = queryEntry.key.join('/')\n\n // clear any pending retry\n clearTimeout(retryMap.get(key)?.timeoutId)\n // if the user manually calls the action, reset the retry count\n if (!isInternalCall) {\n retryMap.delete(key)\n }\n\n const retryFetch = () => {\n if (queryEntry.state.value.status === 'error') {\n const error = queryEntry.state.value.error\n // ensure the entry exists\n let entry = retryMap.get(key)\n if (!entry) {\n entry = { retryCount: 0 }\n retryMap.set(key, entry)\n }\n\n const shouldRetry =\n typeof retry === 'number' ? retry > entry.retryCount : retry(entry.retryCount, error)\n\n if (shouldRetry) {\n const delayTime = typeof delay === 'function' ? delay(entry.retryCount) : delay\n entry.timeoutId = setTimeout(() => {\n if (!queryEntry.active) {\n retryMap.delete(key)\n return\n }\n // NOTE: we could add some default error handler\n isInternalCall = true\n Promise.resolve(queryCache.fetch(queryEntry)).catch(\n process.env.NODE_ENV !== 'test' ? console.error : () => {},\n )\n isInternalCall = false\n if (entry) {\n entry.retryCount++\n }\n }, delayTime)\n } else {\n // remove the entry if we are not going to retry\n retryMap.delete(key)\n }\n } else {\n // remove the entry if it worked out to reset it\n retryMap.delete(key)\n }\n }\n onError(retryFetch)\n after(retryFetch)\n })\n }\n}\n\ndeclare module '@pinia/colada' {\n // eslint-disable-next-line unused-imports/no-unused-vars\n export interface UseQueryOptions<TData, TError, TDataInitial> {\n /**\n * Options for the retries of this query added by `@pinia/colada-plugin-retry`.\n */\n retry?: RetryOptions | Exclude<RetryOptions['retry'], undefined>\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqCA,IAAM,yBAAyB;AAAA,EAC7B,OAAO,CAAC,YAAoB;AAC1B,UAAM,OAAO,KAAK;AAAA,MAChB,KAAK,UAAU;AAAA;AAAA,MAEf;AAAA,IACF;AAEA,YAAQ,IAAI,kCAAwB,UAAU,CAAC,OAAO,IAAI,IAAI;AAC9D,WAAO;AAAA,EACT;AAAA,EACA,OAAO,CAAC,UAAU;AAEhB,YAAQ,IAAI,sBAAe,YAAK,OAAO,QAAQ,CAAC,CAAC,GAAG,eAAK,OAAO,IAAI,KAAK,CAAC,EAAE;AAC5E,WAAO,QAAQ;AAAA,EACjB;AACF;AAOO,SAAS,iBACd,eAC6C;AAC7C,QAAM,WAAW,EAAE,GAAG,wBAAwB,GAAG,cAAc;AAE/D,SAAO,CAAC,EAAE,WAAW,MAAM;AACzB,UAAM,WAAW,oBAAI,IAAwB;AAE7C,QAAI,iBAAiB;AACrB,eAAW,UAAU,CAAC,EAAE,MAAM,MAAM,OAAO,QAAQ,MAAM;AAEvD,UAAI,SAAS,UAAU;AACrB,cAAM,CAAC,UAAU,IAAI;AACrB,cAAMA,OAAM,WAAW,IAAI,KAAK,GAAG;AACnC,cAAM,QAAQ,SAAS,IAAIA,IAAG;AAC9B,YAAI,OAAO;AACT,uBAAa,MAAM,SAAS;AAC5B,mBAAS,OAAOA,IAAG;AAAA,QACrB;AAAA,MACF;AAEA,UAAI,SAAS,QAAS;AACtB,YAA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AO,GAAG;AAAA,QACrB;AAAA,MACF;AACA,cAAQ,UAAU;AAClB,YAAM,UAAU;AAAA,IAClB,CAAC;AAAA,EACH;AACF;","names":["key"]}
1
+ {"version":3,"file":"index.cjs","names":["key"],"sources":["../src/retry.ts"],"sourcesContent":["/**\n * Pinia Colada Retry plugin.\n *\n * Adds the ability to retry failed queries.\n *\n * @module @pinia/colada-plugin-retry\n */\nimport type { PiniaColadaPluginContext } from '@pinia/colada'\n\n/**\n * Options for the Pinia Colada Retry plugin.\n */\nexport interface RetryOptions {\n /**\n * The delay between retries. Can be a duration in ms or a function that\n * receives the attempt number (starts at 0) and returns a duration in ms. By\n * default, it will wait 2^attempt * 1000 ms, but never more than 30 seconds.\n *\n * @param attempt -\n * @returns\n */\n delay?: number | ((attempt: number) => number)\n\n /**\n * The maximum number of times to retry the operation. Set to 0 to disable or\n * to Infinity to retry forever. It can also be a function that receives the\n * failure count and the error and returns if it should retry. Defaults to 3.\n * **Must be a positive number**.\n */\n retry?: number | ((failureCount: number, error: unknown) => boolean)\n}\n\nexport interface RetryEntry {\n retryCount: number\n timeoutId?: ReturnType<typeof setTimeout>\n}\n\nconst RETRY_OPTIONS_DEFAULTS = {\n delay: (attempt: number) => {\n const time = Math.min(\n 2 ** attempt * 1000,\n // never more than 30 seconds\n 30_000,\n )\n // oxlint-disable-next-line no-console\n console.log(`⏲️ delaying attempt #${attempt + 1} by ${time}ms`)\n return time\n },\n retry: (count) => {\n // oxlint-disable-next-line no-console\n console.log(`🔄 Retrying ${'🟨'.repeat(count + 1)}${'⬜️'.repeat(2 - count)}`)\n return count < 2\n },\n} satisfies Required<RetryOptions>\n\n/**\n * Plugin that adds the ability to retry failed queries.\n *\n * @param globalOptions - global options for the retries\n */\nexport function PiniaColadaRetry(\n globalOptions?: RetryOptions,\n): (context: PiniaColadaPluginContext) => void {\n const defaults = { ...RETRY_OPTIONS_DEFAULTS, ...globalOptions }\n\n return ({ queryCache }) => {\n const retryMap = new Map<string, RetryEntry>()\n\n let isInternalCall = false\n queryCache.$onAction(({ name, args, after, onError }) => {\n // cleanup all pending retries when data is deleted (means the data is not needed anymore)\n if (name === 'remove') {\n const [cacheEntry] = args\n const key = cacheEntry.key.join('/')\n const entry = retryMap.get(key)\n if (entry) {\n clearTimeout(entry.timeoutId)\n retryMap.delete(key)\n }\n }\n\n if (name !== 'fetch') return\n const [queryEntry] = args\n const localOptions = queryEntry.options?.retry\n\n const options = {\n ...(typeof localOptions === 'object'\n ? localOptions\n : {\n retry: localOptions,\n }),\n } satisfies RetryOptions\n\n const retry = options.retry ?? defaults.retry\n const delay = options.delay ?? defaults.delay\n // avoid setting up anything at all\n if (retry === 0) return\n\n const key = queryEntry.key.join('/')\n\n // clear any pending retry\n clearTimeout(retryMap.get(key)?.timeoutId)\n // if the user manually calls the action, reset the retry count\n if (!isInternalCall) {\n retryMap.delete(key)\n }\n\n const retryFetch = () => {\n if (queryEntry.state.value.status === 'error') {\n const error = queryEntry.state.value.error\n // ensure the entry exists\n let entry = retryMap.get(key)\n if (!entry) {\n entry = { retryCount: 0 }\n retryMap.set(key, entry)\n }\n\n const shouldRetry =\n typeof retry === 'number' ? retry > entry.retryCount : retry(entry.retryCount, error)\n\n if (shouldRetry) {\n const delayTime = typeof delay === 'function' ? delay(entry.retryCount) : delay\n entry.timeoutId = setTimeout(() => {\n if (!queryEntry.active) {\n retryMap.delete(key)\n return\n }\n // NOTE: we could add some default error handler\n isInternalCall = true\n Promise.resolve(queryCache.fetch(queryEntry)).catch(\n process.env.NODE_ENV !== 'test' ? console.error : () => {},\n )\n isInternalCall = false\n if (entry) {\n entry.retryCount++\n }\n }, delayTime)\n } else {\n // remove the entry if we are not going to retry\n retryMap.delete(key)\n }\n } else {\n // remove the entry if it worked out to reset it\n retryMap.delete(key)\n }\n }\n onError(retryFetch)\n after(retryFetch)\n })\n }\n}\n\ndeclare module '@pinia/colada' {\n // eslint-disable-next-line unused-imports/no-unused-vars\n export interface UseQueryOptions<TData, TError, TDataInitial> {\n /**\n * Options for the retries of this query added by `@pinia/colada-plugin-retry`.\n */\n retry?: RetryOptions | Exclude<RetryOptions['retry'], undefined>\n }\n}\n"],"mappings":";;AAqCA,MAAM,yBAAyB;CAC7B,QAAQ,YAAoB;EAC1B,MAAM,OAAO,KAAK,IAChB,KAAK,UAAU,KAEf,IACD;AAED,UAAQ,IAAI,wBAAwB,UAAU,EAAE,MAAM,KAAK,IAAI;AAC/D,SAAO;;CAET,QAAQ,UAAU;AAEhB,UAAQ,IAAI,eAAe,KAAK,OAAO,QAAQ,EAAE,GAAG,KAAK,OAAO,IAAI,MAAM,GAAG;AAC7E,SAAO,QAAQ;;CAElB;;;;;;AAOD,SAAgB,iBACd,eAC6C;CAC7C,MAAM,WAAW;EAAE,GAAG;EAAwB,GAAG;EAAe;AAEhE,SAAQ,EAAE,iBAAiB;EACzB,MAAM,2BAAW,IAAI,KAAyB;EAE9C,IAAI,iBAAiB;AACrB,aAAW,WAAW,EAAE,MAAM,MAAM,OAAO,cAAc;AAEvD,OAAI,SAAS,UAAU;IACrB,MAAM,CAAC,cAAc;IACrB,MAAMA,QAAM,WAAW,IAAI,KAAK,IAAI;IACpC,MAAM,QAAQ,SAAS,IAAIA,MAAI;AAC/B,QAAI,OAAO;AACT,kBAAa,MAAM,UAAU;AAC7B,cAAS,OAAOA,MAAI;;;AAIxB,OAAI,SAAS,QAAS;GACtB,MAAM,CAAC,cAAc;GACrB,MAAM,eAAe,WAAW,SAAS;GAEzC,MAAM,UAAU,EACd,GAAI,OAAO,iBAAiB,WACxB,eACA,EACE,OAAO,cACR,EACN;GAED,MAAM,QAAQ,QAAQ,SAAS,SAAS;GACxC,MAAM,QAAQ,QAAQ,SAAS,SAAS;AAExC,OAAI,UAAU,EAAG;GAEjB,MAAM,MAAM,WAAW,IAAI,KAAK,IAAI;AAGpC,gBAAa,SAAS,IAAI,IAAI,EAAE,UAAU;AAE1C,OAAI,CAAC,eACH,UAAS,OAAO,IAAI;GAGtB,MAAM,mBAAmB;AACvB,QAAI,WAAW,MAAM,MAAM,WAAW,SAAS;KAC7C,MAAM,QAAQ,WAAW,MAAM,MAAM;KAErC,IAAI,QAAQ,SAAS,IAAI,IAAI;AAC7B,SAAI,CAAC,OAAO;AACV,cAAQ,EAAE,YAAY,GAAG;AACzB,eAAS,IAAI,KAAK,MAAM;;AAM1B,SAFE,OAAO,UAAU,WAAW,QAAQ,MAAM,aAAa,MAAM,MAAM,YAAY,MAAM,EAEtE;MACf,MAAM,YAAY,OAAO,UAAU,aAAa,MAAM,MAAM,WAAW,GAAG;AAC1E,YAAM,YAAY,iBAAiB;AACjC,WAAI,CAAC,WAAW,QAAQ;AACtB,iBAAS,OAAO,IAAI;AACpB;;AAGF,wBAAiB;AACjB,eAAQ,QAAQ,WAAW,MAAM,WAAW,CAAC,CAAC,MAC5C,QAAQ,IAAI,aAAa,SAAS,QAAQ,cAAc,GACzD;AACD,wBAAiB;AACjB,WAAI,MACF,OAAM;SAEP,UAAU;WAGb,UAAS,OAAO,IAAI;UAItB,UAAS,OAAO,IAAI;;AAGxB,WAAQ,WAAW;AACnB,SAAM,WAAW;IACjB"}
package/dist/index.d.cts CHANGED
@@ -1,37 +1,31 @@
1
- import { PiniaColadaPluginContext } from '@pinia/colada';
1
+ import { PiniaColadaPluginContext } from "@pinia/colada";
2
2
 
3
- /**
4
- * Pinia Colada Retry plugin.
5
- *
6
- * Adds the ability to retry failed queries.
7
- *
8
- * @module @pinia/colada-plugin-retry
9
- */
3
+ //#region src/retry.d.ts
10
4
 
11
5
  /**
12
6
  * Options for the Pinia Colada Retry plugin.
13
7
  */
14
8
  interface RetryOptions {
15
- /**
16
- * The delay between retries. Can be a duration in ms or a function that
17
- * receives the attempt number (starts at 0) and returns a duration in ms. By
18
- * default, it will wait 2^attempt * 1000 ms, but never more than 30 seconds.
19
- *
20
- * @param attempt -
21
- * @returns
22
- */
23
- delay?: number | ((attempt: number) => number);
24
- /**
25
- * The maximum number of times to retry the operation. Set to 0 to disable or
26
- * to Infinity to retry forever. It can also be a function that receives the
27
- * failure count and the error and returns if it should retry. Defaults to 3.
28
- * **Must be a positive number**.
29
- */
30
- retry?: number | ((failureCount: number, error: unknown) => boolean);
9
+ /**
10
+ * The delay between retries. Can be a duration in ms or a function that
11
+ * receives the attempt number (starts at 0) and returns a duration in ms. By
12
+ * default, it will wait 2^attempt * 1000 ms, but never more than 30 seconds.
13
+ *
14
+ * @param attempt -
15
+ * @returns
16
+ */
17
+ delay?: number | ((attempt: number) => number);
18
+ /**
19
+ * The maximum number of times to retry the operation. Set to 0 to disable or
20
+ * to Infinity to retry forever. It can also be a function that receives the
21
+ * failure count and the error and returns if it should retry. Defaults to 3.
22
+ * **Must be a positive number**.
23
+ */
24
+ retry?: number | ((failureCount: number, error: unknown) => boolean);
31
25
  }
32
26
  interface RetryEntry {
33
- retryCount: number;
34
- timeoutId?: ReturnType<typeof setTimeout>;
27
+ retryCount: number;
28
+ timeoutId?: ReturnType<typeof setTimeout>;
35
29
  }
36
30
  /**
37
31
  * Plugin that adds the ability to retry failed queries.
@@ -40,12 +34,13 @@ interface RetryEntry {
40
34
  */
41
35
  declare function PiniaColadaRetry(globalOptions?: RetryOptions): (context: PiniaColadaPluginContext) => void;
42
36
  declare module '@pinia/colada' {
43
- interface UseQueryOptions<TData, TError, TDataInitial> {
44
- /**
45
- * Options for the retries of this query added by `@pinia/colada-plugin-retry`.
46
- */
47
- retry?: RetryOptions | Exclude<RetryOptions['retry'], undefined>;
48
- }
37
+ interface UseQueryOptions<TData, TError, TDataInitial> {
38
+ /**
39
+ * Options for the retries of this query added by `@pinia/colada-plugin-retry`.
40
+ */
41
+ retry?: RetryOptions | Exclude<RetryOptions['retry'], undefined>;
42
+ }
49
43
  }
50
-
51
- export { PiniaColadaRetry, type RetryEntry, type RetryOptions };
44
+ //#endregion
45
+ export { PiniaColadaRetry, RetryEntry, RetryOptions };
46
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1,46 @@
1
+ import { PiniaColadaPluginContext } from "@pinia/colada";
2
+
3
+ //#region src/retry.d.ts
4
+
5
+ /**
6
+ * Options for the Pinia Colada Retry plugin.
7
+ */
8
+ interface RetryOptions {
9
+ /**
10
+ * The delay between retries. Can be a duration in ms or a function that
11
+ * receives the attempt number (starts at 0) and returns a duration in ms. By
12
+ * default, it will wait 2^attempt * 1000 ms, but never more than 30 seconds.
13
+ *
14
+ * @param attempt -
15
+ * @returns
16
+ */
17
+ delay?: number | ((attempt: number) => number);
18
+ /**
19
+ * The maximum number of times to retry the operation. Set to 0 to disable or
20
+ * to Infinity to retry forever. It can also be a function that receives the
21
+ * failure count and the error and returns if it should retry. Defaults to 3.
22
+ * **Must be a positive number**.
23
+ */
24
+ retry?: number | ((failureCount: number, error: unknown) => boolean);
25
+ }
26
+ interface RetryEntry {
27
+ retryCount: number;
28
+ timeoutId?: ReturnType<typeof setTimeout>;
29
+ }
30
+ /**
31
+ * Plugin that adds the ability to retry failed queries.
32
+ *
33
+ * @param globalOptions - global options for the retries
34
+ */
35
+ declare function PiniaColadaRetry(globalOptions?: RetryOptions): (context: PiniaColadaPluginContext) => void;
36
+ declare module '@pinia/colada' {
37
+ interface UseQueryOptions<TData, TError, TDataInitial> {
38
+ /**
39
+ * Options for the retries of this query added by `@pinia/colada-plugin-retry`.
40
+ */
41
+ retry?: RetryOptions | Exclude<RetryOptions['retry'], undefined>;
42
+ }
43
+ }
44
+ //#endregion
45
+ export { PiniaColadaRetry, RetryEntry, RetryOptions };
46
+ //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs ADDED
@@ -0,0 +1,77 @@
1
+ //#region src/retry.ts
2
+ const RETRY_OPTIONS_DEFAULTS = {
3
+ delay: (attempt) => {
4
+ const time = Math.min(2 ** attempt * 1e3, 3e4);
5
+ console.log(`⏲️ delaying attempt #${attempt + 1} by ${time}ms`);
6
+ return time;
7
+ },
8
+ retry: (count) => {
9
+ console.log(`🔄 Retrying ${"🟨".repeat(count + 1)}${"⬜️".repeat(2 - count)}`);
10
+ return count < 2;
11
+ }
12
+ };
13
+ /**
14
+ * Plugin that adds the ability to retry failed queries.
15
+ *
16
+ * @param globalOptions - global options for the retries
17
+ */
18
+ function PiniaColadaRetry(globalOptions) {
19
+ const defaults = {
20
+ ...RETRY_OPTIONS_DEFAULTS,
21
+ ...globalOptions
22
+ };
23
+ return ({ queryCache }) => {
24
+ const retryMap = /* @__PURE__ */ new Map();
25
+ let isInternalCall = false;
26
+ queryCache.$onAction(({ name, args, after, onError }) => {
27
+ if (name === "remove") {
28
+ const [cacheEntry] = args;
29
+ const key$1 = cacheEntry.key.join("/");
30
+ const entry = retryMap.get(key$1);
31
+ if (entry) {
32
+ clearTimeout(entry.timeoutId);
33
+ retryMap.delete(key$1);
34
+ }
35
+ }
36
+ if (name !== "fetch") return;
37
+ const [queryEntry] = args;
38
+ const localOptions = queryEntry.options?.retry;
39
+ const options = { ...typeof localOptions === "object" ? localOptions : { retry: localOptions } };
40
+ const retry = options.retry ?? defaults.retry;
41
+ const delay = options.delay ?? defaults.delay;
42
+ if (retry === 0) return;
43
+ const key = queryEntry.key.join("/");
44
+ clearTimeout(retryMap.get(key)?.timeoutId);
45
+ if (!isInternalCall) retryMap.delete(key);
46
+ const retryFetch = () => {
47
+ if (queryEntry.state.value.status === "error") {
48
+ const error = queryEntry.state.value.error;
49
+ let entry = retryMap.get(key);
50
+ if (!entry) {
51
+ entry = { retryCount: 0 };
52
+ retryMap.set(key, entry);
53
+ }
54
+ if (typeof retry === "number" ? retry > entry.retryCount : retry(entry.retryCount, error)) {
55
+ const delayTime = typeof delay === "function" ? delay(entry.retryCount) : delay;
56
+ entry.timeoutId = setTimeout(() => {
57
+ if (!queryEntry.active) {
58
+ retryMap.delete(key);
59
+ return;
60
+ }
61
+ isInternalCall = true;
62
+ Promise.resolve(queryCache.fetch(queryEntry)).catch(process.env.NODE_ENV !== "test" ? console.error : () => {});
63
+ isInternalCall = false;
64
+ if (entry) entry.retryCount++;
65
+ }, delayTime);
66
+ } else retryMap.delete(key);
67
+ } else retryMap.delete(key);
68
+ };
69
+ onError(retryFetch);
70
+ after(retryFetch);
71
+ });
72
+ };
73
+ }
74
+
75
+ //#endregion
76
+ export { PiniaColadaRetry };
77
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["key"],"sources":["../src/retry.ts"],"sourcesContent":["/**\n * Pinia Colada Retry plugin.\n *\n * Adds the ability to retry failed queries.\n *\n * @module @pinia/colada-plugin-retry\n */\nimport type { PiniaColadaPluginContext } from '@pinia/colada'\n\n/**\n * Options for the Pinia Colada Retry plugin.\n */\nexport interface RetryOptions {\n /**\n * The delay between retries. Can be a duration in ms or a function that\n * receives the attempt number (starts at 0) and returns a duration in ms. By\n * default, it will wait 2^attempt * 1000 ms, but never more than 30 seconds.\n *\n * @param attempt -\n * @returns\n */\n delay?: number | ((attempt: number) => number)\n\n /**\n * The maximum number of times to retry the operation. Set to 0 to disable or\n * to Infinity to retry forever. It can also be a function that receives the\n * failure count and the error and returns if it should retry. Defaults to 3.\n * **Must be a positive number**.\n */\n retry?: number | ((failureCount: number, error: unknown) => boolean)\n}\n\nexport interface RetryEntry {\n retryCount: number\n timeoutId?: ReturnType<typeof setTimeout>\n}\n\nconst RETRY_OPTIONS_DEFAULTS = {\n delay: (attempt: number) => {\n const time = Math.min(\n 2 ** attempt * 1000,\n // never more than 30 seconds\n 30_000,\n )\n // oxlint-disable-next-line no-console\n console.log(`⏲️ delaying attempt #${attempt + 1} by ${time}ms`)\n return time\n },\n retry: (count) => {\n // oxlint-disable-next-line no-console\n console.log(`🔄 Retrying ${'🟨'.repeat(count + 1)}${'⬜️'.repeat(2 - count)}`)\n return count < 2\n },\n} satisfies Required<RetryOptions>\n\n/**\n * Plugin that adds the ability to retry failed queries.\n *\n * @param globalOptions - global options for the retries\n */\nexport function PiniaColadaRetry(\n globalOptions?: RetryOptions,\n): (context: PiniaColadaPluginContext) => void {\n const defaults = { ...RETRY_OPTIONS_DEFAULTS, ...globalOptions }\n\n return ({ queryCache }) => {\n const retryMap = new Map<string, RetryEntry>()\n\n let isInternalCall = false\n queryCache.$onAction(({ name, args, after, onError }) => {\n // cleanup all pending retries when data is deleted (means the data is not needed anymore)\n if (name === 'remove') {\n const [cacheEntry] = args\n const key = cacheEntry.key.join('/')\n const entry = retryMap.get(key)\n if (entry) {\n clearTimeout(entry.timeoutId)\n retryMap.delete(key)\n }\n }\n\n if (name !== 'fetch') return\n const [queryEntry] = args\n const localOptions = queryEntry.options?.retry\n\n const options = {\n ...(typeof localOptions === 'object'\n ? localOptions\n : {\n retry: localOptions,\n }),\n } satisfies RetryOptions\n\n const retry = options.retry ?? defaults.retry\n const delay = options.delay ?? defaults.delay\n // avoid setting up anything at all\n if (retry === 0) return\n\n const key = queryEntry.key.join('/')\n\n // clear any pending retry\n clearTimeout(retryMap.get(key)?.timeoutId)\n // if the user manually calls the action, reset the retry count\n if (!isInternalCall) {\n retryMap.delete(key)\n }\n\n const retryFetch = () => {\n if (queryEntry.state.value.status === 'error') {\n const error = queryEntry.state.value.error\n // ensure the entry exists\n let entry = retryMap.get(key)\n if (!entry) {\n entry = { retryCount: 0 }\n retryMap.set(key, entry)\n }\n\n const shouldRetry =\n typeof retry === 'number' ? retry > entry.retryCount : retry(entry.retryCount, error)\n\n if (shouldRetry) {\n const delayTime = typeof delay === 'function' ? delay(entry.retryCount) : delay\n entry.timeoutId = setTimeout(() => {\n if (!queryEntry.active) {\n retryMap.delete(key)\n return\n }\n // NOTE: we could add some default error handler\n isInternalCall = true\n Promise.resolve(queryCache.fetch(queryEntry)).catch(\n process.env.NODE_ENV !== 'test' ? console.error : () => {},\n )\n isInternalCall = false\n if (entry) {\n entry.retryCount++\n }\n }, delayTime)\n } else {\n // remove the entry if we are not going to retry\n retryMap.delete(key)\n }\n } else {\n // remove the entry if it worked out to reset it\n retryMap.delete(key)\n }\n }\n onError(retryFetch)\n after(retryFetch)\n })\n }\n}\n\ndeclare module '@pinia/colada' {\n // eslint-disable-next-line unused-imports/no-unused-vars\n export interface UseQueryOptions<TData, TError, TDataInitial> {\n /**\n * Options for the retries of this query added by `@pinia/colada-plugin-retry`.\n */\n retry?: RetryOptions | Exclude<RetryOptions['retry'], undefined>\n }\n}\n"],"mappings":";AAqCA,MAAM,yBAAyB;CAC7B,QAAQ,YAAoB;EAC1B,MAAM,OAAO,KAAK,IAChB,KAAK,UAAU,KAEf,IACD;AAED,UAAQ,IAAI,wBAAwB,UAAU,EAAE,MAAM,KAAK,IAAI;AAC/D,SAAO;;CAET,QAAQ,UAAU;AAEhB,UAAQ,IAAI,eAAe,KAAK,OAAO,QAAQ,EAAE,GAAG,KAAK,OAAO,IAAI,MAAM,GAAG;AAC7E,SAAO,QAAQ;;CAElB;;;;;;AAOD,SAAgB,iBACd,eAC6C;CAC7C,MAAM,WAAW;EAAE,GAAG;EAAwB,GAAG;EAAe;AAEhE,SAAQ,EAAE,iBAAiB;EACzB,MAAM,2BAAW,IAAI,KAAyB;EAE9C,IAAI,iBAAiB;AACrB,aAAW,WAAW,EAAE,MAAM,MAAM,OAAO,cAAc;AAEvD,OAAI,SAAS,UAAU;IACrB,MAAM,CAAC,cAAc;IACrB,MAAMA,QAAM,WAAW,IAAI,KAAK,IAAI;IACpC,MAAM,QAAQ,SAAS,IAAIA,MAAI;AAC/B,QAAI,OAAO;AACT,kBAAa,MAAM,UAAU;AAC7B,cAAS,OAAOA,MAAI;;;AAIxB,OAAI,SAAS,QAAS;GACtB,MAAM,CAAC,cAAc;GACrB,MAAM,eAAe,WAAW,SAAS;GAEzC,MAAM,UAAU,EACd,GAAI,OAAO,iBAAiB,WACxB,eACA,EACE,OAAO,cACR,EACN;GAED,MAAM,QAAQ,QAAQ,SAAS,SAAS;GACxC,MAAM,QAAQ,QAAQ,SAAS,SAAS;AAExC,OAAI,UAAU,EAAG;GAEjB,MAAM,MAAM,WAAW,IAAI,KAAK,IAAI;AAGpC,gBAAa,SAAS,IAAI,IAAI,EAAE,UAAU;AAE1C,OAAI,CAAC,eACH,UAAS,OAAO,IAAI;GAGtB,MAAM,mBAAmB;AACvB,QAAI,WAAW,MAAM,MAAM,WAAW,SAAS;KAC7C,MAAM,QAAQ,WAAW,MAAM,MAAM;KAErC,IAAI,QAAQ,SAAS,IAAI,IAAI;AAC7B,SAAI,CAAC,OAAO;AACV,cAAQ,EAAE,YAAY,GAAG;AACzB,eAAS,IAAI,KAAK,MAAM;;AAM1B,SAFE,OAAO,UAAU,WAAW,QAAQ,MAAM,aAAa,MAAM,MAAM,YAAY,MAAM,EAEtE;MACf,MAAM,YAAY,OAAO,UAAU,aAAa,MAAM,MAAM,WAAW,GAAG;AAC1E,YAAM,YAAY,iBAAiB;AACjC,WAAI,CAAC,WAAW,QAAQ;AACtB,iBAAS,OAAO,IAAI;AACpB;;AAGF,wBAAiB;AACjB,eAAQ,QAAQ,WAAW,MAAM,WAAW,CAAC,CAAC,MAC5C,QAAQ,IAAI,aAAa,SAAS,QAAQ,cAAc,GACzD;AACD,wBAAiB;AACjB,WAAI,MACF,OAAM;SAEP,UAAU;WAGb,UAAS,OAAO,IAAI;UAItB,UAAS,OAAO,IAAI;;AAGxB,WAAQ,WAAW;AACnB,SAAM,WAAW;IACjB"}
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
- "version": "0.1.2",
7
+ "version": "0.2.0",
8
8
  "description": "Retry failed requests with Pinia Colada",
9
9
  "author": {
10
10
  "name": "Eduardo San Martin Morote",
@@ -13,10 +13,7 @@
13
13
  "license": "MIT",
14
14
  "funding": "https://github.com/sponsors/posva",
15
15
  "homepage": "https://github.com/posva/pinia-colada/plugins/retry#readme",
16
- "repository": {
17
- "type": "git",
18
- "url": "git+https://github.com/posva/pinia-colada.git"
19
- },
16
+ "repository": "posva/pinia-colada",
20
17
  "bugs": {
21
18
  "url": "https://github.com/posva/pinia-colada/issues"
22
19
  },
@@ -34,16 +31,16 @@
34
31
  "exports": {
35
32
  ".": {
36
33
  "types": {
37
- "import": "./dist/index.d.ts",
34
+ "import": "./dist/index.d.mts",
38
35
  "require": "./dist/index.d.cts"
39
36
  },
40
- "import": "./dist/index.js",
37
+ "import": "./dist/index.mjs",
41
38
  "require": "./dist/index.cjs"
42
39
  }
43
40
  },
44
41
  "main": "./dist/index.cjs",
45
- "module": "./dist/index.js",
46
- "types": "./dist/index.d.ts",
42
+ "module": "./dist/index.mjs",
43
+ "types": "./dist/index.d.mts",
47
44
  "typesVersions": {
48
45
  "*": {
49
46
  "*": [
@@ -58,13 +55,13 @@
58
55
  "dist"
59
56
  ],
60
57
  "peerDependencies": {
61
- "@pinia/colada": ">=0.17.7"
58
+ "@pinia/colada": ">=0.20.0"
62
59
  },
63
60
  "devDependencies": {
64
- "@pinia/colada": "^0.17.7"
61
+ "@pinia/colada": "^0.20.0"
65
62
  },
66
63
  "scripts": {
67
- "build": "tsup",
64
+ "build": "tsdown",
68
65
  "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s --commit-path . -l @pinia/colada-plugin-retry -r 1",
69
66
  "test": "vitest --ui"
70
67
  }
package/dist/index.d.ts DELETED
@@ -1,51 +0,0 @@
1
- import { PiniaColadaPluginContext } from '@pinia/colada';
2
-
3
- /**
4
- * Pinia Colada Retry plugin.
5
- *
6
- * Adds the ability to retry failed queries.
7
- *
8
- * @module @pinia/colada-plugin-retry
9
- */
10
-
11
- /**
12
- * Options for the Pinia Colada Retry plugin.
13
- */
14
- interface RetryOptions {
15
- /**
16
- * The delay between retries. Can be a duration in ms or a function that
17
- * receives the attempt number (starts at 0) and returns a duration in ms. By
18
- * default, it will wait 2^attempt * 1000 ms, but never more than 30 seconds.
19
- *
20
- * @param attempt -
21
- * @returns
22
- */
23
- delay?: number | ((attempt: number) => number);
24
- /**
25
- * The maximum number of times to retry the operation. Set to 0 to disable or
26
- * to Infinity to retry forever. It can also be a function that receives the
27
- * failure count and the error and returns if it should retry. Defaults to 3.
28
- * **Must be a positive number**.
29
- */
30
- retry?: number | ((failureCount: number, error: unknown) => boolean);
31
- }
32
- interface RetryEntry {
33
- retryCount: number;
34
- timeoutId?: ReturnType<typeof setTimeout>;
35
- }
36
- /**
37
- * Plugin that adds the ability to retry failed queries.
38
- *
39
- * @param globalOptions - global options for the retries
40
- */
41
- declare function PiniaColadaRetry(globalOptions?: RetryOptions): (context: PiniaColadaPluginContext) => void;
42
- declare module '@pinia/colada' {
43
- interface UseQueryOptions<TData, TError, TDataInitial> {
44
- /**
45
- * Options for the retries of this query added by `@pinia/colada-plugin-retry`.
46
- */
47
- retry?: RetryOptions | Exclude<RetryOptions['retry'], undefined>;
48
- }
49
- }
50
-
51
- export { PiniaColadaRetry, type RetryEntry, type RetryOptions };
package/dist/index.js DELETED
@@ -1,89 +0,0 @@
1
- // src/retry.ts
2
- var RETRY_OPTIONS_DEFAULTS = {
3
- delay: (attempt) => {
4
- const time = Math.min(
5
- 2 ** attempt * 1e3,
6
- // never more than 30 seconds
7
- 3e4
8
- );
9
- console.log(`\u23F2\uFE0F delaying attempt #${attempt + 1} by ${time}ms`);
10
- return time;
11
- },
12
- retry: (count) => {
13
- console.log(`\u{1F504} Retrying ${"\u{1F7E8}".repeat(count + 1)}${"\u2B1C\uFE0F".repeat(2 - count)}`);
14
- return count < 2;
15
- }
16
- };
17
- function PiniaColadaRetry(globalOptions) {
18
- const defaults = { ...RETRY_OPTIONS_DEFAULTS, ...globalOptions };
19
- return ({ queryCache }) => {
20
- const retryMap = /* @__PURE__ */ new Map();
21
- let isInternalCall = false;
22
- queryCache.$onAction(({ name, args, after, onError }) => {
23
- if (name === "remove") {
24
- const [cacheEntry] = args;
25
- const key2 = cacheEntry.key.join("/");
26
- const entry = retryMap.get(key2);
27
- if (entry) {
28
- clearTimeout(entry.timeoutId);
29
- retryMap.delete(key2);
30
- }
31
- }
32
- if (name !== "fetch") return;
33
- const [queryEntry] = args;
34
- const localOptions = queryEntry.options?.retry;
35
- const options = {
36
- ...typeof localOptions === "object" ? localOptions : {
37
- retry: localOptions
38
- }
39
- };
40
- const retry = options.retry ?? defaults.retry;
41
- const delay = options.delay ?? defaults.delay;
42
- if (retry === 0) return;
43
- const key = queryEntry.key.join("/");
44
- clearTimeout(retryMap.get(key)?.timeoutId);
45
- if (!isInternalCall) {
46
- retryMap.delete(key);
47
- }
48
- const retryFetch = () => {
49
- if (queryEntry.state.value.status === "error") {
50
- const error = queryEntry.state.value.error;
51
- let entry = retryMap.get(key);
52
- if (!entry) {
53
- entry = { retryCount: 0 };
54
- retryMap.set(key, entry);
55
- }
56
- const shouldRetry = typeof retry === "number" ? retry > entry.retryCount : retry(entry.retryCount, error);
57
- if (shouldRetry) {
58
- const delayTime = typeof delay === "function" ? delay(entry.retryCount) : delay;
59
- entry.timeoutId = setTimeout(() => {
60
- if (!queryEntry.active) {
61
- retryMap.delete(key);
62
- return;
63
- }
64
- isInternalCall = true;
65
- Promise.resolve(queryCache.fetch(queryEntry)).catch(
66
- process.env.NODE_ENV !== "test" ? console.error : () => {
67
- }
68
- );
69
- isInternalCall = false;
70
- if (entry) {
71
- entry.retryCount++;
72
- }
73
- }, delayTime);
74
- } else {
75
- retryMap.delete(key);
76
- }
77
- } else {
78
- retryMap.delete(key);
79
- }
80
- };
81
- onError(retryFetch);
82
- after(retryFetch);
83
- });
84
- };
85
- }
86
- export {
87
- PiniaColadaRetry
88
- };
89
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/retry.ts"],"sourcesContent":["/**\n * Pinia Colada Retry plugin.\n *\n * Adds the ability to retry failed queries.\n *\n * @module @pinia/colada-plugin-retry\n */\nimport type { PiniaColadaPluginContext } from '@pinia/colada'\n\n/**\n * Options for the Pinia Colada Retry plugin.\n */\nexport interface RetryOptions {\n /**\n * The delay between retries. Can be a duration in ms or a function that\n * receives the attempt number (starts at 0) and returns a duration in ms. By\n * default, it will wait 2^attempt * 1000 ms, but never more than 30 seconds.\n *\n * @param attempt -\n * @returns\n */\n delay?: number | ((attempt: number) => number)\n\n /**\n * The maximum number of times to retry the operation. Set to 0 to disable or\n * to Infinity to retry forever. It can also be a function that receives the\n * failure count and the error and returns if it should retry. Defaults to 3.\n * **Must be a positive number**.\n */\n retry?: number | ((failureCount: number, error: unknown) => boolean)\n}\n\nexport interface RetryEntry {\n retryCount: number\n timeoutId?: ReturnType<typeof setTimeout>\n}\n\nconst RETRY_OPTIONS_DEFAULTS = {\n delay: (attempt: number) => {\n const time = Math.min(\n 2 ** attempt * 1000,\n // never more than 30 seconds\n 30_000,\n )\n // oxlint-disable-next-line no-console\n console.log(`⏲️ delaying attempt #${attempt + 1} by ${time}ms`)\n return time\n },\n retry: (count) => {\n // oxlint-disable-next-line no-console\n console.log(`🔄 Retrying ${'🟨'.repeat(count + 1)}${'⬜️'.repeat(2 - count)}`)\n return count < 2\n },\n} satisfies Required<RetryOptions>\n\n/**\n * Plugin that adds the ability to retry failed queries.\n *\n * @param globalOptions - global options for the retries\n */\nexport function PiniaColadaRetry(\n globalOptions?: RetryOptions,\n): (context: PiniaColadaPluginContext) => void {\n const defaults = { ...RETRY_OPTIONS_DEFAULTS, ...globalOptions }\n\n return ({ queryCache }) => {\n const retryMap = new Map<string, RetryEntry>()\n\n let isInternalCall = false\n queryCache.$onAction(({ name, args, after, onError }) => {\n // cleanup all pending retries when data is deleted (means the data is not needed anymore)\n if (name === 'remove') {\n const [cacheEntry] = args\n const key = cacheEntry.key.join('/')\n const entry = retryMap.get(key)\n if (entry) {\n clearTimeout(entry.timeoutId)\n retryMap.delete(key)\n }\n }\n\n if (name !== 'fetch') return\n const [queryEntry] = args\n const localOptions = queryEntry.options?.retry\n\n const options = {\n ...(typeof localOptions === 'object'\n ? localOptions\n : {\n retry: localOptions,\n }),\n } satisfies RetryOptions\n\n const retry = options.retry ?? defaults.retry\n const delay = options.delay ?? defaults.delay\n // avoid setting up anything at all\n if (retry === 0) return\n\n const key = queryEntry.key.join('/')\n\n // clear any pending retry\n clearTimeout(retryMap.get(key)?.timeoutId)\n // if the user manually calls the action, reset the retry count\n if (!isInternalCall) {\n retryMap.delete(key)\n }\n\n const retryFetch = () => {\n if (queryEntry.state.value.status === 'error') {\n const error = queryEntry.state.value.error\n // ensure the entry exists\n let entry = retryMap.get(key)\n if (!entry) {\n entry = { retryCount: 0 }\n retryMap.set(key, entry)\n }\n\n const shouldRetry =\n typeof retry === 'number' ? retry > entry.retryCount : retry(entry.retryCount, error)\n\n if (shouldRetry) {\n const delayTime = typeof delay === 'function' ? delay(entry.retryCount) : delay\n entry.timeoutId = setTimeout(() => {\n if (!queryEntry.active) {\n retryMap.delete(key)\n return\n }\n // NOTE: we could add some default error handler\n isInternalCall = true\n Promise.resolve(queryCache.fetch(queryEntry)).catch(\n process.env.NODE_ENV !== 'test' ? console.error : () => {},\n )\n isInternalCall = false\n if (entry) {\n entry.retryCount++\n }\n }, delayTime)\n } else {\n // remove the entry if we are not going to retry\n retryMap.delete(key)\n }\n } else {\n // remove the entry if it worked out to reset it\n retryMap.delete(key)\n }\n }\n onError(retryFetch)\n after(retryFetch)\n })\n }\n}\n\ndeclare module '@pinia/colada' {\n // eslint-disable-next-line unused-imports/no-unused-vars\n export interface UseQueryOptions<TData, TError, TDataInitial> {\n /**\n * Options for the retries of this query added by `@pinia/colada-plugin-retry`.\n */\n retry?: RetryOptions | Exclude<RetryOptions['retry'], undefined>\n }\n}\n"],"mappings":";AAqCA,IAAM,yBAAyB;AAAA,EAC7B,OAAO,CAAC,YAAoB;AAC1B,UAAM,OAAO,KAAK;AAAA,MAChB,KAAK,UAAU;AAAA;AAAA,MAEf;AAAA,IACF;AAEA,YAAQ,IAAI,kCAAwB,UAAU,CAAC,OAAO,IAAI,IAAI;AAC9D,WAAO;AAAA,EACT;AAAA,EACA,OAAO,CAAC,UAAU;AAEhB,YAAQ,IAAI,sBAAe,YAAK,OAAO,QAAQ,CAAC,CAAC,GAAG,eAAK,OAAO,IAAI,KAAK,CAAC,EAAE;AAC5E,WAAO,QAAQ;AAAA,EAC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