@stencil/core 5.0.0-beta.9 → 5.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/app-data/index.d.ts +1 -1
  2. package/dist/app-data/index.js +1 -0
  3. package/dist/{client-BRu0GtRn.mjs → client-ClM4H9-P.mjs} +204 -76
  4. package/dist/compiler/browser.d.ts +120 -81
  5. package/dist/compiler/browser.js +964 -402
  6. package/dist/compiler/index.d.mts +110 -2
  7. package/dist/compiler/index.mjs +3 -3
  8. package/dist/compiler/utils/index.d.mts +2 -2
  9. package/dist/compiler/utils/index.mjs +3 -3
  10. package/dist/{compiler-wLrjuSOK.mjs → compiler-DFanjq9z.mjs} +5300 -3005
  11. package/dist/declarations/stencil-public-compiler.d.ts +178 -133
  12. package/dist/declarations/stencil-public-docs.d.ts +23 -0
  13. package/dist/declarations/stencil-public-runtime.d.ts +81 -59
  14. package/dist/{index-BvF31nqP.d.mts → index-DvfFOkiJ.d.mts} +220 -133
  15. package/dist/{index-BXAcVN2j.d.ts → index-XQHZl0MW.d.ts} +70 -57
  16. package/dist/{index-BAP9T4CB.d.mts → index-aBMJC5F9.d.mts} +6 -2
  17. package/dist/index.d.mts +3 -0
  18. package/dist/index.mjs +1 -1
  19. package/dist/jsx-runtime.d.mts +6 -0
  20. package/dist/jsx-runtime.mjs +1 -1
  21. package/dist/{node-75gQKkFz.mjs → node-DJP8JuAS.mjs} +42 -48
  22. package/dist/runtime/client/lazy.js +522 -262
  23. package/dist/runtime/client/runtime.d.ts +100 -68
  24. package/dist/runtime/client/runtime.js +522 -262
  25. package/dist/runtime/index.d.ts +6 -6
  26. package/dist/runtime/index.js +521 -261
  27. package/dist/runtime/server/index.d.mts +36 -12
  28. package/dist/runtime/server/index.mjs +635 -304
  29. package/dist/runtime/server/runner.d.mts +49 -6
  30. package/dist/runtime/server/runner.mjs +385 -87
  31. package/dist/signals/index.d.ts +11 -2
  32. package/dist/signals/index.js +15 -35
  33. package/dist/sys/node/index.d.mts +1 -1
  34. package/dist/sys/node/index.mjs +1 -1
  35. package/dist/sys/node/worker.mjs +2 -2
  36. package/dist/testing/index.d.mts +152 -124
  37. package/dist/testing/index.mjs +535 -269
  38. package/dist/{util-IKfWWLJo.mjs → util-C-H1H84W.mjs} +8 -1
  39. package/dist/{validation-DAdGTrys.mjs → validation-ByYYKvnS.mjs} +37 -3
  40. package/package.json +8 -4
@@ -6772,7 +6772,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
6772
6772
  value: mod,
6773
6773
  enumerable: true
6774
6774
  }) : target, mod));
6775
- const HYDRATE_ID = "s-id";
6776
6775
  const XML_NS = "http://www.w3.org/XML/1998/namespace";
6777
6776
  const XMLNS_NS = "http://www.w3.org/2000/xmlns/";
6778
6777
  /**
@@ -7680,6 +7679,11 @@ function* streamToHtml(node, opts, output) {
7680
7679
  yield " shadowrootserializable";
7681
7680
  output.currentLineWidth += 23;
7682
7681
  }
7682
+ if ("referenceTarget" in node && typeof node.referenceTarget === "string" && node.referenceTarget) {
7683
+ const referenceTargetAttr = ` shadowrootreferencetarget="${escapeString(node.referenceTarget, true)}"`;
7684
+ yield referenceTargetAttr;
7685
+ output.currentLineWidth += referenceTargetAttr.length;
7686
+ }
7683
7687
  }
7684
7688
  const attrsLength = node.attributes.length;
7685
7689
  const attributes = opts.prettyHtml && attrsLength > 1 ? cloneAttributes(node.attributes, true) : node.attributes;
@@ -7687,7 +7691,7 @@ function* streamToHtml(node, opts, output) {
7687
7691
  const attr = attributes.item(i);
7688
7692
  const attrName = attr.name;
7689
7693
  if (attrName === "style") continue;
7690
- if (tag === "template" && isShadowRoot && (attrName === "shadowrootmode" || attrName === "shadowrootdelegatesfocus" || attrName === "shadowrootcustomelementregistry")) continue;
7694
+ if (tag === "template" && isShadowRoot && (attrName === "shadowrootmode" || attrName === "shadowrootdelegatesfocus" || attrName === "shadowrootreferencetarget" || attrName === "shadowrootcustomelementregistry")) continue;
7691
7695
  let attrValue = attr.value;
7692
7696
  if (opts.removeEmptyAttributes && attrValue === "" && REMOVE_EMPTY_ATTR.has(attrName)) continue;
7693
7697
  const attrNamespaceURI = attr.namespaceURI;
@@ -7767,19 +7771,7 @@ function* streamToHtml(node, opts, output) {
7767
7771
  const isWithinWhitespaceSensitiveNode = opts.newLines || (opts.indentSpaces ?? 0) > 0 ? isWithinWhitespaceSensitive(node) : false;
7768
7772
  if (!isWithinWhitespaceSensitiveNode && (opts.indentSpaces ?? 0) > 0 && ignoreTag === false) output.indent = output.indent + (opts.indentSpaces ?? 0);
7769
7773
  for (let i = 0; i < childNodeLength; i++) {
7770
- /**
7771
- * In cases where a user would pass in a declarative shadow dom of a
7772
- * Stencil component, we want to skip over the template tag as we
7773
- * will be parsing the shadow root of the component again.
7774
- *
7775
- * We know it is a hydrated Stencil component by checking if the `HYDRATE_ID`
7776
- * is set on the node.
7777
- */
7778
- const sId = node.attributes.getNamedItem(HYDRATE_ID);
7779
- if (childNodes[i].nodeName.toLowerCase() === "template" && sId) {
7780
- yield `\n${" ".repeat(output.indent)}<!--r.${sId.value}-->`;
7781
- continue;
7782
- }
7774
+ if (childNodes[i].nodeName.toLowerCase() === "template" && node.attributes.getNamedItem("s-id")) continue;
7783
7775
  yield* streamToHtml(childNodes[i], opts, output);
7784
7776
  }
7785
7777
  if (ignoreTag === false) {
@@ -8047,10 +8039,12 @@ var MockTokenList = class {
8047
8039
  token = String(token);
8048
8040
  return getItems(this.elm, this.attr).includes(token);
8049
8041
  }
8050
- toggle(token) {
8042
+ toggle(token, force) {
8051
8043
  token = String(token);
8052
- if (this.contains(token) === true) this.remove(token);
8053
- else this.add(token);
8044
+ const shouldAdd = force === void 0 ? !this.contains(token) : !!force;
8045
+ if (shouldAdd) this.add(token);
8046
+ else this.remove(token);
8047
+ return shouldAdd;
8054
8048
  }
8055
8049
  get length() {
8056
8050
  return getItems(this.elm, this.attr).length;
@@ -8275,6 +8269,21 @@ var MockNodeList = class {
8275
8269
  this.length = length;
8276
8270
  }
8277
8271
  };
8272
+ /**
8273
+ * Just enough of `ElementInternals` for form-associated components to run without throwing.
8274
+ * There is no form, validation or accessibility tree to update, so the methods do nothing.
8275
+ */
8276
+ var MockElementInternals = class {
8277
+ states = /* @__PURE__ */ new Set();
8278
+ setFormValue() {}
8279
+ setValidity() {}
8280
+ checkValidity() {
8281
+ return true;
8282
+ }
8283
+ reportValidity() {
8284
+ return true;
8285
+ }
8286
+ };
8278
8287
  var MockElement = class extends MockNode {
8279
8288
  __namespaceURI;
8280
8289
  __localName;
@@ -8282,13 +8291,7 @@ var MockElement = class extends MockNode {
8282
8291
  __shadowRoot;
8283
8292
  __style;
8284
8293
  attachInternals() {
8285
- return new Proxy({}, { get: function(_target, prop, _receiver) {
8286
- /**
8287
- * only print warning when running in a test environment
8288
- */
8289
- if ("process" in globalThis && globalThis.process.env.__STENCIL_SPEC_TESTS__) console.error(`NOTE: Property ${String(prop)} was accessed on ElementInternals, but this property is not implemented.
8290
- Testing components with ElementInternals is fully supported in e2e tests.`);
8291
- } });
8294
+ return new MockElementInternals();
8292
8295
  }
8293
8296
  constructor(ownerDocument, nodeName, namespaceURI = null) {
8294
8297
  super(ownerDocument, 1, typeof nodeName === "string" ? nodeName : null, null);
@@ -8306,6 +8309,7 @@ var MockElement = class extends MockNode {
8306
8309
  shadowRoot.delegatesFocus = _opts.delegatesFocus ?? false;
8307
8310
  shadowRoot.clonable = _opts.clonable ?? false;
8308
8311
  shadowRoot.serializable = _opts.serializable ?? false;
8312
+ shadowRoot.referenceTarget = _opts.referenceTarget ?? null;
8309
8313
  this.shadowRoot = shadowRoot;
8310
8314
  return shadowRoot;
8311
8315
  }
@@ -8546,7 +8550,8 @@ var MockElement = class extends MockNode {
8546
8550
  return this.hasAttributeNS(null, "hidden");
8547
8551
  }
8548
8552
  set hidden(isHidden) {
8549
- if (isHidden === true) this.setAttributeNS(null, "hidden", "");
8553
+ if (isHidden === "until-found") this.setAttributeNS(null, "hidden", "until-found");
8554
+ else if (isHidden === true) this.setAttributeNS(null, "hidden", "");
8550
8555
  else this.removeAttributeNS(null, "hidden");
8551
8556
  }
8552
8557
  get lang() {
@@ -11358,6 +11363,7 @@ var MockShadowRoot = class extends MockDocumentFragment {
11358
11363
  _delegatesFocus = false;
11359
11364
  _clonable = false;
11360
11365
  _serializable = false;
11366
+ _referenceTarget = null;
11361
11367
  get activeElement() {
11362
11368
  return null;
11363
11369
  }
@@ -11396,6 +11402,12 @@ var MockShadowRoot = class extends MockDocumentFragment {
11396
11402
  get pointerLockElement() {
11397
11403
  return null;
11398
11404
  }
11405
+ get referenceTarget() {
11406
+ return this._referenceTarget;
11407
+ }
11408
+ set referenceTarget(value) {
11409
+ this._referenceTarget = value;
11410
+ }
11399
11411
  get serializable() {
11400
11412
  return this._serializable;
11401
11413
  }
@@ -11908,6 +11920,77 @@ function constrainTimeouts(win) {
11908
11920
  win.__allowInterval = false;
11909
11921
  win.__maxTimeout = 0;
11910
11922
  }
11923
+ /**
11924
+ * Reset a window so the same object can be used for another render, then parse `html` into its
11925
+ * document.
11926
+ *
11927
+ * Code that captured the window's sub-objects (e.g. an SSR platform holding `win.location`,
11928
+ * `win.console` or `win.document`) keeps working: those objects are kept and reset in place,
11929
+ * rather than replaced. Everything else on the window - including anything a previous render
11930
+ * added - is removed.
11931
+ * @param win the window to reset
11932
+ * @param html the HTML for the next render
11933
+ */
11934
+ function resetWindowForReuse(win, html) {
11935
+ const retained = {
11936
+ console: win.console,
11937
+ document: win.document,
11938
+ eventCounts: win.performance.eventCounts,
11939
+ history: win.history,
11940
+ localStorage: win.localStorage,
11941
+ location: win.location,
11942
+ navigator: win.navigator,
11943
+ orientation: win.screen.orientation,
11944
+ performance: win.performance,
11945
+ screen: win.screen,
11946
+ sessionStorage: win.sessionStorage
11947
+ };
11948
+ if (win.__timeouts) win.__timeouts.forEach((timeoutId) => {
11949
+ nativeClearInterval(timeoutId);
11950
+ nativeClearTimeout(timeoutId);
11951
+ });
11952
+ resetObject(retained.console, createConsole());
11953
+ resetObject(retained.history, new MockHistory());
11954
+ resetObject(retained.location, new MockLocation());
11955
+ resetObject(retained.navigator, new MockNavigator());
11956
+ retained.localStorage.clear();
11957
+ retained.sessionStorage.clear();
11958
+ retained.eventCounts.clear();
11959
+ resetObject(retained.performance, {
11960
+ eventCounts: retained.eventCounts,
11961
+ interactionCount: 0,
11962
+ timeOrigin: Date.now()
11963
+ });
11964
+ for (const key of Reflect.ownKeys(win)) delete win[key];
11965
+ resetWindowDefaults(win);
11966
+ resetWindowDimensions(win);
11967
+ const defaultScreen = win.screen;
11968
+ resetObject(retained.orientation, defaultScreen.orientation);
11969
+ resetObject(retained.screen, {
11970
+ ...defaultScreen,
11971
+ orientation: retained.orientation
11972
+ });
11973
+ win.console = retained.console;
11974
+ win.customElements = null;
11975
+ win.document = retained.document;
11976
+ win.history = retained.history;
11977
+ win.localStorage = retained.localStorage;
11978
+ win.location = retained.location;
11979
+ win.navigator = retained.navigator;
11980
+ win.performance = retained.performance;
11981
+ win.screen = retained.screen;
11982
+ win.sessionStorage = retained.sessionStorage;
11983
+ resetDocumentForReuse(retained.document, win, html);
11984
+ }
11985
+ /**
11986
+ * Replace every own property of `target` with those of `defaults`, keeping the object itself.
11987
+ * @param target the object to reset in place
11988
+ * @param defaults the properties it should have afterwards
11989
+ */
11990
+ function resetObject(target, defaults) {
11991
+ for (const key of Reflect.ownKeys(target)) delete target[key];
11992
+ Object.assign(target, defaults);
11993
+ }
11911
11994
  function resetWindow(win) {
11912
11995
  if (win != null) {
11913
11996
  if (win.__timeouts) {
@@ -11927,11 +12010,14 @@ function resetWindow(win) {
11927
12010
  if (win.document != null) try {
11928
12011
  win.document.defaultView = win;
11929
12012
  } catch {}
11930
- win.fetch = null;
11931
- win.Headers = null;
11932
- win.Request = null;
11933
- win.Response = null;
11934
- win.FetchError = null;
12013
+ const windowDestroyed = () => {
12014
+ throw new Error("MockWindow was already destroyed");
12015
+ };
12016
+ win.fetch = windowDestroyed;
12017
+ win.Headers = windowDestroyed;
12018
+ win.Request = windowDestroyed;
12019
+ win.Response = windowDestroyed;
12020
+ win.FetchError = windowDestroyed;
11935
12021
  }
11936
12022
  }
11937
12023
  function resetWindowDimensions(win) {
@@ -12205,6 +12291,37 @@ function resetDocument(doc) {
12205
12291
  } catch {}
12206
12292
  }
12207
12293
  }
12294
+ /**
12295
+ * Reset a document so the same object can be used for another render, then parse `html` into
12296
+ * it. The document object itself is kept (code holding a reference to it stays valid), but its
12297
+ * whole element tree is replaced with freshly parsed elements - so caches keyed on elements, like
12298
+ * the runtime's applied-styles cache keyed on `<head>`, start empty.
12299
+ * @param doc the document to reset
12300
+ * @param win the window that owns the document
12301
+ * @param html the HTML to parse into the document
12302
+ */
12303
+ function resetDocumentForReuse(doc, win, html) {
12304
+ resetDocument(doc);
12305
+ for (const key of Reflect.ownKeys(doc)) if (typeof key !== "string" || !REUSABLE_DOC_KEY_KEEPERS.has(key)) delete doc[key];
12306
+ doc.defaultView = win;
12307
+ doc.documentElement = parseDocumentUtil(doc, html).documentElement;
12308
+ }
12309
+ /** Structural document properties kept by {@link resetDocumentForReuse}; everything else is per-render state. */
12310
+ const REUSABLE_DOC_KEY_KEEPERS = /* @__PURE__ */ new Set([
12311
+ "_nodeValue",
12312
+ "nodeName",
12313
+ "nodeType",
12314
+ "ownerDocument",
12315
+ "parentNode",
12316
+ "_childNodes",
12317
+ "__namespaceURI",
12318
+ "__localName",
12319
+ "defaultView",
12320
+ "cookie",
12321
+ "referrer",
12322
+ "compatMode",
12323
+ "contentType"
12324
+ ]);
12208
12325
  const DOC_KEY_KEEPERS = /* @__PURE__ */ new Set([
12209
12326
  "nodeName",
12210
12327
  "nodeType",
@@ -12254,39 +12371,6 @@ function createWindowFromHtml(templateHtml, uniqueId) {
12254
12371
  return cloneWindow(templateWindow);
12255
12372
  }
12256
12373
  //#endregion
12257
- //#region src/runtime/runtime-constants.ts
12258
- const HYDRATED_STYLE_ID = "sty-id";
12259
- const STENCIL_DOC_DATA = "_stencilDocData";
12260
- //#endregion
12261
- //#region src/utils/helpers.ts
12262
- const isString = (v) => typeof v === "string";
12263
- //#endregion
12264
- //#region src/runtime/mode.ts
12265
- const setMode = (handler) => modeResolutionChain.push(handler);
12266
- BUILD.lazyLoad || globalThis.HTMLElement;
12267
- //#endregion
12268
- //#region src/runtime/tag-transform.ts
12269
- let tagTransformer = void 0;
12270
- /**
12271
- * Transforms a tag name using the current tag transformer
12272
- * @param tag - the tag to transform e.g. `my-tag`
12273
- * @returns the transformed tag e.g. `new-my-tag`
12274
- */
12275
- function transformTag(tag) {
12276
- if (!tagTransformer) return tag;
12277
- return tagTransformer(tag);
12278
- }
12279
- /**
12280
- * Sets the tag transformer to be used when rendering custom elements
12281
- * @param transformer the transformer function to use. Must return a string
12282
- */
12283
- function setTagTransformer(transformer) {
12284
- tagTransformer = transformer;
12285
- }
12286
- //#endregion
12287
- //#region src/server/platform/index.ts
12288
- const modeResolutionChain = [];
12289
- //#endregion
12290
12374
  //#region src/compiler/html/canonical-link.ts
12291
12375
  const updateCanonicalLink = (doc, href) => {
12292
12376
  let canonicalLinkElm = doc.head.querySelector("link[rel=\"canonical\"]");
@@ -12313,6 +12397,9 @@ const relocateMetaCharset = (doc) => {
12313
12397
  head.insertBefore(charsetElm, head.firstChild);
12314
12398
  };
12315
12399
  //#endregion
12400
+ //#region src/utils/helpers.ts
12401
+ const isString = (v) => typeof v === "string";
12402
+ //#endregion
12316
12403
  //#region src/utils/message-utils.ts
12317
12404
  /**
12318
12405
  * Builds a diagnostic from an `Error`, appends it to the `diagnostics` parameter, and returns the created diagnostic
@@ -12355,6 +12442,39 @@ const TASK_CANCELED_MSG = `task canceled`;
12355
12442
  //#endregion
12356
12443
  //#region src/compiler/style/css-parser/parse-css.ts
12357
12444
  /**
12445
+ * Splits a selector list on top-level commas in a single pass: a comma only
12446
+ * splits when it's outside a quoted string and at paren depth 0, so commas in
12447
+ * `:is(:a,:has(:b))` or `[title="a,b"]` aren't treated as separators.
12448
+ * Backslash escapes (inside or outside a string) are skipped so they can't shift state,
12449
+ * so e.g. `[title="a\,b"]` is treated as a single selector.
12450
+ * @param selectors The selector list to split
12451
+ * @returns An array of selectors, with whitespace trimmed from each selector
12452
+ */
12453
+ const splitSelectorList = (selectors) => {
12454
+ const parts = [];
12455
+ let depth = 0;
12456
+ let quote = null;
12457
+ let start = 0;
12458
+ for (let i = 0; i < selectors.length; i++) {
12459
+ const ch = selectors[i];
12460
+ if (quote) {
12461
+ if (ch === "\\") i++;
12462
+ else if (ch === quote) quote = null;
12463
+ continue;
12464
+ }
12465
+ if (ch === "\"" || ch === "'") quote = ch;
12466
+ else if (ch === "\\") i++;
12467
+ else if (ch === "(") depth++;
12468
+ else if (ch === ")") depth = Math.max(0, depth - 1);
12469
+ else if (ch === "," && depth === 0) {
12470
+ parts.push(selectors.slice(start, i));
12471
+ start = i + 1;
12472
+ }
12473
+ }
12474
+ parts.push(selectors.slice(start));
12475
+ return parts.map((s) => s.trim());
12476
+ };
12477
+ /**
12358
12478
  * Parses CSS string input into an AST representation.
12359
12479
  * Used for minification, finding & resolving URLs and during SSR / prerendering, removing unused selectors.
12360
12480
  *
@@ -12479,11 +12599,8 @@ const parseCss = (css, filePath) => {
12479
12599
  const selector = () => {
12480
12600
  const m = match(/^([^{]+)/);
12481
12601
  if (!m) return null;
12482
- return trim(m[0]).replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, "").replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g, function(str) {
12483
- return str.replace(/,/g, "‌");
12484
- }).split(/\s*(?![^(]*\)),\s*/).map(function(s) {
12485
- return s.replace(/\u200C/g, ",");
12486
- });
12602
+ const cleaned = trim(m[0]).replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, "");
12603
+ return splitSelectorList(cleaned);
12487
12604
  };
12488
12605
  const declaration = () => {
12489
12606
  const pos = position();
@@ -13103,6 +13220,37 @@ const removeUnusedStyleText = (usedSelectors, diagnostics, styleElm) => {
13103
13220
  }
13104
13221
  };
13105
13222
  //#endregion
13223
+ //#region src/runtime/runtime-constants.ts
13224
+ const HYDRATED_STYLE_ID = "sty-id";
13225
+ const STENCIL_DOC_DATA = "_stencilDocData";
13226
+ const SERVER_BUILD_FLAGS = {
13227
+ isBrowser: false,
13228
+ isServer: true,
13229
+ isDev: false,
13230
+ isTesting: false
13231
+ };
13232
+ //#endregion
13233
+ //#region src/runtime/tag-transform.ts
13234
+ let tagTransformer = void 0;
13235
+ /**
13236
+ * Transforms a tag name using the current tag transformer
13237
+ * @param tag - the tag to transform e.g. `my-tag`
13238
+ * @returns the transformed tag e.g. `new-my-tag`
13239
+ */
13240
+ function transformTag(tag) {
13241
+ if (!tagTransformer) return tag;
13242
+ return tagTransformer(tag);
13243
+ }
13244
+ /**
13245
+ * Sets the tag transformer to be used when rendering custom elements
13246
+ * @param transformer the transformer function to use. Must return a string
13247
+ */
13248
+ function setTagTransformer(transformer) {
13249
+ tagTransformer = transformer;
13250
+ }
13251
+ ({ ...SERVER_BUILD_FLAGS });
13252
+ BUILD.lazyLoad || globalThis.HTMLElement;
13253
+ //#endregion
13106
13254
  //#region src/server/runner/inspect-element.ts
13107
13255
  function inspectElement(results, elm, depth) {
13108
13256
  const children = [...Array.from(elm.children), ...Array.from(elm.shadowRoot ? elm.shadowRoot.children : [])];
@@ -13324,6 +13472,90 @@ function renderCatchError(results, err) {
13324
13472
  return diagnostic;
13325
13473
  }
13326
13474
  //#endregion
13475
+ //#region src/server/runner/reusable-window.ts
13476
+ /**
13477
+ * A canonical key for a `serializeShadowRoot` value: values that render every component the same
13478
+ * way get the same key.
13479
+ *
13480
+ * Rendering shadow components as scoped permanently changes their metadata inside the SSR platform
13481
+ * that rendered them, so a platform (and a reusable window) can only be shared by renders whose
13482
+ * `serializeShadowRoot` marks the same components as scoped. Which components that is depends
13483
+ * only on this value: for the object form, on `default` and the two tag lists - so those are
13484
+ * normalized (lowercased, de-duplicated, sorted) to give equivalent objects one key.
13485
+ * @param serializeShadowRoot the render's `serializeShadowRoot` option
13486
+ * @returns the key
13487
+ */
13488
+ function serializeShadowRootKey(serializeShadowRoot) {
13489
+ if (serializeShadowRoot === null || typeof serializeShadowRoot !== "object") return `${typeof serializeShadowRoot}:${serializeShadowRoot}`;
13490
+ const opts = serializeShadowRoot;
13491
+ const tags = (list) => Array.isArray(list) ? [...new Set(list.map((tag) => String(tag).toLowerCase()))].sort().join(",") : "";
13492
+ return `object:default=${opts.default};dsd=${tags(opts["declarative-shadow-dom"])};scoped=${tags(opts.scoped)}`;
13493
+ }
13494
+ /** The most reusable windows kept at once (one per distinct `serializeShadowRoot` key). */
13495
+ const MAX_REUSABLE_WINDOWS = 16;
13496
+ /** Long-lived windows used by `reuseWindow` renders, by `serializeShadowRoot` key. */
13497
+ const reusableWindows = /* @__PURE__ */ new Map();
13498
+ /** Renders sharing a reusable window must not overlap, so each key has a queue. */
13499
+ const renderQueues = /* @__PURE__ */ new Map();
13500
+ const NOOP$1 = () => {};
13501
+ /**
13502
+ * Run `render` once every earlier render using the same reusable window has finished.
13503
+ * @param key the render's {@link serializeShadowRootKey}
13504
+ * @param render the render to run
13505
+ * @returns the render's result
13506
+ */
13507
+ function enqueueReusableRender(key, render) {
13508
+ const queued = (renderQueues.get(key) ?? Promise.resolve()).then(render, render);
13509
+ renderQueues.set(key, queued.then(NOOP$1, NOOP$1));
13510
+ return queued;
13511
+ }
13512
+ /**
13513
+ * Get the reusable window for a `serializeShadowRoot` key, reset and holding `html`.
13514
+ * @param html the HTML to render
13515
+ * @param key the render's {@link serializeShadowRootKey}
13516
+ * @returns the window to render into
13517
+ */
13518
+ function getReusableWindow(html, key) {
13519
+ let win = reusableWindows.get(key);
13520
+ if (!win) {
13521
+ if (reusableWindows.size >= MAX_REUSABLE_WINDOWS) reusableWindows.delete(reusableWindows.keys().next().value);
13522
+ win = new MockWindow(html);
13523
+ reusableWindows.set(key, win);
13524
+ return win;
13525
+ }
13526
+ try {
13527
+ resetWindowForReuse(win, html);
13528
+ return win;
13529
+ } catch (e) {
13530
+ discardReusableWindow(key);
13531
+ throw e;
13532
+ }
13533
+ }
13534
+ /**
13535
+ * Stop reusing the window for a key, e.g. after a render failed and may have left it in a bad
13536
+ * state. The next render with that key creates a new one.
13537
+ * @param key the render's {@link serializeShadowRootKey}
13538
+ */
13539
+ function discardReusableWindow(key) {
13540
+ const win = reusableWindows.get(key);
13541
+ reusableWindows.delete(key);
13542
+ try {
13543
+ win?.close();
13544
+ } catch {}
13545
+ }
13546
+ /**
13547
+ * Drop every reusable window and render queue. For hosts where a render can be abandoned without
13548
+ * ever settling (the `ssr-wasm` plugin, when a call ends with a render still waiting), so the
13549
+ * next render doesn't queue behind it forever.
13550
+ */
13551
+ function resetReusableWindows() {
13552
+ for (const win of reusableWindows.values()) try {
13553
+ win.close();
13554
+ } catch {}
13555
+ reusableWindows.clear();
13556
+ renderQueues.clear();
13557
+ }
13558
+ //#endregion
13327
13559
  //#region src/server/runner/runtime-log.ts
13328
13560
  function runtimeLogging(win, opts, results) {
13329
13561
  try {
@@ -13365,19 +13597,31 @@ function runtimeLog(pathname, type, msgs) {
13365
13597
  }
13366
13598
  //#endregion
13367
13599
  //#region src/server/runner/window-initialize.ts
13368
- /**
13369
- * Maintain a unique `docData` object across multiple hydration runs
13370
- * to ensure that host ids remain unique.
13371
- */
13372
- const docData = {
13600
+ const createDocData = () => ({
13373
13601
  hostIds: 0,
13374
13602
  rootLevelIds: 0,
13375
13603
  staticComponents: /* @__PURE__ */ new Set()
13376
- };
13604
+ });
13377
13605
  /**
13378
- * Reset the docData counters. Useful for testing to ensure deterministic IDs.
13606
+ * Shared across fragment renders (`fullDocument: false`). Several fragments usually end up in
13607
+ * one page, so their hydration ids must not collide - this keeps counting across calls until
13608
+ * `resetSsrDocData()` is called.
13609
+ *
13610
+ * Full-document renders don't use it: a document is a whole page, so each gets its own
13611
+ * `docData` and its ids always start from 1. That keeps the output deterministic without any
13612
+ * reset, and stays correct when several renders run concurrently.
13613
+ */
13614
+ const fragmentDocData = createDocData();
13615
+ /**
13616
+ * Restart the hydration ids used by fragment renders (`fullDocument: false`).
13617
+ *
13618
+ * Optional - ids only need to be unique within a page, and they are without it. Call it once at
13619
+ * the start of each request that renders fragments, to get the same output for the same input.
13620
+ * Never call it between fragments that end up in the same page, or their ids will collide.
13621
+ * Full-document renders always start from 1 and aren't affected.
13379
13622
  */
13380
13623
  function resetSsrDocData() {
13624
+ const docData = fragmentDocData;
13381
13625
  docData.hostIds = 0;
13382
13626
  docData.rootLevelIds = 0;
13383
13627
  docData.staticComponents.clear();
@@ -13409,13 +13653,36 @@ function initializeWindow(win, doc, opts, results) {
13409
13653
  } catch {}
13410
13654
  if (opts.constrainTimeouts) constrainTimeouts(win);
13411
13655
  runtimeLogging(win, opts, results);
13412
- doc[STENCIL_DOC_DATA] = docData;
13656
+ doc[STENCIL_DOC_DATA] = opts.fullDocument === false ? fragmentDocData : createDocData();
13413
13657
  return win;
13414
13658
  }
13415
13659
  //#endregion
13416
13660
  //#region src/server/runner/render.ts
13417
13661
  const NOOP = () => {};
13418
13662
  /**
13663
+ * Render into the long-lived window for this render's `serializeShadowRoot` mode, once any
13664
+ * earlier render using that window has finished. See the `reuseWindow` option.
13665
+ * @param html the HTML to render
13666
+ * @param opts the normalized render options
13667
+ * @param results the results object to fill in
13668
+ * @returns the render results
13669
+ */
13670
+ function renderInReusableWindow(html, opts, results) {
13671
+ opts.destroyWindow = false;
13672
+ opts.destroyDocument = false;
13673
+ const key = opts.serializeShadowRootKey;
13674
+ const run = async () => {
13675
+ try {
13676
+ await render(getReusableWindow(html, key), opts, results);
13677
+ } catch (e) {
13678
+ discardReusableWindow(key);
13679
+ renderCatchError(results, e);
13680
+ }
13681
+ return results;
13682
+ };
13683
+ return enqueueReusableRender(key, run);
13684
+ }
13685
+ /**
13419
13686
  * Renders HTML to a string, returning the full hydration results.
13420
13687
  * This is the primary SSR function and is portable (no Node.js dependencies).
13421
13688
  * @param html - the HTML string or document to render
@@ -13468,9 +13735,11 @@ function ssrDocument(doc, options) {
13468
13735
  * Defines whether we render the shadow root as a declarative shadow root or as scoped shadow root.
13469
13736
  */
13470
13737
  opts.serializeShadowRoot = typeof opts.serializeShadowRoot === "undefined" ? "declarative-shadow-dom" : opts.serializeShadowRoot;
13738
+ opts.serializeShadowRootKey = serializeShadowRootKey(opts.serializeShadowRoot);
13471
13739
  let win = null;
13472
13740
  const results = generateHydrateResults(opts);
13473
13741
  if (hasError(results.diagnostics)) return Promise.resolve(results);
13742
+ if (typeof doc === "string" && opts.reuseWindow) return renderInReusableWindow(doc, opts, results);
13474
13743
  if (typeof doc === "string") try {
13475
13744
  opts.destroyWindow = true;
13476
13745
  opts.destroyDocument = true;
@@ -13513,14 +13782,6 @@ async function render(win, opts, results) {
13513
13782
  try {
13514
13783
  await Promise.resolve(beforeHydrateFn(win.document));
13515
13784
  return new Promise((resolve) => {
13516
- if (Array.isArray(opts.modes)) {
13517
- /**
13518
- * Reset the mode resolution chain as we expect every `renderToString` call to render
13519
- * the components in new environment/document.
13520
- */
13521
- modeResolutionChain.length = 0;
13522
- opts.modes.forEach((mode) => setMode(mode));
13523
- }
13524
13785
  return ssrFactory(win, opts, results, afterSsr, resolve);
13525
13786
  });
13526
13787
  } catch (e) {
@@ -13578,7 +13839,10 @@ function finalizeSsr(win, doc, opts, results) {
13578
13839
  renderCatchError(results, e);
13579
13840
  }
13580
13841
  if (opts.clientSsrAnnotations) doc.documentElement.classList.add("hydrated");
13581
- if (opts.serializeToHtml) results.html = serializeDocumentToString(doc, opts);
13842
+ if (opts.serializeToHtml) {
13843
+ if (opts.fullDocument === false) moveComponentStylesIntoBody(doc);
13844
+ results.html = serializeDocumentToString(doc, opts);
13845
+ }
13582
13846
  } catch (e) {
13583
13847
  renderCatchError(results, e);
13584
13848
  }
@@ -13610,6 +13874,23 @@ function serializeDocumentToString(doc, opts) {
13610
13874
  fullDocument: opts.fullDocument
13611
13875
  });
13612
13876
  }
13877
+ /**
13878
+ * A fragment (`fullDocument: false`) serializes only the contents of `<body>`, but the styles of
13879
+ * scoped components - and of shadow components rendered with `serializeShadowRoot: 'scoped'` -
13880
+ * are written to `<head>`. Move them to the start of `<body>` so the fragment carries the styles
13881
+ * its components need, instead of rendering unstyled until the client loads.
13882
+ *
13883
+ * Stateless: every fragment includes all the styles it uses, so the same styles can appear in
13884
+ * several fragments on one page. On the client, a style found outside `<head>` isn't reused, so
13885
+ * the runtime adds its own copy to `<head>` when the component loads - harmless duplication.
13886
+ * @param doc the rendered document
13887
+ */
13888
+ function moveComponentStylesIntoBody(doc) {
13889
+ if (!doc.head || !doc.body) return;
13890
+ const styles = Array.from(doc.head.querySelectorAll(`style[${HYDRATED_STYLE_ID}]`));
13891
+ const firstChild = doc.body.firstChild;
13892
+ for (const style of styles) doc.body.insertBefore(style, firstChild);
13893
+ }
13613
13894
  function isValidDocument(doc) {
13614
13895
  return doc != null && doc.nodeType === 9 && doc.documentElement != null && doc.documentElement.nodeType === 1 && doc.body != null && doc.body.nodeType === 1;
13615
13896
  }
@@ -13622,4 +13903,21 @@ function removeScripts(elm) {
13622
13903
  }
13623
13904
  }
13624
13905
  //#endregion
13625
- export { createWindowFromHtml, hydrateDocument, renderToString, resetSsrDocData, serializeDocumentToString, setTagTransformer, ssrDocument, streamToString, transformTag };
13906
+ //#region src/server/runner/index.ts
13907
+ /**
13908
+ * Render components under transformed tag names, to match tag transformation on the client.
13909
+ *
13910
+ * Components are registered under their transformed names when a window's SSR platform is set up,
13911
+ * so this also discards the reusable windows (see the `reuseWindow` option): later renders set up
13912
+ * new ones that use the new transformer.
13913
+ *
13914
+ * (A function declaration with its own name, so the runtime's `setTagTransformer` keeps its name in
13915
+ * the bundle - the SSR build looks for it - and this is hoisted.)
13916
+ * @param transformer the tag transformer
13917
+ */
13918
+ function setTagTransformerForSsr(transformer) {
13919
+ setTagTransformer(transformer);
13920
+ resetReusableWindows();
13921
+ }
13922
+ //#endregion
13923
+ export { createWindowFromHtml, hydrateDocument, renderToString, resetReusableWindows, resetSsrDocData, serializeDocumentToString, setTagTransformerForSsr as setTagTransformer, ssrDocument, streamToString, transformTag };
@@ -1,6 +1,15 @@
1
- import { ReadonlySignal, ReadonlySignal as ReadonlySignal$1, Signal, batch, computed, effect, signal, untracked } from "@preact/signals-core";
1
+ import * as SignalsCore from "@preact/signals-core";
2
+ import { ReadonlySignal, Signal } from "@preact/signals-core";
2
3
  import "rolldown";
3
4
  import "typescript";
5
+ //#region src/runtime/signals-core.d.ts
6
+ declare const batch: typeof SignalsCore.batch;
7
+ declare const computed: typeof SignalsCore.computed;
8
+ declare const effect: typeof SignalsCore.effect;
9
+ declare const untracked: typeof SignalsCore.untracked;
10
+ declare function signal<T>(value: T, options?: SignalsCore.SignalOptions<T>): SignalsCore.Signal<T>;
11
+ declare function signal<T = undefined>(): SignalsCore.Signal<T | undefined>;
12
+ //#endregion
4
13
  //#region src/runtime/signals.d.ts
5
14
  declare const STENCIL_SIGNALS_SYMBOL: unique symbol;
6
15
  //#endregion
@@ -22,7 +31,7 @@ declare const STENCIL_SIGNALS_SYMBOL: unique symbol;
22
31
  * @param prop - the `@Prop` member name
23
32
  * @returns the `ReadonlySignal` for the prop, or `null` if not found / not signal-backed
24
33
  */
25
- declare const getSignal: <T = unknown>(elm: Element, prop: string) => ReadonlySignal$1<T> | null;
34
+ declare const getSignal: <T = unknown>(elm: Element, prop: string) => ReadonlySignal<T> | null;
26
35
  /**
27
36
  * Marks a class method as a reactive effect. Wraps the method in `effect()` after
28
37
  * signal initialization and registers cleanup on disconnect. Dependencies are