@modern-js/runtime-utils 2.69.5 → 3.0.0-alpha.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.
Files changed (135) hide show
  1. package/dist/cjs/browser/deferreds.js +141 -145
  2. package/dist/cjs/browser/index.js +62 -21
  3. package/dist/cjs/browser/nestedRoutes.js +121 -147
  4. package/dist/cjs/merge.js +51 -44
  5. package/dist/cjs/node/fileReader.js +88 -97
  6. package/dist/cjs/node/index.js +87 -33
  7. package/dist/cjs/node/loaderContext/createLoaderCtx.js +43 -36
  8. package/dist/cjs/node/loaderContext/createRequestCtx.js +43 -41
  9. package/dist/cjs/node/loaderContext/index.js +38 -29
  10. package/dist/cjs/node/serialize.js +46 -40
  11. package/dist/cjs/node/storer/container.js +62 -58
  12. package/dist/cjs/node/storer/index.js +39 -31
  13. package/dist/cjs/node/storer/storage.js +82 -92
  14. package/dist/cjs/node/stream.js +89 -91
  15. package/dist/cjs/parsed.js +40 -38
  16. package/dist/cjs/router.js +88 -19
  17. package/dist/cjs/rsc.js +58 -0
  18. package/dist/cjs/server/index.js +55 -19
  19. package/dist/cjs/server/nestedRoutes.js +43 -39
  20. package/dist/cjs/time.js +53 -47
  21. package/dist/cjs/universal/async_storage.js +53 -37
  22. package/dist/cjs/universal/async_storage.server.js +63 -74
  23. package/dist/cjs/universal/cache.js +330 -381
  24. package/dist/cjs/universal/request.js +73 -65
  25. package/dist/cjs/url.js +33 -28
  26. package/dist/esm/browser/deferreds.mjs +118 -0
  27. package/dist/esm/browser/nestedRoutes.mjs +104 -0
  28. package/dist/esm/merge.mjs +26 -0
  29. package/dist/esm/node/fileReader.mjs +47 -0
  30. package/dist/{esm-node/node/index.js → esm/node/index.mjs} +2 -5
  31. package/dist/esm/node/loaderContext/createLoaderCtx.mjs +14 -0
  32. package/dist/esm/node/loaderContext/createRequestCtx.mjs +16 -0
  33. package/dist/{esm-node/node/loaderContext/index.js → esm/node/loaderContext/index.mjs} +1 -4
  34. package/dist/esm/node/serialize.mjs +5 -0
  35. package/dist/esm/node/storer/container.mjs +38 -0
  36. package/dist/{esm-node/node/storer/index.js → esm/node/storer/index.mjs} +2 -6
  37. package/dist/esm/node/storer/storage.mjs +53 -0
  38. package/dist/esm/node/stream.mjs +68 -0
  39. package/dist/esm/parsed.mjs +12 -0
  40. package/dist/esm/router.mjs +18 -0
  41. package/dist/esm/rsc.mjs +1 -0
  42. package/dist/esm/server/nestedRoutes.mjs +15 -0
  43. package/dist/esm/time.mjs +27 -0
  44. package/dist/esm/universal/async_storage.mjs +7 -0
  45. package/dist/esm/universal/async_storage.server.mjs +32 -0
  46. package/dist/esm/universal/cache.mjs +326 -0
  47. package/dist/esm/universal/request.mjs +40 -0
  48. package/dist/esm/url.mjs +5 -0
  49. package/dist/esm-node/browser/deferreds.mjs +118 -0
  50. package/dist/esm-node/browser/index.mjs +2 -0
  51. package/dist/esm-node/browser/nestedRoutes.mjs +104 -0
  52. package/dist/esm-node/merge.mjs +26 -0
  53. package/dist/esm-node/node/fileReader.mjs +47 -0
  54. package/dist/esm-node/node/index.mjs +5 -0
  55. package/dist/esm-node/node/loaderContext/createLoaderCtx.mjs +14 -0
  56. package/dist/esm-node/node/loaderContext/createRequestCtx.mjs +16 -0
  57. package/dist/esm-node/node/loaderContext/index.mjs +4 -0
  58. package/dist/esm-node/node/serialize.mjs +5 -0
  59. package/dist/esm-node/node/storer/container.mjs +38 -0
  60. package/dist/esm-node/node/storer/index.mjs +7 -0
  61. package/dist/esm-node/node/storer/storage.mjs +53 -0
  62. package/dist/esm-node/node/stream.mjs +68 -0
  63. package/dist/esm-node/parsed.mjs +12 -0
  64. package/dist/esm-node/router.mjs +18 -0
  65. package/dist/esm-node/rsc.mjs +1 -0
  66. package/dist/esm-node/server/index.mjs +1 -0
  67. package/dist/esm-node/server/nestedRoutes.mjs +15 -0
  68. package/dist/esm-node/time.mjs +27 -0
  69. package/dist/esm-node/universal/async_storage.mjs +24 -0
  70. package/dist/esm-node/universal/async_storage.server.mjs +32 -0
  71. package/dist/esm-node/universal/cache.mjs +326 -0
  72. package/dist/esm-node/universal/request.mjs +40 -0
  73. package/dist/esm-node/url.mjs +5 -0
  74. package/dist/types/browser/nestedRoutes.d.ts +2 -1
  75. package/dist/types/node/stream.d.ts +1 -1
  76. package/dist/types/router.d.ts +6 -1
  77. package/dist/types/rsc.d.ts +1 -0
  78. package/dist/types/universal/async_storage.d.ts +1 -1
  79. package/dist/types/universal/async_storage.server.d.ts +1 -1
  80. package/package.json +36 -46
  81. package/rslib.config.mts +27 -0
  82. package/rstest.config.ts +26 -0
  83. package/dist/cjs/node/router.js +0 -22
  84. package/dist/cjs/remixRouter.js +0 -43
  85. package/dist/esm/browser/deferreds.js +0 -227
  86. package/dist/esm/browser/index.js +0 -2
  87. package/dist/esm/browser/nestedRoutes.js +0 -177
  88. package/dist/esm/merge.js +0 -33
  89. package/dist/esm/node/fileReader.js +0 -140
  90. package/dist/esm/node/index.js +0 -8
  91. package/dist/esm/node/loaderContext/createLoaderCtx.js +0 -24
  92. package/dist/esm/node/loaderContext/createRequestCtx.js +0 -24
  93. package/dist/esm/node/loaderContext/index.js +0 -7
  94. package/dist/esm/node/router.js +0 -1
  95. package/dist/esm/node/serialize.js +0 -9
  96. package/dist/esm/node/storer/container.js +0 -94
  97. package/dist/esm/node/storer/index.js +0 -11
  98. package/dist/esm/node/storer/storage.js +0 -135
  99. package/dist/esm/node/stream.js +0 -87
  100. package/dist/esm/parsed.js +0 -20
  101. package/dist/esm/remixRouter.js +0 -7
  102. package/dist/esm/router.js +0 -1
  103. package/dist/esm/server/index.js +0 -1
  104. package/dist/esm/server/nestedRoutes.js +0 -23
  105. package/dist/esm/time.js +0 -32
  106. package/dist/esm/universal/async_storage.js +0 -18
  107. package/dist/esm/universal/async_storage.server.js +0 -43
  108. package/dist/esm/universal/cache.js +0 -1032
  109. package/dist/esm/universal/request.js +0 -51
  110. package/dist/esm/url.js +0 -10
  111. package/dist/esm-node/browser/deferreds.js +0 -138
  112. package/dist/esm-node/browser/nestedRoutes.js +0 -142
  113. package/dist/esm-node/merge.js +0 -29
  114. package/dist/esm-node/node/fileReader.js +0 -68
  115. package/dist/esm-node/node/loaderContext/createLoaderCtx.js +0 -19
  116. package/dist/esm-node/node/loaderContext/createRequestCtx.js +0 -24
  117. package/dist/esm-node/node/router.js +0 -1
  118. package/dist/esm-node/node/serialize.js +0 -9
  119. package/dist/esm-node/node/storer/container.js +0 -44
  120. package/dist/esm-node/node/storer/storage.js +0 -73
  121. package/dist/esm-node/node/stream.js +0 -80
  122. package/dist/esm-node/parsed.js +0 -20
  123. package/dist/esm-node/remixRouter.js +0 -7
  124. package/dist/esm-node/router.js +0 -1
  125. package/dist/esm-node/server/nestedRoutes.js +0 -21
  126. package/dist/esm-node/time.js +0 -31
  127. package/dist/esm-node/universal/async_storage.js +0 -18
  128. package/dist/esm-node/universal/async_storage.server.js +0 -45
  129. package/dist/esm-node/universal/cache.js +0 -401
  130. package/dist/esm-node/universal/request.js +0 -50
  131. package/dist/esm-node/url.js +0 -10
  132. package/dist/types/node/router.d.ts +0 -1
  133. package/dist/types/remixRouter.d.ts +0 -2
  134. /package/dist/{esm-node/browser/index.js → esm/browser/index.mjs} +0 -0
  135. /package/dist/{esm-node/server/index.js → esm/server/index.mjs} +0 -0
@@ -1,432 +1,381 @@
1
1
  "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var cache_exports = {};
20
- __export(cache_exports, {
21
- CacheSize: () => CacheSize,
22
- CacheTime: () => CacheTime,
23
- cache: () => cache,
24
- clearStore: () => clearStore,
25
- configureCache: () => configureCache,
26
- generateKey: () => generateKey,
27
- revalidateTag: () => revalidateTag,
28
- withRequestCache: () => withRequestCache
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ cache: ()=>cache,
28
+ revalidateTag: ()=>revalidateTag,
29
+ CacheSize: ()=>CacheSize,
30
+ clearStore: ()=>clearStore,
31
+ configureCache: ()=>configureCache,
32
+ withRequestCache: ()=>withRequestCache,
33
+ generateKey: ()=>generateKey,
34
+ CacheTime: ()=>CacheTime
29
35
  });
30
- module.exports = __toCommonJS(cache_exports);
31
- var import_lru_cache = require("lru-cache");
32
- var import_async_storage = require("./async_storage");
36
+ const external_lru_cache_namespaceObject = require("lru-cache");
37
+ const external_async_storage_js_namespaceObject = require("./async_storage.js");
33
38
  const CacheSize = {
34
- KB: 1024,
35
- MB: 1024 * 1024,
36
- GB: 1024 * 1024 * 1024
39
+ KB: 1024,
40
+ MB: 1048576,
41
+ GB: 1073741824
37
42
  };
38
43
  const CacheTime = {
39
- SECOND: 1e3,
40
- MINUTE: 60 * 1e3,
41
- HOUR: 60 * 60 * 1e3,
42
- DAY: 24 * 60 * 60 * 1e3,
43
- WEEK: 7 * 24 * 60 * 60 * 1e3,
44
- MONTH: 30 * 24 * 60 * 60 * 1e3
44
+ SECOND: 1000,
45
+ MINUTE: 60000,
46
+ HOUR: 3600000,
47
+ DAY: 86400000,
48
+ WEEK: 604800000,
49
+ MONTH: 2592000000
45
50
  };
46
51
  function estimateObjectSize(data) {
47
- const type = typeof data;
48
- if (type === "number")
49
- return 8;
50
- if (type === "boolean")
51
- return 4;
52
- if (type === "string")
53
- return Math.max(data.length * 2, 1);
54
- if (data === null || data === void 0)
52
+ const type = typeof data;
53
+ if ('number' === type) return 8;
54
+ if ('boolean' === type) return 4;
55
+ if ('string' === type) return Math.max(2 * data.length, 1);
56
+ if (null == data) return 1;
57
+ if (ArrayBuffer.isView(data)) return Math.max(data.byteLength, 1);
58
+ if (Array.isArray(data)) return Math.max(data.reduce((acc, item)=>acc + estimateObjectSize(item), 0), 1);
59
+ if (data instanceof Map || data instanceof Set) return 1024;
60
+ if (data instanceof Date) return 8;
61
+ if ('object' === type) return Math.max(Object.entries(data).reduce((acc, [key, value])=>acc + 2 * key.length + estimateObjectSize(value), 0), 1);
55
62
  return 1;
56
- if (ArrayBuffer.isView(data)) {
57
- return Math.max(data.byteLength, 1);
58
- }
59
- if (Array.isArray(data)) {
60
- return Math.max(data.reduce((acc, item) => acc + estimateObjectSize(item), 0), 1);
61
- }
62
- if (data instanceof Map || data instanceof Set) {
63
- return 1024;
64
- }
65
- if (data instanceof Date) {
66
- return 8;
67
- }
68
- if (type === "object") {
69
- return Math.max(Object.entries(data).reduce((acc, [key, value]) => acc + key.length * 2 + estimateObjectSize(value), 0), 1);
70
- }
71
- return 1;
72
63
  }
73
64
  class MemoryContainer {
74
- async get(key) {
75
- return this.lru.get(key);
76
- }
77
- async set(key, value, options) {
78
- if (options === null || options === void 0 ? void 0 : options.ttl) {
79
- this.lru.set(key, value, {
80
- ttl: options.ttl * 1e3
81
- });
82
- } else {
83
- this.lru.set(key, value);
65
+ async get(key) {
66
+ return this.lru.get(key);
67
+ }
68
+ async set(key, value, options) {
69
+ if (options?.ttl) this.lru.set(key, value, {
70
+ ttl: 1000 * options.ttl
71
+ });
72
+ else this.lru.set(key, value);
73
+ }
74
+ async has(key) {
75
+ return this.lru.has(key);
76
+ }
77
+ async delete(key) {
78
+ return this.lru.delete(key);
79
+ }
80
+ async clear() {
81
+ this.lru.clear();
82
+ }
83
+ constructor(options){
84
+ this.lru = new external_lru_cache_namespaceObject.LRUCache({
85
+ maxSize: options?.maxSize ?? CacheSize.GB,
86
+ sizeCalculation: estimateObjectSize,
87
+ updateAgeOnGet: true,
88
+ updateAgeOnHas: true
89
+ });
84
90
  }
85
- }
86
- async has(key) {
87
- return this.lru.has(key);
88
- }
89
- async delete(key) {
90
- return this.lru.delete(key);
91
- }
92
- async clear() {
93
- this.lru.clear();
94
- }
95
- constructor(options) {
96
- var _options_maxSize;
97
- this.lru = new import_lru_cache.LRUCache({
98
- maxSize: (_options_maxSize = options === null || options === void 0 ? void 0 : options.maxSize) !== null && _options_maxSize !== void 0 ? _options_maxSize : CacheSize.GB,
99
- sizeCalculation: estimateObjectSize,
100
- updateAgeOnGet: true,
101
- updateAgeOnHas: true
102
- });
103
- }
104
91
  }
105
- const isServer = typeof window === "undefined";
106
- const requestCacheMap = /* @__PURE__ */ new WeakMap();
107
- const TAG_PREFIX = "tag:";
108
- const CACHE_PREFIX = "modernjs_cache:";
109
- const ongoingRevalidations = /* @__PURE__ */ new Map();
110
- let storage;
92
+ const isServer = "u" < typeof window;
93
+ const requestCacheMap = new WeakMap();
94
+ const TAG_PREFIX = 'tag:';
95
+ const CACHE_PREFIX = 'modernjs_cache:';
96
+ const ongoingRevalidations = new Map();
97
+ let cache_storage;
111
98
  let cacheConfig = {
112
- maxSize: CacheSize.GB
99
+ maxSize: CacheSize.GB
113
100
  };
114
101
  function getStorage() {
115
- if (storage) {
116
- return storage;
117
- }
118
- if (cacheConfig.container) {
119
- storage = cacheConfig.container;
120
- } else {
121
- storage = new MemoryContainer({
122
- maxSize: cacheConfig.maxSize
102
+ if (cache_storage) return cache_storage;
103
+ cache_storage = cacheConfig.container ? cacheConfig.container : new MemoryContainer({
104
+ maxSize: cacheConfig.maxSize
123
105
  });
124
- }
125
- return storage;
106
+ return cache_storage;
126
107
  }
127
108
  function configureCache(config) {
128
- cacheConfig = {
129
- ...cacheConfig,
130
- ...config
131
- };
132
- storage = void 0;
109
+ cacheConfig = {
110
+ ...cacheConfig,
111
+ ...config
112
+ };
113
+ cache_storage = void 0;
133
114
  }
134
115
  function generateKey(args) {
135
- return JSON.stringify(args, (_, value) => {
136
- if (value && typeof value === "object" && !Array.isArray(value)) {
137
- return Object.keys(value).sort().reduce((result, key) => {
138
- result[key] = value[key];
139
- return result;
140
- }, {});
141
- }
142
- return value;
143
- });
116
+ return JSON.stringify(args, (_, value)=>{
117
+ if (value && 'object' == typeof value && !Array.isArray(value)) return Object.keys(value).sort().reduce((result, key)=>{
118
+ result[key] = value[key];
119
+ return result;
120
+ }, {});
121
+ return value;
122
+ });
144
123
  }
145
124
  function generateStableFunctionId(fn) {
146
- const fnString = fn.toString();
147
- let hash = 0;
148
- for (let i = 0; i < fnString.length; i++) {
149
- const char = fnString.charCodeAt(i);
150
- hash = (hash << 5) - hash + char;
151
- hash = hash & hash;
152
- }
153
- return `fn_${fn.name || "anonymous"}_${Math.abs(hash).toString(36)}`;
125
+ const fnString = fn.toString();
126
+ let hash = 0;
127
+ for(let i = 0; i < fnString.length; i++){
128
+ const char = fnString.charCodeAt(i);
129
+ hash = (hash << 5) - hash + char;
130
+ hash &= hash;
131
+ }
132
+ return `fn_${fn.name || 'anonymous'}_${Math.abs(hash).toString(36)}`;
154
133
  }
155
134
  function cache(fn, options) {
156
- return async (...args) => {
157
- if (isServer && typeof options === "undefined") {
158
- var _storage_useContext;
159
- const storage2 = (0, import_async_storage.getAsyncLocalStorage)();
160
- const request = storage2 === null || storage2 === void 0 ? void 0 : (_storage_useContext = storage2.useContext()) === null || _storage_useContext === void 0 ? void 0 : _storage_useContext.request;
161
- if (request) {
162
- let shouldDisableCaching = false;
163
- if (cacheConfig.unstable_shouldDisable) {
164
- shouldDisableCaching = await cacheConfig.unstable_shouldDisable({
165
- request
166
- });
167
- }
168
- if (shouldDisableCaching) {
169
- return fn(...args);
170
- }
171
- let requestCache = requestCacheMap.get(request);
172
- if (!requestCache) {
173
- requestCache = /* @__PURE__ */ new Map();
174
- requestCacheMap.set(request, requestCache);
175
- }
176
- let fnCache = requestCache.get(fn);
177
- if (!fnCache) {
178
- fnCache = /* @__PURE__ */ new Map();
179
- requestCache.set(fn, fnCache);
180
- }
181
- const key = generateKey(args);
182
- if (fnCache.has(key)) {
183
- return fnCache.get(key);
184
- }
185
- const promise = fn(...args);
186
- fnCache.set(key, promise);
187
- try {
188
- const data = await promise;
189
- return data;
190
- } catch (error) {
191
- fnCache.delete(key);
192
- throw error;
193
- }
194
- }
195
- } else if (typeof options !== "undefined") {
196
- try {
197
- const { tag, maxAge = CacheTime.MINUTE * 5, revalidate = 0, customKey, onCache, getKey, unstable_shouldCache } = options;
198
- let missReason;
199
- const currentStorage = getStorage();
200
- const now = Date.now();
201
- const tags = tag ? Array.isArray(tag) ? tag : [
202
- tag
203
- ] : [];
204
- const genKey = getKey ? getKey(...args) : generateKey(args);
205
- let finalKey;
206
- if (customKey) {
207
- finalKey = customKey({
208
- params: args,
209
- fn,
210
- generatedKey: genKey
211
- });
212
- } else {
213
- const functionId = generateStableFunctionId(fn);
214
- finalKey = `${functionId}:${genKey}`;
215
- }
216
- const storageKey = `${CACHE_PREFIX}${finalKey}`;
217
- let shouldDisableCaching = false;
218
- if (isServer && cacheConfig.unstable_shouldDisable) {
219
- var _asyncStorage_useContext;
220
- const asyncStorage = (0, import_async_storage.getAsyncLocalStorage)();
221
- const request = asyncStorage === null || asyncStorage === void 0 ? void 0 : (_asyncStorage_useContext = asyncStorage.useContext()) === null || _asyncStorage_useContext === void 0 ? void 0 : _asyncStorage_useContext.request;
222
- if (request) {
223
- shouldDisableCaching = await cacheConfig.unstable_shouldDisable({
224
- request
225
- });
226
- }
227
- }
228
- if (!shouldDisableCaching) {
229
- const cached = await currentStorage.get(storageKey);
230
- if (cached) {
231
- try {
232
- const cacheItem = cached;
233
- const age = now - cacheItem.timestamp;
234
- if (age < maxAge) {
235
- onCache === null || onCache === void 0 ? void 0 : onCache({
236
- status: "hit",
237
- key: finalKey,
238
- params: args,
239
- result: cacheItem.data
135
+ return async (...args)=>{
136
+ if (isServer && void 0 === options) {
137
+ const storage = await (0, external_async_storage_js_namespaceObject.getAsyncLocalStorage)();
138
+ const request = storage?.useContext()?.request;
139
+ if (request) {
140
+ let shouldDisableCaching = false;
141
+ if (cacheConfig.unstable_shouldDisable) shouldDisableCaching = await cacheConfig.unstable_shouldDisable({
142
+ request
240
143
  });
241
- return cacheItem.data;
242
- }
243
- if (revalidate > 0 && age < maxAge + revalidate) {
244
- onCache === null || onCache === void 0 ? void 0 : onCache({
245
- status: "stale",
246
- key: finalKey,
247
- params: args,
248
- result: cacheItem.data
144
+ if (shouldDisableCaching) return fn(...args);
145
+ let requestCache = requestCacheMap.get(request);
146
+ if (!requestCache) {
147
+ requestCache = new Map();
148
+ requestCacheMap.set(request, requestCache);
149
+ }
150
+ let fnCache = requestCache.get(fn);
151
+ if (!fnCache) {
152
+ fnCache = new Map();
153
+ requestCache.set(fn, fnCache);
154
+ }
155
+ const key = generateKey(args);
156
+ if (fnCache.has(key)) return fnCache.get(key);
157
+ const promise = fn(...args);
158
+ fnCache.set(key, promise);
159
+ try {
160
+ const data = await promise;
161
+ return data;
162
+ } catch (error) {
163
+ fnCache.delete(key);
164
+ throw error;
165
+ }
166
+ }
167
+ } else if (void 0 !== options) try {
168
+ const { tag, maxAge = 5 * CacheTime.MINUTE, revalidate = 0, customKey, onCache, getKey, unstable_shouldCache } = options;
169
+ let missReason;
170
+ const currentStorage = getStorage();
171
+ const now = Date.now();
172
+ const tags = tag ? Array.isArray(tag) ? tag : [
173
+ tag
174
+ ] : [];
175
+ const genKey = getKey ? getKey(...args) : generateKey(args);
176
+ let finalKey;
177
+ if (customKey) finalKey = customKey({
178
+ params: args,
179
+ fn,
180
+ generatedKey: genKey
181
+ });
182
+ else {
183
+ const functionId = generateStableFunctionId(fn);
184
+ finalKey = `${functionId}:${genKey}`;
185
+ }
186
+ const storageKey = `${CACHE_PREFIX}${finalKey}`;
187
+ let shouldDisableCaching = false;
188
+ if (isServer && cacheConfig.unstable_shouldDisable) {
189
+ const asyncStorage = await (0, external_async_storage_js_namespaceObject.getAsyncLocalStorage)();
190
+ const request = asyncStorage?.useContext()?.request;
191
+ if (request) shouldDisableCaching = await cacheConfig.unstable_shouldDisable({
192
+ request
249
193
  });
250
- if (!ongoingRevalidations.has(storageKey)) {
251
- const revalidationPromise = (async () => {
252
- try {
253
- const newData = await fn(...args);
254
- let shouldCache = true;
255
- if (unstable_shouldCache) {
256
- shouldCache = await unstable_shouldCache({
257
- params: args,
258
- result: newData
194
+ }
195
+ if (shouldDisableCaching) missReason = 1;
196
+ else {
197
+ const cached = await currentStorage.get(storageKey);
198
+ if (cached) try {
199
+ const cacheItem = cached;
200
+ const age = now - cacheItem.timestamp;
201
+ if (age < maxAge) {
202
+ onCache?.({
203
+ status: 'hit',
204
+ key: finalKey,
205
+ params: args,
206
+ result: cacheItem.data
207
+ });
208
+ return cacheItem.data;
209
+ }
210
+ if (revalidate > 0 && age < maxAge + revalidate) {
211
+ onCache?.({
212
+ status: 'stale',
213
+ key: finalKey,
214
+ params: args,
215
+ result: cacheItem.data
259
216
  });
260
- }
261
- if (shouldCache) {
262
- await setCacheItem(currentStorage, storageKey, newData, tags, maxAge, revalidate);
263
- }
264
- } catch (error) {
265
- if (isServer) {
266
- var _asyncStorage_useContext_monitors, _asyncStorage_useContext2;
267
- const asyncStorage = (0, import_async_storage.getAsyncLocalStorage)();
268
- asyncStorage === null || asyncStorage === void 0 ? void 0 : (_asyncStorage_useContext2 = asyncStorage.useContext()) === null || _asyncStorage_useContext2 === void 0 ? void 0 : (_asyncStorage_useContext_monitors = _asyncStorage_useContext2.monitors) === null || _asyncStorage_useContext_monitors === void 0 ? void 0 : _asyncStorage_useContext_monitors.error(error.message);
269
- } else {
270
- console.error("Background revalidation failed:", error);
271
- }
272
- } finally {
273
- ongoingRevalidations.delete(storageKey);
217
+ if (!ongoingRevalidations.has(storageKey)) {
218
+ const revalidationPromise = (async ()=>{
219
+ try {
220
+ const newData = await fn(...args);
221
+ let shouldCache = true;
222
+ if (unstable_shouldCache) shouldCache = await unstable_shouldCache({
223
+ params: args,
224
+ result: newData
225
+ });
226
+ if (shouldCache) await setCacheItem(currentStorage, storageKey, newData, tags, maxAge, revalidate);
227
+ } catch (error) {
228
+ if (isServer) {
229
+ const asyncStorage = await (0, external_async_storage_js_namespaceObject.getAsyncLocalStorage)();
230
+ asyncStorage?.useContext()?.monitors?.error(error.message);
231
+ } else console.error('Background revalidation failed:', error);
232
+ } finally{
233
+ ongoingRevalidations.delete(storageKey);
234
+ }
235
+ })();
236
+ ongoingRevalidations.set(storageKey, revalidationPromise);
237
+ }
238
+ return cacheItem.data;
274
239
  }
275
- })();
276
- ongoingRevalidations.set(storageKey, revalidationPromise);
240
+ missReason = 3;
241
+ } catch (error) {
242
+ console.warn('Failed to parse cached data:', error);
243
+ missReason = 4;
277
244
  }
278
- return cacheItem.data;
279
- }
280
- missReason = 3;
281
- } catch (error) {
282
- console.warn("Failed to parse cached data:", error);
283
- missReason = 4;
245
+ else missReason = 2;
284
246
  }
285
- } else {
286
- missReason = 2;
287
- }
288
- } else {
289
- missReason = 1;
290
- }
291
- const data = await fn(...args);
292
- if (!shouldDisableCaching) {
293
- let shouldCache = true;
294
- if (unstable_shouldCache) {
295
- shouldCache = await unstable_shouldCache({
296
- params: args,
297
- result: data
247
+ const data = await fn(...args);
248
+ if (!shouldDisableCaching) {
249
+ let shouldCache = true;
250
+ if (unstable_shouldCache) shouldCache = await unstable_shouldCache({
251
+ params: args,
252
+ result: data
253
+ });
254
+ if (shouldCache) await setCacheItem(currentStorage, storageKey, data, tags, maxAge, revalidate);
255
+ }
256
+ onCache?.({
257
+ status: 'miss',
258
+ key: finalKey,
259
+ params: args,
260
+ result: data,
261
+ reason: missReason
298
262
  });
299
- }
300
- if (shouldCache) {
301
- await setCacheItem(currentStorage, storageKey, data, tags, maxAge, revalidate);
302
- }
263
+ return data;
264
+ } catch (error) {
265
+ console.warn('Cache operation failed, falling back to direct execution:', error);
266
+ const data = await fn(...args);
267
+ const { onCache } = options;
268
+ try {
269
+ onCache?.({
270
+ status: 'miss',
271
+ key: 'cache_failed',
272
+ params: args,
273
+ result: data,
274
+ reason: 5
275
+ });
276
+ } catch (callbackError) {
277
+ console.warn('Failed to call onCache callback:', callbackError);
278
+ }
279
+ return data;
303
280
  }
304
- onCache === null || onCache === void 0 ? void 0 : onCache({
305
- status: "miss",
306
- key: finalKey,
307
- params: args,
308
- result: data,
309
- reason: missReason
310
- });
311
- return data;
312
- } catch (error) {
313
- console.warn("Cache operation failed, falling back to direct execution:", error);
314
- const data = await fn(...args);
315
- const { onCache } = options;
316
- try {
317
- onCache === null || onCache === void 0 ? void 0 : onCache({
318
- status: "miss",
319
- key: "cache_failed",
320
- params: args,
321
- result: data,
322
- reason: 5
323
- });
324
- } catch (callbackError) {
325
- console.warn("Failed to call onCache callback:", callbackError);
281
+ else {
282
+ console.warn('The cache function will not work because it runs on the browser and there are no options are provided.');
283
+ return fn(...args);
326
284
  }
327
- return data;
328
- }
329
- } else {
330
- console.warn("The cache function will not work because it runs on the browser and there are no options are provided.");
331
- return fn(...args);
332
- }
333
- };
285
+ };
334
286
  }
335
- async function setCacheItem(storage2, storageKey, data, tags, maxAge, revalidate) {
336
- const newItem = {
337
- data,
338
- timestamp: Date.now(),
339
- tags: tags.length > 0 ? tags : void 0
340
- };
341
- const ttl = (maxAge + revalidate) / 1e3;
342
- await storage2.set(storageKey, newItem, {
343
- ttl: ttl > 0 ? ttl : void 0
344
- });
345
- await updateTagRelationships(storage2, storageKey, tags);
287
+ async function setCacheItem(storage, storageKey, data, tags, maxAge, revalidate) {
288
+ const newItem = {
289
+ data,
290
+ timestamp: Date.now(),
291
+ tags: tags.length > 0 ? tags : void 0
292
+ };
293
+ const ttl = (maxAge + revalidate) / 1000;
294
+ await storage.set(storageKey, newItem, {
295
+ ttl: ttl > 0 ? ttl : void 0
296
+ });
297
+ await updateTagRelationships(storage, storageKey, tags);
346
298
  }
347
- async function updateTagRelationships(storage2, storageKey, tags) {
348
- for (const tag of tags) {
349
- const tagStoreKey = `${TAG_PREFIX}${tag}`;
350
- const keyList = await storage2.get(tagStoreKey);
351
- const keyArray = keyList || [];
352
- if (!keyArray.includes(storageKey)) {
353
- keyArray.push(storageKey);
299
+ async function updateTagRelationships(storage, storageKey, tags) {
300
+ for (const tag of tags){
301
+ const tagStoreKey = `${TAG_PREFIX}${tag}`;
302
+ const keyList = await storage.get(tagStoreKey);
303
+ const keyArray = keyList || [];
304
+ if (!keyArray.includes(storageKey)) keyArray.push(storageKey);
305
+ await storage.set(tagStoreKey, keyArray);
354
306
  }
355
- await storage2.set(tagStoreKey, keyArray);
356
- }
357
307
  }
358
- async function removeKeyFromTags(storage2, storageKey, tags) {
359
- for (const tag of tags) {
360
- const tagStoreKey = `${TAG_PREFIX}${tag}`;
361
- const keyList = await storage2.get(tagStoreKey);
362
- if (keyList) {
363
- try {
364
- const keyArray = Array.isArray(keyList) ? keyList : [];
365
- const updatedKeyList = keyArray.filter((key) => key !== storageKey);
366
- if (updatedKeyList.length > 0) {
367
- await storage2.set(tagStoreKey, updatedKeyList);
368
- } else {
369
- await storage2.delete(tagStoreKey);
308
+ async function removeKeyFromTags(storage, storageKey, tags) {
309
+ for (const tag of tags){
310
+ const tagStoreKey = `${TAG_PREFIX}${tag}`;
311
+ const keyList = await storage.get(tagStoreKey);
312
+ if (keyList) try {
313
+ const keyArray = Array.isArray(keyList) ? keyList : [];
314
+ const updatedKeyList = keyArray.filter((key)=>key !== storageKey);
315
+ if (updatedKeyList.length > 0) await storage.set(tagStoreKey, updatedKeyList);
316
+ else await storage.delete(tagStoreKey);
317
+ } catch (error) {
318
+ console.warn(`Failed to process tag key list for tag ${tag}:`, error);
370
319
  }
371
- } catch (error) {
372
- console.warn(`Failed to process tag key list for tag ${tag}:`, error);
373
- }
374
320
  }
375
- }
376
321
  }
377
322
  function withRequestCache(handler) {
378
- if (!isServer) {
379
- return handler;
380
- }
381
- return async (req, ...args) => {
382
- const storage2 = (0, import_async_storage.getAsyncLocalStorage)();
383
- return storage2.run({
384
- request: req
385
- }, () => handler(req, ...args));
386
- };
323
+ if (!isServer) return handler;
324
+ return async (req, ...args)=>{
325
+ const storage = await (0, external_async_storage_js_namespaceObject.getAsyncLocalStorage)();
326
+ return storage.run({
327
+ request: req
328
+ }, ()=>handler(req, ...args));
329
+ };
387
330
  }
388
331
  async function revalidateTag(tag) {
389
- const currentStorage = getStorage();
390
- const tagStoreKey = `${TAG_PREFIX}${tag}`;
391
- const keyList = await currentStorage.get(tagStoreKey);
392
- if (keyList) {
393
- try {
394
- const keyArray = Array.isArray(keyList) ? keyList : [];
395
- for (const cacheKey of keyArray) {
396
- const cached = await currentStorage.get(cacheKey);
397
- if (cached) {
398
- try {
399
- const cacheItem = cached;
400
- if (cacheItem.tags) {
401
- const otherTags = cacheItem.tags.filter((t) => t !== tag);
402
- await removeKeyFromTags(currentStorage, cacheKey, otherTags);
332
+ const currentStorage = getStorage();
333
+ const tagStoreKey = `${TAG_PREFIX}${tag}`;
334
+ const keyList = await currentStorage.get(tagStoreKey);
335
+ if (keyList) try {
336
+ const keyArray = Array.isArray(keyList) ? keyList : [];
337
+ for (const cacheKey of keyArray){
338
+ const cached = await currentStorage.get(cacheKey);
339
+ if (cached) try {
340
+ const cacheItem = cached;
341
+ if (cacheItem.tags) {
342
+ const otherTags = cacheItem.tags.filter((t)=>t !== tag);
343
+ await removeKeyFromTags(currentStorage, cacheKey, otherTags);
344
+ }
345
+ } catch (error) {
346
+ console.warn('Failed to parse cached data while revalidating:', error);
403
347
  }
404
- } catch (error) {
405
- console.warn("Failed to parse cached data while revalidating:", error);
406
- }
348
+ await currentStorage.delete(cacheKey);
407
349
  }
408
- await currentStorage.delete(cacheKey);
409
- }
410
- await currentStorage.delete(tagStoreKey);
350
+ await currentStorage.delete(tagStoreKey);
411
351
  } catch (error) {
412
- console.warn("Failed to process tag key list:", error);
352
+ console.warn('Failed to process tag key list:', error);
413
353
  }
414
- }
415
354
  }
416
355
  async function clearStore() {
417
- const currentStorage = getStorage();
418
- await currentStorage.clear();
419
- storage = void 0;
420
- ongoingRevalidations.clear();
356
+ const currentStorage = getStorage();
357
+ await currentStorage.clear();
358
+ cache_storage = void 0;
359
+ ongoingRevalidations.clear();
421
360
  }
422
- // Annotate the CommonJS export names for ESM import in node:
423
- 0 && (module.exports = {
424
- CacheSize,
425
- CacheTime,
426
- cache,
427
- clearStore,
428
- configureCache,
429
- generateKey,
430
- revalidateTag,
431
- withRequestCache
361
+ exports.CacheSize = __webpack_exports__.CacheSize;
362
+ exports.CacheTime = __webpack_exports__.CacheTime;
363
+ exports.cache = __webpack_exports__.cache;
364
+ exports.clearStore = __webpack_exports__.clearStore;
365
+ exports.configureCache = __webpack_exports__.configureCache;
366
+ exports.generateKey = __webpack_exports__.generateKey;
367
+ exports.revalidateTag = __webpack_exports__.revalidateTag;
368
+ exports.withRequestCache = __webpack_exports__.withRequestCache;
369
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
370
+ "CacheSize",
371
+ "CacheTime",
372
+ "cache",
373
+ "clearStore",
374
+ "configureCache",
375
+ "generateKey",
376
+ "revalidateTag",
377
+ "withRequestCache"
378
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
379
+ Object.defineProperty(exports, '__esModule', {
380
+ value: true
432
381
  });