@shadow-js/web 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/dist/dev/attributes.d.ts +10 -3
- package/dist/dev/attributes.js +27 -49
- package/dist/dev/attributes.js.map +1 -1
- package/dist/dev/class-style.d.ts +6 -2
- package/dist/dev/class-style.js +24 -7
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/control-flow/dynamic.d.ts +11 -2
- package/dist/dev/control-flow/dynamic.js +56 -39
- package/dist/dev/control-flow/dynamic.js.map +1 -1
- package/dist/dev/control-flow/portal.js +2 -0
- package/dist/dev/control-flow/portal.js.map +1 -1
- package/dist/dev/element.js +1 -1
- package/dist/dev/element.js.map +1 -1
- package/dist/dev/events.js +15 -44
- package/dist/dev/events.js.map +1 -1
- package/dist/dev/insert.d.ts +15 -5
- package/dist/dev/insert.js +35 -13
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/claim.d.ts +2 -1
- package/dist/dev/internal/claim.js +18 -2
- package/dist/dev/internal/claim.js.map +1 -1
- package/dist/dev/internal/diagnostics.d.ts +7 -3
- package/dist/dev/internal/diagnostics.js +14 -4
- package/dist/dev/internal/diagnostics.js.map +1 -1
- package/dist/dev/internal/early-events.js +20 -2
- package/dist/dev/internal/early-events.js.map +1 -1
- package/dist/dev/internal/react-names.js +25 -61
- package/dist/dev/internal/react-names.js.map +1 -1
- package/dist/dev/internal/reconcile.js +3 -6
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/jsx/global.d.ts +5 -2
- package/dist/dev/jsx/html.d.ts +1 -0
- package/dist/dev/resource-hints.js +4 -2
- package/dist/dev/resource-hints.js.map +1 -1
- package/dist/dev/select-value.js +5 -15
- package/dist/dev/select-value.js.map +1 -1
- package/dist/dev/server/attributes.d.ts +3 -0
- package/dist/dev/server/attributes.js +5 -1
- package/dist/dev/server/attributes.js.map +1 -1
- package/dist/dev/server/element.js +8 -4
- package/dist/dev/server/element.js.map +1 -1
- package/dist/dev/server/errors.js +7 -1
- package/dist/dev/server/errors.js.map +1 -1
- package/dist/dev/server/escape.js +14 -6
- package/dist/dev/server/escape.js.map +1 -1
- package/dist/dev/server/form-controls.js +5 -2
- package/dist/dev/server/form-controls.js.map +1 -1
- package/dist/dev/server/index.d.ts +2 -1
- package/dist/dev/server/index.js +2 -1
- package/dist/dev/server/raw-text.d.ts +28 -0
- package/dist/dev/server/raw-text.js +66 -0
- package/dist/dev/server/raw-text.js.map +1 -0
- package/dist/dev/server/render.d.ts +2 -1
- package/dist/dev/server/render.js +2 -2
- package/dist/dev/server/render.js.map +1 -1
- package/dist/dev/server/stream.d.ts +1 -1
- package/dist/dev/server/stream.js +2 -2
- package/dist/dev/server/stream.js.map +1 -1
- package/dist/dev/server.d.ts +2 -1
- package/dist/dev/server.js +2 -1
- package/dist/dev/spread.js +7 -54
- package/dist/dev/spread.js.map +1 -1
- package/dist/prod/attributes.js +1 -1
- package/dist/prod/attributes.js.map +1 -1
- package/dist/prod/class-style.js +1 -1
- package/dist/prod/class-style.js.map +1 -1
- package/dist/prod/control-flow/dynamic.js +1 -1
- package/dist/prod/control-flow/dynamic.js.map +1 -1
- package/dist/prod/control-flow/portal.js +1 -1
- package/dist/prod/control-flow/portal.js.map +1 -1
- package/dist/prod/element.js +1 -1
- package/dist/prod/element.js.map +1 -1
- package/dist/prod/events.js +1 -1
- package/dist/prod/events.js.map +1 -1
- package/dist/prod/insert.js +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/internal/claim.js +1 -1
- package/dist/prod/internal/claim.js.map +1 -1
- package/dist/prod/internal/diagnostics.js +1 -1
- package/dist/prod/internal/diagnostics.js.map +1 -1
- package/dist/prod/internal/early-events.js +1 -1
- package/dist/prod/internal/early-events.js.map +1 -1
- package/dist/prod/internal/react-names.js +1 -1
- package/dist/prod/internal/react-names.js.map +1 -1
- package/dist/prod/internal/reconcile.js +1 -1
- package/dist/prod/internal/reconcile.js.map +1 -1
- package/dist/prod/resource-hints.js +1 -1
- package/dist/prod/resource-hints.js.map +1 -1
- package/dist/prod/select-value.js +1 -1
- package/dist/prod/select-value.js.map +1 -1
- package/dist/prod/server/attributes.js +1 -1
- package/dist/prod/server/attributes.js.map +1 -1
- package/dist/prod/server/element.js +1 -1
- package/dist/prod/server/element.js.map +1 -1
- package/dist/prod/server/errors.js +1 -1
- package/dist/prod/server/errors.js.map +1 -1
- package/dist/prod/server/escape.js +1 -1
- package/dist/prod/server/escape.js.map +1 -1
- package/dist/prod/server/form-controls.js +2 -2
- package/dist/prod/server/form-controls.js.map +1 -1
- package/dist/prod/server/index.js +1 -1
- package/dist/prod/server/raw-text.js +2 -0
- package/dist/prod/server/raw-text.js.map +1 -0
- package/dist/prod/server/render.js +1 -1
- package/dist/prod/server/render.js.map +1 -1
- package/dist/prod/server/stream.js +1 -1
- package/dist/prod/server/stream.js.map +1 -1
- package/dist/prod/server.js +1 -1
- package/dist/prod/spread.js +1 -1
- package/dist/prod/spread.js.map +1 -1
- package/dist/server/attributes.js +1 -1
- package/dist/server/attributes.js.map +1 -1
- package/dist/server/class-style.js +1 -1
- package/dist/server/class-style.js.map +1 -1
- package/dist/server/control-flow/dynamic.js +1 -1
- package/dist/server/control-flow/dynamic.js.map +1 -1
- package/dist/server/control-flow/portal.js +1 -1
- package/dist/server/control-flow/portal.js.map +1 -1
- package/dist/server/element.js +1 -1
- package/dist/server/element.js.map +1 -1
- package/dist/server/events.js +1 -1
- package/dist/server/events.js.map +1 -1
- package/dist/server/insert.js +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/internal/claim.js +1 -1
- package/dist/server/internal/claim.js.map +1 -1
- package/dist/server/internal/diagnostics.js +1 -1
- package/dist/server/internal/diagnostics.js.map +1 -1
- package/dist/server/internal/early-events.js +1 -1
- package/dist/server/internal/early-events.js.map +1 -1
- package/dist/server/internal/react-names.js +1 -1
- package/dist/server/internal/react-names.js.map +1 -1
- package/dist/server/internal/reconcile.js +1 -1
- package/dist/server/internal/reconcile.js.map +1 -1
- package/dist/server/resource-hints.js +1 -1
- package/dist/server/resource-hints.js.map +1 -1
- package/dist/server/select-value.js +1 -1
- package/dist/server/select-value.js.map +1 -1
- package/dist/server/server/attributes.js +1 -1
- package/dist/server/server/attributes.js.map +1 -1
- package/dist/server/server/element.js +1 -1
- package/dist/server/server/element.js.map +1 -1
- package/dist/server/server/errors.js +1 -1
- package/dist/server/server/errors.js.map +1 -1
- package/dist/server/server/escape.js +1 -1
- package/dist/server/server/escape.js.map +1 -1
- package/dist/server/server/form-controls.js +2 -2
- package/dist/server/server/form-controls.js.map +1 -1
- package/dist/server/server/index.js +1 -1
- package/dist/server/server/raw-text.js +2 -0
- package/dist/server/server/raw-text.js.map +1 -0
- package/dist/server/server/render.js +1 -1
- package/dist/server/server/render.js.map +1 -1
- package/dist/server/server/stream.js +1 -1
- package/dist/server/server/stream.js.map +1 -1
- package/dist/server/server.js +1 -1
- package/dist/server/spread.js +1 -1
- package/dist/server/spread.js.map +1 -1
- package/dist/server-dev/attributes.js +27 -49
- package/dist/server-dev/attributes.js.map +1 -1
- package/dist/server-dev/class-style.js +24 -7
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/control-flow/dynamic.js +22 -10
- package/dist/server-dev/control-flow/dynamic.js.map +1 -1
- package/dist/server-dev/control-flow/portal.js +2 -0
- package/dist/server-dev/control-flow/portal.js.map +1 -1
- package/dist/server-dev/element.js +3 -1
- package/dist/server-dev/element.js.map +1 -1
- package/dist/server-dev/events.js +15 -44
- package/dist/server-dev/events.js.map +1 -1
- package/dist/server-dev/insert.js +35 -13
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/claim.js +18 -2
- package/dist/server-dev/internal/claim.js.map +1 -1
- package/dist/server-dev/internal/diagnostics.js +14 -4
- package/dist/server-dev/internal/diagnostics.js.map +1 -1
- package/dist/server-dev/internal/early-events.js +20 -2
- package/dist/server-dev/internal/early-events.js.map +1 -1
- package/dist/server-dev/internal/react-names.js +25 -61
- package/dist/server-dev/internal/react-names.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js +3 -6
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/resource-hints.js +4 -2
- package/dist/server-dev/resource-hints.js.map +1 -1
- package/dist/server-dev/select-value.js +5 -15
- package/dist/server-dev/select-value.js.map +1 -1
- package/dist/server-dev/server/attributes.js +5 -1
- package/dist/server-dev/server/attributes.js.map +1 -1
- package/dist/server-dev/server/element.js +8 -4
- package/dist/server-dev/server/element.js.map +1 -1
- package/dist/server-dev/server/errors.js +7 -1
- package/dist/server-dev/server/errors.js.map +1 -1
- package/dist/server-dev/server/escape.js +14 -6
- package/dist/server-dev/server/escape.js.map +1 -1
- package/dist/server-dev/server/form-controls.js +5 -2
- package/dist/server-dev/server/form-controls.js.map +1 -1
- package/dist/server-dev/server/index.js +2 -1
- package/dist/server-dev/server/raw-text.js +86 -0
- package/dist/server-dev/server/raw-text.js.map +1 -0
- package/dist/server-dev/server/render.js +2 -2
- package/dist/server-dev/server/render.js.map +1 -1
- package/dist/server-dev/server/stream.js +2 -2
- package/dist/server-dev/server/stream.js.map +1 -1
- package/dist/server-dev/server.js +2 -1
- package/dist/server-dev/spread.js +7 -54
- package/dist/server-dev/spread.js.map +1 -1
- package/package.json +3 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","ANIMATION_VALUE_ATTRIBUTES","ENUMERATED_ATTRIBUTES","BOOLEAN_ATTRIBUTES","UNSAFE_URL_PREFIXES","assertAttributeName","name","invalid","isEventName","lowerName","isStringValued","stripControls","kept","char","text","code","isUnsafeUrl","normalized","value","prefix","isUnsafeAttributeValue","attributeText","assertNotSymbol","ssrAttribute","resolved","resolveValue","isBoolean","escapeHtml"],"sources":["../../../src/server/attributes.ts"],"sourcesContent":["import { invalid } from \"./errors\";\nimport { escapeHtml, resolveValue } from \"./escape\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. Same as the client. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/** Attributes whose value is a URL and is therefore checked for script schemes. Same as the client. */\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"
|
|
1
|
+
{"version":3,"file":"attributes.js","names":["ATTRIBUTE_NAME","URL_ATTRIBUTES","ANIMATION_VALUE_ATTRIBUTES","ENUMERATED_ATTRIBUTES","BOOLEAN_ATTRIBUTES","UNSAFE_URL_PREFIXES","assertAttributeName","name","invalid","isEventName","lowerName","isStringValued","stripControls","kept","char","text","code","isUnsafeUrl","normalized","value","prefix","isUnsafeAttributeValue","attributeText","assertNotSymbol","ssrAttribute","resolved","resolveValue","isBoolean","escapeHtml"],"sources":["../../../src/server/attributes.ts"],"sourcesContent":["import { SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"../internal/diagnostics\";\nimport { invalid } from \"./errors\";\nimport { escapeHtml, resolveValue } from \"./escape\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. Same as the client. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/** Attributes whose value is a URL and is therefore checked for script schemes. Same as the client. */\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"xlink:href\",\n \"poster\",\n \"data\",\n]);\n\n/**\n * SVG animation attributes (`animate`, `set`): with `attributeName=\"href\"` they write an `href` by animation, so their value\n * is checked like one. `values` is a `;` list and every entry is checked. Same as the client.\n */\nconst ANIMATION_VALUE_ATTRIBUTES: ReadonlySet<string> = new Set([\"values\", \"from\", \"to\", \"by\"]);\n\n/** Enumerated attributes where `false` is a real value (\"false\") rather than an absence. */\nconst ENUMERATED_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"draggable\",\n \"spellcheck\",\n \"contenteditable\",\n]);\n\n/**\n * Boolean attributes that a props object writes as presence flags (`disabled: true` gives a bare\n * `disabled`). Lower-case names only.\n * @internal\n */\nexport const BOOLEAN_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"async\",\n \"autofocus\",\n \"autoplay\",\n \"checked\",\n \"controls\",\n \"default\",\n \"defer\",\n \"disabled\",\n \"formnovalidate\",\n \"hidden\",\n \"inert\",\n \"ismap\",\n \"loop\",\n \"multiple\",\n \"muted\",\n \"nomodule\",\n \"novalidate\",\n \"open\",\n \"playsinline\",\n \"readonly\",\n \"required\",\n \"reversed\",\n \"selected\",\n]);\n\n/** URL prefixes (after normalization) that are never written. Same as the client. */\nconst UNSAFE_URL_PREFIXES: readonly string[] = [\"javascript:\", \"data:text/html\", \"vbscript:\"];\n\n/** Throws a TypeError unless `name` can be written as an attribute name. @internal */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) {\n throw invalid(\"INVALID_ATTRIBUTE_NAME\", `\"${name}\" is not a valid attribute name.`);\n }\n}\n\n/** True for `on*` names, which never reach markup. Length matches the client's event test. @internal */\nexport function isEventName(lowerName: string): boolean {\n return lowerName.length > 2 && lowerName.startsWith(\"on\");\n}\n\n/** True for `aria-*`, `data-*` and the enumerated attributes: their booleans are strings. */\nfunction isStringValued(lowerName: string): boolean {\n return (\n lowerName.startsWith(\"aria-\") ||\n lowerName.startsWith(\"data-\") ||\n ENUMERATED_ATTRIBUTES.has(lowerName)\n );\n}\n\n/** Removes C0 and C1 control characters, which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n let kept = \"\";\n for (const char of text) {\n const code = char.charCodeAt(0);\n if (code > 0x1f && (code < 0x7f || code > 0x9f)) kept += char;\n }\n return kept;\n}\n\n/** True when the URL would run script, after the normalization browsers apply. @internal */\nexport function isUnsafeUrl(value: string): boolean {\n const normalized = stripControls(value).trim().toLowerCase();\n return UNSAFE_URL_PREFIXES.some((prefix) => normalized.startsWith(prefix));\n}\n\n/** True when `lowerName` carries a URL (or an animated one) and `value` would run script. */\nfunction isUnsafeAttributeValue(lowerName: string, value: string): boolean {\n if (URL_ATTRIBUTES.has(lowerName)) return isUnsafeUrl(value);\n return ANIMATION_VALUE_ATTRIBUTES.has(lowerName) && value.split(\";\").some(isUnsafeUrl);\n}\n\n/** Text to write for `value`, or null when the attribute is removed. Same rules as the client. @internal */\nexport function attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return isStringValued(lowerName) ? \"false\" : null;\n if (value === true) return isStringValued(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** Refuses symbols, which have no markup form and would otherwise be coerced silently. */\nfunction assertNotSymbol(value: unknown): void {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be an attribute value.\");\n }\n}\n\n/**\n * Renders one attribute as markup with a leading space, or `\"\"` when the attribute is absent: the\n * helper the compiler's server output calls for a dynamic attribute. It applies the client's value\n * rules and URL check, so server and client agree on what is written.\n *\n * - `null`, `undefined` and `false` give `\"\"` (except `false` on `aria-*`, `data-*`, `draggable`,\n * `spellcheck` and `contenteditable`, which is written as `\"false\"`); `true` writes `=\"\"` (or\n * `\"true\"` for those same names). Other values are written as `String(value)`, HTML-escaped.\n * - URL attributes whose value would run script are dropped, with the check of\n * `isUnsafeUrlAttribute` (including the SVG animation attributes `values`, `from`, `to`, `by`).\n * - `srcdoc` is an HTML sink, not a URL: its value is a document the frame runs, escaped for the attribute\n * and otherwise written as it is, with the trust of `innerHTML`. Sanitize it and give the frame a `sandbox`\n * attribute. Development builds warn once with `SRCDOC_DYNAMIC`.\n * - `on*` names are dropped: event handlers never reach markup.\n * - Accessors are called (untracked) until a plain value remains.\n *\n * @param name Attribute name, matching `[A-Za-z_:][A-Za-z0-9_:.-]*`. It is validated before\n * anything else, so an invalid name always throws.\n * @param value The value, or an accessor of it.\n * @param isBoolean `true` for a presence attribute such as `disabled`: a truthy value writes the bare\n * name, a falsy one writes nothing. Default: `false`.\n * @returns Markup such as `' title=\"a&b\"'`, or `\"\"`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an invalid name, and `UNRECOGNIZED_INSERT_VALUE`\n * when the value is a symbol.\n * @example\n * import { ssrAttribute } from \"@shadow-js/web/server\";\n *\n * ssrAttribute(\"title\", \"Tom & Jerry\"); // ' title=\"Tom & Jerry\"'\n * ssrAttribute(\"disabled\", true, true); // \" disabled\"\n * ssrAttribute(\"href\", \"javascript:alert(1)\"); // \"\"\n * @since 1.0.0\n */\nexport function ssrAttribute(name: string, value: unknown, isBoolean = false): string {\n assertAttributeName(name);\n const lowerName = name.toLowerCase();\n if (isEventName(lowerName)) return \"\";\n const resolved = resolveValue(value);\n assertNotSymbol(resolved);\n if (isBoolean) return resolved ? ` ${name}` : \"\";\n const text = attributeText(lowerName, resolved);\n if (text === null) return \"\";\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeAttributeValue(lowerName, text)) return \"\";\n return ` ${name}=\"${escapeHtml(text)}\"`;\n}\n"],"mappings":"A,iGAKA,MAAMA,EAAiB,+BAGjBC,kBAAsC,IAAI,IAAI,CAClD,OACA,MACA,SACA,aACA,aACA,SACA,MACF,CAAC,EAMKC,kBAAkD,IAAI,IAAI,CAAC,SAAU,OAAQ,KAAM,IAAI,CAAC,EAGxFC,kBAA6C,IAAI,IAAI,CACzD,YACA,aACA,iBACF,CAAC,EAOYC,kBAA0C,IAAI,IAAI,CAC7D,QACA,YACA,WACA,UACA,WACA,UACA,QACA,WACA,iBACA,SACA,QACA,QACA,OACA,WACA,QACA,WACA,aACA,OACA,cACA,WACA,WACA,WACA,UACF,CAAC,EAGKC,EAAyC,CAAC,cAAe,iBAAkB,WAAW,EAG5F,SAAgBC,EAAoB,EAAoB,CACtD,GAAI,CAACN,EAA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nC,IAAMe,EAAWC,EAAaP,CAAK,EAEnC,GADAI,EAAgBE,CAAQ,EACpBE,EAAW,OAAOF,EAAW,IAAIlB,IAAS,GAC9C,IAAMQ,EAAOO,EAAcZ,EAAWe,CAAQ,EAI9C,OAHIV,IAAS,MAETM,EAAuBX,EAAWK,CAAI,EAAU,GAC7C,IAAIR,EAAK,IAAIqB,EAAWb,CAAI,EAAE,EACvC,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{nextKey as e}from"../internal/hydration-scope.js";import{IGNORED_KEYS as t,attributeName as n}from"../internal/react-names.js";import{invalid as r}from"./errors.js";import{SsrNode as i,isSsrNode as a}from"./node.js";import{escape as o,escapeHtml as s,resolveValue as c}from"./escape.js";import{BOOLEAN_ATTRIBUTES as l,isEventName as u,ssrAttribute as d}from"./attributes.js";import{classText as f,ssrStyle as p,styleText as m}from"./class-style.js";import{
|
|
1
|
+
import{nextKey as e}from"../internal/hydration-scope.js";import{IGNORED_KEYS as t,attributeName as n}from"../internal/react-names.js";import{invalid as r}from"./errors.js";import{SsrNode as i,isSsrNode as a}from"./node.js";import{escape as o,escapeHtml as s,resolveValue as c}from"./escape.js";import{BOOLEAN_ATTRIBUTES as l,isEventName as u,ssrAttribute as d}from"./attributes.js";import{classText as f,ssrStyle as p,styleText as m}from"./class-style.js";import{keepLeadingNewline as h,markSelectedOptions as g,textareaContent as _}from"./form-controls.js";import{rawElementContent as v}from"./raw-text.js";const y=/^[A-Za-z][A-Za-z0-9-]*$/,b=/* @__PURE__ */ new Set([`area`,`base`,`br`,`col`,`command`,`embed`,`hr`,`img`,`input`,`keygen`,`link`,`meta`,`param`,`source`,`track`,`wbr`]),x=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`,`children`,`ref`]);function S(e){if(typeof e==`object`&&e)return Reflect.get(e,`__html`)}function C(e,...t){if(!Array.isArray(e)||e.length!==t.length+1)throw TypeError(`ssr(): parts must have one more entry than there are holes.`);let n=e[0]??``;for(let r=0;r<t.length;r+=1){let i=t[r];if(typeof i==`string`)n+=i;else if(a(i))n+=i.t;else throw TypeError(`ssr(): a hole must be an escaped string or an SsrNode.`);n+=e[r+1]??``}return new i(n)}function w(e){if(typeof e!=`string`)throw TypeError(`ssrRaw(): the markup must be a string.`);return new i(e)}function T(){let t=e();return t===void 0?``:` data-hk="${s(t)}"`}function E(e,a,C=void 0,w=!1,E=!1){if(typeof e!=`string`||!y.test(e))throw r(`INVALID_TAG_NAME`,`"${String(e)}" is not a valid tag name.`);let A=e.toLowerCase(),j=A===`select`,M=A===`textarea`,N={},P=!1,F=!1,I=w?T():``,L=[],R=``,z;if(typeof a==`object`&&a)for(let e of Object.keys(a)){if(x.has(e)||t.has(e)||e===`ref`||e.startsWith(`on:`)||e.startsWith(`use:`)||e.startsWith(`prop:`)||u(e)||w&&e===`data-hk`)continue;let r=c(Reflect.get(a,e));if(e===`class`||e===`className`){let e=f(r);e!==``&&L.push(e)}else if(e===`classList`)O(r,L);else if(e===`style`)R=m(r);else if(e===`innerHTML`)z=k(r);else if(e===`dangerouslySetInnerHTML`)z=k(c(S(r)));else if((j||M)&&e===`value`)N.value=r,P=!0;else if((j||M)&&e===`defaultValue`)N.fallback=r,F=!0;else if(e.startsWith(`attr:`))I+=d(e.slice(5),r);else if(e.startsWith(`bool:`))I+=d(e.slice(5),r,!0);else if(e===`defaultValue`||e===`defaultChecked`){let t=e===`defaultValue`?`value`:`checked`;Object.hasOwn(a,t)||(I+=d(t,r,t===`checked`))}else{let t=n(e,E),i=l.has(t)&&(t!==`hidden`||r!==`until-found`);I+=d(t,r,i)}}if(L.length>0&&(I+=` class="${s(L.join(` `))}"`),R!==``&&(I+=p(R)),b.has(A))return new i(`<${e}${I}>`);let B=!E&&(A===`script`||A===`style`),V=C===void 0?D(a):C,H=z===void 0?B?v(A,V):o(V):z;if(z===void 0&&(P||F)){let e=P?N.value:N.fallback;H=M?_(e):g(e,H)}else M&&z===void 0&&(H=h(H));return new i(`<${e}${I}>${H}</${e}>`)}function D(e){if(typeof e==`object`&&e)return Reflect.get(e,`children`)}function O(e,t){if(typeof e==`object`&&e&&!Array.isArray(e))for(let n of Object.keys(e))n!==``&&c(Reflect.get(e,n))&&t.push(n)}function k(e){if(e==null)return``;if(a(e))return e.t;if(typeof e==`symbol`)throw r(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be innerHTML.`);return String(e)}export{C as ssr,E as ssrElement,T as ssrHydrationKey,w as ssrRaw};
|
|
2
2
|
//# sourceMappingURL=element.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"element.js","names":["TAG_NAME","VOID_ELEMENTS","SKIPPED_KEYS","innerHtmlOfValue","value","ssr","holes","parts","html","index","hole","isSsrNode","SsrNode","ssrRaw","ssrHydrationKey","key","nextKey","escapeHtml","ssrElement","tag","invalid","lowerTag","isSelect","isTextarea","control","hasValue","hasFallback","attributes","needsKey","classes","style","innerHtml","props","IGNORED_KEYS","isEventName","resolveValue","text","classText","collectTruthyKeys","styleText","plainHtml","ssrAttribute","name","attributeName","svg","BOOLEAN_ATTRIBUTES","ssrStyle","content","escape","children","propsChildren","textareaContent","markSelectedOptions","out"],"sources":["../../../src/server/element.ts"],"sourcesContent":["import { nextKey } from \"../internal/hydration-scope\";\nimport { attributeName, IGNORED_KEYS } from \"../internal/react-names\";\nimport { BOOLEAN_ATTRIBUTES, isEventName, ssrAttribute } from \"./attributes\";\nimport { classText, ssrStyle, styleText } from \"./class-style\";\nimport { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { markSelectedOptions, textareaContent } from \"./form-controls\";\nimport { isSsrNode, SsrNode } from \"./node\";\n\n/** A tag name: letters, digits and dashes, starting with a letter. Anything else could break out. */\nconst TAG_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;\n\n/** Elements that never have children or a closing tag. */\nconst VOID_ELEMENTS: ReadonlySet<string> = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"command\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"keygen\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\n/** Keys that never become attributes: they are handled elsewhere or would reach a prototype. */\nconst SKIPPED_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n \"children\",\n \"ref\",\n]);\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`): null and undefined are empty. */\nfunction innerHtmlOfValue(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return undefined;\n return Reflect.get(value, \"__html\");\n}\n\n/**\n * Joins the static parts of a server template with its dynamic holes into trusted markup: the\n * function compiled server output calls for each element tree. Holes are inserted unchanged, so each\n * must already be escaped (the output of `escape`, `ssrAttribute`, `ssrClass`, ...) or an `SsrNode`;\n * any other value throws, so a raw user value cannot reach the markup.\n *\n * @param parts The static markup, one more entry than there are holes.\n * @param holes The dynamic parts: strings produced by the escaping helpers, or `SsrNode` values.\n * @returns The markup as a trusted `SsrNode`, which `escape` writes without encoding.\n * @throws TypeError when `parts` is not an array of `holes.length + 1` entries, or when a hole is not\n * a string or an `SsrNode`.\n * @example\n * import { escape, renderToString, ssr } from \"@shadow-js/web/server\";\n *\n * const name = \"<Ada>\";\n * const html = renderToString(() => ssr([\"<p>Hello, \", \"</p>\"], escape(name)));\n * // \"<p>Hello, <Ada></p>\"\n * @see ssrRaw\n * @since 1.0.0\n */\nexport function ssr(parts: readonly string[], ...holes: unknown[]): SsrNode {\n if (!Array.isArray(parts) || parts.length !== holes.length + 1) {\n throw new TypeError(\"ssr(): parts must have one more entry than there are holes.\");\n }\n let html = parts[0] ?? \"\";\n for (let index = 0; index < holes.length; index += 1) {\n const hole = holes[index];\n if (typeof hole === \"string\") html += hole;\n else if (isSsrNode(hole)) html += hole.t;\n else throw new TypeError(\"ssr(): a hole must be an escaped string or an SsrNode.\");\n html += parts[index + 1] ?? \"\";\n }\n return new SsrNode(html);\n}\n\n/**\n * Marks a string as trusted markup that `escape` and `ssr` insert unchanged. Only use it for markup\n * the application wrote itself, never for user input.\n *\n * @param html The markup, inserted unchanged.\n * @returns The markup as a trusted `SsrNode`.\n * @throws TypeError when `html` is not a string.\n * @example\n * import { renderToString, ssrRaw } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => [\"<b>escaped</b>\", ssrRaw(\"<!-- build 42 -->\")]);\n * // \"<b>escaped</b><!-- build 42 -->\"\n * @see ssr\n * @since 1.0.0\n */\nexport function ssrRaw(html: string): SsrNode {\n if (typeof html !== \"string\") throw new TypeError(\"ssrRaw(): the markup must be a string.\");\n return new SsrNode(html);\n}\n\n/**\n * Draws the next hydration key of the current scope and returns it as a `data-hk` attribute, such as\n * `' data-hk=\"0-0\"'`: compiled server output calls it for the root element of each template, and\n * the client's `hydrate()` claims the element by that key. Calls must happen in the same order as on\n * the client, so call it only where the compiler would.\n *\n * @returns Markup for the `data-hk` attribute, or `\"\"` outside a server render (no key is drawn).\n * @example\n * import { renderToString, ssr, ssrHydrationKey } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => ssr([\"<div\", \">x</div>\"], ssrHydrationKey()));\n * // '<div data-hk=\"0-0\">x</div>'\n * @since 1.0.0\n */\nexport function ssrHydrationKey(): string {\n const key = nextKey();\n return key === undefined ? \"\" : ` data-hk=\"${escapeHtml(key)}\"`;\n}\n\n/**\n * Renders an element from a props object: what compiled server output calls for an element with a\n * spread (`<div {...props} />`), and the server half of `Dynamic` and `element`. It writes the same\n * markup the client's `spread` produces.\n *\n * `class`, `className`, `classList` and `style` are combined into one `class` and one `style`\n * attribute; other keys are attributes, with React names mapped (`htmlFor` is `for`) and HTML boolean\n * attributes (`disabled`, `checked`, ...) written as bare names. `ref`, `children`, `on*` keys and the\n * `on:`, `use:` and `prop:` prefixes are skipped; `attr:` and `bool:` select the attribute and presence\n * forms. `innerHTML` and `dangerouslySetInnerHTML` are written unescaped as the content. On a\n * `textarea` the `value` (or `defaultValue`) is the content; on a `select` it marks the matching\n * `<option selected>` (an array for `multiple`); on other elements `defaultValue` and `defaultChecked`\n * are the `value` and `checked` attributes. Void elements (`img`, `input`, ...) get no content.\n *\n * @param tag Element name: letters, digits and dashes, starting with a letter.\n * @param props The props object (each getter is read once), or `null`.\n * @param children The content, escaped unless it is an `SsrNode`. Undefined (the default) uses the\n * `children` prop.\n * @param needsKey `true` writes the hydration key of this template root first. Default: `false`.\n * @param svg `true` for an SVG element: SVG presentation names are hyphenated (`strokeWidth` is\n * `stroke-width`), other names keep their case. Default: `false`.\n * @returns The element as a trusted `SsrNode`.\n * @throws TypeError `INVALID_TAG_NAME` for an invalid tag, `INVALID_ATTRIBUTE_NAME` for an invalid\n * attribute name, and the errors of {@link ssrAttribute}, `ssrClass` and `ssrStyle` for invalid values.\n * @example\n * import { renderToString, ssrElement } from \"@shadow-js/web/server\";\n *\n * const props = { id: \"save\", disabled: true, class: [\"btn\", { primary: true }], children: \"Save\" };\n * const html = renderToString(() => ssrElement(\"button\", props));\n * // '<button id=\"save\" disabled class=\"btn primary\">Save</button>'\n * @since 1.0.0\n */\nexport function ssrElement(\n tag: string,\n props: unknown,\n children: unknown = undefined,\n needsKey = false,\n svg = false,\n): SsrNode {\n if (typeof tag !== \"string\" || !TAG_NAME.test(tag)) {\n throw invalid(\"INVALID_TAG_NAME\", `\"${String(tag)}\" is not a valid tag name.`);\n }\n const lowerTag = tag.toLowerCase();\n // A browser ignores `value` on these: a textarea's value is its content, a select's value is the\n // `selected` flag of its options. The props are read once and applied to the content below.\n const isSelect = lowerTag === \"select\";\n const isTextarea = lowerTag === \"textarea\";\n const control: { value?: unknown; fallback?: unknown } = {};\n let hasValue = false;\n let hasFallback = false;\n let attributes = needsKey ? ssrHydrationKey() : \"\";\n const classes: string[] = [];\n let style = \"\";\n let innerHtml: string | undefined;\n if (props !== null && typeof props === \"object\") {\n for (const key of Object.keys(props)) {\n if (SKIPPED_KEYS.has(key) || IGNORED_KEYS.has(key)) continue;\n if (\n key === \"ref\" ||\n key.startsWith(\"on:\") ||\n key.startsWith(\"use:\") ||\n key.startsWith(\"prop:\")\n )\n continue;\n if (isEventName(key)) continue;\n if (needsKey && key === \"data-hk\") continue;\n const value = resolveValue(Reflect.get(props, key));\n if (key === \"class\" || key === \"className\") {\n const text = classText(value);\n if (text !== \"\") classes.push(text);\n } else if (key === \"classList\") {\n collectTruthyKeys(value, classes);\n } else if (key === \"style\") {\n style = styleText(value);\n } else if (key === \"innerHTML\") {\n innerHtml = plainHtml(value);\n } else if (key === \"dangerouslySetInnerHTML\") {\n innerHtml = plainHtml(resolveValue(innerHtmlOfValue(value)));\n } else if ((isSelect || isTextarea) && key === \"value\") {\n control.value = value;\n hasValue = true;\n } else if ((isSelect || isTextarea) && key === \"defaultValue\") {\n control.fallback = value;\n hasFallback = true;\n } else if (key.startsWith(\"attr:\")) {\n attributes += ssrAttribute(key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n attributes += ssrAttribute(key.slice(5), value, true);\n } else if (key === \"defaultValue\" || key === \"defaultChecked\") {\n // The attributes of the same name in HTML are the defaults: `value` and `checked`.\n const name = key === \"defaultValue\" ? \"value\" : \"checked\";\n if (!Object.hasOwn(props, name))\n attributes += ssrAttribute(name, value, name === \"checked\");\n } else {\n const name = attributeName(key, svg);\n attributes += ssrAttribute(name, value, BOOLEAN_ATTRIBUTES.has(name));\n }\n }\n }\n if (classes.length > 0) attributes += ` class=\"${escapeHtml(classes.join(\" \"))}\"`;\n if (style !== \"\") attributes += ssrStyle(style);\n if (VOID_ELEMENTS.has(lowerTag)) return new SsrNode(`<${tag}${attributes}>`);\n // Like the DOM `spread`: a `children` prop supplies the content unless the element wrote its own.\n let content =\n innerHtml !== undefined\n ? innerHtml\n : escape(children === undefined ? propsChildren(props) : children);\n if (innerHtml === undefined && (hasValue || hasFallback)) {\n const value = hasValue ? control.value : control.fallback;\n content = isTextarea ? textareaContent(value) : markSelectedOptions(value, content);\n }\n return new SsrNode(`<${tag}${attributes}>${content}</${tag}>`);\n}\n\n/** The `children` of a spread props object (read once, so a getter runs once), or undefined. */\nfunction propsChildren(props: unknown): unknown {\n if (props === null || typeof props !== \"object\") return undefined;\n return Reflect.get(props, \"children\");\n}\n\n/** Class names whose key is truthy, from a `classList` object. */\nfunction collectTruthyKeys(value: unknown, out: string[]): void {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return;\n for (const key of Object.keys(value)) {\n if (key !== \"\" && resolveValue(Reflect.get(value, key))) out.push(key);\n }\n}\n\n/** Raw HTML text for `innerHTML`: null and undefined become \"\", an SsrNode its markup. */\nfunction plainHtml(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (isSsrNode(value)) return value.t;\n if (typeof value === \"symbol\")\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be innerHTML.\");\n return String(value);\n}\n"],"mappings":"A,shBAWA,MAAMA,EAAW,0BAGXC,kBAAqC,IAAI,IAAI,CACjD,OACA,OACA,KACA,MACA,UACA,QACA,KACA,MACA,QACA,SACA,OACA,OACA,QACA,SACA,QACA,KACF,CAAC,EAGKC,kBAAoC,IAAI,IAAI,CAChD,YACA,cACA,YACA,WACA,KACF,CAAC,EAGD,SAASC,EAAiB,EAAyB,CACjD,GAAsB,OAAOC,GAAU,UAAnCA,EACJ,OAAO,QAAQ,IAAIA,EAAO,QAAQ,CACpC,CAsBA,SAAgBC,EAAI,EAA0B,GAAGC,EAA2B,CAC1E,GAAI,CAAC,MAAM,QAAQC,CAAK,GAAKA,EAAM,SAAWD,EAAM,OAAS,EAC3D,MAAU,UAAU,6DAA6D,EAEnF,IAAIE,EAAOD,EAAM,IAAM,GACvB,IAAK,IAAIE,EAAQ,EAAGA,EAAQH,EAAM,OAAQ,GAAS,EAAG,CACpD,IAAMI,EAAOJ,EAAMG,GACnB,GAAI,OAAOC,GAAS,SAAU,GAAQA,OACjC,GAAIC,E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,GAAc,CACxD,IAAMtB,EAAQqB,EAAWD,EAAQ,MAAQA,EAAQ,SACjD,EAAUD,EAAa4B,EAAgB/C,CAAK,EAAIgD,EAAoBhD,EAAO2C,CAAO,CACpF,CACA,OAAO,IAAInC,EAAQ,IAAIO,IAAMQ,EAAW,GAAGoB,EAAQ,IAAI5B,EAAI,EAAE,CAC/D,CAGA,SAAS+B,EAAc,EAAyB,CAC9C,GAAsB,OAAOlB,GAAU,UAAnCA,EACJ,OAAO,QAAQ,IAAIA,EAAO,UAAU,CACtC,CAGA,SAASM,EAAkB,EAAgB,EAAqB,CAC9D,GAAsB,OAAOlC,GAAU,UAAnCA,GAA+C,OAAM,QAAQA,CAAK,EACtE,IAAK,IAAMW,KAAO,OAAO,KAAKX,CAAK,EAC7BW,IAAQ,IAAMoB,EAAa,QAAQ,IAAI/B,EAAOW,CAAG,CAAC,GAAGsC,EAAI,KAAKtC,CAAG,CAEzE,CAGA,SAASyB,EAAU,EAAwB,CACzC,GAAIpC,GAAU,KAA6B,MAAO,GAClD,GAAIO,EAAUP,CAAK,EAAG,OAAOA,EAAM,EACnC,GAAI,OAAOA,GAAU,SACnB,MAAMgB,EAAQ,4BAA6B,+BAA+B,EAC5E,OAAO,OAAOhB,CAAK,CACrB,C"}
|
|
1
|
+
{"version":3,"file":"element.js","names":["TAG_NAME","VOID_ELEMENTS","SKIPPED_KEYS","innerHtmlOfValue","value","ssr","holes","parts","html","index","hole","isSsrNode","SsrNode","ssrRaw","ssrHydrationKey","key","nextKey","escapeHtml","ssrElement","tag","invalid","lowerTag","isSelect","isTextarea","control","hasValue","hasFallback","attributes","needsKey","classes","style","innerHtml","props","IGNORED_KEYS","isEventName","resolveValue","text","classText","collectTruthyKeys","styleText","plainHtml","ssrAttribute","name","attributeName","svg","flag","BOOLEAN_ATTRIBUTES","ssrStyle","raw","given","children","propsChildren","content","rawElementContent","escape","textareaContent","markSelectedOptions","keepLeadingNewline","out"],"sources":["../../../src/server/element.ts"],"sourcesContent":["import { nextKey } from \"../internal/hydration-scope\";\nimport { attributeName, IGNORED_KEYS } from \"../internal/react-names\";\nimport { BOOLEAN_ATTRIBUTES, isEventName, ssrAttribute } from \"./attributes\";\nimport { classText, ssrStyle, styleText } from \"./class-style\";\nimport { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { keepLeadingNewline, markSelectedOptions, textareaContent } from \"./form-controls\";\nimport { isSsrNode, SsrNode } from \"./node\";\nimport { rawElementContent } from \"./raw-text\";\n\n/** A tag name: letters, digits and dashes, starting with a letter. Anything else could break out. */\nconst TAG_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;\n\n/** Elements that never have children or a closing tag. */\nconst VOID_ELEMENTS: ReadonlySet<string> = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"command\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"keygen\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\n/** Keys that never become attributes: they are handled elsewhere or would reach a prototype. */\nconst SKIPPED_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n \"children\",\n \"ref\",\n]);\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`): null and undefined are empty. */\nfunction innerHtmlOfValue(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return undefined;\n return Reflect.get(value, \"__html\");\n}\n\n/**\n * Joins the static parts of a server template with its dynamic holes into trusted markup: the\n * function compiled server output calls for each element tree. Holes are inserted unchanged, so each\n * must already be escaped (the output of `escape`, `ssrAttribute`, `ssrClass`, ...) or an `SsrNode`;\n * any other value throws, so a raw user value cannot reach the markup.\n *\n * @param parts The static markup, one more entry than there are holes.\n * @param holes The dynamic parts: strings produced by the escaping helpers, or `SsrNode` values.\n * @returns The markup as a trusted `SsrNode`, which `escape` writes without encoding.\n * @throws TypeError when `parts` is not an array of `holes.length + 1` entries, or when a hole is not\n * a string or an `SsrNode`.\n * @example\n * import { escape, renderToString, ssr } from \"@shadow-js/web/server\";\n *\n * const name = \"<Ada>\";\n * const html = renderToString(() => ssr([\"<p>Hello, \", \"</p>\"], escape(name)));\n * // \"<p>Hello, <Ada></p>\"\n * @see ssrRaw\n * @since 1.0.0\n */\nexport function ssr(parts: readonly string[], ...holes: unknown[]): SsrNode {\n if (!Array.isArray(parts) || parts.length !== holes.length + 1) {\n throw new TypeError(\"ssr(): parts must have one more entry than there are holes.\");\n }\n let html = parts[0] ?? \"\";\n for (let index = 0; index < holes.length; index += 1) {\n const hole = holes[index];\n if (typeof hole === \"string\") html += hole;\n else if (isSsrNode(hole)) html += hole.t;\n else throw new TypeError(\"ssr(): a hole must be an escaped string or an SsrNode.\");\n html += parts[index + 1] ?? \"\";\n }\n return new SsrNode(html);\n}\n\n/**\n * Marks a string as trusted markup that `escape` and `ssr` insert unchanged. Only use it for markup\n * the application wrote itself, never for user input.\n *\n * @param html The markup, inserted unchanged.\n * @returns The markup as a trusted `SsrNode`.\n * @throws TypeError when `html` is not a string.\n * @example\n * import { renderToString, ssrRaw } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => [\"<b>escaped</b>\", ssrRaw(\"<!-- build 42 -->\")]);\n * // \"<b>escaped</b><!-- build 42 -->\"\n * @see ssr\n * @since 1.0.0\n */\nexport function ssrRaw(html: string): SsrNode {\n if (typeof html !== \"string\") throw new TypeError(\"ssrRaw(): the markup must be a string.\");\n return new SsrNode(html);\n}\n\n/**\n * Draws the next hydration key of the current scope and returns it as a `data-hk` attribute, such as\n * `' data-hk=\"0-0\"'`: compiled server output calls it for the root element of each template, and\n * the client's `hydrate()` claims the element by that key. Calls must happen in the same order as on\n * the client, so call it only where the compiler would.\n *\n * @returns Markup for the `data-hk` attribute, or `\"\"` outside a server render (no key is drawn).\n * @example\n * import { renderToString, ssr, ssrHydrationKey } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => ssr([\"<div\", \">x</div>\"], ssrHydrationKey()));\n * // '<div data-hk=\"0-0\">x</div>'\n * @since 1.0.0\n */\nexport function ssrHydrationKey(): string {\n const key = nextKey();\n return key === undefined ? \"\" : ` data-hk=\"${escapeHtml(key)}\"`;\n}\n\n/**\n * Renders an element from a props object: what compiled server output calls for an element with a\n * spread (`<div {...props} />`), and the server half of `Dynamic` and `element`. It writes the same\n * markup the client's `spread` produces.\n *\n * `class`, `className`, `classList` and `style` are combined into one `class` and one `style`\n * attribute; other keys are attributes, with React names mapped (`htmlFor` is `for`) and HTML boolean\n * attributes (`disabled`, `checked`, ...) written as bare names. `ref`, `children`, `on*` keys and the\n * `on:`, `use:` and `prop:` prefixes are skipped; `attr:` and `bool:` select the attribute and presence\n * forms. `innerHTML` and `dangerouslySetInnerHTML` are written unescaped as the content. On a\n * `textarea` the `value` (or `defaultValue`) is the content; on a `select` it marks the matching\n * `<option selected>` (an array for `multiple`); on other elements `defaultValue` and `defaultChecked`\n * are the `value` and `checked` attributes. Void elements (`img`, `input`, ...) get no content.\n *\n * @param tag Element name: letters, digits and dashes, starting with a letter.\n * @param props The props object (each getter is read once), or `null`.\n * @param children The content, escaped unless it is an `SsrNode`. Undefined (the default) uses the\n * `children` prop.\n * @param needsKey `true` writes the hydration key of this template root first. Default: `false`.\n * @param svg `true` for an SVG element: SVG presentation names are hyphenated (`strokeWidth` is\n * `stroke-width`), other names keep their case. Default: `false`.\n * @returns The element as a trusted `SsrNode`.\n * @throws TypeError `INVALID_TAG_NAME` for an invalid tag, `INVALID_ATTRIBUTE_NAME` for an invalid\n * attribute name, and the errors of {@link ssrAttribute}, `ssrClass` and `ssrStyle` for invalid values.\n * @example\n * import { renderToString, ssrElement } from \"@shadow-js/web/server\";\n *\n * const props = { id: \"save\", disabled: true, class: [\"btn\", { primary: true }], children: \"Save\" };\n * const html = renderToString(() => ssrElement(\"button\", props));\n * // '<button id=\"save\" disabled class=\"btn primary\">Save</button>'\n * @since 1.0.0\n */\nexport function ssrElement(\n tag: string,\n props: unknown,\n children: unknown = undefined,\n needsKey = false,\n svg = false,\n): SsrNode {\n if (typeof tag !== \"string\" || !TAG_NAME.test(tag)) {\n throw invalid(\"INVALID_TAG_NAME\", `\"${String(tag)}\" is not a valid tag name.`);\n }\n const lowerTag = tag.toLowerCase();\n // A browser ignores `value` on these: a textarea's value is its content, a select's value is the\n // `selected` flag of its options. The props are read once and applied to the content below.\n const isSelect = lowerTag === \"select\";\n const isTextarea = lowerTag === \"textarea\";\n const control: { value?: unknown; fallback?: unknown } = {};\n let hasValue = false;\n let hasFallback = false;\n let attributes = needsKey ? ssrHydrationKey() : \"\";\n const classes: string[] = [];\n let style = \"\";\n let innerHtml: string | undefined;\n if (props !== null && typeof props === \"object\") {\n for (const key of Object.keys(props)) {\n if (SKIPPED_KEYS.has(key) || IGNORED_KEYS.has(key)) continue;\n if (\n key === \"ref\" ||\n key.startsWith(\"on:\") ||\n key.startsWith(\"use:\") ||\n key.startsWith(\"prop:\")\n )\n continue;\n if (isEventName(key)) continue;\n if (needsKey && key === \"data-hk\") continue;\n const value = resolveValue(Reflect.get(props, key));\n if (key === \"class\" || key === \"className\") {\n const text = classText(value);\n if (text !== \"\") classes.push(text);\n } else if (key === \"classList\") {\n collectTruthyKeys(value, classes);\n } else if (key === \"style\") {\n style = styleText(value);\n } else if (key === \"innerHTML\") {\n innerHtml = plainHtml(value);\n } else if (key === \"dangerouslySetInnerHTML\") {\n innerHtml = plainHtml(resolveValue(innerHtmlOfValue(value)));\n } else if ((isSelect || isTextarea) && key === \"value\") {\n control.value = value;\n hasValue = true;\n } else if ((isSelect || isTextarea) && key === \"defaultValue\") {\n control.fallback = value;\n hasFallback = true;\n } else if (key.startsWith(\"attr:\")) {\n attributes += ssrAttribute(key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n attributes += ssrAttribute(key.slice(5), value, true);\n } else if (key === \"defaultValue\" || key === \"defaultChecked\") {\n // The attributes of the same name in HTML are the defaults: `value` and `checked`.\n const name = key === \"defaultValue\" ? \"value\" : \"checked\";\n if (!Object.hasOwn(props, name))\n attributes += ssrAttribute(name, value, name === \"checked\");\n } else {\n const name = attributeName(key, svg);\n // `hidden=\"until-found\"` is a keyword, not a flag: a bare `hidden` would hide what it should only collapse.\n const flag =\n BOOLEAN_ATTRIBUTES.has(name) && !(name === \"hidden\" && value === \"until-found\");\n attributes += ssrAttribute(name, value, flag);\n }\n }\n }\n if (classes.length > 0) attributes += ` class=\"${escapeHtml(classes.join(\" \"))}\"`;\n if (style !== \"\") attributes += ssrStyle(style);\n if (VOID_ELEMENTS.has(lowerTag)) return new SsrNode(`<${tag}${attributes}>`);\n // Like the DOM `spread`: a `children` prop supplies the content unless the element wrote its own.\n // The text of a script or a style is raw (no entities), so it is written as it is and checked instead.\n const raw = !svg && (lowerTag === \"script\" || lowerTag === \"style\");\n const given = children === undefined ? propsChildren(props) : children;\n let content =\n innerHtml !== undefined ? innerHtml : raw ? rawElementContent(lowerTag, given) : escape(given);\n if (innerHtml === undefined && (hasValue || hasFallback)) {\n const value = hasValue ? control.value : control.fallback;\n content = isTextarea ? textareaContent(value) : markSelectedOptions(value, content);\n } else if (isTextarea && innerHtml === undefined) {\n // The children of a textarea are its value (as on the client): keep a first line break the parser drops.\n content = keepLeadingNewline(content);\n }\n return new SsrNode(`<${tag}${attributes}>${content}</${tag}>`);\n}\n\n/** The `children` of a spread props object (read once, so a getter runs once), or undefined. */\nfunction propsChildren(props: unknown): unknown {\n if (props === null || typeof props !== \"object\") return undefined;\n return Reflect.get(props, \"children\");\n}\n\n/** Class names whose key is truthy, from a `classList` object. */\nfunction collectTruthyKeys(value: unknown, out: string[]): void {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return;\n for (const key of Object.keys(value)) {\n if (key !== \"\" && resolveValue(Reflect.get(value, key))) out.push(key);\n }\n}\n\n/** Raw HTML text for `innerHTML`: null and undefined become \"\", an SsrNode its markup. */\nfunction plainHtml(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (isSsrNode(value)) return value.t;\n if (typeof value === \"symbol\")\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be innerHTML.\");\n return String(value);\n}\n"],"mappings":"A,gmBAYA,MAAMA,EAAW,0BAGXC,kBAAqC,IAAI,IAAI,CACjD,OACA,OACA,KACA,MACA,UACA,QACA,KACA,MACA,QACA,SACA,OACA,OACA,QACA,SACA,QACA,KACF,CAAC,EAGKC,kBAAoC,IAAI,IAAI,CAChD,YACA,cACA,YACA,WACA,KACF,CAAC,EAGD,SAASC,EAAiB,EAAyB,CACjD,GAAsB,OAAOC,GAAU,UAAnCA,EACJ,OAAO,QAAQ,IAAIA,EAAO,QAAQ,CACpC,CAsBA,SAAgBC,EAAI,EAA0B,GAAGC,EAA2B,CAC1E,GAAI,CAAC,MAAM,QAAQC,CAAK,GAAKA,EAAM,SAAWD,EAAM,OAAS,EAC3D,MAAU,UAAU,6DAA6D,EAEnF,IAAIE,EAAOD,EAAM,IAAM,GACvB,IAAK,IAAIE,EAAQ,EAAGA,EAAQH,EAAM,OAAQ,GAAS,EAAG,CACpD,IAAMI,EAAOJ,EAAMG,GACnB,GAAI,OAAOC,GAAS,SAAU,GAAQA,OACjC,GAAIC,EAAUD,CAAI,EAAG,GAAQA,EAAK,OAClC,MAAU,UAAU,wDAAwD,EACjF,GAAQH,EAAME,EAAQ,IAAM,EAC9B,CACA,OAAO,IAAIG,EAAQJ,CAAI,CACzB,CAiBA,SAAgBK,EAAO,EAAuB,CAC5C,GAAI,OAAOL,GAAS,SAAU,MAAU,UAAU,wCAAwC,EAC1F,OAAO,IAAII,EAAQJ,CAAI,CACzB,CAgBA,SAAgBM,GAA0B,CACxC,IAAMC,EAAMC,EAAQ,EACpB,OAAOD,IAAQ,IAAA,GAAY,GAAK,aAAaE,EAAWF,CAAG,EAAE,EAC/D,CAkCA,SAAgBG,EACd,EACA,EACA,EAAoB,IAAA,GACpB,EA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C/D,CAGA,SAASgC,EAAc,EAAyB,CAC9C,GAAsB,OAAOnB,GAAU,UAAnCA,EACJ,OAAO,QAAQ,IAAIA,EAAO,UAAU,CACtC,CAGA,SAASM,EAAkB,EAAgB,EAAqB,CAC9D,GAAsB,OAAOlC,GAAU,UAAnCA,GAA+C,OAAM,QAAQA,CAAK,EACtE,IAAK,IAAMW,KAAO,OAAO,KAAKX,CAAK,EAC7BW,IAAQ,IAAMoB,EAAa,QAAQ,IAAI/B,EAAOW,CAAG,CAAC,GAAG2C,EAAI,KAAK3C,CAAG,CAEzE,CAGA,SAASyB,EAAU,EAAwB,CACzC,GAAIpC,GAAU,KAA6B,MAAO,GAClD,GAAIO,EAAUP,CAAK,EAAG,OAAOA,EAAM,EACnC,GAAI,OAAOA,GAAU,SACnB,MAAMgB,EAAQ,4BAA6B,+BAA+B,EAC5E,OAAO,OAAOhB,CAAK,CACrB,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=class extends Error{code;constructor(e,t){super(`SHADOW_${e}`),this.name=`SsrError`,this.code=e}};function t(e,t){return/* @__PURE__ */ TypeError(`SHADOW_${e}`)}export{e as SsrError,t as invalid};
|
|
1
|
+
var e=class extends Error{code;constructor(e,t){super(`SHADOW_${e}`),this.name=`SsrError`,this.code=e}};function t(e,t){return/* @__PURE__ */ TypeError(`SHADOW_${e}`)}const n=2147483647;export{n as MAX_TIMER_MS,e as SsrError,t as invalid};
|
|
2
2
|
//# sourceMappingURL=errors.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":["SsrError","code","invalid"],"sources":["../../../src/server/errors.ts"],"sourcesContent":["/** Diagnostic codes raised by the server renderer. @internal */\nexport type SsrErrorCode = \"SSR_BOUNDARY_WATERFALL\" | \"SSR_PORTAL_LIMIT\" | \"SSR_TIMEOUT\";\n\n/**\n * Error thrown by the server renderer, carrying a stable code. Dev builds carry the full text;\n * production builds keep only the code (the same split as core's diagnostics).\n * @internal\n */\nexport class SsrError extends Error {\n readonly code: SsrErrorCode;\n constructor(code: SsrErrorCode, detail: string) {\n super(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n this.name = \"SsrError\";\n this.code = code;\n }\n}\n\n/**\n * A TypeError for input the renderer refuses: a value that could become unsafe markup, or a\n * malformed argument. Dev builds carry the detail; production builds keep the code.\n * @internal\n */\nexport function invalid(code: string, detail: string): TypeError {\n return new TypeError(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n}\n"],"mappings":"AAQA,IAAaA,EAAb,cAA8B,KAAM,CAClC,KACA,YAAY,EAAoB,EAAgB,CAC9C,MAA+C,UAAUC,GAAM,EAC/D,KAAK,KAAO,WACZ,KAAK,KAAOA,CACd,CACF,EAOA,SAAgBC,EAAQ,EAAc,EAA2B,CAC/D,MAAO,gBAAI,UAAmD,UAAUD,GAAM,CAChF,
|
|
1
|
+
{"version":3,"file":"errors.js","names":["SsrError","code","invalid","MAX_TIMER_MS"],"sources":["../../../src/server/errors.ts"],"sourcesContent":["/** Diagnostic codes raised by the server renderer. @internal */\nexport type SsrErrorCode = \"SSR_BOUNDARY_WATERFALL\" | \"SSR_PORTAL_LIMIT\" | \"SSR_TIMEOUT\";\n\n/**\n * Error thrown by the server renderer, carrying a stable code. Dev builds carry the full text;\n * production builds keep only the code (the same split as core's diagnostics).\n * @internal\n */\nexport class SsrError extends Error {\n readonly code: SsrErrorCode;\n constructor(code: SsrErrorCode, detail: string) {\n super(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n this.name = \"SsrError\";\n this.code = code;\n }\n}\n\n/**\n * A TypeError for input the renderer refuses: a value that could become unsafe markup, or a\n * malformed argument. Dev builds carry the detail; production builds keep the code.\n * @internal\n */\nexport function invalid(code: string, detail: string): TypeError {\n return new TypeError(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n}\n\n/**\n * The longest delay `setTimeout` honors: larger values fire after one millisecond. A budget above it\n * (`Number.MAX_SAFE_INTEGER` for \"no limit\") is clamped here instead of ending every render at once.\n * @internal\n */\nexport const MAX_TIMER_MS = 2_147_483_647;\n"],"mappings":"AAQA,IAAaA,EAAb,cAA8B,KAAM,CAClC,KACA,YAAY,EAAoB,EAAgB,CAC9C,MAA+C,UAAUC,GAAM,EAC/D,KAAK,KAAO,WACZ,KAAK,KAAOA,CACd,CACF,EAOA,SAAgBC,EAAQ,EAAc,EAA2B,CAC/D,MAAO,gBAAI,UAAmD,UAAUD,GAAM,CAChF,CAOA,MAAaE,EAAe,W"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{invalid as e}from"./errors.js";import{isSsrNode as t}from"./node.js";import{untrack as n}from"@shadow-js/core";const r={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},i=/[&<>"']/g;function a(e){return e.replace(i,e=>r[e]??e)}function o(e){let t=e;for(let e=0;typeof t==`function`;e+=1){if(e>=1e3)throw TypeError(`An accessor returns accessors more than 1000 levels deep.`);t=n(t)}return t}function s(n,r){if(n!=null&&typeof n!=`boolean`){if(typeof n==`string`)r.push(
|
|
1
|
+
import{invalid as e}from"./errors.js";import{isSsrNode as t}from"./node.js";import{untrack as n}from"@shadow-js/core";const r={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},i=/[&<>"']/g;function a(e){return e.replace(i,e=>r[e]??e)}function o(e){let t=e;for(let e=0;typeof t==`function`;e+=1){if(e>=1e3)throw TypeError(`An accessor returns accessors more than 1000 levels deep.`);t=n(t)}return t}function s(n,r,i){if(n!=null&&typeof n!=`boolean`){if(typeof n==`string`)r.push(i(n));else if(typeof n==`number`||typeof n==`bigint`)r.push(String(n));else{if(typeof n==`symbol`)throw e(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be rendered.`);t(n)?r.push(n.t):typeof n!=`object`&&r.push(i(String(n)))}}}function c(e){return l(e,a)}function l(e,t){let n=[],r=[],i=[],a=/* @__PURE__ */ new Set,c=e;for(;;){let e=o(c);if(Array.isArray(e)){if(a.has(e))throw TypeError(`escape(): an array contains itself.`);a.add(e),r.push(e),i.push(0)}else s(e,n,t);let l,u=!1;for(;!u&&r.length>0;){let e=r.length-1,t=r[e],n=i[e]??0;if(t===void 0)break;n<t.length?(i[e]=n+1,l=t[n],u=!0):(r.pop(),i.pop(),a.delete(t))}if(!u)return n.join(``);c=l}}export{c as escape,a as escapeHtml,l as render,o as resolveValue};
|
|
2
2
|
//# sourceMappingURL=escape.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"escape.js","names":["accessor","HTML_ESCAPES","HTML_SPECIAL","escapeHtml","text","char","resolveValue","current","value","layer","untrack","appendLeaf","out","invalid","isSsrNode","escape","frames","cursors","open","item","resolved","next","found","top","frame","cursor"],"sources":["../../../src/server/escape.ts"],"sourcesContent":["import { untrack } from \"@shadow-js/core\";\nimport { invalid } from \"./errors\";\nimport { isSsrNode } from \"./node\";\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = {\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\n};\n\nconst HTML_SPECIAL = /[&<>\"']/g;\n\n/** Longest chain of accessors that returns accessors; longer chains are a bug in user code. */\nconst MAX_ACCESSOR_LAYERS = 1000;\n\n/**\n * Escapes the five HTML-significant characters. Escaping `&` too means entity-looking text is\n * written literally, and the result is safe in text and in quoted attribute values alike.\n * @internal\n */\nexport function escapeHtml(text: string): string {\n return text.replace(HTML_SPECIAL, (char) => HTML_ESCAPES[char] ?? char);\n}\n\n/**\n * Calls accessors until a plain value remains. Accessors run untracked; a chain longer than\n * {@link MAX_ACCESSOR_LAYERS} throws instead of looping.\n * @internal\n */\nexport function resolveValue(value: unknown): unknown {\n let current = value;\n for (let layer = 0; typeof current === \"function\"; layer += 1) {\n if (layer >= MAX_ACCESSOR_LAYERS) {\n throw new TypeError(\"An accessor returns accessors more than 1000 levels deep.\");\n }\n const accessor = current as () => unknown;\n current = untrack(accessor);\n }\n return current;\n}\n\n/** Writes the markup for one resolved value that is not an array. */\nfunction appendLeaf(value: unknown, out: string[]): void {\n if (value === null || value === undefined || typeof value === \"boolean\") return;\n if (typeof value === \"string\") {\n out.push(
|
|
1
|
+
{"version":3,"file":"escape.js","names":["accessor","HTML_ESCAPES","HTML_SPECIAL","escapeHtml","text","char","resolveValue","current","value","layer","untrack","appendLeaf","out","invalid","isSsrNode","escape","render","frames","cursors","open","item","resolved","next","found","top","frame","cursor"],"sources":["../../../src/server/escape.ts"],"sourcesContent":["import { untrack } from \"@shadow-js/core\";\nimport { invalid } from \"./errors\";\nimport { isSsrNode } from \"./node\";\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = {\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\n};\n\nconst HTML_SPECIAL = /[&<>\"']/g;\n\n/** Longest chain of accessors that returns accessors; longer chains are a bug in user code. */\nconst MAX_ACCESSOR_LAYERS = 1000;\n\n/**\n * Escapes the five HTML-significant characters. Escaping `&` too means entity-looking text is\n * written literally, and the result is safe in text and in quoted attribute values alike.\n * @internal\n */\nexport function escapeHtml(text: string): string {\n return text.replace(HTML_SPECIAL, (char) => HTML_ESCAPES[char] ?? char);\n}\n\n/**\n * Calls accessors until a plain value remains. Accessors run untracked; a chain longer than\n * {@link MAX_ACCESSOR_LAYERS} throws instead of looping.\n * @internal\n */\nexport function resolveValue(value: unknown): unknown {\n let current = value;\n for (let layer = 0; typeof current === \"function\"; layer += 1) {\n if (layer >= MAX_ACCESSOR_LAYERS) {\n throw new TypeError(\"An accessor returns accessors more than 1000 levels deep.\");\n }\n const accessor = current as () => unknown;\n current = untrack(accessor);\n }\n return current;\n}\n\n/** Writes the markup for one resolved value that is not an array; `text` encodes the text of a string. */\nfunction appendLeaf(value: unknown, out: string[], text: (value: string) => string): void {\n if (value === null || value === undefined || typeof value === \"boolean\") return;\n if (typeof value === \"string\") {\n out.push(text(value));\n return;\n }\n // Numbers and bigints never contain markup characters.\n if (typeof value === \"number\" || typeof value === \"bigint\") {\n out.push(String(value));\n return;\n }\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be rendered.\");\n }\n if (isSsrNode(value)) {\n out.push(value.t);\n return;\n }\n // Any other object is not trusted markup. Dev fails loudly; production renders nothing.\n if (typeof value === \"object\") {\n if (__DEV__) {\n throw invalid(\n \"UNRECOGNIZED_INSERT_VALUE\",\n \"A plain object cannot be rendered. Use a string, a number, an array or an SsrNode.\",\n );\n }\n return;\n }\n out.push(text(String(value)));\n}\n\n/**\n * Converts any value a JSX child may hold to escaped HTML: the helper compiled server output calls\n * for every dynamic child, and what the renderers call on the app's result.\n *\n * - Strings are escaped (`& < > \" '`); numbers and bigints are written as they are; `null`,\n * `undefined` and booleans render nothing.\n * - `SsrNode` values (from `ssr`, `ssrRaw` and the other helpers) pass through unchanged: they were\n * escaped when they were built.\n * - Accessors are called (untracked) and their result is rendered; a chain of more than 1000\n * accessors returning accessors throws.\n * - Arrays are flattened in order, with an explicit stack, so nesting depth is not limited by the\n * call stack.\n * - Plain objects throw in development builds and render nothing in production builds.\n *\n * @param value The value to render.\n * @returns The escaped markup.\n * @throws TypeError when an array contains itself, for a symbol (`UNRECOGNIZED_INSERT_VALUE`), for an\n * object that is not an `SsrNode` (`UNRECOGNIZED_INSERT_VALUE`, development builds only), and for an\n * accessor chain deeper than 1000.\n * @example\n * import { escape } from \"@shadow-js/web/server\";\n *\n * const name = () => \"<Ada>\";\n * escape([\"Hello, \", name, null, 3]); // \"Hello, <Ada>3\"\n * @since 1.0.0\n */\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nexport function escape(value: unknown): string {\n return render(value, escapeHtml);\n}\n\n/**\n * {@link escape} with the encoding of strings left to the caller: the walk over accessors, arrays and\n * trusted nodes that every kind of text shares (an element's text is encoded one way, a script's another).\n * @internal\n */\nexport function render(value: unknown, text: (value: string) => string): string {\n const out: string[] = [];\n const frames: unknown[][] = [];\n const cursors: number[] = [];\n const open = new Set<unknown[]>();\n let item: unknown = value;\n for (;;) {\n const resolved = resolveValue(item);\n if (Array.isArray(resolved)) {\n if (open.has(resolved)) throw new TypeError(\"escape(): an array contains itself.\");\n open.add(resolved);\n frames.push(resolved);\n cursors.push(0);\n } else {\n appendLeaf(resolved, out, text);\n }\n // Find the next item, closing every array that has no items left.\n let next: unknown;\n let found = false;\n while (!found && frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined) break;\n if (cursor < frame.length) {\n cursors[top] = cursor + 1;\n next = frame[cursor];\n found = true;\n } else {\n frames.pop();\n cursors.pop();\n open.delete(frame);\n }\n }\n if (!found) return out.join(\"\");\n item = next;\n }\n}\n"],"mappings":"A,sHAIA,MAAMC,EAAiD,CACrD,IAAK,QACL,IAAK,OACL,IAAK,OACL,IAAK,SACL,IAAK,OACP,EAEMC,EAAe,WAUrB,SAAgBC,EAAW,EAAsB,CAC/C,OAAOC,EAAK,QAAQF,EAAe,GAASD,EAAaI,IAASA,CAAI,CACxE,CAOA,SAAgBC,EAAa,EAAyB,CACpD,IAAIC,EAAUC,EACd,IAAK,IAAIC,EAAQ,EAAG,OAAOF,GAAY,WAAY,GAAS,EAAG,CAC7D,GAAIE,GAAS,IACX,MAAU,UAAU,2DAA2D,EAGjF,EAAUC,EAAQV,CAAQ,CAC5B,CACA,OAAOO,CACT,CAGA,SAASI,EAAW,EAAgB,EAAe,EAAuC,CACxF,GAAIH,GAAU,MAA+B,OAAOA,GAAU,UAC9D,IAAI,OAAOA,GAAU,SACnBI,EAAI,KAAKR,EAAKI,CAAK,CAAC,OAItB,GAAI,OAAOA,GAAU,UAAY,OAAOA,GAAU,SAChDI,EAAI,KAAK,OAAOJ,CAAK,CAAC,MAGxB,IAAI,OAAOA,GAAU,SACnB,MAAMK,EAAQ,4BAA6B,8BAA8B,EAEvEC,EAAUN,CAAK,EACjBI,EAAI,KAAKJ,EAAM,CAAC,EAId,OAAOA,GAAU,UASrBI,EAAI,KAAKR,EAAK,OAAOI,CAAK,CAAC,CAAC,CAhB+C,CAP3E,CAwBF,CA6BA,SAAgBO,EAAO,EAAwB,CAC7C,OAAOC,EAAOR,EAAOL,CAAU,CACjC,CAOA,SAAgBa,EAAO,EAAgB,EAAyC,CAC9E,IAAMJ,EAAgB,CAAC,EACjBK,EAAsB,CAAC,EACvBC,EAAoB,CAAC,EACrBC,kBAAO,IAAI,IACbC,EAAgBZ,EACpB,OAAS,CACP,IAAMa,EAAWf,EAAac,CAAI,EAClC,GAAI,MAAM,QAAQC,CAAQ,EAAG,CAC3B,GAAIF,EAAK,IAAIE,CAAQ,EAAG,MAAU,UAAU,qCAAqC,EACjFF,EAAK,IAAIE,CAAQ,EACjBJ,EAAO,KAAKI,CAAQ,EACpBH,EAAQ,KAAK,CAAC,CAChB,MACEP,EAAWU,EAAUT,EAAKR,CAAI,EAGhC,IAAIkB,EACAC,EAAQ,GACZ,KAAO,CAACA,GAASN,EAAO,OAAS,GAAG,CAClC,IAAMO,EAAMP,EAAO,OAAS,EACtBQ,EAAQR,EAAOO,GACfE,EAASR,EAAQM,IAAQ,EAC/B,GAAIC,IAAU,IAAA,GAAW,MACrBC,EAASD,EAAM,QACjB,EAAQD,GAAOE,EAAS,EACxB,EAAOD,EAAMC,GACb,EAAQ,KAERT,EAAO,IAAI,EACXC,EAAQ,IAAI,EACZC,EAAK,OAAOM,CAAK,EAErB,CACA,GAAI,CAACF,EAAO,OAAOX,EAAI,KAAK,EAAE,EAC9B,EAAOU,CACT,CACF,C"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{invalid as e}from"./errors.js";import{SsrNode as t}from"./node.js";import{escape as n,escapeHtml as r,resolveValue as i}from"./escape.js";function a(t){if(typeof t==`symbol`)throw e(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a form control value.`);return t==null?``:String(t)}function o(e){
|
|
2
|
-
`||
|
|
1
|
+
import{invalid as e}from"./errors.js";import{SsrNode as t}from"./node.js";import{escape as n,escapeHtml as r,resolveValue as i}from"./escape.js";function a(t){if(typeof t==`symbol`)throw e(`UNRECOGNIZED_INSERT_VALUE`,`A symbol cannot be a form control value.`);return t==null?``:String(t)}function o(e){return s(r(a(i(e))))}function s(e){let t=e.charAt(0);return t===`
|
|
2
|
+
`||t===`\r`?`\n${e}`:e}function c(e){return new t(o(e))}function l(e){let t=i(e);if(!Array.isArray(t))return{values:/* @__PURE__ */ new Set([a(t)]),many:!1};let n=/* @__PURE__ */ new Set;for(let e of t){let t=i(e);t!=null&&n.add(a(t))}return{values:n,many:!0}}const u=/[ \t\n\f\r]+/g,d=/&(?:#(\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi,f={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:`\xA0`},p=/<!--[\s\S]*?-->|<[^>]*>/g;function m(e){return e.replace(d,(e,t,n,r)=>{if(r!==void 0)return f[r.toLowerCase()]??e;let i=t===void 0?Number.parseInt(n??``,16):Number(t);return Number.isInteger(i)&&i>=0&&i<=1114111&&!(i>=55296&&i<=57343)?String.fromCodePoint(i):e})}function h(e,t){let n=``;for(let r=t;r<e.length;r+=1){let t=e.charAt(r);if(n!==``)t===n&&(n=``);else if(t===`"`||t===`'`)n=t;else if(t===`>`)return r}return-1}function g(e,t,n){n.lastIndex=t;let r=n.exec(e);return m(e.slice(t,r===null?e.length:r.index).replace(p,``)).replace(u,` `).trim()}function _(e,t){let n=``,r=0,i=0,a=!1,o=/* @__PURE__ */ RegExp(`\\s+([^\\s"'<>/=]+)(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\`]+)))?`,`g`),s=/* @__PURE__ */ RegExp(`<\\/?(?:option|optgroup)(?=[\\s/>])`,`gi`);for(;;){let c=e.indexOf(`<option`,i);if(c===-1)break;let l=c+7;if(i=l,!/[\s/>]/.test(e.charAt(l)))continue;let u=h(e,l);if(u===-1)break;let d=e.slice(l,u),f,p=-1,_=-1;o.lastIndex=0;for(let e=o.exec(d);e!==null;e=o.exec(d)){let t=(e[1]??``).toLowerCase();t===`selected`?(p=e.index,_=e.index+e[0].length):t===`value`&&f===void 0&&(f=m(e[2]??e[3]??e[4]??``))}let v=(t.many||!a)&&t.values.has(f??g(e,u+1,s));if(v&&(a=!0),v&&p===-1){let t=d.endsWith(`/`)?d.length-1:d.length;n+=`${e.slice(r,l+t)} selected`,r=l+t}else!v&&p!==-1&&(n+=e.slice(r,l+p),r=l+_);i=u}return r===0?e:n+e.slice(r)}function v(e,r){return new t(y(e,n(r)))}function y(e,t){return _(t,l(e))}export{s as keepLeadingNewline,y as markSelectedOptions,v as ssrSelectValue,c as ssrTextArea,o as textareaContent};
|
|
3
3
|
//# sourceMappingURL=form-controls.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"form-controls.js","names":["valueText","value","invalid","textareaContent","html","escapeHtml","resolveValue","first","ssrTextArea","SsrNode","wantedValues","resolved","values","item","one","WHITESPACE","ENTITY","NAMED_ENTITIES","TAGS","decodeEntities","text","named","whole","code","decimal","hex","tagEnd","quote","index","from","char","optionText","boundary","boundaries","markOptions","out","copied","at","found","attribute","start","attributesFrom","end","source","selectedAt","selectedEnd","match","name","matches","wanted","slash","ssrSelectValue","markSelectedOptions","escape","children"],"sources":["../../../src/server/form-controls.ts"],"sourcesContent":["import { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { SsrNode } from \"./node\";\n\n/**\n * Server markup for the controls whose state is not an attribute. A browser ignores `value` on a\n * `<textarea>` and on a `<select>`: the textarea's text is its content, and the select's value is\n * the `selected` flag of its options. These helpers write that markup, so the server HTML shows the\n * same state the client sets and a form posted without JavaScript sends it.\n */\n\n/** Text of a value for a textarea: null and undefined are empty, everything else is its string. */\nfunction valueText(value: unknown): string {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be a form control value.\");\n }\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Markup of a textarea's content. The HTML parser drops one newline directly after `<textarea>`,\n * so a value that starts with a line break gets one more; its content is then exactly the value.\n * @internal\n */\nexport function textareaContent(value: unknown): string {\n const html = escapeHtml(valueText(resolveValue(value)));\n const first = html.charAt(0);\n return first === \"\\n\" || first === \"\\r\" ? `\\n${html}` : html;\n}\n\n/**\n * Renders the content of a `<textarea>` from its value: the helper compiled server output calls for\n * `<textarea value={...}>` and `defaultValue`, since a browser ignores a `value` attribute on a\n * textarea. The text is escaped, and a value that starts with a line break gets one more, because\n * the HTML parser drops the first one.\n *\n * @param value The value, or an accessor of it. `null` and `undefined` give an empty textarea;\n * anything else is written as `String(value)`.\n * @returns The escaped content as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol.\n * @example\n * import { renderToString, ssr, ssrTextArea } from \"@shadow-js/web/server\";\n *\n * const bio = \"Loves <b>tags</b>\";\n * const html = renderToString(() => ssr([\"<textarea>\", \"</textarea>\"], ssrTextArea(bio)));\n * // \"<textarea>Loves <b>tags</b></textarea>\"\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function ssrTextArea(value: unknown): SsrNode {\n return new SsrNode(textareaContent(value));\n}\n\n/** The values a select value stands for: an array lists them (`multiple`), anything else is one. */\nfunction wantedValues(value: unknown): { values: Set<string>; many: boolean } {\n const resolved = resolveValue(value);\n if (!Array.isArray(resolved)) return { values: new Set([valueText(resolved)]), many: false };\n const values = new Set<string>();\n for (const item of resolved) {\n const one = resolveValue(item);\n if (one !== null && one !== undefined) values.add(valueText(one));\n }\n return { values, many: true };\n}\n\n/** Characters of the HTML spec's \"ASCII whitespace\". */\nconst WHITESPACE = /[ \\t\\n\\f\\r]+/g;\n/** Entities our own escaping writes, plus numeric references and ` ` from trusted raw markup. */\nconst ENTITY = /&(?:#(\\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi;\nconst NAMED_ENTITIES: Readonly<Record<string, string>> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n};\n/** Comments and tags inside an option's text (the region markers the compiler writes). */\nconst TAGS = /<!--[\\s\\S]*?-->|<[^>]*>/g;\n/**\n * The next option or optgroup tag, start or end: where an option's text ends. Sources of global\n * expressions, built per call so no `lastIndex` outlives it.\n */\nconst OPTION_BOUNDARY = \"<\\\\/?(?:option|optgroup)(?=[\\\\s/>])\";\n/** One attribute of a start tag: name, then an optional quoted or bare value. */\nconst ATTRIBUTE = \"\\\\s+([^\\\\s\\\"'<>/=]+)(?:\\\\s*=\\\\s*(?:\\\"([^\\\"]*)\\\"|'([^']*)'|([^\\\\s\\\"'=<>`]+)))?\";\n\nfunction decodeEntities(text: string): string {\n return text.replace(ENTITY, (whole, decimal?: string, hex?: string, named?: string) => {\n if (named !== undefined) return NAMED_ENTITIES[named.toLowerCase()] ?? whole;\n const code = decimal !== undefined ? Number(decimal) : Number.parseInt(hex ?? \"\", 16);\n return Number.isInteger(code) &&\n code >= 0 &&\n code <= 0x10ffff &&\n !(code >= 0xd800 && code <= 0xdfff)\n ? String.fromCodePoint(code)\n : whole;\n });\n}\n\n/** Index of the `>` that ends the start tag whose attributes begin at `from`, or -1. Quotes are skipped. */\nfunction tagEnd(html: string, from: number): number {\n let quote = \"\";\n for (let index = from; index < html.length; index += 1) {\n const char = html.charAt(index);\n if (quote !== \"\") {\n if (char === quote) quote = \"\";\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === \">\") {\n return index;\n }\n }\n return -1;\n}\n\n/** The text an option without a `value` attribute stands for: its text content, whitespace collapsed. */\nfunction optionText(html: string, from: number, boundaries: RegExp): string {\n boundaries.lastIndex = from;\n const boundary = boundaries.exec(html);\n const raw = html.slice(from, boundary === null ? html.length : boundary.index);\n return decodeEntities(raw.replace(TAGS, \"\")).replace(WHITESPACE, \" \").trim();\n}\n\n/**\n * Rewrites the option start tags of `html` so that exactly the wanted ones carry `selected`. The\n * input is markup this runtime produced (text and attribute values are escaped, so `<option` is\n * always a tag); only the `selected` attribute is added or removed, and nothing from the wanted\n * values is ever written.\n */\nfunction markOptions(html: string, wanted: { values: Set<string>; many: boolean }): string {\n let out = \"\";\n let copied = 0;\n let at = 0;\n let found = false;\n const attribute = new RegExp(ATTRIBUTE, \"g\");\n const boundaries = new RegExp(OPTION_BOUNDARY, \"gi\");\n for (;;) {\n const start = html.indexOf(\"<option\", at);\n if (start === -1) break;\n const attributesFrom = start + 7;\n at = attributesFrom;\n if (!/[\\s/>]/.test(html.charAt(attributesFrom))) continue;\n const end = tagEnd(html, attributesFrom);\n if (end === -1) break;\n const source = html.slice(attributesFrom, end);\n let value: string | undefined;\n let selectedAt = -1;\n let selectedEnd = -1;\n attribute.lastIndex = 0;\n for (let match = attribute.exec(source); match !== null; match = attribute.exec(source)) {\n const name = (match[1] ?? \"\").toLowerCase();\n if (name === \"selected\") {\n selectedAt = match.index;\n selectedEnd = match.index + match[0].length;\n } else if (name === \"value\" && value === undefined) {\n value = decodeEntities(match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n }\n // A scalar behaves like `select.value = x`: the first option with that value wins.\n const matches =\n (wanted.many || !found) && wanted.values.has(value ?? optionText(html, end + 1, boundaries));\n if (matches) found = true;\n if (matches && selectedAt === -1) {\n const slash = source.endsWith(\"/\") ? source.length - 1 : source.length;\n out += `${html.slice(copied, attributesFrom + slash)} selected`;\n copied = attributesFrom + slash;\n } else if (!matches && selectedAt !== -1) {\n out += html.slice(copied, attributesFrom + selectedAt);\n copied = attributesFrom + selectedEnd;\n }\n at = end;\n }\n return copied === 0 ? html : out + html.slice(copied);\n}\n\n/**\n * The options of a `<select>` with the ones its value stands for marked `selected`. A browser\n * ignores a `value` attribute on `<select>`, so the server flags the options instead: the option\n * whose `value` attribute equals the value (or, with no such attribute, whose text does) is\n * selected, and every other option loses `selected`. An array selects every listed option, for\n * `<select multiple>`; a single value selects the first match, like `select.value = x`. `null`\n * and `undefined` stand for the empty string. Options inside `<optgroup>`, control flow and\n * components are found because the search runs on the serialized children. Values are compared,\n * never written, so they cannot add markup.\n *\n * @param value The select's `value`, or an accessor of it. Entries of an array are compared as\n * strings; `null` and `undefined` entries are skipped.\n * @param children The select's children (an `SsrNode`, or anything `escape` accepts).\n * @returns The children with the `selected` flags set, as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol, and the errors of\n * {@link escape} for the children.\n * @example\n * import { renderToString, ssr, ssrRaw, ssrSelectValue } from \"@shadow-js/web/server\";\n *\n * const options = ssrRaw(`<option value=\"red\">Red</option><option value=\"blue\">Blue</option>`);\n * const html = renderToString(() => ssr([\"<select>\", \"</select>\"], ssrSelectValue(\"blue\", options)));\n * // '<select><option value=\"red\">Red</option><option value=\"blue\" selected>Blue</option></select>'\n * @see setSelectValue\n * @since 1.0.0\n */\nexport function ssrSelectValue(value: unknown, children: unknown): SsrNode {\n return new SsrNode(markSelectedOptions(value, escape(children)));\n}\n\n/** {@link ssrSelectValue} on markup that is already escaped. @internal */\nexport function markSelectedOptions(value: unknown, html: string): string {\n return markOptions(html, wantedValues(value));\n}\n"],"mappings":"A,iJAaA,SAASA,EAAU,EAAwB,CACzC,GAAI,OAAOC,GAAU,SACnB,MAAMC,EAAQ,4BAA6B,0CAA0C,EAEvF,OAAOD,GAAU,KAA8B,GAAK,OAAOA,CAAK,CAClE,CAOA,SAAgBE,EAAgB,EAAwB,CACtD,IAAMC,EAAOC,EAAWL,EAAUM,EAAaL,CAAK,CAAC,CAAC,EAChDM,EAAQH,EAAK,OAAO,CAAC,EAC3B,OAAOG,IAAU;GAAQA,IAAU,KAAO,KAAKH,IAASA,CAC1D,CAqBA,SAAgBI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UW,EAAO,OAAO,IAAIhD,GAAS8B,EAAW3B,EAAMsC,EAAM,EAAGT,CAAU,CAAC,EAE7F,GADIe,IAAS,EAAQ,IACjBA,GAAWJ,IAAe,GAAI,CAChC,IAAMM,EAAQP,EAAO,SAAS,GAAG,EAAIA,EAAO,OAAS,EAAIA,EAAO,OAChE,GAAO,GAAGvC,EAAK,MAAMgC,EAAQK,EAAiBS,CAAK,EAAE,WACrD,EAAST,EAAiBS,CAC5B,KAAW,CAACF,GAAWJ,IAAe,KACpC,GAAOxC,EAAK,MAAMgC,EAAQK,EAAiBG,CAAU,EACrD,EAASH,EAAiBI,GAE5B,EAAKH,CACP,CACA,OAAON,IAAW,EAAIhC,EAAO+B,EAAM/B,EAAK,MAAMgC,CAAM,CACtD,CA2BA,SAAgBe,EAAe,EAAgB,EAA4B,CACzE,OAAO,IAAI1C,EAAQ2C,EAAoBnD,EAAOoD,EAAOC,CAAQ,CAAC,CAAC,CACjE,CAGA,SAAgBF,EAAoB,EAAgB,EAAsB,CACxE,OAAOlB,EAAY9B,EAAMM,EAAaT,CAAK,CAAC,CAC9C,C"}
|
|
1
|
+
{"version":3,"file":"form-controls.js","names":["valueText","value","invalid","textareaContent","keepLeadingNewline","escapeHtml","resolveValue","first","html","ssrTextArea","SsrNode","wantedValues","resolved","values","item","one","WHITESPACE","ENTITY","NAMED_ENTITIES","TAGS","decodeEntities","text","named","whole","code","decimal","hex","tagEnd","quote","index","from","char","optionText","boundary","boundaries","markOptions","out","copied","at","found","attribute","start","attributesFrom","end","source","selectedAt","selectedEnd","match","name","matches","wanted","slash","ssrSelectValue","markSelectedOptions","escape","children"],"sources":["../../../src/server/form-controls.ts"],"sourcesContent":["import { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { SsrNode } from \"./node\";\n\n/**\n * Server markup for the controls whose state is not an attribute. A browser ignores `value` on a\n * `<textarea>` and on a `<select>`: the textarea's text is its content, and the select's value is\n * the `selected` flag of its options. These helpers write that markup, so the server HTML shows the\n * same state the client sets and a form posted without JavaScript sends it.\n */\n\n/** Text of a value for a textarea: null and undefined are empty, everything else is its string. */\nfunction valueText(value: unknown): string {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be a form control value.\");\n }\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Markup of a textarea's content. The HTML parser drops one newline directly after `<textarea>`,\n * so a value that starts with a line break gets one more; its content is then exactly the value.\n * @internal\n */\nexport function textareaContent(value: unknown): string {\n return keepLeadingNewline(escapeHtml(valueText(resolveValue(value))));\n}\n\n/** Content markup of a textarea with the line break its parser would drop kept. @internal */\nexport function keepLeadingNewline(html: string): string {\n const first = html.charAt(0);\n return first === \"\\n\" || first === \"\\r\" ? `\\n${html}` : html;\n}\n\n/**\n * Renders the content of a `<textarea>` from its value: the helper compiled server output calls for\n * `<textarea value={...}>` and `defaultValue`, since a browser ignores a `value` attribute on a\n * textarea. The text is escaped, and a value that starts with a line break gets one more, because\n * the HTML parser drops the first one.\n *\n * @param value The value, or an accessor of it. `null` and `undefined` give an empty textarea;\n * anything else is written as `String(value)`.\n * @returns The escaped content as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol.\n * @example\n * import { renderToString, ssr, ssrTextArea } from \"@shadow-js/web/server\";\n *\n * const bio = \"Loves <b>tags</b>\";\n * const html = renderToString(() => ssr([\"<textarea>\", \"</textarea>\"], ssrTextArea(bio)));\n * // \"<textarea>Loves <b>tags</b></textarea>\"\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function ssrTextArea(value: unknown): SsrNode {\n return new SsrNode(textareaContent(value));\n}\n\n/** The values a select value stands for: an array lists them (`multiple`), anything else is one. */\nfunction wantedValues(value: unknown): { values: Set<string>; many: boolean } {\n const resolved = resolveValue(value);\n if (!Array.isArray(resolved)) return { values: new Set([valueText(resolved)]), many: false };\n const values = new Set<string>();\n for (const item of resolved) {\n const one = resolveValue(item);\n if (one !== null && one !== undefined) values.add(valueText(one));\n }\n return { values, many: true };\n}\n\n/** Characters of the HTML spec's \"ASCII whitespace\". */\nconst WHITESPACE = /[ \\t\\n\\f\\r]+/g;\n/** Entities our own escaping writes, plus numeric references and ` ` from trusted raw markup. */\nconst ENTITY = /&(?:#(\\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi;\nconst NAMED_ENTITIES: Readonly<Record<string, string>> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n};\n/** Comments and tags inside an option's text (the region markers the compiler writes). */\nconst TAGS = /<!--[\\s\\S]*?-->|<[^>]*>/g;\n/**\n * The next option or optgroup tag, start or end: where an option's text ends. Sources of global\n * expressions, built per call so no `lastIndex` outlives it.\n */\nconst OPTION_BOUNDARY = \"<\\\\/?(?:option|optgroup)(?=[\\\\s/>])\";\n/** One attribute of a start tag: name, then an optional quoted or bare value. */\nconst ATTRIBUTE = \"\\\\s+([^\\\\s\\\"'<>/=]+)(?:\\\\s*=\\\\s*(?:\\\"([^\\\"]*)\\\"|'([^']*)'|([^\\\\s\\\"'=<>`]+)))?\";\n\nfunction decodeEntities(text: string): string {\n return text.replace(ENTITY, (whole, decimal?: string, hex?: string, named?: string) => {\n if (named !== undefined) return NAMED_ENTITIES[named.toLowerCase()] ?? whole;\n const code = decimal !== undefined ? Number(decimal) : Number.parseInt(hex ?? \"\", 16);\n return Number.isInteger(code) &&\n code >= 0 &&\n code <= 0x10ffff &&\n !(code >= 0xd800 && code <= 0xdfff)\n ? String.fromCodePoint(code)\n : whole;\n });\n}\n\n/** Index of the `>` that ends the start tag whose attributes begin at `from`, or -1. Quotes are skipped. */\nfunction tagEnd(html: string, from: number): number {\n let quote = \"\";\n for (let index = from; index < html.length; index += 1) {\n const char = html.charAt(index);\n if (quote !== \"\") {\n if (char === quote) quote = \"\";\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === \">\") {\n return index;\n }\n }\n return -1;\n}\n\n/** The text an option without a `value` attribute stands for: its text content, whitespace collapsed. */\nfunction optionText(html: string, from: number, boundaries: RegExp): string {\n boundaries.lastIndex = from;\n const boundary = boundaries.exec(html);\n const raw = html.slice(from, boundary === null ? html.length : boundary.index);\n return decodeEntities(raw.replace(TAGS, \"\")).replace(WHITESPACE, \" \").trim();\n}\n\n/**\n * Rewrites the option start tags of `html` so that exactly the wanted ones carry `selected`. The\n * input is markup this runtime produced (text and attribute values are escaped, so `<option` is\n * always a tag); only the `selected` attribute is added or removed, and nothing from the wanted\n * values is ever written.\n */\nfunction markOptions(html: string, wanted: { values: Set<string>; many: boolean }): string {\n let out = \"\";\n let copied = 0;\n let at = 0;\n let found = false;\n const attribute = new RegExp(ATTRIBUTE, \"g\");\n const boundaries = new RegExp(OPTION_BOUNDARY, \"gi\");\n for (;;) {\n const start = html.indexOf(\"<option\", at);\n if (start === -1) break;\n const attributesFrom = start + 7;\n at = attributesFrom;\n if (!/[\\s/>]/.test(html.charAt(attributesFrom))) continue;\n const end = tagEnd(html, attributesFrom);\n if (end === -1) break;\n const source = html.slice(attributesFrom, end);\n let value: string | undefined;\n let selectedAt = -1;\n let selectedEnd = -1;\n attribute.lastIndex = 0;\n for (let match = attribute.exec(source); match !== null; match = attribute.exec(source)) {\n const name = (match[1] ?? \"\").toLowerCase();\n if (name === \"selected\") {\n selectedAt = match.index;\n selectedEnd = match.index + match[0].length;\n } else if (name === \"value\" && value === undefined) {\n value = decodeEntities(match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n }\n // A scalar behaves like `select.value = x`: the first option with that value wins.\n const matches =\n (wanted.many || !found) && wanted.values.has(value ?? optionText(html, end + 1, boundaries));\n if (matches) found = true;\n if (matches && selectedAt === -1) {\n const slash = source.endsWith(\"/\") ? source.length - 1 : source.length;\n out += `${html.slice(copied, attributesFrom + slash)} selected`;\n copied = attributesFrom + slash;\n } else if (!matches && selectedAt !== -1) {\n out += html.slice(copied, attributesFrom + selectedAt);\n copied = attributesFrom + selectedEnd;\n }\n at = end;\n }\n return copied === 0 ? html : out + html.slice(copied);\n}\n\n/**\n * The options of a `<select>` with the ones its value stands for marked `selected`. A browser\n * ignores a `value` attribute on `<select>`, so the server flags the options instead: the option\n * whose `value` attribute equals the value (or, with no such attribute, whose text does) is\n * selected, and every other option loses `selected`. An array selects every listed option, for\n * `<select multiple>`; a single value selects the first match, like `select.value = x`. `null`\n * and `undefined` stand for the empty string. Options inside `<optgroup>`, control flow and\n * components are found because the search runs on the serialized children. Values are compared,\n * never written, so they cannot add markup.\n *\n * @param value The select's `value`, or an accessor of it. Entries of an array are compared as\n * strings; `null` and `undefined` entries are skipped.\n * @param children The select's children (an `SsrNode`, or anything `escape` accepts).\n * @returns The children with the `selected` flags set, as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol, and the errors of\n * {@link escape} for the children.\n * @example\n * import { renderToString, ssr, ssrRaw, ssrSelectValue } from \"@shadow-js/web/server\";\n *\n * const options = ssrRaw(`<option value=\"red\">Red</option><option value=\"blue\">Blue</option>`);\n * const html = renderToString(() => ssr([\"<select>\", \"</select>\"], ssrSelectValue(\"blue\", options)));\n * // '<select><option value=\"red\">Red</option><option value=\"blue\" selected>Blue</option></select>'\n * @see setSelectValue\n * @since 1.0.0\n */\nexport function ssrSelectValue(value: unknown, children: unknown): SsrNode {\n return new SsrNode(markSelectedOptions(value, escape(children)));\n}\n\n/** {@link ssrSelectValue} on markup that is already escaped. @internal */\nexport function markSelectedOptions(value: unknown, html: string): string {\n return markOptions(html, wantedValues(value));\n}\n"],"mappings":"A,iJAaA,SAASA,EAAU,EAAwB,CACzC,GAAI,OAAOC,GAAU,SACnB,MAAMC,EAAQ,4BAA6B,0CAA0C,EAEvF,OAAOD,GAAU,KAA8B,GAAK,OAAOA,CAAK,CAClE,C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GAAA,CAAI,YAAY,EACtCC,IAAS,YACX,EAAaD,EAAM,MACnB,EAAcA,EAAM,MAAQA,EAAM,EAAE,CAAC,QAC5BC,IAAS,SAAW/C,IAAU,IAAA,KACvC,EAAQmB,EAAe2B,EAAM,IAAMA,EAAM,IAAMA,EAAM,IAAM,EAAE,EAEjE,CAEA,IAAME,GACHC,EAAO,MAAQ,CAACX,IAAUW,EAAO,OAAO,IAAIjD,GAAS+B,EAAWxB,EAAMmC,EAAM,EAAGT,CAAU,CAAC,EAE7F,GADIe,IAAS,EAAQ,IACjBA,GAAWJ,IAAe,GAAI,CAChC,IAAMM,EAAQP,EAAO,SAAS,GAAG,EAAIA,EAAO,OAAS,EAAIA,EAAO,OAChE,GAAO,GAAGpC,EAAK,MAAM6B,EAAQK,EAAiBS,CAAK,EAAE,WACrD,EAAST,EAAiBS,CAC5B,KAAW,CAACF,GAAWJ,IAAe,KACpC,GAAOrC,EAAK,MAAM6B,EAAQK,EAAiBG,CAAU,EACrD,EAASH,EAAiBI,GAE5B,EAAKH,CACP,CACA,OAAON,IAAW,EAAI7B,EAAO4B,EAAM5B,EAAK,MAAM6B,CAAM,CACtD,CA2BA,SAAgBe,EAAe,EAAgB,EAA4B,CACzE,OAAO,IAAI1C,EAAQ2C,EAAoBpD,EAAOqD,EAAOC,CAAQ,CAAC,CAAC,CACjE,CAGA,SAAgBF,EAAoB,EAAgB,EAAsB,CACxE,OAAOlB,EAAY3B,EAAMG,EAAaV,CAAK,CAAC,CAC9C,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{escape as e}from"./escape.js";import{ssrAttribute as t}from"./attributes.js";import{ssrClass as n,ssrStyle as r}from"./class-style.js";import{ssrSelectValue as i,ssrTextArea as a}from"./form-controls.js";import{ssr as
|
|
1
|
+
import{escape as e}from"./escape.js";import{ssrAttribute as t}from"./attributes.js";import{ssrClass as n,ssrStyle as r}from"./class-style.js";import{ssrSelectValue as i,ssrTextArea as a}from"./form-controls.js";import{ssrRawText as o}from"./raw-text.js";import{ssr as s,ssrElement as c,ssrHydrationKey as l,ssrRaw as u}from"./element.js";import{createServerPortals as d}from"./portals.js";import{normalizeTags as f}from"../head/validate.js";import{createServerHead as p}from"../head/server-head.js";import{createComponent as m,memo as h}from"./component.js";import{derived as g}from"./derived.js";import{HydrationScript as _,generateHydrationScript as v}from"./hydration-script.js";import{renderToString as y,renderToStringAsync as b}from"./render.js";import{deserialize as x,serialize as S}from"./serialize.js";import{renderToStream as C}from"./stream.js";import{mergeProps as w}from"@shadow-js/core";export{_ as HydrationScript,m as createComponent,p as createServerHead,d as createServerPortals,g as derived,x as deserialize,e as escape,v as generateHydrationScript,h as memo,w as mergeProps,f as normalizeTags,C as renderToStream,y as renderToString,b as renderToStringAsync,S as serialize,s as ssr,t as ssrAttribute,n as ssrClass,c as ssrElement,l as ssrHydrationKey,u as ssrRaw,o as ssrRawText,i as ssrSelectValue,r as ssrStyle,a as ssrTextArea};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{invalid as e}from"./errors.js";import{SsrNode as t,isSsrNode as n}from"./node.js";import{render as r,resolveValue as i}from"./escape.js";const a=/* @__PURE__ */ new Set([`script`,`style`]),o={script:/<\/(script)|<!--/gi,style:/<\/(style)/gi};function s(e,t){return t.replace(o[e],e=>e===`<!--`?`<\\u0021--`:`<\\/${e.slice(2)}`)}function c(e,t){return s(e.toLowerCase()===`script`?`script`:`style`,r(t,e=>e))}function l(e,t){let r=i(t);return n(r)?r.t:c(e,r)}function u(n,r){if(typeof n!=`string`||!a.has(n.toLowerCase()))throw e(`INVALID_RAW_TEXT_TAG`,`ssrRawText(): the tag must be script or style.`);return new t(c(n,r))}export{l as rawElementContent,c as rawTextContent,u as ssrRawText};
|
|
2
|
+
//# sourceMappingURL=raw-text.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"raw-text.js","names":["RAW_TEXT_ELEMENTS","CLOSING_TAG","neutralize","text","tag","match","rawTextContent","render","value","rawElementContent","resolved","resolveValue","isSsrNode","ssrRawText","invalid","SsrNode"],"sources":["../../../src/server/raw-text.ts"],"sourcesContent":["import { invalid } from \"./errors\";\nimport { render, resolveValue } from \"./escape\";\nimport { isSsrNode, SsrNode } from \"./node\";\n\n/**\n * Elements whose content the HTML parser reads as text and nothing else: `script` and `style` (raw text, no\n * entities) and `title` and `textarea` (entities only). Neither kind can hold a comment, so the region markers\n * that delimit a dynamic child elsewhere would show up as literal text inside them.\n */\nconst TEXT_ONLY_ELEMENTS: ReadonlySet<string> = new Set([\"script\", \"style\", \"title\", \"textarea\"]);\n\n/**\n * True for an HTML element whose content is text only, so its children are written without region markers\n * and the client adopts the text as it is. Pass the tag in any letter case; SVG elements of the same names\n * are ordinary elements and are not text only.\n * @internal\n */\nexport function isTextOnlyElement(tag: string): boolean {\n return TEXT_ONLY_ELEMENTS.has(tag.toLowerCase());\n}\n\n/** The elements whose text the parser reads raw. */\nconst RAW_TEXT_ELEMENTS: ReadonlySet<string> = new Set([\"script\", \"style\"]);\n\n/** The closing tag of a script or style in any case, and the `<!--` that opens a script's double-escaped state. */\nconst CLOSING_TAG = {\n script: /<\\/(script)|<!--/gi,\n style: /<\\/(style)/gi,\n} as const;\n\n/**\n * Keeps raw text from ending its element or the script data state. `</script` and `</style` get a backslash that\n * CSS, JavaScript and JSON all read as the character itself (`<\\/style` is `</style` in a string, a comment or a\n * selector escape), and `<!--` in a script becomes `<\\u0021--`: `\\!` is no JSON escape, and a script that holds\n * JSON data (`application/json`, `ld+json`) must still parse. The text means what it meant and the parser does\n * not see a tag. Entities would instead change the text: raw text has none.\n */\nfunction neutralize(tag: \"script\" | \"style\", text: string): string {\n return text.replace(CLOSING_TAG[tag], (match: string) =>\n match === \"<!--\" ? \"<\\\\u0021--\" : `<\\\\/${match.slice(2)}`,\n );\n}\n\n/** The text of a child value for a `script` or `style`: strings unescaped, the whole checked by {@link neutralize}. @internal */\nexport function rawTextContent(tag: string, value: unknown): string {\n return neutralize(\n tag.toLowerCase() === \"script\" ? \"script\" : \"style\",\n render(value, (text) => text),\n );\n}\n\n/**\n * The content of a `script` or `style` element made by `ssrElement`. A node the compiler built (`ssr`, `ssrRaw`)\n * is the application's own markup and is left as it is; any other value is raw text and is checked.\n * @internal\n */\nexport function rawElementContent(tag: string, value: unknown): string {\n const resolved = resolveValue(value);\n return isSsrNode(resolved) ? resolved.t : rawTextContent(tag, resolved);\n}\n\n/**\n * Writes the children of a `<script>` or `<style>` element: the helper compiled server output calls for a\n * dynamic child of one. The browser reads these elements' content as raw text, so the value is written\n * as it is (`a > b` stays `a > b`; HTML entities would corrupt the stylesheet or the code) with no region\n * markers around it, and the client adopts the text when it hydrates. Only one thing is changed: a closing tag of\n * the element, in any letter case (`</style`, `</SCRIPT`), and `<!--` in a script, would end the element\n * early or hide its end, so each is rewritten (`<\\/style`, `<\\u0021--`) to text that CSS, JavaScript and JSON read as the same characters.\n *\n * Accessors are called untracked, arrays are flattened, `null`, `undefined` and booleans write nothing, and\n * a symbol throws, as in {@link escape}.\n *\n * @param tag The element, `\"script\"` or `\"style\"` (any letter case).\n * @param value The child value: a string, a number, an array, an accessor or `null`.\n * @returns The text as a trusted `SsrNode`.\n * @throws TypeError `INVALID_RAW_TEXT_TAG` when `tag` is not `script` or `style`, and the errors of\n * {@link escape} for the value.\n * @example\n * import { renderToString, ssr, ssrRawText } from \"@shadow-js/web/server\";\n *\n * const css = \"a > b { color: red } </style><script>alert(1)</script>\";\n * const html = renderToString(() => ssr([\"<style>\", \"</style>\"], ssrRawText(\"style\", css)));\n * // \"<style>a > b { color: red } <\\/style><script>alert(1)</script></style>\"\n * @see escape\n * @since 1.0.2\n */\nexport function ssrRawText(tag: \"script\" | \"style\", value: unknown): SsrNode {\n if (typeof tag !== \"string\" || !RAW_TEXT_ELEMENTS.has(tag.toLowerCase())) {\n throw invalid(\"INVALID_RAW_TEXT_TAG\", \"ssrRawText(): the tag must be script or style.\");\n }\n return new SsrNode(rawTextContent(tag, value));\n}\n"],"mappings":"A,gJAsBA,MAAMA,kBAAyC,IAAI,IAAI,CAAC,SAAU,OAAO,CAAC,EAGpEC,EAAc,CAClB,OAAQ,qBACR,MAAO,cACT,EASA,SAASC,EAAW,EAAyB,EAAsB,CACjE,OAAOC,EAAK,QAAQF,EAAYG,GAAO,GACrCC,IAAU,OAAS,aAAe,OAAOA,EAAM,MAAM,CAAC,GACxD,CACF,CAGA,SAAgBC,EAAe,EAAa,EAAwB,CAClE,OAAOJ,EACLE,EAAI,YAAY,IAAM,SAAW,SAAW,QAC5CG,EAAOC,EAAQ,GAASL,CAAI,CAC9B,CACF,CAOA,SAAgBM,EAAkB,EAAa,EAAwB,CACrE,IAAMC,EAAWC,EAAaH,CAAK,EACnC,OAAOI,EAAUF,CAAQ,EAAIA,EAAS,EAAIJ,EAAeF,EAAKM,CAAQ,CACxE,CA2BA,SAAgBG,EAAW,EAAyB,EAAyB,CAC3E,GAAI,OAAOT,GAAQ,UAAY,CAACJ,EAAkB,IAAII,EAAI,YAAY,CAAC,EACrE,MAAMU,EAAQ,uBAAwB,gDAAgD,EAExF,OAAO,IAAIC,EAAQT,EAAeF,EAAKI,CAAK,CAAC,CAC/C,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{SsrError as
|
|
1
|
+
import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{MAX_TIMER_MS as r,SsrError as i}from"./errors.js";import{escape as a}from"./escape.js";import{attachRootErrors as o}from"../control-flow/root-errors.js";import{portalCollectorFor as s,withPortalSink as c}from"./portals.js";import{runWithServerHead as l}from"../head/server-head.js";import{ResourceCacheContext as u,createRoot as d}from"@shadow-js/core";const f=/^[A-Za-z0-9_-]+$/;function p(e){if(typeof e!=`string`||!f.test(e))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);return e}function m(e){return{...e?.onCaughtError===void 0?{}:{onCaughtError:e.onCaughtError},...e?.onUncaughtError===void 0?{}:{onUncaughtError:e.onUncaughtError}}}function h(t,r,i,s,d,f){return o(f),c(d,()=>u({value:i,get children(){return l(s,()=>n(e(r),()=>a(t())))}}))()}function g(e,t){let n=p(t?.renderId??`0`),r=s(t?.portals),i=m(t);return d(a=>{try{return h(e,n,null,t?.head,r,i)}finally{a()}})}function _(e,n,r,i,a,o){let s=/* @__PURE__ */ new Set,c=[],l={caught:[],uncaught:[]},u={onCaughtError:e=>{l.caught.push(e)},...o.onUncaughtError===void 0?{}:{onUncaughtError:e=>{l.uncaught.push(e)}}},f=/* @__PURE__ */ new Set,p={key:e=>{let n=t(e);return s.add(n),n},read:e=>r.has(e)?{value:r.get(e)}:void 0,track:(e,t)=>{f.has(e)||(f.add(e),c.push({key:e,promise:t}))}};return d(t=>(i?.clear(),a?.clear(),{html:h(e,n,p,i,a,u),requested:s,tracked:c,errors:l,dispose:t}))}function v(e,t){for(let n of e.caught)t.onCaughtError?.(n);for(let n of e.uncaught)t.onUncaughtError?.(n)}function y(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function b(e,t){let n={};for(let r of e)t.has(r)&&y(n,r,t.get(r));return n}function x(e){if(e.canceled)throw new i(`SSR_TIMEOUT`,`The render was canceled after its time budget.`)}async function S(e,t,n,r,a,o,s){let c=/* @__PURE__ */ new Map;for(let l=1;;l+=1){x(r);let u=_(e,t,c,a,o,s);if(r.roots.push(u.dispose),u.tracked.length===0)return u.dispose(),v(u.errors,s),{html:u.html,data:b(u.requested,c)};let d=await Promise.allSettled(u.tracked.map(e=>e.promise));x(r);let f=!1;if(d.forEach((e,t)=>{let n=u.tracked[t];n!==void 0&&e.status===`fulfilled`&&(c.has(n.key)||(f=!0),c.set(n.key,e.value))}),u.dispose(),!f)return v(u.errors,s),{html:u.html,data:b(u.requested,c)};if(l>=n)throw new i(`SSR_BOUNDARY_WATERFALL`,`Resources kept loading new resources after ${n} passes; raise maxPasses or flatten the data flow.`)}}function C(e){let t=e?.timeoutMs??1e4,n=e?.maxPasses??10;if(typeof t!=`number`||!(t>0)||!Number.isFinite(t))throw TypeError(`render options: timeoutMs must be a positive finite number.`);if(!Number.isInteger(n)||n<1)throw TypeError(`render options: maxPasses must be an integer of at least 1.`);return{timeoutMs:t,maxPasses:n}}async function w(e,t){let n=p(t?.renderId??`0`),{timeoutMs:a,maxPasses:o}=C(t),c={canceled:!1,roots:[]},l,u=new Promise((e,t)=>{l=setTimeout(()=>{c.canceled=!0,t(new i(`SSR_TIMEOUT`,`The render did not finish within ${a} ms.`))},Math.min(a,r))});try{let r=s(t?.portals);return await Promise.race([S(e,n,o,c,t?.head,r,m(t)),u])}finally{clearTimeout(l),c.canceled=!0;for(let e of c.roots.splice(0))e()}}export{g as renderToString,w as renderToStringAsync};
|
|
2
2
|
//# sourceMappingURL=render.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render.js","names":["RENDER_ID","checkRenderId","renderId","reportersOf","options","renderMarkup","attachRootErrors","reporters","withPortalSink","portals","ResourceCacheContext","cache","runWithServerHead","head","withScope","createRootScope","escape","code","renderToString","portalCollectorFor","createRoot","dispose","runPass","requested","tracked","errors","error","user","seen","key","resourceKey","explicit","settled","reportPass","defineData","target","collectData","data","assertActive","job","SsrError","runPasses","pass","current","results","entry","advanced","index","result","maxPasses","checkAsyncOptions","timeoutMs","renderToStringAsync","timer","expired","reject"],"sources":["../../../src/server/render.ts"],"sourcesContent":["import { createRoot, type ResourceCache, ResourceCacheContext } from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\nimport {\n type PortalCollector,\n portalCollectorFor,\n type ServerPortals,\n withPortalSink,\n} from \"./portals\";\n\n/**\n * Options of {@link renderToString}, and the base of {@link AsyncRenderOptions}.\n * @since 1.0.0\n */\nexport interface RenderOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Give each app rendered into the\n * same page its own id, and pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * Collects the tags `useHead`, `<Title>`, `<Meta>`, ... register while rendering (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Collects the markup of the portals the render produces (see {@link createServerPortals}). Emit\n * `portals.html()` at the end of `<body>` once the render is done.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the render caught. The boundary's fallback is in the markup,\n * so the caller can answer the request with the status of the error. Called once per caught error.\n * For {@link renderToStringAsync} only the last pass is reported.\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the render does not throw that error and the markup\n * lacks the part that failed.\n * @default undefined (the error propagates out of the render)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\n/**\n * Options of {@link renderToStringAsync}: the {@link RenderOptions} plus the limits of the multi-pass\n * render.\n * @since 1.0.0\n */\nexport interface AsyncRenderOptions extends RenderOptions {\n /**\n * Upper bound for the whole render, in milliseconds: a positive finite number.\n * @default 10000\n */\n readonly timeoutMs?: number;\n /**\n * Maximum number of render passes: an integer of at least 1. Each pass renders with the resource\n * values the previous passes resolved.\n * @default 10\n */\n readonly maxPasses?: number;\n}\n\n/**\n * What {@link renderToStringAsync} resolves to: the markup and the resource data to embed for\n * hydration.\n * @since 1.0.0\n */\nexport interface AsyncRenderResult {\n /** The markup of the last pass. */\n readonly html: string;\n /**\n * The resolved resource values the last pass read, keyed as the client looks them up. Embed it in\n * the page with {@link serialize} and pass it to `hydrate()` as its `data` option, so the client\n * reuses the values instead of fetching again.\n */\n readonly data: Record<string, unknown>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_PASSES = 10;\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\n\n/** Validates a render id: it is written into markup, so only plain tokens are accepted. */\nfunction checkRenderId(renderId: string): string {\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n return renderId;\n}\n\n/**\n * The reporters of a render, in the shape the root takes them. An `onUncaughtError` is set only when the\n * caller gave one: a root with a handler does not rethrow, so without one the error must keep propagating.\n */\nfunction reportersOf(options: RenderOptions | undefined): RootErrorOptions {\n return {\n ...(options?.onCaughtError === undefined ? {} : { onCaughtError: options.onCaughtError }),\n ...(options?.onUncaughtError === undefined ? {} : { onUncaughtError: options.onUncaughtError }),\n };\n}\n\n/**\n * Runs `code` under the render's resource cache and returns the escaped markup. The root scope\n * is entered inside the provider, so accessors evaluated during escaping see the same cache.\n * Must run inside the root that is being rendered: the reporters are attached to it.\n */\nfunction renderMarkup(\n code: () => unknown,\n renderId: string,\n cache: ResourceCache | null,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n reporters: RootErrorOptions,\n): string {\n attachRootErrors(reporters);\n // The provider returns an accessor; reading it surfaces an error thrown while rendering.\n return (\n withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n ) as () => string\n )();\n}\n\n/**\n * Renders an app to an HTML string synchronously: the simplest server render, for pages whose data\n * is already at hand. Suspense boundaries whose resources are still pending render their fallback\n * (use {@link renderToStringAsync} or {@link renderToStream} to wait for data). Effects never run.\n * The root is disposed before this returns, and an error from `code` propagates after that cleanup.\n *\n * @param code Builds the app: returns a component result, an `SsrNode`, text or an array.\n * @param options Hydration-key prefix, head and portal collectors, and error reporters. Undefined uses\n * the defaults of {@link RenderOptions}.\n * @returns The escaped markup of the app.\n * @throws TypeError for an invalid `renderId`, for `portals` not created by\n * {@link createServerPortals}, or for a value that cannot be rendered (see {@link escape}). An error\n * no boundary caught propagates unless `onUncaughtError` is set.\n * @example\n * import { createComponent, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * const html = renderToString(() => createComponent(App, {}));\n * @see renderToStringAsync\n * @see renderToStream\n * @since 1.0.0\n */\nexport function renderToString(code: () => unknown, options?: RenderOptions): string {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const portals = portalCollectorFor(options?.portals);\n const reporters = reportersOf(options);\n return createRoot((dispose) => {\n try {\n return renderMarkup(code, renderId, null, options?.head, portals, reporters);\n } finally {\n dispose();\n }\n });\n}\n\n/** The errors one pass reported to its root, kept until the pass is known to be the answer. */\ninterface PassErrors {\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n}\n\n/** One render pass: its markup, the keys it asked for, and the fetches it started. */\ninterface Pass {\n readonly html: string;\n readonly requested: Set<string>;\n readonly tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }>;\n readonly errors: PassErrors;\n readonly dispose: () => void;\n}\n\n/**\n * Runs one pass. The root stays alive until the caller disposes it, so fetches are not aborted. The\n * pass records its errors instead of reporting them: every pass renders the same boundaries again, so\n * only the answering pass (see {@link reportPass}) reports.\n */\nfunction runPass(\n code: () => unknown,\n renderId: string,\n settled: ReadonlyMap<string, unknown>,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Pass {\n const requested = new Set<string>();\n const tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }> = [];\n const errors: PassErrors = { caught: [], uncaught: [] };\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n errors.caught.push(error);\n },\n // Recorded only when the caller reports uncaught errors; otherwise the error must still throw.\n ...(user.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n errors.uncaught.push(error);\n },\n }),\n };\n const seen = new Set<string>();\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise) => {\n if (seen.has(key)) return;\n seen.add(key);\n tracked.push({ key, promise });\n },\n };\n return createRoot((dispose) => {\n // Every pass registers the same tags and portals again: only the last pass counts.\n head?.clear();\n portals?.clear();\n const html = renderMarkup(code, renderId, cache, head, portals, reporters);\n return { html, requested, tracked, errors, dispose };\n });\n}\n\n/**\n * Hands the errors of the answering pass to the caller's reporters, in the order they happened. Called\n * once per render, so each caught error is reported once even when several passes rendered it.\n */\nfunction reportPass(errors: PassErrors, user: RootErrorOptions): void {\n for (const error of errors.caught) user.onCaughtError?.(error);\n for (const error of errors.uncaught) user.onUncaughtError?.(error);\n}\n\n/** Records a value under a key with defineProperty, so keys such as \"__proto__\" stay data. */\nfunction defineData(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** The values of `settled` that the pass asked for. */\nfunction collectData(\n requested: ReadonlySet<string>,\n settled: ReadonlyMap<string, unknown>,\n): Record<string, unknown> {\n const data: Record<string, unknown> = {};\n for (const key of requested) {\n if (settled.has(key)) defineData(data, key, settled.get(key));\n }\n return data;\n}\n\n/** Shared state of one async render: its cancellation flag and the roots still alive. */\ninterface Job {\n canceled: boolean;\n readonly roots: Array<() => void>;\n}\n\nfunction assertActive(job: Job): void {\n if (job.canceled)\n throw new SsrError(\"SSR_TIMEOUT\", \"The render was canceled after its time budget.\");\n}\n\n/**\n * The multi-pass algorithm. Pass N renders with the values resolved so far; the fetches it starts\n * are awaited, and another pass runs only if one of them produced a value that the next render can\n * use. A pass with no new value is final: its markup is the answer.\n */\nasync function runPasses(\n code: () => unknown,\n renderId: string,\n maxPasses: number,\n job: Job,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Promise<AsyncRenderResult> {\n const settled = new Map<string, unknown>();\n for (let pass = 1; ; pass += 1) {\n assertActive(job);\n const current = runPass(code, renderId, settled, head, portals, user);\n job.roots.push(current.dispose);\n if (current.tracked.length === 0) {\n current.dispose();\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n const results = await Promise.allSettled(current.tracked.map((entry) => entry.promise));\n assertActive(job);\n let advanced = false;\n results.forEach((result, index) => {\n const entry = current.tracked[index];\n if (entry === undefined || result.status !== \"fulfilled\") return;\n if (!settled.has(entry.key)) advanced = true;\n settled.set(entry.key, result.value);\n });\n current.dispose();\n if (!advanced) {\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n if (pass >= maxPasses) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept loading new resources after ${maxPasses} passes; raise maxPasses or flatten the data flow.`,\n );\n }\n }\n}\n\n/** Validates the numeric options. */\nfunction checkAsyncOptions(options: AsyncRenderOptions | undefined): {\n timeoutMs: number;\n maxPasses: number;\n} {\n const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxPasses = options?.maxPasses ?? DEFAULT_MAX_PASSES;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n if (!Number.isInteger(maxPasses) || maxPasses < 1) {\n throw new TypeError(\"render options: maxPasses must be an integer of at least 1.\");\n }\n return { timeoutMs, maxPasses };\n}\n\n/**\n * Renders an app to an HTML string once its data has loaded: each pass renders with the resource\n * values found so far, the fetches it starts are awaited, and another pass runs while one of them\n * produced a new value. Resources that reject are not cached and render their fallback. The error\n * reporters (`onCaughtError`, `onUncaughtError`) are called once, for the pass that gives the answer.\n *\n * @param code Builds the app.\n * @param options The {@link RenderOptions} plus `timeoutMs` and `maxPasses`. Undefined uses the\n * defaults of {@link AsyncRenderOptions}.\n * @returns A promise of the final markup and the resolved resource values, to embed in the page.\n * @throws TypeError (synchronously rejected) for an invalid `renderId`, `timeoutMs` or `maxPasses`.\n * The promise rejects with an `Error` named `SsrError` whose `code` is `SSR_BOUNDARY_WATERFALL` when\n * more than `maxPasses` passes are needed, or `SSR_TIMEOUT` when the time budget runs out; and with\n * the error of a failing render.\n * @example\n * import { createComponent, renderToStringAsync, serialize } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * async function page(): Promise<string> {\n * const { html, data } = await renderToStringAsync(() => createComponent(App, {}));\n * return `${html}<script type=\"application/json\" data-sh=\"0\">${serialize(data)}</script>`;\n * }\n * @see renderToString\n * @see renderToStream\n * @since 1.0.0\n */\nexport async function renderToStringAsync(\n code: () => unknown,\n options?: AsyncRenderOptions,\n): Promise<AsyncRenderResult> {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const { timeoutMs, maxPasses } = checkAsyncOptions(options);\n const job: Job = { canceled: false, roots: [] };\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n job.canceled = true;\n reject(new SsrError(\"SSR_TIMEOUT\", `The render did not finish within ${timeoutMs} ms.`));\n }, timeoutMs);\n });\n try {\n const portals = portalCollectorFor(options?.portals);\n return await Promise.race([\n runPasses(code, renderId, maxPasses, job, options?.head, portals, reportersOf(options)),\n expired,\n ]);\n } finally {\n clearTimeout(timer);\n job.canceled = true;\n for (const dispose of job.roots.splice(0)) dispose();\n }\n}\n"],"mappings":"A,ubAuFA,MAEMA,EAAY,mBAGlB,SAASC,EAAc,EAA0B,CAC/C,GAAI,OAAOC,GAAa,UAAY,CAACF,EAAU,KAAKE,CAAQ,EAC1D,MAAU,UAAU,oEAAoE,EAE1F,OAAOA,CACT,CAMA,SAASC,EAAY,EAAsD,CACzE,MAAO,CACL,GAAIC,GAAS,gBAAkB,IAAA,GAAY,CAAC,EAAI,CAAE,cAAeA,EAAQ,aAAc,EACvF,GAAIA,GAAS,kBAAoB,IAAA,GAA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CACzF,EAAGA,CAAS,CACd,CAAC,EACD,GAAI,CACF,IAAM1C,EAAUU,EAAmBf,GAAS,OAAO,EACnD,OAAO,MAAM,QAAQ,KAAK,CACxBqC,EAAUxB,EAAMf,EAAU+C,EAAWV,EAAKnC,GAAS,KAAMK,EAASN,EAAYC,CAAO,CAAC,EACtFkD,CACF,CAAC,CACH,QAAU,CACR,aAAaD,CAAK,EAClB,EAAI,SAAW,GACf,IAAK,IAAMhC,KAAWkB,EAAI,MAAM,OAAO,CAAC,EAAGlB,EAAQ,CACrD,CACF,C"}
|
|
1
|
+
{"version":3,"file":"render.js","names":["RENDER_ID","checkRenderId","renderId","reportersOf","options","renderMarkup","attachRootErrors","reporters","withPortalSink","portals","ResourceCacheContext","cache","runWithServerHead","head","withScope","createRootScope","escape","code","renderToString","portalCollectorFor","createRoot","dispose","runPass","requested","tracked","errors","error","user","seen","key","resourceKey","explicit","settled","reportPass","defineData","target","collectData","data","assertActive","job","SsrError","runPasses","pass","current","results","entry","advanced","index","result","maxPasses","checkAsyncOptions","timeoutMs","renderToStringAsync","timer","expired","reject","MAX_TIMER_MS"],"sources":["../../../src/server/render.ts"],"sourcesContent":["import { createRoot, type ResourceCache, ResourceCacheContext } from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { MAX_TIMER_MS, SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\nimport {\n type PortalCollector,\n portalCollectorFor,\n type ServerPortals,\n withPortalSink,\n} from \"./portals\";\n\n/**\n * Options of {@link renderToString}, and the base of {@link AsyncRenderOptions}.\n * @since 1.0.0\n */\nexport interface RenderOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Give each app rendered into the\n * same page its own id, and pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * Collects the tags `useHead`, `<Title>`, `<Meta>`, ... register while rendering (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Collects the markup of the portals the render produces (see {@link createServerPortals}). Emit\n * `portals.html()` at the end of `<body>` once the render is done.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the render caught. The boundary's fallback is in the markup,\n * so the caller can answer the request with the status of the error. Called once per caught error.\n * For {@link renderToStringAsync} only the last pass is reported.\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the render does not throw that error and the markup\n * lacks the part that failed.\n * @default undefined (the error propagates out of the render)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\n/**\n * Options of {@link renderToStringAsync}: the {@link RenderOptions} plus the limits of the multi-pass\n * render.\n * @since 1.0.0\n */\nexport interface AsyncRenderOptions extends RenderOptions {\n /**\n * Upper bound for the whole render, in milliseconds: a positive finite number. Values above the\n * timer range (2147483647, about 24.8 days) count as 2147483647.\n * @default 10000\n */\n readonly timeoutMs?: number;\n /**\n * Maximum number of render passes: an integer of at least 1. Each pass renders with the resource\n * values the previous passes resolved.\n * @default 10\n */\n readonly maxPasses?: number;\n}\n\n/**\n * What {@link renderToStringAsync} resolves to: the markup and the resource data to embed for\n * hydration.\n * @since 1.0.0\n */\nexport interface AsyncRenderResult {\n /** The markup of the last pass. */\n readonly html: string;\n /**\n * The resolved resource values the last pass read, keyed as the client looks them up. Embed it in\n * the page with {@link serialize} and pass it to `hydrate()` as its `data` option, so the client\n * reuses the values instead of fetching again.\n */\n readonly data: Record<string, unknown>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_PASSES = 10;\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\n\n/** Validates a render id: it is written into markup, so only plain tokens are accepted. */\nfunction checkRenderId(renderId: string): string {\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n return renderId;\n}\n\n/**\n * The reporters of a render, in the shape the root takes them. An `onUncaughtError` is set only when the\n * caller gave one: a root with a handler does not rethrow, so without one the error must keep propagating.\n */\nfunction reportersOf(options: RenderOptions | undefined): RootErrorOptions {\n return {\n ...(options?.onCaughtError === undefined ? {} : { onCaughtError: options.onCaughtError }),\n ...(options?.onUncaughtError === undefined ? {} : { onUncaughtError: options.onUncaughtError }),\n };\n}\n\n/**\n * Runs `code` under the render's resource cache and returns the escaped markup. The root scope\n * is entered inside the provider, so accessors evaluated during escaping see the same cache.\n * Must run inside the root that is being rendered: the reporters are attached to it.\n */\nfunction renderMarkup(\n code: () => unknown,\n renderId: string,\n cache: ResourceCache | null,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n reporters: RootErrorOptions,\n): string {\n attachRootErrors(reporters);\n // The provider returns an accessor; reading it surfaces an error thrown while rendering.\n return (\n withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n ) as () => string\n )();\n}\n\n/**\n * Renders an app to an HTML string synchronously: the simplest server render, for pages whose data\n * is already at hand. Suspense boundaries whose resources are still pending render their fallback\n * (use {@link renderToStringAsync} or {@link renderToStream} to wait for data). Effects never run.\n * The root is disposed before this returns, and an error from `code` propagates after that cleanup.\n *\n * @param code Builds the app: returns a component result, an `SsrNode`, text or an array.\n * @param options Hydration-key prefix, head and portal collectors, and error reporters. Undefined uses\n * the defaults of {@link RenderOptions}.\n * @returns The escaped markup of the app.\n * @throws TypeError for an invalid `renderId`, for `portals` not created by\n * {@link createServerPortals}, or for a value that cannot be rendered (see {@link escape}). An error\n * no boundary caught propagates unless `onUncaughtError` is set.\n * @example\n * import { createComponent, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * const html = renderToString(() => createComponent(App, {}));\n * @see renderToStringAsync\n * @see renderToStream\n * @since 1.0.0\n */\nexport function renderToString(code: () => unknown, options?: RenderOptions): string {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const portals = portalCollectorFor(options?.portals);\n const reporters = reportersOf(options);\n return createRoot((dispose) => {\n try {\n return renderMarkup(code, renderId, null, options?.head, portals, reporters);\n } finally {\n dispose();\n }\n });\n}\n\n/** The errors one pass reported to its root, kept until the pass is known to be the answer. */\ninterface PassErrors {\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n}\n\n/** One render pass: its markup, the keys it asked for, and the fetches it started. */\ninterface Pass {\n readonly html: string;\n readonly requested: Set<string>;\n readonly tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }>;\n readonly errors: PassErrors;\n readonly dispose: () => void;\n}\n\n/**\n * Runs one pass. The root stays alive until the caller disposes it, so fetches are not aborted. The\n * pass records its errors instead of reporting them: every pass renders the same boundaries again, so\n * only the answering pass (see {@link reportPass}) reports.\n */\nfunction runPass(\n code: () => unknown,\n renderId: string,\n settled: ReadonlyMap<string, unknown>,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Pass {\n const requested = new Set<string>();\n const tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }> = [];\n const errors: PassErrors = { caught: [], uncaught: [] };\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n errors.caught.push(error);\n },\n // Recorded only when the caller reports uncaught errors; otherwise the error must still throw.\n ...(user.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n errors.uncaught.push(error);\n },\n }),\n };\n const seen = new Set<string>();\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise) => {\n if (seen.has(key)) return;\n seen.add(key);\n tracked.push({ key, promise });\n },\n };\n return createRoot((dispose) => {\n // Every pass registers the same tags and portals again: only the last pass counts.\n head?.clear();\n portals?.clear();\n const html = renderMarkup(code, renderId, cache, head, portals, reporters);\n return { html, requested, tracked, errors, dispose };\n });\n}\n\n/**\n * Hands the errors of the answering pass to the caller's reporters, in the order they happened. Called\n * once per render, so each caught error is reported once even when several passes rendered it.\n */\nfunction reportPass(errors: PassErrors, user: RootErrorOptions): void {\n for (const error of errors.caught) user.onCaughtError?.(error);\n for (const error of errors.uncaught) user.onUncaughtError?.(error);\n}\n\n/** Records a value under a key with defineProperty, so keys such as \"__proto__\" stay data. */\nfunction defineData(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** The values of `settled` that the pass asked for. */\nfunction collectData(\n requested: ReadonlySet<string>,\n settled: ReadonlyMap<string, unknown>,\n): Record<string, unknown> {\n const data: Record<string, unknown> = {};\n for (const key of requested) {\n if (settled.has(key)) defineData(data, key, settled.get(key));\n }\n return data;\n}\n\n/** Shared state of one async render: its cancellation flag and the roots still alive. */\ninterface Job {\n canceled: boolean;\n readonly roots: Array<() => void>;\n}\n\nfunction assertActive(job: Job): void {\n if (job.canceled)\n throw new SsrError(\"SSR_TIMEOUT\", \"The render was canceled after its time budget.\");\n}\n\n/**\n * The multi-pass algorithm. Pass N renders with the values resolved so far; the fetches it starts\n * are awaited, and another pass runs only if one of them produced a value that the next render can\n * use. A pass with no new value is final: its markup is the answer.\n */\nasync function runPasses(\n code: () => unknown,\n renderId: string,\n maxPasses: number,\n job: Job,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Promise<AsyncRenderResult> {\n const settled = new Map<string, unknown>();\n for (let pass = 1; ; pass += 1) {\n assertActive(job);\n const current = runPass(code, renderId, settled, head, portals, user);\n job.roots.push(current.dispose);\n if (current.tracked.length === 0) {\n current.dispose();\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n const results = await Promise.allSettled(current.tracked.map((entry) => entry.promise));\n assertActive(job);\n let advanced = false;\n results.forEach((result, index) => {\n const entry = current.tracked[index];\n if (entry === undefined || result.status !== \"fulfilled\") return;\n if (!settled.has(entry.key)) advanced = true;\n settled.set(entry.key, result.value);\n });\n current.dispose();\n if (!advanced) {\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n if (pass >= maxPasses) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept loading new resources after ${maxPasses} passes; raise maxPasses or flatten the data flow.`,\n );\n }\n }\n}\n\n/** Validates the numeric options. */\nfunction checkAsyncOptions(options: AsyncRenderOptions | undefined): {\n timeoutMs: number;\n maxPasses: number;\n} {\n const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxPasses = options?.maxPasses ?? DEFAULT_MAX_PASSES;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n if (!Number.isInteger(maxPasses) || maxPasses < 1) {\n throw new TypeError(\"render options: maxPasses must be an integer of at least 1.\");\n }\n return { timeoutMs, maxPasses };\n}\n\n/**\n * Renders an app to an HTML string once its data has loaded: each pass renders with the resource\n * values found so far, the fetches it starts are awaited, and another pass runs while one of them\n * produced a new value. Resources that reject are not cached and render their fallback. The error\n * reporters (`onCaughtError`, `onUncaughtError`) are called once, for the pass that gives the answer.\n *\n * @param code Builds the app.\n * @param options The {@link RenderOptions} plus `timeoutMs` and `maxPasses`. Undefined uses the\n * defaults of {@link AsyncRenderOptions}.\n * @returns A promise of the final markup and the resolved resource values, to embed in the page.\n * @throws TypeError (synchronously rejected) for an invalid `renderId`, `timeoutMs` or `maxPasses`.\n * The promise rejects with an `Error` named `SsrError` whose `code` is `SSR_BOUNDARY_WATERFALL` when\n * more than `maxPasses` passes are needed, or `SSR_TIMEOUT` when the time budget runs out; and with\n * the error of a failing render.\n * @example\n * import { createComponent, renderToStringAsync, serialize } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * async function page(): Promise<string> {\n * const { html, data } = await renderToStringAsync(() => createComponent(App, {}));\n * return `${html}<script type=\"application/json\" data-sh=\"0\">${serialize(data)}</script>`;\n * }\n * @see renderToString\n * @see renderToStream\n * @since 1.0.0\n */\nexport async function renderToStringAsync(\n code: () => unknown,\n options?: AsyncRenderOptions,\n): Promise<AsyncRenderResult> {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const { timeoutMs, maxPasses } = checkAsyncOptions(options);\n const job: Job = { canceled: false, roots: [] };\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () => {\n job.canceled = true;\n reject(new SsrError(\"SSR_TIMEOUT\", `The render did not finish within ${timeoutMs} ms.`));\n },\n Math.min(timeoutMs, MAX_TIMER_MS),\n );\n });\n try {\n const portals = portalCollectorFor(options?.portals);\n return await Promise.race([\n runPasses(code, renderId, maxPasses, job, options?.head, portals, reportersOf(options)),\n expired,\n ]);\n } finally {\n clearTimeout(timer);\n job.canceled = true;\n for (const dispose of job.roots.splice(0)) dispose();\n }\n}\n"],"mappings":"A,ycAwFA,MAEMA,EAAY,mBAGlB,SAASC,EAAc,EAA0B,CAC/C,GAAI,OAAOC,GAAa,UAAY,CAACF,EAAU,KAAKE,CAAQ,EAC1D,MAAU,UAAU,oEAAoE,EAE1F,OAAOA,CACT,CAMA,SAASC,EAAY,EAAsD,CACzE,MAAO,CACL,GAAIC,GAAS,gBAAkB,IAAA,GAAY,CAAC,EAAI,CAAE,cAAeA,EAAQ,aAAc,EACvF,GAAIA,GAAS,kBAAoB,IAAA,GAAY,CAAC,EAAI,CAAE,gBAAiBA,EAAQ,eAAgB,CAC/F,CACF,CAOA,SAASC,EACP,EACA,EACA,EACA,EACA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GAAS,OAAO,EACnD,OAAO,MAAM,QAAQ,KAAK,CACxBqC,EAAUxB,EAAMf,EAAU+C,EAAWV,EAAKnC,GAAS,KAAMK,EAASN,EAAYC,CAAO,CAAC,EACtFkD,CACF,CAAC,CACH,QAAU,CACR,aAAaD,CAAK,EAClB,EAAI,SAAW,GACf,IAAK,IAAMhC,KAAWkB,EAAI,MAAM,OAAO,CAAC,EAAGlB,EAAQ,CACrD,CACF,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{SsrError as
|
|
1
|
+
import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{MAX_TIMER_MS as r,SsrError as i}from"./errors.js";import{escape as a}from"./escape.js";import{StreamContext as o}from"../internal/stream-context.js";import{attachRootErrors as s}from"../control-flow/root-errors.js";import{portalCollectorFor as c,withPortalSink as l}from"./portals.js";import{runWithServerHead as u}from"../head/server-head.js";import{serialize as d}from"./serialize.js";import{ResourceCacheContext as f,createRoot as p,untrack as m}from"@shadow-js/core";const h=/^[A-Za-z0-9_-]+$/;function g(e,t){return`<script${t===void 0?``:` nonce="${t.replace(/[^A-Za-z0-9+/=_-]/g,``)}"`}>${e}<\/script>`}function _(_,v={}){let y=v.renderId??`0`;if(typeof y!=`string`||!h.test(y))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);let b=v.timeoutMs??3e4;if(typeof b!=`number`||!(b>0)||!Number.isFinite(b))throw TypeError(`render options: timeoutMs must be a positive finite number.`);let x=v.signal,S=c(v.portals),C=new TextEncoder,w=[],T=()=>{let e=[];for(let t of w.splice(0))try{t.dispose()}catch(t){e.push(t)}if(e.length>0)throw e.length===1?e[0]:AggregateError(e,`Stream cleanup failed.`)},E=!1,D,O=()=>void 0;return new ReadableStream({async start(c){let h=/* @__PURE__ */ new Map,k=/* @__PURE__ */ new Map,A=e=>{if(x?.aborted)throw x.reason;E||c.enqueue(C.encode(e))},j=()=>{let r={html:``,boundaries:[],requested:/* @__PURE__ */ new Set,held:[],inFlight:/* @__PURE__ */ new Set,caught:[],uncaught:[],answered:!1,dispose:()=>void 0};w.push(r);let i={key:e=>{let n=t(e);return r.requested.add(n),n},read:e=>h.has(e)?{value:h.get(e)}:void 0,track:(e,t,n)=>{k.set(e,t);let i=t.then(t=>{h.set(e,t)},()=>void 0);r.inFlight.add(i),i.finally(()=>r.inFlight.delete(i)),n?.deferStream===!0&&r.held.push({key:e,entry:i})},pending:e=>k.get(e)},c={defer:e=>{r.boundaries.push(e)}},d={onCaughtError:e=>{r.answered?v.onCaughtError?.(e):r.caught.push(e)},...v.onUncaughtError===void 0?{}:{onUncaughtError:e=>{r.answered?v.onUncaughtError?.(e):r.uncaught.push(e)}}};return v.head?.clear(),S?.clear(),r.html=p(t=>(r.dispose=t,s(d),o({value:c,get children(){return l(S,()=>f({value:i,get children(){return u(v.head,()=>n(e(y),()=>a(_())))}}))}})()())),r},M=()=>void 0,N=new Promise((e,t)=>{M=t,D=setTimeout(()=>t(new i(`SSR_TIMEOUT`,`The stream did not finish within ${b} ms.`)),Math.min(b,r))}),P=()=>M(x?.reason??/* @__PURE__ */ Error(`The render was aborted.`));x?.addEventListener(`abort`,P,{once:!0});let F=()=>{clearTimeout(D),x?.removeEventListener(`abort`,P),T()};O=e=>{M(e),F()},N.catch(()=>void 0);try{if(x?.aborted)throw x.reason;let e=j();for(let t=1;e.held.length>0&&(await Promise.race([N,Promise.allSettled(e.held.map(e=>e.entry))]),e.held.some(e=>h.has(e.key)));t+=1){if(t>=10)throw new i(`SSR_BOUNDARY_WATERFALL`,`Resources kept holding the stream after 10 shell renders; flatten the data flow.`);e=j()}e.answered=!0,m(()=>{for(let t of e.caught)v.onCaughtError?.(t);for(let t of e.uncaught)v.onUncaughtError?.(t);v.onShellReady?.(e.html)}),A(e.boundaries.length>0?e.html+g(`window.$S=function(i,f){var t=document.getElementById("s:"+i);if(!t)return;if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){if(c.data==="[b:"+i){var d=1,n=c.nextSibling,e=null;while(n){if(n.nodeType===8){if(n.data.charAt(0)==="["){d++}else if(n.data==="]"){d--;if(d===0){e=n;break}}}n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};`,v.nonce):e.html);let t=()=>{for(let t of e.boundaries.splice(0))A(`<template id="s:${t.id}"></template>`+g(`$S(${JSON.stringify(t.id)},1)`,v.nonce))},n=0;for(;e.boundaries.length>0;){if(e.inFlight.size===0){t();break}let r=h.size;await Promise.race([N,Promise.race([...e.inFlight])]);let i=e.boundaries;e.boundaries=[];let a=!1;for(let e of i){let t=e.rebuild();t!==null&&(a=!0,A(`<template id="s:${e.id}">${t}</template>`+g(`$S(${JSON.stringify(e.id)})`,v.nonce)))}n=h.size===r&&!a?n+1:0,e.boundaries.length>0&&n>=2&&t()}let r={};for(let t of e.requested)h.has(t)&&Object.defineProperty(r,t,{value:h.get(t),enumerable:!0,writable:!0,configurable:!0});Object.keys(r).length>0&&A(`<script type="application/json" data-sh="${y}">${d(r)}<\/script>`),F(),E||c.close()}catch(e){F(),E||c.error(e)}},cancel(e){E=!0,O(e)}})}export{_ as renderToStream};
|
|
2
2
|
//# sourceMappingURL=stream.js.map
|