@modern-js/prod-server 2.42.2 → 2.44.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 (90) hide show
  1. package/dist/cjs/libs/{render/cache/page-caches/index.js → hook-api/afterRenderForStream.js} +12 -14
  2. package/dist/cjs/libs/hook-api/index.js +12 -0
  3. package/dist/cjs/libs/render/index.js +4 -14
  4. package/dist/cjs/libs/render/ssr.js +15 -4
  5. package/dist/cjs/libs/render/{cache/page-caches/lru.js → ssrCache/cacheMod.js} +21 -31
  6. package/dist/cjs/libs/render/ssrCache/index.js +81 -0
  7. package/dist/cjs/libs/render/ssrCache/manager.js +104 -0
  8. package/dist/cjs/libs/render/static.js +5 -5
  9. package/dist/cjs/server/index.js +2 -0
  10. package/dist/cjs/server/modernServer.js +2 -9
  11. package/dist/esm/libs/hook-api/afterRenderForStream.js +33 -0
  12. package/dist/esm/libs/hook-api/index.js +10 -0
  13. package/dist/esm/libs/render/index.js +4 -14
  14. package/dist/esm/libs/render/ssr.js +19 -5
  15. package/dist/esm/libs/render/ssrCache/cacheMod.js +33 -0
  16. package/dist/esm/libs/render/ssrCache/index.js +146 -0
  17. package/dist/esm/libs/render/ssrCache/manager.js +159 -0
  18. package/dist/esm/libs/render/static.js +5 -5
  19. package/dist/esm/server/index.js +14 -4
  20. package/dist/esm/server/modernServer.js +32 -42
  21. package/dist/esm-node/libs/hook-api/afterRenderForStream.js +10 -0
  22. package/dist/esm-node/libs/hook-api/index.js +11 -0
  23. package/dist/esm-node/libs/render/index.js +4 -14
  24. package/dist/esm-node/libs/render/ssr.js +15 -4
  25. package/dist/esm-node/libs/render/ssrCache/cacheMod.js +22 -0
  26. package/dist/esm-node/libs/render/ssrCache/index.js +57 -0
  27. package/dist/esm-node/libs/render/ssrCache/manager.js +80 -0
  28. package/dist/esm-node/libs/render/static.js +5 -5
  29. package/dist/esm-node/server/index.js +2 -0
  30. package/dist/esm-node/server/modernServer.js +2 -9
  31. package/dist/types/libs/context/index.d.ts +2 -0
  32. package/dist/types/libs/hook-api/afterRenderForStream.d.ts +4 -0
  33. package/dist/types/libs/hook-api/index.d.ts +2 -1
  34. package/dist/types/libs/preload/flushServerHeader.d.ts +2 -0
  35. package/dist/types/libs/proxy.d.ts +2 -0
  36. package/dist/types/libs/render/ssr.d.ts +5 -5
  37. package/dist/types/libs/render/ssrCache/cacheMod.d.ts +8 -0
  38. package/dist/types/libs/render/ssrCache/index.d.ts +7 -0
  39. package/dist/types/libs/render/ssrCache/manager.d.ts +14 -0
  40. package/dist/types/renderHtml.d.ts +2 -0
  41. package/dist/types/server/index.d.ts +2 -0
  42. package/dist/types/server/modernServer.d.ts +2 -3
  43. package/dist/types/type.d.ts +2 -0
  44. package/package.json +8 -11
  45. package/dist/cjs/libs/render/cache/__tests__/cache.fun.test.js +0 -95
  46. package/dist/cjs/libs/render/cache/__tests__/cache.test.js +0 -223
  47. package/dist/cjs/libs/render/cache/__tests__/cacheable.js +0 -93
  48. package/dist/cjs/libs/render/cache/__tests__/error-configuration.js +0 -71
  49. package/dist/cjs/libs/render/cache/__tests__/matched-cache.js +0 -173
  50. package/dist/cjs/libs/render/cache/index.js +0 -92
  51. package/dist/cjs/libs/render/cache/spr.js +0 -247
  52. package/dist/cjs/libs/render/cache/type.js +0 -16
  53. package/dist/cjs/libs/render/cache/util.js +0 -121
  54. package/dist/cjs/libs/render/reader.js +0 -131
  55. package/dist/esm/libs/render/cache/__tests__/cache.fun.test.js +0 -124
  56. package/dist/esm/libs/render/cache/__tests__/cache.test.js +0 -612
  57. package/dist/esm/libs/render/cache/__tests__/cacheable.js +0 -69
  58. package/dist/esm/libs/render/cache/__tests__/error-configuration.js +0 -47
  59. package/dist/esm/libs/render/cache/__tests__/matched-cache.js +0 -149
  60. package/dist/esm/libs/render/cache/index.js +0 -204
  61. package/dist/esm/libs/render/cache/page-caches/index.js +0 -34
  62. package/dist/esm/libs/render/cache/page-caches/lru.js +0 -57
  63. package/dist/esm/libs/render/cache/spr.js +0 -345
  64. package/dist/esm/libs/render/cache/type.js +0 -0
  65. package/dist/esm/libs/render/cache/util.js +0 -105
  66. package/dist/esm/libs/render/reader.js +0 -196
  67. package/dist/esm-node/libs/render/cache/__tests__/cache.fun.test.js +0 -72
  68. package/dist/esm-node/libs/render/cache/__tests__/cache.test.js +0 -222
  69. package/dist/esm-node/libs/render/cache/__tests__/cacheable.js +0 -69
  70. package/dist/esm-node/libs/render/cache/__tests__/error-configuration.js +0 -47
  71. package/dist/esm-node/libs/render/cache/__tests__/matched-cache.js +0 -149
  72. package/dist/esm-node/libs/render/cache/index.js +0 -72
  73. package/dist/esm-node/libs/render/cache/page-caches/index.js +0 -12
  74. package/dist/esm-node/libs/render/cache/page-caches/lru.js +0 -32
  75. package/dist/esm-node/libs/render/cache/spr.js +0 -212
  76. package/dist/esm-node/libs/render/cache/type.js +0 -0
  77. package/dist/esm-node/libs/render/cache/util.js +0 -80
  78. package/dist/esm-node/libs/render/reader.js +0 -93
  79. package/dist/types/libs/render/cache/__tests__/cache.fun.test.d.ts +0 -1
  80. package/dist/types/libs/render/cache/__tests__/cache.test.d.ts +0 -1
  81. package/dist/types/libs/render/cache/__tests__/cacheable.d.ts +0 -62
  82. package/dist/types/libs/render/cache/__tests__/error-configuration.d.ts +0 -28
  83. package/dist/types/libs/render/cache/__tests__/matched-cache.d.ts +0 -124
  84. package/dist/types/libs/render/cache/index.d.ts +0 -6
  85. package/dist/types/libs/render/cache/page-caches/index.d.ts +0 -2
  86. package/dist/types/libs/render/cache/page-caches/lru.d.ts +0 -15
  87. package/dist/types/libs/render/cache/spr.d.ts +0 -22
  88. package/dist/types/libs/render/cache/type.d.ts +0 -48
  89. package/dist/types/libs/render/cache/util.d.ts +0 -18
  90. package/dist/types/libs/render/reader.d.ts +0 -20
@@ -1,247 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var spr_exports = {};
30
- __export(spr_exports, {
31
- createCache: () => createCache,
32
- destroyCache: () => destroyCache
33
- });
34
- module.exports = __toCommonJS(spr_exports);
35
- var import_define_property = require("@swc/helpers/_/_define_property");
36
- var import_crypto = __toESM(require("crypto"));
37
- var import_lru_cache = __toESM(require("lru-cache"));
38
- var import_utils = require("@modern-js/utils");
39
- var import_util = require("./util");
40
- var import_page_caches = require("./page-caches");
41
- const MAX_CACHE_EACH_REQ = Number(process.env.ROUTE_CACHE_LIMIT) || 10;
42
- const MAX_SIZE_EACH_CLUSTER = Number(process.env.CLUSTER_CACHE_LIMIT) || 100;
43
- const BASE_LEVEL = 0;
44
- const QUERY_LEVEL = 1;
45
- const HEADER_LEVEL = 2;
46
- const QUERY_HEADER_LEVEL = 3;
47
- class CacheManager {
48
- md5(content) {
49
- const md5 = import_crypto.default.createHash("md5");
50
- return md5.update(content).digest("hex");
51
- }
52
- generateRequestKey(context) {
53
- const { pathname, entry } = context;
54
- return this.md5(`${pathname}_${entry}`);
55
- }
56
- replaceValue(value, matcher) {
57
- let final = value;
58
- Object.keys(matcher).some((replacer) => {
59
- const reg = new RegExp(matcher[replacer]);
60
- if (reg.test(value)) {
61
- final = replacer;
62
- return true;
63
- }
64
- return false;
65
- });
66
- return final;
67
- }
68
- factor(keys, obj, matches = {}) {
69
- keys.sort();
70
- const getValue = (0, import_util.valueFactory)(obj);
71
- const factorAry = keys.reduce((ary, key) => {
72
- let value = getValue(key) || "";
73
- const matcher = matches[key];
74
- if (matcher) {
75
- value = this.replaceValue(value, matcher);
76
- }
77
- return ary.concat([
78
- key,
79
- value
80
- ]);
81
- }, []);
82
- return factorAry.join(",");
83
- }
84
- queryFactor(context, data) {
85
- var _data_includes, _data_matches;
86
- const queryKeys = (_data_includes = data.includes) === null || _data_includes === void 0 ? void 0 : _data_includes.query;
87
- const queryMatches = (_data_matches = data.matches) === null || _data_matches === void 0 ? void 0 : _data_matches.query;
88
- if (!queryKeys || queryKeys.length === 0) {
89
- return null;
90
- }
91
- const requestQuery = context.query;
92
- const queryFactor = this.factor(queryKeys, requestQuery, queryMatches);
93
- return queryFactor;
94
- }
95
- headerFactor(context, data) {
96
- var _data_includes, _data_matches;
97
- const headerKeys = (_data_includes = data.includes) === null || _data_includes === void 0 ? void 0 : _data_includes.header;
98
- const headerMatches = (_data_matches = data.matches) === null || _data_matches === void 0 ? void 0 : _data_matches.header;
99
- if (!headerKeys || headerKeys.length === 0) {
100
- return null;
101
- }
102
- const requestHeader = context.headers;
103
- const headerFactor = this.factor(headerKeys, requestHeader, headerMatches);
104
- return headerFactor;
105
- }
106
- async best(context, cacheKey, data) {
107
- const { level } = data;
108
- const cacheHash = this.find[(0, import_util.fname)(level)](context, cacheKey, data);
109
- if (!cacheHash) {
110
- return null;
111
- }
112
- return data.caches.get(cacheHash);
113
- }
114
- createCacheContent(config, caches) {
115
- return {
116
- level: config.level,
117
- interval: config.interval,
118
- includes: config.includes || null,
119
- limit: config.staleLimit,
120
- matches: config.matches || null,
121
- caches
122
- };
123
- }
124
- async get(context) {
125
- const cacheKey = this.generateRequestKey(context);
126
- const data = this.cache.get(cacheKey);
127
- if (!data) {
128
- return null;
129
- }
130
- const dest = await this.best(context, cacheKey, data);
131
- if (!dest) {
132
- return null;
133
- }
134
- const { expireTime, limitTime, html, cacheHash } = dest;
135
- const isStale = Date.now() - expireTime > 0;
136
- const isGarbage = limitTime ? Date.now() - limitTime > 0 : false;
137
- return {
138
- content: html || "",
139
- contentType: import_utils.mime.contentType("html"),
140
- isStale,
141
- isGarbage,
142
- hash: cacheHash
143
- };
144
- }
145
- async set(context, html, cacheConfig, sync = false) {
146
- if (!cacheConfig) {
147
- return false;
148
- }
149
- const cacheKey = this.generateRequestKey(context);
150
- let data = this.cache.get(cacheKey);
151
- if (!data) {
152
- const caches = await (0, import_page_caches.createPageCaches)(MAX_CACHE_EACH_REQ);
153
- data = this.createCacheContent(cacheConfig, caches);
154
- }
155
- const cacheHash = this.find[(0, import_util.fname)(cacheConfig.level)](context, cacheKey, data);
156
- if (!cacheHash) {
157
- return false;
158
- }
159
- const cacheSyncOrAsync = async () => {
160
- const next = data;
161
- const limit = cacheConfig.staleLimit;
162
- const storeHTML = (0, import_util.cacheAddition)(html, cacheHash);
163
- const size = storeHTML.length;
164
- await next.caches.set(cacheHash, {
165
- expireTime: Date.now() + cacheConfig.interval * 1e3,
166
- limitTime: typeof limit === "number" ? Date.now() + limit * 1e3 : null,
167
- cacheHash,
168
- html: storeHTML,
169
- size
170
- });
171
- this.cache.set(cacheKey, next);
172
- return true;
173
- };
174
- const doCache = (0, import_util.withCoalescedInvoke)(cacheSyncOrAsync).bind(null, (0, import_util.namespaceHash)("stream", cacheHash), []);
175
- return (0, import_util.maybeSync)(doCache)(sync);
176
- }
177
- async del(context, cacheHash) {
178
- const cacheKey = this.generateRequestKey(context);
179
- const data = this.cache.get(cacheKey);
180
- data === null || data === void 0 ? void 0 : data.caches.del(cacheHash);
181
- }
182
- constructor(cacheOptions) {
183
- (0, import_define_property._)(this, "cache", void 0);
184
- (0, import_define_property._)(this, "cacheOptions", void 0);
185
- (0, import_define_property._)(this, "find", (() => {
186
- {
187
- const _this = this;
188
- return {
189
- [(0, import_util.fname)(BASE_LEVEL)](context, cacheKey) {
190
- return _this.md5(cacheKey);
191
- },
192
- [(0, import_util.fname)(QUERY_LEVEL)](context, cacheKey, data) {
193
- const queryFactor = _this.queryFactor(context, data);
194
- if (!queryFactor) {
195
- return null;
196
- }
197
- return _this.md5((0, import_util.connectFactor)(cacheKey, queryFactor));
198
- },
199
- [(0, import_util.fname)(HEADER_LEVEL)](context, cacheKey, data) {
200
- const headerFactor = _this.headerFactor(context, data);
201
- if (!headerFactor) {
202
- return null;
203
- }
204
- return _this.md5((0, import_util.connectFactor)(cacheKey, headerFactor));
205
- },
206
- [(0, import_util.fname)(QUERY_HEADER_LEVEL)](context, cacheKey, data) {
207
- const queryFactor = _this.queryFactor(context, data);
208
- const headerFactor = _this.headerFactor(context, data);
209
- if (!queryFactor || !headerFactor) {
210
- return null;
211
- }
212
- return _this.md5((0, import_util.connectFactor)(cacheKey, headerFactor, queryFactor));
213
- }
214
- };
215
- }
216
- })());
217
- this.cacheOptions = cacheOptions;
218
- this.cache = new import_lru_cache.default({
219
- max: Math.min(MAX_SIZE_EACH_CLUSTER, 600) * 1024 * 1024,
220
- length(n) {
221
- const len = n.caches.keys().reduce((total, cur) => {
222
- var _n_caches_peek;
223
- return total + (((_n_caches_peek = n.caches.peek(cur)) === null || _n_caches_peek === void 0 ? void 0 : _n_caches_peek.size) || 0);
224
- }, 1);
225
- return len;
226
- }
227
- });
228
- }
229
- }
230
- let manager;
231
- function createCache() {
232
- if (manager) {
233
- return manager;
234
- }
235
- manager = new CacheManager({
236
- max: 0
237
- });
238
- return manager;
239
- }
240
- function destroyCache() {
241
- manager = null;
242
- }
243
- // Annotate the CommonJS export names for ESM import in node:
244
- 0 && (module.exports = {
245
- createCache,
246
- destroyCache
247
- });
@@ -1,16 +0,0 @@
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 __copyProps = (to, from, except, desc) => {
7
- if (from && typeof from === "object" || typeof from === "function") {
8
- for (let key of __getOwnPropNames(from))
9
- if (!__hasOwnProp.call(to, key) && key !== except)
10
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
- }
12
- return to;
13
- };
14
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
- var type_exports = {};
16
- module.exports = __toCommonJS(type_exports);
@@ -1,121 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var util_exports = {};
30
- __export(util_exports, {
31
- cacheAddition: () => cacheAddition,
32
- connectFactor: () => connectFactor,
33
- fname: () => fname,
34
- getTime: () => getTime,
35
- maybeSync: () => maybeSync,
36
- namespaceHash: () => namespaceHash,
37
- valueFactory: () => valueFactory,
38
- withCoalescedInvoke: () => withCoalescedInvoke
39
- });
40
- module.exports = __toCommonJS(util_exports);
41
- var import_url = __toESM(require("url"));
42
- function namespaceHash(namespace, hash) {
43
- return `${namespace}/${hash}`;
44
- }
45
- function fname(lv) {
46
- return `f${lv}`;
47
- }
48
- function connectFactor(...args) {
49
- return args.join("-");
50
- }
51
- function valueFactory(obj) {
52
- if (obj instanceof import_url.default.URLSearchParams) {
53
- return function(key) {
54
- return obj.get(key);
55
- };
56
- } else {
57
- return function(key) {
58
- const value = obj[key];
59
- if (Array.isArray(value)) {
60
- return value.join(",");
61
- }
62
- return value;
63
- };
64
- }
65
- }
66
- function getTime([s, ns]) {
67
- return Math.floor(s * 1e3 + ns / 1e6);
68
- }
69
- const RE_START_IN_HEAD = /<head>/;
70
- function cacheAddition(html, hash) {
71
- const additionHtml = html.replace(RE_START_IN_HEAD, `<head><meta name="x-moden-spr" content="${hash}">`);
72
- return additionHtml;
73
- }
74
- const globalInvokeCache = /* @__PURE__ */ new Map();
75
- function withCoalescedInvoke(func) {
76
- return async function(key, args) {
77
- const entry = globalInvokeCache.get(key);
78
- if (entry) {
79
- return entry.then((res) => ({
80
- isOrigin: false,
81
- value: res.value
82
- }));
83
- }
84
- function __wrapper() {
85
- return func(...args);
86
- }
87
- const future = __wrapper().then((res) => {
88
- globalInvokeCache.delete(key);
89
- return {
90
- isOrigin: true,
91
- value: res
92
- };
93
- }).catch((err) => {
94
- globalInvokeCache.delete(key);
95
- throw err;
96
- });
97
- globalInvokeCache.set(key, future);
98
- return future;
99
- };
100
- }
101
- function maybeSync(fn) {
102
- return (sync) => {
103
- if (sync) {
104
- return fn();
105
- } else {
106
- fn();
107
- return Promise.resolve();
108
- }
109
- };
110
- }
111
- // Annotate the CommonJS export names for ESM import in node:
112
- 0 && (module.exports = {
113
- cacheAddition,
114
- connectFactor,
115
- fname,
116
- getTime,
117
- maybeSync,
118
- namespaceHash,
119
- valueFactory,
120
- withCoalescedInvoke
121
- });
@@ -1,131 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var reader_exports = {};
30
- __export(reader_exports, {
31
- LruReader: () => LruReader,
32
- close: () => close,
33
- init: () => init,
34
- readFile: () => readFile,
35
- updateFile: () => updateFile
36
- });
37
- module.exports = __toCommonJS(reader_exports);
38
- var import_define_property = require("@swc/helpers/_/_define_property");
39
- var import_utils = require("@modern-js/utils");
40
- var import_lru_cache = __toESM(require("lru-cache"));
41
- const Byte = 1;
42
- const KB = 1024 * Byte;
43
- const MB = 1024 * KB;
44
- const getContentLength = (cache) => cache.content.length;
45
- const createCacheItem = async (content, mtime) => {
46
- return {
47
- content,
48
- mtime
49
- };
50
- };
51
- class LruReader {
52
- init(fs) {
53
- this.fs = fs || import_utils.fs;
54
- }
55
- close() {
56
- }
57
- async read(filepath) {
58
- const { fs } = this;
59
- if (this.cache.has(filepath)) {
60
- const { content: content2 } = this.cache.get(filepath);
61
- return {
62
- content: content2
63
- };
64
- }
65
- if (!fs.existsSync(filepath)) {
66
- return null;
67
- }
68
- const stat = fs.statSync(filepath);
69
- if (stat.isDirectory()) {
70
- return null;
71
- }
72
- if (stat.size > 20 * MB) {
73
- return null;
74
- }
75
- const content = await fs.promises.readFile(filepath);
76
- const item = await createCacheItem(content, stat.mtime);
77
- this.cache.set(filepath, item);
78
- return item;
79
- }
80
- update() {
81
- const { cache, fs } = this;
82
- const files = cache.keys();
83
- for (const filepath of files) {
84
- if (!fs.existsSync(filepath)) {
85
- cache.del(filepath);
86
- }
87
- try {
88
- const item = cache.get(filepath);
89
- const stat = fs.statSync(filepath);
90
- const { mtime } = stat;
91
- if (item.mtime < mtime) {
92
- cache.del(filepath);
93
- }
94
- } catch (e) {
95
- cache.del(filepath);
96
- }
97
- }
98
- }
99
- constructor() {
100
- (0, import_define_property._)(this, "cache", void 0);
101
- (0, import_define_property._)(this, "fs", void 0);
102
- this.cache = new import_lru_cache.default({
103
- max: 256 * MB,
104
- length: getContentLength,
105
- maxAge: 5 * 60 * 5e3
106
- });
107
- this.fs = import_utils.fs;
108
- }
109
- }
110
- const reader = new LruReader();
111
- const readFile = async (filepath) => {
112
- const file = await reader.read(filepath);
113
- return file === null || file === void 0 ? void 0 : file.content;
114
- };
115
- const updateFile = () => {
116
- reader.update();
117
- };
118
- const init = (fs) => {
119
- reader.init(fs);
120
- };
121
- const close = () => {
122
- reader.close();
123
- };
124
- // Annotate the CommonJS export names for ESM import in node:
125
- 0 && (module.exports = {
126
- LruReader,
127
- close,
128
- init,
129
- readFile,
130
- updateFile
131
- });
@@ -1,124 +0,0 @@
1
- import { _ as _async_to_generator } from "@swc/helpers/_/_async_to_generator";
2
- import { _ as _sliced_to_array } from "@swc/helpers/_/_sliced_to_array";
3
- import { _ as _ts_generator } from "@swc/helpers/_/_ts_generator";
4
- import url from "url";
5
- import { createCache, destroyCache } from "../spr";
6
- import { cacheAddition, connectFactor, fname, maybeSync, namespaceHash, valueFactory, withCoalescedInvoke } from "../util";
7
- describe("test spr util functions", function() {
8
- it("should return value correctly", function() {
9
- expect(connectFactor("bar", "foo")).toBe("bar-foo");
10
- expect(fname(1)).toBe("f1");
11
- expect(namespaceHash("modern", "!@#$%^&")).toBe("modern/!@#$%^&");
12
- });
13
- it("should create or destroy instance correctly", function() {
14
- var ins1 = createCache();
15
- var ins2 = createCache();
16
- expect(ins1 === ins2).toBe(true);
17
- destroyCache();
18
- var ins3 = createCache();
19
- expect(ins1 === ins3).toBe(false);
20
- expect(ins2 === ins3).toBe(false);
21
- });
22
- it("should return function correctly", function() {
23
- var urlParams = function() {
24
- return new url.URLSearchParams();
25
- }();
26
- urlParams.set("name", "modern");
27
- var getParam = valueFactory(urlParams);
28
- expect(getParam("name")).toBe("modern");
29
- var headers = {
30
- age: "12345"
31
- };
32
- var getHeader = valueFactory(headers);
33
- expect(getHeader("age")).toBe("12345");
34
- });
35
- it("should add target html content", function() {
36
- var contentNoHead = "<div>123</div>";
37
- var html = cacheAddition(contentNoHead, Math.random().toString());
38
- expect(html).toBe(contentNoHead);
39
- var contentWithHead = "<head></head><div>123</div>";
40
- var hash = Math.random().toString();
41
- var htmlWithHead = cacheAddition(contentWithHead, hash);
42
- expect(htmlWithHead).toBe('<head><meta name="x-moden-spr" content="'.concat(hash, '"></head><div>123</div>'));
43
- });
44
- it("should only invoke func one time", /* @__PURE__ */ _async_to_generator(function() {
45
- var index, fn, key, _ref, res1, res2;
46
- return _ts_generator(this, function(_state) {
47
- switch (_state.label) {
48
- case 0:
49
- index = 0;
50
- fn = withCoalescedInvoke(/* @__PURE__ */ _async_to_generator(function() {
51
- return _ts_generator(this, function(_state2) {
52
- return [
53
- 2,
54
- new Promise(function(resolve) {
55
- setTimeout(function() {
56
- index += 1;
57
- resolve(index);
58
- }, 500);
59
- })
60
- ];
61
- });
62
- }));
63
- key = "test";
64
- return [
65
- 4,
66
- Promise.all([
67
- fn(key, []),
68
- fn(key, [])
69
- ])
70
- ];
71
- case 1:
72
- _ref = _sliced_to_array.apply(void 0, [
73
- _state.sent(),
74
- 2
75
- ]), res1 = _ref[0], res2 = _ref[1];
76
- expect(res1.isOrigin && res2.isOrigin).toBe(false);
77
- expect(res1.isOrigin || res2.isOrigin).toBe(true);
78
- expect(res1.value).toBe(1);
79
- expect(res2.value).toBe(1);
80
- return [
81
- 2
82
- ];
83
- }
84
- });
85
- }));
86
- it("should invoke sync or async", /* @__PURE__ */ _async_to_generator(function() {
87
- var foo, async, sync;
88
- return _ts_generator(this, function(_state) {
89
- switch (_state.label) {
90
- case 0:
91
- foo = "";
92
- return [
93
- 4,
94
- maybeSync(function() {
95
- return new Promise(function(resolve) {
96
- setTimeout(function() {
97
- resolve(foo);
98
- }, 100);
99
- });
100
- })(false)
101
- ];
102
- case 1:
103
- async = _state.sent();
104
- expect(async).toBeUndefined();
105
- return [
106
- 4,
107
- maybeSync(function() {
108
- return new Promise(function(resolve) {
109
- setTimeout(function() {
110
- resolve(foo);
111
- }, 100);
112
- });
113
- })(true)
114
- ];
115
- case 2:
116
- sync = _state.sent();
117
- expect(sync).toBe(foo);
118
- return [
119
- 2
120
- ];
121
- }
122
- });
123
- }));
124
- });