@bleedingdev/modern-js-runtime-utils 3.2.0-ultramodern.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/LICENSE +21 -0
- package/README.md +26 -0
- package/dist/cjs/browser/deferreds.js +161 -0
- package/dist/cjs/browser/index.js +65 -0
- package/dist/cjs/browser/nestedRoutes.js +141 -0
- package/dist/cjs/merge.js +60 -0
- package/dist/cjs/node/fileReader.js +94 -0
- package/dist/cjs/node/index.js +99 -0
- package/dist/cjs/node/loaderContext/createLoaderCtx.js +51 -0
- package/dist/cjs/node/loaderContext/createRequestCtx.js +50 -0
- package/dist/cjs/node/loaderContext/index.js +41 -0
- package/dist/cjs/node/nestedRoutes.js +58 -0
- package/dist/cjs/node/sanitize.js +103 -0
- package/dist/cjs/node/serialize.js +49 -0
- package/dist/cjs/node/storer/container.js +72 -0
- package/dist/cjs/node/storer/index.js +44 -0
- package/dist/cjs/node/storer/storage.js +87 -0
- package/dist/cjs/parsed.js +46 -0
- package/dist/cjs/router.js +91 -0
- package/dist/cjs/rsc.js +58 -0
- package/dist/cjs/server/index.js +58 -0
- package/dist/cjs/server/nestedRoutes.js +49 -0
- package/dist/cjs/time.js +61 -0
- package/dist/cjs/universal/async_storage.js +58 -0
- package/dist/cjs/universal/async_storage.server.js +69 -0
- package/dist/cjs/universal/cache.js +381 -0
- package/dist/cjs/universal/request.js +86 -0
- package/dist/cjs/url.js +39 -0
- package/dist/esm/browser/deferreds.mjs +118 -0
- package/dist/esm/browser/index.mjs +2 -0
- package/dist/esm/browser/nestedRoutes.mjs +104 -0
- package/dist/esm/merge.mjs +26 -0
- package/dist/esm/node/fileReader.mjs +47 -0
- package/dist/esm/node/index.mjs +5 -0
- package/dist/esm/node/loaderContext/createLoaderCtx.mjs +14 -0
- package/dist/esm/node/loaderContext/createRequestCtx.mjs +16 -0
- package/dist/esm/node/loaderContext/index.mjs +4 -0
- package/dist/esm/node/nestedRoutes.mjs +1 -0
- package/dist/esm/node/sanitize.mjs +66 -0
- package/dist/esm/node/serialize.mjs +5 -0
- package/dist/esm/node/storer/container.mjs +38 -0
- package/dist/esm/node/storer/index.mjs +7 -0
- package/dist/esm/node/storer/storage.mjs +53 -0
- package/dist/esm/parsed.mjs +12 -0
- package/dist/esm/router.mjs +18 -0
- package/dist/esm/rsc.mjs +1 -0
- package/dist/esm/server/index.mjs +1 -0
- package/dist/esm/server/nestedRoutes.mjs +15 -0
- package/dist/esm/time.mjs +27 -0
- package/dist/esm/universal/async_storage.mjs +7 -0
- package/dist/esm/universal/async_storage.server.mjs +32 -0
- package/dist/esm/universal/cache.mjs +326 -0
- package/dist/esm/universal/request.mjs +40 -0
- package/dist/esm/url.mjs +5 -0
- package/dist/esm-node/browser/deferreds.mjs +119 -0
- package/dist/esm-node/browser/index.mjs +3 -0
- package/dist/esm-node/browser/nestedRoutes.mjs +105 -0
- package/dist/esm-node/merge.mjs +27 -0
- package/dist/esm-node/node/fileReader.mjs +48 -0
- package/dist/esm-node/node/index.mjs +6 -0
- package/dist/esm-node/node/loaderContext/createLoaderCtx.mjs +15 -0
- package/dist/esm-node/node/loaderContext/createRequestCtx.mjs +17 -0
- package/dist/esm-node/node/loaderContext/index.mjs +5 -0
- package/dist/esm-node/node/nestedRoutes.mjs +2 -0
- package/dist/esm-node/node/sanitize.mjs +67 -0
- package/dist/esm-node/node/serialize.mjs +6 -0
- package/dist/esm-node/node/storer/container.mjs +39 -0
- package/dist/esm-node/node/storer/index.mjs +8 -0
- package/dist/esm-node/node/storer/storage.mjs +54 -0
- package/dist/esm-node/parsed.mjs +13 -0
- package/dist/esm-node/router.mjs +19 -0
- package/dist/esm-node/rsc.mjs +2 -0
- package/dist/esm-node/server/index.mjs +2 -0
- package/dist/esm-node/server/nestedRoutes.mjs +16 -0
- package/dist/esm-node/time.mjs +28 -0
- package/dist/esm-node/universal/async_storage.mjs +25 -0
- package/dist/esm-node/universal/async_storage.server.mjs +33 -0
- package/dist/esm-node/universal/cache.mjs +327 -0
- package/dist/esm-node/universal/request.mjs +41 -0
- package/dist/esm-node/url.mjs +6 -0
- package/dist/types/browser/deferreds.d.ts +31 -0
- package/dist/types/browser/index.d.ts +2 -0
- package/dist/types/browser/nestedRoutes.d.ts +12 -0
- package/dist/types/merge.d.ts +6 -0
- package/dist/types/node/fileReader.d.ts +19 -0
- package/dist/types/node/index.d.ts +8 -0
- package/dist/types/node/loaderContext/createLoaderCtx.d.ts +7 -0
- package/dist/types/node/loaderContext/createRequestCtx.d.ts +16 -0
- package/dist/types/node/loaderContext/index.d.ts +4 -0
- package/dist/types/node/nestedRoutes.d.ts +1 -0
- package/dist/types/node/sanitize.d.ts +11 -0
- package/dist/types/node/serialize.d.ts +1 -0
- package/dist/types/node/storer/container.d.ts +27 -0
- package/dist/types/node/storer/index.d.ts +3 -0
- package/dist/types/node/storer/storage.d.ts +26 -0
- package/dist/types/parsed.d.ts +1 -0
- package/dist/types/router.d.ts +6 -0
- package/dist/types/rsc.d.ts +1 -0
- package/dist/types/server/index.d.ts +1 -0
- package/dist/types/server/nestedRoutes.d.ts +2 -0
- package/dist/types/time.d.ts +1 -0
- package/dist/types/universal/async_storage.d.ts +2 -0
- package/dist/types/universal/async_storage.server.d.ts +29 -0
- package/dist/types/universal/cache.d.ts +68 -0
- package/dist/types/universal/request.d.ts +17 -0
- package/dist/types/url.d.ts +11 -0
- package/package.json +197 -0
- package/rslib.config.mts +28 -0
- package/rstest.config.mts +26 -0
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
import { LRUCache } from "lru-cache";
|
|
2
|
+
import { getAsyncLocalStorage } from "./async_storage.mjs";
|
|
3
|
+
const CacheSize = {
|
|
4
|
+
KB: 1024,
|
|
5
|
+
MB: 1048576,
|
|
6
|
+
GB: 1073741824
|
|
7
|
+
};
|
|
8
|
+
const CacheTime = {
|
|
9
|
+
SECOND: 1000,
|
|
10
|
+
MINUTE: 60000,
|
|
11
|
+
HOUR: 3600000,
|
|
12
|
+
DAY: 86400000,
|
|
13
|
+
WEEK: 604800000,
|
|
14
|
+
MONTH: 2592000000
|
|
15
|
+
};
|
|
16
|
+
function estimateObjectSize(data) {
|
|
17
|
+
const type = typeof data;
|
|
18
|
+
if ('number' === type) return 8;
|
|
19
|
+
if ('boolean' === type) return 4;
|
|
20
|
+
if ('string' === type) return Math.max(2 * data.length, 1);
|
|
21
|
+
if (null == data) return 1;
|
|
22
|
+
if (ArrayBuffer.isView(data)) return Math.max(data.byteLength, 1);
|
|
23
|
+
if (Array.isArray(data)) return Math.max(data.reduce((acc, item)=>acc + estimateObjectSize(item), 0), 1);
|
|
24
|
+
if (data instanceof Map || data instanceof Set) return 1024;
|
|
25
|
+
if (data instanceof Date) return 8;
|
|
26
|
+
if ('object' === type) return Math.max(Object.entries(data).reduce((acc, [key, value])=>acc + 2 * key.length + estimateObjectSize(value), 0), 1);
|
|
27
|
+
return 1;
|
|
28
|
+
}
|
|
29
|
+
class MemoryContainer {
|
|
30
|
+
async get(key) {
|
|
31
|
+
return this.lru.get(key);
|
|
32
|
+
}
|
|
33
|
+
async set(key, value, options) {
|
|
34
|
+
if (options?.ttl) this.lru.set(key, value, {
|
|
35
|
+
ttl: 1000 * options.ttl
|
|
36
|
+
});
|
|
37
|
+
else this.lru.set(key, value);
|
|
38
|
+
}
|
|
39
|
+
async has(key) {
|
|
40
|
+
return this.lru.has(key);
|
|
41
|
+
}
|
|
42
|
+
async delete(key) {
|
|
43
|
+
return this.lru.delete(key);
|
|
44
|
+
}
|
|
45
|
+
async clear() {
|
|
46
|
+
this.lru.clear();
|
|
47
|
+
}
|
|
48
|
+
constructor(options){
|
|
49
|
+
this.lru = new LRUCache({
|
|
50
|
+
maxSize: options?.maxSize ?? CacheSize.GB,
|
|
51
|
+
sizeCalculation: estimateObjectSize,
|
|
52
|
+
updateAgeOnGet: true,
|
|
53
|
+
updateAgeOnHas: true
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const isServer = "u" < typeof window;
|
|
58
|
+
const requestCacheMap = new WeakMap();
|
|
59
|
+
const TAG_PREFIX = 'tag:';
|
|
60
|
+
const CACHE_PREFIX = 'modernjs_cache:';
|
|
61
|
+
const ongoingRevalidations = new Map();
|
|
62
|
+
let cache_storage;
|
|
63
|
+
let cacheConfig = {
|
|
64
|
+
maxSize: CacheSize.GB
|
|
65
|
+
};
|
|
66
|
+
function getStorage() {
|
|
67
|
+
if (cache_storage) return cache_storage;
|
|
68
|
+
cache_storage = cacheConfig.container ? cacheConfig.container : new MemoryContainer({
|
|
69
|
+
maxSize: cacheConfig.maxSize
|
|
70
|
+
});
|
|
71
|
+
return cache_storage;
|
|
72
|
+
}
|
|
73
|
+
function configureCache(config) {
|
|
74
|
+
cacheConfig = {
|
|
75
|
+
...cacheConfig,
|
|
76
|
+
...config
|
|
77
|
+
};
|
|
78
|
+
cache_storage = void 0;
|
|
79
|
+
}
|
|
80
|
+
function generateKey(args) {
|
|
81
|
+
return JSON.stringify(args, (_, value)=>{
|
|
82
|
+
if (value && 'object' == typeof value && !Array.isArray(value)) return Object.keys(value).sort().reduce((result, key)=>{
|
|
83
|
+
result[key] = value[key];
|
|
84
|
+
return result;
|
|
85
|
+
}, {});
|
|
86
|
+
return value;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
function generateStableFunctionId(fn) {
|
|
90
|
+
const fnString = fn.toString();
|
|
91
|
+
let hash = 0;
|
|
92
|
+
for(let i = 0; i < fnString.length; i++){
|
|
93
|
+
const char = fnString.charCodeAt(i);
|
|
94
|
+
hash = (hash << 5) - hash + char;
|
|
95
|
+
hash &= hash;
|
|
96
|
+
}
|
|
97
|
+
return `fn_${fn.name || 'anonymous'}_${Math.abs(hash).toString(36)}`;
|
|
98
|
+
}
|
|
99
|
+
function cache(fn, options) {
|
|
100
|
+
return async (...args)=>{
|
|
101
|
+
if (isServer && void 0 === options) {
|
|
102
|
+
const storage = await getAsyncLocalStorage();
|
|
103
|
+
const request = storage?.useContext()?.request;
|
|
104
|
+
if (request) {
|
|
105
|
+
let shouldDisableCaching = false;
|
|
106
|
+
if (cacheConfig.unstable_shouldDisable) shouldDisableCaching = await cacheConfig.unstable_shouldDisable({
|
|
107
|
+
request
|
|
108
|
+
});
|
|
109
|
+
if (shouldDisableCaching) return fn(...args);
|
|
110
|
+
let requestCache = requestCacheMap.get(request);
|
|
111
|
+
if (!requestCache) {
|
|
112
|
+
requestCache = new Map();
|
|
113
|
+
requestCacheMap.set(request, requestCache);
|
|
114
|
+
}
|
|
115
|
+
let fnCache = requestCache.get(fn);
|
|
116
|
+
if (!fnCache) {
|
|
117
|
+
fnCache = new Map();
|
|
118
|
+
requestCache.set(fn, fnCache);
|
|
119
|
+
}
|
|
120
|
+
const key = generateKey(args);
|
|
121
|
+
if (fnCache.has(key)) return fnCache.get(key);
|
|
122
|
+
const promise = fn(...args);
|
|
123
|
+
fnCache.set(key, promise);
|
|
124
|
+
try {
|
|
125
|
+
const data = await promise;
|
|
126
|
+
return data;
|
|
127
|
+
} catch (error) {
|
|
128
|
+
fnCache.delete(key);
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
} else if (void 0 !== options) try {
|
|
133
|
+
const { tag, maxAge = 5 * CacheTime.MINUTE, revalidate = 0, customKey, onCache, getKey, unstable_shouldCache } = options;
|
|
134
|
+
let missReason;
|
|
135
|
+
const currentStorage = getStorage();
|
|
136
|
+
const now = Date.now();
|
|
137
|
+
const tags = tag ? Array.isArray(tag) ? tag : [
|
|
138
|
+
tag
|
|
139
|
+
] : [];
|
|
140
|
+
const genKey = getKey ? getKey(...args) : generateKey(args);
|
|
141
|
+
let finalKey;
|
|
142
|
+
if (customKey) finalKey = customKey({
|
|
143
|
+
params: args,
|
|
144
|
+
fn,
|
|
145
|
+
generatedKey: genKey
|
|
146
|
+
});
|
|
147
|
+
else {
|
|
148
|
+
const functionId = generateStableFunctionId(fn);
|
|
149
|
+
finalKey = `${functionId}:${genKey}`;
|
|
150
|
+
}
|
|
151
|
+
const storageKey = `${CACHE_PREFIX}${finalKey}`;
|
|
152
|
+
let shouldDisableCaching = false;
|
|
153
|
+
if (isServer && cacheConfig.unstable_shouldDisable) {
|
|
154
|
+
const asyncStorage = await getAsyncLocalStorage();
|
|
155
|
+
const request = asyncStorage?.useContext()?.request;
|
|
156
|
+
if (request) shouldDisableCaching = await cacheConfig.unstable_shouldDisable({
|
|
157
|
+
request
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
if (shouldDisableCaching) missReason = 1;
|
|
161
|
+
else {
|
|
162
|
+
const cached = await currentStorage.get(storageKey);
|
|
163
|
+
if (cached) try {
|
|
164
|
+
const cacheItem = cached;
|
|
165
|
+
const age = now - cacheItem.timestamp;
|
|
166
|
+
if (age < maxAge) {
|
|
167
|
+
onCache?.({
|
|
168
|
+
status: 'hit',
|
|
169
|
+
key: finalKey,
|
|
170
|
+
params: args,
|
|
171
|
+
result: cacheItem.data
|
|
172
|
+
});
|
|
173
|
+
return cacheItem.data;
|
|
174
|
+
}
|
|
175
|
+
if (revalidate > 0 && age < maxAge + revalidate) {
|
|
176
|
+
onCache?.({
|
|
177
|
+
status: 'stale',
|
|
178
|
+
key: finalKey,
|
|
179
|
+
params: args,
|
|
180
|
+
result: cacheItem.data
|
|
181
|
+
});
|
|
182
|
+
if (!ongoingRevalidations.has(storageKey)) {
|
|
183
|
+
const revalidationPromise = (async ()=>{
|
|
184
|
+
try {
|
|
185
|
+
const newData = await fn(...args);
|
|
186
|
+
let shouldCache = true;
|
|
187
|
+
if (unstable_shouldCache) shouldCache = await unstable_shouldCache({
|
|
188
|
+
params: args,
|
|
189
|
+
result: newData
|
|
190
|
+
});
|
|
191
|
+
if (shouldCache) await setCacheItem(currentStorage, storageKey, newData, tags, maxAge, revalidate);
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (isServer) {
|
|
194
|
+
const asyncStorage = await getAsyncLocalStorage();
|
|
195
|
+
asyncStorage?.useContext()?.monitors?.error(error.message);
|
|
196
|
+
} else console.error('Background revalidation failed:', error);
|
|
197
|
+
} finally{
|
|
198
|
+
ongoingRevalidations.delete(storageKey);
|
|
199
|
+
}
|
|
200
|
+
})();
|
|
201
|
+
ongoingRevalidations.set(storageKey, revalidationPromise);
|
|
202
|
+
}
|
|
203
|
+
return cacheItem.data;
|
|
204
|
+
}
|
|
205
|
+
missReason = 3;
|
|
206
|
+
} catch (error) {
|
|
207
|
+
console.warn('Failed to parse cached data:', error);
|
|
208
|
+
missReason = 4;
|
|
209
|
+
}
|
|
210
|
+
else missReason = 2;
|
|
211
|
+
}
|
|
212
|
+
const data = await fn(...args);
|
|
213
|
+
if (!shouldDisableCaching) {
|
|
214
|
+
let shouldCache = true;
|
|
215
|
+
if (unstable_shouldCache) shouldCache = await unstable_shouldCache({
|
|
216
|
+
params: args,
|
|
217
|
+
result: data
|
|
218
|
+
});
|
|
219
|
+
if (shouldCache) await setCacheItem(currentStorage, storageKey, data, tags, maxAge, revalidate);
|
|
220
|
+
}
|
|
221
|
+
onCache?.({
|
|
222
|
+
status: 'miss',
|
|
223
|
+
key: finalKey,
|
|
224
|
+
params: args,
|
|
225
|
+
result: data,
|
|
226
|
+
reason: missReason
|
|
227
|
+
});
|
|
228
|
+
return data;
|
|
229
|
+
} catch (error) {
|
|
230
|
+
console.warn('Cache operation failed, falling back to direct execution:', error);
|
|
231
|
+
const data = await fn(...args);
|
|
232
|
+
const { onCache } = options;
|
|
233
|
+
try {
|
|
234
|
+
onCache?.({
|
|
235
|
+
status: 'miss',
|
|
236
|
+
key: 'cache_failed',
|
|
237
|
+
params: args,
|
|
238
|
+
result: data,
|
|
239
|
+
reason: 5
|
|
240
|
+
});
|
|
241
|
+
} catch (callbackError) {
|
|
242
|
+
console.warn('Failed to call onCache callback:', callbackError);
|
|
243
|
+
}
|
|
244
|
+
return data;
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
console.warn('The cache function will not work because it runs on the browser and there are no options are provided.');
|
|
248
|
+
return fn(...args);
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
async function setCacheItem(storage, storageKey, data, tags, maxAge, revalidate) {
|
|
253
|
+
const newItem = {
|
|
254
|
+
data,
|
|
255
|
+
timestamp: Date.now(),
|
|
256
|
+
tags: tags.length > 0 ? tags : void 0
|
|
257
|
+
};
|
|
258
|
+
const ttl = (maxAge + revalidate) / 1000;
|
|
259
|
+
await storage.set(storageKey, newItem, {
|
|
260
|
+
ttl: ttl > 0 ? ttl : void 0
|
|
261
|
+
});
|
|
262
|
+
await updateTagRelationships(storage, storageKey, tags);
|
|
263
|
+
}
|
|
264
|
+
async function updateTagRelationships(storage, storageKey, tags) {
|
|
265
|
+
for (const tag of tags){
|
|
266
|
+
const tagStoreKey = `${TAG_PREFIX}${tag}`;
|
|
267
|
+
const keyList = await storage.get(tagStoreKey);
|
|
268
|
+
const keyArray = keyList || [];
|
|
269
|
+
if (!keyArray.includes(storageKey)) keyArray.push(storageKey);
|
|
270
|
+
await storage.set(tagStoreKey, keyArray);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
async function removeKeyFromTags(storage, storageKey, tags) {
|
|
274
|
+
for (const tag of tags){
|
|
275
|
+
const tagStoreKey = `${TAG_PREFIX}${tag}`;
|
|
276
|
+
const keyList = await storage.get(tagStoreKey);
|
|
277
|
+
if (keyList) try {
|
|
278
|
+
const keyArray = Array.isArray(keyList) ? keyList : [];
|
|
279
|
+
const updatedKeyList = keyArray.filter((key)=>key !== storageKey);
|
|
280
|
+
if (updatedKeyList.length > 0) await storage.set(tagStoreKey, updatedKeyList);
|
|
281
|
+
else await storage.delete(tagStoreKey);
|
|
282
|
+
} catch (error) {
|
|
283
|
+
console.warn(`Failed to process tag key list for tag ${tag}:`, error);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
function withRequestCache(handler) {
|
|
288
|
+
if (!isServer) return handler;
|
|
289
|
+
return async (req, ...args)=>{
|
|
290
|
+
const storage = await getAsyncLocalStorage();
|
|
291
|
+
return storage.run({
|
|
292
|
+
request: req
|
|
293
|
+
}, ()=>handler(req, ...args));
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
async function revalidateTag(tag) {
|
|
297
|
+
const currentStorage = getStorage();
|
|
298
|
+
const tagStoreKey = `${TAG_PREFIX}${tag}`;
|
|
299
|
+
const keyList = await currentStorage.get(tagStoreKey);
|
|
300
|
+
if (keyList) try {
|
|
301
|
+
const keyArray = Array.isArray(keyList) ? keyList : [];
|
|
302
|
+
for (const cacheKey of keyArray){
|
|
303
|
+
const cached = await currentStorage.get(cacheKey);
|
|
304
|
+
if (cached) try {
|
|
305
|
+
const cacheItem = cached;
|
|
306
|
+
if (cacheItem.tags) {
|
|
307
|
+
const otherTags = cacheItem.tags.filter((t)=>t !== tag);
|
|
308
|
+
await removeKeyFromTags(currentStorage, cacheKey, otherTags);
|
|
309
|
+
}
|
|
310
|
+
} catch (error) {
|
|
311
|
+
console.warn('Failed to parse cached data while revalidating:', error);
|
|
312
|
+
}
|
|
313
|
+
await currentStorage.delete(cacheKey);
|
|
314
|
+
}
|
|
315
|
+
await currentStorage.delete(tagStoreKey);
|
|
316
|
+
} catch (error) {
|
|
317
|
+
console.warn('Failed to process tag key list:', error);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
async function clearStore() {
|
|
321
|
+
const currentStorage = getStorage();
|
|
322
|
+
await currentStorage.clear();
|
|
323
|
+
cache_storage = void 0;
|
|
324
|
+
ongoingRevalidations.clear();
|
|
325
|
+
}
|
|
326
|
+
export { CacheSize, CacheTime, cache, clearStore, configureCache, generateKey, revalidateTag, withRequestCache };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
function parseQuery(req) {
|
|
2
|
+
const query = {};
|
|
3
|
+
const { url } = req;
|
|
4
|
+
const q = url.split('?')[1];
|
|
5
|
+
if (q) {
|
|
6
|
+
const search = new URLSearchParams(q);
|
|
7
|
+
search.forEach((v, k)=>{
|
|
8
|
+
query[k] = v;
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
return query;
|
|
12
|
+
}
|
|
13
|
+
function parseHeaders(request) {
|
|
14
|
+
const headersData = {};
|
|
15
|
+
request.headers.forEach((value, key)=>{
|
|
16
|
+
headersData[key] = value;
|
|
17
|
+
});
|
|
18
|
+
return headersData;
|
|
19
|
+
}
|
|
20
|
+
function getPathname(request) {
|
|
21
|
+
const match = request.url.match(/^https?:\/\/[^/]+(\/[^?]*)/);
|
|
22
|
+
return match ? match[1] : '/';
|
|
23
|
+
}
|
|
24
|
+
function getHost(request) {
|
|
25
|
+
const { headers } = request;
|
|
26
|
+
let host = headers.get('X-Forwarded-Host');
|
|
27
|
+
if (!host) host = headers.get('Host');
|
|
28
|
+
host = host?.split(/\s*,\s*/, 1)[0] || 'undefined';
|
|
29
|
+
return host;
|
|
30
|
+
}
|
|
31
|
+
function parseCookie(req) {
|
|
32
|
+
const _cookie = req.headers.get('Cookie');
|
|
33
|
+
const cookie = {};
|
|
34
|
+
_cookie?.trim().split(';').forEach((item)=>{
|
|
35
|
+
const [k, v] = item.trim().split('=');
|
|
36
|
+
if (k) cookie[k] = v;
|
|
37
|
+
});
|
|
38
|
+
return cookie;
|
|
39
|
+
}
|
|
40
|
+
export { getHost, getPathname, parseCookie, parseHeaders, parseQuery };
|
package/dist/esm/url.mjs
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
function invariant(value, message) {
|
|
3
|
+
if (false === value || null == value) throw new Error(message);
|
|
4
|
+
}
|
|
5
|
+
class AbortedDeferredError extends Error {
|
|
6
|
+
}
|
|
7
|
+
function isTrackedPromise(value) {
|
|
8
|
+
return value instanceof Promise && true === value._tracked;
|
|
9
|
+
}
|
|
10
|
+
function unwrapTrackedPromise(value) {
|
|
11
|
+
if (!isTrackedPromise(value)) return value;
|
|
12
|
+
if (value._error) throw value._error;
|
|
13
|
+
return value._data;
|
|
14
|
+
}
|
|
15
|
+
class DeferredData {
|
|
16
|
+
trackPromise(key, value) {
|
|
17
|
+
if (!(value instanceof Promise)) return value;
|
|
18
|
+
this.deferredKeys.push(key);
|
|
19
|
+
this.pendingKeysSet.add(key);
|
|
20
|
+
const promise = Promise.race([
|
|
21
|
+
value,
|
|
22
|
+
this.abortPromise
|
|
23
|
+
]).then((data)=>this.onSettle(promise, key, void 0, data), (error)=>this.onSettle(promise, key, error));
|
|
24
|
+
promise.catch(()=>{});
|
|
25
|
+
Object.defineProperty(promise, '_tracked', {
|
|
26
|
+
get: ()=>true
|
|
27
|
+
});
|
|
28
|
+
return promise;
|
|
29
|
+
}
|
|
30
|
+
onSettle(promise, key, error, data) {
|
|
31
|
+
if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {
|
|
32
|
+
this.unlistenAbortSignal();
|
|
33
|
+
Object.defineProperty(promise, '_error', {
|
|
34
|
+
get: ()=>error
|
|
35
|
+
});
|
|
36
|
+
return Promise.reject(error);
|
|
37
|
+
}
|
|
38
|
+
this.pendingKeysSet.delete(key);
|
|
39
|
+
if (this.done) this.unlistenAbortSignal();
|
|
40
|
+
if (void 0 === error && void 0 === data) {
|
|
41
|
+
const undefinedError = new Error(`Deferred data for key "${key}" resolved/rejected with \`undefined\`, you must resolve/reject with a value or \`null\`.`);
|
|
42
|
+
Object.defineProperty(promise, '_error', {
|
|
43
|
+
get: ()=>undefinedError
|
|
44
|
+
});
|
|
45
|
+
this.emit(false, key);
|
|
46
|
+
return Promise.reject(undefinedError);
|
|
47
|
+
}
|
|
48
|
+
if (void 0 === data) {
|
|
49
|
+
Object.defineProperty(promise, '_error', {
|
|
50
|
+
get: ()=>error
|
|
51
|
+
});
|
|
52
|
+
this.emit(false, key);
|
|
53
|
+
return Promise.reject(error);
|
|
54
|
+
}
|
|
55
|
+
Object.defineProperty(promise, '_data', {
|
|
56
|
+
get: ()=>data
|
|
57
|
+
});
|
|
58
|
+
this.emit(false, key);
|
|
59
|
+
return data;
|
|
60
|
+
}
|
|
61
|
+
emit(aborted, settledKey) {
|
|
62
|
+
this.subscribers.forEach((subscriber)=>subscriber(aborted, settledKey));
|
|
63
|
+
}
|
|
64
|
+
subscribe(fn) {
|
|
65
|
+
this.subscribers.add(fn);
|
|
66
|
+
return ()=>this.subscribers.delete(fn);
|
|
67
|
+
}
|
|
68
|
+
cancel() {
|
|
69
|
+
this.controller.abort();
|
|
70
|
+
this.pendingKeysSet.forEach((v, k)=>this.pendingKeysSet.delete(k));
|
|
71
|
+
this.emit(true);
|
|
72
|
+
}
|
|
73
|
+
async resolveData(signal) {
|
|
74
|
+
let aborted = false;
|
|
75
|
+
if (!this.done) {
|
|
76
|
+
const onAbort = ()=>this.cancel();
|
|
77
|
+
signal.addEventListener('abort', onAbort);
|
|
78
|
+
aborted = await new Promise((resolve)=>{
|
|
79
|
+
this.subscribe((aborted)=>{
|
|
80
|
+
signal.removeEventListener('abort', onAbort);
|
|
81
|
+
if (aborted || this.done) resolve(aborted);
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
return aborted;
|
|
86
|
+
}
|
|
87
|
+
get done() {
|
|
88
|
+
return 0 === this.pendingKeysSet.size;
|
|
89
|
+
}
|
|
90
|
+
get unwrappedData() {
|
|
91
|
+
invariant(null !== this.data && this.done, 'Can only unwrap data on initialized and settled deferreds');
|
|
92
|
+
return Object.entries(this.data).reduce((acc, [key, value])=>Object.assign(acc, {
|
|
93
|
+
[key]: unwrapTrackedPromise(value)
|
|
94
|
+
}), {});
|
|
95
|
+
}
|
|
96
|
+
get pendingKeys() {
|
|
97
|
+
return Array.from(this.pendingKeysSet);
|
|
98
|
+
}
|
|
99
|
+
constructor(data, responseInit){
|
|
100
|
+
this.pendingKeysSet = new Set();
|
|
101
|
+
this.subscribers = new Set();
|
|
102
|
+
this.__modern_deferred = true;
|
|
103
|
+
this.deferredKeys = [];
|
|
104
|
+
invariant(data && 'object' == typeof data && !Array.isArray(data), 'defer() only accepts plain objects');
|
|
105
|
+
let reject;
|
|
106
|
+
this.abortPromise = new Promise((_, r)=>reject = r);
|
|
107
|
+
this.controller = new AbortController();
|
|
108
|
+
const onAbort = ()=>reject(new AbortedDeferredError('Deferred data aborted'));
|
|
109
|
+
this.unlistenAbortSignal = ()=>this.controller.signal.removeEventListener('abort', onAbort);
|
|
110
|
+
this.controller.signal.addEventListener('abort', onAbort);
|
|
111
|
+
this.data = Object.entries(data).reduce((acc, [key, value])=>Object.assign(acc, {
|
|
112
|
+
[key]: this.trackPromise(key, value)
|
|
113
|
+
}), {});
|
|
114
|
+
if (this.done) this.unlistenAbortSignal();
|
|
115
|
+
this.init = responseInit;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const activeDeferreds = new Map();
|
|
119
|
+
export { AbortedDeferredError, DeferredData, activeDeferreds, invariant };
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { jsx } from "react/jsx-runtime";
|
|
3
|
+
import { LOADER_REPORTER_NAME } from "@modern-js/utils/universal/constants";
|
|
4
|
+
import { Suspense } from "react";
|
|
5
|
+
import { Outlet, Route, createRoutesFromElements } from "react-router";
|
|
6
|
+
import { time } from "../time.mjs";
|
|
7
|
+
import { getAsyncLocalStorage } from "../universal/async_storage.mjs";
|
|
8
|
+
import { DeferredData, activeDeferreds as external_deferreds_mjs_activeDeferreds } from "./deferreds.mjs";
|
|
9
|
+
const privateDefer = (data)=>new DeferredData(data);
|
|
10
|
+
const transformNestedRoutes = (routes)=>{
|
|
11
|
+
const routeElements = [];
|
|
12
|
+
for (const route of routes){
|
|
13
|
+
const routeElement = renderNestedRoute(route);
|
|
14
|
+
routeElements.push(routeElement);
|
|
15
|
+
}
|
|
16
|
+
return createRoutesFromElements(routeElements);
|
|
17
|
+
};
|
|
18
|
+
const renderNestedRoute = (nestedRoute, options = {})=>{
|
|
19
|
+
const { children, index, id, component, isRoot, lazyImport, config, handle } = nestedRoute;
|
|
20
|
+
const Component = component;
|
|
21
|
+
const { parent, props = {} } = options;
|
|
22
|
+
const routeProps = {
|
|
23
|
+
caseSensitive: nestedRoute.caseSensitive,
|
|
24
|
+
path: nestedRoute.path,
|
|
25
|
+
id: nestedRoute.id,
|
|
26
|
+
loader: createLoader(nestedRoute),
|
|
27
|
+
action: nestedRoute.action,
|
|
28
|
+
hasErrorBoundary: nestedRoute.hasErrorBoundary,
|
|
29
|
+
shouldRevalidate: nestedRoute.shouldRevalidate,
|
|
30
|
+
handle: {
|
|
31
|
+
...handle,
|
|
32
|
+
...'object' == typeof config ? config?.handle : {}
|
|
33
|
+
},
|
|
34
|
+
index: nestedRoute.index,
|
|
35
|
+
element: nestedRoute.element,
|
|
36
|
+
errorElement: nestedRoute.errorElement
|
|
37
|
+
};
|
|
38
|
+
if (nestedRoute.error) {
|
|
39
|
+
const errorElement = /*#__PURE__*/ jsx(nestedRoute.error, {});
|
|
40
|
+
routeProps.errorElement = errorElement;
|
|
41
|
+
}
|
|
42
|
+
let element;
|
|
43
|
+
if (Component) if (parent?.loading && lazyImport) {
|
|
44
|
+
const Loading = parent.loading;
|
|
45
|
+
element = isLoadableComponent(Component) ? /*#__PURE__*/ jsx(Component, {
|
|
46
|
+
fallback: /*#__PURE__*/ jsx(Loading, {})
|
|
47
|
+
}) : /*#__PURE__*/ jsx(Suspense, {
|
|
48
|
+
fallback: /*#__PURE__*/ jsx(Loading, {}),
|
|
49
|
+
children: /*#__PURE__*/ jsx(Component, {})
|
|
50
|
+
});
|
|
51
|
+
} else element = isLoadableComponent(Component) && lazyImport ? /*#__PURE__*/ jsx(Component, {}) : isRoot ? /*#__PURE__*/ jsx(Component, {
|
|
52
|
+
...props
|
|
53
|
+
}) : lazyImport ? /*#__PURE__*/ jsx(Suspense, {
|
|
54
|
+
fallback: null,
|
|
55
|
+
children: /*#__PURE__*/ jsx(Component, {})
|
|
56
|
+
}) : /*#__PURE__*/ jsx(Component, {});
|
|
57
|
+
else {
|
|
58
|
+
nestedRoute.loading = parent?.loading;
|
|
59
|
+
routeProps.element = /*#__PURE__*/ jsx(Outlet, {});
|
|
60
|
+
}
|
|
61
|
+
if (element) routeProps.element = element;
|
|
62
|
+
const childElements = children?.map((childRoute)=>renderNestedRoute(childRoute, {
|
|
63
|
+
parent: nestedRoute
|
|
64
|
+
}));
|
|
65
|
+
const routeElement = index ? /*#__PURE__*/ jsx(Route, {
|
|
66
|
+
...routeProps,
|
|
67
|
+
index: true
|
|
68
|
+
}, id) : /*#__PURE__*/ jsx(Route, {
|
|
69
|
+
...routeProps,
|
|
70
|
+
index: false,
|
|
71
|
+
children: childElements
|
|
72
|
+
}, id);
|
|
73
|
+
return routeElement;
|
|
74
|
+
};
|
|
75
|
+
function isPlainObject(value) {
|
|
76
|
+
return null != value && 'object' == typeof value && Object.getPrototypeOf(value) === Object.prototype;
|
|
77
|
+
}
|
|
78
|
+
function createLoader(route) {
|
|
79
|
+
const { loader } = route;
|
|
80
|
+
if (loader) return async (args)=>{
|
|
81
|
+
if ('function' == typeof route.lazyImport) route.lazyImport();
|
|
82
|
+
const end = time();
|
|
83
|
+
const res = await loader(args);
|
|
84
|
+
let activeDeferreds = null;
|
|
85
|
+
activeDeferreds = "u" < typeof document ? (await getAsyncLocalStorage())?.useContext()?.activeDeferreds : external_deferreds_mjs_activeDeferreds;
|
|
86
|
+
if (isPlainObject(res)) {
|
|
87
|
+
const deferredData = privateDefer(res);
|
|
88
|
+
activeDeferreds.set(route.id, deferredData);
|
|
89
|
+
}
|
|
90
|
+
const cost = end();
|
|
91
|
+
if ("u" < typeof document) {
|
|
92
|
+
const storage = await getAsyncLocalStorage();
|
|
93
|
+
storage?.useContext().monitors?.timing(`${LOADER_REPORTER_NAME}-${route.id?.replace(/\//g, '_')}`, cost);
|
|
94
|
+
}
|
|
95
|
+
return res;
|
|
96
|
+
};
|
|
97
|
+
return ()=>{
|
|
98
|
+
if ('function' == typeof route.lazyImport) route.lazyImport();
|
|
99
|
+
return null;
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function isLoadableComponent(component) {
|
|
103
|
+
return component && 'Loadable' === component.displayName && component.preload && 'function' == typeof component.preload;
|
|
104
|
+
}
|
|
105
|
+
export { renderNestedRoute, transformNestedRoutes };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
function isObject(obj) {
|
|
3
|
+
return obj && 'object' == typeof obj && !Array.isArray(obj);
|
|
4
|
+
}
|
|
5
|
+
function isComplexInstance(obj) {
|
|
6
|
+
if (!isObject(obj)) return false;
|
|
7
|
+
const hasMethods = 'function' == typeof obj.init || 'function' == typeof obj.changeLanguage || 'function' == typeof obj.t;
|
|
8
|
+
const hasInternalProps = void 0 !== obj.isInitialized || void 0 !== obj.language || void 0 !== obj.store;
|
|
9
|
+
return hasMethods || hasInternalProps;
|
|
10
|
+
}
|
|
11
|
+
function merge(target, ...sources) {
|
|
12
|
+
if (!sources.length) return target;
|
|
13
|
+
const source = sources.shift();
|
|
14
|
+
if (isObject(target) && isObject(source)) for(const key in source)if (isComplexInstance(source[key])) Object.assign(target, {
|
|
15
|
+
[key]: source[key]
|
|
16
|
+
});
|
|
17
|
+
else if (isObject(source[key])) {
|
|
18
|
+
if (!target[key]) Object.assign(target, {
|
|
19
|
+
[key]: {}
|
|
20
|
+
});
|
|
21
|
+
merge(target[key], source[key]);
|
|
22
|
+
} else Object.assign(target, {
|
|
23
|
+
[key]: source[key]
|
|
24
|
+
});
|
|
25
|
+
return merge(target, ...sources);
|
|
26
|
+
}
|
|
27
|
+
export { merge };
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import fs_extra from "@modern-js/utils/fs-extra";
|
|
3
|
+
import { createMemoryStorage } from "./storer/index.mjs";
|
|
4
|
+
class FileReader {
|
|
5
|
+
async readFile(path, encoding = 'utf-8') {
|
|
6
|
+
const { fs } = this;
|
|
7
|
+
const _readfile = this._readFileFactory(fs);
|
|
8
|
+
return _readfile(path, encoding);
|
|
9
|
+
}
|
|
10
|
+
async readFileFromSystem(path, encoding = 'utf-8') {
|
|
11
|
+
const _readfile = this._readFileFactory(fs_extra);
|
|
12
|
+
return _readfile(path, encoding);
|
|
13
|
+
}
|
|
14
|
+
_readFileFactory(fs) {
|
|
15
|
+
return async (path, encoding = 'utf-8')=>{
|
|
16
|
+
const cache = await this.storage.get(path);
|
|
17
|
+
if (null === cache) return null;
|
|
18
|
+
if (cache) return this.encodingContent(cache, encoding);
|
|
19
|
+
const isExistFile = await new Promise((resolve)=>{
|
|
20
|
+
fs.stat(path, (err, stats)=>{
|
|
21
|
+
if (err) return void resolve(false);
|
|
22
|
+
stats.isFile() ? resolve(true) : resolve(false);
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
if (isExistFile) {
|
|
26
|
+
const content = await fs.promises.readFile(path);
|
|
27
|
+
this.storage.set(path, content);
|
|
28
|
+
return this.encodingContent(content, encoding);
|
|
29
|
+
}
|
|
30
|
+
this.storage.set(path, null);
|
|
31
|
+
return null;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
reset(fs) {
|
|
35
|
+
fs && (this.fs = fs);
|
|
36
|
+
return this.storage.clear?.();
|
|
37
|
+
}
|
|
38
|
+
encodingContent(value, encoding) {
|
|
39
|
+
if ('utf-8' === encoding) return value.toString();
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
constructor(storage){
|
|
43
|
+
this.fs = fs_extra;
|
|
44
|
+
this.storage = storage;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const fileReader = new FileReader(createMemoryStorage('__file__system'));
|
|
48
|
+
export { FileReader, fileReader };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
export * from "./loaderContext/index.mjs";
|
|
3
|
+
export * from "./nestedRoutes.mjs";
|
|
4
|
+
export { storage } from "../universal/async_storage.server.mjs";
|
|
5
|
+
export { sanitizeSSRPayload } from "./sanitize.mjs";
|
|
6
|
+
export { serializeJson } from "./serialize.mjs";
|