@qwik.dev/core 2.0.0-beta.4 → 2.0.0-beta.40

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 (151) hide show
  1. package/dist/backpatch/index.d.ts +2 -0
  2. package/dist/backpatch/index.mjs +5 -0
  3. package/dist/backpatch/package.json +8 -0
  4. package/dist/backpatch-executor.debug.js +59 -0
  5. package/dist/backpatch-executor.js +1 -0
  6. package/dist/build/package.json +1 -1
  7. package/dist/cli.mjs +12974 -0
  8. package/dist/core-internal.d.ts +1615 -810
  9. package/dist/core.min.mjs +9 -1
  10. package/dist/core.mjs +14792 -9192
  11. package/dist/core.mjs.map +1 -1
  12. package/dist/core.prod.mjs +10482 -5382
  13. package/dist/insights/index.qwik.mjs +82 -71
  14. package/dist/insights/vite/index.mjs +79 -81
  15. package/dist/loader/index.mjs +2 -2
  16. package/dist/loader/package.json +1 -1
  17. package/dist/optimizer.d.ts +77 -288
  18. package/dist/optimizer.mjs +2966 -4088
  19. package/dist/out-of-order-executor.debug.js +140 -0
  20. package/dist/out-of-order-executor.js +1 -0
  21. package/dist/preloader.mjs +172 -192
  22. package/dist/qwikloader.debug.js +403 -244
  23. package/dist/qwikloader.js +1 -1
  24. package/dist/server-modules.d.ts +1 -0
  25. package/dist/server.d.ts +54 -249
  26. package/dist/server.mjs +2332 -1407
  27. package/dist/server.prod.mjs +3844 -0
  28. package/dist/starters/adapters/aws-lambda/adapters/aws-lambda/{vite.config.mts → vite.config.ts} +3 -3
  29. package/dist/starters/adapters/aws-lambda/package.json +3 -2
  30. package/dist/starters/adapters/aws-lambda/src/entry_aws-lambda.tsx +2 -6
  31. package/dist/starters/adapters/azure-swa/adapters/azure-swa/{vite.config.mts → vite.config.ts} +3 -3
  32. package/dist/starters/adapters/azure-swa/package.json +3 -2
  33. package/dist/starters/adapters/azure-swa/src/entry.azure-swa.tsx +2 -3
  34. package/dist/starters/adapters/bun/adapters/bun/{vite.config.mts → vite.config.ts} +4 -4
  35. package/dist/starters/adapters/bun/package.json +3 -2
  36. package/dist/starters/adapters/bun/src/entry.bun.ts +37 -10
  37. package/dist/starters/adapters/cloud-run/adapters/cloud-run/{vite.config.mts → vite.config.ts} +3 -3
  38. package/dist/starters/adapters/cloud-run/package.json +3 -2
  39. package/dist/starters/adapters/cloud-run/src/entry.cloud-run.tsx +23 -7
  40. package/dist/starters/adapters/cloudflare-pages/adapters/cloudflare-pages/{vite.config.mts → vite.config.ts} +3 -3
  41. package/dist/starters/adapters/cloudflare-pages/package.json +3 -2
  42. package/dist/starters/adapters/cloudflare-pages/src/entry.cloudflare-pages.tsx +2 -3
  43. package/dist/starters/adapters/cloudflare-workers/README.md +52 -0
  44. package/dist/starters/adapters/cloudflare-workers/adapters/cloudflare-workers/vite.config.ts +15 -0
  45. package/dist/starters/adapters/cloudflare-workers/gitignore +3 -0
  46. package/dist/starters/adapters/cloudflare-workers/package.json +31 -0
  47. package/dist/starters/adapters/cloudflare-workers/public/.assetsignore +4 -0
  48. package/dist/starters/adapters/cloudflare-workers/public/_headers +11 -0
  49. package/dist/starters/adapters/cloudflare-workers/public/_redirects +1 -0
  50. package/dist/starters/adapters/cloudflare-workers/src/entry.cloudflare-pages.tsx +23 -0
  51. package/dist/starters/adapters/cloudflare-workers/worker-configuration.d.ts +5 -0
  52. package/dist/starters/adapters/cloudflare-workers/wrangler.jsonc +41 -0
  53. package/dist/starters/adapters/deno/adapters/deno/{vite.config.mts → vite.config.ts} +3 -3
  54. package/dist/starters/adapters/deno/package.json +3 -2
  55. package/dist/starters/adapters/deno/src/entry.deno.ts +43 -10
  56. package/dist/starters/adapters/express/adapters/express/{vite.config.mts → vite.config.ts} +3 -3
  57. package/dist/starters/adapters/express/package.json +4 -3
  58. package/dist/starters/adapters/express/src/entry.express.tsx +22 -7
  59. package/dist/starters/adapters/fastify/adapters/fastify/{vite.config.mts → vite.config.ts} +3 -3
  60. package/dist/starters/adapters/fastify/package.json +5 -4
  61. package/dist/starters/adapters/fastify/src/entry.fastify.tsx +21 -1
  62. package/dist/starters/adapters/fastify/src/plugins/fastify-qwik.ts +11 -4
  63. package/dist/starters/adapters/firebase/adapters/firebase/{vite.config.mts → vite.config.ts} +3 -3
  64. package/dist/starters/adapters/firebase/package.json +3 -2
  65. package/dist/starters/adapters/firebase/src/entry-firebase.tsx +2 -3
  66. package/dist/starters/adapters/netlify-edge/adapters/netlify-edge/{vite.config.mts → vite.config.ts} +3 -3
  67. package/dist/starters/adapters/netlify-edge/package.json +5 -4
  68. package/dist/starters/adapters/netlify-edge/src/entry.netlify-edge.tsx +2 -3
  69. package/dist/starters/adapters/node-server/adapters/node-server/{vite.config.mts → vite.config.ts} +3 -3
  70. package/dist/starters/adapters/node-server/package.json +3 -2
  71. package/dist/starters/adapters/node-server/src/entry.node-server.tsx +22 -6
  72. package/dist/starters/adapters/{static/adapters/static/vite.config.mts → ssg/adapters/ssg/vite.config.ts} +4 -4
  73. package/dist/starters/adapters/ssg/package.json +20 -0
  74. package/dist/starters/adapters/vercel-edge/README.md +2 -2
  75. package/dist/starters/adapters/vercel-edge/adapters/vercel-edge/{vite.config.mts → vite.config.ts} +3 -3
  76. package/dist/starters/adapters/vercel-edge/package.json +3 -2
  77. package/dist/starters/adapters/vercel-edge/src/entry.vercel-edge.tsx +2 -3
  78. package/dist/starters/adapters/vercel-edge/vercel.json +1 -1
  79. package/dist/starters/features/auth/package.json +1 -1
  80. package/dist/starters/features/compiled-i18n/package.json +37 -0
  81. package/dist/starters/features/compiled-i18n/src/components/locale-selector/locale-selector.tsx +30 -0
  82. package/dist/starters/features/compiled-i18n/src/entry.ssr.tsx +31 -0
  83. package/dist/starters/features/compiled-i18n/src/routes/plugin@compiled-i18n.ts +28 -0
  84. package/dist/starters/features/csr/index.html +27 -0
  85. package/dist/starters/features/csr/package.json +29 -0
  86. package/dist/starters/features/csr/src/root.tsx +15 -0
  87. package/dist/starters/features/csr/vite.config.ts +13 -0
  88. package/dist/starters/features/cypress/src/actions/example.action.ts +5 -0
  89. package/dist/starters/features/cypress/src/components/example/example.cy.tsx +50 -8
  90. package/dist/starters/features/cypress/src/components/example/example.tsx +13 -3
  91. package/dist/starters/features/cypress/src/loaders/example.loader.ts +5 -0
  92. package/dist/starters/features/drizzle/package.json +1 -1
  93. package/dist/starters/features/pandacss/package.json +1 -1
  94. package/dist/starters/features/postcss/postcss.config.js +1 -1
  95. package/dist/starters/features/storybook/.storybook/tsconfig.json +0 -1
  96. package/dist/starters/features/styled-vanilla-extract/package.json +2 -1
  97. package/dist/starters/features/tailwind/package.json +2 -2
  98. package/dist/starters/features/tailwind/prettier.config.js +10 -0
  99. package/dist/starters/features/tailwind-v3/package.json +1 -1
  100. package/dist/starters/features/tailwind-v3/prettier.config.js +10 -0
  101. package/dist/starters/features/vitest/package.json +1 -1
  102. package/dist/testing/index.d.ts +1000 -7
  103. package/dist/testing/index.mjs +16487 -11656
  104. package/dist/testing/package.json +1 -1
  105. package/dist/worker/index.d.mts +21 -0
  106. package/dist/worker/index.mjs +251 -0
  107. package/dist/worker/package.json +9 -0
  108. package/dist/worker/worker.js +13 -0
  109. package/dist/worker/worker.node.js +15 -0
  110. package/dist/worker/worker.shared.js +63 -0
  111. package/handlers.mjs +21 -1
  112. package/package.json +40 -56
  113. package/public.d.ts +14 -2
  114. package/{qwik-cli.cjs → qwik-cli.mjs} +1 -1
  115. package/server.d.ts +2 -0
  116. package/worker.d.ts +2 -0
  117. package/bindings/qwik.darwin-arm64.node +0 -0
  118. package/bindings/qwik.darwin-x64.node +0 -0
  119. package/bindings/qwik.linux-x64-gnu.node +0 -0
  120. package/bindings/qwik.wasm.cjs +0 -471
  121. package/bindings/qwik.wasm.mjs +0 -464
  122. package/bindings/qwik.win32-x64-msvc.node +0 -0
  123. package/bindings/qwik_wasm_bg.wasm +0 -0
  124. package/dist/build/index.cjs +0 -35
  125. package/dist/build/index.cjs.map +0 -7
  126. package/dist/build/index.dev.cjs +0 -37
  127. package/dist/build/index.dev.cjs.map +0 -7
  128. package/dist/build/index.prod.cjs +0 -37
  129. package/dist/build/index.prod.cjs.map +0 -7
  130. package/dist/cli.cjs +0 -5545
  131. package/dist/core.cjs +0 -11870
  132. package/dist/core.cjs.map +0 -1
  133. package/dist/core.prod.cjs +0 -5723
  134. package/dist/insights/index.qwik.cjs +0 -1
  135. package/dist/insights/vite/index.cjs +0 -1
  136. package/dist/loader/index.cjs +0 -4
  137. package/dist/optimizer.cjs +0 -4020
  138. package/dist/preloader.cjs +0 -269
  139. package/dist/server.cjs +0 -3040
  140. package/dist/starters/adapters/static/package.json +0 -19
  141. package/dist/starters/features/localize/package.json +0 -37
  142. package/dist/starters/features/localize/src/entry.ssr.tsx +0 -30
  143. package/dist/starters/features/localize/src/locales/message.en.json +0 -8
  144. package/dist/starters/features/localize/src/locales/message.it.json +0 -8
  145. package/dist/starters/features/localize/src/routes/[locale]/i18n-utils.ts +0 -94
  146. package/dist/starters/features/localize/src/routes/[locale]/index.tsx +0 -52
  147. package/dist/starters/features/localize/src/routes/[locale]/layout.tsx +0 -12
  148. package/dist/starters/features/playwright/playwright-report/index.html +0 -22026
  149. package/dist/starters/features/tailwind/.prettierrc.js +0 -3
  150. package/dist/testing/index.cjs +0 -33388
  151. /package/dist/starters/adapters/{static → ssg}/README.md +0 -0
package/dist/server.mjs CHANGED
@@ -1,30 +1,27 @@
1
1
  /**
2
2
  * @license
3
- * @qwik.dev/core/server 2.0.0-beta.4-dev+9849dcf
3
+ * @qwik.dev/core/server 2.0.0-beta.40-dev+a459d55
4
4
  * Copyright QwikDev. All Rights Reserved.
5
5
  * Use of this source code is governed by an MIT-style license that can be
6
6
  * found in the LICENSE file at https://github.com/QwikDev/qwik/blob/main/LICENSE
7
7
  */
8
- var __defProp = Object.defineProperty;
9
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
11
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
12
- }) : x)(function(x) {
13
- if (typeof require !== "undefined") return require.apply(this, arguments);
14
- throw Error('Dynamic require of "' + x + '" is not supported');
15
- });
16
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
17
8
 
18
9
  // packages/qwik/src/server/index.ts
19
10
  import { setPlatform as setPlatform2 } from "@qwik.dev/core";
20
11
 
21
12
  // packages/qwik/src/server/platform.ts
22
13
  import { setPlatform } from "@qwik.dev/core";
14
+ import { isDev as isDev6 } from "@qwik.dev/core/build";
15
+
16
+ // packages/qwik/src/core/client/util-mapArray.ts
17
+ import { isDev as isDev2 } from "@qwik.dev/core/build";
18
+
19
+ // packages/qwik/src/core/shared/error/assert.ts
20
+ import { isDev } from "@qwik.dev/core/build";
23
21
 
24
22
  // packages/qwik/src/core/shared/utils/qdev.ts
25
23
  var qDev = globalThis.qDev !== false;
26
24
  var qInspector = globalThis.qInspector === true;
27
- var qSerialize = globalThis.qSerialize !== false;
28
25
  var qDynamicPlatform = globalThis.qDynamicPlatform !== false;
29
26
  var qTest = globalThis.qTest === true;
30
27
  var qRuntimeQrl = globalThis.qRuntimeQrl === true;
@@ -53,7 +50,7 @@ var createAndLogError = (asyncThrow, message, ...optionalParams) => {
53
50
  // packages/qwik/src/core/shared/error/assert.ts
54
51
  var ASSERT_DISCLAIMER = "Internal assert, this is likely caused by a bug in Qwik: ";
55
52
  function assertTrue(value1, text, ...parts) {
56
- if (qDev) {
53
+ if (isDev) {
57
54
  if (value1 === true) {
58
55
  return;
59
56
  }
@@ -63,7 +60,7 @@ function assertTrue(value1, text, ...parts) {
63
60
 
64
61
  // packages/qwik/src/core/client/util-mapArray.ts
65
62
  var mapApp_findIndx = (array, key, start) => {
66
- assertTrue(start % 2 === 0, "Expecting even number.");
63
+ isDev2 && assertTrue(start % 2 === 0, "Expecting even number.");
67
64
  let bottom = start >> 1;
68
65
  let top = array.length - 2 >> 1;
69
66
  while (bottom <= top) {
@@ -80,15 +77,15 @@ var mapApp_findIndx = (array, key, start) => {
80
77
  }
81
78
  return bottom << 1 ^ -1;
82
79
  };
83
- var mapArray_set = (array, key, value, start) => {
80
+ var mapArray_set = (array, key, value, start, allowNullValue = false) => {
84
81
  const indx = mapApp_findIndx(array, key, start);
85
82
  if (indx >= 0) {
86
- if (value == null) {
83
+ if (value == null && !allowNullValue) {
87
84
  array.splice(indx, 2);
88
85
  } else {
89
86
  array[indx + 1] = value;
90
87
  }
91
- } else if (value != null) {
88
+ } else if (value != null || allowNullValue) {
92
89
  array.splice(indx ^ -1, 0, key, value);
93
90
  }
94
91
  };
@@ -114,6 +111,9 @@ var mapArray_has = (array, key, start) => {
114
111
  return mapApp_findIndx(array, key, start) >= 0;
115
112
  };
116
113
 
114
+ // packages/qwik/src/core/shared/error/error.ts
115
+ import { isDev as isDev3 } from "@qwik.dev/core/build";
116
+
117
117
  // packages/qwik/src/core/shared/utils/types.ts
118
118
  var isObject = (v) => {
119
119
  return typeof v === "object" && v !== null;
@@ -126,8 +126,9 @@ var isString = (v) => {
126
126
  };
127
127
 
128
128
  // packages/qwik/src/core/shared/error/error.ts
129
+ var baseUrl = "https://qwikdev-build-v2.qwik-8nx.pages.dev/docs/errors/#q";
129
130
  var codeToText = (code, ...parts) => {
130
- if (qDev) {
131
+ if (isDev3) {
131
132
  const MAP = [
132
133
  "Error while serializing class or style attributes",
133
134
  // 0
@@ -141,7 +142,7 @@ var codeToText = (code, ...parts) => {
141
142
  // 4
142
143
  "QRL is not a function",
143
144
  // 5
144
- "Dynamic import not found",
145
+ "Dynamic import {{0}} not found",
145
146
  // 6
146
147
  "Unknown type argument",
147
148
  // 7
@@ -150,7 +151,7 @@ var codeToText = (code, ...parts) => {
150
151
  "Invoking 'use*()' method outside of invocation context.",
151
152
  // 9
152
153
  `Calling a 'use*()' method outside 'component$(() => { HERE })' is not allowed. 'use*()' methods provide hooks to the 'component$' state and lifecycle, ie 'use' hooks can only be called synchronously within the 'component$' function or another 'use' method.
153
- See https://qwik.dev/docs/components/tasks/#use-method-rules`,
154
+ See https://qwik.dev/docs/core/tasks/#use-method-rules`,
154
155
  // 10
155
156
  'The provided Context reference "{{0}}" is not a valid context created by createContextId()',
156
157
  // 11
@@ -188,18 +189,31 @@ See https://qwik.dev/docs/components/tasks/#use-method-rules`,
188
189
  // 27
189
190
  "Cannot coerce a Signal, use `.value` instead",
190
191
  // 28
191
- "useComputed$ QRL {{0}} {{1}} cannot return a Promise",
192
- // 29
193
- "ComputedSignal is read-only",
192
+ "",
193
+ // 29 (cleared: useComputed$ now supports async functions)
194
+ `===
195
+ Qwik version {{0}} already imported while importing {{1}}.
196
+ This can lead to issues due to duplicated shared structures.
197
+ Verify that the Qwik libraries you're using are in "resolve.noExternal[]" and in "optimizeDeps.exclude".
198
+ ===
199
+ `,
194
200
  // 30
195
201
  "WrappedSignal is read-only",
196
202
  // 31
197
- "Attribute value is unsafe for SSR",
203
+ "Attribute value is unsafe for SSR {{0}}",
198
204
  // 32
199
205
  "SerializerSymbol function returned rejected promise",
200
206
  // 33
201
- "Serialization Error: Cannot serialize function: {{0}}"
207
+ "Serialization Error: Cannot serialize function: {{0}}",
202
208
  // 34
209
+ "Cannot read .value of a clientOnly async signal during SSR. Use .loading to check state, or provide an initial value.",
210
+ // 35
211
+ "Invalid element name for SSR {{0}}",
212
+ // 36
213
+ "Invalid serialized Promise dependency",
214
+ // 37
215
+ "Invalid serialized Uint8Array payload"
216
+ // 38
203
217
  ];
204
218
  let text = MAP[code] ?? "";
205
219
  if (parts.length) {
@@ -213,7 +227,7 @@ See https://qwik.dev/docs/components/tasks/#use-method-rules`,
213
227
  }
214
228
  return `Code(Q${code}): ${text}`;
215
229
  } else {
216
- return `Code(Q${code}) https://github.com/QwikDev/qwik/blob/main/packages/qwik/src/core/error/error.ts#L${8 + code}`;
230
+ return `Code(Q${code}) ${baseUrl}${code}`;
217
231
  }
218
232
  };
219
233
  var qError = (code, errorMessageArgs = []) => {
@@ -222,247 +236,12 @@ var qError = (code, errorMessageArgs = []) => {
222
236
  };
223
237
 
224
238
  // packages/qwik/src/core/shared/qrl/qrl-utils.ts
225
- import { isDev } from "@qwik.dev/core/build";
239
+ import { isDev as isDev4 } from "@qwik.dev/core/build";
226
240
  var SYNC_QRL = "<sync>";
227
241
 
228
242
  // packages/qwik/src/core/shared/types.ts
229
243
  var DEBUG_TYPE = "q:type";
230
244
 
231
- // packages/qwik/src/core/shared/utils/character-escaping.ts
232
- function escapeHTML(html) {
233
- let escapedHTML = "";
234
- const length = html.length;
235
- let idx = 0;
236
- let lastIdx = idx;
237
- for (; idx < length; idx++) {
238
- const ch = html.charCodeAt(idx);
239
- if (ch === 60) {
240
- escapedHTML += html.substring(lastIdx, idx) + "&lt;";
241
- } else if (ch === 62) {
242
- escapedHTML += html.substring(lastIdx, idx) + "&gt;";
243
- } else if (ch === 38) {
244
- escapedHTML += html.substring(lastIdx, idx) + "&amp;";
245
- } else if (ch === 34) {
246
- escapedHTML += html.substring(lastIdx, idx) + "&quot;";
247
- } else if (ch === 39) {
248
- escapedHTML += html.substring(lastIdx, idx) + "&#39;";
249
- } else {
250
- continue;
251
- }
252
- lastIdx = idx + 1;
253
- }
254
- if (lastIdx === 0) {
255
- return html;
256
- } else {
257
- return escapedHTML + html.substring(lastIdx);
258
- }
259
- }
260
-
261
- // packages/qwik/src/core/shared/utils/markers.ts
262
- var OnRenderProp = "q:renderFn";
263
- var QSlot = "q:slot";
264
- var QSlotParent = "q:sparent";
265
- var QStyle = "q:style";
266
- var QStyleSelector = "style[q\\:style]";
267
- var QStyleSSelector = "style[q\\:sstyle]";
268
- var QStylesAllSelector = QStyleSelector + "," + QStyleSSelector;
269
- var QScopedStyle = "q:sstyle";
270
- var QCtxAttr = "q:ctx";
271
- var QBackRefs = "q:brefs";
272
- var QRenderAttr = "q:render";
273
- var QRuntimeAttr = "q:runtime";
274
- var QVersionAttr = "q:version";
275
- var QBaseAttr = "q:base";
276
- var QLocaleAttr = "q:locale";
277
- var QManifestHashAttr = "q:manifest-hash";
278
- var QInstanceAttr = "q:instance";
279
- var QContainerIsland = "q:container-island";
280
- var QContainerIslandEnd = "/" + QContainerIsland;
281
- var QIgnore = "q:ignore";
282
- var QIgnoreEnd = "/" + QIgnore;
283
- var QContainerAttr = "q:container";
284
- var QContainerAttrEnd = "/" + QContainerAttr;
285
- var QTemplate = "q:template";
286
- var QContainerSelector = "[q\\:container]:not([q\\:container=" + "html" /* HTML */ + "]):not([q\\:container=" + "text" /* TEXT */ + "])";
287
- var QDefaultSlot = "";
288
- var ELEMENT_ID = "q:id";
289
- var ELEMENT_KEY = "q:key";
290
- var ELEMENT_PROPS = "q:props";
291
- var ELEMENT_SEQ = "q:seq";
292
- var ELEMENT_SEQ_IDX = "q:seqIdx";
293
- var NON_SERIALIZABLE_MARKER_PREFIX = ":";
294
- var USE_ON_LOCAL = NON_SERIALIZABLE_MARKER_PREFIX + "on";
295
- var USE_ON_LOCAL_SEQ_IDX = NON_SERIALIZABLE_MARKER_PREFIX + "onIdx";
296
- var USE_ON_LOCAL_FLAGS = NON_SERIALIZABLE_MARKER_PREFIX + "onFlags";
297
- var FLUSH_COMMENT = "qkssr-f";
298
- var STREAM_BLOCK_START_COMMENT = "qkssr-pu";
299
- var STREAM_BLOCK_END_COMMENT = "qkssr-po";
300
- var Q_PROPS_SEPARATOR = ":";
301
- var dangerouslySetInnerHTML = "dangerouslySetInnerHTML";
302
-
303
- // packages/qwik/src/core/shared/utils/promises.ts
304
- import { isDev as isDev2, isServer } from "@qwik.dev/core/build";
305
- var isPromise = (value) => {
306
- return !!value && typeof value == "object" && typeof value.then === "function";
307
- };
308
- var maybeThen = (valueOrPromise, thenFn) => {
309
- return isPromise(valueOrPromise) ? valueOrPromise.then(thenFn, shouldNotError) : thenFn(valueOrPromise);
310
- };
311
- var shouldNotError = (reason) => {
312
- throwErrorAndStop(reason);
313
- };
314
-
315
- // packages/qwik/src/core/shared/utils/scoped-styles.ts
316
- function isClassAttr(key) {
317
- return key === "class" || key === "className";
318
- }
319
- function convertStyleIdsToString(scopedStyleIds) {
320
- return Array.from(scopedStyleIds).join(" ");
321
- }
322
-
323
- // packages/qwik/src/core/shared/utils/event-names.ts
324
- function isPreventDefault(key) {
325
- return key.startsWith("preventdefault:");
326
- }
327
-
328
- // packages/qwik/src/core/shared/utils/unitless_number.ts
329
- var unitlessNumbers = /* @__PURE__ */ new Set([
330
- "animationIterationCount",
331
- "aspectRatio",
332
- "borderImageOutset",
333
- "borderImageSlice",
334
- "borderImageWidth",
335
- "boxFlex",
336
- "boxFlexGroup",
337
- "boxOrdinalGroup",
338
- "columnCount",
339
- "columns",
340
- "flex",
341
- "flexGrow",
342
- "flexShrink",
343
- "gridArea",
344
- "gridRow",
345
- "gridRowEnd",
346
- "gridRowStart",
347
- "gridColumn",
348
- "gridColumnEnd",
349
- "gridColumnStart",
350
- "fontWeight",
351
- "lineClamp",
352
- "lineHeight",
353
- "opacity",
354
- "order",
355
- "orphans",
356
- "scale",
357
- "tabSize",
358
- "widows",
359
- "zIndex",
360
- "zoom",
361
- "MozAnimationIterationCount",
362
- // Known Prefixed Properties
363
- "MozBoxFlex",
364
- // TODO: Remove these since they shouldn't be used in modern code
365
- "msFlex",
366
- "msFlexPositive",
367
- "WebkitAnimationIterationCount",
368
- "WebkitBoxFlex",
369
- "WebkitBoxOrdinalGroup",
370
- "WebkitColumnCount",
371
- "WebkitColumns",
372
- "WebkitFlex",
373
- "WebkitFlexGrow",
374
- "WebkitFlexShrink",
375
- "WebkitLineClamp"
376
- ]);
377
- var isUnitlessNumber = (name) => {
378
- return unitlessNumbers.has(name);
379
- };
380
-
381
- // packages/qwik/src/core/shared/utils/styles.ts
382
- var serializeClass = (obj) => {
383
- if (!obj) {
384
- return "";
385
- }
386
- if (isString(obj)) {
387
- return obj.trim();
388
- }
389
- const classes = [];
390
- if (isArray(obj)) {
391
- for (const o of obj) {
392
- const classList = serializeClass(o);
393
- if (classList) {
394
- classes.push(classList);
395
- }
396
- }
397
- } else {
398
- for (const [key, value] of Object.entries(obj)) {
399
- if (value) {
400
- classes.push(key.trim());
401
- }
402
- }
403
- }
404
- return classes.join(" ");
405
- };
406
- var fromCamelToKebabCaseWithDash = (text) => {
407
- return text.replace(/([A-Z])/g, "-$1").toLowerCase();
408
- };
409
- var stringifyStyle = (obj) => {
410
- if (obj == null) {
411
- return "";
412
- }
413
- if (typeof obj == "object") {
414
- if (isArray(obj)) {
415
- throw qError(0 /* stringifyClassOrStyle */, [obj, "style"]);
416
- } else {
417
- const chunks = [];
418
- for (const key in obj) {
419
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
420
- const value = obj[key];
421
- if (value != null && typeof value !== "function") {
422
- if (key.startsWith("--")) {
423
- chunks.push(key + ":" + value);
424
- } else {
425
- chunks.push(fromCamelToKebabCaseWithDash(key) + ":" + setValueForStyle(key, value));
426
- }
427
- }
428
- }
429
- }
430
- return chunks.join(";");
431
- }
432
- }
433
- return String(obj);
434
- };
435
- var serializeBooleanOrNumberAttribute = (value) => {
436
- return value != null ? String(value) : null;
437
- };
438
- function serializeAttribute(key, value, styleScopedId) {
439
- if (isClassAttr(key)) {
440
- const serializedClass = serializeClass(value);
441
- value = styleScopedId ? styleScopedId + (serializedClass.length ? " " + serializedClass : serializedClass) : serializedClass;
442
- } else if (key === "style") {
443
- value = stringifyStyle(value);
444
- } else if (isEnumeratedBooleanAttribute(key) || typeof value === "number") {
445
- value = serializeBooleanOrNumberAttribute(value);
446
- } else if (value === false || value == null) {
447
- value = null;
448
- } else if (value === true && isPreventDefault(key)) {
449
- value = "";
450
- }
451
- return value;
452
- }
453
- function isEnumeratedBooleanAttribute(key) {
454
- return isAriaAttribute(key) || ["spellcheck", "draggable", "contenteditable"].includes(key);
455
- }
456
- var setValueForStyle = (styleName, value) => {
457
- if (typeof value === "number" && value !== 0 && !isUnitlessNumber(styleName)) {
458
- return value + "px";
459
- }
460
- return value;
461
- };
462
- function isAriaAttribute(prop) {
463
- return prop.startsWith("aria-");
464
- }
465
-
466
245
  // packages/qwik/src/core/shared/vnode-data-types.ts
467
246
  var VNodeDataSeparator = {
468
247
  REFERENCE_CH: (
@@ -653,6 +432,12 @@ var VNodeDataChar = {
653
432
  /* ** */
654
433
  "<"
655
434
  ),
435
+ RENDER_HASH_PREFIX: (
436
+ /* **/
437
+ 95
438
+ ),
439
+ // `_` after `<` identifies a component hash.
440
+ RENDER_HASH_PREFIX_CHAR: "_",
656
441
  ID: (
657
442
  /* ***************** */
658
443
  61
@@ -750,303 +535,470 @@ var VNodeDataChar = {
750
535
  "~"
751
536
  )
752
537
  };
753
-
754
- // packages/qwik/src/core/preloader/queue.ts
755
- import { isBrowser as isBrowser3 } from "@qwik.dev/core/build";
756
-
757
- // packages/qwik/src/core/preloader/bundle-graph.ts
758
- import { isBrowser as isBrowser2 } from "@qwik.dev/core/build";
759
-
760
- // packages/qwik/src/core/preloader/constants.ts
761
- import { isBrowser } from "@qwik.dev/core/build";
762
- var doc = isBrowser ? document : void 0;
763
- var config = {
764
- $DEBUG$: false,
765
- $maxIdlePreloads$: 25,
766
- $invPreloadProbability$: 0.65
538
+ var getSegmentVNodeRefId = (segmentId, localIndex) => {
539
+ const segmentIndex = parseInt(segmentId, 10) - 1;
540
+ const diagonal = segmentIndex + localIndex;
541
+ return -(diagonal * (diagonal + 1) / 2 + localIndex + 1);
767
542
  };
768
- var rel = isBrowser && doc.createElement("link").relList.supports("modulepreload") ? "modulePreload" : "preload";
769
- var loadStart = Date.now();
770
- var isJSRegex = /\.[mc]?js$/;
771
543
 
772
- // packages/qwik/src/core/preloader/types.ts
773
- var BundleImportState_None = 0;
774
- var BundleImportState_Queued = 1;
775
- var BundleImportState_Preload = 2;
776
- var BundleImportState_Alias = 3;
777
- var BundleImportState_Loaded = 4;
778
-
779
- // packages/qwik/src/core/preloader/bundle-graph.ts
780
- var base;
781
- var graph;
782
- var makeBundle = (name, deps) => {
783
- return {
784
- $name$: name,
785
- $state$: isJSRegex.test(name) ? BundleImportState_None : BundleImportState_Alias,
786
- $deps$: shouldResetFactor ? deps?.map((d) => ({ ...d, $factor$: 1 })) : deps,
787
- $inverseProbability$: 1,
788
- $createdTs$: Date.now(),
789
- $waitedMs$: 0,
790
- $loadedMs$: 0
791
- };
792
- };
793
- var parseBundleGraph = (serialized) => {
794
- const graph2 = /* @__PURE__ */ new Map();
795
- let i = 0;
796
- while (i < serialized.length) {
797
- const name = serialized[i++];
798
- const deps = [];
799
- let idx;
800
- let probability = 1;
801
- while (idx = serialized[i], typeof idx === "number") {
802
- if (idx < 0) {
803
- probability = -idx / 10;
804
- } else {
805
- deps.push({
806
- $name$: serialized[idx],
807
- $importProbability$: probability,
808
- $factor$: 1
809
- });
810
- }
811
- i++;
544
+ // packages/qwik/src/core/shared/utils/character-escaping.ts
545
+ function escapeHTML(html) {
546
+ let escapedHTML = "";
547
+ const length = html.length;
548
+ let idx = 0;
549
+ let lastIdx = idx;
550
+ for (; idx < length; idx++) {
551
+ const ch = html.charCodeAt(idx);
552
+ if (ch === 60) {
553
+ escapedHTML += html.substring(lastIdx, idx) + "&lt;";
554
+ } else if (ch === 62) {
555
+ escapedHTML += html.substring(lastIdx, idx) + "&gt;";
556
+ } else if (ch === 38) {
557
+ escapedHTML += html.substring(lastIdx, idx) + "&amp;";
558
+ } else if (ch === 34) {
559
+ escapedHTML += html.substring(lastIdx, idx) + "&quot;";
560
+ } else if (ch === 39) {
561
+ escapedHTML += html.substring(lastIdx, idx) + "&#39;";
562
+ } else {
563
+ continue;
812
564
  }
813
- graph2.set(name, deps);
565
+ lastIdx = idx + 1;
814
566
  }
815
- return graph2;
816
- };
817
- var getBundle = (name) => {
818
- let bundle = bundles.get(name);
819
- if (!bundle) {
820
- let deps;
821
- if (graph) {
822
- deps = graph.get(name);
823
- if (!deps) {
824
- return;
825
- }
826
- if (!deps.length) {
827
- deps = void 0;
828
- }
829
- }
830
- bundle = makeBundle(name, deps);
831
- bundles.set(name, bundle);
567
+ if (lastIdx === 0) {
568
+ return html;
569
+ } else {
570
+ return escapedHTML + html.substring(lastIdx);
832
571
  }
833
- return bundle;
834
- };
835
- var initPreloader = (serializedBundleGraph, opts) => {
836
- if (opts) {
837
- if ("debug" in opts) {
838
- config.$DEBUG$ = !!opts.debug;
572
+ }
573
+ function encodeVNodeDataString(str) {
574
+ let escapedHTML = "";
575
+ const length = str.length;
576
+ let idx = 0;
577
+ let lastIdx = idx;
578
+ for (; idx < length; idx++) {
579
+ const ch = str.charCodeAt(idx);
580
+ if (ch >= VNodeDataSeparator.ADVANCE_1 && ch <= VNodeDataSeparator.ADVANCE_8192) {
581
+ escapedHTML += str.substring(lastIdx, idx) + "\\" + str.charAt(idx);
582
+ } else {
583
+ continue;
839
584
  }
840
- if (typeof opts.preloadProbability === "number") {
841
- config.$invPreloadProbability$ = 1 - opts.preloadProbability;
585
+ lastIdx = idx + 1;
586
+ }
587
+ if (lastIdx === 0) {
588
+ return str;
589
+ } else {
590
+ return escapedHTML + str.substring(lastIdx);
591
+ }
592
+ }
593
+ function encodeVNodeDataKey(str) {
594
+ const encoded = encodeURI(str);
595
+ let encodedKey = "";
596
+ const length = encoded.length;
597
+ let idx = 0;
598
+ let lastIdx = idx;
599
+ for (; idx < length; idx++) {
600
+ const ch = encoded.charCodeAt(idx);
601
+ let replacement = null;
602
+ if (ch === 59) {
603
+ replacement = "%3B";
604
+ } else if (ch === 61) {
605
+ replacement = "%3D";
606
+ } else if (ch === 63) {
607
+ replacement = "%3F";
608
+ } else if (ch === 64) {
609
+ replacement = "%40";
610
+ } else if (ch === 126) {
611
+ replacement = "%7E";
612
+ } else {
613
+ continue;
842
614
  }
615
+ encodedKey += encoded.substring(lastIdx, idx) + replacement;
616
+ lastIdx = idx + 1;
843
617
  }
844
- if (base != null || !serializedBundleGraph) {
845
- return;
618
+ if (lastIdx === 0) {
619
+ return encoded;
620
+ } else {
621
+ return encodedKey + encoded.substring(lastIdx);
846
622
  }
847
- base = "";
848
- graph = parseBundleGraph(serializedBundleGraph);
849
- };
623
+ }
850
624
 
851
- // packages/qwik/src/core/preloader/queue.ts
852
- var bundles = /* @__PURE__ */ new Map();
853
- var shouldResetFactor;
854
- var queueDirty;
855
- var preloadCount = 0;
856
- var queue = [];
857
- var log = (...args) => {
858
- console.log(
859
- `Preloader ${Date.now() - loadStart}ms ${preloadCount}/${queue.length} queued>`,
860
- ...args
861
- );
625
+ // packages/qwik/src/core/shared/utils/markers.ts
626
+ var OnRenderProp = "q:renderFn";
627
+ var QSlot = "q:slot";
628
+ var QSlotParent = "q:sparent";
629
+ var QStatePatchAttr = "q:patch";
630
+ var QSuspenseResolved = "q:r";
631
+ var QStyle = "q:style";
632
+ var QStyleSelector = "style[q\\:style]";
633
+ var QStyleSSelector = "style[q\\:sstyle]";
634
+ var QStylesAllSelector = QStyleSelector + "," + QStyleSSelector;
635
+ var QScopedStyle = "q:sstyle";
636
+ var QCtxAttr = "q:ctx";
637
+ var QBackRefs = "q:brefs";
638
+ var QwikEvContainerReady = 0;
639
+ var QRenderAttr = "q:render";
640
+ var QRuntimeAttr = "q:runtime";
641
+ var QVersionAttr = "q:version";
642
+ var QBaseAttr = "q:base";
643
+ var QLocaleAttr = "q:locale";
644
+ var QManifestHashAttr = "q:manifest-hash";
645
+ var QInstanceAttr = "q:instance";
646
+ var QStatePrewarmAttr = "q:prewarm";
647
+ var QContainerIsland = "q:container-island";
648
+ var QContainerIslandEnd = "/" + QContainerIsland;
649
+ var QIgnore = "q:ignore";
650
+ var QIgnoreEnd = "/" + QIgnore;
651
+ var QContainerAttr = "q:container";
652
+ var QContainerAttrEnd = "/" + QContainerAttr;
653
+ var QTemplate = "q:template";
654
+ var QContainerSelector = "[q\\:container]:not([q\\:container=" + "html" /* HTML */ + "]):not([q\\:container=" + "text" /* TEXT */ + "])";
655
+ var QDefaultSlot = "";
656
+ var ELEMENT_ID = "q:id";
657
+ var ELEMENT_KEY = "q:key";
658
+ var ELEMENT_PROPS = "q:props";
659
+ var ELEMENT_SEQ = "q:seq";
660
+ var ELEMENT_SEQ_IDX = "q:seqIdx";
661
+ var ELEMENT_BACKPATCH_DATA = "qwik/backpatch";
662
+ var ITERATION_ITEM_SINGLE = "q:p";
663
+ var ITERATION_ITEM_MULTI = "q:ps";
664
+ var NON_SERIALIZABLE_MARKER_PREFIX = ":";
665
+ var USE_ON_LOCAL = NON_SERIALIZABLE_MARKER_PREFIX + "on";
666
+ var USE_ON_LOCAL_SEQ_IDX = NON_SERIALIZABLE_MARKER_PREFIX + "onIdx";
667
+ var USE_ON_LOCAL_FLAGS = NON_SERIALIZABLE_MARKER_PREFIX + "onFlags";
668
+ var QCursorBoundary = NON_SERIALIZABLE_MARKER_PREFIX + "cursorBoundary";
669
+ var NEAREST_CURSOR_BOUNDARY = NON_SERIALIZABLE_MARKER_PREFIX + "nearestCursorBoundary";
670
+ var Q_PROPS_SEPARATOR = ":";
671
+ var dangerouslySetInnerHTML = "dangerouslySetInnerHTML";
672
+
673
+ // packages/qwik/src/core/shared/utils/promises.ts
674
+ import { isDev as isDev5, isServer } from "@qwik.dev/core/build";
675
+ var MAX_RETRY_ON_PROMISE_COUNT = 100;
676
+ var isPromise = (value) => {
677
+ return !!value && typeof value == "object" && typeof value.then === "function";
862
678
  };
863
- var resetQueue = () => {
864
- bundles.clear();
865
- queueDirty = false;
866
- shouldResetFactor = true;
867
- preloadCount = 0;
868
- queue.length = 0;
679
+ var maybeThen = (valueOrPromise, thenFn) => {
680
+ return isPromise(valueOrPromise) ? valueOrPromise.then(thenFn) : thenFn(valueOrPromise);
869
681
  };
870
- var sortQueue = () => {
871
- if (queueDirty) {
872
- queue.sort((a, b) => a.$inverseProbability$ - b.$inverseProbability$);
873
- queueDirty = false;
682
+ var checkError = (e) => {
683
+ if (isServer && e instanceof ReferenceError && e.message.includes("window")) {
684
+ e.message = 'It seems like you forgot to add "if (isBrowser) {...}" here:' + e.message;
874
685
  }
875
686
  };
876
- var getQueue = () => {
877
- sortQueue();
878
- let probability = 0.4;
879
- const result = [];
880
- for (const b of queue) {
881
- const nextProbability = Math.round((1 - b.$inverseProbability$) * 10);
882
- if (nextProbability !== probability) {
883
- probability = nextProbability;
884
- result.push(probability);
885
- }
886
- result.push(b.$name$);
887
- }
888
- return result;
687
+ var justThrow = (e) => {
688
+ throw e;
889
689
  };
890
- var trigger = () => {
891
- if (!queue.length) {
892
- return;
893
- }
894
- sortQueue();
895
- while (queue.length) {
896
- const bundle = queue[0];
897
- const inverseProbability = bundle.$inverseProbability$;
898
- const probability = 1 - inverseProbability;
899
- const allowedPreloads = graph ? (
900
- // The more likely the bundle, the more simultaneous preloads we want to allow
901
- Math.max(1, config.$maxIdlePreloads$ * probability)
902
- ) : (
903
- // While the graph is not available, we limit to 2 preloads
904
- 2
905
- );
906
- if (probability >= 0.99 || preloadCount < allowedPreloads) {
907
- queue.shift();
908
- preloadOne(bundle);
909
- } else {
910
- break;
690
+ function retryOnPromise(fn, onError = justThrow) {
691
+ let ok = false;
692
+ let result;
693
+ try {
694
+ result = fn();
695
+ ok = true;
696
+ } catch (e) {
697
+ result = e;
698
+ }
699
+ if (!isPromise(result)) {
700
+ if (ok) {
701
+ return result;
911
702
  }
703
+ isDev5 && checkError(result);
704
+ return onError(result);
912
705
  }
913
- if (config.$DEBUG$ && !queue.length) {
914
- const loaded = [...bundles.values()].filter((b) => b.$state$ > BundleImportState_None);
915
- const waitTime = loaded.reduce((acc, b) => acc + b.$waitedMs$, 0);
916
- const loadTime = loaded.reduce((acc, b) => acc + b.$loadedMs$, 0);
917
- log(
918
- `>>>> done ${loaded.length}/${bundles.size} total: ${waitTime}ms waited, ${loadTime}ms loaded`
919
- );
920
- }
921
- };
922
- var preloadOne = (bundle) => {
923
- if (bundle.$state$ >= BundleImportState_Preload) {
924
- return;
925
- }
926
- preloadCount++;
927
- const start = Date.now();
928
- bundle.$waitedMs$ = start - bundle.$createdTs$;
929
- bundle.$state$ = BundleImportState_Preload;
930
- config.$DEBUG$ && log(
931
- `<< load ${Math.round((1 - bundle.$inverseProbability$) * 100)}% after ${`${bundle.$waitedMs$}ms`}`,
932
- bundle.$name$
933
- );
934
- const link = doc.createElement("link");
935
- link.href = new URL(`${base}${bundle.$name$}`, doc.baseURI).toString();
936
- link.rel = rel;
937
- link.as = "script";
938
- link.onload = link.onerror = () => {
939
- preloadCount--;
940
- const end = Date.now();
941
- bundle.$loadedMs$ = end - start;
942
- bundle.$state$ = BundleImportState_Loaded;
943
- config.$DEBUG$ && log(`>> done after ${bundle.$loadedMs$}ms`, bundle.$name$);
944
- link.remove();
945
- trigger();
706
+ let retryCount = MAX_RETRY_ON_PROMISE_COUNT;
707
+ const retry = async (p) => {
708
+ while (isPromise(p)) {
709
+ try {
710
+ await p;
711
+ return await fn();
712
+ } catch (err) {
713
+ if (isPromise(err)) {
714
+ if (!--retryCount) {
715
+ p = new Error("Exceeded max retry count in retryOnPromise");
716
+ break;
717
+ } else {
718
+ p = err;
719
+ }
720
+ } else {
721
+ p = err;
722
+ break;
723
+ }
724
+ }
725
+ }
726
+ isDev5 && checkError(p);
727
+ return onError(p);
946
728
  };
947
- doc.head.appendChild(link);
729
+ return ok ? result.catch(retry) : retry(result);
730
+ }
731
+
732
+ // packages/qwik/src/core/shared/utils/scoped-styles.ts
733
+ function isClassAttr(key) {
734
+ return key === "class";
735
+ }
736
+ function convertStyleIdsToString(scopedStyleIds) {
737
+ return Array.from(scopedStyleIds).join(" ");
738
+ }
739
+
740
+ // packages/qwik/src/core/shared/utils/event-names.ts
741
+ var isHtmlAttributeAnEventName = (name) => {
742
+ return name.charCodeAt(0) === 113 && name.charCodeAt(1) === 45 && (name.charCodeAt(3) === 58 || name.charCodeAt(3) === 112 && name.charCodeAt(4) === 58);
948
743
  };
949
- var adjustProbabilities = (bundle, newInverseProbability, seen) => {
950
- if (seen?.has(bundle)) {
951
- return;
744
+ function isPreventDefault(key) {
745
+ return key.startsWith("preventdefault:");
746
+ }
747
+
748
+ // packages/qwik/src/core/shared/utils/unitless_number.ts
749
+ var unitlessNumbers = /* @__PURE__ */ new Set([
750
+ "animationIterationCount",
751
+ "aspectRatio",
752
+ "borderImageOutset",
753
+ "borderImageSlice",
754
+ "borderImageWidth",
755
+ "boxFlex",
756
+ "boxFlexGroup",
757
+ "boxOrdinalGroup",
758
+ "columnCount",
759
+ "columns",
760
+ "flex",
761
+ "flexGrow",
762
+ "flexShrink",
763
+ "gridArea",
764
+ "gridRow",
765
+ "gridRowEnd",
766
+ "gridRowStart",
767
+ "gridColumn",
768
+ "gridColumnEnd",
769
+ "gridColumnStart",
770
+ "fontWeight",
771
+ "lineClamp",
772
+ "lineHeight",
773
+ "opacity",
774
+ "order",
775
+ "orphans",
776
+ "scale",
777
+ "tabSize",
778
+ "widows",
779
+ "zIndex",
780
+ "zoom",
781
+ "MozAnimationIterationCount",
782
+ // Known Prefixed Properties
783
+ "MozBoxFlex",
784
+ // TODO: Remove these since they shouldn't be used in modern code
785
+ "msFlex",
786
+ "msFlexPositive",
787
+ "WebkitAnimationIterationCount",
788
+ "WebkitBoxFlex",
789
+ "WebkitBoxOrdinalGroup",
790
+ "WebkitColumnCount",
791
+ "WebkitColumns",
792
+ "WebkitFlex",
793
+ "WebkitFlexGrow",
794
+ "WebkitFlexShrink",
795
+ "WebkitLineClamp"
796
+ ]);
797
+ var isUnitlessNumber = (name) => {
798
+ return unitlessNumbers.has(name);
799
+ };
800
+
801
+ // packages/qwik/src/core/shared/utils/styles.ts
802
+ var serializeClass = (obj) => {
803
+ if (!obj) {
804
+ return "";
952
805
  }
953
- const previousInverseProbability = bundle.$inverseProbability$;
954
- bundle.$inverseProbability$ = newInverseProbability;
955
- if (previousInverseProbability - bundle.$inverseProbability$ < 0.01) {
956
- return;
806
+ if (isString(obj)) {
807
+ return obj.trim();
957
808
  }
958
- if (
959
- // don't queue until we have initialized the preloader
960
- base != null && bundle.$state$ < BundleImportState_Preload && bundle.$inverseProbability$ < config.$invPreloadProbability$
961
- ) {
962
- if (bundle.$state$ === BundleImportState_None) {
963
- bundle.$state$ = BundleImportState_Queued;
964
- queue.push(bundle);
965
- config.$DEBUG$ && log(`queued ${Math.round((1 - bundle.$inverseProbability$) * 100)}%`, bundle.$name$);
966
- }
967
- queueDirty = true;
968
- }
969
- if (bundle.$deps$) {
970
- seen || (seen = /* @__PURE__ */ new Set());
971
- seen.add(bundle);
972
- const probability = 1 - bundle.$inverseProbability$;
973
- for (const dep of bundle.$deps$) {
974
- const depBundle = getBundle(dep.$name$);
975
- if (depBundle.$inverseProbability$ === 0) {
976
- continue;
809
+ const classes = [];
810
+ if (isArray(obj)) {
811
+ for (let i = 0; i < obj.length; i++) {
812
+ const o = obj[i];
813
+ const classList = serializeClass(o);
814
+ if (classList) {
815
+ classes.push(classList);
977
816
  }
978
- let newInverseProbability2;
979
- if (dep.$importProbability$ > 0.5 && (probability === 1 || probability >= 0.99 && depsCount < 100)) {
980
- depsCount++;
981
- newInverseProbability2 = Math.min(0.01, 1 - dep.$importProbability$);
982
- } else {
983
- const newInverseImportProbability = 1 - dep.$importProbability$ * probability;
984
- const prevAdjust = dep.$factor$;
985
- const factor = newInverseImportProbability / prevAdjust;
986
- newInverseProbability2 = Math.max(0.02, depBundle.$inverseProbability$ * factor);
987
- dep.$factor$ = factor;
817
+ }
818
+ } else {
819
+ for (const [key, value] of Object.entries(obj)) {
820
+ if (value) {
821
+ classes.push(key.trim());
988
822
  }
989
- adjustProbabilities(depBundle, newInverseProbability2, seen);
990
823
  }
991
824
  }
825
+ return classes.join(" ");
992
826
  };
993
- var handleBundle = (name, inverseProbability) => {
994
- const bundle = getBundle(name);
995
- if (bundle && bundle.$inverseProbability$ > inverseProbability) {
996
- adjustProbabilities(bundle, inverseProbability);
827
+ var fromCamelToKebabCaseWithDash = (text) => {
828
+ return text.replace(/([A-Z])/g, "-$1").toLowerCase();
829
+ };
830
+ var stringifyStyle = (obj) => {
831
+ if (obj == null) {
832
+ return "";
833
+ }
834
+ if (typeof obj == "object") {
835
+ if (isArray(obj)) {
836
+ throw qError(0 /* stringifyClassOrStyle */, [obj, "style"]);
837
+ } else {
838
+ const chunks = [];
839
+ for (const key in obj) {
840
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
841
+ const value = obj[key];
842
+ if (value != null && typeof value !== "function") {
843
+ if (key.startsWith("--")) {
844
+ chunks.push(key + ":" + value);
845
+ } else {
846
+ chunks.push(fromCamelToKebabCaseWithDash(key) + ":" + setValueForStyle(key, value));
847
+ }
848
+ }
849
+ }
850
+ }
851
+ return chunks.join(";");
852
+ }
997
853
  }
854
+ return String(obj);
998
855
  };
999
- var depsCount;
1000
- var preload = (name, probability) => {
1001
- if (!name?.length) {
1002
- return;
856
+ var serializeBooleanOrNumberAttribute = (value) => {
857
+ return value != null ? String(value) : null;
858
+ };
859
+ function serializeAttribute(key, value, styleScopedId) {
860
+ if (isClassAttr(key)) {
861
+ const serializedClass = serializeClass(value);
862
+ value = styleScopedId ? styleScopedId + (serializedClass.length ? " " + serializedClass : serializedClass) : serializedClass;
863
+ } else if (key === "style") {
864
+ value = stringifyStyle(value);
865
+ } else if (isEnumeratedBooleanAttribute(key) || typeof value === "number") {
866
+ value = serializeBooleanOrNumberAttribute(value);
867
+ } else if (value === false || value == null) {
868
+ value = null;
869
+ } else if (value === true && isPreventDefault(key)) {
870
+ value = "";
871
+ }
872
+ return value;
873
+ }
874
+ function isEnumeratedBooleanAttribute(key) {
875
+ return isAriaAttribute(key) || ["spellcheck", "draggable", "contenteditable"].includes(key);
876
+ }
877
+ var setValueForStyle = (styleName, value) => {
878
+ if (typeof value === "number" && value !== 0 && !isUnitlessNumber(styleName)) {
879
+ return value + "px";
1003
880
  }
1004
- depsCount = 0;
1005
- let inverseProbability = probability ? 1 - probability : 0.4;
1006
- if (Array.isArray(name)) {
1007
- for (let i = name.length - 1; i >= 0; i--) {
1008
- const item = name[i];
1009
- if (typeof item === "number") {
1010
- inverseProbability = 1 - item / 10;
881
+ return value;
882
+ };
883
+ function isAriaAttribute(prop) {
884
+ return prop.startsWith("aria-");
885
+ }
886
+
887
+ // packages/qwik/src/core/preloader/bundle-graph.ts
888
+ var base;
889
+ var graph;
890
+ var parseBundleGraph = (serialized) => {
891
+ const graph2 = /* @__PURE__ */ new Map();
892
+ let i = 0;
893
+ while (i < serialized.length) {
894
+ const name = serialized[i++];
895
+ const deps = [];
896
+ let idx;
897
+ let probability = 1;
898
+ while (idx = serialized[i], typeof idx === "number") {
899
+ if (idx < 0) {
900
+ probability = -idx / 10;
1011
901
  } else {
1012
- handleBundle(item, inverseProbability);
902
+ deps.push({
903
+ $name$: serialized[idx],
904
+ $importProbability$: probability,
905
+ $factor$: 1
906
+ });
1013
907
  }
908
+ i++;
1014
909
  }
1015
- } else {
1016
- handleBundle(name, inverseProbability);
910
+ graph2.set(name, deps);
1017
911
  }
1018
- if (isBrowser3) {
1019
- trigger();
912
+ return graph2;
913
+ };
914
+ var initPreloader = (serializedBundleGraph) => {
915
+ if (base != null || !serializedBundleGraph) {
916
+ return;
1020
917
  }
918
+ base = "";
919
+ graph = parseBundleGraph(serializedBundleGraph);
1021
920
  };
1022
- if (isBrowser3) {
1023
- document.addEventListener("qsymbol", (ev) => {
1024
- const { symbol, href } = ev.detail;
1025
- if (href) {
1026
- const hash2 = symbol.slice(symbol.lastIndexOf("_") + 1);
1027
- preload(hash2, 1);
921
+
922
+ // packages/qwik/src/core/shared/utils/objects.ts
923
+ var isObjectEmpty = (obj) => {
924
+ for (const key in obj) {
925
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
926
+ return false;
1028
927
  }
1029
- });
1030
- }
928
+ }
929
+ return true;
930
+ };
931
+
932
+ // packages/qwik/src/core/ssr/stream-writer.ts
933
+ var stringifyRootRefPath = (path) => {
934
+ let text = String(path[0]);
935
+ for (let i = 1; i < path.length; i++) {
936
+ text += " " + path[i];
937
+ }
938
+ return text;
939
+ };
940
+ var writeStringRootRef = (writer, id) => writer.write(String(id));
941
+ var writeStringRootRefPath = (writer, path) => writer.write(stringifyRootRefPath(path));
942
+ var writeStringRootRefDelta = (writer, id, base2) => writer.write(String(id - base2));
943
+ var createStringStreamWriter = (write) => ({
944
+ write,
945
+ writeRootRef(id) {
946
+ return writeStringRootRef(this, id);
947
+ },
948
+ writeRootRefPath(path) {
949
+ return writeStringRootRefPath(this, path);
950
+ },
951
+ writeRootRefDelta(id, base2) {
952
+ return writeStringRootRefDelta(this, id, base2);
953
+ }
954
+ });
955
+
956
+ // packages/qwik/src/core/shared/ssr-const.ts
957
+ var LT = "<";
958
+ var GT = ">";
959
+ var CLOSE_TAG = "</";
960
+ var SPACE = " ";
961
+ var ATTR_EQUALS_QUOTE = '="';
962
+ var QUOTE = '"';
963
+ var EMPTY_ATTR = '=""';
964
+ var BRACKET_OPEN = "[";
965
+ var BRACKET_CLOSE = "]";
966
+ var PAREN_CLOSE = ")";
967
+ var COMMA = ",";
1031
968
 
1032
969
  // packages/qwik/src/server/platform.ts
970
+ var getDevSegmentPath = (mapper, hash, symbolName, parent) => {
971
+ const existing = mapper?.[hash];
972
+ if (existing) {
973
+ return existing;
974
+ }
975
+ if (symbolName === SYNC_QRL) {
976
+ return [symbolName, ""];
977
+ }
978
+ if (!parent) {
979
+ if (symbolName.startsWith("_") && symbolName.length < 6) {
980
+ return [symbolName, `${import.meta.env?.BASE_URL}@qwik-handlers`];
981
+ }
982
+ console.error("qwik symbolMapper: unknown qrl requested without parent:", symbolName);
983
+ return [symbolName, `${import.meta.env?.BASE_URL}${symbolName}.js`];
984
+ }
985
+ const qrlFile = `${import.meta.env?.BASE_URL}${parent.startsWith("/") ? parent.slice(1) : parent}_${symbolName}.js`;
986
+ return [symbolName, qrlFile];
987
+ };
1033
988
  function createPlatform(opts, resolvedManifest) {
1034
989
  const mapper = resolvedManifest?.mapper;
1035
990
  const mapperFn = opts.symbolMapper ? opts.symbolMapper : (symbolName, _chunk, parent) => {
1036
- if (mapper) {
1037
- const hash2 = getSymbolHash(symbolName);
1038
- const result = mapper[hash2];
991
+ if (mapper || isDev6 && import.meta.env?.MODE !== "test") {
992
+ const hash = getSymbolHash(symbolName);
993
+ const result = !isDev6 ? mapper[hash] : getDevSegmentPath(mapper, hash, symbolName, parent);
1039
994
  if (!result) {
1040
- if (hash2 === SYNC_QRL) {
1041
- return [hash2, ""];
995
+ if (hash === SYNC_QRL) {
996
+ return [hash, ""];
1042
997
  }
1043
- const isRegistered = globalThis.__qwik_reg_symbols?.has(hash2);
998
+ const isRegistered = globalThis.__qwik_reg_symbols?.has(hash);
1044
999
  if (isRegistered) {
1045
1000
  return [symbolName, "_"];
1046
1001
  }
1047
- if (parent) {
1048
- return [symbolName, `${parent}?qrl=${symbolName}`];
1049
- }
1050
1002
  console.error("Cannot resolve symbol", symbolName, "in", mapper, parent);
1051
1003
  }
1052
1004
  return result;
@@ -1055,32 +1007,17 @@ function createPlatform(opts, resolvedManifest) {
1055
1007
  const serverPlatform = {
1056
1008
  isServer: true,
1057
1009
  async importSymbol(_containerEl, url, symbolName) {
1058
- const hash2 = getSymbolHash(symbolName);
1059
- const regSym = globalThis.__qwik_reg_symbols?.get(hash2);
1010
+ const hash = getSymbolHash(symbolName);
1011
+ const regSym = globalThis.__qwik_reg_symbols?.get(hash);
1060
1012
  if (regSym) {
1061
1013
  return regSym;
1062
1014
  }
1063
- let modulePath = String(url);
1064
- if (!modulePath.endsWith(".js")) {
1065
- modulePath += ".js";
1066
- }
1067
- const module = __require(modulePath);
1068
- if (!(symbolName in module)) {
1069
- throw new Error(`Q-ERROR: missing symbol '${symbolName}' in module '${modulePath}'.`);
1070
- }
1071
- return module[symbolName];
1015
+ throw qError(6 /* dynamicImportFailed */, [symbolName]);
1072
1016
  },
1073
1017
  raf: () => {
1074
1018
  console.error("server can not rerender");
1075
1019
  return Promise.resolve();
1076
1020
  },
1077
- nextTick: (fn) => {
1078
- return new Promise((resolve) => {
1079
- setTimeout(() => {
1080
- resolve(fn());
1081
- });
1082
- });
1083
- },
1084
1021
  chunkForSymbol(symbolName, _chunk, parent) {
1085
1022
  return mapperFn(symbolName, mapper, parent);
1086
1023
  }
@@ -1099,50 +1036,253 @@ var getSymbolHash = (symbolName) => {
1099
1036
  return symbolName;
1100
1037
  };
1101
1038
 
1102
- // packages/qwik/src/server/utils.ts
1103
- function createTimer() {
1104
- if (typeof performance === "undefined") {
1105
- return () => 0;
1106
- }
1107
- const start = performance.now();
1108
- return () => {
1109
- const end = performance.now();
1110
- const delta = end - start;
1111
- return delta / 1e6;
1112
- };
1113
- }
1114
- function getBuildBase(opts) {
1115
- let base2 = opts.base;
1116
- if (typeof opts.base === "function") {
1117
- base2 = opts.base(opts);
1118
- }
1119
- if (typeof base2 === "string") {
1120
- if (!base2.endsWith("/")) {
1121
- base2 += "/";
1122
- }
1123
- return base2;
1124
- }
1125
- return `${import.meta.env.BASE_URL || "/"}build/`;
1126
- }
1127
- var versions = {
1128
- qwik: "2.0.0-beta.4-dev+9849dcf",
1129
- qwikDom: "2.1.19"
1130
- };
1039
+ // packages/qwik/src/server/ssr-render.ts
1040
+ import { getClientManifest } from "@qwik.dev/core";
1131
1041
 
1132
1042
  // packages/qwik/src/server/ssr-container.ts
1043
+ import { isDev as isDev8 } from "@qwik.dev/core/build";
1133
1044
  import {
1134
1045
  _SubscriptionData as SubscriptionData,
1135
1046
  _SharedContainer,
1136
1047
  _jsxSorted,
1137
1048
  _jsxSplit,
1049
+ _res,
1050
+ _setEvent,
1138
1051
  _walkJSX,
1052
+ _createQRL as createQRL,
1139
1053
  isSignal
1140
- } from "@qwik.dev/core";
1141
- import { isDev as isDev4 } from "@qwik.dev/core/build";
1054
+ } from "@qwik.dev/core/internal";
1055
+
1056
+ // packages/qwik/src/server/ooos-utils.ts
1057
+ import { _SubscriptionPatch as SubscriptionPatch } from "@qwik.dev/core/internal";
1058
+ var recordExternalRootEffect = (rootCtx, segmentCtx, storeProxyMap, records, producer, effect, prop, sourceEffects) => {
1059
+ if (!records || prop !== null && !sourceEffects) {
1060
+ return;
1061
+ }
1062
+ let rootObj = producer;
1063
+ if (prop !== null && producer && (typeof producer === "object" || typeof producer === "function")) {
1064
+ rootObj = storeProxyMap.get(producer) || producer;
1065
+ }
1066
+ const rootId = rootCtx.$hasRootId$(rootObj);
1067
+ segmentCtx.$addRoot$(rootObj);
1068
+ segmentCtx.$addRoot$(effect);
1069
+ if (prop !== null && typeof prop !== "string") {
1070
+ segmentCtx.$addRoot$(prop);
1071
+ }
1072
+ records.push({
1073
+ rootObj,
1074
+ rootId,
1075
+ effect,
1076
+ prop
1077
+ });
1078
+ };
1079
+ var collectSubscriptionPatches = (rootCtx, records, rootLimit) => {
1080
+ if (!records?.length) {
1081
+ return;
1082
+ }
1083
+ const patches = [];
1084
+ const patchesByRoot = /* @__PURE__ */ new Map();
1085
+ for (let i = 0; i < records.length; i++) {
1086
+ const entry = records[i];
1087
+ const rootId = entry.rootId === void 0 ? rootCtx.$hasRootId$(entry.rootObj) : entry.rootId;
1088
+ if (rootId === void 0 || rootId >= rootLimit) {
1089
+ continue;
1090
+ }
1091
+ let patch = patchesByRoot.get(rootId);
1092
+ if (!patch) {
1093
+ patch = new SubscriptionPatch(
1094
+ rootId,
1095
+ entry.prop === null ? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Map()
1096
+ );
1097
+ patchesByRoot.set(rootId, patch);
1098
+ patches.push(patch);
1099
+ }
1100
+ const subscriptions = patch.subscriptions;
1101
+ if (entry.prop === null) {
1102
+ if (subscriptions instanceof Set) {
1103
+ subscriptions.add(entry.effect);
1104
+ }
1105
+ } else {
1106
+ if (subscriptions instanceof Map) {
1107
+ let effects = subscriptions.get(entry.prop);
1108
+ if (!effects) {
1109
+ effects = /* @__PURE__ */ new Set();
1110
+ subscriptions.set(entry.prop, effects);
1111
+ }
1112
+ effects.add(entry.effect);
1113
+ }
1114
+ }
1115
+ }
1116
+ return patches.length ? patches : void 0;
1117
+ };
1118
+
1119
+ // packages/qwik/src/server/preload-impl.ts
1120
+ import { getPlatform } from "@qwik.dev/core";
1121
+ var simplifyPath = (base2, path) => {
1122
+ if (path == null) {
1123
+ return null;
1124
+ }
1125
+ const segments = `${base2}${path}`.split("/");
1126
+ const simplified = [];
1127
+ for (let i = 0; i < segments.length; i++) {
1128
+ const segment = segments[i];
1129
+ if (segment === ".." && simplified.length > 0) {
1130
+ simplified.pop();
1131
+ } else {
1132
+ simplified.push(segment);
1133
+ }
1134
+ }
1135
+ return simplified.join("/");
1136
+ };
1137
+ var getBase = (container) => {
1138
+ let base2 = container.$buildBase$;
1139
+ if (import.meta.env?.DEV && !qTest) {
1140
+ base2 = import.meta.env?.BASE_URL;
1141
+ }
1142
+ return base2;
1143
+ };
1144
+ var preloaderPre = (container, options, nonce) => {
1145
+ const { resolvedManifest } = container;
1146
+ const base2 = getBase(container);
1147
+ const preloaderBundle = simplifyPath(base2, resolvedManifest?.manifest?.preloader);
1148
+ let bundleGraphPath = resolvedManifest?.manifest.bundleGraphAsset;
1149
+ if (bundleGraphPath) {
1150
+ bundleGraphPath = (import.meta.env?.BASE_URL || "/") + bundleGraphPath;
1151
+ }
1152
+ if (!(import.meta.env?.DEV && !qTest) && preloaderBundle && bundleGraphPath && options !== false) {
1153
+ const bundleGraph = container.resolvedManifest?.manifest.bundleGraph;
1154
+ initPreloader(bundleGraph);
1155
+ const opts = [];
1156
+ if (options) {
1157
+ if (options.maxIdlePreloads) {
1158
+ opts.push(`P:${options.maxIdlePreloads}`);
1159
+ }
1160
+ }
1161
+ const optsStr = opts.length ? `,{${opts.join(",")}}` : "";
1162
+ const preloaderLinkAttrs = {
1163
+ rel: "modulepreload",
1164
+ href: preloaderBundle
1165
+ };
1166
+ if (nonce) {
1167
+ preloaderLinkAttrs["nonce"] = nonce;
1168
+ }
1169
+ container.openElement("link", null, preloaderLinkAttrs, null, null, null);
1170
+ container.closeElement();
1171
+ container.openElement(
1172
+ "link",
1173
+ null,
1174
+ { rel: "preload", href: bundleGraphPath, as: "fetch", crossorigin: "anonymous" },
1175
+ null,
1176
+ null,
1177
+ null
1178
+ );
1179
+ container.closeElement();
1180
+ const script = `let b=fetch("${bundleGraphPath}");import("${preloaderBundle}").then(({l})=>l(${JSON.stringify(base2)},b${optsStr}));`;
1181
+ const scriptAttrs = {
1182
+ type: "module",
1183
+ async: true,
1184
+ crossorigin: "anonymous"
1185
+ };
1186
+ if (nonce) {
1187
+ scriptAttrs["nonce"] = nonce;
1188
+ }
1189
+ container.writeScript(scriptAttrs, script);
1190
+ }
1191
+ const corePath = simplifyPath(base2, resolvedManifest?.manifest.core);
1192
+ if (corePath) {
1193
+ const linkAttrs = { rel: "modulepreload", href: corePath };
1194
+ if (nonce) {
1195
+ linkAttrs["nonce"] = nonce;
1196
+ }
1197
+ container.openElement("link", null, linkAttrs, null, null, null);
1198
+ container.closeElement();
1199
+ }
1200
+ };
1201
+ var includePreloader = (container, options, referencedBundles, nonce) => {
1202
+ if (referencedBundles.length === 0 || options === false) {
1203
+ return null;
1204
+ }
1205
+ const { ssrPreloads } = normalizePreLoaderOptions(
1206
+ typeof options === "boolean" ? void 0 : options
1207
+ );
1208
+ let allowedSsrPreloads = ssrPreloads;
1209
+ const base2 = getBase(container);
1210
+ const links = [];
1211
+ const { resolvedManifest } = container;
1212
+ if (allowedSsrPreloads) {
1213
+ const preloaderBundle2 = resolvedManifest?.manifest.preloader;
1214
+ const coreBundle = resolvedManifest?.manifest.core;
1215
+ for (let i = 0; i < referencedBundles.length; i++) {
1216
+ const href = referencedBundles[i];
1217
+ if (href === preloaderBundle2 || href === coreBundle) {
1218
+ continue;
1219
+ }
1220
+ links.push(href);
1221
+ if (--allowedSsrPreloads === 0) {
1222
+ break;
1223
+ }
1224
+ }
1225
+ }
1226
+ const preloaderBundle = simplifyPath(base2, resolvedManifest?.manifest.preloader);
1227
+ const insertLinks = links.length ? (
1228
+ /**
1229
+ * We only use modulepreload links because they behave best. Older browsers can rely on the
1230
+ * preloader which does feature detection and which will be available soon after inserting these
1231
+ * links.
1232
+ */
1233
+ `${JSON.stringify(links)}.map((l,e)=>{e=document.createElement('link');e.rel='modulepreload';e.href=${JSON.stringify(base2)}+l;document.head.appendChild(e)});`
1234
+ ) : "";
1235
+ let script = insertLinks;
1236
+ if (preloaderBundle) {
1237
+ script += `window.addEventListener('load',f=>{f=_=>import("${preloaderBundle}").then(({p})=>p(${JSON.stringify(referencedBundles)}));try{requestIdleCallback(f,{timeout:2000})}catch(e){setTimeout(f,200)}})`;
1238
+ }
1239
+ if (script) {
1240
+ const attrs = { type: "module", async: "true", "q:type": "preload" };
1241
+ if (nonce) {
1242
+ attrs["nonce"] = nonce;
1243
+ }
1244
+ container.writeScript(attrs, script);
1245
+ }
1246
+ return null;
1247
+ };
1248
+ var preloaderPost = (ssrContainer, opts, nonce) => {
1249
+ if (import.meta.env?.DEV && !qTest) {
1250
+ return;
1251
+ }
1252
+ if (opts.preloader !== false) {
1253
+ const qrls = Array.from(ssrContainer.serializationCtx.$eventQrls$);
1254
+ const preloadBundles = getBundles(qrls);
1255
+ includePreloader(ssrContainer, opts.preloader, preloadBundles, nonce);
1256
+ }
1257
+ };
1258
+ function normalizePreLoaderOptions(input) {
1259
+ return { ...preLoaderOptionsDefault, ...input };
1260
+ }
1261
+ var getBundles = (qrls) => {
1262
+ const platform = getPlatform();
1263
+ const bundles = qrls?.map((qrl) => {
1264
+ const symbol = qrl.$symbol$;
1265
+ const chunk = qrl.$chunk$;
1266
+ const result = platform.chunkForSymbol(symbol, chunk, qrl.dev?.file);
1267
+ if (result) {
1268
+ return result[1];
1269
+ }
1270
+ return chunk;
1271
+ }).filter(Boolean);
1272
+ return [...new Set(bundles)];
1273
+ };
1274
+ var preLoaderOptionsDefault = {
1275
+ ssrPreloads: 7,
1276
+ maxIdlePreloads: 25
1277
+ };
1142
1278
 
1143
1279
  // packages/qwik/src/server/scripts.ts
1144
- var QWIK_LOADER_DEFAULT_MINIFIED = 'const t=document,e=window,n=new Set,o=new Set([t]);let r;const s=(t,e)=>Array.from(t.querySelectorAll(e)),i=t=>{const e=[];return o.forEach(n=>e.push(...s(n,t))),e},a=t=>{v(t),s(t,"[q\\\\:shadowroot]").forEach(t=>{const e=t.shadowRoot;e&&a(e)})},c=t=>t&&"function"==typeof t.then;let l=!0;const f=(t,e,n=e.type)=>{let o=l;i("[on"+t+"\\\\:"+n+"]").forEach(r=>{o=!0,b(r,t,e,n)}),o||window[t.slice(1)].removeEventListener(n,"-window"===t?d:_)},p=e=>{if(void 0===e._qwikjson_){let n=(e===t.documentElement?t.body:e).lastElementChild;for(;n;){if("SCRIPT"===n.tagName&&"qwik/json"===n.getAttribute("type")){e._qwikjson_=JSON.parse(n.textContent.replace(/\\\\x3C(\\/?script)/gi,"<$1"));break}n=n.previousElementSibling}}},u=(t,e)=>new CustomEvent(t,{detail:e}),b=async(e,n,o,r=o.type)=>{const s="on"+n+":"+r;e.hasAttribute("preventdefault:"+r)&&o.preventDefault(),e.hasAttribute("stoppropagation:"+r)&&o.stopPropagation();const i=e._qc_,a=i&&i.li.filter(t=>t[0]===s);if(a&&a.length>0){for(const t of a){const n=t[1].getFn([e,o],()=>e.isConnected)(o,e),r=o.cancelBubble;c(n)&&await n,r&&o.stopPropagation()}return}const l=e.getAttribute(s),f=e.qDispatchEvent;if(f)return f(o,n);if(l){const n=e.closest("[q\\\\:container]:not([q\\\\:container=html]):not([q\\\\:container=text])"),r=n.getAttribute("q:base"),s=n.getAttribute("q:version")||"unknown",i=n.getAttribute("q:manifest-hash")||"dev",a=new URL(r,t.baseURI);for(const f of l.split("\\n")){const l=new URL(f,a),u=l.href,b=l.hash.replace(/^#?([^?[|]*).*$/,"$1")||"default",h=performance.now();let _,d,w;const m=f.startsWith("#"),y={qBase:r,qManifest:i,qVersion:s,href:u,symbol:b,element:e,reqTime:h};if(m){const e=n.getAttribute("q:instance");_=(t["qFuncs_"+e]||[])[Number.parseInt(b)],_||(d="sync",w=Error("sym:"+b))}else{q("qsymbol",y);const t=l.href.split("#")[0];try{const e=import(t);p(n),_=(await e)[b],_||(d="no-symbol",w=Error(`${b} not in ${t}`))}catch(t){d||(d="async"),w=t}}if(!_){q("qerror",{importError:d,error:w,...y}),console.error(w);break}const v=t.__q_context__;if(e.isConnected)try{t.__q_context__=[e,o,l];const n=_(o,e);c(n)&&await n}catch(t){q("qerror",{error:t,...y})}finally{t.__q_context__=v}}}},q=(e,n)=>{t.dispatchEvent(u(e,n))},h=t=>t.replace(/([A-Z])/g,t=>"-"+t.toLowerCase()),_=async t=>{let e=h(t.type),n=t.target;for(f("-document",t,e);n&&n.getAttribute;){const o=b(n,"",t,e);let r=t.cancelBubble;c(o)&&await o,r||(r=r||t.cancelBubble||n.hasAttribute("stoppropagation:"+t.type)),n=t.bubbles&&!0!==r?n.parentElement:null}},d=t=>{f("-window",t,h(t.type))},w=()=>{var s;const c=t.readyState;if(!r&&("interactive"==c||"complete"==c)&&(o.forEach(a),r=1,q("qinit"),(null!=(s=e.requestIdleCallback)?s:e.setTimeout).bind(e)(()=>q("qidle")),n.has("qvisible"))){const t=i("[on\\\\:qvisible]"),e=new IntersectionObserver(t=>{for(const n of t)n.isIntersecting&&(e.unobserve(n.target),b(n.target,"",u("qvisible",n)))});t.forEach(t=>e.observe(t))}},m=(t,e,n,o=!1)=>{t.addEventListener(e,n,{capture:o,passive:!1})};let y;const v=(...t)=>{l=!0,clearTimeout(y),y=setTimeout(()=>l=!1,2e4);for(const r of t)"string"==typeof r?n.has(r)||(o.forEach(t=>m(t,r,_,!0)),m(e,r,d,!0),n.add(r)):o.has(r)||(n.forEach(t=>m(r,t,_,!0)),o.add(r))};if(!("__q_context__"in t)){t.__q_context__=0;const r=e.qwikevents;r&&(Array.isArray(r)?v(...r):v("click","input")),e.qwikevents={events:n,roots:o,push:v},m(t,"readystatechange",w),w()}';
1145
- var QWIK_LOADER_DEFAULT_DEBUG = 'const doc = document;\nconst win = window;\nconst events = /* @__PURE__ */ new Set();\nconst roots = /* @__PURE__ */ new Set([doc]);\nlet hasInitialized;\nconst nativeQuerySelectorAll = (root, selector) => Array.from(root.querySelectorAll(selector));\nconst querySelectorAll = (query) => {\n const elements = [];\n roots.forEach((root) => elements.push(...nativeQuerySelectorAll(root, query)));\n return elements;\n};\nconst findShadowRoots = (fragment) => {\n processEventOrNode(fragment);\n nativeQuerySelectorAll(fragment, "[q\\\\:shadowroot]").forEach((parent) => {\n const shadowRoot = parent.shadowRoot;\n shadowRoot && findShadowRoots(shadowRoot);\n });\n};\nconst isPromise = (promise) => promise && typeof promise.then === "function";\nlet doNotClean = true;\nconst broadcast = (infix, ev, type = ev.type) => {\n let found = doNotClean;\n querySelectorAll("[on" + infix + "\\\\:" + type + "]").forEach((el) => {\n found = true;\n dispatch(el, infix, ev, type);\n });\n if (!found) {\n window[infix.slice(1)].removeEventListener(\n type,\n infix === "-window" ? processWindowEvent : processDocumentEvent\n );\n }\n};\nconst resolveContainer = (containerEl) => {\n if (containerEl._qwikjson_ === void 0) {\n const parentJSON = containerEl === doc.documentElement ? doc.body : containerEl;\n let script = parentJSON.lastElementChild;\n while (script) {\n if (script.tagName === "SCRIPT" && script.getAttribute("type") === "qwik/json") {\n containerEl._qwikjson_ = JSON.parse(\n script.textContent.replace(/\\\\x3C(\\/?script)/gi, "<$1")\n );\n break;\n }\n script = script.previousElementSibling;\n }\n }\n};\nconst createEvent = (eventName, detail) => new CustomEvent(eventName, {\n detail\n});\nconst dispatch = async (element, scope, ev, eventName = ev.type) => {\n const attrName = "on" + scope + ":" + eventName;\n if (element.hasAttribute("preventdefault:" + eventName)) {\n ev.preventDefault();\n }\n if (element.hasAttribute("stoppropagation:" + eventName)) {\n ev.stopPropagation();\n }\n const ctx = element._qc_;\n const relevantListeners = ctx && ctx.li.filter((li) => li[0] === attrName);\n if (relevantListeners && relevantListeners.length > 0) {\n for (const listener of relevantListeners) {\n const results = listener[1].getFn([element, ev], () => element.isConnected)(ev, element);\n const cancelBubble = ev.cancelBubble;\n if (isPromise(results)) {\n await results;\n }\n if (cancelBubble) {\n ev.stopPropagation();\n }\n }\n return;\n }\n const attrValue = element.getAttribute(attrName);\n const qDispatchEvent = element.qDispatchEvent;\n if (qDispatchEvent) {\n return qDispatchEvent(ev, scope);\n }\n if (attrValue) {\n const container = element.closest(\n "[q\\\\:container]:not([q\\\\:container=html]):not([q\\\\:container=text])"\n );\n const qBase = container.getAttribute("q:base");\n const qVersion = container.getAttribute("q:version") || "unknown";\n const qManifest = container.getAttribute("q:manifest-hash") || "dev";\n const base = new URL(qBase, doc.baseURI);\n for (const qrl of attrValue.split("\\n")) {\n const url = new URL(qrl, base);\n const href = url.href;\n const symbol = url.hash.replace(/^#?([^?[|]*).*$/, "$1") || "default";\n const reqTime = performance.now();\n let handler;\n let importError;\n let error;\n const isSync = qrl.startsWith("#");\n const eventData = {\n qBase,\n qManifest,\n qVersion,\n href,\n symbol,\n element,\n reqTime\n };\n if (isSync) {\n const hash = container.getAttribute("q:instance");\n handler = (doc["qFuncs_" + hash] || [])[Number.parseInt(symbol)];\n if (!handler) {\n importError = "sync";\n error = new Error("sym:" + symbol);\n }\n } else {\n emitEvent("qsymbol", eventData);\n const uri = url.href.split("#")[0];\n try {\n const module = import(\n uri\n );\n resolveContainer(container);\n handler = (await module)[symbol];\n if (!handler) {\n importError = "no-symbol";\n error = new Error(`${symbol} not in ${uri}`);\n }\n } catch (err) {\n importError || (importError = "async");\n error = err;\n }\n }\n if (!handler) {\n emitEvent("qerror", {\n importError,\n error,\n ...eventData\n });\n console.error(error);\n break;\n }\n const previousCtx = doc.__q_context__;\n if (element.isConnected) {\n try {\n doc.__q_context__ = [element, ev, url];\n const results = handler(ev, element);\n if (isPromise(results)) {\n await results;\n }\n } catch (error2) {\n emitEvent("qerror", { error: error2, ...eventData });\n } finally {\n doc.__q_context__ = previousCtx;\n }\n }\n }\n }\n};\nconst emitEvent = (eventName, detail) => {\n doc.dispatchEvent(createEvent(eventName, detail));\n};\nconst camelToKebab = (str) => str.replace(/([A-Z])/g, (a) => "-" + a.toLowerCase());\nconst processDocumentEvent = async (ev) => {\n let type = camelToKebab(ev.type);\n let element = ev.target;\n broadcast("-document", ev, type);\n while (element && element.getAttribute) {\n const results = dispatch(element, "", ev, type);\n let cancelBubble = ev.cancelBubble;\n if (isPromise(results)) {\n await results;\n }\n cancelBubble || (cancelBubble = cancelBubble || ev.cancelBubble || element.hasAttribute("stoppropagation:" + ev.type));\n element = ev.bubbles && cancelBubble !== true ? element.parentElement : null;\n }\n};\nconst processWindowEvent = (ev) => {\n broadcast("-window", ev, camelToKebab(ev.type));\n};\nconst processReadyStateChange = () => {\n var _a;\n const readyState = doc.readyState;\n if (!hasInitialized && (readyState == "interactive" || readyState == "complete")) {\n roots.forEach(findShadowRoots);\n hasInitialized = 1;\n emitEvent("qinit");\n const riC = (_a = win.requestIdleCallback) != null ? _a : win.setTimeout;\n riC.bind(win)(() => emitEvent("qidle"));\n if (events.has("qvisible")) {\n const results = querySelectorAll("[on\\\\:qvisible]");\n const observer = new IntersectionObserver((entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n observer.unobserve(entry.target);\n dispatch(entry.target, "", createEvent("qvisible", entry));\n }\n }\n });\n results.forEach((el) => observer.observe(el));\n }\n }\n};\nconst addEventListener = (el, eventName, handler, capture = false) => {\n el.addEventListener(eventName, handler, { capture, passive: false });\n};\nlet cleanTimer;\nconst processEventOrNode = (...eventNames) => {\n doNotClean = true;\n clearTimeout(cleanTimer);\n cleanTimer = setTimeout(() => doNotClean = false, 2e4);\n for (const eventNameOrNode of eventNames) {\n if (typeof eventNameOrNode === "string") {\n if (!events.has(eventNameOrNode)) {\n roots.forEach(\n (root) => addEventListener(root, eventNameOrNode, processDocumentEvent, true)\n );\n addEventListener(win, eventNameOrNode, processWindowEvent, true);\n events.add(eventNameOrNode);\n }\n } else {\n if (!roots.has(eventNameOrNode)) {\n events.forEach(\n (eventName) => addEventListener(eventNameOrNode, eventName, processDocumentEvent, true)\n );\n roots.add(eventNameOrNode);\n }\n }\n }\n};\nif (!("__q_context__" in doc)) {\n doc.__q_context__ = 0;\n const qwikevents = win.qwikevents;\n if (qwikevents) {\n if (Array.isArray(qwikevents)) {\n processEventOrNode(...qwikevents);\n } else {\n processEventOrNode("click", "input");\n }\n }\n win.qwikevents = {\n events,\n roots,\n push: processEventOrNode\n };\n addEventListener(doc, "readystatechange", processReadyStateChange);\n processReadyStateChange();\n}';
1280
+ var QWIK_LOADER_DEFAULT_MINIFIED = 'var e,t,n,r=document,o=window,s="w",i="wp",a="d",c="dp",l="e",p="ep",u="capture:",d="readystatechange",f=0,h=new Set,q=new Set([r]),b=new Map,g={},m=(e,t)=>Array.from(e.querySelectorAll(t)),v=e=>{const t=[];return q.forEach(n=>t.push(...m(n,e))),t},w=(e,t,n,r=!1,o=!1)=>e.addEventListener(t,n,{capture:r,passive:o}),y=e=>{H(e);const t=m(e,"[q\\\\:shadowroot]");for(let e=0;e<t.length;e++){const n=t[e].shadowRoot;n&&y(n)}},A=e=>e&&"function"==typeof e.then,E=async e=>{for(let t=0;t<e.length;t++)await e[t]()},S=e=>{if(e.length){const t=()=>E(e);n=n?n.then(t,t):t()}},C=e=>{if(void 0===e._qwikjson_){let t=(e===r.documentElement?r.body:e).lastElementChild;for(;t;){if("SCRIPT"===t.tagName&&"qwik/json"===t.getAttribute("type")){e._qwikjson_=JSON.parse(t.textContent.replace(/\\\\x3C(\\/?script)/gi,"<$1"));break}t=t.previousElementSibling}}},_=e=>{g[e]=1,I(d)},k=e=>{const t=e.getAttribute("q:instance");return"paused"===e.getAttribute("q:container")&&"loading"===r.readyState&&!g[t]&&new Promise(e=>{w(r,d,()=>{("loading"!==r.readyState||g[t])&&e()})})},$=(e,t)=>new CustomEvent(e,{detail:t}),I=(e,t)=>{r.dispatchEvent($(e,t))},N=e=>e.replace(/([A-Z-])/g,e=>"-"+e.toLowerCase()),R=e=>e.replace(/-./g,e=>e[1].toUpperCase()),T=e=>{const t=e.indexOf(":");return{scope:e.slice(0,t),eventName:R(e.slice(t+1))}},x=e=>2===e.length,B=e=>e.charAt(0),L=e=>!!e&&1===e.nodeType,U=(e,t,n)=>e.hasAttribute(n)&&(!!e._qDispatch?.[t]||e.hasAttribute("q-"+t)),j=(e,t,n,o,s,i,a,c=!0)=>{const l={qBase:n,symbol:i,element:t,reqTime:a};if(!s){const t=(r["qFuncs_"+e.getAttribute("q:instance")]||[])[+i];if(!t&&c){const e=Error("sym:"+i);I("qerror",{importError:"sync",error:e,...l}),console.error(e)}return t}const p=`${i}|${n}|${s}`,u=b.get(p);if(u)return u;const d=new URL(s,o).href,f=import(d);return C(e),f.then(e=>{const t=e[i];if(t)b.set(p,t),I("qsymbol",l);else{const e=Error(`${i} not in ${d}`);I("qerror",{importError:"no-symbol",error:e,...l}),console.error(e)}return t},e=>{I("qerror",{importError:"async",error:e,...l}),console.error(e)})},D=(e,t,n,o,s,i=!0)=>{let a=!1;s&&(i&&e.hasAttribute("preventdefault:"+s)&&t.preventDefault(),e.hasAttribute("stoppropagation:"+s)&&t.stopPropagation());const c=e._qDispatch?.[n];if(c){if("function"==typeof c){const n=()=>c(t,e);if(a)o.push(async()=>{const e=n();A(e)&&await e});else{const e=n();A(e)&&(a=!0,o.push(()=>e))}}else if(c.length)for(let n=0;n<c.length;n++){const r=c[n];if(r){const n=()=>r(t,e);if(a)o.push(async()=>{const e=n();A(e)&&await e});else{const e=n();A(e)&&(a=!0,o.push(()=>e))}}}return}const l=e.getAttribute("q-"+n);if(l){const n=e.closest("[q\\\\:container]:not([q\\\\:container=html]):not([q\\\\:container=text])"),s=n.getAttribute("q:base"),i=new URL(s,r.baseURI),c=l.split("|"),p=k(n);for(let r=0;r<c.length;r++){const l=c[r],u=performance.now(),[d,f,h]=l.split("#"),q=n=>{if(n&&e.isConnected){const r=t=>{I("qerror",{error:t,qBase:s,symbol:f,element:e,reqTime:u})};try{const o=n.call(h,t,e);if(A(o))return o.catch(r)}catch(e){return r(e)}}},b=(t=!0)=>j(n,e,s,i,d,f,u,t),g=p?void 0:b();if(p)a=!0,o.push(async()=>{await p,await q(await b(!1)||await b())});else if(A(g))a=!0,o.push(()=>g.then(q));else if(a)a=!0,o.push(async()=>{await q(g||await b())});else{const e=q(g);A(e)&&(a=!0,o.push(()=>e))}}}},O=(e,t=l,n=!0)=>{const r=N(e.type),o=t+":"+r,s=u+r,i=[],a=[],c=[];let p=e.target;for(;p;)L(p)?(i.push(p),a.push(U(p,o,s)),p=p.parentElement):p=p.parentElement;for(let t=i.length-1;t>=0;t--)if(a[t]&&(D(i[t],e,o,c,r,n),e.cancelBubble))return void S(c);for(let t=0;t<i.length;t++)if(!a[t]&&(D(i[t],e,o,c,r,n),!e.bubbles||e.cancelBubble))return void S(c);S(c)},P=e=>O(e,p,!1),F=(e,t,n=!0)=>{const r=N(t.type),o=e+":"+r,s=v("[q-"+CSS.escape(o)+"]"),i=[];for(let e=0;e<s.length;e++){const a=s[e];D(a,t,o,i,r,n)}S(i)},J=e=>{F(a,e)},M=e=>{F(c,e,!1)},Z=e=>{F(s,e)},z=e=>{F(i,e,!1)},G=()=>{const n=r.readyState;if("interactive"==n||"complete"==n){if(t=1,q.forEach(y),h.has("d:qinit")){h.delete("d:qinit");const e=$("qinit"),t=v("[q-d\\\\:qinit]"),n=[];for(let r=0;r<t.length;r++){const o=t[r];D(o,e,"d:qinit",n),o.removeAttribute("q-d:qinit")}S(n)}if(h.has("d:qidle")&&(h.delete("d:qidle"),(o.requestIdleCallback??o.setTimeout).bind(o)(()=>{const e=$("qidle"),t=v("[q-d\\\\:qidle]"),n=[];for(let r=0;r<t.length;r++){const o=t[r];D(o,e,"d:qidle",n),o.removeAttribute("q-d:qidle")}S(n)})),h.has("e:qvisible")){e||(e=new IntersectionObserver(t=>{const n=[];for(let r=0;r<t.length;r++){const o=t[r];o.isIntersecting&&(e.unobserve(o.target),D(o.target,$("qvisible",o),"e:qvisible",n))}S(n)}));const t=v("[q-e\\\\:qvisible]:not([q\\\\:observed])");for(let n=0;n<t.length;n++){const r=t[n];e.observe(r),r.setAttribute("q:observed","true")}}}},H=(...e)=>{for(let n=0;n<e.length;n++){const r=e[n];if(r===f)_(e[++n]);else if("string"==typeof r){if(!h.has(r)){h.add(r);const{scope:e,eventName:n}=T(r),i=x(e),c=B(e);c===s?w(o,n,i?z:Z,!0,i):q.forEach(e=>w(e,n,c===a?i?M:J:i?P:O,!0,i)),1!==t||"e:qvisible"!==r&&"d:qinit"!==r&&"d:qidle"!==r||G()}}else q.has(r)||(h.forEach(e=>{const{scope:t,eventName:n}=T(e),o=x(t),i=B(t);i!==s&&w(r,n,i===a?o?M:J:o?P:O,!0,o)}),q.add(r))}},K=o._qwikEv;K?.roots||(Array.isArray(K)?H(...K):H("e:click","e:input"),o._qwikEv={events:h,roots:q,push:H},w(r,d,G),G())';
1281
+ var QWIK_LOADER_DEFAULT_DEBUG = '//#region packages/qwik/src/qwikloader.ts\nvar doc = document;\nvar win = window;\nvar windowPrefix = "w";\nvar passiveWindowPrefix = "wp";\nvar documentPrefix = "d";\nvar passiveDocumentPrefix = "dp";\nvar elementPrefix = "e";\nvar passiveElementPrefix = "ep";\nvar capturePrefix = "capture:";\nvar readyStateChange = "readystatechange";\nvar QwikEvContainerReady = 0;\nvar events = /* @__PURE__ */ new Set();\nvar roots = /* @__PURE__ */ new Set([doc]);\nvar symbols = /* @__PURE__ */ new Map();\nvar readyContainers = {};\nvar observer;\nvar hasInitialized;\nvar queuedTasks;\nvar nativeQuerySelectorAll = (root, selector) => Array.from(root.querySelectorAll(selector));\nvar querySelectorAll = (query) => {\n const elements = [];\n roots.forEach((root) => elements.push(...nativeQuerySelectorAll(root, query)));\n return elements;\n};\nvar addEventListener = (el, eventName, handler, capture = false, passive = false) => el.addEventListener(eventName, handler, {\n capture,\n passive\n});\nvar findShadowRoots = (fragment) => {\n addEventOrRoot(fragment);\n const shadowRoots = nativeQuerySelectorAll(fragment, "[q\\\\:shadowroot]");\n for (let i = 0; i < shadowRoots.length; i++) {\n const shadowRoot = shadowRoots[i].shadowRoot;\n shadowRoot && findShadowRoots(shadowRoot);\n }\n};\nvar isPromise = (promise) => promise && typeof promise.then === "function";\nvar runTasks = async (tasks) => {\n for (let i = 0; i < tasks.length; i++) await tasks[i]();\n};\nvar queueTasks = (tasks) => {\n if (tasks.length) {\n const run = () => runTasks(tasks);\n queuedTasks = queuedTasks ? queuedTasks.then(run, run) : run();\n }\n};\nvar resolveContainer = (containerEl) => {\n if (containerEl._qwikjson_ === void 0) {\n let script = (containerEl === doc.documentElement ? doc.body : containerEl).lastElementChild;\n while (script) {\n if (script.tagName === "SCRIPT" && script.getAttribute("type") === "qwik/json") {\n containerEl._qwikjson_ = JSON.parse(script.textContent.replace(/\\\\x3C(\\/?script)/gi, "<$1"));\n break;\n }\n script = script.previousElementSibling;\n }\n }\n};\nvar markContainerReady = (hash) => {\n readyContainers[hash] = 1;\n emitEvent(readyStateChange);\n};\nvar waitForContainerReady = (container) => {\n const hash = container.getAttribute("q:instance");\n return container.getAttribute("q:container") === "paused" && doc.readyState === "loading" && !readyContainers[hash] && new Promise((resolve) => {\n const ready = () => {\n if (doc.readyState !== "loading" || readyContainers[hash]) resolve();\n };\n addEventListener(doc, readyStateChange, ready);\n });\n};\nvar createEvent = (eventName, detail) => new CustomEvent(eventName, { detail });\nvar emitEvent = (eventName, detail) => {\n doc.dispatchEvent(createEvent(eventName, detail));\n};\nvar camelToKebab = (str) => str.replace(/([A-Z-])/g, (a) => "-" + a.toLowerCase());\nvar kebabToCamel = (eventName) => eventName.replace(/-./g, (a) => a[1].toUpperCase());\nvar parseKebabEvent = (event) => {\n const separatorIndex = event.indexOf(":");\n return {\n scope: event.slice(0, separatorIndex),\n eventName: kebabToCamel(event.slice(separatorIndex + 1))\n };\n};\nvar isPassiveScope = (scope) => scope.length === 2;\nvar getRootScope = (scope) => scope.charAt(0);\nvar isElementNode = (node) => !!node && node.nodeType === 1;\nvar isCaptureHandlerElement = (element, scopedKebabName, captureAttribute) => element.hasAttribute(captureAttribute) && (!!element._qDispatch?.[scopedKebabName] || element.hasAttribute("q-" + scopedKebabName));\nvar resolveHandler = (container, element, qBase, base, chunk, symbol, reqTime, reportSyncError = true) => {\n const eventData = {\n qBase,\n symbol,\n element,\n reqTime\n };\n if (!chunk) {\n const handler = (doc["qFuncs_" + container.getAttribute("q:instance")] || [])[+symbol];\n if (!handler && reportSyncError) {\n const error = /* @__PURE__ */ new Error("sym:" + symbol);\n emitEvent("qerror", {\n importError: "sync",\n error,\n ...eventData\n });\n console.error(error);\n }\n return handler;\n }\n const key = `${symbol}|${qBase}|${chunk}`;\n const handler = symbols.get(key);\n if (handler) return handler;\n const href = new URL(chunk, base).href;\n const module = import(\n href\n);\n resolveContainer(container);\n return module.then((module) => {\n const handler = module[symbol];\n if (!handler) {\n const error = /* @__PURE__ */ new Error(`${symbol} not in ${href}`);\n emitEvent("qerror", {\n importError: "no-symbol",\n error,\n ...eventData\n });\n console.error(error);\n } else {\n symbols.set(key, handler);\n emitEvent("qsymbol", eventData);\n }\n return handler;\n }, (error) => {\n emitEvent("qerror", {\n importError: "async",\n error,\n ...eventData\n });\n console.error(error);\n });\n};\n/**\n* Dispatch an event by invoking QRL handlers. If there are multiple handlers, they are awaited in\n* order.\n*/\nvar dispatch = (element, ev, scopedKebabName, tasks, kebabName, allowPreventDefault = true) => {\n let defer = false;\n if (kebabName) {\n if (allowPreventDefault && element.hasAttribute("preventdefault:" + kebabName)) ev.preventDefault();\n if (element.hasAttribute("stoppropagation:" + kebabName)) ev.stopPropagation();\n }\n const handlers = element._qDispatch?.[scopedKebabName];\n if (handlers) {\n if (typeof handlers === "function") {\n const run = () => handlers(ev, element);\n if (defer) tasks.push(async () => {\n const result = run();\n if (isPromise(result)) await result;\n });\n else {\n const result = run();\n if (isPromise(result)) {\n defer = true;\n tasks.push(() => result);\n }\n }\n } else if (handlers.length) for (let i = 0; i < handlers.length; i++) {\n const handler = handlers[i];\n if (handler) {\n const run = () => handler(ev, element);\n if (defer) tasks.push(async () => {\n const result = run();\n if (isPromise(result)) await result;\n });\n else {\n const result = run();\n if (isPromise(result)) {\n defer = true;\n tasks.push(() => result);\n }\n }\n }\n }\n return;\n }\n const attrValue = element.getAttribute("q-" + scopedKebabName);\n if (attrValue) {\n const container = element.closest("[q\\\\:container]:not([q\\\\:container=html]):not([q\\\\:container=text])");\n const qBase = container.getAttribute("q:base");\n const base = new URL(qBase, doc.baseURI);\n const qrls = attrValue.split("|");\n const waitForReady = waitForContainerReady(container);\n for (let i = 0; i < qrls.length; i++) {\n const qrl = qrls[i];\n const reqTime = performance.now();\n const [chunk, symbol, capturedIds] = qrl.split("#");\n const run = (handler) => {\n if (handler && element.isConnected) {\n const onError = (error) => {\n emitEvent("qerror", {\n error,\n qBase,\n symbol,\n element,\n reqTime\n });\n };\n try {\n const result = handler.call(capturedIds, ev, element);\n if (isPromise(result)) return result.catch(onError);\n } catch (error) {\n return onError(error);\n }\n }\n };\n const resolve = (reportSyncError = true) => resolveHandler(container, element, qBase, base, chunk, symbol, reqTime, reportSyncError);\n const handler = waitForReady ? void 0 : resolve();\n if (waitForReady) {\n defer = true;\n tasks.push(async () => {\n await waitForReady;\n await run(await resolve(false) || await resolve());\n });\n } else if (isPromise(handler)) {\n defer = true;\n tasks.push(() => handler.then(run));\n } else if (defer) {\n defer = true;\n tasks.push(async () => {\n await run(handler || await resolve());\n });\n } else {\n const result = run(handler);\n if (isPromise(result)) {\n defer = true;\n tasks.push(() => result);\n }\n }\n }\n }\n};\n/**\n* Event handler responsible for processing element events.\n*\n* If browser emits an event, the `eventProcessor` walks the DOM tree looking for corresponding\n* `(${event.type})`. If found the event\'s URL is parsed and `import()`ed.\n*\n* @param ev - Browser event.\n*/\nvar processElementEvent = (ev, scope = elementPrefix, allowPreventDefault = true) => {\n const kebabName = camelToKebab(ev.type);\n const scopedKebabName = scope + ":" + kebabName;\n const captureAttribute = capturePrefix + kebabName;\n const elements = [];\n const captureHandlers = [];\n const tasks = [];\n let current = ev.target;\n while (current) if (isElementNode(current)) {\n elements.push(current);\n captureHandlers.push(isCaptureHandlerElement(current, scopedKebabName, captureAttribute));\n current = current.parentElement;\n } else current = current.parentElement;\n for (let i = elements.length - 1; i >= 0; i--) if (captureHandlers[i]) {\n dispatch(elements[i], ev, scopedKebabName, tasks, kebabName, allowPreventDefault);\n if (ev.cancelBubble) {\n queueTasks(tasks);\n return;\n }\n }\n for (let i = 0; i < elements.length; i++) if (!captureHandlers[i]) {\n dispatch(elements[i], ev, scopedKebabName, tasks, kebabName, allowPreventDefault);\n if (!ev.bubbles || ev.cancelBubble) {\n queueTasks(tasks);\n return;\n }\n }\n queueTasks(tasks);\n};\nvar processPassiveElementEvent = (ev) => processElementEvent(ev, passiveElementPrefix, false);\nvar broadcast = (scope, ev, allowPreventDefault = true) => {\n const kebabName = camelToKebab(ev.type);\n const scopedKebabName = scope + ":" + kebabName;\n const elements = querySelectorAll("[q-" + CSS.escape(scopedKebabName) + "]");\n const tasks = [];\n for (let i = 0; i < elements.length; i++) {\n const el = elements[i];\n dispatch(el, ev, scopedKebabName, tasks, kebabName, allowPreventDefault);\n }\n queueTasks(tasks);\n};\n/**\n* Event handler responsible for processing browser events.\n*\n* If browser emits an event, the `eventProcessor` walks the DOM tree looking for corresponding\n* `(${event.type})`. If found the event\'s URL is parsed and `import()`ed.\n*\n* @param ev - Browser event.\n*/\nvar processDocumentEvent = (ev) => {\n broadcast(documentPrefix, ev);\n};\nvar processPassiveDocumentEvent = (ev) => {\n broadcast(passiveDocumentPrefix, ev, false);\n};\nvar processWindowEvent = (ev) => {\n broadcast(windowPrefix, ev);\n};\nvar processPassiveWindowEvent = (ev) => {\n broadcast(passiveWindowPrefix, ev, false);\n};\n/**\n* Called when the document is ready and whenever a container is added, so make this idempotent. For\n* qidle and qinit we remove the attributes immediately, and for qvisible we add an attribute\n*/\nvar processReadyStateChange = () => {\n const readyState = doc.readyState;\n if (readyState == "interactive" || readyState == "complete") {\n hasInitialized = 1;\n roots.forEach(findShadowRoots);\n if (events.has("d:qinit")) {\n events.delete("d:qinit");\n const ev = createEvent("qinit");\n const elements = querySelectorAll("[q-d\\\\:qinit]");\n const tasks = [];\n for (let i = 0; i < elements.length; i++) {\n const el = elements[i];\n dispatch(el, ev, "d:qinit", tasks);\n el.removeAttribute("q-d:qinit");\n }\n queueTasks(tasks);\n }\n if (events.has("d:qidle")) {\n events.delete("d:qidle");\n (win.requestIdleCallback ?? win.setTimeout).bind(win)(() => {\n const ev = createEvent("qidle");\n const elements = querySelectorAll("[q-d\\\\:qidle]");\n const tasks = [];\n for (let i = 0; i < elements.length; i++) {\n const el = elements[i];\n dispatch(el, ev, "d:qidle", tasks);\n el.removeAttribute("q-d:qidle");\n }\n queueTasks(tasks);\n });\n }\n if (events.has("e:qvisible")) {\n observer || (observer = new IntersectionObserver((entries) => {\n const tasks = [];\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n if (entry.isIntersecting) {\n observer.unobserve(entry.target);\n dispatch(entry.target, createEvent("qvisible", entry), "e:qvisible", tasks);\n }\n }\n queueTasks(tasks);\n }));\n const elements = querySelectorAll("[q-e\\\\:qvisible]:not([q\\\\:observed])");\n for (let i = 0; i < elements.length; i++) {\n const el = elements[i];\n observer.observe(el);\n el.setAttribute("q:observed", "true");\n }\n }\n }\n};\nvar addEventOrRoot = (...eventNames) => {\n for (let i = 0; i < eventNames.length; i++) {\n const eventNameOrRoot = eventNames[i];\n if (eventNameOrRoot === QwikEvContainerReady) markContainerReady(eventNames[++i]);\n else if (typeof eventNameOrRoot === "string") {\n if (!events.has(eventNameOrRoot)) {\n events.add(eventNameOrRoot);\n const { scope, eventName } = parseKebabEvent(eventNameOrRoot);\n const passive = isPassiveScope(scope);\n const rootScope = getRootScope(scope);\n if (rootScope === windowPrefix) addEventListener(win, eventName, passive ? processPassiveWindowEvent : processWindowEvent, true, passive);\n else roots.forEach((root) => addEventListener(root, eventName, rootScope === documentPrefix ? passive ? processPassiveDocumentEvent : processDocumentEvent : passive ? processPassiveElementEvent : processElementEvent, true, passive));\n if (hasInitialized === 1 && (eventNameOrRoot === "e:qvisible" || eventNameOrRoot === "d:qinit" || eventNameOrRoot === "d:qidle")) processReadyStateChange();\n }\n } else if (!roots.has(eventNameOrRoot)) {\n events.forEach((kebabEventName) => {\n const { scope, eventName } = parseKebabEvent(kebabEventName);\n const passive = isPassiveScope(scope);\n const rootScope = getRootScope(scope);\n if (rootScope !== windowPrefix) addEventListener(eventNameOrRoot, eventName, rootScope === documentPrefix ? passive ? processPassiveDocumentEvent : processDocumentEvent : passive ? processPassiveElementEvent : processElementEvent, true, passive);\n });\n roots.add(eventNameOrRoot);\n }\n }\n};\nvar _qwikEv = win._qwikEv;\nif (!_qwikEv?.roots) {\n if (Array.isArray(_qwikEv)) addEventOrRoot(..._qwikEv);\n else addEventOrRoot("e:click", "e:input");\n win._qwikEv = {\n events,\n roots,\n push: addEventOrRoot\n };\n addEventListener(doc, readyStateChange, processReadyStateChange);\n processReadyStateChange();\n}\n//#endregion';
1282
+ var QWIK_BACKPATCH_EXECUTOR_MINIFIED = `var t='script[type="qwik/backpatch"]';function e(e,n){const o=n||e.querySelector("[q\\\\:container]:not([q\\\\:container=html]):not([q\\\\:container=text])");if(o){const n=o.querySelectorAll(t),r=n[n.length-1];if(r){const t=JSON.parse(r.textContent||"[]"),n=e.createTreeWalker(o,NodeFilter.SHOW_ELEMENT);let c=n.currentNode,i=c.hasAttribute(":")?0:-1;for(let e=0;e<t.length;e+=3){const o=t[e],r=t[e+1];let l=t[e+2];for(;i<o&&(c=n.nextNode(),c);)c.hasAttribute(":")&&i++;const a=c;null==l||!1===l?a.removeAttribute(r):("boolean"==typeof l&&(l=""),a.setAttribute(r,l))}}}}var n=document.currentScript;if(n){const t=n.closest("[q\\\\:container]:not([q\\\\:container=html]):not([q\\\\:container=text])");t&&e(document,t)}`;
1283
+ var QWIK_BACKPATCH_EXECUTOR_DEBUG = '//#region packages/qwik/src/backpatch-executor-shared.ts\n/**\n* Shared backpatch executor logic that can be imported by both the inline script\n* (backpatch-executor.ts) and test utilities.\n*/\nvar BACKPATCH_DATA_SELECTOR = "script[type=\\"qwik/backpatch\\"]";\n/**\n* Execute backpatch operations on a document.\n*\n* @param doc - The document to execute backpatch on\n* @param containerElement - Optional specific container element (if not provided, will search for\n* it)\n*/\nfunction executeBackpatch(doc, containerElement) {\n const container = containerElement || doc.querySelector("[q\\\\:container]:not([q\\\\:container=html]):not([q\\\\:container=text])");\n if (container) {\n const scripts = container.querySelectorAll(BACKPATCH_DATA_SELECTOR);\n const script = scripts[scripts.length - 1];\n if (script) {\n const data = JSON.parse(script.textContent || "[]");\n const walker = doc.createTreeWalker(container, NodeFilter.SHOW_ELEMENT);\n let currentNode = walker.currentNode;\n let currentNodeIdx = currentNode.hasAttribute(":") ? 0 : -1;\n for (let i = 0; i < data.length; i += 3) {\n const elementIdx = data[i];\n const attrName = data[i + 1];\n let value = data[i + 2];\n while (currentNodeIdx < elementIdx) {\n currentNode = walker.nextNode();\n if (!currentNode) break;\n if (currentNode.hasAttribute(":")) currentNodeIdx++;\n }\n const element = currentNode;\n if (value == null || value === false) element.removeAttribute(attrName);\n else {\n if (typeof value === "boolean") value = "";\n element.setAttribute(attrName, value);\n }\n }\n }\n }\n}\n//#endregion\n//#region packages/qwik/src/backpatch-executor.ts\n/**\n* Qwik Backpatch Executor\n*\n* This script executes the backpatch operations by finding the backpatch data script within the\n* same container and applying the patches to the DOM elements.\n*\n* This is the inline script version that auto-executes when loaded in the browser. The actual logic\n* is in backpatch-executor-shared.ts for reusability.\n*/\nvar executorScript = document.currentScript;\nif (executorScript) {\n const container = executorScript.closest("[q\\\\:container]:not([q\\\\:container=html]):not([q\\\\:container=text])");\n if (container) executeBackpatch(document, container);\n}\n//#endregion';
1284
+ var QWIK_OUT_OF_ORDER_EXECUTOR_MINIFIED = `var t='template[q\\\\:r="',e="q:r",r='[q\\\\:rp="',n="q:g",l="q:i",o="q:o",i="[q\\\\:container]:not([q\\\\:container=html]):not([q\\\\:container=text])",u=u=>{const s=new WeakMap,c=()=>{const t=u.currentScript;return t&&t.closest(i)||u},f=(t,e,r,n)=>{let l=s.get(t);return l||s.set(t,l={}),l[e]||(l[e]={r:{},n:0,t:r,o:n})},a=(t,e)=>t?(e&&e.style&&(e.style.display="none"),t.style&&(t.style.display="contents"),1):0,q=t=>{const e=t.o;let r,n,l=0;if("p"===e)for(const e in t.r)r=t.r[e],r[0]&&a(r[0],r[1])&&(r[0]=0,l++);else if("s"===e)for(n=t.n;(r=t.r[n])&&r[0]&&a(r[0],r[1]);n++)r[0]=0,l++,t.n=n+1;else if("r"===e){if(t.t<0)return 0;for(t.n<0&&(t.n=t.t-1),n=t.n;(r=t.r[n])&&r[0]&&a(r[0],r[1]);n--)r[0]=0,l++,t.n=n-1}else{if(t.t<0)return 0;for(n=0;n<t.t;n++)if(r=t.r[n],!r)return 0;for(n=0;n<t.t;n++)r=t.r[n],r[0]&&a(r[0],r[1])&&(r[0]=0,l++)}return l},p=i=>{const s=c(),p=((r,n)=>{const l=u.currentScript,o=l?l.previousElementSibling:null;if(o&&"template"===o.localName&&o.getAttribute(e)===n+"")return o;const i=r.querySelectorAll(t+n+'"]');return i.length?i[i.length-1]:null})(s,i);if(!p)return;const g=((e,n,l)=>{if(!l)return null;const o=((t,e)=>t.querySelector(r+e+'"]'))(e,n),i=o?((e,r)=>e.querySelector(t+r+'"]'))(o,n):null,u=i?i.parentNode:null;return i&&o&&u?(u.insertBefore(l.content,i),i.remove(),l.remove(),[o,o.previousElementSibling]):null})(s,i,p);if(!g)return;((t,e)=>{var r;const n=u;null===(r=n.qProcessOOOS)||void 0===r||r.call(n,t,e)})(i,g[0]||null);const m=p.getAttribute(n);if(m){const t=+(p.getAttribute(l)||0),e=f(s,m,-1,p.getAttribute(o)||"p");return e.r[t]=g,void q(e)}a(g[0]||null,g[1])};p.g=(t,e,r)=>{const n=f(c(),t,e,r);n.t=e,n.o=r,"r"===n.o&&0===n.n&&(n.n=e-1),q(n)},p.d=u,globalThis.qO=p};u(document)`;
1285
+ var QWIK_OUT_OF_ORDER_EXECUTOR_DEBUG = '//#region packages/qwik/src/out-of-order-executor-shared.ts\n/** Shared out-of-order Suspense executor logic for the inline script and source tests. */\nvar Q_RESOLVED_SELECTOR = "template[q\\\\:r=\\"";\nvar Q_RESOLVED_ATTR = "q:r";\nvar Q_RESULT_PARENT_SELECTOR = "[q\\\\:rp=\\"";\nvar Q_GROUP_ATTR = "q:g";\nvar Q_INDEX_ATTR = "q:i";\nvar Q_ORDER_ATTR = "q:o";\nvar Q_CONTAINER_SELECTOR = "[q\\\\:container]:not([q\\\\:container=html]):not([q\\\\:container=text])";\nvar installOutOfOrderExecutor = (doc) => {\n const groups = /* @__PURE__ */ new WeakMap();\n const process = (boundaryId, content) => {\n var _executorDoc$qProcess;\n const executorDoc = doc;\n (_executorDoc$qProcess = executorDoc.qProcessOOOS) === null || _executorDoc$qProcess === void 0 || _executorDoc$qProcess.call(executorDoc, boundaryId, content);\n };\n const getScope = () => {\n const script = doc.currentScript;\n return script ? script.closest(Q_CONTAINER_SELECTOR) || doc : doc;\n };\n const group = (scope, groupId, total, order) => {\n let scopedGroups = groups.get(scope);\n if (!scopedGroups) groups.set(scope, scopedGroups = {});\n return scopedGroups[groupId] || (scopedGroups[groupId] = {\n r: {},\n n: 0,\n t: total,\n o: order\n });\n };\n const getResolvedTemplate = (scope, boundaryId) => {\n const currentScript = doc.currentScript;\n const previousElement = currentScript ? currentScript.previousElementSibling : null;\n if (previousElement && previousElement.localName === "template" && previousElement.getAttribute(Q_RESOLVED_ATTR) === String(boundaryId)) return previousElement;\n const templates = scope.querySelectorAll(Q_RESOLVED_SELECTOR + boundaryId + "\\"]");\n return templates.length ? templates[templates.length - 1] : null;\n };\n const getPlaceholderTemplate = (content, boundaryId) => {\n return content.querySelector(Q_RESOLVED_SELECTOR + boundaryId + "\\"]");\n };\n const getResultParent = (scope, boundaryId) => {\n return scope.querySelector(Q_RESULT_PARENT_SELECTOR + boundaryId + "\\"]");\n };\n const reveal = (content, fallback) => {\n if (!content) return 0;\n if (fallback && fallback.style) fallback.style.display = "none";\n if (content.style) content.style.display = "contents";\n return 1;\n };\n const move = (scope, boundaryId, resolved) => {\n if (!resolved) return null;\n const content = getResultParent(scope, boundaryId);\n const placeholder = content ? getPlaceholderTemplate(content, boundaryId) : null;\n const parent = placeholder ? placeholder.parentNode : null;\n if (!placeholder || !content || !parent) return null;\n parent.insertBefore(resolved.content, placeholder);\n placeholder.remove();\n resolved.remove();\n return [content, content.previousElementSibling];\n };\n const flush = (group) => {\n const order = group.o;\n let entry;\n let index;\n let swapped = 0;\n if (order === "p") for (const key in group.r) {\n entry = group.r[key];\n if (entry[0] && reveal(entry[0], entry[1])) {\n entry[0] = 0;\n swapped++;\n }\n }\n else if (order === "s") for (index = group.n; (entry = group.r[index]) && entry[0]; index++) {\n if (!reveal(entry[0], entry[1])) break;\n entry[0] = 0;\n swapped++;\n group.n = index + 1;\n }\n else if (order === "r") {\n if (group.t < 0) return 0;\n if (group.n < 0) group.n = group.t - 1;\n for (index = group.n; (entry = group.r[index]) && entry[0]; index--) {\n if (!reveal(entry[0], entry[1])) break;\n entry[0] = 0;\n swapped++;\n group.n = index - 1;\n }\n } else {\n if (group.t < 0) return 0;\n for (index = 0; index < group.t; index++) {\n entry = group.r[index];\n if (!entry) return 0;\n }\n for (index = 0; index < group.t; index++) {\n entry = group.r[index];\n if (entry[0] && reveal(entry[0], entry[1])) {\n entry[0] = 0;\n swapped++;\n }\n }\n }\n return swapped;\n };\n const qO = ((boundaryId) => {\n const scope = getScope();\n const resolved = getResolvedTemplate(scope, boundaryId);\n if (!resolved) return;\n const entry = move(scope, boundaryId, resolved);\n if (!entry) return;\n process(boundaryId, entry[0] || null);\n const groupId = resolved.getAttribute(Q_GROUP_ATTR);\n if (groupId) {\n const index = +(resolved.getAttribute(Q_INDEX_ATTR) || 0);\n const currentGroup = group(scope, groupId, -1, resolved.getAttribute(Q_ORDER_ATTR) || "p");\n currentGroup.r[index] = entry;\n flush(currentGroup);\n return;\n }\n reveal(entry[0] || null, entry[1]);\n });\n qO.g = (groupId, total, order) => {\n const currentGroup = group(getScope(), groupId, total, order);\n currentGroup.t = total;\n currentGroup.o = order;\n if (currentGroup.o === "r" && currentGroup.n === 0) currentGroup.n = total - 1;\n flush(currentGroup);\n };\n qO.d = doc;\n globalThis.qO = qO;\n};\n//#endregion\n//#region packages/qwik/src/out-of-order-executor.ts\n/**\n* Qwik Out-of-Order Suspense Executor\n*\n* This is the inline script entry. The actual logic lives in out-of-order-executor-shared.ts so\n* source tests can install the same executor.\n*/\ninstallOutOfOrderExecutor(document);\n//#endregion';
1146
1286
  function getQwikLoaderScript(opts = {}) {
1147
1287
  return opts.debug ? QWIK_LOADER_DEFAULT_DEBUG : QWIK_LOADER_DEFAULT_MINIFIED;
1148
1288
  }
@@ -1151,50 +1291,69 @@ var QWIK_PREFETCH_DEBUG = globalThis.QWIK_PREFETCH_DEBUG;
1151
1291
  function getQwikPrefetchWorkerScript(opts = {}) {
1152
1292
  return opts.debug ? QWIK_PREFETCH_DEBUG : QWIK_PREFETCH_MINIFIED;
1153
1293
  }
1294
+ function getQwikBackpatchExecutorScript(opts = {}) {
1295
+ return opts.debug ? QWIK_BACKPATCH_EXECUTOR_DEBUG : QWIK_BACKPATCH_EXECUTOR_MINIFIED;
1296
+ }
1297
+ function getQwikOutOfOrderExecutorScript(opts = {}) {
1298
+ if (!__EXPERIMENTAL__.suspense) {
1299
+ return "";
1300
+ }
1301
+ const script = opts.debug ? QWIK_OUT_OF_ORDER_EXECUTOR_DEBUG : QWIK_OUT_OF_ORDER_EXECUTOR_MINIFIED;
1302
+ return `if(!globalThis.qO||globalThis.qO.d!==document){${script}
1303
+ }`;
1304
+ }
1154
1305
 
1155
1306
  // packages/qwik/src/server/ssr-node.ts
1156
1307
  import {
1157
1308
  _isJSXNode as isJSXNode,
1158
- _EMPTY_ARRAY,
1309
+ _EMPTY_OBJ,
1159
1310
  _EFFECT_BACK_REF
1160
- } from "@qwik.dev/core";
1161
- import { isDev as isDev3 } from "@qwik.dev/core/build";
1311
+ } from "@qwik.dev/core/internal";
1312
+ import { isDev as isDev7 } from "@qwik.dev/core/build";
1162
1313
  var SsrNode = class {
1163
- constructor(parentSsrNode, id, attributesIndex, cleanupQueue, vnodeData) {
1314
+ constructor(parentComponent, id, attributesIndex, cleanupQueue, vnodeData, currentFile) {
1315
+ this.parentComponent = parentComponent;
1164
1316
  this.attributesIndex = attributesIndex;
1165
1317
  this.cleanupQueue = cleanupQueue;
1166
1318
  this.vnodeData = vnodeData;
1167
- __publicField(this, "__brand__", "SsrNode");
1168
- /**
1169
- * ID which the deserialize will use to retrieve the node.
1170
- *
1171
- * @param id - Unique id for the node.
1172
- */
1173
- __publicField(this, "id");
1174
- __publicField(this, "parentSsrNode");
1175
- __publicField(this, "children", null);
1176
- __publicField(this, "attrs");
1177
- /** Local props which don't serialize; */
1178
- __publicField(this, "localProps", null);
1179
- this.parentSsrNode = parentSsrNode;
1180
- this.parentSsrNode?.addChild(this);
1319
+ this.currentFile = currentFile;
1181
1320
  this.id = id;
1182
- this.attrs = this.attributesIndex >= 0 ? this.vnodeData[this.attributesIndex] : _EMPTY_ARRAY;
1183
- if (isDev3 && id.indexOf("undefined") != -1) {
1321
+ this.flags = 1 /* Updatable */;
1322
+ this.attrs = this.attributesIndex >= 0 ? this.vnodeData[this.attributesIndex] : _EMPTY_OBJ;
1323
+ this.parentComponent?.addChild(this);
1324
+ if (isDev7 && id.indexOf("undefined") != -1) {
1184
1325
  throw new Error(`Invalid SSR node id: ${id}`);
1185
1326
  }
1186
1327
  }
1328
+ parentComponent;
1329
+ attributesIndex;
1330
+ cleanupQueue;
1331
+ vnodeData;
1332
+ currentFile;
1333
+ __brand__ = "SsrNode";
1334
+ /**
1335
+ * ID which the deserialize will use to retrieve the node.
1336
+ *
1337
+ * @param id - Unique id for the node.
1338
+ */
1339
+ id;
1340
+ flags;
1341
+ dirty = 0 /* NONE */;
1342
+ children = null;
1343
+ attrs;
1344
+ /** Local props which don't serialize; */
1345
+ localProps = null;
1187
1346
  get [_EFFECT_BACK_REF]() {
1188
1347
  return this.getProp(QBackRefs);
1189
1348
  }
1190
1349
  setProp(name, value) {
1191
- if (this.attrs === _EMPTY_ARRAY) {
1350
+ if (this.attrs === _EMPTY_OBJ) {
1192
1351
  this.setEmptyArrayAsVNodeDataAttributes();
1193
1352
  }
1194
1353
  if (name.startsWith(NON_SERIALIZABLE_MARKER_PREFIX)) {
1195
- mapArray_set(this.localProps || (this.localProps = []), name, value, 0);
1354
+ (this.localProps ||= {})[name] = value;
1196
1355
  } else {
1197
- mapArray_set(this.attrs, name, value, 0);
1356
+ this.attrs[name] = value;
1198
1357
  }
1199
1358
  if (name == ELEMENT_SEQ && value) {
1200
1359
  this.cleanupQueue.push(value);
@@ -1202,29 +1361,29 @@ var SsrNode = class {
1202
1361
  }
1203
1362
  setEmptyArrayAsVNodeDataAttributes() {
1204
1363
  if (this.attributesIndex >= 0) {
1205
- this.vnodeData[this.attributesIndex] = [];
1364
+ this.vnodeData[this.attributesIndex] = {};
1206
1365
  this.attrs = this.vnodeData[this.attributesIndex];
1207
1366
  } else {
1208
1367
  const newAttributesIndex = this.vnodeData.length > 1 ? 1 : 0;
1209
- this.vnodeData.splice(newAttributesIndex, 0, []);
1368
+ this.vnodeData.splice(newAttributesIndex, 0, {});
1210
1369
  this.attributesIndex = newAttributesIndex;
1211
1370
  this.attrs = this.vnodeData[this.attributesIndex];
1212
1371
  }
1213
1372
  }
1214
1373
  getProp(name) {
1215
1374
  if (name.startsWith(NON_SERIALIZABLE_MARKER_PREFIX)) {
1216
- return this.localProps ? mapArray_get(this.localProps, name, 0) : null;
1375
+ return this.localProps ? this.localProps[name] ?? null : null;
1217
1376
  } else {
1218
- return mapArray_get(this.attrs, name, 0);
1377
+ return this.attrs[name] ?? null;
1219
1378
  }
1220
1379
  }
1221
1380
  removeProp(name) {
1222
1381
  if (name.startsWith(NON_SERIALIZABLE_MARKER_PREFIX)) {
1223
1382
  if (this.localProps) {
1224
- mapApp_remove(this.localProps, name, 0);
1383
+ delete this.localProps[name];
1225
1384
  }
1226
1385
  } else {
1227
- mapApp_remove(this.attrs, name, 0);
1386
+ delete this.attrs[name];
1228
1387
  }
1229
1388
  }
1230
1389
  addChild(child) {
@@ -1233,35 +1392,49 @@ var SsrNode = class {
1233
1392
  }
1234
1393
  this.children.push(child);
1235
1394
  }
1395
+ setTreeNonUpdatable() {
1396
+ if (this.flags & 1 /* Updatable */) {
1397
+ this.flags &= ~1 /* Updatable */;
1398
+ if (this.children) {
1399
+ for (let i = 0; i < this.children.length; i++) {
1400
+ const child = this.children[i];
1401
+ child.setTreeNonUpdatable();
1402
+ }
1403
+ }
1404
+ }
1405
+ }
1236
1406
  toString() {
1237
- let stringifiedAttrs = "";
1238
- for (let i = 0; i < this.attrs.length; i += 2) {
1239
- const key = this.attrs[i];
1240
- const value = this.attrs[i + 1];
1241
- stringifiedAttrs += `${key}=`;
1242
- stringifiedAttrs += `${typeof value === "string" || typeof value === "number" ? JSON.stringify(value) : "*"}`;
1243
- if (i < this.attrs.length - 2) {
1407
+ if (isDev7) {
1408
+ let stringifiedAttrs = "";
1409
+ for (const key in this.attrs) {
1410
+ const value = this.attrs[key];
1411
+ stringifiedAttrs += `${key}=`;
1412
+ stringifiedAttrs += `${typeof value === "string" || typeof value === "number" ? JSON.stringify(value) : "*"}`;
1244
1413
  stringifiedAttrs += ", ";
1245
1414
  }
1415
+ return `<SSRNode id="${this.id}" ${stringifiedAttrs} />`;
1416
+ } else {
1417
+ return `<SSRNode id="${this.id}" />`;
1246
1418
  }
1247
- return `SSRNode [<${this.id}> ${stringifiedAttrs}]`;
1248
1419
  }
1249
1420
  };
1250
1421
  var DomRef = class {
1251
1422
  constructor($ssrNode$) {
1252
1423
  this.$ssrNode$ = $ssrNode$;
1253
- __publicField(this, "__brand__", "DomRef");
1254
1424
  }
1425
+ $ssrNode$;
1426
+ __brand__ = "DomRef";
1255
1427
  };
1256
1428
  var SsrComponentFrame = class {
1257
1429
  constructor(componentNode) {
1258
1430
  this.componentNode = componentNode;
1259
- __publicField(this, "slots", []);
1260
- __publicField(this, "projectionDepth", 0);
1261
- __publicField(this, "scopedStyleIds", /* @__PURE__ */ new Set());
1262
- __publicField(this, "projectionScopedStyle", null);
1263
- __publicField(this, "projectionComponentFrame", null);
1264
1431
  }
1432
+ componentNode;
1433
+ slots = [];
1434
+ projectionDepth = 0;
1435
+ scopedStyleIds = /* @__PURE__ */ new Set();
1436
+ projectionScopedStyle = null;
1437
+ projectionComponentFrame = null;
1265
1438
  distributeChildrenIntoSlots(children, projectionScopedStyle, projectionComponentFrame) {
1266
1439
  this.projectionScopedStyle = projectionScopedStyle;
1267
1440
  this.projectionComponentFrame = projectionComponentFrame;
@@ -1308,19 +1481,88 @@ var SsrComponentFrame = class {
1308
1481
  hasSlot(slotName) {
1309
1482
  return mapArray_has(this.slots, slotName, 0);
1310
1483
  }
1484
+ claimChildrenForSlot(slotName) {
1485
+ return mapApp_remove(this.slots, slotName, 0);
1486
+ }
1311
1487
  consumeChildrenForSlot(projectionNode, slotName) {
1312
- const children = mapApp_remove(this.slots, slotName, 0);
1488
+ const children = this.claimChildrenForSlot(slotName);
1313
1489
  this.componentNode.setProp(slotName, projectionNode.id);
1314
1490
  projectionNode.setProp(QSlotParent, this.componentNode.id);
1315
1491
  return children;
1316
1492
  }
1317
- releaseUnclaimedProjections(unclaimedProjections) {
1318
- if (this.slots.length) {
1319
- unclaimedProjections.push(this);
1320
- unclaimedProjections.push(this.projectionScopedStyle);
1321
- unclaimedProjections.push.apply(unclaimedProjections, this.slots);
1493
+ };
1494
+
1495
+ // packages/qwik/src/server/ssr-stream-writer.ts
1496
+ var renderSSRChunks = (chunks, remap) => {
1497
+ let out = "";
1498
+ for (let i = 0; i < chunks.length; i++) {
1499
+ const chunk = chunks[i];
1500
+ if (typeof chunk === "string") {
1501
+ out += chunk;
1502
+ } else if (chunk.type === "root-ref-delta") {
1503
+ const id = remap ? remap[chunk.localId] ?? chunk.localId : chunk.localId;
1504
+ const base2 = remap ? remap[chunk.localBaseId] ?? chunk.localBaseId : chunk.localBaseId;
1505
+ out += String(id - base2);
1506
+ } else {
1507
+ const localId = chunk.type === "root-ref" ? chunk.localId : chunk.localPath[0];
1508
+ out += String(remap ? remap[localId] ?? localId : localId);
1509
+ if (chunk.type !== "root-ref-path") {
1510
+ continue;
1511
+ }
1512
+ const path = chunk.localPath;
1513
+ for (let j = 1; j < path.length; j++) {
1514
+ out += " " + path[j];
1515
+ }
1322
1516
  }
1323
1517
  }
1518
+ return out;
1519
+ };
1520
+ var StringSSRWriter = class {
1521
+ buffer = [];
1522
+ write(text) {
1523
+ this.buffer.push(text);
1524
+ }
1525
+ writeRootRef(id) {
1526
+ writeStringRootRef(this, id);
1527
+ }
1528
+ writeRootRefPath(path) {
1529
+ writeStringRootRefPath(this, path);
1530
+ }
1531
+ writeRootRefDelta(id, base2) {
1532
+ writeStringRootRefDelta(this, id, base2);
1533
+ }
1534
+ clear() {
1535
+ this.buffer.length = 0;
1536
+ }
1537
+ toString(_) {
1538
+ return this.buffer.join("");
1539
+ }
1540
+ };
1541
+ var StringBufferSegmentWriter = class {
1542
+ chunks = [];
1543
+ write(text) {
1544
+ this.chunks.push(text);
1545
+ }
1546
+ writeRootRef(id) {
1547
+ this.chunks.push({ type: "root-ref", localId: id });
1548
+ }
1549
+ writeRootRefPath(path) {
1550
+ this.chunks.push({ type: "root-ref-path", localPath: path });
1551
+ }
1552
+ writeRootRefDelta(id, base2) {
1553
+ this.chunks.push({ type: "root-ref-delta", localId: id, localBaseId: base2 });
1554
+ }
1555
+ clear() {
1556
+ this.chunks.length = 0;
1557
+ }
1558
+ extract() {
1559
+ const chunks = this.chunks;
1560
+ this.chunks = [];
1561
+ return chunks;
1562
+ }
1563
+ toString(remap) {
1564
+ return renderSSRChunks(this.chunks, remap);
1565
+ }
1324
1566
  };
1325
1567
 
1326
1568
  // packages/qwik/src/server/tag-nesting.ts
@@ -1355,6 +1597,10 @@ var allowedContent = (state) => {
1355
1597
  case 514 /* PHRASING_INSIDE_INPUT */:
1356
1598
  case 1026 /* PHRASING_CONTAINER */:
1357
1599
  return ["phrasing content", "<a>, <b>, <img>, <input> ... (no <div>, <p> ...)"];
1600
+ case 2050 /* PICTURE */:
1601
+ return ["picture content", "<source>, <img>"];
1602
+ case 4098 /* BUTTON */:
1603
+ return ["button content", "phrasing content except interactive elements"];
1358
1604
  case 1 /* DOCUMENT */:
1359
1605
  return ["document", "<html>"];
1360
1606
  }
@@ -1396,6 +1642,10 @@ function isTagAllowed(state, tag) {
1396
1642
  return isInPhrasing(tag, true);
1397
1643
  case 514 /* PHRASING_INSIDE_INPUT */:
1398
1644
  return isInPhrasing(tag, false);
1645
+ case 2050 /* PICTURE */:
1646
+ return isInPicture(tag);
1647
+ case 4098 /* BUTTON */:
1648
+ return isInButton(tag);
1399
1649
  case 1 /* DOCUMENT */:
1400
1650
  if (tag === "html") {
1401
1651
  return 32 /* HTML */;
@@ -1475,9 +1725,12 @@ function isInAnything(text) {
1475
1725
  case "body":
1476
1726
  return 0 /* NOT_ALLOWED */;
1477
1727
  case "button":
1728
+ return 4098 /* BUTTON */;
1478
1729
  case "input":
1479
1730
  case "textarea":
1480
1731
  return 514 /* PHRASING_INSIDE_INPUT */;
1732
+ case "picture":
1733
+ return 2050 /* PICTURE */;
1481
1734
  default:
1482
1735
  return 10 /* ANYTHING */;
1483
1736
  }
@@ -1492,6 +1745,8 @@ function isInTable(text) {
1492
1745
  case "tbody":
1493
1746
  case "tfoot":
1494
1747
  return 8192 /* TABLE_BODY */;
1748
+ case "script":
1749
+ return 2 /* TEXT */;
1495
1750
  default:
1496
1751
  return 0 /* NOT_ALLOWED */;
1497
1752
  }
@@ -1500,6 +1755,8 @@ function isInTableBody(text) {
1500
1755
  switch (text) {
1501
1756
  case "tr":
1502
1757
  return 16384 /* TABLE_ROW */;
1758
+ case "script":
1759
+ return 2 /* TEXT */;
1503
1760
  default:
1504
1761
  return 0 /* NOT_ALLOWED */;
1505
1762
  }
@@ -1509,6 +1766,8 @@ function isInTableRow(text) {
1509
1766
  case "td":
1510
1767
  case "th":
1511
1768
  return 10 /* ANYTHING */;
1769
+ case "script":
1770
+ return 2 /* TEXT */;
1512
1771
  default:
1513
1772
  return 0 /* NOT_ALLOWED */;
1514
1773
  }
@@ -1517,16 +1776,43 @@ function isInTableColGroup(text) {
1517
1776
  switch (text) {
1518
1777
  case "col":
1519
1778
  return 4 /* EMPTY */;
1779
+ case "script":
1780
+ return 2 /* TEXT */;
1781
+ default:
1782
+ return 0 /* NOT_ALLOWED */;
1783
+ }
1784
+ }
1785
+ function isInPicture(text) {
1786
+ switch (text) {
1787
+ case "source":
1788
+ return 4 /* EMPTY */;
1789
+ case "img":
1790
+ return 4 /* EMPTY */;
1791
+ case "script":
1792
+ return 2 /* TEXT */;
1520
1793
  default:
1521
1794
  return 0 /* NOT_ALLOWED */;
1522
1795
  }
1523
1796
  }
1797
+ function isInButton(text) {
1798
+ switch (text) {
1799
+ case "button":
1800
+ case "input":
1801
+ case "textarea":
1802
+ case "select":
1803
+ case "a":
1804
+ return 0 /* NOT_ALLOWED */;
1805
+ case "picture":
1806
+ return 2050 /* PICTURE */;
1807
+ default:
1808
+ return isInPhrasing(text, false);
1809
+ }
1810
+ }
1524
1811
  function isInPhrasing(text, allowInput) {
1525
1812
  switch (text) {
1526
1813
  case "svg":
1527
1814
  case "math":
1528
1815
  return 1026 /* PHRASING_CONTAINER */;
1529
- case "button":
1530
1816
  case "input":
1531
1817
  case "textarea":
1532
1818
  return allowInput ? 514 /* PHRASING_INSIDE_INPUT */ : 0 /* NOT_ALLOWED */;
@@ -1538,6 +1824,7 @@ function isInPhrasing(text, allowInput) {
1538
1824
  case "bdi":
1539
1825
  case "bdo":
1540
1826
  case "br":
1827
+ case "button":
1541
1828
  case "canvas":
1542
1829
  case "cite":
1543
1830
  case "code":
@@ -1565,13 +1852,11 @@ function isInPhrasing(text, allowInput) {
1565
1852
  case "object":
1566
1853
  case "option":
1567
1854
  case "output":
1568
- case "picture":
1569
1855
  case "progress":
1570
1856
  case "q":
1571
1857
  case "ruby":
1572
1858
  case "s":
1573
1859
  case "samp":
1574
- case "script":
1575
1860
  case "select":
1576
1861
  case "slot":
1577
1862
  case "small":
@@ -1586,13 +1871,46 @@ function isInPhrasing(text, allowInput) {
1586
1871
  case "video":
1587
1872
  case "wbr":
1588
1873
  return allowInput ? 258 /* PHRASING_ANY */ : 514 /* PHRASING_INSIDE_INPUT */;
1874
+ case "script":
1589
1875
  case "style":
1590
1876
  return 2 /* TEXT */;
1877
+ case "picture":
1878
+ return 2050 /* PICTURE */;
1591
1879
  default:
1592
1880
  return 0 /* NOT_ALLOWED */;
1593
1881
  }
1594
1882
  }
1595
1883
 
1884
+ // packages/qwik/src/server/utils.ts
1885
+ function createTimer() {
1886
+ if (typeof performance === "undefined") {
1887
+ return () => 0;
1888
+ }
1889
+ const start = performance.now();
1890
+ return () => {
1891
+ const end = performance.now();
1892
+ const delta = end - start;
1893
+ return delta / 1e6;
1894
+ };
1895
+ }
1896
+ function getBuildBase(opts) {
1897
+ let base2 = opts.base;
1898
+ if (typeof opts.base === "function") {
1899
+ base2 = opts.base(opts);
1900
+ }
1901
+ if (typeof base2 === "string") {
1902
+ if (!base2.endsWith("/")) {
1903
+ base2 += "/";
1904
+ }
1905
+ return base2;
1906
+ }
1907
+ return `${import.meta.env?.BASE_URL || "/"}build/`;
1908
+ }
1909
+ var versions = {
1910
+ qwik: "2.0.0-beta.40-dev+a459d55",
1911
+ qwikDom: "2.1.19"
1912
+ };
1913
+
1596
1914
  // packages/qwik/src/server/vnode-data.ts
1597
1915
  var OPEN_FRAGMENT = Number.MAX_SAFE_INTEGER;
1598
1916
  var CLOSE_FRAGMENT = Number.MAX_SAFE_INTEGER - 1;
@@ -1605,320 +1923,110 @@ function vNodeData_incrementElementCount(vNodeData) {
1605
1923
  } else {
1606
1924
  vNodeData[length - 1] = lastValue - 1;
1607
1925
  }
1608
- }
1609
- function vNodeData_addTextSize(vNodeData, size) {
1610
- const length = vNodeData.length;
1611
- const lastValue = length > 1 ? vNodeData[length - 1] : 0;
1612
- if (length > 1 && lastValue >= 0) {
1613
- vNodeData[0] |= 1 /* TEXT_DATA */;
1614
- }
1615
- vNodeData.push(size);
1616
- if (size == 0) {
1617
- vNodeData[0] |= 1 /* TEXT_DATA */;
1618
- }
1619
- }
1620
- function vNodeData_openFragment(vNodeData, attrs) {
1621
- vNodeData.push(attrs, OPEN_FRAGMENT);
1622
- vNodeData[0] |= 2 /* VIRTUAL_NODE */;
1623
- }
1624
- function vNodeData_closeFragment(vNodeData) {
1625
- vNodeData.push(CLOSE_FRAGMENT);
1626
- }
1627
- function vNodeData_openElement(vNodeData) {
1628
- vNodeData.push([], WRITE_ELEMENT_ATTRS);
1629
- vNodeData[0] |= 4 /* ELEMENT_NODE */;
1630
- }
1631
- function vNodeData_createSsrNodeReference(currentComponentNode, vNodeData, depthFirstElementIdx, cleanupQueue) {
1632
- vNodeData[0] |= 8 /* REFERENCE */;
1633
- const stack = [-1];
1634
- let attributesIndex = -1;
1635
- for (let i = 1; i < vNodeData.length; i++) {
1636
- const value = vNodeData[i];
1637
- if (Array.isArray(value)) {
1638
- attributesIndex = i;
1639
- i++;
1640
- if (vNodeData[i] !== WRITE_ELEMENT_ATTRS) {
1641
- stack[stack.length - 1]++;
1642
- stack.push(-1);
1643
- }
1644
- } else if (value === CLOSE_FRAGMENT) {
1645
- stack.pop();
1646
- } else if (value < 0) {
1647
- const numberOfElements = 0 - value;
1648
- stack[stack.length - 1] += numberOfElements;
1649
- } else {
1650
- stack[stack.length - 1]++;
1651
- }
1652
- }
1653
- let refId = String(depthFirstElementIdx);
1654
- if (vNodeData[0] & (2 /* VIRTUAL_NODE */ | 1 /* TEXT_DATA */)) {
1655
- for (let i = 0; i < stack.length; i++) {
1656
- const childCount = stack[i];
1657
- if (childCount >= 0) {
1658
- refId += encodeAsAlphanumeric(childCount);
1659
- }
1660
- }
1661
- }
1662
- return new SsrNode(currentComponentNode, refId, attributesIndex, cleanupQueue, vNodeData);
1663
- }
1664
- var ALPHANUMERIC = [];
1665
- function encodeAsAlphanumeric(value) {
1666
- while (ALPHANUMERIC.length <= value) {
1667
- let value2 = ALPHANUMERIC.length;
1668
- let text = "";
1669
- do {
1670
- text = String.fromCharCode(
1671
- (text.length === 0 ? 65 : 97) + value2 % 26
1672
- /* A-Z */
1673
- ) + text;
1674
- value2 = Math.floor(
1675
- value2 / 26
1676
- /* A-Z */
1677
- );
1678
- } while (value2 !== 0);
1679
- ALPHANUMERIC.push(text);
1680
- }
1681
- return ALPHANUMERIC[value];
1682
- }
1683
-
1684
- // packages/qwik/src/server/preload-strategy.ts
1685
- import { getPlatform } from "@qwik.dev/core";
1686
-
1687
- // packages/qwik/src/server/preload-utils.ts
1688
- function flattenPrefetchResources(prefetchResources) {
1689
- const urls = [];
1690
- const addPrefetchResource = (prefetchResources2) => {
1691
- if (prefetchResources2) {
1692
- for (const prefetchResource of prefetchResources2) {
1693
- if (!urls.includes(prefetchResource.url)) {
1694
- urls.push(prefetchResource.url);
1695
- if (prefetchResource.imports) {
1696
- addPrefetchResource(prefetchResource.imports);
1697
- }
1698
- }
1699
- }
1700
- }
1701
- };
1702
- addPrefetchResource(prefetchResources);
1703
- return urls;
1704
- }
1705
-
1706
- // packages/qwik/src/server/preload-strategy.ts
1707
- var getBundles = (qrls) => {
1708
- const platform = getPlatform();
1709
- return qrls?.map((qrl) => {
1710
- const symbol = qrl.$symbol$;
1711
- const chunk = qrl.$chunk$;
1712
- const result = platform.chunkForSymbol(symbol, chunk, qrl.dev?.file);
1713
- if (result) {
1714
- return result[1];
1715
- }
1716
- return chunk;
1717
- }).filter(Boolean);
1718
- };
1719
- function getPreloadPaths(qrls, opts, resolvedManifest) {
1720
- const prefetchStrategy = opts.prefetchStrategy;
1721
- if (prefetchStrategy === null) {
1722
- return [];
1723
- }
1724
- if (!resolvedManifest?.manifest.bundleGraph) {
1725
- return getBundles(qrls);
1726
- }
1727
- if (typeof prefetchStrategy?.symbolsToPrefetch === "function") {
1728
- try {
1729
- const prefetchResources = prefetchStrategy.symbolsToPrefetch({
1730
- manifest: resolvedManifest.manifest
1731
- });
1732
- return flattenPrefetchResources(prefetchResources);
1733
- } catch (e) {
1734
- console.error("getPrefetchUrls, symbolsToPrefetch()", e);
1735
- }
1736
- }
1737
- const symbols = /* @__PURE__ */ new Set();
1738
- for (const qrl of qrls) {
1739
- const symbol = getSymbolHash(qrl.$symbol$);
1740
- if (symbol && symbol.length >= 10) {
1741
- symbols.add(symbol);
1742
- }
1743
- }
1744
- return [...symbols];
1745
- }
1746
- var expandBundles = (names, resolvedManifest) => {
1747
- if (!resolvedManifest?.manifest.bundleGraph) {
1748
- return [...new Set(names)];
1749
- }
1750
- resetQueue();
1751
- let probability = 0.99;
1752
- for (const name of names) {
1753
- preload(name, probability);
1754
- probability *= 0.95;
1755
- }
1756
- return getQueue();
1757
- };
1758
-
1759
- // packages/qwik/src/server/preload-impl.ts
1760
- var simplifyPath = (base2, path) => {
1761
- if (path == null) {
1762
- return null;
1763
- }
1764
- const segments = `${base2}${path}`.split("/");
1765
- const simplified = [];
1766
- for (const segment of segments) {
1767
- if (segment === ".." && simplified.length > 0) {
1768
- simplified.pop();
1769
- } else {
1770
- simplified.push(segment);
1771
- }
1772
- }
1773
- return simplified.join("/");
1774
- };
1775
- var getBase = (container) => {
1776
- let base2 = container.$buildBase$;
1777
- if (import.meta.env.DEV && !import.meta.env.TEST) {
1778
- base2 = import.meta.env.BASE_URL;
1779
- }
1780
- return base2;
1781
- };
1782
- var preloaderPre = (container, options, nonce) => {
1783
- const { resolvedManifest } = container;
1784
- const base2 = getBase(container);
1785
- const preloaderBundle = simplifyPath(base2, resolvedManifest?.manifest?.preloader);
1786
- let bundleGraphPath = resolvedManifest?.manifest.bundleGraphAsset;
1787
- if (bundleGraphPath) {
1788
- bundleGraphPath = (import.meta.env.BASE_URL || "/") + bundleGraphPath;
1789
- }
1790
- if (preloaderBundle && bundleGraphPath && options !== false) {
1791
- const preloaderOpts = typeof options === "object" ? {
1792
- debug: options.debug,
1793
- preloadProbability: options.ssrPreloadProbability
1794
- } : void 0;
1795
- const bundleGraph = container.resolvedManifest?.manifest.bundleGraph;
1796
- initPreloader(bundleGraph, preloaderOpts);
1797
- const opts = [];
1798
- if (options) {
1799
- if (options.debug) {
1800
- opts.push("d:1");
1801
- }
1802
- if (options.maxIdlePreloads) {
1803
- opts.push(`P:${options.maxIdlePreloads}`);
1804
- }
1805
- if (options.preloadProbability) {
1806
- opts.push(`Q:${options.preloadProbability}`);
1807
- }
1808
- }
1809
- const optsStr = opts.length ? `,{${opts.join(",")}}` : "";
1810
- container.openElement("link", null, ["rel", "modulepreload", "href", preloaderBundle]);
1811
- container.closeElement();
1812
- container.openElement("link", null, [
1813
- "rel",
1814
- "preload",
1815
- "href",
1816
- bundleGraphPath,
1817
- "as",
1818
- "fetch",
1819
- "crossorigin",
1820
- "anonymous"
1821
- ]);
1822
- container.closeElement();
1823
- const script = `let b=fetch("${bundleGraphPath}");import("${preloaderBundle}").then(({l})=>l(${JSON.stringify(base2)},b${optsStr}));`;
1824
- const scriptAttrs = ["type", "module", "async", true];
1825
- if (nonce) {
1826
- scriptAttrs.push("nonce", nonce);
1827
- }
1828
- container.openElement("script", null, scriptAttrs);
1829
- container.writer.write(script);
1830
- container.closeElement();
1831
- }
1832
- const corePath = simplifyPath(base2, resolvedManifest?.manifest.core);
1833
- if (corePath) {
1834
- container.openElement("link", null, ["rel", "modulepreload", "href", corePath]);
1835
- container.closeElement();
1926
+ }
1927
+ function vNodeData_addTextSize(vNodeData, size) {
1928
+ const length = vNodeData.length;
1929
+ const lastValue = length > 1 ? vNodeData[length - 1] : 0;
1930
+ if (length > 1 && lastValue >= 0) {
1931
+ vNodeData[0] |= 1 /* TEXT_DATA */;
1836
1932
  }
1837
- };
1838
- var includePreloader = (container, options, referencedBundles, nonce) => {
1839
- if (referencedBundles.length === 0 || options === false) {
1840
- return null;
1933
+ vNodeData.push(size);
1934
+ if (size == 0) {
1935
+ vNodeData[0] |= 1 /* TEXT_DATA */;
1841
1936
  }
1842
- const { ssrPreloads, ssrPreloadProbability } = normalizePreLoaderOptions(
1843
- typeof options === "boolean" ? void 0 : options
1844
- );
1845
- let allowed = ssrPreloads;
1846
- const base2 = getBase(container);
1847
- const links = [];
1848
- const { resolvedManifest } = container;
1849
- if (allowed) {
1850
- const preloaderBundle2 = resolvedManifest?.manifest.preloader;
1851
- const coreBundle = resolvedManifest?.manifest.core;
1852
- const expandedBundles = expandBundles(referencedBundles, resolvedManifest);
1853
- let probability = 4;
1854
- const tenXMinProbability = ssrPreloadProbability * 10;
1855
- for (const hrefOrProbability of expandedBundles) {
1856
- if (typeof hrefOrProbability === "string") {
1857
- if (probability < tenXMinProbability) {
1858
- break;
1859
- }
1860
- if (hrefOrProbability === preloaderBundle2 || hrefOrProbability === coreBundle) {
1861
- continue;
1862
- }
1863
- links.push(hrefOrProbability);
1864
- if (--allowed === 0) {
1865
- break;
1866
- }
1867
- } else {
1868
- probability = hrefOrProbability;
1937
+ }
1938
+ function vNodeData_openFragment(vNodeData, attrs) {
1939
+ vNodeData.push(attrs, OPEN_FRAGMENT);
1940
+ vNodeData[0] |= 2 /* VIRTUAL_NODE */;
1941
+ }
1942
+ function vNodeData_closeFragment(vNodeData) {
1943
+ vNodeData.push(CLOSE_FRAGMENT);
1944
+ }
1945
+ function vNodeData_openElement(vNodeData) {
1946
+ vNodeData.push({}, WRITE_ELEMENT_ATTRS);
1947
+ vNodeData[0] |= 4 /* ELEMENT_NODE */;
1948
+ }
1949
+ function vNodeData_createSsrNodeReference(currentComponentNode, vNodeData, depthFirstElementIdx, cleanupQueue, currentFile) {
1950
+ vNodeData[0] |= 8 /* REFERENCE */;
1951
+ const stack = [-1];
1952
+ let attributesIndex = -1;
1953
+ for (let i = 1; i < vNodeData.length; i++) {
1954
+ const value = vNodeData[i];
1955
+ if (typeof value === "object" && value !== null) {
1956
+ attributesIndex = i;
1957
+ i++;
1958
+ if (vNodeData[i] !== WRITE_ELEMENT_ATTRS) {
1959
+ stack[stack.length - 1]++;
1960
+ stack.push(-1);
1869
1961
  }
1962
+ } else if (value === CLOSE_FRAGMENT) {
1963
+ stack.pop();
1964
+ } else if (value < 0) {
1965
+ const numberOfElements = 0 - value;
1966
+ stack[stack.length - 1] += numberOfElements;
1967
+ } else {
1968
+ stack[stack.length - 1]++;
1870
1969
  }
1871
1970
  }
1872
- const preloaderBundle = simplifyPath(base2, resolvedManifest?.manifest.preloader);
1873
- const insertLinks = links.length ? (
1874
- /**
1875
- * We only use modulepreload links because they behave best. Older browsers can rely on the
1876
- * preloader which does feature detection and which will be available soon after inserting these
1877
- * links.
1878
- */
1879
- `${JSON.stringify(links)}.map((l,e)=>{e=document.createElement('link');e.rel='modulepreload';e.href=${JSON.stringify(base2)}+l;document.head.appendChild(e)});`
1880
- ) : "";
1881
- let script = insertLinks;
1882
- if (preloaderBundle) {
1883
- script += `window.addEventListener('load',f=>{f=_=>import("${preloaderBundle}").then(({p})=>p(${JSON.stringify(referencedBundles)}));try{requestIdleCallback(f,{timeout:2000})}catch(e){setTimeout(f,200)}})`;
1884
- }
1885
- if (script) {
1886
- const attrs = ["type", "module", "async", true, "q:type", "preload"];
1887
- if (nonce) {
1888
- attrs.push("nonce", nonce);
1971
+ let refId = String(depthFirstElementIdx);
1972
+ if (vNodeData[0] & (2 /* VIRTUAL_NODE */ | 1 /* TEXT_DATA */)) {
1973
+ for (let i = 0; i < stack.length; i++) {
1974
+ const childCount = stack[i];
1975
+ if (childCount >= 0) {
1976
+ refId += encodeAsAlphanumeric(childCount);
1977
+ }
1889
1978
  }
1890
- container.openElement("script", null, attrs);
1891
- container.writer.write(script);
1892
- container.closeElement();
1893
1979
  }
1894
- return null;
1895
- };
1896
- var preloaderPost = (ssrContainer, opts, nonce) => {
1897
- if (opts.preloader !== false) {
1898
- const qrls = Array.from(ssrContainer.serializationCtx.$eventQrls$);
1899
- const preloadBundles = getPreloadPaths(qrls, opts, ssrContainer.resolvedManifest);
1900
- if (preloadBundles.length > 0) {
1901
- includePreloader(ssrContainer, opts.preloader, preloadBundles, nonce);
1902
- }
1980
+ return new SsrNode(
1981
+ currentComponentNode,
1982
+ refId,
1983
+ attributesIndex,
1984
+ cleanupQueue,
1985
+ vNodeData,
1986
+ currentFile
1987
+ );
1988
+ }
1989
+ var ALPHANUMERIC = [];
1990
+ function encodeAsAlphanumeric(value) {
1991
+ while (ALPHANUMERIC.length <= value) {
1992
+ let value2 = ALPHANUMERIC.length;
1993
+ let text = "";
1994
+ do {
1995
+ text = String.fromCharCode(
1996
+ (text.length === 0 ? 65 : 97) + value2 % 26
1997
+ /* A-Z */
1998
+ ) + text;
1999
+ value2 = Math.floor(
2000
+ value2 / 26
2001
+ /* A-Z */
2002
+ );
2003
+ } while (value2 !== 0);
2004
+ ALPHANUMERIC.push(text);
1903
2005
  }
1904
- };
1905
- function normalizePreLoaderOptions(input) {
1906
- return { ...preLoaderOptionsDefault, ...input };
2006
+ return ALPHANUMERIC[value];
1907
2007
  }
1908
- var preLoaderOptionsDefault = {
1909
- ssrPreloads: 7,
1910
- ssrPreloadProbability: 0.5,
1911
- debug: false,
1912
- maxIdlePreloads: 25,
1913
- preloadProbability: 0.35
1914
- };
1915
2008
 
1916
2009
  // packages/qwik/src/server/ssr-container.ts
2010
+ var VALID_ELEMENT_NAME = /^[A-Za-z][A-Za-z0-9._:-]*$/;
2011
+ var NO_SCRIPT_HERE_ELEMENTS = /* @__PURE__ */ new Set([
2012
+ "script",
2013
+ "style",
2014
+ "textarea",
2015
+ "title",
2016
+ "iframe",
2017
+ "noframes",
2018
+ "noscript",
2019
+ "xmp",
2020
+ "template",
2021
+ "svg",
2022
+ "math"
2023
+ ]);
1917
2024
  function ssrCreateContainer(opts) {
1918
- opts.renderOptions || (opts.renderOptions = {});
2025
+ opts.renderOptions ||= {};
1919
2026
  return new SSRContainer({
1920
2027
  tagName: opts.tagName || "div",
1921
- writer: opts.writer || new StringBufferWriter(),
2028
+ writer: opts.writer || new StringSSRWriter(),
2029
+ streamHandler: opts.streamHandler,
1922
2030
  locale: opts.locale || "",
1923
2031
  timing: opts.timing || {
1924
2032
  firstFlush: 0,
@@ -1936,73 +2044,90 @@ function ssrCreateContainer(opts) {
1936
2044
  renderOptions: opts.renderOptions
1937
2045
  });
1938
2046
  }
1939
- var StringBufferWriter = class {
1940
- constructor() {
1941
- __publicField(this, "buffer", []);
1942
- }
1943
- write(text) {
1944
- this.buffer.push(text);
1945
- }
1946
- toString() {
1947
- return this.buffer.join("");
2047
+ var noopStreamHandler = {
2048
+ flush() {
2049
+ },
2050
+ waitForPendingFlush() {
2051
+ },
2052
+ streamBlockStart() {
2053
+ },
2054
+ streamBlockEnd() {
1948
2055
  }
1949
2056
  };
1950
- var EMPTY_OBJ = {};
2057
+ var QTemplateProps = {
2058
+ hidden: true,
2059
+ "aria-hidden": true
2060
+ };
1951
2061
  var SSRContainer = class extends _SharedContainer {
2062
+ tag;
2063
+ isHtml;
2064
+ writer;
2065
+ streamHandler;
2066
+ timing;
2067
+ size = 0;
2068
+ resolvedManifest;
2069
+ symbolToChunkResolver;
2070
+ renderOptions;
2071
+ outOfOrderStreaming;
2072
+ serializationCtx;
2073
+ // Sometimes there is no app state, but framework metadata still points to a vnode id.
2074
+ // For example, an OOOS segment can point outside the segment to a root vnode through
2075
+ // q:sparent, so root vnode data must still be emitted for the client ref table.
2076
+ hasVNodeRefsForSerialization = false;
2077
+ /**
2078
+ * We use this to append additional nodes in the head node
2079
+ *
2080
+ * - From manifest injections
2081
+ * - From useStyles and useScopedStyles hooks
2082
+ */
2083
+ additionalHeadNodes = new Array();
2084
+ /**
2085
+ * We use this to append additional nodes in the body node
2086
+ *
2087
+ * - From manifest injections
2088
+ */
2089
+ additionalBodyNodes = new Array();
2090
+ lastNode = null;
2091
+ currentComponentNode = null;
2092
+ styleIds = /* @__PURE__ */ new Set();
2093
+ isBackpatchExecutorEmitted = false;
2094
+ isOutOfOrderExecutorEmitted = false;
2095
+ backpatchMap = /* @__PURE__ */ new Map();
2096
+ currentElementFrame = null;
2097
+ renderTimer;
2098
+ /**
2099
+ * Current element index.
2100
+ *
2101
+ * This number must match the depth-first traversal of the DOM elements as returned by the
2102
+ * https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker
2103
+ */
2104
+ depthFirstElementCount = -1;
2105
+ vNodeDatas = [];
2106
+ vNodeDataOffset = 0;
2107
+ componentStack = [];
2108
+ cleanupQueue = [];
2109
+ emitContainerDataFrame = null;
2110
+ $instanceHash$ = randomStr();
2111
+ // Temporary flag to find missing roots after the state was serialized
2112
+ $noMoreRoots$ = false;
2113
+ qlInclude;
2114
+ promiseAttributes = null;
2115
+ vnodeSegment = null;
2116
+ $containerState$ = 0 /* NotReady */;
2117
+ // OOOS related fields
2118
+ outOfOrderId = 0;
2119
+ outOfOrderUsed = false;
2120
+ outOfOrderPendingSegments = [];
2121
+ outOfOrderSegments = [];
2122
+ rootContainerReadyPromise = null;
2123
+ resolveRootContainerReady = null;
2124
+ renderQueue = Promise.resolve();
2125
+ emittedQwikEventNames = /* @__PURE__ */ new Set();
2126
+ emittedSyncFnCount = 0;
2127
+ rootContainerSerializedRootCount = 0;
2128
+ emittedVNodeDataOwners = null;
1952
2129
  constructor(opts) {
1953
- super(
1954
- () => {
1955
- try {
1956
- return this.$scheduler$(255 /* WAIT_FOR_ALL */);
1957
- } catch (e) {
1958
- this.handleError(e, null);
1959
- }
1960
- },
1961
- () => null,
1962
- opts.renderOptions.serverData ?? EMPTY_OBJ,
1963
- opts.locale
1964
- );
1965
- __publicField(this, "tag");
1966
- __publicField(this, "isHtml");
1967
- __publicField(this, "writer");
1968
- __publicField(this, "timing");
1969
- __publicField(this, "resolvedManifest");
1970
- __publicField(this, "symbolToChunkResolver");
1971
- __publicField(this, "renderOptions");
1972
- __publicField(this, "serializationCtx");
1973
- /**
1974
- * We use this to append additional nodes in the head node
1975
- *
1976
- * - From manifest injections
1977
- * - From useStyles and useScopedStyles hooks
1978
- */
1979
- __publicField(this, "additionalHeadNodes", new Array());
1980
- /**
1981
- * We use this to append additional nodes in the body node
1982
- *
1983
- * - From manifest injections
1984
- */
1985
- __publicField(this, "additionalBodyNodes", new Array());
1986
- __publicField(this, "lastNode", null);
1987
- __publicField(this, "currentComponentNode", null);
1988
- __publicField(this, "styleIds", /* @__PURE__ */ new Set());
1989
- __publicField(this, "currentElementFrame", null);
1990
- __publicField(this, "renderTimer");
1991
- /**
1992
- * Current element index.
1993
- *
1994
- * This number must match the depth-first traversal of the DOM elements as returned by the
1995
- * https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker
1996
- */
1997
- __publicField(this, "depthFirstElementCount", -1);
1998
- __publicField(this, "vNodeDatas", []);
1999
- __publicField(this, "componentStack", []);
2000
- __publicField(this, "unclaimedProjections", []);
2001
- __publicField(this, "unclaimedProjectionComponentFrameQueue", []);
2002
- __publicField(this, "cleanupQueue", []);
2003
- __publicField(this, "$instanceHash$", hash());
2004
- // Temporary flag to find missing roots after the state was serialized
2005
- __publicField(this, "$noMoreRoots$", false);
2130
+ super(opts.renderOptions.serverData ?? {}, opts.locale);
2006
2131
  this.symbolToChunkResolver = (symbol) => {
2007
2132
  const idx = symbol.lastIndexOf("_");
2008
2133
  const chunk = this.resolvedManifest.mapper[idx == -1 ? symbol : symbol.substring(idx + 1)];
@@ -2018,10 +2143,31 @@ var SSRContainer = class extends _SharedContainer {
2018
2143
  this.tag = opts.tagName;
2019
2144
  this.isHtml = opts.tagName === "html";
2020
2145
  this.writer = opts.writer;
2146
+ this.streamHandler = opts.streamHandler;
2021
2147
  this.timing = opts.timing;
2022
2148
  this.$buildBase$ = opts.buildBase;
2023
2149
  this.resolvedManifest = opts.resolvedManifest;
2024
2150
  this.renderOptions = opts.renderOptions;
2151
+ const outOfOrderStreaming = this.renderOptions.streaming?.outOfOrder === true;
2152
+ if (!__EXPERIMENTAL__.suspense) {
2153
+ if (outOfOrderStreaming) {
2154
+ throw new Error(
2155
+ 'Out-of-order Suspense streaming requires `experimental: ["suspense"]` in the `qwikVite` plugin.'
2156
+ );
2157
+ }
2158
+ this.outOfOrderStreaming = false;
2159
+ } else {
2160
+ this.outOfOrderStreaming = outOfOrderStreaming;
2161
+ }
2162
+ this.$currentUniqueId$ = 1e5;
2163
+ const qlOpt = this.renderOptions.qwikLoader;
2164
+ this.qlInclude = qlOpt ? typeof qlOpt === "object" ? qlOpt.include === "never" ? 2 /* Done */ : 0 /* Module */ : qlOpt === "inline" ? 1 /* Inline */ : qlOpt === "never" ? 2 /* Done */ : 0 /* Module */ : 0 /* Module */;
2165
+ if (this.qlInclude === 0 /* Module */) {
2166
+ const qwikLoaderChunk = this.resolvedManifest?.manifest.qwikLoader;
2167
+ if (!qwikLoaderChunk) {
2168
+ this.qlInclude = 1 /* Inline */;
2169
+ }
2170
+ }
2025
2171
  this.$processInjectionsFromManifest$();
2026
2172
  }
2027
2173
  ensureProjectionResolved(_host) {
@@ -2029,40 +2175,201 @@ var SSRContainer = class extends _SharedContainer {
2029
2175
  handleError(err, _$host$) {
2030
2176
  throw err;
2031
2177
  }
2178
+ addBackpatchEntry(ssrNodeId, attrName, serializedValue) {
2179
+ const elementIndex = parseInt(ssrNodeId, 10);
2180
+ const entry = {
2181
+ attrName,
2182
+ value: serializedValue
2183
+ };
2184
+ const entries = this.backpatchMap.get(elementIndex) || [];
2185
+ entries.push(entry);
2186
+ this.backpatchMap.set(elementIndex, entries);
2187
+ }
2032
2188
  async render(jsx) {
2033
2189
  this.openContainer();
2034
- await _walkJSX(this, jsx, {
2190
+ await this.renderJSX(jsx, {
2035
2191
  currentStyleScoped: null,
2036
2192
  parentComponentFrame: this.getComponentFrame()
2037
2193
  });
2038
2194
  await this.closeContainer();
2039
2195
  }
2196
+ async renderJSX(jsx, options) {
2197
+ await _walkJSX(this, jsx, options);
2198
+ }
2199
+ $isReadyForOOOS$() {
2200
+ return this.$containerState$ === 2 /* OOOSReady */;
2201
+ }
2202
+ /** Queue OOOS serialization/write work that must not overlap with root state serialization. */
2203
+ $runQueuedRender$(render) {
2204
+ if (!__EXPERIMENTAL__.suspense || !this.outOfOrderStreaming) {
2205
+ return render();
2206
+ }
2207
+ if (this.$containerState$ === 0 /* NotReady */) {
2208
+ return render();
2209
+ }
2210
+ const result = this.$containerState$ === 1 /* DataStreamStarted */ ? this.renderQueue.then(() => this.$waitForRootContainerReady$()).then(render) : this.renderQueue.then(render);
2211
+ this.renderQueue = result.catch(() => {
2212
+ });
2213
+ return result;
2214
+ }
2215
+ $waitForRootContainerReady$() {
2216
+ if (!__EXPERIMENTAL__.suspense || !this.outOfOrderStreaming || this.$isReadyForOOOS$()) {
2217
+ return;
2218
+ }
2219
+ return this.rootContainerReadyPromise ||= new Promise((resolve) => {
2220
+ this.resolveRootContainerReady = resolve;
2221
+ });
2222
+ }
2223
+ $markRootContainerReady$() {
2224
+ if (!__EXPERIMENTAL__.suspense || !this.outOfOrderStreaming || this.$isReadyForOOOS$()) {
2225
+ return;
2226
+ }
2227
+ this.rootContainerSerializedRootCount = this.serializationCtx.$roots$.length;
2228
+ this.$containerState$ = 2 /* OOOSReady */;
2229
+ this.resolveRootContainerReady?.();
2230
+ this.resolveRootContainerReady = null;
2231
+ this.rootContainerReadyPromise = null;
2232
+ }
2233
+ nextOutOfOrderId() {
2234
+ if (!__EXPERIMENTAL__.suspense || !this.outOfOrderStreaming) {
2235
+ return 0;
2236
+ }
2237
+ this.outOfOrderUsed = true;
2238
+ return ++this.outOfOrderId;
2239
+ }
2240
+ emitOutOfOrderSegmentScripts(scripts) {
2241
+ if (!__EXPERIMENTAL__.suspense || !this.outOfOrderStreaming || !scripts) {
2242
+ return;
2243
+ }
2244
+ this.write(scripts);
2245
+ }
2246
+ async segment(segmentId, jsx, options) {
2247
+ if (!__EXPERIMENTAL__.suspense) {
2248
+ throw new Error(
2249
+ 'Out-of-order Suspense streaming requires `experimental: ["suspense"]` in the `qwikVite` plugin.'
2250
+ );
2251
+ }
2252
+ if (!this.outOfOrderStreaming) {
2253
+ throw new Error(
2254
+ "Out-of-order Suspense streaming requires `streaming.outOfOrder` to be `true`."
2255
+ );
2256
+ }
2257
+ this.markVNodeRefForSerialization(options.parentComponentFrame?.componentNode);
2258
+ const writer = new StringBufferSegmentWriter();
2259
+ const segmentContainer = this.createSegmentContainer(segmentId, writer);
2260
+ this.outOfOrderSegments.push(segmentContainer);
2261
+ try {
2262
+ await segmentContainer.renderJSX(jsx, options);
2263
+ await segmentContainer.resolvePromiseAttributes();
2264
+ const htmlChunks = writer.extract();
2265
+ return {
2266
+ container: segmentContainer,
2267
+ writer,
2268
+ htmlChunks
2269
+ };
2270
+ } catch (error) {
2271
+ this.removeOutOfOrderSegment(segmentContainer);
2272
+ throw error;
2273
+ }
2274
+ }
2275
+ $getRootContainer$() {
2276
+ let rootContainer = this;
2277
+ while (rootContainer instanceof SSRSegmentContainer) {
2278
+ rootContainer = rootContainer.$rootContainer$;
2279
+ }
2280
+ return rootContainer;
2281
+ }
2282
+ createSegmentContainer(segmentId, writer) {
2283
+ const rootContainer = this.$getRootContainer$();
2284
+ const contentHostNode = this.getOrCreateLastNode();
2285
+ this.addRoot(contentHostNode);
2286
+ this.markVNodeRefForSerialization(contentHostNode);
2287
+ const rootFrame = {
2288
+ tagNesting: 10 /* ANYTHING */,
2289
+ parent: null,
2290
+ elementName: "#segment",
2291
+ depthFirstElementIdx: -1,
2292
+ // OOOS inserts this synthetic root under the Suspense content host on the client.
2293
+ vNodeData: [16 /* SERIALIZE */],
2294
+ currentFile: null,
2295
+ refBase: contentHostNode.id
2296
+ };
2297
+ const segmentContainer = new SSRSegmentContainer(
2298
+ {
2299
+ tagName: this.tag,
2300
+ writer,
2301
+ streamHandler: noopStreamHandler,
2302
+ locale: this.$locale$,
2303
+ timing: this.timing,
2304
+ buildBase: this.$buildBase$ || "/build/",
2305
+ resolvedManifest: this.resolvedManifest,
2306
+ renderOptions: this.renderOptions
2307
+ },
2308
+ rootContainer
2309
+ );
2310
+ const innerSegmentContainer = segmentContainer;
2311
+ innerSegmentContainer.$isOutOfOrderSegment$ = true;
2312
+ innerSegmentContainer.$storeProxyMap$ = this.$storeProxyMap$;
2313
+ segmentContainer.serializationCtx = segmentContainer.serializationCtxFactory(
2314
+ SsrNode,
2315
+ DomRef,
2316
+ this.symbolToChunkResolver,
2317
+ writer
2318
+ );
2319
+ segmentContainer.serializationCtx.$addSyncFn$ = this.serializationCtx.$addSyncFn$.bind(
2320
+ this.serializationCtx
2321
+ );
2322
+ segmentContainer.currentElementFrame = rootFrame;
2323
+ segmentContainer.currentComponentNode = this.currentComponentNode;
2324
+ segmentContainer.depthFirstElementCount = 0;
2325
+ segmentContainer.vNodeDatas = [rootFrame.vNodeData];
2326
+ segmentContainer.componentStack = this.componentStack.slice();
2327
+ segmentContainer.vnodeSegment = segmentId;
2328
+ segmentContainer.styleIds = this.styleIds;
2329
+ segmentContainer.emittedQwikEventNames = this.emittedQwikEventNames;
2330
+ segmentContainer.qlInclude = 2 /* Done */;
2331
+ segmentContainer.$instanceHash$ = this.$instanceHash$;
2332
+ innerSegmentContainer._didAddQwikLoader = true;
2333
+ return segmentContainer;
2334
+ }
2335
+ queueOutOfOrderSegment(segment) {
2336
+ if (!__EXPERIMENTAL__.suspense || !this.outOfOrderStreaming) {
2337
+ return;
2338
+ }
2339
+ this.outOfOrderPendingSegments.push(segment);
2340
+ }
2341
+ removeOutOfOrderSegment(segment) {
2342
+ const segments = this.outOfOrderSegments;
2343
+ for (let i = 0; i < segments.length; i++) {
2344
+ if (segments[i] === segment) {
2345
+ segments.splice(i, 1);
2346
+ return;
2347
+ }
2348
+ }
2349
+ }
2040
2350
  setContext(host, context, value) {
2041
2351
  const ssrNode = host;
2042
2352
  let ctx = ssrNode.getProp(QCtxAttr);
2043
- if (!ctx) {
2353
+ if (ctx == null) {
2044
2354
  ssrNode.setProp(QCtxAttr, ctx = []);
2045
2355
  }
2046
- mapArray_set(ctx, context.id, value, 0);
2356
+ mapArray_set(ctx, context.id, value, 0, true);
2047
2357
  this.addRoot(ssrNode);
2048
2358
  }
2049
2359
  resolveContext(host, contextId) {
2050
2360
  let ssrNode = host;
2051
2361
  while (ssrNode) {
2052
2362
  const ctx = ssrNode.getProp(QCtxAttr);
2053
- if (ctx) {
2054
- const value = mapArray_get(ctx, contextId.id, 0);
2055
- if (value) {
2056
- return value;
2057
- }
2363
+ if (ctx != null && mapArray_has(ctx, contextId.id, 0)) {
2364
+ return mapArray_get(ctx, contextId.id, 0);
2058
2365
  }
2059
- ssrNode = ssrNode.parentSsrNode;
2366
+ ssrNode = ssrNode.parentComponent;
2060
2367
  }
2061
2368
  return void 0;
2062
2369
  }
2063
2370
  getParentHost(host) {
2064
2371
  const ssrNode = host;
2065
- return ssrNode.parentSsrNode;
2372
+ return ssrNode.parentComponent;
2066
2373
  }
2067
2374
  setHostProp(host, name, value) {
2068
2375
  const ssrNode = host;
@@ -2085,52 +2392,97 @@ var SSRContainer = class extends _SharedContainer {
2085
2392
  containerAttributes[QContainerAttr] = "paused" /* PAUSED */;
2086
2393
  containerAttributes[QRuntimeAttr] = "2";
2087
2394
  containerAttributes[QVersionAttr] = this.$version$ ?? "dev";
2088
- containerAttributes[QRenderAttr] = (qRender ? qRender + "-" : "") + (isDev4 ? "ssr-dev" : "ssr");
2395
+ containerAttributes[QRenderAttr] = (qRender ? qRender + "-" : "") + (isDev8 ? "ssr-dev" : "ssr");
2089
2396
  containerAttributes[QBaseAttr] = this.$buildBase$ || "";
2090
2397
  containerAttributes[QLocaleAttr] = this.$locale$;
2091
2398
  containerAttributes[QManifestHashAttr] = this.resolvedManifest.manifest.manifestHash;
2092
2399
  containerAttributes[QInstanceAttr] = this.$instanceHash$;
2400
+ const statePrewarm = this.renderOptions.statePrewarm;
2401
+ if (typeof statePrewarm === "number") {
2402
+ containerAttributes[QStatePrewarmAttr] = String(statePrewarm);
2403
+ } else {
2404
+ delete containerAttributes[QStatePrewarmAttr];
2405
+ }
2093
2406
  this.$serverData$.containerAttributes = containerAttributes;
2094
- const containerAttributeArray = Object.entries(containerAttributes).reduce(
2095
- (acc, [key, value]) => {
2096
- acc.push(key, value);
2097
- return acc;
2098
- },
2099
- []
2100
- );
2101
- this.openElement(this.tag, containerAttributeArray);
2407
+ this.openElement(this.tag, null, containerAttributes);
2408
+ if (!this.isHtml) {
2409
+ this.emitContainerDataFrame = this.currentElementFrame;
2410
+ }
2102
2411
  }
2103
2412
  /** Renders closing tag for current container */
2104
2413
  closeContainer() {
2105
2414
  return this.closeElement();
2106
2415
  }
2416
+ $noScriptHere$ = 0;
2107
2417
  /** Renders opening tag for DOM element */
2108
- openElement(elementName, varAttrs, constAttrs, currentFile) {
2418
+ openElement(elementName, key, varAttrs, constAttrs = null, styleScopedId = null, currentFile = null, hasMovedCaptures = true) {
2419
+ if (!VALID_ELEMENT_NAME.test(elementName)) {
2420
+ throw qError(36 /* invalidElementName */, [JSON.stringify(elementName)]);
2421
+ }
2422
+ const isQwikStyle = isQwikStyleElement(elementName, varAttrs) || isQwikStyleElement(elementName, constAttrs);
2423
+ if (NO_SCRIPT_HERE_ELEMENTS.has(elementName)) {
2424
+ this.$noScriptHere$++;
2425
+ }
2426
+ if (
2427
+ // don't append qwik loader before qwik style elements
2428
+ // it will confuse the resuming, because styles are expected to be the first nodes in subtree
2429
+ !isQwikStyle && this.qlInclude === 1 /* Inline */
2430
+ ) {
2431
+ if (this.$noScriptHere$ === 0 && this.size > 30 * 1024 && elementName !== "body") {
2432
+ this.emitQwikLoaderInline();
2433
+ }
2434
+ }
2109
2435
  let innerHTML = void 0;
2110
2436
  this.lastNode = null;
2111
- const isQwikStyle = isQwikStyleElement(elementName, varAttrs) || isQwikStyleElement(elementName, constAttrs);
2112
2437
  if (!isQwikStyle && this.currentElementFrame) {
2113
2438
  vNodeData_incrementElementCount(this.currentElementFrame.vNodeData);
2114
2439
  }
2115
2440
  this.createAndPushFrame(elementName, this.depthFirstElementCount++, currentFile);
2441
+ if (this.isHtml && elementName === "body" && this.emitContainerDataFrame === null) {
2442
+ this.emitContainerDataFrame = this.currentElementFrame;
2443
+ }
2116
2444
  vNodeData_openElement(this.currentElementFrame.vNodeData);
2117
- this.write("<");
2445
+ this.write(LT);
2118
2446
  this.write(elementName);
2447
+ const lastNode = this.getOrCreateLastNode();
2119
2448
  if (varAttrs) {
2120
- innerHTML = this.writeAttrs(elementName, varAttrs, false, currentFile);
2449
+ innerHTML = this.writeAttrs(
2450
+ elementName,
2451
+ varAttrs,
2452
+ false,
2453
+ styleScopedId,
2454
+ currentFile,
2455
+ hasMovedCaptures
2456
+ );
2121
2457
  }
2122
2458
  this.write(" " + Q_PROPS_SEPARATOR);
2123
- isDev4 && this.write('=""');
2124
- if (constAttrs && constAttrs.length) {
2125
- innerHTML = this.writeAttrs(elementName, constAttrs, true, currentFile) || innerHTML;
2459
+ if (key !== null) {
2460
+ this.write(ATTR_EQUALS_QUOTE);
2461
+ this.write(escapeHTML(key));
2462
+ this.write(QUOTE);
2463
+ } else if (qTest) {
2464
+ this.write(EMPTY_ATTR);
2465
+ }
2466
+ if (constAttrs && !isObjectEmpty(constAttrs)) {
2467
+ innerHTML = this.writeAttrs(
2468
+ elementName,
2469
+ constAttrs,
2470
+ true,
2471
+ styleScopedId,
2472
+ currentFile,
2473
+ hasMovedCaptures
2474
+ ) || innerHTML;
2475
+ }
2476
+ this.write(GT);
2477
+ if (lastNode) {
2478
+ lastNode.setTreeNonUpdatable();
2126
2479
  }
2127
- this.write(">");
2128
- this.lastNode = null;
2129
2480
  return innerHTML;
2130
2481
  }
2131
2482
  /** Renders closing tag for DOM element */
2132
2483
  closeElement() {
2133
- if (this.shouldEmitDataBeforeClosingElement()) {
2484
+ if (this.currentElementFrame === this.emitContainerDataFrame) {
2485
+ this.emitContainerDataFrame = null;
2134
2486
  this.onRenderDone();
2135
2487
  const snapshotTimer = createTimer();
2136
2488
  return maybeThen(
@@ -2142,16 +2494,6 @@ var SSRContainer = class extends _SharedContainer {
2142
2494
  }
2143
2495
  this._closeElement();
2144
2496
  }
2145
- shouldEmitDataBeforeClosingElement() {
2146
- const currentFrame = this.currentElementFrame;
2147
- return (
2148
- /**
2149
- * - Micro-frontends don't have html tag, emit data before closing custom element
2150
- * - Regular applications should emit data inside body
2151
- */
2152
- currentFrame.parent === null && currentFrame.elementName !== "html" || currentFrame.elementName === "body"
2153
- );
2154
- }
2155
2497
  onRenderDone() {
2156
2498
  this.drainCleanupQueue();
2157
2499
  this.timing.render = this.renderTimer();
@@ -2173,11 +2515,14 @@ var SSRContainer = class extends _SharedContainer {
2173
2515
  const currentFrame = this.popFrame();
2174
2516
  const elementName = currentFrame.elementName;
2175
2517
  if (!isSelfClosingTag(elementName)) {
2176
- this.write("</");
2518
+ this.write(CLOSE_TAG);
2177
2519
  this.write(elementName);
2178
- this.write(">");
2520
+ this.write(GT);
2179
2521
  }
2180
2522
  this.lastNode = null;
2523
+ if (NO_SCRIPT_HERE_ELEMENTS.has(elementName)) {
2524
+ this.$noScriptHere$--;
2525
+ }
2181
2526
  }
2182
2527
  /** Writes opening data to vNodeData for fragment boundaries */
2183
2528
  openFragment(attrs) {
@@ -2188,13 +2533,22 @@ var SSRContainer = class extends _SharedContainer {
2188
2533
  /** Writes closing data to vNodeData for fragment boundaries */
2189
2534
  closeFragment() {
2190
2535
  vNodeData_closeFragment(this.currentElementFrame.vNodeData);
2536
+ if (this.currentComponentNode) {
2537
+ this.currentComponentNode.setTreeNonUpdatable();
2538
+ }
2191
2539
  this.lastNode = null;
2192
2540
  }
2193
2541
  openProjection(attrs) {
2194
2542
  this.openFragment(attrs);
2195
2543
  const componentFrame = this.getComponentFrame();
2196
2544
  if (componentFrame) {
2197
- this.serializationCtx.$addRoot$(componentFrame.componentNode);
2545
+ const projectionNode = this.getOrCreateLastNode();
2546
+ this.markVNodeRefForSerialization(projectionNode);
2547
+ if (!this.vnodeSegment) {
2548
+ this.addRoot(componentFrame.componentNode);
2549
+ } else {
2550
+ this.markVNodeRefForSerialization(componentFrame.componentNode);
2551
+ }
2198
2552
  componentFrame.projectionDepth++;
2199
2553
  }
2200
2554
  }
@@ -2227,12 +2581,42 @@ var SSRContainer = class extends _SharedContainer {
2227
2581
  const localProjectionDepth = this.getComponentFrame()?.projectionDepth || 0;
2228
2582
  return this.getComponentFrame(localProjectionDepth);
2229
2583
  }
2230
- /** Writes closing data to vNodeData for component boundaries and mark unclaimed projections */
2231
- closeComponent() {
2584
+ /** Writes closing data to vNodeData for component boundaries and emit unclaimed projections inline */
2585
+ async closeComponent() {
2232
2586
  const componentFrame = this.componentStack.pop();
2233
- componentFrame.releaseUnclaimedProjections(this.unclaimedProjections);
2587
+ await this.emitUnclaimedProjectionForComponent(componentFrame);
2234
2588
  this.closeFragment();
2235
- this.currentComponentNode = this.currentComponentNode?.parentSsrNode || null;
2589
+ this.currentComponentNode = this.currentComponentNode?.parentComponent || null;
2590
+ }
2591
+ async emitUnclaimedProjectionForComponent(componentFrame) {
2592
+ if (componentFrame.slots.length === 0) {
2593
+ return;
2594
+ }
2595
+ this.openElement(QTemplate, null, QTemplateProps, null);
2596
+ const scopedStyleId = componentFrame.projectionScopedStyle;
2597
+ for (let i = 0; i < componentFrame.slots.length; i += 2) {
2598
+ const slotName = componentFrame.slots[i];
2599
+ const children = componentFrame.slots[i + 1];
2600
+ if (this.vnodeSegment) {
2601
+ this.markVNodeRefForSerialization(componentFrame.componentNode);
2602
+ }
2603
+ this.openFragment(
2604
+ isDev8 ? {
2605
+ [DEBUG_TYPE]: "P" /* Projection */,
2606
+ [QSlotParent]: componentFrame.componentNode.id,
2607
+ [QSlot]: slotName
2608
+ } : { [QSlotParent]: componentFrame.componentNode.id, [QSlot]: slotName }
2609
+ );
2610
+ const lastNode = this.getOrCreateLastNode();
2611
+ lastNode.vnodeData[0] |= 16 /* SERIALIZE */;
2612
+ componentFrame.componentNode.setProp(slotName, lastNode.id);
2613
+ await this.renderJSX(children, {
2614
+ currentStyleScoped: scopedStyleId,
2615
+ parentComponentFrame: componentFrame.projectionComponentFrame
2616
+ });
2617
+ this.closeFragment();
2618
+ }
2619
+ this.closeElement();
2236
2620
  }
2237
2621
  /** Write a text node with correct escaping. Save the length of the text node in the vNodeData. */
2238
2622
  textNode(text) {
@@ -2248,24 +2632,28 @@ var SSRContainer = class extends _SharedContainer {
2248
2632
  }
2249
2633
  addRoot(obj) {
2250
2634
  if (this.$noMoreRoots$) {
2251
- return this.serializationCtx.$hasRootId$(obj);
2635
+ const rootId = this.serializationCtx.$hasRootId$(obj);
2636
+ return rootId;
2252
2637
  }
2253
2638
  return this.serializationCtx.$addRoot$(obj);
2254
2639
  }
2255
2640
  getOrCreateLastNode() {
2256
2641
  if (!this.lastNode) {
2642
+ const currentFrame = this.currentElementFrame;
2643
+ const elementIndex = currentFrame.depthFirstElementIdx + 1;
2644
+ const refBase = currentFrame.refBase ?? (this.vnodeSegment ? getSegmentVNodeRefId(this.vnodeSegment, elementIndex) : elementIndex + this.vNodeDataOffset);
2257
2645
  this.lastNode = vNodeData_createSsrNodeReference(
2258
2646
  this.currentComponentNode,
2259
- this.currentElementFrame.vNodeData,
2260
- // we start at -1, so we need to add +1
2261
- this.currentElementFrame.depthFirstElementIdx + 1,
2262
- this.cleanupQueue
2647
+ currentFrame.vNodeData,
2648
+ refBase,
2649
+ this.cleanupQueue,
2650
+ currentFrame.currentFile
2263
2651
  );
2264
2652
  }
2265
2653
  return this.lastNode;
2266
2654
  }
2267
2655
  addUnclaimedProjection(frame, name, children) {
2268
- this.unclaimedProjections.push(frame, null, name, children);
2656
+ frame.slots.push(name, children);
2269
2657
  }
2270
2658
  $processInjectionsFromManifest$() {
2271
2659
  const injections = this.resolvedManifest.manifest.injections;
@@ -2308,23 +2696,72 @@ var SSRContainer = class extends _SharedContainer {
2308
2696
  }
2309
2697
  }
2310
2698
  _styleNode(styleId, content) {
2311
- this.openElement("style", [QStyle, styleId]);
2699
+ this.openElement("style", null, {
2700
+ [QStyle]: styleId
2701
+ });
2312
2702
  this.write(content);
2313
2703
  this.closeElement();
2314
2704
  }
2705
+ $deferRootPlaceholder$(scriptNode) {
2706
+ if (this.isHtml && this.currentElementFrame?.elementName === "html") {
2707
+ this.additionalHeadNodes.push(scriptNode);
2708
+ return true;
2709
+ }
2710
+ return false;
2711
+ }
2315
2712
  ////////////////////////////////////
2316
2713
  emitContainerData() {
2714
+ const isStreamingDisabled = this.renderOptions.streaming?.inOrder?.strategy === "disabled";
2715
+ const shouldFlushShell = !isStreamingDisabled || __EXPERIMENTAL__.suspense && this.outOfOrderStreaming && this.outOfOrderUsed;
2317
2716
  return maybeThen(
2318
- this.emitUnclaimedProjection(),
2319
- () => maybeThen(this.emitStateData(), () => {
2320
- this.$noMoreRoots$ = true;
2321
- this.emitVNodeData();
2322
- preloaderPost(this, this.renderOptions, this.$serverData$?.nonce);
2323
- this.emitSyncFnsData();
2324
- this.emitQwikLoaderAtBottomIfNeeded();
2325
- })
2717
+ maybeThen(
2718
+ shouldFlushShell ? this.streamHandler.flush() : void 0,
2719
+ () => this.resolvePromiseAttributes()
2720
+ ),
2721
+ () => {
2722
+ this.$containerState$ = 1 /* DataStreamStarted */;
2723
+ return maybeThen(this.emitStateData(), () => {
2724
+ this.$noMoreRoots$ = true;
2725
+ return maybeThen(this.emitRestStateData(), () => this.emitOutOfOrderSegmentsAndData());
2726
+ });
2727
+ }
2326
2728
  );
2327
2729
  }
2730
+ emitRestStateData() {
2731
+ this.emitVNodeData();
2732
+ this.emitDelayedOutOfOrderSegmentVNodeData();
2733
+ if (!isDev8) {
2734
+ preloaderPost(this, this.renderOptions, this.$serverData$?.nonce);
2735
+ }
2736
+ this.emitSyncFnsData();
2737
+ this.emitPatchDataIfNeeded();
2738
+ this.emitExecutorIfNeeded();
2739
+ this.emitQwikLoaderAtBottomIfNeeded();
2740
+ }
2741
+ emitDelayedOutOfOrderSegmentVNodeData() {
2742
+ if (!__EXPERIMENTAL__.suspense || !this.outOfOrderStreaming || !this.outOfOrderUsed) {
2743
+ return;
2744
+ }
2745
+ for (let i = 0; i < this.outOfOrderSegments.length; i++) {
2746
+ const segment = this.outOfOrderSegments[i];
2747
+ if (segment.$outOfOrderState$ === 1 /* EarlyFinalized */) {
2748
+ segment.$emitDelayedOutOfOrderVNodeData$();
2749
+ i--;
2750
+ }
2751
+ }
2752
+ }
2753
+ emitOutOfOrderSegmentsAndData() {
2754
+ if (!__EXPERIMENTAL__.suspense || !this.outOfOrderStreaming || !this.outOfOrderUsed) {
2755
+ return;
2756
+ }
2757
+ this.emitOutOfOrderExecutorIfNeeded();
2758
+ return maybeThen(this.streamHandler.flush(), async () => {
2759
+ this.$markRootContainerReady$();
2760
+ if (this.outOfOrderPendingSegments.length) {
2761
+ await Promise.all(this.outOfOrderPendingSegments);
2762
+ }
2763
+ });
2764
+ }
2328
2765
  /**
2329
2766
  * Serialize the vNodeData into a string and emit it as a script tag.
2330
2767
  *
@@ -2343,16 +2780,25 @@ var SSRContainer = class extends _SharedContainer {
2343
2780
  * NOTE: Not every element will need vNodeData. So we need to encode how many elements should be
2344
2781
  * skipped. By choosing different separators we can encode different numbers of elements to skip.
2345
2782
  */
2346
- emitVNodeData() {
2347
- if (!this.serializationCtx.$roots$.length) {
2783
+ emitVNodeData(segmentId) {
2784
+ this.$getRootContainer$().markVNodeDataOwnerEmitted(segmentId);
2785
+ if (!segmentId && !this.serializationCtx.$roots$.length && !this.hasVNodeRefsForSerialization) {
2348
2786
  return;
2349
2787
  }
2350
- this.openElement("script", ["type", "qwik/vnode"]);
2788
+ this.emitVNodeDataScript(segmentId, this.vNodeDatas.entries());
2789
+ }
2790
+ emitVNodeDataScript(segmentId, entries, patch = false) {
2791
+ const attrs = { type: "qwik/vnode" };
2792
+ if (__EXPERIMENTAL__.suspense && this.outOfOrderStreaming && segmentId) {
2793
+ attrs[QSuspenseResolved] = segmentId;
2794
+ }
2795
+ if (patch) {
2796
+ attrs[QStatePatchAttr] = true;
2797
+ }
2798
+ this.openScript(attrs);
2351
2799
  const vNodeAttrsStack = [];
2352
- const vNodeData = this.vNodeDatas;
2353
2800
  let lastSerializedIdx = 0;
2354
- for (let elementIdx = 0; elementIdx < vNodeData.length; elementIdx++) {
2355
- const vNode = vNodeData[elementIdx];
2801
+ for (const [elementIdx, vNode] of entries) {
2356
2802
  const flag = vNode[0];
2357
2803
  if (flag & 16 /* SERIALIZE */) {
2358
2804
  lastSerializedIdx = this.emitVNodeSeparators(lastSerializedIdx, elementIdx);
@@ -2364,7 +2810,7 @@ var SSRContainer = class extends _SharedContainer {
2364
2810
  let depth = 0;
2365
2811
  for (let i = 1; i < vNode.length; i++) {
2366
2812
  const value = vNode[i];
2367
- if (Array.isArray(value)) {
2813
+ if (typeof value === "object" && value !== null) {
2368
2814
  vNodeAttrsStack.push(fragmentAttrs);
2369
2815
  fragmentAttrs = value;
2370
2816
  } else if (value === OPEN_FRAGMENT) {
@@ -2372,15 +2818,17 @@ var SSRContainer = class extends _SharedContainer {
2372
2818
  this.write(VNodeDataChar.OPEN_CHAR);
2373
2819
  } else if (value === CLOSE_FRAGMENT) {
2374
2820
  if (fragmentAttrs) {
2375
- writeFragmentAttrs(this.write.bind(this), this.addRoot.bind(this), fragmentAttrs);
2821
+ this.writeFragmentAttrs(fragmentAttrs);
2376
2822
  fragmentAttrs = vNodeAttrsStack.pop();
2377
2823
  }
2378
2824
  depth--;
2379
2825
  this.write(VNodeDataChar.CLOSE_CHAR);
2380
2826
  } else if (value === WRITE_ELEMENT_ATTRS) {
2381
- if (fragmentAttrs && fragmentAttrs.length) {
2827
+ if (fragmentAttrs && !isObjectEmpty(fragmentAttrs)) {
2828
+ this.write(VNodeDataChar.SEPARATOR_CHAR);
2829
+ this.write(VNodeDataChar.SEPARATOR_CHAR);
2830
+ this.writeFragmentAttrs(fragmentAttrs);
2382
2831
  this.write(VNodeDataChar.SEPARATOR_CHAR);
2383
- writeFragmentAttrs(this.write.bind(this), this.addRoot.bind(this), fragmentAttrs);
2384
2832
  this.write(VNodeDataChar.SEPARATOR_CHAR);
2385
2833
  fragmentAttrs = vNodeAttrsStack.pop();
2386
2834
  }
@@ -2392,7 +2840,7 @@ var SSRContainer = class extends _SharedContainer {
2392
2840
  }
2393
2841
  while (depth-- > 0) {
2394
2842
  if (fragmentAttrs) {
2395
- writeFragmentAttrs(this.write.bind(this), this.addRoot.bind(this), fragmentAttrs);
2843
+ this.writeFragmentAttrs(fragmentAttrs);
2396
2844
  fragmentAttrs = vNodeAttrsStack.pop();
2397
2845
  }
2398
2846
  this.write(VNodeDataChar.CLOSE_CHAR);
@@ -2400,206 +2848,323 @@ var SSRContainer = class extends _SharedContainer {
2400
2848
  }
2401
2849
  }
2402
2850
  }
2403
- function writeFragmentAttrs(write, addRoot, fragmentAttrs) {
2404
- for (let i = 0; i < fragmentAttrs.length; ) {
2405
- const key = fragmentAttrs[i++];
2406
- let value = fragmentAttrs[i++];
2407
- let encodeValue = false;
2408
- if (typeof value !== "string") {
2409
- const rootId = addRoot(value);
2410
- if (rootId === void 0) {
2411
- continue;
2412
- }
2413
- value = String(rootId);
2414
- }
2415
- switch (key) {
2416
- case QScopedStyle:
2417
- write(VNodeDataChar.SCOPED_STYLE_CHAR);
2418
- break;
2419
- case OnRenderProp:
2420
- write(VNodeDataChar.RENDER_FN_CHAR);
2421
- break;
2422
- case ELEMENT_ID:
2423
- write(VNodeDataChar.ID_CHAR);
2424
- break;
2425
- case ELEMENT_PROPS:
2426
- write(VNodeDataChar.PROPS_CHAR);
2427
- break;
2428
- case ELEMENT_KEY:
2429
- encodeValue = true;
2430
- write(VNodeDataChar.KEY_CHAR);
2431
- break;
2432
- case ELEMENT_SEQ:
2433
- write(VNodeDataChar.SEQ_CHAR);
2434
- break;
2435
- case ELEMENT_SEQ_IDX:
2436
- write(VNodeDataChar.SEQ_IDX_CHAR);
2437
- break;
2438
- case QBackRefs:
2439
- write(VNodeDataChar.BACK_REFS_CHAR);
2440
- break;
2441
- case QSlotParent:
2442
- write(VNodeDataChar.SLOT_PARENT_CHAR);
2443
- break;
2444
- // Skipping `\` character for now because it is used for escaping.
2445
- case QCtxAttr:
2446
- write(VNodeDataChar.CONTEXT_CHAR);
2447
- break;
2448
- case QSlot:
2449
- write(VNodeDataChar.SLOT_CHAR);
2450
- break;
2451
- default:
2452
- write(VNodeDataChar.SEPARATOR_CHAR);
2453
- write(key);
2454
- write(VNodeDataChar.SEPARATOR_CHAR);
2851
+ this.closeScript();
2852
+ if (patch && !segmentId) {
2853
+ this.emitInlineScript(
2854
+ "document.qProcessVNodeDataPatch&&document.qProcessVNodeDataPatch(document.currentScript.previousElementSibling)"
2855
+ );
2856
+ }
2857
+ }
2858
+ markVNodeRefForSerialization(node) {
2859
+ if (node) {
2860
+ this.hasVNodeRefsForSerialization = true;
2861
+ node.vnodeData[0] |= 16 /* SERIALIZE */ | 8 /* REFERENCE */;
2862
+ }
2863
+ }
2864
+ markVNodeDataOwnerEmitted(segmentId) {
2865
+ if (!__EXPERIMENTAL__.suspense || !this.outOfOrderStreaming) {
2866
+ return;
2867
+ }
2868
+ (this.emittedVNodeDataOwners ||= /* @__PURE__ */ new Set()).add(segmentId);
2869
+ }
2870
+ isVNodeDataOwnerEmitted(owner) {
2871
+ return this.emittedVNodeDataOwners?.has(owner) === true;
2872
+ }
2873
+ getVNodeDataOwnerFromNodeId(id) {
2874
+ const refBase = parseInt(id, 10);
2875
+ if (refBase >= 0) {
2876
+ return { owner: void 0, localIndex: refBase };
2877
+ }
2878
+ const pair = -refBase - 1;
2879
+ const diagonal = Math.floor((Math.sqrt(8 * pair + 1) - 1) / 2);
2880
+ const diagonalStart = diagonal * (diagonal + 1) / 2;
2881
+ const localIndex = pair - diagonalStart;
2882
+ const segmentIndex = diagonal - localIndex;
2883
+ return { owner: String(segmentIndex + 1), localIndex };
2884
+ }
2885
+ writeFragmentAttrs(fragmentAttrs) {
2886
+ for (const key in fragmentAttrs) {
2887
+ const rawValue = fragmentAttrs[key];
2888
+ let value = rawValue;
2889
+ let rootId;
2890
+ let encodeValue = null;
2891
+ if (key === ELEMENT_ID && typeof rawValue === "number") {
2892
+ rootId = rawValue;
2893
+ value = String(rawValue);
2894
+ } else if (typeof rawValue !== "string") {
2895
+ rootId = this.addRoot(rawValue);
2896
+ if (rootId === void 0) {
2897
+ if (key === OnRenderProp) {
2898
+ this.write(VNodeDataChar.RENDER_FN_CHAR);
2899
+ this.write(VNodeDataChar.RENDER_HASH_PREFIX_CHAR);
2900
+ this.write(encodeVNodeDataString(encodeVNodeDataKey(rawValue.$hash$)));
2901
+ }
2902
+ continue;
2455
2903
  }
2456
- const encodedValue = encodeValue ? encodeURI(value) : value;
2457
- const isEncoded = encodeValue ? encodedValue !== value : false;
2458
- if (isEncoded) {
2459
- write(VNodeDataChar.SEPARATOR_CHAR);
2460
- write(encodedValue);
2461
- write(VNodeDataChar.SEPARATOR_CHAR);
2462
- } else {
2463
- write(value);
2904
+ value = String(rootId);
2905
+ }
2906
+ switch (key) {
2907
+ case QScopedStyle:
2908
+ this.write(VNodeDataChar.SCOPED_STYLE_CHAR);
2909
+ break;
2910
+ case OnRenderProp:
2911
+ this.write(VNodeDataChar.RENDER_FN_CHAR);
2912
+ break;
2913
+ case ELEMENT_ID:
2914
+ this.write(VNodeDataChar.ID_CHAR);
2915
+ break;
2916
+ case ELEMENT_PROPS:
2917
+ this.write(VNodeDataChar.PROPS_CHAR);
2918
+ break;
2919
+ case ELEMENT_KEY:
2920
+ encodeValue = encodeVNodeDataKey;
2921
+ this.write(VNodeDataChar.KEY_CHAR);
2922
+ break;
2923
+ case ELEMENT_SEQ:
2924
+ this.write(VNodeDataChar.SEQ_CHAR);
2925
+ break;
2926
+ case ELEMENT_SEQ_IDX:
2927
+ this.write(VNodeDataChar.SEQ_IDX_CHAR);
2928
+ break;
2929
+ case QBackRefs:
2930
+ this.write(VNodeDataChar.BACK_REFS_CHAR);
2931
+ break;
2932
+ case QSlotParent:
2933
+ this.write(VNodeDataChar.SLOT_PARENT_CHAR);
2934
+ break;
2935
+ // Skipping `\` character for now because it is used for escaping.
2936
+ case QCtxAttr:
2937
+ this.write(VNodeDataChar.CONTEXT_CHAR);
2938
+ break;
2939
+ case QSlot:
2940
+ encodeValue = encodeVNodeDataKey;
2941
+ this.write(VNodeDataChar.SLOT_CHAR);
2942
+ break;
2943
+ default: {
2944
+ encodeValue = encodeURI;
2945
+ this.write(VNodeDataChar.SEPARATOR_CHAR);
2946
+ this.write(encodeVNodeDataString(encodeVNodeDataKey(key)));
2947
+ this.write(VNodeDataChar.SEPARATOR_CHAR);
2464
2948
  }
2465
2949
  }
2950
+ const encodedValue = encodeVNodeDataString(encodeValue ? encodeValue(value) : value);
2951
+ const isEncoded = encodeValue ? encodedValue !== value : false;
2952
+ if (isEncoded) {
2953
+ this.write(VNodeDataChar.SEPARATOR_CHAR);
2954
+ this.write(encodedValue);
2955
+ this.write(VNodeDataChar.SEPARATOR_CHAR);
2956
+ } else if (typeof rootId === "number") {
2957
+ this.writeRootRef(rootId);
2958
+ } else {
2959
+ this.write(value);
2960
+ }
2466
2961
  }
2467
- this.closeElement();
2468
2962
  }
2469
2963
  emitStateData() {
2470
- if (!this.serializationCtx.$roots$.length) {
2964
+ if (!this.serializationCtx.$roots$.length && !this.serializationCtx.$eagerResume$.size) {
2471
2965
  return;
2472
2966
  }
2473
- this.openElement("script", ["type", "qwik/state"]);
2967
+ const attrs = this.stateScriptAttrs();
2968
+ this.openScript(attrs);
2969
+ this.serializationCtx.$setWriter$(this.writer);
2474
2970
  return maybeThen(this.serializationCtx.$serialize$(), () => {
2475
- this.closeElement();
2971
+ this.closeScript();
2476
2972
  });
2477
2973
  }
2478
- emitSyncFnsData() {
2974
+ /** Add q-d:qidle attribute to eagerly resume some state if needed */
2975
+ stateScriptAttrs() {
2976
+ const attrs = { type: "qwik/state", [QInstanceAttr]: this.$instanceHash$ };
2977
+ const eagerResume = this.serializationCtx.$eagerResume$;
2978
+ if (eagerResume.size > 0) {
2979
+ attrs["q-d:qidle"] = createQRL(null, "_res", _res, null, [...eagerResume]);
2980
+ }
2981
+ return attrs;
2982
+ }
2983
+ emitSyncFnsData(append = false) {
2479
2984
  const fns = this.serializationCtx.$syncFns$;
2480
- if (fns.length) {
2481
- const scriptAttrs = ["q:func", "qwik/json"];
2985
+ const start = append ? this.emittedSyncFnCount : 0;
2986
+ if (fns.length > start) {
2987
+ const scriptAttrs = { "q:func": "qwik/json" };
2482
2988
  if (this.renderOptions.serverData?.nonce) {
2483
- scriptAttrs.push("nonce", this.renderOptions.serverData.nonce);
2989
+ scriptAttrs["nonce"] = this.renderOptions.serverData.nonce;
2484
2990
  }
2485
- this.openElement("script", scriptAttrs);
2486
- this.write(Q_FUNCS_PREFIX.replace("HASH", this.$instanceHash$));
2487
- this.write("[");
2488
- this.writeArray(fns, ",");
2489
- this.write("]");
2490
- this.closeElement();
2991
+ this.openScript(scriptAttrs);
2992
+ if (append) {
2993
+ const qFuncsExpr = Q_FUNCS_PREFIX.replace("HASH", this.$instanceHash$).slice(0, -1);
2994
+ this.write(`(${qFuncsExpr}||(${qFuncsExpr}=[])).push(`);
2995
+ } else {
2996
+ this.write(Q_FUNCS_PREFIX.replace("HASH", this.$instanceHash$));
2997
+ }
2998
+ if (!append) {
2999
+ this.write(BRACKET_OPEN);
3000
+ }
3001
+ this.writeArray(append ? fns.slice(start) : fns, COMMA);
3002
+ if (!append) {
3003
+ this.write(BRACKET_CLOSE);
3004
+ }
3005
+ if (append) {
3006
+ this.write(")");
3007
+ }
3008
+ this.closeScript();
3009
+ this.emittedSyncFnCount = fns.length;
3010
+ }
3011
+ }
3012
+ emitPatchDataIfNeeded() {
3013
+ const patches = [];
3014
+ for (const [elementIndex, backpatchEntries] of this.backpatchMap) {
3015
+ for (let i = 0; i < backpatchEntries.length; i++) {
3016
+ const backpatchEntry = backpatchEntries[i];
3017
+ patches.push(
3018
+ elementIndex,
3019
+ backpatchEntry.attrName,
3020
+ isSignal(backpatchEntry.value) ? backpatchEntry.value.untrackedValue : backpatchEntry.value
3021
+ );
3022
+ }
3023
+ }
3024
+ this.backpatchMap.clear();
3025
+ if (patches.length > 0) {
3026
+ this.isBackpatchExecutorEmitted = true;
3027
+ const scriptAttrs = { type: ELEMENT_BACKPATCH_DATA };
3028
+ if (this.renderOptions.serverData?.nonce) {
3029
+ scriptAttrs["nonce"] = this.renderOptions.serverData.nonce;
3030
+ }
3031
+ this.writeScript(scriptAttrs, JSON.stringify(patches).replaceAll("<", "\\u003C"));
2491
3032
  }
2492
3033
  }
3034
+ emitBackpatchDataAndExecutorIfNeeded() {
3035
+ if (this.backpatchMap.size === 0) {
3036
+ return;
3037
+ }
3038
+ this.emitPatchDataIfNeeded();
3039
+ this.emitExecutorIfNeeded();
3040
+ }
3041
+ emitExecutorIfNeeded() {
3042
+ if (!this.isBackpatchExecutorEmitted) {
3043
+ return;
3044
+ }
3045
+ this.isBackpatchExecutorEmitted = false;
3046
+ const scriptAttrs = { type: "text/javascript" };
3047
+ if (this.renderOptions.serverData?.nonce) {
3048
+ scriptAttrs["nonce"] = this.renderOptions.serverData.nonce;
3049
+ }
3050
+ const backpatchScript = getQwikBackpatchExecutorScript({ debug: isDev8 });
3051
+ this.writeScript(scriptAttrs, backpatchScript);
3052
+ }
3053
+ emitOutOfOrderExecutorIfNeeded() {
3054
+ if (!__EXPERIMENTAL__.suspense || !this.outOfOrderStreaming || !this.outOfOrderUsed || this.isOutOfOrderExecutorEmitted) {
3055
+ return;
3056
+ }
3057
+ this.isOutOfOrderExecutorEmitted = true;
3058
+ this.writeScript(
3059
+ { type: "text/javascript", nonce: this.renderOptions.serverData?.nonce },
3060
+ getQwikOutOfOrderExecutorScript({ debug: isDev8 })
3061
+ );
3062
+ }
3063
+ emitInlineScript(script) {
3064
+ const scriptAttrs = { type: "text/javascript" };
3065
+ if (this.renderOptions.serverData?.nonce) {
3066
+ scriptAttrs["nonce"] = this.renderOptions.serverData.nonce;
3067
+ }
3068
+ this.writeScript(scriptAttrs, script);
3069
+ }
3070
+ writeScript(attrs, body) {
3071
+ this.openScript(attrs);
3072
+ if (body) {
3073
+ this.write(body);
3074
+ }
3075
+ this.closeScript();
3076
+ }
3077
+ openScript(attrs) {
3078
+ this.write("<script");
3079
+ this.writeAttrs("script", attrs, true, null, null, true);
3080
+ this.write(GT);
3081
+ }
3082
+ closeScript() {
3083
+ this.write("</script>");
3084
+ }
2493
3085
  emitPreloaderPre() {
2494
- preloaderPre(this, this.renderOptions.preloader, this.renderOptions.serverData?.nonce);
3086
+ if (!isDev8) {
3087
+ preloaderPre(this, this.renderOptions.preloader, this.renderOptions.serverData?.nonce);
3088
+ }
2495
3089
  }
2496
3090
  isStatic() {
2497
- return this.serializationCtx.$eventQrls$.size === 0;
2498
- }
2499
- getQwikLoaderIncludeMode() {
2500
- return this.renderOptions.qwikLoader?.include ?? "auto";
3091
+ return !(__EXPERIMENTAL__.suspense && this.outOfOrderStreaming && this.outOfOrderUsed) && this.serializationCtx.$eventQrls$.size === 0;
2501
3092
  }
2502
3093
  emitQwikLoaderAtTopIfNeeded() {
2503
- const includeMode = this.getQwikLoaderIncludeMode();
2504
- const includeLoader = includeMode !== "never";
2505
- if (includeLoader) {
2506
- let qwikLoaderBundle = this.resolvedManifest.manifest.qwikLoader;
2507
- if (qwikLoaderBundle) {
2508
- qwikLoaderBundle = this.$buildBase$ + qwikLoaderBundle;
2509
- this.openElement("link", ["rel", "modulepreload", "href", qwikLoaderBundle]);
2510
- this.closeElement();
2511
- this.openElement("script", ["type", "module", "async", true, "src", qwikLoaderBundle]);
2512
- this.closeElement();
3094
+ if (this.qlInclude === 0 /* Module */) {
3095
+ this.qlInclude = 2 /* Done */;
3096
+ const qwikLoaderBundle = this.$buildBase$ + this.resolvedManifest.manifest.qwikLoader;
3097
+ const linkAttrs = { rel: "modulepreload", href: qwikLoaderBundle };
3098
+ const nonce = this.renderOptions.serverData?.nonce;
3099
+ if (nonce) {
3100
+ linkAttrs["nonce"] = nonce;
3101
+ }
3102
+ this.openElement("link", null, linkAttrs);
3103
+ this.closeElement();
3104
+ const scriptAttrs = {
3105
+ async: true,
3106
+ type: "module",
3107
+ src: qwikLoaderBundle
3108
+ };
3109
+ if (nonce) {
3110
+ scriptAttrs["nonce"] = nonce;
2513
3111
  }
3112
+ this.writeScript(scriptAttrs);
3113
+ }
3114
+ }
3115
+ emitQwikLoaderInline() {
3116
+ this.qlInclude = 2 /* Done */;
3117
+ const qwikLoaderScript = getQwikLoaderScript({ debug: this.renderOptions.debug });
3118
+ const scriptAttrs = {
3119
+ id: "qwikloader",
3120
+ async: true,
3121
+ type: "module"
3122
+ };
3123
+ if (this.renderOptions.serverData?.nonce) {
3124
+ scriptAttrs["nonce"] = this.renderOptions.serverData.nonce;
2514
3125
  }
3126
+ this.writeScript(scriptAttrs, qwikLoaderScript);
2515
3127
  }
2516
3128
  emitQwikLoaderAtBottomIfNeeded() {
2517
- const qwikLoaderBundle = this.resolvedManifest.manifest.qwikLoader;
2518
- if (!qwikLoaderBundle) {
2519
- const needLoader = !this.isStatic();
2520
- const includeMode = this.getQwikLoaderIncludeMode();
2521
- const includeLoader = includeMode === "always" || includeMode === "auto" && needLoader;
2522
- if (includeLoader) {
2523
- const qwikLoaderScript = getQwikLoaderScript({
2524
- debug: this.renderOptions.debug
2525
- });
2526
- const scriptAttrs = ["id", "qwikloader", "async", true];
2527
- const nonce = this.renderOptions.serverData?.nonce;
2528
- if (nonce) {
2529
- scriptAttrs.push("nonce", nonce);
2530
- }
2531
- this.openElement("script", scriptAttrs);
2532
- this.write(qwikLoaderScript);
2533
- this.closeElement();
3129
+ if (!this.isStatic()) {
3130
+ if (this.qlInclude !== 2 /* Done */) {
3131
+ this.emitQwikLoaderInline();
2534
3132
  }
3133
+ this.emitNewQwikEvents(true);
2535
3134
  }
2536
- this.emitQwikEvents(Array.from(this.serializationCtx.$eventNames$, (s) => JSON.stringify(s)));
2537
3135
  }
2538
- emitQwikEvents(eventNames) {
2539
- if (eventNames.length > 0) {
2540
- const scriptAttrs = this.renderOptions.serverData?.nonce ? ["nonce", this.renderOptions.serverData.nonce] : null;
2541
- this.openElement("script", scriptAttrs);
2542
- this.write(`(window.qwikevents||(window.qwikevents=[])).push(`);
2543
- this.writeArray(eventNames, ", ");
2544
- this.write(")");
2545
- this.closeElement();
3136
+ emitNewQwikEvents(includeContainerReady = false) {
3137
+ const qwikEventItems = [];
3138
+ for (const eventName of this.serializationCtx.$eventNames$) {
3139
+ if (!this.emittedQwikEventNames.has(eventName)) {
3140
+ this.emittedQwikEventNames.add(eventName);
3141
+ qwikEventItems.push(JSON.stringify(eventName));
3142
+ }
3143
+ }
3144
+ if (includeContainerReady) {
3145
+ qwikEventItems.push(`${QwikEvContainerReady}`, JSON.stringify(this.$instanceHash$));
2546
3146
  }
3147
+ this.emitQwikEvents(qwikEventItems);
2547
3148
  }
2548
- async emitUnclaimedProjection() {
2549
- const unclaimedProjections = this.unclaimedProjections;
2550
- if (unclaimedProjections.length) {
2551
- const previousCurrentComponentNode = this.currentComponentNode;
2552
- try {
2553
- this.openElement(QTemplate, ["hidden", true, "aria-hidden", "true"], null);
2554
- let idx = 0;
2555
- let ssrComponentNode = null;
2556
- let ssrComponentFrame = null;
2557
- let scopedStyleId = null;
2558
- for (let i = 0; i < unclaimedProjections.length; i += 4) {
2559
- this.unclaimedProjectionComponentFrameQueue.push(
2560
- unclaimedProjections[i]
2561
- );
2562
- }
2563
- while (idx < unclaimedProjections.length) {
2564
- const value = unclaimedProjections[idx++];
2565
- if (value instanceof SsrComponentFrame) {
2566
- ssrComponentNode = this.currentComponentNode = value.componentNode;
2567
- ssrComponentFrame = value;
2568
- scopedStyleId = unclaimedProjections[idx++];
2569
- } else if (typeof value === "string") {
2570
- const children = unclaimedProjections[idx++];
2571
- if (!ssrComponentFrame?.hasSlot(value)) {
2572
- ssrComponentFrame && ssrComponentFrame.componentNode.removeProp(value);
2573
- continue;
2574
- }
2575
- this.unclaimedProjectionComponentFrameQueue.shift();
2576
- this.openFragment(
2577
- isDev4 ? [DEBUG_TYPE, "P" /* Projection */, QSlotParent, ssrComponentNode.id] : [QSlotParent, ssrComponentNode.id]
2578
- );
2579
- const lastNode = this.getOrCreateLastNode();
2580
- if (lastNode.vnodeData) {
2581
- lastNode.vnodeData[0] |= 16 /* SERIALIZE */;
2582
- }
2583
- ssrComponentNode?.setProp(value, lastNode.id);
2584
- await _walkJSX(this, children, {
2585
- currentStyleScoped: scopedStyleId,
2586
- parentComponentFrame: null
2587
- });
2588
- this.closeFragment();
2589
- } else {
2590
- throw Error();
2591
- }
2592
- }
2593
- this.closeElement();
2594
- } finally {
2595
- this.currentComponentNode = previousCurrentComponentNode;
3149
+ emitQwikEvents(qwikEventItems) {
3150
+ if (qwikEventItems.length > 0) {
3151
+ const scriptAttrs = {};
3152
+ const nonce = this.renderOptions.serverData?.nonce;
3153
+ if (nonce) {
3154
+ scriptAttrs["nonce"] = nonce;
2596
3155
  }
3156
+ this.openScript(scriptAttrs);
3157
+ this.write(`(window._qwikEv||(window._qwikEv=[])).push(`);
3158
+ this.writeArray(qwikEventItems, COMMA);
3159
+ this.write(PAREN_CLOSE);
3160
+ this.closeScript();
2597
3161
  }
2598
3162
  }
3163
+ // Keep in sync with process-vnode-data.unit.ts
2599
3164
  emitVNodeSeparators(lastSerializedIdx, elementIdx) {
2600
3165
  let skipCount = elementIdx - lastSerializedIdx;
2601
3166
  while (skipCount != 0) {
2602
- if (skipCount > 4096) {
3167
+ if (skipCount >= 8192) {
2603
3168
  this.write(VNodeDataSeparator.ADVANCE_8192_CH);
2604
3169
  skipCount -= 8192;
2605
3170
  } else {
@@ -2623,7 +3188,7 @@ var SSRContainer = class extends _SharedContainer {
2623
3188
  }
2624
3189
  createAndPushFrame(elementName, depthFirstElementIdx, currentFile) {
2625
3190
  let tagNesting = 10 /* ANYTHING */;
2626
- if (isDev4) {
3191
+ if (isDev8) {
2627
3192
  if (!this.currentElementFrame) {
2628
3193
  tagNesting = initialTag(elementName);
2629
3194
  } else {
@@ -2648,7 +3213,8 @@ var SSRContainer = class extends _SharedContainer {
2648
3213
  );
2649
3214
  let indent = " ";
2650
3215
  let lastName = "";
2651
- for (const frame3 of frames) {
3216
+ for (let i = 0; i < frames.length; i++) {
3217
+ const frame3 = frames[i];
2652
3218
  const [name, example] = allowedContent(frame3.tagNesting);
2653
3219
  text.push(
2654
3220
  `${indent}<${frame3.elementName}>${lastName !== name ? ` [${name}]${example ? ` -> ${example}` : ""}` : ""}`
@@ -2668,7 +3234,9 @@ var SSRContainer = class extends _SharedContainer {
2668
3234
  parent: this.currentElementFrame,
2669
3235
  elementName,
2670
3236
  depthFirstElementIdx,
2671
- vNodeData: [0 /* NONE */]
3237
+ vNodeData: [0 /* NONE */],
3238
+ currentFile: isDev8 ? currentFile || null : null,
3239
+ refBase: null
2672
3240
  };
2673
3241
  this.currentElementFrame = frame;
2674
3242
  this.vNodeDatas.push(frame.vNodeData);
@@ -2680,8 +3248,25 @@ var SSRContainer = class extends _SharedContainer {
2680
3248
  }
2681
3249
  ////////////////////////////////////
2682
3250
  write(text) {
3251
+ this.size += text.length;
2683
3252
  this.writer.write(text);
2684
3253
  }
3254
+ writeRootRef(id) {
3255
+ this.size += String(id).length;
3256
+ this.writer.writeRootRef(id);
3257
+ }
3258
+ writeRootRefPath(path) {
3259
+ this.size += String(path[0]).length;
3260
+ this.writer.writeRootRefPath(path);
3261
+ for (let i = 1; i < path.length; i++) {
3262
+ this.size += 1 + String(path[i]).length;
3263
+ }
3264
+ }
3265
+ writeRootRefDelta(id, base2) {
3266
+ const delta = id - base2;
3267
+ this.size += String(delta).length;
3268
+ this.writer.writeRootRefDelta(id, base2);
3269
+ }
2685
3270
  writeArray(array, separator) {
2686
3271
  for (let i = 0; i < array.length; i++) {
2687
3272
  const element = array[i];
@@ -2691,89 +3276,379 @@ var SSRContainer = class extends _SharedContainer {
2691
3276
  this.write(element);
2692
3277
  }
2693
3278
  }
2694
- writeAttrs(tag, attrs, isConst, currentFile) {
3279
+ writeAttrs(tag, attrs, isConst, styleScopedId, currentFile, hasMovedCaptures) {
2695
3280
  let innerHTML = void 0;
2696
- if (attrs.length) {
2697
- for (let i = 0; i < attrs.length; i++) {
2698
- let key = attrs[i++];
2699
- let value = attrs[i];
2700
- let styleScopedId = null;
2701
- if (isSSRUnsafeAttr(key)) {
2702
- if (isDev4) {
2703
- throw qError(32 /* unsafeAttr */);
2704
- }
2705
- continue;
2706
- }
2707
- if (isClassAttr(key) && Array.isArray(value)) {
2708
- const [signalValue, styleId] = value;
2709
- value = signalValue;
2710
- styleScopedId = styleId;
2711
- }
2712
- if (key === "ref") {
2713
- const lastNode = this.getOrCreateLastNode();
2714
- if (isSignal(value)) {
2715
- value.$untrackedValue$ = new DomRef(lastNode);
2716
- continue;
2717
- } else if (typeof value === "function") {
2718
- value(new DomRef(lastNode));
2719
- continue;
2720
- } else if (value == null) {
2721
- continue;
2722
- } else {
2723
- throw qError(15 /* invalidRefValue */, [currentFile]);
2724
- }
3281
+ for (let key in attrs) {
3282
+ let value = attrs[key];
3283
+ if (isSSRUnsafeAttr(key)) {
3284
+ if (isDev8) {
3285
+ throw qError(32 /* unsafeAttr */, [key]);
2725
3286
  }
3287
+ continue;
3288
+ }
3289
+ if (isHtmlAttributeAnEventName(key)) {
3290
+ value = _setEvent(this.serializationCtx, key, value, hasMovedCaptures);
3291
+ } else if (key === "ref") {
3292
+ const lastNode = this.getOrCreateLastNode();
2726
3293
  if (isSignal(value)) {
2727
- const lastNode = this.getOrCreateLastNode();
2728
- const signalData = new SubscriptionData({
2729
- $scopedStyleIdPrefix$: styleScopedId,
2730
- $isConst$: isConst
2731
- });
2732
- value = this.trackSignalValue(value, lastNode, key, signalData);
3294
+ value.$untrackedValue$ = new DomRef(lastNode);
3295
+ continue;
3296
+ } else if (typeof value === "function") {
3297
+ value(new DomRef(lastNode));
3298
+ continue;
3299
+ } else if (value == null) {
3300
+ continue;
3301
+ } else {
3302
+ throw qError(15 /* invalidRefValue */, [currentFile]);
3303
+ }
3304
+ } else if (key === ITERATION_ITEM_SINGLE || key === ITERATION_ITEM_MULTI) {
3305
+ const rootId = this.addRoot(value);
3306
+ if (rootId === void 0) {
3307
+ continue;
2733
3308
  }
2734
- if (key === dangerouslySetInnerHTML) {
3309
+ value = typeof rootId === "number" ? [rootId] : String(rootId);
3310
+ } else if (isSignal(value)) {
3311
+ const lastNode = this.getOrCreateLastNode();
3312
+ const signalData = new SubscriptionData({
3313
+ $scopedStyleIdPrefix$: styleScopedId,
3314
+ $isConst$: isConst
3315
+ });
3316
+ const signal = value;
3317
+ value = retryOnPromise(
3318
+ () => this.trackSignalValue(signal, lastNode, key, signalData)
3319
+ );
3320
+ }
3321
+ if (isPromise(value)) {
3322
+ const lastNode = this.getOrCreateLastNode();
3323
+ this.addPromiseAttribute(value);
3324
+ value.then((resolvedValue) => {
3325
+ this.addBackpatchEntry(
3326
+ lastNode.id,
3327
+ key,
3328
+ serializeAttribute(key, resolvedValue, styleScopedId)
3329
+ );
3330
+ });
3331
+ continue;
3332
+ }
3333
+ if (key === dangerouslySetInnerHTML) {
3334
+ if (value) {
2735
3335
  innerHTML = String(value);
2736
3336
  key = QContainerAttr;
2737
3337
  value = "html" /* HTML */;
2738
- if (tag === "style") {
2739
- continue;
2740
- }
2741
3338
  }
2742
- if (tag === "textarea" && key === "value") {
2743
- if (value && typeof value !== "string") {
2744
- if (isDev4) {
2745
- throw qError(23 /* wrongTextareaValue */, [currentFile, value]);
2746
- }
2747
- continue;
3339
+ if (tag === "style") {
3340
+ continue;
3341
+ }
3342
+ } else if (isPreventDefault(key)) {
3343
+ addPreventDefaultEventToSerializationContext(this.serializationCtx, key);
3344
+ }
3345
+ if (tag === "textarea" && key === "value") {
3346
+ if (value && typeof value !== "string") {
3347
+ if (isDev8) {
3348
+ throw qError(23 /* wrongTextareaValue */, [currentFile, value]);
2748
3349
  }
2749
- innerHTML = escapeHTML(value || "");
2750
- key = QContainerAttr;
2751
- value = "text" /* TEXT */;
3350
+ continue;
2752
3351
  }
2753
- const serializedValue = serializeAttribute(key, value, styleScopedId);
2754
- if (serializedValue != null && serializedValue !== false) {
2755
- this.write(" ");
2756
- this.write(key);
2757
- if (serializedValue !== true) {
2758
- this.write('="');
3352
+ innerHTML = escapeHTML(value || "");
3353
+ key = QContainerAttr;
3354
+ value = "text" /* TEXT */;
3355
+ }
3356
+ const serializedValue = serializeAttribute(key, value, styleScopedId);
3357
+ if (serializedValue != null && serializedValue !== false) {
3358
+ this.write(SPACE);
3359
+ this.write(key);
3360
+ if (serializedValue !== true) {
3361
+ this.write(ATTR_EQUALS_QUOTE);
3362
+ if (Array.isArray(serializedValue)) {
3363
+ this.writeEscapedChunks(serializedValue);
3364
+ } else {
2759
3365
  const strValue = escapeHTML(String(serializedValue));
2760
3366
  this.write(strValue);
2761
- this.write('"');
2762
3367
  }
3368
+ this.write(QUOTE);
2763
3369
  }
2764
3370
  }
2765
3371
  }
2766
3372
  return innerHTML;
2767
3373
  }
3374
+ writeEscapedChunks(chunks) {
3375
+ for (let i = 0; i < chunks.length; i++) {
3376
+ const chunk = chunks[i];
3377
+ if (typeof chunk === "string") {
3378
+ this.write(escapeHTML(chunk));
3379
+ } else if (typeof chunk === "number") {
3380
+ this.writeRootRef(chunk);
3381
+ } else if ("base" in chunk) {
3382
+ this.writeRootRefDelta(chunk.id, chunk.base);
3383
+ } else {
3384
+ this.writeRootRefPath(chunk.path);
3385
+ }
3386
+ }
3387
+ }
3388
+ addPromiseAttribute(promise) {
3389
+ this.promiseAttributes ||= [];
3390
+ this.promiseAttributes.push(promise);
3391
+ }
3392
+ async resolvePromiseAttributes() {
3393
+ if (this.promiseAttributes) {
3394
+ await Promise.all(this.promiseAttributes);
3395
+ this.promiseAttributes = null;
3396
+ }
3397
+ }
2768
3398
  };
2769
- var isQwikStyleElement = (tag, attrs) => {
2770
- if (tag === "style" && attrs != null) {
2771
- for (let i = 0; i < attrs.length; i = i + 2) {
2772
- const attr = attrs[i];
2773
- if (attr === QStyle || attr === QScopedStyle) {
2774
- return true;
3399
+ var SSRSegmentContainer = class extends SSRContainer {
3400
+ constructor(opts, $rootContainer$) {
3401
+ super(opts);
3402
+ this.$rootContainer$ = $rootContainer$;
3403
+ }
3404
+ $rootContainer$;
3405
+ $outOfOrderState$ = 0 /* Rendering */;
3406
+ $outOfOrderRootIdMap$ = null;
3407
+ subscriptionPatchRecords = [];
3408
+ pendingVNodeDataPatches = null;
3409
+ $recordExternalRootEffect$(producer, effect, prop, sourceEffects) {
3410
+ recordExternalRootEffect(
3411
+ this.$rootContainer$.serializationCtx,
3412
+ this.serializationCtx,
3413
+ this.$rootContainer$.$storeProxyMap$,
3414
+ this.subscriptionPatchRecords,
3415
+ producer,
3416
+ effect,
3417
+ prop,
3418
+ sourceEffects
3419
+ );
3420
+ }
3421
+ async $finalizeOutOfOrderSegment$(segmentId, segment) {
3422
+ const rootContainer = this.$rootContainer$;
3423
+ const rootReadyAtSegment = rootContainer.$isReadyForOOOS$();
3424
+ const segmentSerializationCtx = this.serializationCtx;
3425
+ try {
3426
+ const commit = this.$commitRoots$(rootContainer, segmentSerializationCtx);
3427
+ this.$mergeSegmentEventData$(rootContainer, segmentSerializationCtx);
3428
+ const subscriptionPatchRootId = this.$addSubscriptionsToRoots$(
3429
+ rootContainer,
3430
+ rootReadyAtSegment,
3431
+ segmentSerializationCtx
3432
+ );
3433
+ if (rootReadyAtSegment && (commit.newRootLocalIds.length > 0 || subscriptionPatchRootId !== void 0)) {
3434
+ segmentSerializationCtx.$forwardRefOffset$ = rootContainer.serializationCtx.$serializedForwardRefCount$;
3435
+ await this.emitStatePatchData(
3436
+ segmentId,
3437
+ commit.newRootStart,
3438
+ commit.newRootLocalIds,
3439
+ subscriptionPatchRootId
3440
+ );
3441
+ rootContainer.serializationCtx.$serializedRootCount$ = rootContainer.serializationCtx.$roots$.length + (rootContainer.serializationCtx.$hasRootStateForwardRefs$ ? 1 : 0);
3442
+ rootContainer.serializationCtx.$serializedForwardRefCount$ += segmentSerializationCtx.$serializedForwardRefCount$;
3443
+ }
3444
+ this.emitPendingVNodeDataPatches();
3445
+ if (rootReadyAtSegment) {
3446
+ this.$noMoreRoots$ = true;
3447
+ this.emitVNodeData(segmentId);
3448
+ const segmentCtx = this.serializationCtx;
3449
+ this.serializationCtx = rootContainer.serializationCtx;
3450
+ this.emittedSyncFnCount = rootContainer.emittedSyncFnCount;
3451
+ this.emitSyncFnsData(true);
3452
+ rootContainer.emittedSyncFnCount = this.emittedSyncFnCount;
3453
+ this.serializationCtx = segmentCtx;
3454
+ this.emitNewQwikEvents();
3455
+ }
3456
+ this.emitPatchDataIfNeeded();
3457
+ this.drainCleanupQueue();
3458
+ const rootIdMap = commit.rootIdMap;
3459
+ if (rootReadyAtSegment) {
3460
+ this.$outOfOrderState$ = 2 /* Done */;
3461
+ } else {
3462
+ this.$outOfOrderRootIdMap$ = rootIdMap;
3463
+ this.$outOfOrderState$ = 1 /* EarlyFinalized */;
3464
+ }
3465
+ return {
3466
+ html: renderSSRChunks(segment.htmlChunks, rootIdMap),
3467
+ scripts: segment.writer.toString(rootIdMap)
3468
+ };
3469
+ } finally {
3470
+ if (this.$outOfOrderState$ !== 1 /* EarlyFinalized */) {
3471
+ segmentSerializationCtx.$onAddRoot$ = void 0;
3472
+ rootContainer.removeOutOfOrderSegment(this);
3473
+ }
3474
+ rootContainer.serializationCtx.$setWriter$(rootContainer.writer);
3475
+ }
3476
+ }
3477
+ $emitDelayedOutOfOrderVNodeData$() {
3478
+ try {
3479
+ this.emitVNodeData(this.vnodeSegment);
3480
+ this.emitPendingVNodeDataPatches();
3481
+ this.$rootContainer$.emitOutOfOrderSegmentScripts(
3482
+ this.writer.toString(this.$outOfOrderRootIdMap$)
3483
+ );
3484
+ this.$outOfOrderState$ = 2 /* Done */;
3485
+ this.$rootContainer$.removeOutOfOrderSegment(this);
3486
+ } finally {
3487
+ this.serializationCtx.$onAddRoot$ = void 0;
3488
+ }
3489
+ }
3490
+ markVNodeDataForSerialization(node, flags = 16 /* SERIALIZE */) {
3491
+ const previousFlags = node.vnodeData[0];
3492
+ const nextFlags = previousFlags | flags;
3493
+ if (nextFlags !== previousFlags) {
3494
+ node.vnodeData[0] = nextFlags;
3495
+ this.queueLateVNodeDataPatch(node, nextFlags & ~previousFlags);
3496
+ }
3497
+ }
3498
+ queueLateVNodeDataPatch(node, addedFlags) {
3499
+ if (!(addedFlags & (16 /* SERIALIZE */ | 8 /* REFERENCE */))) {
3500
+ return;
3501
+ }
3502
+ const owner = this.getVNodeDataOwnerFromNodeId(node.id);
3503
+ if (!this.$getRootContainer$().isVNodeDataOwnerEmitted(owner.owner)) {
3504
+ return;
3505
+ }
3506
+ let ownerPatches = (this.pendingVNodeDataPatches ||= /* @__PURE__ */ new Map()).get(owner.owner);
3507
+ if (!ownerPatches) {
3508
+ this.pendingVNodeDataPatches.set(owner.owner, ownerPatches = /* @__PURE__ */ new Map());
3509
+ }
3510
+ ownerPatches.set(owner.localIndex, node.vnodeData);
3511
+ }
3512
+ emitPendingVNodeDataPatches() {
3513
+ const pendingPatches = this.pendingVNodeDataPatches;
3514
+ this.pendingVNodeDataPatches = null;
3515
+ if (!pendingPatches) {
3516
+ return;
3517
+ }
3518
+ for (const [owner, entries] of pendingPatches) {
3519
+ if (entries.size === 0) {
3520
+ continue;
3521
+ }
3522
+ const sortedEntries = Array.from(entries).sort((a, b) => a[0] - b[0]);
3523
+ this.emitVNodeDataScript(owner, sortedEntries, true);
3524
+ }
3525
+ }
3526
+ $commitRoots$(rootContainer, segmentSerializationCtx) {
3527
+ const commit = this.commitSegmentRoots(rootContainer, segmentSerializationCtx);
3528
+ segmentSerializationCtx.$onAddRoot$ = (localId, root, obj) => {
3529
+ this.commitSegmentRoot(rootContainer, localId, root, obj, commit);
3530
+ };
3531
+ return commit;
3532
+ }
3533
+ $addSubscriptionsToRoots$(rootContainer, rootReadyAtSegment, segmentSerializationCtx) {
3534
+ let subscriptionPatchRootId = void 0;
3535
+ const subscriptionPatches = rootReadyAtSegment ? this.collectSubscriptionPatches(
3536
+ rootContainer,
3537
+ rootContainer.rootContainerSerializedRootCount
3538
+ ) : void 0;
3539
+ if (subscriptionPatches) {
3540
+ subscriptionPatchRootId = segmentSerializationCtx.$addRoot$(subscriptionPatches);
3541
+ }
3542
+ return subscriptionPatchRootId;
3543
+ }
3544
+ commitSegmentRoots(rootContainer, segmentSerializationCtx) {
3545
+ const rootIdMap = [];
3546
+ const newRootStart = rootContainer.$isReadyForOOOS$() ? rootContainer.serializationCtx.$serializedRootCount$ : rootContainer.serializationCtx.$roots$.length;
3547
+ const newRootLocalIds = [];
3548
+ const commit = {
3549
+ rootIdMap,
3550
+ newRootStart,
3551
+ newRootLocalIds
3552
+ };
3553
+ this.promoteSharedSegmentRoots(rootContainer, segmentSerializationCtx, commit);
3554
+ const segmentRoots = segmentSerializationCtx.$roots$;
3555
+ const segmentRootObjs = segmentSerializationCtx.$rootObjs$;
3556
+ for (let i = 0; i < segmentRoots.length; i++) {
3557
+ const rootObj = segmentRootObjs[i];
3558
+ this.commitSegmentRoot(rootContainer, i, segmentRoots[i], rootObj, commit);
3559
+ }
3560
+ return commit;
3561
+ }
3562
+ promoteSharedSegmentRoots(rootContainer, segmentSerializationCtx, commit) {
3563
+ const segmentRoots = segmentSerializationCtx.$roots$;
3564
+ const segmentRootObjs = segmentSerializationCtx.$rootObjs$;
3565
+ for (let i = 0; i < segmentRootObjs.length; i++) {
3566
+ const rootObj = segmentRootObjs[i];
3567
+ if (this.isRootOrUsedByOtherLiveSegment(rootContainer, rootObj)) {
3568
+ this.commitSegmentRoot(rootContainer, i, segmentRoots[i], rootObj, commit);
3569
+ }
3570
+ }
3571
+ }
3572
+ isRootOrUsedByOtherLiveSegment(rootContainer, obj) {
3573
+ if (rootContainer.serializationCtx.$hasRootId$(obj) !== void 0) {
3574
+ return true;
3575
+ }
3576
+ const segments = rootContainer.outOfOrderSegments;
3577
+ for (let i = 0; i < segments.length; i++) {
3578
+ const segment = segments[i];
3579
+ if (segment === this) {
3580
+ continue;
3581
+ }
3582
+ const rootObjs = segment.serializationCtx.$rootObjs$;
3583
+ for (let j = 0; j < rootObjs.length; j++) {
3584
+ if (rootObjs[j] === obj) {
3585
+ return true;
3586
+ }
3587
+ }
3588
+ }
3589
+ return false;
3590
+ }
3591
+ commitSegmentRoot(rootContainer, localId, root, rootObj, commit) {
3592
+ if (commit.rootIdMap[localId] !== void 0) {
3593
+ return;
3594
+ }
3595
+ let rootId = rootContainer.serializationCtx.$hasRootId$(rootObj);
3596
+ if (rootId === void 0) {
3597
+ rootId = rootContainer.serializationCtx.$commitRoot$(root, rootObj);
3598
+ commit.newRootLocalIds.push(localId);
3599
+ this.seedCommittedRootForLiveSegments(rootContainer, rootObj);
3600
+ }
3601
+ const rootCtx = rootContainer.serializationCtx;
3602
+ commit.rootIdMap[localId] = rootContainer.$isReadyForOOOS$() && rootId >= rootCtx.$rootStateRootCount$ ? rootId + (rootCtx.$hasRootStateForwardRefs$ ? 1 : 0) : rootId;
3603
+ }
3604
+ seedCommittedRootForLiveSegments(rootContainer, rootObj) {
3605
+ const segments = rootContainer.outOfOrderSegments;
3606
+ for (let i = 0; i < segments.length; i++) {
3607
+ const segment = segments[i];
3608
+ if (segment !== this && segment.$outOfOrderState$ === 0 /* Rendering */) {
3609
+ segment.serializationCtx.$addRoot$(rootObj);
3610
+ }
3611
+ }
3612
+ }
3613
+ $mergeSegmentEventData$(rootContainer, segmentSerializationCtx) {
3614
+ for (const eventName of segmentSerializationCtx.$eventNames$) {
3615
+ rootContainer.serializationCtx.$eventNames$.add(eventName);
3616
+ }
3617
+ for (const qrl of segmentSerializationCtx.$eventQrls$) {
3618
+ rootContainer.serializationCtx.$eventQrls$.add(qrl);
3619
+ }
3620
+ }
3621
+ collectSubscriptionPatches(rootContainer, rootLimit) {
3622
+ return collectSubscriptionPatches(
3623
+ rootContainer.serializationCtx,
3624
+ this.subscriptionPatchRecords,
3625
+ rootLimit
3626
+ );
3627
+ }
3628
+ emitStatePatchData(segmentId, rootStart, rootIds, subscriptionPatchRootId) {
3629
+ const attrs = this.statePatchScriptAttrs(segmentId);
3630
+ this.openScript(attrs);
3631
+ this.serializationCtx.$setWriter$(this.writer);
3632
+ this.serializationCtx.$markSsrNodeForSerialization$ = this.markVNodeDataForSerialization.bind(this);
3633
+ return maybeThen(
3634
+ this.serializationCtx.$serializePatch$(rootStart, rootIds, subscriptionPatchRootId, 0),
3635
+ () => {
3636
+ this.closeScript();
2775
3637
  }
3638
+ );
3639
+ }
3640
+ statePatchScriptAttrs(segmentId) {
3641
+ const attrs = this.stateScriptAttrs();
3642
+ attrs[QStatePatchAttr] = true;
3643
+ if (segmentId) {
3644
+ attrs[QSuspenseResolved] = segmentId;
2776
3645
  }
3646
+ return attrs;
3647
+ }
3648
+ };
3649
+ var isQwikStyleElement = (tag, attrs) => {
3650
+ if (tag === "style" && attrs != null) {
3651
+ return Object.prototype.hasOwnProperty.call(attrs, QStyle) || Object.prototype.hasOwnProperty.call(attrs, QScopedStyle);
2777
3652
  }
2778
3653
  return false;
2779
3654
  };
@@ -2792,29 +3667,184 @@ function isSSRUnsafeAttr(name) {
2792
3667
  }
2793
3668
  return false;
2794
3669
  }
2795
- function hash() {
2796
- return Math.random().toString(36).slice(2);
3670
+ function randomStr() {
3671
+ return (Math.random().toString(36) + "000000").slice(2, 8);
3672
+ }
3673
+ function addPreventDefaultEventToSerializationContext(serializationCtx, key) {
3674
+ const eventName = "e" + key.substring(14);
3675
+ if (eventName) {
3676
+ serializationCtx.$eventNames$.add(eventName);
3677
+ }
2797
3678
  }
2798
3679
 
3680
+ // packages/qwik/src/server/ssr-stream-handler.ts
3681
+ var StreamHandler = class {
3682
+ constructor(opts, timing) {
3683
+ this.opts = opts;
3684
+ this.timing = timing;
3685
+ this.inOrderStreaming = opts.streaming?.inOrder ?? {
3686
+ strategy: "auto",
3687
+ maximumInitialChunk: 2e4,
3688
+ maximumChunk: 1e4
3689
+ };
3690
+ this.nativeStream = opts.stream;
3691
+ this.stream = this.setupStreamWriter();
3692
+ }
3693
+ opts;
3694
+ timing;
3695
+ bufferSize = 0;
3696
+ buffer = "";
3697
+ networkFlushes = 0;
3698
+ inOrderStreaming;
3699
+ streamBlockDepth = 0;
3700
+ streamBlockBuffer = "";
3701
+ streamBlockBufferSize = 0;
3702
+ nativeStream;
3703
+ firstFlushTimer = createTimer();
3704
+ pendingFlush;
3705
+ flushQueued = false;
3706
+ stream;
3707
+ setupStreamWriter() {
3708
+ const handler = this;
3709
+ let stream;
3710
+ switch (this.inOrderStreaming.strategy) {
3711
+ case "disabled":
3712
+ stream = createStringStreamWriter((chunk) => {
3713
+ if (chunk === void 0 || chunk === null) {
3714
+ return;
3715
+ }
3716
+ handler.enqueue(chunk);
3717
+ });
3718
+ break;
3719
+ case "direct": {
3720
+ const originalStream = this.nativeStream;
3721
+ stream = createStringStreamWriter((chunk) => {
3722
+ if (chunk === void 0 || chunk === null) {
3723
+ return;
3724
+ }
3725
+ if (handler.pendingFlush) {
3726
+ const queued = handler.pendingFlush.then(() => originalStream.write(chunk));
3727
+ return handler.trackPendingFlush(queued);
3728
+ }
3729
+ return handler.trackPendingFlush(originalStream.write(chunk));
3730
+ });
3731
+ break;
3732
+ }
3733
+ default:
3734
+ case "auto": {
3735
+ const minimumChunkSize = this.inOrderStreaming.maximumChunk ?? 0;
3736
+ const initialChunkSize = this.inOrderStreaming.maximumInitialChunk ?? 0;
3737
+ stream = createStringStreamWriter((chunk) => {
3738
+ if (chunk === void 0 || chunk === null) {
3739
+ return;
3740
+ }
3741
+ handler.enqueue(chunk);
3742
+ if (handler.streamBlockDepth === 0) {
3743
+ const maxBufferSize = handler.networkFlushes === 0 ? initialChunkSize : minimumChunkSize;
3744
+ if (handler.bufferSize >= maxBufferSize) {
3745
+ return handler.flush();
3746
+ }
3747
+ }
3748
+ });
3749
+ break;
3750
+ }
3751
+ }
3752
+ return stream;
3753
+ }
3754
+ enqueue(chunk) {
3755
+ const len = chunk.length;
3756
+ if (this.streamBlockDepth > 0) {
3757
+ this.streamBlockBuffer += chunk;
3758
+ this.streamBlockBufferSize += len;
3759
+ } else {
3760
+ this.bufferSize += len;
3761
+ this.buffer += chunk;
3762
+ }
3763
+ }
3764
+ trackPendingFlush(result) {
3765
+ if (!isPromise(result)) {
3766
+ return;
3767
+ }
3768
+ const pending = Promise.resolve(result).finally(() => {
3769
+ if (this.pendingFlush === pending) {
3770
+ this.pendingFlush = void 0;
3771
+ }
3772
+ });
3773
+ this.pendingFlush = pending;
3774
+ return pending;
3775
+ }
3776
+ flushBuffer() {
3777
+ const chunk = this.buffer;
3778
+ this.buffer = "";
3779
+ this.bufferSize = 0;
3780
+ this.networkFlushes++;
3781
+ if (this.networkFlushes === 1) {
3782
+ this.timing.firstFlush = this.firstFlushTimer();
3783
+ }
3784
+ return this.trackPendingFlush(this.nativeStream.write(chunk));
3785
+ }
3786
+ flush() {
3787
+ if (!this.buffer) {
3788
+ return this.waitForPendingFlush();
3789
+ }
3790
+ if (this.pendingFlush) {
3791
+ if (!this.flushQueued) {
3792
+ this.flushQueued = true;
3793
+ const queued = this.pendingFlush.then(() => {
3794
+ this.flushQueued = false;
3795
+ this.pendingFlush = void 0;
3796
+ return this.flush();
3797
+ });
3798
+ this.pendingFlush = queued.finally(() => {
3799
+ if (this.pendingFlush === queued) {
3800
+ this.pendingFlush = void 0;
3801
+ }
3802
+ });
3803
+ }
3804
+ return this.pendingFlush;
3805
+ }
3806
+ return this.flushBuffer();
3807
+ }
3808
+ waitForPendingFlush() {
3809
+ return this.pendingFlush;
3810
+ }
3811
+ streamBlockStart() {
3812
+ this.streamBlockDepth++;
3813
+ }
3814
+ streamBlockEnd() {
3815
+ this.streamBlockDepth--;
3816
+ if (this.streamBlockDepth === 0 && this.streamBlockBuffer) {
3817
+ this.buffer += this.streamBlockBuffer;
3818
+ this.bufferSize += this.streamBlockBufferSize;
3819
+ this.streamBlockBuffer = "";
3820
+ this.streamBlockBufferSize = 0;
3821
+ return this.flush();
3822
+ }
3823
+ }
3824
+ };
3825
+
2799
3826
  // packages/qwik/src/server/ssr-render.ts
2800
- import { manifest as builtManifest } from "@qwik-client-manifest";
2801
3827
  var renderToString = async (jsx, opts = {}) => {
2802
- const chunks = [];
2803
- const stream = {
2804
- write(chunk) {
2805
- chunks.push(chunk);
2806
- }
2807
- };
3828
+ const stream = new StringSSRWriter();
2808
3829
  const result = await renderToStream(jsx, { ...opts, stream });
2809
3830
  return {
2810
3831
  isStatic: result.isStatic,
2811
3832
  timing: result.timing,
2812
3833
  manifest: result.manifest,
2813
3834
  snapshotResult: result.snapshotResult,
2814
- html: chunks.join("")
3835
+ html: stream.toString()
2815
3836
  };
2816
3837
  };
2817
3838
  var renderToStream = async (jsx, opts) => {
3839
+ if (__EXPERIMENTAL__.suspense && opts.streaming?.outOfOrder === void 0) {
3840
+ opts = {
3841
+ ...opts,
3842
+ streaming: {
3843
+ ...opts.streaming,
3844
+ outOfOrder: true
3845
+ }
3846
+ };
3847
+ }
2818
3848
  const timing = {
2819
3849
  firstFlush: 0,
2820
3850
  render: 0,
@@ -2824,11 +3854,12 @@ var renderToStream = async (jsx, opts) => {
2824
3854
  const buildBase = getBuildBase(opts);
2825
3855
  const resolvedManifest = resolveManifest(opts.manifest);
2826
3856
  const locale = typeof opts.locale === "function" ? opts.locale(opts) : opts.serverData?.locale || opts.locale || opts.containerAttributes?.locale || "";
2827
- const { stream, flush, networkFlushes, totalSize } = handleStreaming(opts, timing);
3857
+ const streamHandler = new StreamHandler(opts, timing);
2828
3858
  const ssrContainer = ssrCreateContainer({
2829
3859
  tagName: containerTagName,
2830
3860
  locale,
2831
- writer: stream,
3861
+ writer: streamHandler.stream,
3862
+ streamHandler,
2832
3863
  timing,
2833
3864
  buildBase,
2834
3865
  resolvedManifest,
@@ -2836,136 +3867,29 @@ var renderToStream = async (jsx, opts) => {
2836
3867
  });
2837
3868
  await setServerPlatform(opts, resolvedManifest);
2838
3869
  await ssrContainer.render(jsx);
2839
- flush();
2840
- const snapshotResult = getSnapshotResult(ssrContainer);
2841
- const isDynamic = snapshotResult.resources.some((r) => r._cache !== Infinity);
3870
+ await ssrContainer.$renderPromise$;
3871
+ await streamHandler.flush();
2842
3872
  const result = {
2843
- snapshotResult,
2844
- flushes: networkFlushes,
3873
+ flushes: streamHandler.networkFlushes,
2845
3874
  manifest: resolvedManifest?.manifest,
2846
- size: totalSize,
2847
- isStatic: !isDynamic,
3875
+ size: ssrContainer.size,
3876
+ isStatic: false,
2848
3877
  timing
2849
3878
  };
2850
3879
  return result;
2851
3880
  };
2852
- function getSnapshotResult(ssrContainer) {
2853
- const hasListeners = !ssrContainer.isStatic();
2854
- const canRender = false;
2855
- return hasListeners ? {
2856
- funcs: Array.from(ssrContainer.serializationCtx.$syncFns$),
2857
- mode: canRender ? "render" : "listeners",
2858
- qrls: Array.from(ssrContainer.serializationCtx.$eventQrls$),
2859
- resources: Array.from(ssrContainer.serializationCtx.$resources$)
2860
- } : {
2861
- funcs: [],
2862
- mode: "static",
2863
- qrls: [],
2864
- resources: Array.from(ssrContainer.serializationCtx.$resources$)
2865
- };
2866
- }
2867
- function handleStreaming(opts, timing) {
2868
- const firstFlushTimer = createTimer();
2869
- let stream = opts.stream;
2870
- let bufferSize = 0;
2871
- let buffer = "";
2872
- let totalSize = 0;
2873
- let networkFlushes = 0;
2874
- const inOrderStreaming = opts.streaming?.inOrder ?? {
2875
- strategy: "auto",
2876
- maximumInitialChunk: 2e4,
2877
- maximumChunk: 1e4
2878
- };
2879
- const nativeStream = stream;
2880
- function flush() {
2881
- if (buffer) {
2882
- nativeStream.write(buffer);
2883
- buffer = "";
2884
- bufferSize = 0;
2885
- networkFlushes++;
2886
- if (networkFlushes === 1) {
2887
- timing.firstFlush = firstFlushTimer();
2888
- }
2889
- }
2890
- }
2891
- function enqueue(chunk) {
2892
- const len = chunk.length;
2893
- bufferSize += len;
2894
- totalSize += len;
2895
- buffer += chunk;
2896
- }
2897
- switch (inOrderStreaming.strategy) {
2898
- case "disabled":
2899
- stream = {
2900
- write(chunk) {
2901
- if (shouldSkipChunk(chunk)) {
2902
- return;
2903
- }
2904
- enqueue(chunk);
2905
- }
2906
- };
2907
- break;
2908
- case "direct":
2909
- stream = {
2910
- write(chunk) {
2911
- if (shouldSkipChunk(chunk)) {
2912
- return;
2913
- }
2914
- nativeStream.write(chunk);
2915
- }
2916
- };
2917
- break;
2918
- case "auto":
2919
- let openedSSRStreamBlocks = 0;
2920
- let forceFlush = false;
2921
- const minimumChunkSize = inOrderStreaming.maximumChunk ?? 0;
2922
- const initialChunkSize = inOrderStreaming.maximumInitialChunk ?? 0;
2923
- stream = {
2924
- write(chunk) {
2925
- if (chunk === void 0 || chunk === null) {
2926
- return;
2927
- }
2928
- if (chunk === "<!--" + FLUSH_COMMENT + "-->") {
2929
- forceFlush = true;
2930
- } else if (chunk === "<!--" + STREAM_BLOCK_START_COMMENT + "-->") {
2931
- openedSSRStreamBlocks++;
2932
- } else if (chunk === "<!--" + STREAM_BLOCK_END_COMMENT + "-->") {
2933
- openedSSRStreamBlocks--;
2934
- if (openedSSRStreamBlocks === 0) {
2935
- forceFlush = true;
2936
- }
2937
- } else {
2938
- enqueue(chunk);
2939
- }
2940
- const maxBufferSize = networkFlushes === 0 ? initialChunkSize : minimumChunkSize;
2941
- if (openedSSRStreamBlocks === 0 && (forceFlush || bufferSize >= maxBufferSize)) {
2942
- forceFlush = false;
2943
- flush();
2944
- }
2945
- }
2946
- };
2947
- break;
2948
- }
2949
- return {
2950
- stream,
2951
- flush,
2952
- networkFlushes,
2953
- totalSize
2954
- };
2955
- }
2956
- function shouldSkipChunk(chunk) {
2957
- return chunk === void 0 || chunk === null || chunk === "<!--" + FLUSH_COMMENT + "-->" || chunk === "<!--" + STREAM_BLOCK_START_COMMENT + "-->" || chunk === "<!--" + STREAM_BLOCK_END_COMMENT + "-->";
2958
- }
2959
3881
  function resolveManifest(manifest) {
3882
+ const builtManifest = getClientManifest();
2960
3883
  const mergedManifest = manifest ? { ...builtManifest, ...manifest } : builtManifest;
2961
3884
  if (!mergedManifest || "mapper" in mergedManifest) {
2962
3885
  return mergedManifest;
2963
3886
  }
2964
3887
  if (mergedManifest.mapping) {
2965
3888
  const mapper = {};
2966
- Object.entries(mergedManifest.mapping).forEach(([symbol, bundleFilename]) => {
3889
+ for (const symbol in mergedManifest.mapping) {
3890
+ const bundleFilename = mergedManifest.mapping[symbol];
2967
3891
  mapper[getSymbolHash(symbol)] = [symbol, bundleFilename];
2968
- });
3892
+ }
2969
3893
  return {
2970
3894
  mapper,
2971
3895
  manifest: mergedManifest,
@@ -2982,6 +3906,7 @@ async function setServerPlatform2(manifest) {
2982
3906
  setPlatform2(platform);
2983
3907
  }
2984
3908
  export {
3909
+ getQwikBackpatchExecutorScript,
2985
3910
  getQwikLoaderScript,
2986
3911
  getQwikPrefetchWorkerScript,
2987
3912
  renderToStream,