@modern-js/runtime 3.9.2 → 3.10.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 (39) hide show
  1. package/dist/cjs/cli/ssr/index.js +5 -0
  2. package/dist/cjs/cli/ssr/loadable-bundler-plugin.js +13 -4
  3. package/dist/cjs/core/browser/hydrate.js +2 -0
  4. package/dist/cjs/core/server/requestHandler.js +2 -0
  5. package/dist/cjs/core/server/stream/createReadableStream.js +51 -8
  6. package/dist/cjs/core/server/stream/createReadableStream.worker.js +37 -15
  7. package/dist/cjs/core/server/stream/deferredScript.js +12 -6
  8. package/dist/cjs/core/server/stream/deferredScriptOutputCoordinator.js +370 -0
  9. package/dist/cjs/router/cli/code/templates.js +2 -2
  10. package/dist/cjs/router/runtime/DeferredDataScripts.node.js +3 -1
  11. package/dist/esm/cli/ssr/index.mjs +5 -0
  12. package/dist/esm/cli/ssr/loadable-bundler-plugin.mjs +13 -4
  13. package/dist/esm/core/browser/hydrate.mjs +2 -0
  14. package/dist/esm/core/server/requestHandler.mjs +2 -0
  15. package/dist/esm/core/server/stream/createReadableStream.mjs +51 -8
  16. package/dist/esm/core/server/stream/createReadableStream.worker.mjs +37 -15
  17. package/dist/esm/core/server/stream/deferredScript.mjs +12 -6
  18. package/dist/esm/core/server/stream/deferredScriptOutputCoordinator.mjs +332 -0
  19. package/dist/esm/router/cli/code/templates.mjs +2 -2
  20. package/dist/esm/router/runtime/DeferredDataScripts.node.mjs +3 -1
  21. package/dist/esm-node/cli/ssr/index.mjs +5 -0
  22. package/dist/esm-node/cli/ssr/loadable-bundler-plugin.mjs +13 -4
  23. package/dist/esm-node/core/browser/hydrate.mjs +2 -0
  24. package/dist/esm-node/core/server/requestHandler.mjs +2 -0
  25. package/dist/esm-node/core/server/stream/createReadableStream.mjs +51 -8
  26. package/dist/esm-node/core/server/stream/createReadableStream.worker.mjs +37 -15
  27. package/dist/esm-node/core/server/stream/deferredScript.mjs +12 -6
  28. package/dist/esm-node/core/server/stream/deferredScriptOutputCoordinator.mjs +333 -0
  29. package/dist/esm-node/router/cli/code/templates.mjs +2 -2
  30. package/dist/esm-node/router/runtime/DeferredDataScripts.node.mjs +3 -1
  31. package/dist/types/core/context/index.d.ts +1 -1
  32. package/dist/types/core/index.d.ts +1 -1
  33. package/dist/types/core/server/stream/deferredScript.d.ts +1 -1
  34. package/dist/types/core/server/stream/deferredScriptOutputCoordinator.d.ts +72 -0
  35. package/dist/types/index.d.ts +1 -1
  36. package/dist/types/router/runtime/routerHelper.d.ts +5 -0
  37. package/package.json +16 -17
  38. package/{rslib.config.mts → rstack.config.mts} +2 -2
  39. package/rstest.config.mts +4 -1
@@ -0,0 +1,370 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, getters, values)=>{
5
+ var define = (defs, kind)=>{
6
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
+ enumerable: true,
8
+ [kind]: defs[key]
9
+ });
10
+ };
11
+ define(getters, "get");
12
+ define(values, "value");
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
+ })();
18
+ (()=>{
19
+ __webpack_require__.r = (exports1)=>{
20
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
+ value: 'Module'
22
+ });
23
+ Object.defineProperty(exports1, '__esModule', {
24
+ value: true
25
+ });
26
+ };
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ __webpack_require__.r(__webpack_exports__);
30
+ __webpack_require__.d(__webpack_exports__, {
31
+ DeferredScriptOutputCoordinator: ()=>DeferredScriptOutputCoordinator
32
+ });
33
+ const constants_namespaceObject = require("@modern-js/utils/universal/constants");
34
+ const VOID_ELEMENTS = new Set([
35
+ 'area',
36
+ 'base',
37
+ 'br',
38
+ 'col',
39
+ 'embed',
40
+ 'hr',
41
+ 'img',
42
+ 'input',
43
+ 'link',
44
+ 'meta',
45
+ 'param',
46
+ 'source',
47
+ 'track',
48
+ 'wbr'
49
+ ]);
50
+ const RAW_TEXT_ELEMENTS = new Set([
51
+ 'iframe',
52
+ 'noembed',
53
+ 'noframes',
54
+ "script",
55
+ 'style',
56
+ 'textarea',
57
+ 'title',
58
+ 'xmp'
59
+ ]);
60
+ const REACT_SEGMENT_ID_PATTERN = new RegExp(`^${constants_namespaceObject.SSR_HYDRATION_ID_PREFIX}S:[0-9a-f]+$`);
61
+ const TABLE_SEGMENT_CHILDREN = new Set([
62
+ 'tbody',
63
+ 'tr',
64
+ 'colgroup'
65
+ ]);
66
+ function isAsciiAlpha(char) {
67
+ return /[A-Za-z]/.test(char);
68
+ }
69
+ function isWhitespace(char) {
70
+ return /[\t\n\f\r ]/.test(char);
71
+ }
72
+ function getSuffix(value, pattern) {
73
+ const start = Math.max(0, value.length - pattern.length);
74
+ for(let index = start; index < value.length; index++){
75
+ const suffix = value.slice(index);
76
+ if (pattern.startsWith(suffix)) return suffix;
77
+ }
78
+ return '';
79
+ }
80
+ class DeferredScriptOutputCoordinator {
81
+ enqueueResolver(script) {
82
+ if (this.closed) return;
83
+ this.pendingResolvers.push(script);
84
+ this.flushResolvers();
85
+ }
86
+ markShellFinished() {
87
+ if (this.closed) return;
88
+ this.shellFinished = true;
89
+ this.flushResolvers();
90
+ }
91
+ writeReact(chunk) {
92
+ if (this.closed || !chunk) return;
93
+ this.flushResolvers();
94
+ let emittedUntil = 0;
95
+ for(let index = 0; index < chunk.length; index++){
96
+ const wasSafe = this.isSafeBoundary();
97
+ this.consume(chunk[index]);
98
+ if (!wasSafe && this.isSafeBoundary() && this.pendingResolvers.length) {
99
+ this.emit(chunk.slice(emittedUntil, index + 1));
100
+ emittedUntil = index + 1;
101
+ this.flushResolvers();
102
+ }
103
+ }
104
+ if (emittedUntil < chunk.length) this.emit(chunk.slice(emittedUntil));
105
+ }
106
+ finish() {
107
+ if (this.closed) return;
108
+ this.flushResolvers();
109
+ this.closed = true;
110
+ if (this.pendingResolvers.length > 0) throw new Error("Cannot emit deferred resolver scripts because the React stream ended outside a safe HTML boundary.");
111
+ }
112
+ abort() {
113
+ this.closed = true;
114
+ this.pendingResolvers.length = 0;
115
+ }
116
+ isSafeBoundary() {
117
+ return this.shellFinished && 'data' === this.state && 0 === this.openElements.length && !this.awaitingContinuationProtocol;
118
+ }
119
+ flushResolvers() {
120
+ if (!this.isSafeBoundary() || 0 === this.pendingResolvers.length) return;
121
+ while(this.pendingResolvers.length > 0){
122
+ const resolver = this.pendingResolvers.shift();
123
+ if (resolver) this.emit(resolver);
124
+ }
125
+ }
126
+ consume(char) {
127
+ switch(this.state){
128
+ case 'data':
129
+ if ('<' === char) this.state = 'tag-open';
130
+ return;
131
+ case 'tag-open':
132
+ if ('/' === char) {
133
+ this.currentTagName = '';
134
+ this.state = 'end-tag-name';
135
+ } else if ('!' === char) {
136
+ this.declarationPrefix = '';
137
+ this.state = 'markup-declaration';
138
+ } else if ('?' === char) this.state = 'bogus-comment';
139
+ else if (isAsciiAlpha(char)) {
140
+ this.startTag(char);
141
+ this.state = 'start-tag-name';
142
+ } else this.state = 'data';
143
+ return;
144
+ case 'start-tag-name':
145
+ if (isWhitespace(char)) this.state = 'before-attribute-name';
146
+ else if ('/' === char) this.state = 'self-closing-start-tag';
147
+ else if ('>' === char) this.completeStartTag(false);
148
+ else this.currentTagName += char.toLowerCase();
149
+ return;
150
+ case 'before-attribute-name':
151
+ if (isWhitespace(char)) return;
152
+ if ('/' === char) this.state = 'self-closing-start-tag';
153
+ else if ('>' === char) this.completeStartTag(false);
154
+ else {
155
+ this.startAttribute(char);
156
+ this.state = 'attribute-name';
157
+ }
158
+ return;
159
+ case 'attribute-name':
160
+ if (isWhitespace(char)) this.state = 'after-attribute-name';
161
+ else if ('=' === char) {
162
+ this.currentAttributeHasValue = true;
163
+ this.state = 'before-attribute-value';
164
+ } else if ('/' === char) {
165
+ this.completeAttribute();
166
+ this.state = 'self-closing-start-tag';
167
+ } else if ('>' === char) this.completeStartTag(false);
168
+ else this.currentAttributeName += char.toLowerCase();
169
+ return;
170
+ case 'after-attribute-name':
171
+ if (isWhitespace(char)) return;
172
+ if ('=' === char) {
173
+ this.currentAttributeHasValue = true;
174
+ this.state = 'before-attribute-value';
175
+ } else if ('/' === char) {
176
+ this.completeAttribute();
177
+ this.state = 'self-closing-start-tag';
178
+ } else if ('>' === char) this.completeStartTag(false);
179
+ else {
180
+ this.completeAttribute();
181
+ this.startAttribute(char);
182
+ this.state = 'attribute-name';
183
+ }
184
+ return;
185
+ case 'before-attribute-value':
186
+ if (isWhitespace(char)) return;
187
+ if ('"' === char) this.state = 'attribute-value-double-quoted';
188
+ else if ("'" === char) this.state = 'attribute-value-single-quoted';
189
+ else if ('>' === char) this.completeStartTag(false);
190
+ else {
191
+ this.currentAttributeValue += char;
192
+ this.state = 'attribute-value-unquoted';
193
+ }
194
+ return;
195
+ case 'attribute-value-double-quoted':
196
+ if ('"' === char) {
197
+ this.completeAttribute();
198
+ this.state = 'before-attribute-name';
199
+ } else this.currentAttributeValue += char;
200
+ return;
201
+ case 'attribute-value-single-quoted':
202
+ if ("'" === char) {
203
+ this.completeAttribute();
204
+ this.state = 'before-attribute-name';
205
+ } else this.currentAttributeValue += char;
206
+ return;
207
+ case 'attribute-value-unquoted':
208
+ if (isWhitespace(char)) {
209
+ this.completeAttribute();
210
+ this.state = 'before-attribute-name';
211
+ } else if ('>' === char) this.completeStartTag(false);
212
+ else this.currentAttributeValue += char;
213
+ return;
214
+ case 'self-closing-start-tag':
215
+ if ('>' === char) this.completeStartTag(true);
216
+ else if (!isWhitespace(char)) {
217
+ this.startAttribute(char);
218
+ this.state = 'attribute-name';
219
+ }
220
+ return;
221
+ case 'end-tag-name':
222
+ if (isWhitespace(char)) this.state = 'after-end-tag-name';
223
+ else if ('>' === char) this.completeEndTag();
224
+ else this.currentTagName += char.toLowerCase();
225
+ return;
226
+ case 'after-end-tag-name':
227
+ if ('>' === char) this.completeEndTag();
228
+ return;
229
+ case 'markup-declaration':
230
+ if (this.declarationPrefix.length < 2 && '-' === char) {
231
+ this.declarationPrefix += char;
232
+ if ('--' === this.declarationPrefix) {
233
+ this.commentTail = '';
234
+ this.state = 'comment';
235
+ }
236
+ } else this.state = '>' === char ? 'data' : 'declaration';
237
+ return;
238
+ case 'declaration':
239
+ if ('>' === char) this.state = 'data';
240
+ return;
241
+ case 'comment':
242
+ this.commentTail = `${this.commentTail}${char}`.slice(-3);
243
+ if ('-->' === this.commentTail) this.state = 'data';
244
+ return;
245
+ case 'bogus-comment':
246
+ if ('>' === char) this.state = 'data';
247
+ return;
248
+ case 'raw-text':
249
+ this.consumeRawText(char);
250
+ return;
251
+ case 'raw-end-tag':
252
+ if ('>' === char) this.completeRawTextEndTag();
253
+ else if (!isWhitespace(char)) {
254
+ this.state = 'raw-text';
255
+ this.rawTextSearch = getSuffix(`${this.rawTextSearch}${char.toLowerCase()}`, `</${this.rawTextElement}`);
256
+ }
257
+ }
258
+ }
259
+ startTag(char) {
260
+ this.currentTagName = char.toLowerCase();
261
+ this.currentAttributes = new Map();
262
+ this.currentAttributeName = '';
263
+ this.currentAttributeValue = '';
264
+ this.currentAttributeHasValue = false;
265
+ }
266
+ startAttribute(char) {
267
+ this.currentAttributeName = char.toLowerCase();
268
+ this.currentAttributeValue = '';
269
+ this.currentAttributeHasValue = false;
270
+ }
271
+ completeAttribute() {
272
+ if (!this.currentAttributeName) return;
273
+ this.currentAttributes.set(this.currentAttributeName, this.currentAttributeHasValue ? this.currentAttributeValue : true);
274
+ this.currentAttributeName = '';
275
+ this.currentAttributeValue = '';
276
+ this.currentAttributeHasValue = false;
277
+ }
278
+ completeStartTag(selfClosing) {
279
+ this.completeAttribute();
280
+ const tagName = this.currentTagName;
281
+ const id = this.currentAttributes.get('id');
282
+ const hasReactSegmentId = 'string' == typeof id && REACT_SEGMENT_ID_PATTERN.test(id);
283
+ const hasHiddenAttribute = this.currentAttributes.has('hidden');
284
+ const isHiddenSegmentTable = 'table' === tagName && hasHiddenAttribute && !hasReactSegmentId;
285
+ const isTableSegmentChild = hasReactSegmentId && TABLE_SEGMENT_CHILDREN.has(tagName) && this.openElements[this.openElements.length - 1]?.isSegmentTableWrapper === true;
286
+ const isContinuationContainer = hasReactSegmentId && ('div' === tagName && hasHiddenAttribute || ('svg' === tagName || 'math' === tagName) && void 0 !== id && 'true' === this.currentAttributes.get('aria-hidden') && 'display:none' === this.currentAttributes.get('style') || 'table' === tagName && hasHiddenAttribute || isTableSegmentChild);
287
+ this.continuationProtocolScript = "script" === tagName && this.awaitingContinuationProtocol;
288
+ this.continuationProtocolTail = '';
289
+ this.hasContinuationProtocolCall = false;
290
+ if (!selfClosing && !VOID_ELEMENTS.has(tagName)) this.openElements.push({
291
+ tagName,
292
+ isContinuationContainer,
293
+ isSegmentTableWrapper: isHiddenSegmentTable
294
+ });
295
+ this.currentTagName = '';
296
+ this.currentAttributes = new Map();
297
+ this.currentAttributeName = '';
298
+ this.currentAttributeValue = '';
299
+ this.currentAttributeHasValue = false;
300
+ if (!selfClosing && RAW_TEXT_ELEMENTS.has(tagName)) {
301
+ this.rawTextElement = tagName;
302
+ this.rawTextSearch = '';
303
+ this.state = 'raw-text';
304
+ } else this.state = 'data';
305
+ }
306
+ completeEndTag() {
307
+ this.closeOpenElement(this.currentTagName);
308
+ this.currentTagName = '';
309
+ this.state = 'data';
310
+ }
311
+ consumeRawText(char) {
312
+ const rawTextElement = this.rawTextElement;
313
+ if (!rawTextElement) {
314
+ this.state = 'data';
315
+ return;
316
+ }
317
+ const endTagPrefix = `</${rawTextElement}`;
318
+ if (this.continuationProtocolScript) {
319
+ this.continuationProtocolTail = `${this.continuationProtocolTail}${char}`.slice(-4);
320
+ if (/\$(?:RC|RS|RX|RB|RR)\b/.test(this.continuationProtocolTail)) this.hasContinuationProtocolCall = true;
321
+ }
322
+ this.rawTextSearch = getSuffix(`${this.rawTextSearch}${char.toLowerCase()}`, endTagPrefix);
323
+ if (this.rawTextSearch === endTagPrefix) this.state = 'raw-end-tag';
324
+ }
325
+ completeRawTextEndTag() {
326
+ const rawTextElement = this.rawTextElement;
327
+ if (rawTextElement) this.closeOpenElement(rawTextElement);
328
+ if ("script" === rawTextElement && this.continuationProtocolScript && this.hasContinuationProtocolCall) this.awaitingContinuationProtocol = false;
329
+ this.rawTextElement = void 0;
330
+ this.rawTextSearch = '';
331
+ this.continuationProtocolScript = false;
332
+ this.continuationProtocolTail = '';
333
+ this.hasContinuationProtocolCall = false;
334
+ this.state = 'data';
335
+ }
336
+ closeOpenElement(tagName) {
337
+ const matchingIndex = this.openElements.map((element)=>element.tagName).lastIndexOf(tagName);
338
+ if (-1 === matchingIndex) return;
339
+ const closedElements = this.openElements.splice(matchingIndex);
340
+ const closedContinuation = closedElements.some((element)=>element.isContinuationContainer);
341
+ if (closedContinuation) this.awaitingContinuationProtocol = true;
342
+ }
343
+ constructor(emit){
344
+ this.emit = emit;
345
+ this.pendingResolvers = [];
346
+ this.openElements = [];
347
+ this.shellFinished = false;
348
+ this.closed = false;
349
+ this.state = 'data';
350
+ this.currentTagName = '';
351
+ this.currentAttributes = new Map();
352
+ this.currentAttributeName = '';
353
+ this.currentAttributeValue = '';
354
+ this.currentAttributeHasValue = false;
355
+ this.declarationPrefix = '';
356
+ this.commentTail = '';
357
+ this.rawTextSearch = '';
358
+ this.continuationProtocolScript = false;
359
+ this.continuationProtocolTail = '';
360
+ this.hasContinuationProtocolCall = false;
361
+ this.awaitingContinuationProtocol = false;
362
+ }
363
+ }
364
+ exports.DeferredScriptOutputCoordinator = __webpack_exports__.DeferredScriptOutputCoordinator;
365
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
366
+ "DeferredScriptOutputCoordinator"
367
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
368
+ Object.defineProperty(exports, '__esModule', {
369
+ value: true
370
+ });
@@ -157,7 +157,7 @@ const fileSystemRoutes = async ({ metaName, routes, ssrMode, nestedRoutesEntry,
157
157
  };
158
158
  const createLazyImport = ({ componentPath, routeId, webpackChunkName, eager })=>{
159
159
  const importOptions = webpackChunkName ? `/* webpackChunkName: "${routeId}" */ ` : eager ? '/* webpackMode: "eager" */ ' : '';
160
- return `() => import(${importOptions}'${componentPath}').then(routeModule => handleRouteModule(routeModule, "${routeId}")).catch(handleRouteModuleError)`;
160
+ return `() => import(${importOptions}'${componentPath}').then(routeModule => handleRouteModule(routeModule, "${routeId}"))`;
161
161
  };
162
162
  const traverseRouteTree = async (route, isRscClientBundle)=>{
163
163
  let children;
@@ -326,7 +326,7 @@ const fileSystemRoutes = async ({ metaName, routes, ssrMode, nestedRoutesEntry,
326
326
  await utils_namespaceObject.fs.ensureFile(loadersMapFile);
327
327
  await utils_namespaceObject.fs.writeJSON(loadersMapFile, loadersMap);
328
328
  const importRuntimeRouterCode = `
329
- import { createShouldRevalidate, handleRouteModule, handleRouteModuleError} from '@${metaName}/runtime/routerHelper';
329
+ import { createShouldRevalidate, handleRouteModule } from '@${metaName}/runtime/routerHelper';
330
330
  `;
331
331
  const routeModulesCode = `
332
332
  if(typeof document !== 'undefined'){
@@ -45,7 +45,8 @@ const DeferredDataScripts = (props)=>{
45
45
  }, []);
46
46
  const deferredScripts = (0, external_react_namespaceObject.useMemo)(()=>{
47
47
  if (!staticContext) return null;
48
- const activeDeferreds = node_namespaceObject.storage.useContext().activeDeferreds;
48
+ const requestStorage = node_namespaceObject.storage.useContext();
49
+ const activeDeferreds = requestStorage.activeDeferreds;
49
50
  const _ROUTER_DATA = {
50
51
  loaderData: staticContext.loaderData,
51
52
  errors: (0, external_utils_js_namespaceObject.serializeErrors)(staticContext.errors)
@@ -58,6 +59,7 @@ const DeferredDataScripts = (props)=>{
58
59
  const deferredDataScripts = [];
59
60
  const initialScripts = Array.from(activeDeferreds.entries()).map(([routeId, deferredData])=>{
60
61
  const pendingKeys = new Set(deferredData.pendingKeys);
62
+ requestStorage.deferredScriptKeys?.set(routeId, Array.from(pendingKeys));
61
63
  const { deferredKeys } = deferredData;
62
64
  const deferredKeyPromiseManifests = deferredKeys.map((key)=>{
63
65
  if (pendingKeys.has(key)) return {
@@ -41,6 +41,11 @@ const ssrBuilderPlugin = (modernAPI, outputModule, exportLoadablePath)=>({
41
41
  module: isServerEnvironment && outputModule
42
42
  },
43
43
  tools: {
44
+ rspack: isServerEnvironment && isUseSSRBundle(userConfig) ? {
45
+ output: {
46
+ strictModuleErrorHandling: true
47
+ }
48
+ } : void 0,
44
49
  bundlerChain: useLoadablePlugin ? (chain)=>{
45
50
  chain.plugin('loadable').use(loadable_bundler_plugin, [
46
51
  {
@@ -1,5 +1,6 @@
1
1
  import path_0 from "path";
2
2
  import { fs } from "@modern-js/utils";
3
+ const DEFAULT_CHUNK_LOADING_GLOBAL = '__LOADABLE_LOADED_CHUNKS__';
3
4
  const normalizeChunkId = (id)=>'string' == typeof id && /^\d+$/.test(id) ? Number(id) : id;
4
5
  const normalizeChunkGroup = (group)=>({
5
6
  ...group,
@@ -8,7 +9,16 @@ const normalizeChunkGroup = (group)=>({
8
9
  class LoadablePlugin {
9
10
  apply(compiler) {
10
11
  this.compiler = compiler;
11
- compiler.options.output.chunkLoadingGlobal = this.opts.chunkLoadingGlobal;
12
+ if (this.opts.chunkLoadingGlobal) compiler.options.output.chunkLoadingGlobal = this.opts.chunkLoadingGlobal;
13
+ compiler.hooks.initialize.tap({
14
+ name: LoadablePlugin.name,
15
+ stage: 1 / 0
16
+ }, ()=>{
17
+ const chunkLoadingGlobal = compiler.options.output.chunkLoadingGlobal || DEFAULT_CHUNK_LOADING_GLOBAL;
18
+ new compiler.webpack.DefinePlugin({
19
+ 'process.env.MODERN_CHUNK_LOADING_GLOBAL': JSON.stringify(chunkLoadingGlobal)
20
+ }).apply(compiler);
21
+ });
12
22
  if (this.opts.outputAsset || this.opts.writeToDisk) compiler.hooks.make.tap(LoadablePlugin.name, (compilation)=>{
13
23
  compilation.hooks.processAssets.tap({
14
24
  name: LoadablePlugin.name,
@@ -68,10 +78,9 @@ class LoadablePlugin {
68
78
  const outputFile = path_0.resolve(outputFolder || '', this.opts.filename);
69
79
  fs.outputFileSync(outputFile, manifest);
70
80
  }
71
- constructor({ filename = 'loadable-stats.json', path, writeToDisk, outputAsset = true, chunkLoadingGlobal = '__LOADABLE_LOADED_CHUNKS__' } = {
81
+ constructor({ filename = 'loadable-stats.json', path, writeToDisk, outputAsset = true, chunkLoadingGlobal } = {
72
82
  filename: 'loadable-stats.json',
73
- outputAsset: true,
74
- chunkLoadingGlobal: '__LOADABLE_LOADED_CHUNKS__'
83
+ outputAsset: true
75
84
  }){
76
85
  this.opts = {
77
86
  filename,
@@ -47,6 +47,8 @@ function hydrate_hydrateRoot(App, context, ModernRender, ModernHydrate) {
47
47
  ModernHydrate(wrapRuntimeContextProvider(/*#__PURE__*/ jsx(SSRApp, {}), hydrateContext)).then((root)=>{
48
48
  resolve(root);
49
49
  });
50
+ }, {
51
+ chunkLoadingGlobal: process.env.MODERN_CHUNK_LOADING_GLOBAL
50
52
  });
51
53
  });
52
54
  console.warn(`unknow render level: ${renderLevel}, execute render()`);
@@ -101,12 +101,14 @@ const createRequestHandler = async (handleRequest, createRequestOptions)=>{
101
101
  status: -1
102
102
  };
103
103
  const activeDeferreds = new Map();
104
+ const deferredScriptKeys = new Map();
104
105
  return storage.run({
105
106
  headers: headersData,
106
107
  request,
107
108
  monitors: options.monitors,
108
109
  responseProxy,
109
110
  activeDeferreds,
111
+ deferredScriptKeys,
110
112
  serverPayload: void 0
111
113
  }, async ()=>{
112
114
  const Root = createRoot();
@@ -1,4 +1,5 @@
1
1
  import { PassThrough, Readable, Transform } from "stream";
2
+ import { StringDecoder } from "string_decoder";
2
3
  import { storage } from "@modern-js/runtime-utils/node";
3
4
  import { SSR_HYDRATION_ID_PREFIX } from "@modern-js/utils/universal/constants";
4
5
  import { ESCAPED_SHELL_STREAM_END_MARK } from "../../../common.mjs";
@@ -6,6 +7,7 @@ import { RenderLevel } from "../../constants.mjs";
6
7
  import { getGlobalInternalRuntimeContext } from "../../context/index.mjs";
7
8
  import { getMonitors } from "../../context/monitors/index.mjs";
8
9
  import { enqueueFromEntries } from "./deferredScript.mjs";
10
+ import { DeferredScriptOutputCoordinator } from "./deferredScriptOutputCoordinator.mjs";
9
11
  import { ShellChunkStatus, getReadableStreamFromString, resolveStreamingMode } from "./shared.mjs";
10
12
  import { getTemplates } from "./template.mjs";
11
13
  const defaultExtender = {
@@ -54,7 +56,14 @@ const createReadableStreamFromElement = async (request, rootElement, options)=>{
54
56
  entryName,
55
57
  styledComponentsStyleTags
56
58
  }).then(({ shellAfter, shellBefore })=>{
59
+ const decoder = new StringDecoder('utf8');
57
60
  const pendingScripts = [];
61
+ const outputState = {};
62
+ let deferredResolversComplete = Promise.resolve();
63
+ const writeReact = (content)=>{
64
+ if (!outputState.coordinator) throw new Error("Deferred script coordinator is not ready");
65
+ outputState.coordinator.writeReact(content);
66
+ };
58
67
  const body = new Transform({
59
68
  transform (chunk, _encoding, callback) {
60
69
  try {
@@ -66,17 +75,49 @@ const createReadableStreamFromElement = async (request, rootElement, options)=>{
66
75
  const beforeMark = concatedChunk.slice(0, markerIndex);
67
76
  const afterMark = concatedChunk.slice(markerIndex + ESCAPED_SHELL_STREAM_END_MARK.length);
68
77
  shellChunkStatus = ShellChunkStatus.FINISH;
69
- this.push(`${shellBefore}${beforeMark}${shellAfter}`);
70
- if (afterMark) this.push(afterMark);
71
- if (pendingScripts.length > 0) for (const s of pendingScripts)this.push(s);
78
+ writeReact(`${shellBefore}${beforeMark}${shellAfter}`);
79
+ if (afterMark) writeReact(afterMark);
80
+ if (outputState.coordinator) {
81
+ outputState.coordinator.markShellFinished();
82
+ for (const script of pendingScripts)outputState.coordinator.enqueueResolver(script);
83
+ pendingScripts.length = 0;
84
+ }
72
85
  }
73
- } else this.push(chunk);
86
+ } else {
87
+ const decodedChunk = decoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
88
+ writeReact(decodedChunk);
89
+ }
74
90
  callback();
75
91
  } catch (e) {
76
92
  e instanceof Error ? callback(e) : callback(new Error('Received unknown error when streaming'));
77
93
  }
94
+ },
95
+ flush (callback) {
96
+ try {
97
+ writeReact(decoder.end());
98
+ } catch (error) {
99
+ callback(error instanceof Error ? error : new Error('Received unknown error when streaming'));
100
+ return;
101
+ }
102
+ deferredResolversComplete.then(()=>{
103
+ try {
104
+ outputState.coordinator?.finish();
105
+ callback();
106
+ } catch (error) {
107
+ callback(error instanceof Error ? error : new Error('Received unknown error when streaming'));
108
+ }
109
+ }, (error)=>{
110
+ callback(error instanceof Error ? error : new Error('Received unknown error when streaming'));
111
+ });
78
112
  }
79
113
  });
114
+ const coordinator = new DeferredScriptOutputCoordinator((content)=>{
115
+ body.push(content);
116
+ });
117
+ outputState.coordinator = coordinator;
118
+ body.once('close', ()=>{
119
+ coordinator.abort();
120
+ });
80
121
  const passThrough = new PassThrough();
81
122
  const stream = Readable.toWeb(body);
82
123
  resolve(stream);
@@ -84,23 +125,25 @@ const createReadableStreamFromElement = async (request, rootElement, options)=>{
84
125
  extenders.forEach((extender)=>{
85
126
  if (extender.processStream) processedStream = extender.processStream(processedStream);
86
127
  });
87
- reactStreamingPipe(passThrough);
88
- processedStream.pipe(body);
89
128
  try {
90
129
  const storageContext = storage.useContext?.();
91
130
  const activeDeferreds = storageContext?.activeDeferreds;
131
+ const deferredScriptKeys = storageContext?.deferredScriptKeys;
92
132
  const entries = activeDeferreds instanceof Map ? Array.from(activeDeferreds.entries()) : [];
93
133
  if (entries.length > 0) {
94
134
  const enqueueScript = (s)=>{
95
- if (shellChunkStatus === ShellChunkStatus.FINISH) body.write(s);
135
+ if (!outputState.coordinator) throw new Error("Deferred script coordinator is not ready");
136
+ if (shellChunkStatus === ShellChunkStatus.FINISH) outputState.coordinator.enqueueResolver(s);
96
137
  else pendingScripts.push(s);
97
138
  };
98
- enqueueFromEntries(entries, config.nonce, (s)=>enqueueScript(s));
139
+ deferredResolversComplete = enqueueFromEntries(entries, deferredScriptKeys, config.nonce, enqueueScript);
99
140
  }
100
141
  } catch (err) {
101
142
  const monitors = getMonitors();
102
143
  monitors.error("cannot inject router data script", err);
103
144
  }
145
+ reactStreamingPipe(passThrough);
146
+ processedStream.pipe(body);
104
147
  });
105
148
  },
106
149
  onShellError (error) {