@shadow-js/web 1.0.6 → 1.1.1
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 +12 -0
- package/README.md +1 -1
- package/dist/dev/attributes.d.ts +1 -2
- package/dist/dev/autofocus.d.ts +1 -2
- package/dist/dev/class-style.d.ts +1 -2
- package/dist/dev/component.d.ts +1 -2
- package/dist/dev/control-flow/activity.d.ts +1 -2
- package/dist/dev/control-flow/client-only.d.ts +1 -2
- package/dist/dev/control-flow/dynamic.d.ts +1 -2
- package/dist/dev/control-flow/error-boundary.d.ts +1 -2
- package/dist/dev/control-flow/for.d.ts +1 -2
- package/dist/dev/control-flow/fragment.d.ts +1 -2
- package/dist/dev/control-flow/index-list.d.ts +1 -2
- package/dist/dev/control-flow/lazy.d.ts +1 -2
- package/dist/dev/control-flow/no-hydration.d.ts +1 -2
- package/dist/dev/control-flow/portal.d.ts +1 -2
- package/dist/dev/control-flow/portal.js.map +1 -1
- package/dist/dev/control-flow/root-errors.d.ts +2 -3
- package/dist/dev/control-flow/show.d.ts +1 -2
- package/dist/dev/control-flow/suspense-list.d.ts +2 -3
- package/dist/dev/control-flow/suspense.d.ts +1 -2
- package/dist/dev/control-flow/switch.d.ts +1 -2
- package/dist/dev/derived.d.ts +1 -2
- package/dist/dev/element.d.ts +1 -2
- package/dist/dev/events.d.ts +1 -2
- package/dist/dev/extend.d.ts +9 -0
- package/dist/dev/head/components.d.ts +1 -2
- package/dist/dev/head/server-head.d.ts +2 -3
- package/dist/dev/head/use-head.d.ts +1 -2
- package/dist/dev/head/validate.d.ts +1 -2
- package/dist/dev/hmr.d.ts +1 -2
- package/dist/dev/hmr.js.map +1 -1
- package/dist/dev/hydration.d.ts +1 -2
- package/dist/dev/insert.d.ts +1 -2
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/claim.d.ts +1 -2
- package/dist/dev/internal/diagnostics.d.ts +1 -2
- package/dist/dev/internal/hydration-hooks.d.ts +1 -2
- package/dist/dev/internal/hydration-scope.d.ts +1 -2
- package/dist/dev/internal/names.d.ts +1 -2
- package/dist/dev/internal/portal-context.d.ts +1 -2
- package/dist/dev/internal/reconcile.d.ts +1 -2
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/internal/stream-context.d.ts +1 -2
- package/dist/dev/jsx/aria.d.ts +7 -2
- package/dist/dev/jsx/component.d.ts +7 -2
- package/dist/dev/jsx/events.d.ts +1 -2
- package/dist/dev/jsx/global.d.ts +11 -2
- package/dist/dev/jsx/html.d.ts +8 -2
- package/dist/dev/jsx/intrinsic.d.ts +10 -2
- package/dist/dev/jsx/mathml.d.ts +8 -2
- package/dist/dev/jsx/svg.d.ts +13 -2
- package/dist/dev/jsx/types.d.ts +1 -2
- package/dist/dev/jsx-dev-runtime.d.ts +6 -0
- package/dist/dev/jsx-runtime.d.ts +13 -2
- package/dist/dev/reactive.d.ts +1 -2
- package/dist/dev/render.d.ts +1 -2
- package/dist/dev/resource-hints.d.ts +1 -2
- package/dist/dev/select-value.d.ts +1 -2
- package/dist/dev/server/attributes.d.ts +1 -2
- package/dist/dev/server/class-style.d.ts +1 -2
- package/dist/dev/server/component.d.ts +1 -2
- package/dist/dev/server/derived.d.ts +1 -2
- package/dist/dev/server/element.d.ts +1 -2
- package/dist/dev/server/errors.js.map +1 -1
- package/dist/dev/server/escape.d.ts +1 -2
- package/dist/dev/server/form-controls.d.ts +1 -2
- package/dist/dev/server/hydration-script.d.ts +1 -2
- package/dist/dev/server/index.d.ts +7 -2
- package/dist/dev/server/index.js +2 -2
- package/dist/dev/server/node.d.ts +1 -2
- package/dist/dev/server/node.js.map +1 -1
- package/dist/dev/server/portals.d.ts +1 -2
- package/dist/dev/server/portals.js.map +1 -1
- package/dist/dev/server/raw-text.d.ts +1 -2
- package/dist/dev/server/render.d.ts +1 -2
- package/dist/dev/server/serialize.d.ts +1 -2
- package/dist/dev/server/stream.d.ts +1 -2
- package/dist/dev/server/stream.js.map +1 -1
- package/dist/dev/server.d.ts +1 -0
- package/dist/dev/spread.d.ts +1 -2
- package/dist/dev/template.d.ts +1 -2
- package/dist/dev/view-transition.d.ts +1 -2
- package/dist/prod/attributes.js.map +1 -1
- package/dist/prod/autofocus.js.map +1 -1
- package/dist/prod/class-style.js.map +1 -1
- package/dist/prod/component.js.map +1 -1
- package/dist/prod/control-flow/activity.js.map +1 -1
- package/dist/prod/control-flow/branch.js.map +1 -1
- package/dist/prod/control-flow/client-only.js.map +1 -1
- package/dist/prod/control-flow/dynamic.js.map +1 -1
- package/dist/prod/control-flow/error-boundary.js.map +1 -1
- package/dist/prod/control-flow/for.js.map +1 -1
- package/dist/prod/control-flow/fragment.js.map +1 -1
- package/dist/prod/control-flow/hot-link.js.map +1 -1
- package/dist/prod/control-flow/index-list.js.map +1 -1
- package/dist/prod/control-flow/lazy.js.map +1 -1
- package/dist/prod/control-flow/no-hydration.js.map +1 -1
- package/dist/prod/control-flow/portal.js.map +1 -1
- package/dist/prod/control-flow/root-errors.js.map +1 -1
- package/dist/prod/control-flow/show.js.map +1 -1
- package/dist/prod/control-flow/suspense-list.js.map +1 -1
- package/dist/prod/control-flow/suspense.js.map +1 -1
- package/dist/prod/control-flow/switch.js.map +1 -1
- package/dist/prod/derived.js.map +1 -1
- package/dist/prod/element.js.map +1 -1
- package/dist/prod/events.js.map +1 -1
- package/dist/prod/head/components.js.map +1 -1
- package/dist/prod/head/registry.js.map +1 -1
- package/dist/prod/head/server-head.js.map +1 -1
- package/dist/prod/head/sink.js.map +1 -1
- package/dist/prod/head/use-head.js.map +1 -1
- package/dist/prod/head/validate.js.map +1 -1
- package/dist/prod/hmr.js.map +1 -1
- package/dist/prod/hydration.js.map +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/internal/accessor.js.map +1 -1
- package/dist/prod/internal/claim.js.map +1 -1
- package/dist/prod/internal/css-units.js.map +1 -1
- package/dist/prod/internal/diagnostics.js.map +1 -1
- package/dist/prod/internal/early-events.js.map +1 -1
- package/dist/prod/internal/hydration-hooks.js.map +1 -1
- package/dist/prod/internal/hydration-scope.js.map +1 -1
- package/dist/prod/internal/portal-context.js.map +1 -1
- package/dist/prod/internal/react-names.js.map +1 -1
- package/dist/prod/internal/reconcile.js.map +1 -1
- package/dist/prod/internal/stream-context.js.map +1 -1
- package/dist/prod/reactive.js.map +1 -1
- package/dist/prod/render.js.map +1 -1
- package/dist/prod/resource-hints.js.map +1 -1
- package/dist/prod/select-value.js.map +1 -1
- package/dist/prod/server/attributes.js.map +1 -1
- package/dist/prod/server/class-style.js.map +1 -1
- package/dist/prod/server/component.js.map +1 -1
- package/dist/prod/server/derived.js.map +1 -1
- package/dist/prod/server/element.js.map +1 -1
- package/dist/prod/server/errors.js.map +1 -1
- package/dist/prod/server/escape.js.map +1 -1
- package/dist/prod/server/form-controls.js.map +1 -1
- package/dist/prod/server/hydration-script.js.map +1 -1
- package/dist/prod/server/node.js.map +1 -1
- package/dist/prod/server/portals.js.map +1 -1
- package/dist/prod/server/raw-text.js.map +1 -1
- package/dist/prod/server/render.js.map +1 -1
- package/dist/prod/server/serialize.js.map +1 -1
- package/dist/prod/server/stream.js.map +1 -1
- package/dist/prod/spread.js.map +1 -1
- package/dist/prod/template.js.map +1 -1
- package/dist/prod/view-transition.js.map +1 -1
- package/dist/server/attributes.js.map +1 -1
- package/dist/server/autofocus.js.map +1 -1
- package/dist/server/class-style.js.map +1 -1
- package/dist/server/component.js.map +1 -1
- package/dist/server/control-flow/activity.js.map +1 -1
- package/dist/server/control-flow/branch.js.map +1 -1
- package/dist/server/control-flow/client-only.js.map +1 -1
- package/dist/server/control-flow/dynamic.js.map +1 -1
- package/dist/server/control-flow/error-boundary.js.map +1 -1
- package/dist/server/control-flow/for.js.map +1 -1
- package/dist/server/control-flow/fragment.js.map +1 -1
- package/dist/server/control-flow/index-list.js.map +1 -1
- package/dist/server/control-flow/lazy.js.map +1 -1
- package/dist/server/control-flow/no-hydration.js.map +1 -1
- package/dist/server/control-flow/portal.js.map +1 -1
- package/dist/server/control-flow/root-errors.js.map +1 -1
- package/dist/server/control-flow/show.js.map +1 -1
- package/dist/server/control-flow/suspense-list.js.map +1 -1
- package/dist/server/control-flow/suspense.js.map +1 -1
- package/dist/server/control-flow/switch.js.map +1 -1
- package/dist/server/derived.js.map +1 -1
- package/dist/server/element.js.map +1 -1
- package/dist/server/events.js.map +1 -1
- package/dist/server/head/components.js.map +1 -1
- package/dist/server/head/registry.js.map +1 -1
- package/dist/server/head/server-head.js.map +1 -1
- package/dist/server/head/sink.js.map +1 -1
- package/dist/server/head/use-head.js.map +1 -1
- package/dist/server/head/validate.js.map +1 -1
- package/dist/server/hydration.js.map +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/internal/accessor.js.map +1 -1
- package/dist/server/internal/claim.js.map +1 -1
- package/dist/server/internal/css-units.js.map +1 -1
- package/dist/server/internal/diagnostics.js.map +1 -1
- package/dist/server/internal/early-events.js.map +1 -1
- package/dist/server/internal/hydration-hooks.js.map +1 -1
- package/dist/server/internal/hydration-scope.js.map +1 -1
- package/dist/server/internal/portal-context.js.map +1 -1
- package/dist/server/internal/react-names.js.map +1 -1
- package/dist/server/internal/reconcile.js.map +1 -1
- package/dist/server/internal/stream-context.js.map +1 -1
- package/dist/server/reactive.js.map +1 -1
- package/dist/server/render.js.map +1 -1
- package/dist/server/resource-hints.js.map +1 -1
- package/dist/server/select-value.js.map +1 -1
- package/dist/server/server/attributes.js.map +1 -1
- package/dist/server/server/class-style.js.map +1 -1
- package/dist/server/server/component.js.map +1 -1
- package/dist/server/server/derived.js.map +1 -1
- package/dist/server/server/element.js.map +1 -1
- package/dist/server/server/errors.js.map +1 -1
- package/dist/server/server/escape.js.map +1 -1
- package/dist/server/server/form-controls.js.map +1 -1
- package/dist/server/server/hydration-script.js.map +1 -1
- package/dist/server/server/node.js.map +1 -1
- package/dist/server/server/portals.js.map +1 -1
- package/dist/server/server/raw-text.js.map +1 -1
- package/dist/server/server/render.js.map +1 -1
- package/dist/server/server/serialize.js.map +1 -1
- package/dist/server/server/stream.js.map +1 -1
- package/dist/server/spread.js.map +1 -1
- package/dist/server/template.js.map +1 -1
- package/dist/server/view-transition.js.map +1 -1
- package/dist/server-dev/control-flow/portal.js.map +1 -1
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/server/errors.js.map +1 -1
- package/dist/server-dev/server/index.js +2 -2
- package/dist/server-dev/server/node.js.map +1 -1
- package/dist/server-dev/server/portals.js.map +1 -1
- package/dist/server-dev/server/stream.js.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate.js","names":["HEAD_MARKER","HEAD_KEY","TAG_NAMES","ATTRIBUTE_NAME","RESERVED_ATTRIBUTES","FORBIDDEN_NAMES","META_IDENTITY_FIELDS","MULTI_VALUED_META","MULTI_LINK_RELS","RESOURCE_RELS","isHeadTagName","value","frame","parts","part","attributeText","attributesFrom","props","values","key","name","text","isUnsafeUrlAttribute","tag","textFrom","children","keyFrom","normalizeRel","raw","tokens","token","metaIdentity","media","lookup","field","linkIdentity","rel","identityOf","normalizeTag","input","normalizeTags","item","identityOfElement","element","attribute"],"sources":["../../../src/head/validate.ts"],"sourcesContent":["import { isUnsafeUrlAttribute, warnOnce } from \"../extend\";\n\n/**\n * Head elements the registry manages. `script` and `noscript` are refused: a head-registered\n * script would bypass CSP nonces and Trusted Types, so scripts come only from the asset pipeline.\n * @since 1.0.0\n */\nexport type HeadTagName = \"title\" | \"meta\" | \"link\" | \"style\" | \"base\";\n\n/**\n * One attribute value: a string is written as is, `true` as an empty attribute, `false` and\n * `undefined` omit it, and a number is written as text.\n * @since 1.0.0\n */\nexport type HeadAttributeValue = string | number | boolean | undefined;\n\n/**\n * Describes one head element. `key` identifies a `style` for replacement; other tags use their\n * own identity (see {@link useHead}).\n *\n * @example\n * import type { HeadTag } from \"@shadow-js/web\";\n *\n * const description: HeadTag = { tag: \"meta\", props: { name: \"description\", content: \"Docs\" } };\n * @since 1.0.0\n */\nexport interface HeadTag {\n /** The element to register: `title`, `meta`, `link`, `style` or `base`. Any other name throws. */\n readonly tag: HeadTagName;\n /**\n * The attributes of the element. Names are case-insensitive, must be valid attribute names, and\n * may not start with `on`.\n * @default undefined (the element has no attributes)\n */\n readonly props?: Readonly<Record<string, HeadAttributeValue>>;\n /**\n * The text of a `title` or `style`. Other tags take no text and throw when it is given.\n * @default undefined (no text)\n */\n readonly children?: string;\n /**\n * Identity of a `style`: a later style with the same key replaces an earlier one. Only `style`\n * takes a key.\n * @default undefined (the style has no identity and always stays)\n */\n readonly key?: string;\n}\n\n/**\n * What {@link useHead} accepts: one tag, several tags, or nothing (which registers nothing).\n * @since 1.0.0\n */\nexport type HeadInput = HeadTag | readonly HeadTag[] | null | undefined | false;\n\n/**\n * A validated tag: lower-case attribute names, the text it carries, and its identity. Produced\n * only by {@link normalizeTag}, so the registry and the DOM sink never see unchecked input.\n * @internal\n */\nexport interface NormalizedTag {\n readonly tag: HeadTagName;\n readonly attributes: ReadonlyArray<readonly [string, string]>;\n readonly text: string | undefined;\n readonly key: string | undefined;\n /** Identity that replaces earlier registrations; undefined for append-only tags. */\n readonly identity: string | undefined;\n}\n\n/** Marks every element the sink created or adopted. Callers may not supply it. @internal */\nexport const HEAD_MARKER = \"data-shadow-head\";\n/** Carries a style's key so a server-rendered style can be adopted. @internal */\nexport const HEAD_KEY = \"data-shadow-key\";\n\nconst TAG_NAMES: ReadonlySet<string> = new Set([\"title\", \"meta\", \"link\", \"style\", \"base\"]);\nconst ATTRIBUTE_NAME = /^[a-zA-Z_][a-zA-Z0-9_:.-]*$/;\nconst RESERVED_ATTRIBUTES: ReadonlySet<string> = new Set([HEAD_MARKER, HEAD_KEY]);\n/** Names skipped silently, as spread does: they would reach a prototype if written as keys. */\nconst FORBIDDEN_NAMES: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\nconst META_IDENTITY_FIELDS = [\"name\", \"property\", \"http-equiv\", \"charset\"] as const;\n/**\n * Properties that repeat by design (one tag per image, per tag, per locale). Their identity includes the content,\n * so every value stays; the others are last-wins. Sub-properties of an image (`og:image:width`) are single.\n * @since 1.0.0\n */\nconst MULTI_VALUED_META: ReadonlySet<string> = new Set([\n \"og:image\",\n \"og:video\",\n \"og:audio\",\n \"og:locale:alternate\",\n \"og:email\",\n \"og:phone_number\",\n \"og:fax_number\",\n \"article:tag\",\n \"article:author\",\n \"book:author\",\n \"book:tag\",\n \"music:album\",\n \"music:song\",\n \"music:musician\",\n \"music:creator\",\n \"video:actor\",\n \"video:director\",\n \"video:writer\",\n \"video:tag\",\n \"fb:admins\",\n \"twitter:image\",\n]);\n/** Links that repeat (alternates per language, authors, archives): their identity is every attribute. */\nconst MULTI_LINK_RELS: ReadonlySet<string> = new Set([\n \"alternate\",\n \"author\",\n \"archives\",\n \"assets\",\n \"bookmarks\",\n \"me\",\n \"apple-touch-startup-image\",\n]);\nconst RESOURCE_RELS: ReadonlySet<string> = new Set([\n \"preload\",\n \"modulepreload\",\n \"prefetch\",\n \"preconnect\",\n \"dns-prefetch\",\n \"stylesheet\",\n]);\n\n/** True for the tag names the registry manages. @internal */\nexport function isHeadTagName(value: string): value is HeadTagName {\n return TAG_NAMES.has(value);\n}\n\n/**\n * Length-prefixed identity: `[\"a|b\"]` and `[\"a\", \"b\"]` can never collide because every part\n * carries its own length.\n */\nfunction frame(parts: readonly string[]): string {\n return parts.map((part) => `${part.length}:${part}`).join(\"\");\n}\n\n/** Text of an attribute value, or undefined when the attribute is omitted. */\nfunction attributeText(value: unknown): string | undefined {\n if (value === undefined || value === null || value === false) return undefined;\n if (value === true) return \"\";\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return String(value);\n throw new TypeError(\n __DEV__\n ? \"ShadowJS head: attribute values must be strings, numbers or booleans.\"\n : \"SHADOW_HEAD_ATTRIBUTE_VALUE\",\n );\n}\n\n/**\n * Validates the props of one tag and returns its lower-case, de-duplicated attributes, in order. The\n * map is the lookup that the identity is built from, so it is built once per tag.\n */\nfunction attributesFrom(tag: HeadTagName, props: unknown): ReadonlyMap<string, string> {\n if (props === undefined || props === null) return new Map();\n if (typeof props !== \"object\" || Array.isArray(props)) {\n throw new TypeError(__DEV__ ? \"ShadowJS head: props must be an object.\" : \"SHADOW_HEAD_PROPS\");\n }\n const values = new Map<string, string>();\n for (const key of Object.keys(props)) {\n if (!ATTRIBUTE_NAME.test(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowJS head: \"${key}\" is not a valid attribute name.`\n : \"SHADOW_HEAD_ATTRIBUTE_NAME\",\n );\n }\n const name = key.toLowerCase();\n if (name.startsWith(\"on\")) {\n throw new TypeError(\n __DEV__\n ? `ShadowJS head: event attribute \"${key}\" is not allowed.`\n : \"SHADOW_HEAD_EVENT_ATTRIBUTE\",\n );\n }\n if (RESERVED_ATTRIBUTES.has(name)) {\n throw new TypeError(\n __DEV__ ? `ShadowJS head: \"${key}\" is reserved for the runtime.` : \"SHADOW_HEAD_RESERVED\",\n );\n }\n if (FORBIDDEN_NAMES.has(name)) continue;\n const text = attributeText(Reflect.get(props, key));\n if (text === undefined) continue;\n if (isUnsafeUrlAttribute(name, text)) {\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Dropped the unsafe \"${name}\" value of a <${tag}> head tag.`);\n continue;\n }\n values.set(name, text);\n }\n return values;\n}\n\n/** Children text: title and style only, and only as a string. */\nfunction textFrom(tag: HeadTagName, children: unknown): string | undefined {\n if (children === undefined || children === null) return undefined;\n if (tag !== \"title\" && tag !== \"style\") {\n throw new TypeError(\n __DEV__ ? `ShadowJS head: <${tag}> takes no children.` : \"SHADOW_HEAD_NO_CHILDREN\",\n );\n }\n if (typeof children !== \"string\")\n throw new TypeError(__DEV__ ? \"ShadowJS head: children must be text.\" : \"SHADOW_HEAD_TEXT\");\n return children;\n}\n\n/** The key of a style. Only style takes one. */\nfunction keyFrom(tag: HeadTagName, key: unknown): string | undefined {\n if (key === undefined || key === null) return undefined;\n if (tag !== \"style\")\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: only <style> takes a key.\" : \"SHADOW_HEAD_STYLE_KEY\",\n );\n if (typeof key !== \"string\" || key === \"\") {\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: a key must be a non-empty string.\" : \"SHADOW_HEAD_KEY\",\n );\n }\n return key;\n}\n\n/** Rel tokens, lower-cased and sorted, so `\"ICON apple\"` and `\"apple icon\"` compare equal. */\nfunction normalizeRel(raw: string | undefined): string | undefined {\n if (raw === undefined) return undefined;\n const tokens = raw\n .toLowerCase()\n .split(/\\s+/)\n .filter((token) => token !== \"\");\n if (tokens.length === 0) return undefined;\n return tokens.sort().join(\" \");\n}\n\n/** Identity of a meta: its first identifying field and the media query. */\nfunction metaIdentity(lookup: ReadonlyMap<string, string>): string | undefined {\n const media = lookup.get(\"media\") ?? \"\";\n for (const field of META_IDENTITY_FIELDS) {\n const value = lookup.get(field);\n if (value === undefined) continue;\n // A document has one charset, whatever its value: that meta is a singleton.\n if (field === \"charset\") return frame([\"meta\", field]);\n if (MULTI_VALUED_META.has(value))\n return frame([\"meta\", field, value, media, lookup.get(\"content\") ?? \"\"]);\n return frame([\"meta\", field, value, media]);\n }\n return undefined;\n}\n\n/** Identity of a link: icons by rel, sizes and type; preloads and stylesheets by rel, href and as. */\nfunction linkIdentity(lookup: ReadonlyMap<string, string>): string | undefined {\n const rel = normalizeRel(lookup.get(\"rel\"));\n if (rel === undefined) return undefined;\n const isIcon = rel.split(\" \").some((token) => token === \"icon\" || token.endsWith(\"-icon\"));\n if (isIcon) {\n return frame([\"link\", \"icon\", rel, lookup.get(\"sizes\") ?? \"\", lookup.get(\"type\") ?? \"\"]);\n }\n // A document has one canonical URL: a singleton, so a new value replaces the old element (and a server's\n // copy is adopted) instead of a second `<link rel=\"canonical\">` being appended.\n if (rel === \"canonical\") return frame([\"link\", \"canonical\"]);\n if (RESOURCE_RELS.has(rel)) {\n return frame([\"link\", \"resource\", rel, lookup.get(\"href\") ?? \"\", lookup.get(\"as\") ?? \"\"]);\n }\n if (MULTI_LINK_RELS.has(rel)) {\n return frame([\n \"link\",\n \"multi\",\n rel,\n lookup.get(\"href\") ?? \"\",\n lookup.get(\"hreflang\") ?? \"\",\n lookup.get(\"media\") ?? \"\",\n lookup.get(\"type\") ?? \"\",\n ]);\n }\n return undefined;\n}\n\n/** Identity of a validated tag, or undefined when the tag is append-only. @internal */\nexport function identityOf(\n tag: HeadTagName,\n lookup: ReadonlyMap<string, string>,\n key: string | undefined,\n): string | undefined {\n if (tag === \"title\") return frame([\"title\"]);\n if (tag === \"base\") return frame([\"base\"]);\n if (tag === \"style\") return key === undefined ? undefined : frame([\"style\", key]);\n return tag === \"meta\" ? metaIdentity(lookup) : linkIdentity(lookup);\n}\n\n/**\n * Validates one head tag description and computes its identity. Hostile input throws a\n * TypeError: an unknown tag (including `script`), a bad attribute name, an event attribute, a\n * reserved marker, children on a void tag, or a key on anything but a style. An unsafe URL\n * attribute is dropped with a dev warning, the same way `setAttribute` treats it.\n *\n * @param input The description, usually a {@link HeadTag}; any value is checked.\n * @returns The normalized tag.\n * @throws TypeError for every invalid input listed above.\n * @internal\n * @since 1.0.0\n */\nexport function normalizeTag(input: unknown): NormalizedTag {\n if (input === null || typeof input !== \"object\" || Array.isArray(input)) {\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: a head tag must be an object.\" : \"SHADOW_HEAD_TAG\",\n );\n }\n const name = Reflect.get(input, \"tag\");\n if (typeof name !== \"string\" || !isHeadTagName(name)) {\n const shown = typeof name === \"string\" ? name : typeof name;\n throw new TypeError(\n __DEV__ ? `ShadowJS head: unsupported tag \"${shown}\".` : \"SHADOW_HEAD_TAG_NAME\",\n );\n }\n const lookup = attributesFrom(name, Reflect.get(input, \"props\"));\n const text = textFrom(name, Reflect.get(input, \"children\"));\n const key = keyFrom(name, Reflect.get(input, \"key\"));\n return {\n tag: name,\n attributes: [...lookup],\n text,\n key,\n identity: identityOf(name, lookup, key),\n };\n}\n\n/**\n * Normalizes what {@link useHead} receives: one description, a list, or nothing.\n *\n * @param input A description, a list of them, or null, undefined or false for none.\n * @returns The normalized tags, in order.\n * @throws TypeError when any description is invalid: an unknown tag (including `script`), an\n * attribute name that is not valid or starts with `on`, a reserved marker attribute, an attribute\n * value that is not a string, number or boolean, children on a tag other than `title` and `style`,\n * or a key on anything but a `style`. The production messages start with `SHADOW_HEAD_`.\n * @example\n * import { normalizeTags } from \"@shadow-js/web/server\";\n *\n * const tags = normalizeTags([\n * { tag: \"title\", children: \"A\" },\n * { tag: \"base\", props: { href: \"/\" } },\n * ]);\n * console.log(tags.length); // 2\n * @see useHead\n * @since 1.0.0\n */\nexport function normalizeTags(input: unknown): NormalizedTag[] {\n if (input === null || input === undefined || input === false) return [];\n if (Array.isArray(input)) return input.map((item: unknown) => normalizeTag(item));\n return [normalizeTag(input)];\n}\n\n/**\n * The identity of an element already in the document, computed the same way as for a\n * registration, so the sink can adopt a server-rendered element. Undefined for elements that are\n * not head tags or that are append-only.\n * @internal\n */\nexport function identityOfElement(element: Element): string | undefined {\n const name = element.localName;\n if (!isHeadTagName(name)) return undefined;\n const lookup = new Map<string, string>();\n for (const attribute of Array.from(element.attributes)) {\n if (attribute.name === HEAD_MARKER || attribute.name === HEAD_KEY) continue;\n lookup.set(attribute.name.toLowerCase(), attribute.value);\n }\n const key = element.getAttribute(HEAD_KEY) ?? undefined;\n return identityOf(name, lookup, key);\n}\n"],"mappings":"A,2FAqEA,MAAaA,EAAc,mBAEdC,EAAW,kBAElBC,kBAAiC,IAAI,IAAI,CAAC,QAAS,OAAQ,OAAQ,QAAS,MAAM,CAAC,EACnFC,EAAiB,8BACjBC,kBAA2C,IAAI,IAAI,CAACJ,EAAaC,CAAQ,CAAC,EAE1EI,kBAAuC,IAAI,IAAI,CAAC,YAAa,cAAe,WAAW,CAAC,EACxFC,EAAuB,CAAC,OAAQ,WAAY,aAAc,SAAS,EAMnEC,kBAAyC,I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D,sBAC3D,EAEF,IAAMa,EAASjB,EAAeI,EAAM,QAAQ,IAAImB,EAAO,OAAO,CAAC,EACzDlB,EAAOG,EAASJ,EAAM,QAAQ,IAAImB,EAAO,UAAU,CAAC,EACpDpB,EAAMO,EAAQN,EAAM,QAAQ,IAAImB,EAAO,KAAK,CAAC,EACnD,MAAO,CACL,IAAKnB,EACL,WAAY,CAAC,GAAGa,CAAM,EACtB,OACA,MACA,SAAUI,EAAWjB,EAAMa,EAAQd,CAAG,CACxC,CACF,CAsBA,SAAgBqB,EAAc,EAAiC,CAG7D,OAFID,GAAU,MAA+BA,IAAU,GAAc,CAAC,EAClE,MAAM,QAAQA,CAAK,EAAUA,EAAM,IAAK,GAAkBD,EAAaG,CAAI,CAAC,EACzE,CAACH,EAAaC,CAAK,CAAC,CAC7B,CAQA,SAAgBG,EAAkB,EAAsC,CACtE,IAAMtB,EAAOuB,EAAQ,UACrB,GAAI,CAACjC,EAAcU,CAAI,EAAG,OAC1B,IAAMa,kBAAS,IAAI,IACnB,IAAK,IAAMW,KAAa,MAAM,KAAKD,EAAQ,UAAU,EAC/CC,EAAU,OAAA,oBAAwBA,EAAU,OAAA,mBAChDX,EAAO,IAAIW,EAAU,KAAK,YAAY,EAAGA,EAAU,KAAK,EAG1D,OAAOP,EAAWjB,EAAMa,EADZU,EAAQ,aAAA,iBAAqB,GAAK,IAAA,EACX,CACrC,C"}
|
|
1
|
+
{"version":3,"file":"validate.js","names":["isUnsafeUrlAttribute","HEAD_MARKER","HEAD_KEY","TAG_NAMES","ATTRIBUTE_NAME","RESERVED_ATTRIBUTES","FORBIDDEN_NAMES","META_IDENTITY_FIELDS","MULTI_VALUED_META","MULTI_LINK_RELS","RESOURCE_RELS","isHeadTagName","value","frame","parts","part","attributeText","attributesFrom","tag","props","values","key","name","text","textFrom","children","keyFrom","normalizeRel","raw","tokens","token","metaIdentity","lookup","media","field","linkIdentity","rel","identityOf","normalizeTag","input","normalizeTags","item","identityOfElement","element","attribute"],"sources":["../../../src/head/validate.ts"],"sourcesContent":["import { isUnsafeUrlAttribute, warnOnce } from \"../extend\";\n\n/**\n * Head elements the registry manages. `script` and `noscript` are refused: a head-registered\n * script would bypass CSP nonces and Trusted Types, so scripts come only from the asset pipeline.\n * @since 1.0.0\n */\nexport type HeadTagName = \"title\" | \"meta\" | \"link\" | \"style\" | \"base\";\n\n/**\n * One attribute value: a string is written as is, `true` as an empty attribute, `false` and\n * `undefined` omit it, and a number is written as text.\n * @since 1.0.0\n */\nexport type HeadAttributeValue = string | number | boolean | undefined;\n\n/**\n * Describes one head element. `key` identifies a `style` for replacement; other tags use their\n * own identity (see {@link useHead}).\n *\n * @example\n * import type { HeadTag } from \"@shadow-js/web\";\n *\n * const description: HeadTag = { tag: \"meta\", props: { name: \"description\", content: \"Docs\" } };\n * @since 1.0.0\n */\nexport interface HeadTag {\n /** The element to register: `title`, `meta`, `link`, `style` or `base`. Any other name throws. */\n readonly tag: HeadTagName;\n /**\n * The attributes of the element. Names are case-insensitive, must be valid attribute names, and\n * may not start with `on`.\n * @default undefined (the element has no attributes)\n */\n readonly props?: Readonly<Record<string, HeadAttributeValue>>;\n /**\n * The text of a `title` or `style`. Other tags take no text and throw when it is given.\n * @default undefined (no text)\n */\n readonly children?: string;\n /**\n * Identity of a `style`: a later style with the same key replaces an earlier one. Only `style`\n * takes a key.\n * @default undefined (the style has no identity and always stays)\n */\n readonly key?: string;\n}\n\n/**\n * What {@link useHead} accepts: one tag, several tags, or nothing (which registers nothing).\n * @since 1.0.0\n */\nexport type HeadInput = HeadTag | readonly HeadTag[] | null | undefined | false;\n\n/**\n * A validated tag: lower-case attribute names, the text it carries, and its identity. Produced\n * only by {@link normalizeTag}, so the registry and the DOM sink never see unchecked input.\n * @internal\n */\nexport interface NormalizedTag {\n readonly tag: HeadTagName;\n readonly attributes: ReadonlyArray<readonly [string, string]>;\n readonly text: string | undefined;\n readonly key: string | undefined;\n /** Identity that replaces earlier registrations; undefined for append-only tags. */\n readonly identity: string | undefined;\n}\n\n/** Marks every element the sink created or adopted. Callers may not supply it. @internal */\nexport const HEAD_MARKER = \"data-shadow-head\";\n/** Carries a style's key so a server-rendered style can be adopted. @internal */\nexport const HEAD_KEY = \"data-shadow-key\";\n\nconst TAG_NAMES: ReadonlySet<string> = new Set([\"title\", \"meta\", \"link\", \"style\", \"base\"]);\nconst ATTRIBUTE_NAME = /^[a-zA-Z_][a-zA-Z0-9_:.-]*$/;\nconst RESERVED_ATTRIBUTES: ReadonlySet<string> = new Set([HEAD_MARKER, HEAD_KEY]);\n/** Names skipped silently, as spread does: they would reach a prototype if written as keys. */\nconst FORBIDDEN_NAMES: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\nconst META_IDENTITY_FIELDS = [\"name\", \"property\", \"http-equiv\", \"charset\"] as const;\n/**\n * Properties that repeat by design (one tag per image, per tag, per locale). Their identity includes the content,\n * so every value stays; the others are last-wins. Sub-properties of an image (`og:image:width`) are single.\n * @since 1.0.0\n */\nconst MULTI_VALUED_META: ReadonlySet<string> = new Set([\n \"og:image\",\n \"og:video\",\n \"og:audio\",\n \"og:locale:alternate\",\n \"og:email\",\n \"og:phone_number\",\n \"og:fax_number\",\n \"article:tag\",\n \"article:author\",\n \"book:author\",\n \"book:tag\",\n \"music:album\",\n \"music:song\",\n \"music:musician\",\n \"music:creator\",\n \"video:actor\",\n \"video:director\",\n \"video:writer\",\n \"video:tag\",\n \"fb:admins\",\n \"twitter:image\",\n]);\n/** Links that repeat (alternates per language, authors, archives): their identity is every attribute. */\nconst MULTI_LINK_RELS: ReadonlySet<string> = new Set([\n \"alternate\",\n \"author\",\n \"archives\",\n \"assets\",\n \"bookmarks\",\n \"me\",\n \"apple-touch-startup-image\",\n]);\nconst RESOURCE_RELS: ReadonlySet<string> = new Set([\n \"preload\",\n \"modulepreload\",\n \"prefetch\",\n \"preconnect\",\n \"dns-prefetch\",\n \"stylesheet\",\n]);\n\n/** True for the tag names the registry manages. @internal */\nexport function isHeadTagName(value: string): value is HeadTagName {\n return TAG_NAMES.has(value);\n}\n\n/**\n * Length-prefixed identity: `[\"a|b\"]` and `[\"a\", \"b\"]` can never collide because every part\n * carries its own length.\n */\nfunction frame(parts: readonly string[]): string {\n return parts.map((part) => `${part.length}:${part}`).join(\"\");\n}\n\n/** Text of an attribute value, or undefined when the attribute is omitted. */\nfunction attributeText(value: unknown): string | undefined {\n if (value === undefined || value === null || value === false) return undefined;\n if (value === true) return \"\";\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return String(value);\n throw new TypeError(\n __DEV__\n ? \"ShadowJS head: attribute values must be strings, numbers or booleans.\"\n : \"SHADOW_HEAD_ATTRIBUTE_VALUE\",\n );\n}\n\n/**\n * Validates the props of one tag and returns its lower-case, de-duplicated attributes, in order. The\n * map is the lookup that the identity is built from, so it is built once per tag.\n */\nfunction attributesFrom(tag: HeadTagName, props: unknown): ReadonlyMap<string, string> {\n if (props === undefined || props === null) return new Map();\n if (typeof props !== \"object\" || Array.isArray(props)) {\n throw new TypeError(__DEV__ ? \"ShadowJS head: props must be an object.\" : \"SHADOW_HEAD_PROPS\");\n }\n const values = new Map<string, string>();\n for (const key of Object.keys(props)) {\n if (!ATTRIBUTE_NAME.test(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowJS head: \"${key}\" is not a valid attribute name.`\n : \"SHADOW_HEAD_ATTRIBUTE_NAME\",\n );\n }\n const name = key.toLowerCase();\n if (name.startsWith(\"on\")) {\n throw new TypeError(\n __DEV__\n ? `ShadowJS head: event attribute \"${key}\" is not allowed.`\n : \"SHADOW_HEAD_EVENT_ATTRIBUTE\",\n );\n }\n if (RESERVED_ATTRIBUTES.has(name)) {\n throw new TypeError(\n __DEV__ ? `ShadowJS head: \"${key}\" is reserved for the runtime.` : \"SHADOW_HEAD_RESERVED\",\n );\n }\n if (FORBIDDEN_NAMES.has(name)) continue;\n const text = attributeText(Reflect.get(props, key));\n if (text === undefined) continue;\n if (isUnsafeUrlAttribute(name, text)) {\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Dropped the unsafe \"${name}\" value of a <${tag}> head tag.`);\n continue;\n }\n values.set(name, text);\n }\n return values;\n}\n\n/** Children text: title and style only, and only as a string. */\nfunction textFrom(tag: HeadTagName, children: unknown): string | undefined {\n if (children === undefined || children === null) return undefined;\n if (tag !== \"title\" && tag !== \"style\") {\n throw new TypeError(\n __DEV__ ? `ShadowJS head: <${tag}> takes no children.` : \"SHADOW_HEAD_NO_CHILDREN\",\n );\n }\n if (typeof children !== \"string\")\n throw new TypeError(__DEV__ ? \"ShadowJS head: children must be text.\" : \"SHADOW_HEAD_TEXT\");\n return children;\n}\n\n/** The key of a style. Only style takes one. */\nfunction keyFrom(tag: HeadTagName, key: unknown): string | undefined {\n if (key === undefined || key === null) return undefined;\n if (tag !== \"style\")\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: only <style> takes a key.\" : \"SHADOW_HEAD_STYLE_KEY\",\n );\n if (typeof key !== \"string\" || key === \"\") {\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: a key must be a non-empty string.\" : \"SHADOW_HEAD_KEY\",\n );\n }\n return key;\n}\n\n/** Rel tokens, lower-cased and sorted, so `\"ICON apple\"` and `\"apple icon\"` compare equal. */\nfunction normalizeRel(raw: string | undefined): string | undefined {\n if (raw === undefined) return undefined;\n const tokens = raw\n .toLowerCase()\n .split(/\\s+/)\n .filter((token) => token !== \"\");\n if (tokens.length === 0) return undefined;\n return tokens.sort().join(\" \");\n}\n\n/** Identity of a meta: its first identifying field and the media query. */\nfunction metaIdentity(lookup: ReadonlyMap<string, string>): string | undefined {\n const media = lookup.get(\"media\") ?? \"\";\n for (const field of META_IDENTITY_FIELDS) {\n const value = lookup.get(field);\n if (value === undefined) continue;\n // A document has one charset, whatever its value: that meta is a singleton.\n if (field === \"charset\") return frame([\"meta\", field]);\n if (MULTI_VALUED_META.has(value))\n return frame([\"meta\", field, value, media, lookup.get(\"content\") ?? \"\"]);\n return frame([\"meta\", field, value, media]);\n }\n return undefined;\n}\n\n/** Identity of a link: icons by rel, sizes and type; preloads and stylesheets by rel, href and as. */\nfunction linkIdentity(lookup: ReadonlyMap<string, string>): string | undefined {\n const rel = normalizeRel(lookup.get(\"rel\"));\n if (rel === undefined) return undefined;\n const isIcon = rel.split(\" \").some((token) => token === \"icon\" || token.endsWith(\"-icon\"));\n if (isIcon) {\n return frame([\"link\", \"icon\", rel, lookup.get(\"sizes\") ?? \"\", lookup.get(\"type\") ?? \"\"]);\n }\n // A document has one canonical URL: a singleton, so a new value replaces the old element (and a server's\n // copy is adopted) instead of a second `<link rel=\"canonical\">` being appended.\n if (rel === \"canonical\") return frame([\"link\", \"canonical\"]);\n if (RESOURCE_RELS.has(rel)) {\n return frame([\"link\", \"resource\", rel, lookup.get(\"href\") ?? \"\", lookup.get(\"as\") ?? \"\"]);\n }\n if (MULTI_LINK_RELS.has(rel)) {\n return frame([\n \"link\",\n \"multi\",\n rel,\n lookup.get(\"href\") ?? \"\",\n lookup.get(\"hreflang\") ?? \"\",\n lookup.get(\"media\") ?? \"\",\n lookup.get(\"type\") ?? \"\",\n ]);\n }\n return undefined;\n}\n\n/** Identity of a validated tag, or undefined when the tag is append-only. @internal */\nexport function identityOf(\n tag: HeadTagName,\n lookup: ReadonlyMap<string, string>,\n key: string | undefined,\n): string | undefined {\n if (tag === \"title\") return frame([\"title\"]);\n if (tag === \"base\") return frame([\"base\"]);\n if (tag === \"style\") return key === undefined ? undefined : frame([\"style\", key]);\n return tag === \"meta\" ? metaIdentity(lookup) : linkIdentity(lookup);\n}\n\n/**\n * Validates one head tag description and computes its identity. Hostile input throws a\n * TypeError: an unknown tag (including `script`), a bad attribute name, an event attribute, a\n * reserved marker, children on a void tag, or a key on anything but a style. An unsafe URL\n * attribute is dropped with a dev warning, the same way `setAttribute` treats it.\n *\n * @param input The description, usually a {@link HeadTag}; any value is checked.\n * @returns The normalized tag.\n * @throws TypeError for every invalid input listed above.\n * @internal\n * @since 1.0.0\n */\nexport function normalizeTag(input: unknown): NormalizedTag {\n if (input === null || typeof input !== \"object\" || Array.isArray(input)) {\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: a head tag must be an object.\" : \"SHADOW_HEAD_TAG\",\n );\n }\n const name = Reflect.get(input, \"tag\");\n if (typeof name !== \"string\" || !isHeadTagName(name)) {\n const shown = typeof name === \"string\" ? name : typeof name;\n throw new TypeError(\n __DEV__ ? `ShadowJS head: unsupported tag \"${shown}\".` : \"SHADOW_HEAD_TAG_NAME\",\n );\n }\n const lookup = attributesFrom(name, Reflect.get(input, \"props\"));\n const text = textFrom(name, Reflect.get(input, \"children\"));\n const key = keyFrom(name, Reflect.get(input, \"key\"));\n return {\n tag: name,\n attributes: [...lookup],\n text,\n key,\n identity: identityOf(name, lookup, key),\n };\n}\n\n/**\n * Normalizes what {@link useHead} receives: one description, a list, or nothing.\n *\n * @param input A description, a list of them, or null, undefined or false for none.\n * @returns The normalized tags, in order.\n * @throws TypeError when any description is invalid: an unknown tag (including `script`), an\n * attribute name that is not valid or starts with `on`, a reserved marker attribute, an attribute\n * value that is not a string, number or boolean, children on a tag other than `title` and `style`,\n * or a key on anything but a `style`. The production messages start with `SHADOW_HEAD_`.\n * @example\n * import { normalizeTags } from \"@shadow-js/web/server\";\n *\n * const tags = normalizeTags([\n * { tag: \"title\", children: \"A\" },\n * { tag: \"base\", props: { href: \"/\" } },\n * ]);\n * console.log(tags.length); // 2\n * @see useHead\n * @since 1.0.0\n */\nexport function normalizeTags(input: unknown): NormalizedTag[] {\n if (input === null || input === undefined || input === false) return [];\n if (Array.isArray(input)) return input.map((item: unknown) => normalizeTag(item));\n return [normalizeTag(input)];\n}\n\n/**\n * The identity of an element already in the document, computed the same way as for a\n * registration, so the sink can adopt a server-rendered element. Undefined for elements that are\n * not head tags or that are append-only.\n * @internal\n */\nexport function identityOfElement(element: Element): string | undefined {\n const name = element.localName;\n if (!isHeadTagName(name)) return undefined;\n const lookup = new Map<string, string>();\n for (const attribute of Array.from(element.attributes)) {\n if (attribute.name === HEAD_MARKER || attribute.name === HEAD_KEY) continue;\n lookup.set(attribute.name.toLowerCase(), attribute.value);\n }\n const key = element.getAttribute(HEAD_KEY) ?? undefined;\n return identityOf(name, lookup, key);\n}\n"],"mappings":"A,2FAqEA,MAAaC,EAAc,mBAEdC,EAAW,kBAElBC,kBAAiC,IAAI,IAAI,CAAC,QAAS,OAAQ,OAAQ,QAAS,MAAM,CAAC,EACnFC,EAAiB,8BACjBC,kBAA2C,IAAI,IAAI,CAACJ,EAAaC,CAAQ,CAAC,EAE1EI,kBAAuC,IAAI,IAAI,CAAC,YAAa,cAAe,WAAW,CAAC,EACxFC,EAAuB,CAAC,OAAQ,WAAY,aAAc,SAAS,EAMnEC,kBAAyC,IAAI,IAAI,CACrD,WACA,WACA,WACA,sBACA,WACA,kBACA,gBACA,cACA,iBACA,cACA,WACA,cACA,aACA,iBACA,gBACA,cACA,iBACA,eACA,YACA,YACA,eACF,CAAC,EAEKC,kBAAuC,IAAI,IAAI,CACnD,YACA,SACA,WACA,SACA,YACA,KACA,2BACF,CAAC,EACKC,kBAAqC,IAAI,IAAI,CACjD,UACA,gBACA,WACA,aACA,eACA,YACF,CAAC,EAGD,SAAgBC,EAAcC,EAAqC,CACjE,OAAOT,EAAU,IAAIS,CAAK,CAC5B,CAMA,SAASC,EAAMC,EAAkC,CAC/C,OAAOA,EAAM,IAAKC,GAAS,GAAGA,EAAK,OAAO,GAAGA,GAAM,CAAC,CAAC,KAAK,EAAE,CAC9D,CAGA,SAASC,EAAcJ,EAAoC,CACzD,GAAIA,GAAiC,MAAQA,IAAU,GACvD,IAAIA,IAAU,GAAM,MAAO,GAC3B,GAAI,OAAOA,GAAU,SAAU,OAAOA,EACtC,GAAI,OAAOA,GAAU,SAAU,OAAO,OAAOA,CAAK,EAClD,MAAU,UAGJ,6BACN,CAP2B,CAQ7B,CAMA,SAASK,EAAeC,EAAkBC,EAA6C,CACrF,GAAIA,GAAiC,KAAM,sBAAO,IAAI,IACtD,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AO,IAAIY,EAAU,KAAK,YAAY,EAAGA,EAAU,KAAK,EAG1D,OAAOP,EAAWf,EAAMU,EADZW,EAAQ,aAAA,iBAAqB,GAAK,IAAA,EACX,CACrC,C"}
|
package/dist/prod/hmr.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hmr.js","names":["
|
|
1
|
+
{"version":3,"file":"hmr.js","names":["hotModulesOf","batch","getOwner","untrack","useSignal","createComputation","readComputation","REGISTRY_KEY","ModuleRegistry","managed","listening","entry","listener","registry","hot","_id","previous","created","data","component","reg","name","implementation","existing","version","setVersion","n","proxy","props","node","accept"],"sources":["../../src/hmr.ts"],"sourcesContent":["import { batch, getOwner, untrack, useSignal } from \"@shadow-js/core\";\nimport { createComputation, readComputation } from \"@shadow-js/core/extend\";\nimport { hotModulesOf } from \"./control-flow/hot-link\";\n\n/**\n * The subset of Vite's `import.meta.hot` the runtime uses. The compiled output passes\n * `import.meta.hot` to `registry`, so any object with these three members works (a test runner can\n * supply its own).\n * @since 1.0.0\n */\nexport interface HotContext {\n /** Data kept across hot updates of the module: values stored in a `dispose` callback arrive here. */\n readonly data: Record<string, unknown>;\n /** Declares that the module accepts its own update, so the page is not reloaded. */\n accept(): void;\n /** Registers a callback that runs before the module is replaced and may store values in `data`. */\n dispose(callback: (data: Record<string, unknown>) => void): void;\n}\n\ntype ComponentFunction = (props: never) => unknown;\n\ninterface Entry {\n implementation: ComponentFunction;\n readonly version: () => number;\n readonly bump: () => void;\n readonly proxy: ComponentFunction;\n dirty: boolean;\n}\n\nconst REGISTRY_KEY = \"shadowjs:hmr-registry\";\n\n/**\n * The components of one module, kept across hot updates. Instances are created through a stable\n * proxy that follows the current implementation, so an edit re-renders only the edited component's\n * instances; parents and siblings keep their state. Produced by `registry`; the compiled output\n * of a development build is its only user.\n *\n * @example\n * import { type HotContext, registry } from \"@shadow-js/web/hmr\";\n *\n * declare const hot: HotContext | undefined;\n * const modules = registry(hot, \"src/app.tsx\");\n * console.log(modules.managed); // false when there is no hot context (production, server)\n * @see registry\n * @since 1.0.0\n */\nexport class ModuleRegistry {\n /** The components of the module by name, each with the proxy instances are created through. */\n readonly entries: Map<string, Entry> = new Map<string, Entry>();\n /** True when the module can hot update (a hot context was given); false makes the registry inert. */\n readonly managed: boolean;\n /**\n * Told after each update of this module, once its components are re-rendered. An error boundary\n * that shows its fallback listens here, so the edit that fixes its error rebuilds its children.\n */\n readonly listeners: Set<() => void> = new Set<() => void>();\n\n /**\n * Creates an empty registry.\n *\n * @param managed Whether the module can hot update. When false, `component` returns each\n * implementation unchanged.\n */\n constructor(managed: boolean) {\n this.managed = managed;\n }\n\n /**\n * Re-renders every instance of the components replaced during the last module evaluation, then tells\n * the listeners. The listeners are read before the re-render: a boundary that starts listening because\n * this very update failed is not reset by it.\n */\n commit(): void {\n const listening = [...this.listeners];\n batch(() => {\n for (const entry of this.entries.values()) {\n if (!entry.dirty) continue;\n entry.dirty = false;\n entry.bump();\n }\n });\n for (const listener of listening) listener();\n }\n}\n\n/**\n * Returns the registry of the module identified by `hot`, reusing the one from the previous\n * evaluation of the same module. Without `hot` (production, server) the registry is inert.\n * @internal\n */\nexport function registry(hot: HotContext | undefined, _id: string): ModuleRegistry {\n // A test runner may define `import.meta.hot` without a `data` bag: nothing can hot update there.\n if (hot === undefined || typeof hot.data !== \"object\" || hot.data === null) {\n return new ModuleRegistry(false);\n }\n const previous = hot.data[REGISTRY_KEY];\n if (previous instanceof ModuleRegistry) return previous;\n const created = new ModuleRegistry(true);\n hot.dispose((data) => {\n data[REGISTRY_KEY] = created;\n });\n return created;\n}\n\n/**\n * Registers a component implementation and returns the function to use in its place. On the first\n * evaluation that is a proxy; on later evaluations the same proxy, now backed by the new code.\n * @internal\n */\nexport function component<P>(\n reg: ModuleRegistry,\n name: string,\n implementation: (props: P) => unknown,\n): (props: P) => unknown {\n if (!reg.managed) return implementation;\n const existing = reg.entries.get(name);\n if (existing !== undefined) {\n existing.implementation = implementation as ComponentFunction;\n existing.dirty = true;\n return existing.proxy as (props: P) => unknown;\n }\n const [version, setVersion] = useSignal(0);\n const entry: Entry = {\n implementation: implementation as ComponentFunction,\n version,\n bump: () => {\n setVersion((n) => n + 1);\n },\n proxy: undefined as unknown as ComponentFunction,\n dirty: false,\n };\n const proxy = (props: P): (() => unknown) => {\n // The error boundary above this instance (if any) learns that its children come from this module.\n hotModulesOf(getOwner())?.add(reg);\n // A memo per instance: an update re-renders this component only, not the arrays or regions\n // that merely contain it. It runs component setup, which may write state it owns.\n const node = createComputation({\n kind: \"memo\",\n allowWrites: true,\n fn: () => {\n entry.version();\n return untrack(() => (entry.implementation as (props: P) => unknown)(props));\n },\n });\n return () => readComputation<unknown>(node);\n };\n Object.defineProperty(proxy, \"name\", { value: name });\n (entry as { proxy: ComponentFunction }).proxy = proxy as unknown as ComponentFunction;\n reg.entries.set(name, entry);\n return proxy;\n}\n\n/**\n * Marks the module as able to update itself and applies the replaced components.\n * @internal\n */\nexport function accept(hot: HotContext | undefined, reg: ModuleRegistry): void {\n if (hot === undefined || !reg.managed) return;\n hot.accept();\n reg.commit();\n}\n"],"mappings":"A,4NA6BA,MAAMO,EAAe,wBAiBrB,IAAaC,EAAb,KAA4B,CAEjB,wBAA8B,IAAI,IAElC,QAKA,0BAA6B,IAAI,IAQ1C,YAAYC,EAAkB,CAC5B,KAAK,QAAUA,CACjB,CAOA,QAAe,CACb,IAAMC,EAAY,CAAC,GAAG,KAAK,SAAS,EACpCT,MAAY,CACV,IAAK,IAAMU,KAAS,KAAK,QAAQ,OAAO,EACjCA,EAAM,QACXA,EAAM,MAAQ,GACdA,EAAM,KAAK,EAEf,CAAC,EACD,IAAK,IAAMC,KAAYF,EAAWE,EAAS,CAC7C,CACF,EAOA,SAAgBC,EAASC,EAA6BC,EAA6B,CAEjF,GAAID,IAAQ,IAAA,IAAa,OAAOA,EAAI,MAAS,UAAYA,EAAI,OAAS,KACpE,OAAO,IAAIN,EAAe,EAAK,EAEjC,IAAMQ,EAAWF,EAAI,KAAKP,GAC1B,GAAIS,aAAoBR,EAAgB,OAAOQ,EAC/C,IAAMC,EAAU,IAAIT,EAAe,EAAI,EAIvC,OAHAM,EAAI,QAASI,GAAS,CACpBA,EAAKX,GAAgBU,CACvB,CAAC,EACMA,CACT,CAOA,SAAgBE,EACdC,EACAC,EACAC,EACuB,CACvB,GAAI,CAACF,EAAI,QAAS,OAAOE,EACzB,IAAMC,EAAWH,EAAI,QAAQ,IAAIC,CAAI,EACrC,GAAIE,IAAa,IAAA,GAGf,MAFAA,GAAS,eAAiBD,EAC1BC,EAAS,MAAQ,GACVA,EAAS,MAElB,GAAM,CAACC,EAASC,GAAcrB,EAAU,CAAC,EACnCO,EAAe,CACHW,iBAChBE,UACA,SAAY,CACVC,EAAYC,GAAMA,EAAI,CAAC,CACzB,EACA,MAAO,IAAA,GACP,MAAO,EACT,EACMC,EAASC,GAA8B,CAE3C5B,EAAaE,EAAS,CAAC,CAAC,EAAE,IAAIkB,CAAG,EAGjC,IAAMS,EAAOxB,EAAkB,CAC7B,KAAM,OACN,YAAa,GACb,QACEM,EAAM,QAAQ,EACPR,MAAeQ,EAAM,eAAyCiB,CAAK,CAAC,EAE/E,CAAC,EACD,UAAatB,EAAyBuB,CAAI,CAC5C,EAIA,OAHA,OAAO,eAAeF,EAAO,OAAQ,CAAE,MAAON,CAAK,CAAC,EACnDV,EAAuC,MAAQgB,EAChDP,EAAI,QAAQ,IAAIC,EAAMV,CAAK,EACpBgB,CACT,CAMA,SAAgBG,EAAOhB,EAA6BM,EAA2B,CACzEN,IAAQ,IAAA,IAAcM,EAAI,UAC9BN,EAAI,OAAO,EACXM,EAAI,OAAO,EACb,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hydration.js","names":["
|
|
1
|
+
{"version":3,"file":"hydration.js","names":["attachRootErrors","bindRegion","createRegion","removeRegion","beginClaiming","claimElement","claimPortal","endClaiming","isClaiming","liftedRegions","releaseUnclaimedPortals","takeRegion","withoutClaiming","replayEarlyEvents","claims","createRootScope","resourceKey","withScope","ResourceCacheContext","batch","createRoot","flushSync","runWithOwner","untrack","withHydration","dataCache","data","used","key","stripLeftovers","container","doc","walker","stale","comment","hydrate","code","options","registry","roots","element","passClaims","previousClaims","cache","region","stop","disposed","teardown","dispose","error","cleanupError"],"sources":["../../src/hydration.ts"],"sourcesContent":["import {\n batch,\n createRoot,\n flushSync,\n type Owner,\n type ResourceCache,\n ResourceCacheContext,\n runWithOwner,\n untrack,\n} from \"@shadow-js/core\";\nimport { withHydration } from \"@shadow-js/core/extend\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport {\n beginClaiming,\n claimElement,\n claimPortal,\n endClaiming,\n isClaiming,\n liftedRegions,\n releaseUnclaimedPortals,\n takeRegion,\n withoutClaiming,\n} from \"./internal/claim\";\nimport { replayEarlyEvents } from \"./internal/early-events\";\nimport { type Claims, claims } from \"./internal/hydration-hooks\";\nimport { createRootScope, resourceKey, withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link hydrate}: the server render it continues, the root's owner, and the error\n * reporters it inherits from `RootErrorOptions` (`onUncaughtError`, `onCaughtError`,\n * `onRecoverableError`).\n * @since 1.0.0\n */\nexport interface HydrateOptions extends RootErrorOptions {\n /**\n * The id the server render used, so the client numbers its elements with the same keys. Must\n * equal the `renderId` given to the server render.\n * @default \"0\"\n */\n renderId?: string;\n /**\n * The resource values the server fetched: the `data` of `renderToStringAsync`. A resource whose\n * key is found here starts with that value instead of fetching it again. Each value is used once.\n * @default {} (no resource value is preloaded; resources fetch on the client)\n */\n data?: Record<string, unknown>;\n /**\n * The owner the hydrated root is created under, so its context (providers) is visible to the app.\n * @default null (the root has no parent owner)\n */\n owner?: Owner;\n}\n\nfunction dataCache(data: Record<string, unknown>): ResourceCache {\n const used = new Set<string>();\n return {\n key: resourceKey,\n read(key) {\n if (used.has(key) || !Object.hasOwn(data, key)) return undefined;\n used.add(key);\n return { value: data[key] };\n },\n track() {\n // Client fetches are not tracked: nothing waits for them.\n },\n };\n}\n\n/**\n * Removes marker comments the pass did not claim, so the live DOM never keeps any, and the server\n * blocks of portals the client did not render (they would show content the client does not have).\n */\nfunction stripLeftovers(container: Node): void {\n const doc = container instanceof Document ? container : container.ownerDocument;\n if (doc === null) return;\n if (doc.body !== null) releaseUnclaimedPortals(doc.body);\n const walker = doc.createTreeWalker(container, NodeFilter.SHOW_COMMENT);\n const stale: Comment[] = [];\n while (walker.nextNode()) {\n const comment = walker.currentNode as Comment;\n if (comment.data === \"[\" || comment.data === \"]\") stale.push(comment);\n }\n for (const comment of stale) comment.remove();\n}\n\n/**\n * Attaches the application to HTML the server already rendered into `container`. Elements are\n * claimed by their `data-hk` keys instead of created, so the DOM is not rebuilt and nodes keep\n * their identity. Event handlers and reactive bindings are attached; markers are removed. Parts the\n * server and client disagree on are repaired by reconciliation, never left half hydrated.\n *\n * @param code Runs once, untracked, and builds the same component tree the server rendered.\n * @param container Element or Document that holds the server markup.\n * @param options `renderId` (must match the server), the server's resource `data`, an `owner`, and\n * the error reporters. Undefined uses the defaults.\n * @returns A dispose function that stops the hydrated root and removes its nodes. Safe to call more\n * than once.\n * @throws Error (production message `SHADOW_HYDRATE_RUNNING`) when called while another hydration\n * pass is in progress.\n * @example\n * import { createComponent, hydrate } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const container = document.getElementById(\"app\") as Element;\n * const data = JSON.parse(document.getElementById(\"data\")?.textContent ?? \"{}\") as Record<\n * string,\n * unknown\n * >;\n * const dispose = hydrate(() => createComponent(App, {}), container, { data });\n * @see render\n * @since 1.0.0\n */\nexport function hydrate(\n code: () => unknown,\n container: Element | Document,\n options: HydrateOptions = {},\n): () => void {\n if (isClaiming())\n throw new Error(\n __DEV__ ? \"hydrate(): a hydration pass is already running.\" : \"SHADOW_HYDRATE_RUNNING\",\n );\n const registry = new Map<string, Element>();\n const roots: Element[] = container instanceof Element ? [container] : [];\n for (const element of [...roots, ...Array.from(container.querySelectorAll(\"[data-hk]\"))]) {\n const key = element.getAttribute(\"data-hk\");\n if (key !== null) registry.set(key, element);\n }\n beginClaiming(registry, options.onRecoverableError);\n // The renderer reaches the claiming code only through this hook, installed for this pass alone.\n const passClaims: Claims = {\n claimElement,\n takeRegion,\n liftedRegions,\n claimPortal,\n isClaiming,\n withoutClaiming,\n };\n const previousClaims = claims.current;\n claims.current = passClaims;\n const cache = dataCache(options.data ?? {});\n const region = createRegion(container, null, Array.from(container.childNodes));\n let stop: (() => void) | undefined;\n let disposed = false;\n const teardown = (): void => {\n if (disposed) return;\n disposed = true;\n stop?.();\n removeRegion(region);\n };\n try {\n // The batch wraps the scope, not the other way round: its exit flushes the queued effects\n // (onMount, and the re-renders they cause) after the scope is restored. The scope numbers only\n // the templates the server rendered; an effect that builds new DOM must not draw keys from it\n // (that shifts the keys of later siblings and misses the ones the server never sent). Boundaries\n // rebuild from their own captured scope, so a reset inside the pass still claims its elements.\n withHydration(() =>\n batch(() =>\n withScope(createRootScope(options.renderId), () =>\n runWithOwner(options.owner ?? null, () =>\n createRoot((dispose) => {\n stop = dispose;\n attachRootErrors(options);\n ResourceCacheContext({\n value: cache,\n get children() {\n bindRegion(region, untrack(code));\n return null;\n },\n });\n }),\n ),\n ),\n ),\n );\n flushSync();\n } catch (error) {\n // The caller gets no dispose function from a hydration that throws, so the root must not stay alive. Its\n // effects and listeners go; the server's markup stays, so the page keeps what the server rendered.\n try {\n stop?.();\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"hydrate() failed and so did its teardown.\" : \"SHADOW_HYDRATE_ERRORS\",\n );\n }\n throw error;\n } finally {\n endClaiming();\n claims.current = previousClaims;\n }\n replayEarlyEvents();\n stripLeftovers(container);\n return teardown;\n}\n"],"mappings":"A,wuBAsDA,SAASyB,EAAUC,EAA8C,CAC/D,IAAMC,kBAAO,IAAI,IACjB,MAAO,CACL,IA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EACzEe,EACAC,EAAW,GACTC,MAAuB,CACvBD,IACJA,EAAW,GACXD,IAAO,EACP1C,EAAayC,CAAM,EACrB,EACA,GAAI,CAMFpB,MACEL,MACEF,EAAUF,EAAgBsB,EAAQ,QAAQ,MACxCf,EAAae,EAAQ,OAAS,SAC5BjB,EAAY4B,GAAY,CACtBH,EAAOG,EACPhD,EAAiBqC,CAAO,EACxBnB,EAAqB,CACnB,MAAOyB,EACP,IAAI,UAAW,CAEb,OADA1C,EAAW2C,EAAQrB,EAAQa,CAAI,CAAC,EACzB,IACT,CACF,CAAC,CACH,CAAC,CACH,CACF,CACF,CACF,EACAf,EAAU,CACZ,OAAS4B,EAAO,CAGd,GAAI,CACFJ,IAAO,CACT,OAASK,EAAc,CACrB,MAAU,eACR,CAACD,EAAOC,CAAY,EACoC,uBAC1D,CACF,CACA,MAAMD,CACR,QAAU,CACR1C,EAAY,EACZO,EAAO,QAAU4B,CACnB,CAGA,OAFA7B,EAAkB,EAClBgB,EAAeC,CAAS,EACjBiB,CACT,C"}
|
package/dist/prod/insert.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"insert.js","names":["tails","documentOf","node","ownsText","texts","region","addText","text","pruneTexts","kept","keep","fragmentChildren","flatten","parts","item","leaves","root","call","kids","child","reusablePool","pool","list","materialize","only","current","nodes","count","seen","part","endOf","last","marker","commitWatchers","watchCommits","set","parent","run","onCleanup","keepWatchingCommits","commit","next","attached","first","end","reconcileNodes","commitValue","raw","created","createRegion","initial","anchorNode","linkRegion","tail","currentOwner","start","anchor","addCleanup","containsFunction","stack","frame","bindRegion","value","latest","ordered","useRenderEffect","owner","memos","touched","fn","createComputation","readComputation","disposeOwner","moveRegion","keepFocus","move","removeRegion","before","insert","resolvedAnchor","claims"],"sources":["../../src/insert.ts"],"sourcesContent":["import { onCleanup, useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { leaves } from \"./internal/accessor\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { keepFocus, reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect\n * that runs again flattens the same fragment value once more: it must still give those nodes.\n */\nconst fragmentChildren = new WeakMap<DocumentFragment, Node[]>();\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call?: (fn: () => unknown) => unknown): Part[] {\n const parts: Part[] = [];\n const cycle = __DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\";\n for (const item of leaves(root, cycle, call)) {\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n const kids = fragmentChildren.get(item) ?? [...item.childNodes];\n fragmentChildren.set(item, kids);\n for (const child of kids) parts.push(child);\n } else parts.push(item instanceof Node ? item : String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */\nconst commitWatchers = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the\n * parent holds (a name on the first element of a content region) can follow a change of content.\n * The watch ends with the owner that is current when this is called.\n * @internal\n */\nexport function watchCommits(parent: Node, run: () => void): void {\n const set = commitWatchers.get(parent) ?? new Set<() => void>();\n commitWatchers.set(parent, set.add(run));\n onCleanup(() => {\n set.delete(run);\n });\n}\n\n/**\n * Like {@link watchCommits}, for a watch that lives as long as `parent` does: it is not tied to the owner that is\n * current, so a binding that runs again does not end it. The select's value (see `setSelectValue`) uses it.\n * @internal\n */\nexport function keepWatchingCommits(parent: Node, run: () => void): void {\n commitWatchers.set(parent, (commitWatchers.get(parent) ?? new Set<() => void>()).add(run));\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n // Makes the DOM show the new nodes for this region.\n const next = materialize(region, parts);\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const first = attached[0];\n const end = endOf(region, attached.at(-1));\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n commitWatchers.get(parent)?.forEach((run) => {\n run();\n });\n // The options of an optgroup are the select's options.\n if (parent.nodeName === \"OPTGROUP\" && parent.parentNode !== null) {\n commitWatchers.get(parent.parentNode)?.forEach((run) => {\n run();\n });\n }\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n // The nodes of `initial` (already in the parent) that the region adopts as its current content.\n const nodes: Node[] = [];\n if (initial !== undefined) {\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n nodes.push(part);\n }\n }\n const marker = nodes.length > 0 ? (nodes[0] as Node).previousSibling : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes. (A function of its\n * own, so the cleanup it registers holds nothing but the anchor: a closure made inside `bindRegion` would keep\n * the regions of that call alive as long as the parent's owner.)\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() as unknown[];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n // One memo per accessor function, owned by this effect (the effect that evaluates the region's expression,\n // so a new result drops them all; the effect that resolves the result runs many times and must not own\n // them). The memos of accessors the last run did not meet are disposed, which bounds the cache by what the\n // region currently shows.\n const owner = currentOwner();\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n const call = (fn: () => unknown): unknown => {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n };\n useRenderEffect(\n () => {\n touched = new Set();\n const parts = flatten(raw, call);\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts\n * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so\n * what it shows is not built again. Only for a region without an anchor.\n * @param region The region to move.\n * @param parent The node that receives the region's nodes.\n * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).\n * @since 1.0.3\n * @internal\n */\nexport function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void {\n const attached = region.nodes.filter((node) => node.parentNode === region.parent);\n // A move that is not in place (appendChild) blurs a focused input: it gets the focus back.\n keepFocus(region.parent, () => {\n for (const node of attached) move(node);\n });\n // Read-only for everyone else: only a move changes where a region lives.\n (region as { parent: Node }).parent = parent;\n region.marker = attached[0]?.previousSibling ?? parent.lastChild;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":"A,oXA+CA,MAAMA,kBAAQ,IAAI,QAGlB,SAASC,EAAW,EAAsB,CACxC,OAAOC,aAAgB,SAAWA,EAAQA,EAAK,eAAiB,QAClE,CAGA,SAASC,EAAS,EAAgB,EAAqB,CACrD,IAAMC,EAAQC,EAAO,MACrB,OAAOD,IAAUF,GAASE,aAAiB,KAAOA,EAAM,IAAIF,CAAY,CAC1E,CAGA,SAASI,EAAQ,EAAgB,EAAkB,CACjD,IAAMF,EAAQC,EAAO,MACjBD,IAAU,KAAM,EAAO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AAE,IAClBF,EAAM,OAAOE,CAAE,EACfG,EAAatE,CAAI,GAEnB,OAAOW,CACT,EACC,GAAU,CACT2B,EAAOnC,EAAQQ,CAAK,CACtB,CACF,CACF,MACEiC,EAAYzC,EAAQ0C,CAAG,CAE3B,CAAC,EACMgB,CACT,CAYA,SAAgBU,EAAW,EAAgB,EAAc,EAAkC,CACzF,IAAM/B,EAAWrC,EAAO,MAAM,OAAQ,GAASH,EAAK,aAAeG,EAAO,MAAM,EAEhFqE,EAAUrE,EAAO,WAAc,CAC7B,IAAK,IAAMH,KAAQwC,EAAUiC,EAAKzE,CAAI,CACxC,CAAC,EAED,EAA6B,OAASkC,EACtC,EAAO,OAASM,EAAS,EAAE,EAAE,iBAAmBN,EAAO,SACzD,CAOA,SAAgBwC,EAAa,EAAsB,CACjD,IAAK,IAAM1E,KAAQG,EAAO,MACpBH,EAAK,aAAeG,EAAO,QAAQA,EAAO,OAAO,YAAYH,CAAI,EAEvE,EAAO,MAAQ,CAAC,EAChB,EAAO,MAAQ,IACjB,CAkBA,SAAgBsD,EAAO,EAAc,EAA2B,CAC9D,IAAMjD,EAAON,EAAWmC,CAAM,CAAC,CAAC,eAAe,EAAE,EAEjD,OADAA,EAAO,aAAa7B,EAAMsE,CAAM,EACzBtE,CACT,CAwCA,SAAgBuE,EACd,EACA,EACA,EACA,EACS,CACT,IAAMC,EAAiB5B,GAAc,KAIrC,OAAOU,EADQZ,EAAab,EAAQ2C,EADlC7B,IAAY,IAAA,GAAY8B,EAAO,QAAQ,WAAW5C,EAAQ2C,CAAc,EAAI7B,CAEvD,EAAGY,EAAOiB,IAAmB,IAAI,CAC1D,C"}
|
|
1
|
+
{"version":3,"file":"insert.js","names":["leaves","claims","keepFocus","reconcileNodes","onCleanup","useRenderEffect","addCleanup","createComputation","currentOwner","disposeOwner","readComputation","tails","documentOf","node","ownsText","region","texts","addText","text","pruneTexts","keep","kept","fragmentChildren","flatten","root","call","parts","item","kids","child","reusablePool","pool","list","materialize","only","current","nodes","count","seen","part","endOf","last","marker","commitWatchers","watchCommits","parent","run","set","keepWatchingCommits","commit","next","attached","first","end","commitValue","raw","created","createRegion","anchorNode","initial","linkRegion","tail","start","anchor","containsFunction","stack","frame","bindRegion","value","ordered","latest","owner","memos","touched","fn","moveRegion","move","removeRegion","before","insert","resolvedAnchor"],"sources":["../../src/insert.ts"],"sourcesContent":["import { onCleanup, useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { leaves } from \"./internal/accessor\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { keepFocus, reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect\n * that runs again flattens the same fragment value once more: it must still give those nodes.\n */\nconst fragmentChildren = new WeakMap<DocumentFragment, Node[]>();\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call?: (fn: () => unknown) => unknown): Part[] {\n const parts: Part[] = [];\n const cycle = __DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\";\n for (const item of leaves(root, cycle, call)) {\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n const kids = fragmentChildren.get(item) ?? [...item.childNodes];\n fragmentChildren.set(item, kids);\n for (const child of kids) parts.push(child);\n } else parts.push(item instanceof Node ? item : String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */\nconst commitWatchers = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the\n * parent holds (a name on the first element of a content region) can follow a change of content.\n * The watch ends with the owner that is current when this is called.\n * @internal\n */\nexport function watchCommits(parent: Node, run: () => void): void {\n const set = commitWatchers.get(parent) ?? new Set<() => void>();\n commitWatchers.set(parent, set.add(run));\n onCleanup(() => {\n set.delete(run);\n });\n}\n\n/**\n * Like {@link watchCommits}, for a watch that lives as long as `parent` does: it is not tied to the owner that is\n * current, so a binding that runs again does not end it. The select's value (see `setSelectValue`) uses it.\n * @internal\n */\nexport function keepWatchingCommits(parent: Node, run: () => void): void {\n commitWatchers.set(parent, (commitWatchers.get(parent) ?? new Set<() => void>()).add(run));\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n // Makes the DOM show the new nodes for this region.\n const next = materialize(region, parts);\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const first = attached[0];\n const end = endOf(region, attached.at(-1));\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n commitWatchers.get(parent)?.forEach((run) => {\n run();\n });\n // The options of an optgroup are the select's options.\n if (parent.nodeName === \"OPTGROUP\" && parent.parentNode !== null) {\n commitWatchers.get(parent.parentNode)?.forEach((run) => {\n run();\n });\n }\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n // The nodes of `initial` (already in the parent) that the region adopts as its current content.\n const nodes: Node[] = [];\n if (initial !== undefined) {\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n nodes.push(part);\n }\n }\n const marker = nodes.length > 0 ? (nodes[0] as Node).previousSibling : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes. (A function of its\n * own, so the cleanup it registers holds nothing but the anchor: a closure made inside `bindRegion` would keep\n * the regions of that call alive as long as the parent's owner.)\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() as unknown[];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n // One memo per accessor function, owned by this effect (the effect that evaluates the region's expression,\n // so a new result drops them all; the effect that resolves the result runs many times and must not own\n // them). The memos of accessors the last run did not meet are disposed, which bounds the cache by what the\n // region currently shows.\n const owner = currentOwner();\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n const call = (fn: () => unknown): unknown => {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n };\n useRenderEffect(\n () => {\n touched = new Set();\n const parts = flatten(raw, call);\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts\n * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so\n * what it shows is not built again. Only for a region without an anchor.\n * @param region The region to move.\n * @param parent The node that receives the region's nodes.\n * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).\n * @since 1.0.3\n * @internal\n */\nexport function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void {\n const attached = region.nodes.filter((node) => node.parentNode === region.parent);\n // A move that is not in place (appendChild) blurs a focused input: it gets the focus back.\n keepFocus(region.parent, () => {\n for (const node of attached) move(node);\n });\n // Read-only for everyone else: only a move changes where a region lives.\n (region as { parent: Node }).parent = parent;\n region.marker = attached[0]?.previousSibling ?? parent.lastChild;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"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zB5D,CACT,CAwCA,SAAgB6D,EACdlC,EACAuB,EACAV,EACAC,EACS,CACT,IAAMqB,EAAiBtB,GAAc,KAIrC,OAAOS,EADQV,EAAaZ,EAAQmC,EADlCrB,IAAY,IAAA,GAAY1D,EAAO,QAAQ,WAAW4C,EAAQmC,CAAc,EAAIrB,CAEvD,EAAGS,EAAOY,IAAmB,IAAI,CAC1D,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accessor.js","names":["unwrap","fn","depth","
|
|
1
|
+
{"version":3,"file":"accessor.js","names":["unwrap","value","call","fn","depth","leaves","root","cycle","found","frames","cursors","active","top","frame","cursor","item"],"sources":["../../../src/internal/accessor.ts"],"sourcesContent":["/** Longest chain of accessors a single value may hold (a function returning a function ...). */\nconst MAX_ACCESSOR_DEPTH = 10_000;\n\n/**\n * Calls `value` while it is a function, so an accessor that returns an accessor is followed to the\n * value at its end. `call` runs each function (default: a plain call); `insert` passes one that\n * memoizes. Class and style values use the default, inside the effect that applies them, so the\n * signals an accessor reads are tracked by it.\n * @throws TypeError (production message `SHADOW_INSERT_DEPTH`) after 10,000 functions in a row.\n * @internal\n */\nexport function unwrap(\n value: unknown,\n call: (fn: () => unknown) => unknown = (fn) => fn(),\n): unknown {\n for (let depth = 0; typeof value === \"function\"; depth += 1) {\n if (depth >= MAX_ACCESSOR_DEPTH)\n throw new TypeError(\n __DEV__\n ? \"An accessor returns accessors more than 10,000 levels deep.\"\n : \"SHADOW_INSERT_DEPTH\",\n );\n value = call(value as () => unknown);\n }\n return value;\n}\n\n/**\n * The leaves of a value made of nested arrays, in order, found without recursion (the nesting depth is\n * the user's): every item goes through {@link unwrap}, an array is entered, anything else is a leaf.\n * `insert` and the class writer share it.\n * @param root The value; an array is entered, any other value is a leaf.\n * @param cycle The message of the `TypeError` thrown when an array contains itself.\n * @param call Passed to {@link unwrap}.\n * @internal\n */\nexport function leaves(\n root: unknown,\n cycle: string,\n call?: (fn: () => unknown) => unknown,\n): unknown[] {\n const found: unknown[] = [];\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const active = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top] as unknown[];\n const cursor = cursors[top] as number;\n if (cursor >= frame.length) {\n active.delete(frames.pop() as unknown[]);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n const item = unwrap(frame[cursor], call);\n if (!Array.isArray(item)) found.push(item);\n else if (active.has(item)) throw new TypeError(cycle);\n else {\n active.add(item);\n frames.push(item);\n cursors.push(0);\n }\n }\n return found;\n}\n"],"mappings":"AAWA,SAAgBA,EACdC,EACAC,EAAwCC,GAAOA,EAAG,EACzC,CACT,IAAK,IAAIC,EAAQ,EAAG,OAAOH,GAAU,WAAYG,GAAS,EAAG,CAC3D,GAAIA,GAAS,IACX,MAAU,UAGJ,qBACN,EACFH,EAAQC,EAAKD,CAAsB,CACrC,CACA,OAAOA,CACT,CAWA,SAAgBI,EACdC,EACAC,EACAL,EACW,CACX,IAAMM,EAAmB,CAAC,EACpBC,EAAsB,CAAC,CAACH,CAAI,CAAC,EAC7BI,EAAoB,CAAC,CAAC,EACtBC,kBAAS,IAAI,IACnB,KAAOF,EAAO,OAAS,GAAG,CACxB,IAAMG,EAAMH,EAAO,OAAS,EACtBI,EAAQJ,EAAOG,GACfE,EAASJ,EAAQE,GACvB,GAAIE,GAAUD,EAAM,OAAQ,CAC1BF,EAAO,OAAOF,EAAO,IAAI,CAAc,EACvCC,EAAQ,IAAI,EACZ,QACF,CACAA,EAAQE,GAAOE,EAAS,EACxB,IAAMC,EAAOf,EAAOa,EAAMC,GAASZ,CAAI,EACvC,GAAI,CAAC,MAAM,QAAQa,CAAI,EAAGP,EAAM,KAAKO,CAAI,OACpC,GAAIJ,EAAO,IAAII,CAAI,EAAG,MAAU,UAAUR,CAAK,OAElDI,EAAO,IAAII,CAAI,EACfN,EAAO,KAAKM,CAAI,EAChBL,EAAQ,KAAK,CAAC,CAElB,CACA,OAAOF,CACT,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claim.js","names":["state","beginClaiming","endClaiming","isClaiming","isMarker","node","text","data","prepare","stack","root","parent","child","following","content","depth","cursor","after","lifted","queue","pending","claimElement","current","key","element","TEXT_ONLY","isTextOnly","takeRegion","anchorNode","liftedRegions","withoutClaiming","saved","fn","PORTAL_OPEN","PORTAL_CLOSE","claimPortal","body","nodes","open","isComment","close","index","isRegionMarker","own","keyed","hk","releaseUnclaimedPortals","opening","last","comment"],"sources":["../../../src/internal/claim.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, devtoolsReport } from \"@shadow-js/core/extend\";\n\n/** What a hydration pass in progress knows. Exists only while `hydrate()` runs its synchronous pass. */\ninterface HydrationState {\n /** Server elements by `data-hk` key; entries are consumed when claimed. */\n readonly registry: Map<string, Element>;\n /** Told about each mismatch the pass repaired (the `onRecoverableError` option). */\n readonly recoverable: ((error: unknown) => void) | undefined;\n /** Region contents taken out of each claimed parent, in document order. */\n readonly pending: WeakMap<Node, Node[][]>;\n /** The content of every region lifted out of a claimed element, in document order (read by `NoHydration`). */\n readonly lifted: Node[][];\n}\n\nlet state: HydrationState | null = null;\n\n/** Starts a claiming pass over the given server elements. @internal */\nexport function beginClaiming(\n registry: Map<string, Element>,\n recoverable?: (error: unknown) => void,\n): void {\n state = { registry, recoverable, pending: new WeakMap(), lifted: [] };\n}\n\n/** Ends the claiming pass. @internal */\nexport function endClaiming(): void {\n state = null;\n}\n\n/**\n * Reports whether a `hydrate()` pass is claiming server DOM right now: a custom renderer reads it to\n * decide between adopting server nodes and building fresh ones. The pass is synchronous, so this is\n * `false` again once `hydrate()` returns, and in every later update.\n *\n * @returns `true` during the synchronous pass of `hydrate()` (outside {@link withoutClaiming}),\n * `false` otherwise.\n * @example\n * import { isClaiming } from \"@shadow-js/web/extend\";\n *\n * function describe(): string {\n * return isClaiming() ? \"adopting server markup\" : \"building fresh DOM\";\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function isClaiming(): boolean {\n return state !== null;\n}\n\nfunction isMarker(node: Node, data: string): boolean {\n if (node.nodeType !== 8) return false;\n const text = (node as Comment).data;\n // `[b:ID` opens a Suspense boundary region (streaming); it hydrates like a plain region.\n return text === data || (data === \"[\" && text.startsWith(\"[b:\"));\n}\n\n/**\n * Turns server markup for one template into the shape a freshly cloned template has: region\n * contents are lifted out (to be re-inserted by `insert`), marker comments are removed and text\n * nodes are merged again. Iterative; static elements below the root are walked, regions are not\n * (their contents belong to other templates, claimed later through the registry).\n */\nfunction prepare(root: Element, pending: WeakMap<Node, Node[][]>, lifted: Node[][]): void {\n const stack: Element[] = [root];\n while (stack.length > 0) {\n const parent = stack.pop() as Element;\n let child: ChildNode | null = parent.firstChild;\n while (child !== null) {\n const following: ChildNode | null = child.nextSibling;\n if (isMarker(child, \"[\")) {\n const content: Node[] = [];\n let depth = 1;\n let cursor: ChildNode | null = child.nextSibling;\n while (cursor !== null) {\n if (isMarker(cursor, \"[\")) depth += 1;\n else if (isMarker(cursor, \"]\")) {\n depth -= 1;\n if (depth === 0) break;\n }\n content.push(cursor);\n cursor = cursor.nextSibling;\n }\n const after: ChildNode | null = cursor === null ? null : cursor.nextSibling;\n lifted.push(content);\n for (const node of content) parent.removeChild(node);\n parent.removeChild(child);\n if (cursor !== null) parent.removeChild(cursor);\n const queue = pending.get(parent);\n if (queue === undefined) pending.set(parent, [content]);\n else queue.push(content);\n child = after;\n continue;\n }\n if (child.nodeType === 1) stack.push(child as Element);\n child = following;\n }\n }\n root.normalize();\n}\n\n/**\n * Adopts the server's element for a hydration key while `hydrate()` runs: the step that lets a custom\n * template reuse server markup instead of creating new nodes. The element loses its `data-hk`\n * attribute, and the content of its regions is lifted out, to be adopted by {@link takeRegion} when\n * the regions bind. Prefer `claims.current.claimElement`, which links this code only into apps that\n * call `hydrate()`.\n *\n * @param key The key from `nextKey()`, drawn where the server drew it. Undefined claims nothing.\n * @returns The server element; `null` when no hydration pass is running, when `key` is undefined, or\n * when the server sent no element for the key (the caller then creates the node itself). A missing\n * key is a recoverable mismatch: development builds warn `HYDRATION_KEY_MISS`, and the pass's\n * `onRecoverableError` receives an `Error`.\n * @example\n * import { claimElement, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createPanel(): Element {\n * // During hydrate(): the server's <section>. Otherwise: a new one.\n * return claimElement(nextKey()) ?? document.createElement(\"section\");\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function claimElement(key: string | undefined): Element | null {\n const current = state;\n if (current === null || key === undefined) return null;\n const element = current.registry.get(key);\n if (element === undefined) {\n // Production keeps only the code (the same split as core's messages): the text stays out of the bundle.\n if (__DEV__) {\n const message = `No server element for key \"${key}\".`;\n console.warn(`[shadow HYDRATION_KEY_MISS] ${message}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, message, key, undefined);\n }\n current.recoverable?.(\n new Error(__DEV__ ? `No server element for key \"${key}\".` : \"SHADOW_HYDRATION_KEY_MISS\"),\n );\n return null;\n }\n current.registry.delete(key);\n element.removeAttribute(\"data-hk\");\n prepare(element, current.pending, current.lifted);\n return element;\n}\n\n/** Characters that stay readable as escapes in a diagnostic snippet: markup, quotes and ampersands. */\nconst SNIPPET_ESCAPES: ReadonlyMap<string, string> = new Map([\n [\"<\", \"\\\\u003c\"],\n [\">\", \"\\\\u003e\"],\n [\"&\", \"\\\\u0026\"],\n ['\"', \"\\\\u0022\"],\n [\"'\", \"\\\\u0027\"],\n]);\n\n/**\n * Escapes text for a diagnostic snippet and cuts it to `limit` output characters, with `...` when cut.\n * Escapes are never split, so the output is at most `limit + 3` characters.\n * @internal\n */\nfunction snippet(text: string, limit: number): string {\n let out = \"\";\n for (const char of text) {\n const code = char.codePointAt(0) ?? 0;\n const controlled = code < 0x20 || (code >= 0x7f && code <= 0x9f);\n const escaped =\n SNIPPET_ESCAPES.get(char) ?? (controlled ? `\\\\u${code.toString(16).padStart(4, \"0\")}` : char);\n if (out.length + escaped.length > limit) return `${out}...`;\n out += escaped;\n }\n return out;\n}\n\n/** The opening tag of a server element as the server wrote it (attribute values as they are). */\nfunction openingMarkup(element: Element): string {\n let markup = `<${element.localName}`;\n for (const attr of Array.from(element.attributes)) markup += ` ${attr.name}=\"${attr.value}\"`;\n return `${markup}>`;\n}\n\n/**\n * Development check of a claimed element against the tag its template or `element()` call expects.\n * A different tag warns `HYDRATION_MISMATCH` on the console and in devtools, with an escaped snippet of\n * the server element (its opening tag and the start of its text, bounded). Recovery is unchanged: the\n * element is still adopted, nothing is thrown or replaced, and the caller gets the same value.\n *\n * Call it under `if (__DEV__)`. Text is not compared here: the expected text is inserted later, by\n * `insert`, and {@link checkClaimedText} compares it with the server text at that point.\n *\n * @param element The server element `claimElement` returned.\n * @param expectedTag The tag the client expects (any case).\n * @internal\n */\nexport function checkClaimedTag(element: Element, expectedTag: string): void {\n if (!__DEV__) return;\n const expected = expectedTag.toLowerCase();\n const actual = element.localName.toLowerCase();\n if (actual === expected) return;\n const text = element.textContent ?? \"\";\n let detail = `expected <${expected}> but the server sent <${snippet(actual, 80)}>; server markup: \"${snippet(openingMarkup(element), 80)}\"`;\n if (text !== \"\") detail += `; text: \"${snippet(text, 40)}\"`;\n console.warn(`[shadow HYDRATION_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/**\n * Development check of the first commit of a region that claimed server text. The server text is the\n * DOM text of the claimed nodes (already decoded, so an escaped `<` compares as `<`); the expected\n * text is the strings of the first commit, joined (a number is already its string, `null` and booleans\n * render nothing, so they expect `\"\"`). Equal text is silent. Different text warns\n * `HYDRATION_TEXT_MISMATCH` on the console and in devtools, with both texts escaped and bounded to 40\n * characters. Recovery is unchanged: the region shows the value the client computed.\n *\n * Not compared, so silent: a region that claimed no nodes (an empty server region has no server text),\n * a region whose server nodes are not all text (an element, or the markers of a nested region), and a\n * commit that holds a node (an element is shown in place of the server's content, as before).\n *\n * Call it under `if (__DEV__)`, once per claimed region, at its first commit.\n *\n * @param claimed The server nodes the region adopted, in document order.\n * @param parts What the first commit shows: strings, or nodes.\n * @internal\n * @since 1.0.0\n */\nexport function checkClaimedText(\n claimed: readonly Node[],\n parts: readonly (Node | string)[],\n): void {\n if (!__DEV__) return;\n if (claimed.length === 0) return;\n let server = \"\";\n for (const node of claimed) {\n if (node.nodeType !== 3) return;\n server += node.textContent ?? \"\";\n }\n let expected = \"\";\n for (const part of parts) {\n if (typeof part !== \"string\") return;\n expected += part;\n }\n if (expected === server) return;\n const detail = `expected text \"${snippet(expected, 40)}\" but the server sent text \"${snippet(server, 40)}\"`;\n console.warn(`[shadow HYDRATION_TEXT_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/** HTML elements whose content is text and nothing else: no comment can mark a region inside them. */\nconst TEXT_ONLY = new Set([\"script\", \"style\", \"title\", \"textarea\"]);\n\n/**\n * True for a `script`, `style`, `title` or `textarea`, in whichever namespace the parser put it: `Dynamic` knows no\n * parent, so the server writes the children of such a tag without region markers even where the page parses it as\n * an SVG `title` or `style`. Its whole content is then the one region.\n */\nfunction isTextOnly(node: Node): boolean {\n return node.nodeType === 1 && TEXT_ONLY.has((node as Element).localName);\n}\n\n/**\n * Adopts the server content of the next region of a claimed parent while `hydrate()` runs: the nodes\n * that sat between the region's markers are put back before `anchorNode` and returned, so a custom\n * region can bind to them instead of inserting new nodes. Regions are taken in document order.\n *\n * @param parent An element returned by {@link claimElement} (or one of its descendants).\n * @param anchorNode The node the content goes before; `null` appends it at the end of `parent`.\n * @returns The adopted nodes; undefined when no hydration pass is running or `parent` has no region\n * left to adopt (the caller then inserts fresh nodes). A `script`, `style`, `title` or `textarea` has no\n * markers (the server writes its text as the parser reads it): its current children are the region.\n * @example\n * import { takeRegion } from \"@shadow-js/web/extend\";\n *\n * function fillRegion(parent: Element): Node[] {\n * const adopted = takeRegion(parent, null);\n * if (adopted !== undefined) return adopted;\n * const text = document.createTextNode(\"fresh\");\n * parent.append(text);\n * return [text];\n * }\n * @see claimElement\n * @since 1.0.0\n */\nexport function takeRegion(parent: Node, anchorNode: Node | null): Node[] | undefined {\n const current = state;\n if (current === null) return undefined;\n const content = current.pending.get(parent)?.shift();\n if (content === undefined) return isTextOnly(parent) ? Array.from(parent.childNodes) : undefined;\n for (const node of content) parent.insertBefore(node, anchorNode);\n return content;\n}\n\n/**\n * The content of every region the pass lifted out of the server elements it claimed, in document order. `NoHydration` finds\n * its own markers in them. Undefined outside a hydration pass.\n * @internal\n */\nexport function liftedRegions(): readonly (readonly Node[])[] | undefined {\n return state?.lifted;\n}\n\n/**\n * Runs `fn` with claiming switched off, so the templates it builds are created fresh instead of\n * claimed from the server markup. Use it for content the server did not render (a portal the server\n * sent nothing for), so its keys are not reported as missing. The previous state is restored when\n * `fn` returns or throws.\n *\n * @param fn The code to run. It runs synchronously, once.\n * @returns What `fn` returns. An error `fn` throws propagates.\n * @example\n * import { template } from \"@shadow-js/web\";\n * import { withoutClaiming } from \"@shadow-js/web/extend\";\n *\n * const makeTip = template(`<div class=\"tip\"></div>`);\n * const tip = withoutClaiming(() => makeTip()); // a fresh clone, even during hydrate()\n * @see claims\n * @since 1.0.0\n */\nexport function withoutClaiming<T>(fn: () => T): T {\n const saved = state;\n state = null;\n try {\n return fn();\n } finally {\n state = saved;\n }\n}\n\n/** Comment that opens the server block of a portal (`<!--portal:KEY-->`). */\nconst PORTAL_OPEN = \"portal:\";\n/** Comment that closes it (`<!--/portal:KEY-->`). */\nconst PORTAL_CLOSE = \"/portal:\";\n\n/**\n * Adopts the server block of a portal while `hydrate()` runs. The server writes each portal's markup\n * at the end of `<body>` between `<!--portal:KEY-->` and `<!--/portal:KEY-->` comments (see\n * `createServerPortals`); this removes the comments, leaves the content in place, and registers its\n * keyed elements so the portal's templates claim them.\n *\n * @param key The portal's key from `nextKey()`. Undefined claims nothing.\n * @returns The nodes of the block, in place in the body; undefined when no hydration pass is running,\n * `key` is undefined, there is no document body, or the server sent no complete block for the key.\n * @example\n * import { claimPortal, nextKey } from \"@shadow-js/web/extend\";\n *\n * function mountOverlay(build: () => Node): Node[] {\n * const adopted = claimPortal(nextKey());\n * if (adopted !== undefined) return adopted;\n * const node = build();\n * document.body.append(node);\n * return [node];\n * }\n * @since 1.0.0\n */\nexport function claimPortal(key: string | undefined): Node[] | undefined {\n const current = state;\n if (current === null || key === undefined || typeof document === \"undefined\") return undefined;\n const body = document.body;\n if (body === null) return undefined;\n const nodes = Array.from(body.childNodes);\n const open = nodes.findIndex((node) => isComment(node, PORTAL_OPEN + key));\n if (open === -1) return undefined;\n const close = nodes.findIndex(\n (node, index) => index > open && isComment(node, PORTAL_CLOSE + key),\n );\n if (close === -1) return undefined;\n // The content stays where the server put it (the region adopts it in place); only the markers go.\n const content: Node[] = [];\n for (const node of nodes.slice(open + 1, close)) {\n if (node.nodeType === 8 && isRegionMarker(node as Comment)) body.removeChild(node);\n else content.push(node);\n }\n for (const node of [nodes[open], nodes[close]]) {\n if (node !== undefined) body.removeChild(node);\n }\n for (const node of content) {\n if (node.nodeType !== 1) continue;\n const element = node as Element;\n const own = element.getAttribute(\"data-hk\");\n if (own !== null) current.registry.set(own, element);\n for (const keyed of Array.from(element.querySelectorAll(\"[data-hk]\"))) {\n const hk = keyed.getAttribute(\"data-hk\");\n if (hk !== null) current.registry.set(hk, keyed);\n }\n }\n return content;\n}\n\n/**\n * Removes the server blocks of portals that were not claimed during the pass: the client did not render\n * those portals, so their markup must not stay in the page. Each block goes with its comments. A block\n * without its closing comment loses only its opening one.\n * @internal\n */\nexport function releaseUnclaimedPortals(body: Node): void {\n const nodes = Array.from(body.childNodes);\n for (let open = 0; open < nodes.length; open += 1) {\n const opening = nodes[open];\n if (opening === undefined || opening.nodeType !== 8) continue;\n const data = (opening as Comment).data;\n if (!data.startsWith(PORTAL_OPEN)) continue;\n const close = nodes.findIndex(\n (node, index) =>\n index > open && isComment(node, PORTAL_CLOSE + data.slice(PORTAL_OPEN.length)),\n );\n const last = close === -1 ? open : close;\n for (const node of nodes.slice(open, last + 1)) {\n if (node.parentNode === body) body.removeChild(node);\n }\n open = last;\n }\n}\n\nfunction isComment(node: Node, data: string): boolean {\n return node.nodeType === 8 && (node as Comment).data === data;\n}\n\nfunction isRegionMarker(comment: Comment): boolean {\n return comment.data === \"[\" || comment.data === \"]\";\n}\n"],"mappings":"A,+BAcA,IAAIA,EAA+B,KAGnC,SAAgBC,EACd,EACA,EACM,CACN,EAAQ,CAAE,WAAU,cAAa,wBAAS,IAAI,QAAW,OAAQ,CAAC,CAAE,CACtE,CAGA,SAAgBC,GAAoB,CAClC,EAAQ,IACV,CAkBA,SAAgBC,GAAsB,CACpC,OAAOH,IAAU,IACnB,CAEA,SAASI,EAAS,EAAY,EAAuB,CACnD,GAAIC,EAAK,WAAa,EAAG,MAAO,GAChC,IAAMC,EAAQD,EAAiB,KAE/B,OAAOC,IAASC,GAASA,IAAS,KAAOD,EAAK,WAAW,KAAK,CAChE,CAQA,SAASE,EAAQ,EAAe,EAAkC,EAAwB,CACxF,IAAMC,EAAmB,CAACC,CAAI,EAC9B,KAAOD,EAAM,OAAS,GAAG,CACvB,IAAME,EAASF,EAAM,IAAI,EACrBG,EAA0BD,EAAO,WACrC,KAAOC,IAAU,MAAM,CACrB,IAAMC,EAA8BD,EAAM,YAC1C,GAAIR,EAASQ,EAAO,GAAG,EAAG,CACxB,IAAME,EAAkB,CAAC,EACrBC,EAAQ,EACRC,EAA2BJ,EAAM,YACrC,KAAOI,IAAW,MAAM,CACtB,GAAIZ,EAASY,EAAQ,GAAG,EAAG,GAAS,OAC/B,GAAIZ,EAASY,EAAQ,GAAG,IAC3B,IACID,IAAU,GAAG,MAEnBD,EAAQ,KAAKE,CAAM,EACnB,EAASA,EAAO,WAClB,CACA,IAAMC,EAA0BD,IAAW,KAAO,KAAOA,EAAO,YAChEE,EAAO,KAAKJ,CAAO,EACnB,IAAK,IAAMT,KAAQS,EAASH,EAAO,YAAYN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CACA,OAAO9B,CACT,CAQA,SAAgBgC,EAAwB,EAAkB,CACxD,IAAMT,EAAQ,MAAM,KAAKD,EAAK,UAAU,EACxC,IAAK,IAAIE,EAAO,EAAGA,EAAOD,EAAM,OAAQ,GAAQ,EAAG,CACjD,IAAMU,EAAUV,EAAMC,GACtB,GAAIS,IAAY,IAAA,IAAaA,EAAQ,WAAa,EAAG,SACrD,IAAMxC,EAAQwC,EAAoB,KAClC,GAAI,CAACxC,EAAK,WAAW0B,CAAW,EAAG,SACnC,IAAMO,EAAQH,EAAM,WACjB,EAAM,IACLI,EAAQH,GAAQC,EAAUlC,EAAM6B,EAAe3B,EAAK,MAAM,CAAkB,CAAC,CACjF,EACMyC,EAAOR,IAAU,GAAKF,EAAOE,EACnC,IAAK,IAAMnC,KAAQgC,EAAM,MAAMC,EAAMU,EAAO,CAAC,EACvC3C,EAAK,aAAe+B,GAAMA,EAAK,YAAY/B,CAAI,EAErD,EAAO2C,CACT,CACF,CAEA,SAAST,EAAU,EAAY,EAAuB,CACpD,OAAOlC,EAAK,WAAa,GAAMA,EAAiB,OAASE,CAC3D,CAEA,SAASmC,EAAe,EAA2B,CACjD,OAAOO,EAAQ,OAAS,KAAOA,EAAQ,OAAS,GAClD,C"}
|
|
1
|
+
{"version":3,"file":"claim.js","names":["state","beginClaiming","registry","recoverable","endClaiming","isClaiming","isMarker","node","data","text","prepare","root","pending","lifted","stack","parent","child","following","content","depth","cursor","after","queue","claimElement","key","current","element","TEXT_ONLY","isTextOnly","takeRegion","anchorNode","liftedRegions","withoutClaiming","fn","saved","PORTAL_OPEN","PORTAL_CLOSE","claimPortal","body","nodes","open","isComment","close","index","isRegionMarker","own","keyed","hk","releaseUnclaimedPortals","opening","last","comment"],"sources":["../../../src/internal/claim.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, devtoolsReport } from \"@shadow-js/core/extend\";\n\n/** What a hydration pass in progress knows. Exists only while `hydrate()` runs its synchronous pass. */\ninterface HydrationState {\n /** Server elements by `data-hk` key; entries are consumed when claimed. */\n readonly registry: Map<string, Element>;\n /** Told about each mismatch the pass repaired (the `onRecoverableError` option). */\n readonly recoverable: ((error: unknown) => void) | undefined;\n /** Region contents taken out of each claimed parent, in document order. */\n readonly pending: WeakMap<Node, Node[][]>;\n /** The content of every region lifted out of a claimed element, in document order (read by `NoHydration`). */\n readonly lifted: Node[][];\n}\n\nlet state: HydrationState | null = null;\n\n/** Starts a claiming pass over the given server elements. @internal */\nexport function beginClaiming(\n registry: Map<string, Element>,\n recoverable?: (error: unknown) => void,\n): void {\n state = { registry, recoverable, pending: new WeakMap(), lifted: [] };\n}\n\n/** Ends the claiming pass. @internal */\nexport function endClaiming(): void {\n state = null;\n}\n\n/**\n * Reports whether a `hydrate()` pass is claiming server DOM right now: a custom renderer reads it to\n * decide between adopting server nodes and building fresh ones. The pass is synchronous, so this is\n * `false` again once `hydrate()` returns, and in every later update.\n *\n * @returns `true` during the synchronous pass of `hydrate()` (outside {@link withoutClaiming}),\n * `false` otherwise.\n * @example\n * import { isClaiming } from \"@shadow-js/web/extend\";\n *\n * function describe(): string {\n * return isClaiming() ? \"adopting server markup\" : \"building fresh DOM\";\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function isClaiming(): boolean {\n return state !== null;\n}\n\nfunction isMarker(node: Node, data: string): boolean {\n if (node.nodeType !== 8) return false;\n const text = (node as Comment).data;\n // `[b:ID` opens a Suspense boundary region (streaming); it hydrates like a plain region.\n return text === data || (data === \"[\" && text.startsWith(\"[b:\"));\n}\n\n/**\n * Turns server markup for one template into the shape a freshly cloned template has: region\n * contents are lifted out (to be re-inserted by `insert`), marker comments are removed and text\n * nodes are merged again. Iterative; static elements below the root are walked, regions are not\n * (their contents belong to other templates, claimed later through the registry).\n */\nfunction prepare(root: Element, pending: WeakMap<Node, Node[][]>, lifted: Node[][]): void {\n const stack: Element[] = [root];\n while (stack.length > 0) {\n const parent = stack.pop() as Element;\n let child: ChildNode | null = parent.firstChild;\n while (child !== null) {\n const following: ChildNode | null = child.nextSibling;\n if (isMarker(child, \"[\")) {\n const content: Node[] = [];\n let depth = 1;\n let cursor: ChildNode | null = child.nextSibling;\n while (cursor !== null) {\n if (isMarker(cursor, \"[\")) depth += 1;\n else if (isMarker(cursor, \"]\")) {\n depth -= 1;\n if (depth === 0) break;\n }\n content.push(cursor);\n cursor = cursor.nextSibling;\n }\n const after: ChildNode | null = cursor === null ? null : cursor.nextSibling;\n lifted.push(content);\n for (const node of content) parent.removeChild(node);\n parent.removeChild(child);\n if (cursor !== null) parent.removeChild(cursor);\n const queue = pending.get(parent);\n if (queue === undefined) pending.set(parent, [content]);\n else queue.push(content);\n child = after;\n continue;\n }\n if (child.nodeType === 1) stack.push(child as Element);\n child = following;\n }\n }\n root.normalize();\n}\n\n/**\n * Adopts the server's element for a hydration key while `hydrate()` runs: the step that lets a custom\n * template reuse server markup instead of creating new nodes. The element loses its `data-hk`\n * attribute, and the content of its regions is lifted out, to be adopted by {@link takeRegion} when\n * the regions bind. Prefer `claims.current.claimElement`, which links this code only into apps that\n * call `hydrate()`.\n *\n * @param key The key from `nextKey()`, drawn where the server drew it. Undefined claims nothing.\n * @returns The server element; `null` when no hydration pass is running, when `key` is undefined, or\n * when the server sent no element for the key (the caller then creates the node itself). A missing\n * key is a recoverable mismatch: development builds warn `HYDRATION_KEY_MISS`, and the pass's\n * `onRecoverableError` receives an `Error`.\n * @example\n * import { claimElement, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createPanel(): Element {\n * // During hydrate(): the server's <section>. Otherwise: a new one.\n * return claimElement(nextKey()) ?? document.createElement(\"section\");\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function claimElement(key: string | undefined): Element | null {\n const current = state;\n if (current === null || key === undefined) return null;\n const element = current.registry.get(key);\n if (element === undefined) {\n // Production keeps only the code (the same split as core's messages): the text stays out of the bundle.\n if (__DEV__) {\n const message = `No server element for key \"${key}\".`;\n console.warn(`[shadow HYDRATION_KEY_MISS] ${message}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, message, key, undefined);\n }\n current.recoverable?.(\n new Error(__DEV__ ? `No server element for key \"${key}\".` : \"SHADOW_HYDRATION_KEY_MISS\"),\n );\n return null;\n }\n current.registry.delete(key);\n element.removeAttribute(\"data-hk\");\n prepare(element, current.pending, current.lifted);\n return element;\n}\n\n/** Characters that stay readable as escapes in a diagnostic snippet: markup, quotes and ampersands. */\nconst SNIPPET_ESCAPES: ReadonlyMap<string, string> = new Map([\n [\"<\", \"\\\\u003c\"],\n [\">\", \"\\\\u003e\"],\n [\"&\", \"\\\\u0026\"],\n ['\"', \"\\\\u0022\"],\n [\"'\", \"\\\\u0027\"],\n]);\n\n/**\n * Escapes text for a diagnostic snippet and cuts it to `limit` output characters, with `...` when cut.\n * Escapes are never split, so the output is at most `limit + 3` characters.\n * @internal\n */\nfunction snippet(text: string, limit: number): string {\n let out = \"\";\n for (const char of text) {\n const code = char.codePointAt(0) ?? 0;\n const controlled = code < 0x20 || (code >= 0x7f && code <= 0x9f);\n const escaped =\n SNIPPET_ESCAPES.get(char) ?? (controlled ? `\\\\u${code.toString(16).padStart(4, \"0\")}` : char);\n if (out.length + escaped.length > limit) return `${out}...`;\n out += escaped;\n }\n return out;\n}\n\n/** The opening tag of a server element as the server wrote it (attribute values as they are). */\nfunction openingMarkup(element: Element): string {\n let markup = `<${element.localName}`;\n for (const attr of Array.from(element.attributes)) markup += ` ${attr.name}=\"${attr.value}\"`;\n return `${markup}>`;\n}\n\n/**\n * Development check of a claimed element against the tag its template or `element()` call expects.\n * A different tag warns `HYDRATION_MISMATCH` on the console and in devtools, with an escaped snippet of\n * the server element (its opening tag and the start of its text, bounded). Recovery is unchanged: the\n * element is still adopted, nothing is thrown or replaced, and the caller gets the same value.\n *\n * Call it under `if (__DEV__)`. Text is not compared here: the expected text is inserted later, by\n * `insert`, and {@link checkClaimedText} compares it with the server text at that point.\n *\n * @param element The server element `claimElement` returned.\n * @param expectedTag The tag the client expects (any case).\n * @internal\n */\nexport function checkClaimedTag(element: Element, expectedTag: string): void {\n if (!__DEV__) return;\n const expected = expectedTag.toLowerCase();\n const actual = element.localName.toLowerCase();\n if (actual === expected) return;\n const text = element.textContent ?? \"\";\n let detail = `expected <${expected}> but the server sent <${snippet(actual, 80)}>; server markup: \"${snippet(openingMarkup(element), 80)}\"`;\n if (text !== \"\") detail += `; text: \"${snippet(text, 40)}\"`;\n console.warn(`[shadow HYDRATION_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/**\n * Development check of the first commit of a region that claimed server text. The server text is the\n * DOM text of the claimed nodes (already decoded, so an escaped `<` compares as `<`); the expected\n * text is the strings of the first commit, joined (a number is already its string, `null` and booleans\n * render nothing, so they expect `\"\"`). Equal text is silent. Different text warns\n * `HYDRATION_TEXT_MISMATCH` on the console and in devtools, with both texts escaped and bounded to 40\n * characters. Recovery is unchanged: the region shows the value the client computed.\n *\n * Not compared, so silent: a region that claimed no nodes (an empty server region has no server text),\n * a region whose server nodes are not all text (an element, or the markers of a nested region), and a\n * commit that holds a node (an element is shown in place of the server's content, as before).\n *\n * Call it under `if (__DEV__)`, once per claimed region, at its first commit.\n *\n * @param claimed The server nodes the region adopted, in document order.\n * @param parts What the first commit shows: strings, or nodes.\n * @internal\n * @since 1.0.0\n */\nexport function checkClaimedText(\n claimed: readonly Node[],\n parts: readonly (Node | string)[],\n): void {\n if (!__DEV__) return;\n if (claimed.length === 0) return;\n let server = \"\";\n for (const node of claimed) {\n if (node.nodeType !== 3) return;\n server += node.textContent ?? \"\";\n }\n let expected = \"\";\n for (const part of parts) {\n if (typeof part !== \"string\") return;\n expected += part;\n }\n if (expected === server) return;\n const detail = `expected text \"${snippet(expected, 40)}\" but the server sent text \"${snippet(server, 40)}\"`;\n console.warn(`[shadow HYDRATION_TEXT_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/** HTML elements whose content is text and nothing else: no comment can mark a region inside them. */\nconst TEXT_ONLY = new Set([\"script\", \"style\", \"title\", \"textarea\"]);\n\n/**\n * True for a `script`, `style`, `title` or `textarea`, in whichever namespace the parser put it: `Dynamic` knows no\n * parent, so the server writes the children of such a tag without region markers even where the page parses it as\n * an SVG `title` or `style`. Its whole content is then the one region.\n */\nfunction isTextOnly(node: Node): boolean {\n return node.nodeType === 1 && TEXT_ONLY.has((node as Element).localName);\n}\n\n/**\n * Adopts the server content of the next region of a claimed parent while `hydrate()` runs: the nodes\n * that sat between the region's markers are put back before `anchorNode` and returned, so a custom\n * region can bind to them instead of inserting new nodes. Regions are taken in document order.\n *\n * @param parent An element returned by {@link claimElement} (or one of its descendants).\n * @param anchorNode The node the content goes before; `null` appends it at the end of `parent`.\n * @returns The adopted nodes; undefined when no hydration pass is running or `parent` has no region\n * left to adopt (the caller then inserts fresh nodes). A `script`, `style`, `title` or `textarea` has no\n * markers (the server writes its text as the parser reads it): its current children are the region.\n * @example\n * import { takeRegion } from \"@shadow-js/web/extend\";\n *\n * function fillRegion(parent: Element): Node[] {\n * const adopted = takeRegion(parent, null);\n * if (adopted !== undefined) return adopted;\n * const text = document.createTextNode(\"fresh\");\n * parent.append(text);\n * return [text];\n * }\n * @see claimElement\n * @since 1.0.0\n */\nexport function takeRegion(parent: Node, anchorNode: Node | null): Node[] | undefined {\n const current = state;\n if (current === null) return undefined;\n const content = current.pending.get(parent)?.shift();\n if (content === undefined) return isTextOnly(parent) ? Array.from(parent.childNodes) : undefined;\n for (const node of content) parent.insertBefore(node, anchorNode);\n return content;\n}\n\n/**\n * The content of every region the pass lifted out of the server elements it claimed, in document order. `NoHydration` finds\n * its own markers in them. Undefined outside a hydration pass.\n * @internal\n */\nexport function liftedRegions(): readonly (readonly Node[])[] | undefined {\n return state?.lifted;\n}\n\n/**\n * Runs `fn` with claiming switched off, so the templates it builds are created fresh instead of\n * claimed from the server markup. Use it for content the server did not render (a portal the server\n * sent nothing for), so its keys are not reported as missing. The previous state is restored when\n * `fn` returns or throws.\n *\n * @param fn The code to run. It runs synchronously, once.\n * @returns What `fn` returns. An error `fn` throws propagates.\n * @example\n * import { template } from \"@shadow-js/web\";\n * import { withoutClaiming } from \"@shadow-js/web/extend\";\n *\n * const makeTip = template(`<div class=\"tip\"></div>`);\n * const tip = withoutClaiming(() => makeTip()); // a fresh clone, even during hydrate()\n * @see claims\n * @since 1.0.0\n */\nexport function withoutClaiming<T>(fn: () => T): T {\n const saved = state;\n state = null;\n try {\n return fn();\n } finally {\n state = saved;\n }\n}\n\n/** Comment that opens the server block of a portal (`<!--portal:KEY-->`). */\nconst PORTAL_OPEN = \"portal:\";\n/** Comment that closes it (`<!--/portal:KEY-->`). */\nconst PORTAL_CLOSE = \"/portal:\";\n\n/**\n * Adopts the server block of a portal while `hydrate()` runs. The server writes each portal's markup\n * at the end of `<body>` between `<!--portal:KEY-->` and `<!--/portal:KEY-->` comments (see\n * `createServerPortals`); this removes the comments, leaves the content in place, and registers its\n * keyed elements so the portal's templates claim them.\n *\n * @param key The portal's key from `nextKey()`. Undefined claims nothing.\n * @returns The nodes of the block, in place in the body; undefined when no hydration pass is running,\n * `key` is undefined, there is no document body, or the server sent no complete block for the key.\n * @example\n * import { claimPortal, nextKey } from \"@shadow-js/web/extend\";\n *\n * function mountOverlay(build: () => Node): Node[] {\n * const adopted = claimPortal(nextKey());\n * if (adopted !== undefined) return adopted;\n * const node = build();\n * document.body.append(node);\n * return [node];\n * }\n * @since 1.0.0\n */\nexport function claimPortal(key: string | undefined): Node[] | undefined {\n const current = state;\n if (current === null || key === undefined || typeof document === \"undefined\") return undefined;\n const body = document.body;\n if (body === null) return undefined;\n const nodes = Array.from(body.childNodes);\n const open = nodes.findIndex((node) => isComment(node, PORTAL_OPEN + key));\n if (open === -1) return undefined;\n const close = nodes.findIndex(\n (node, index) => index > open && isComment(node, PORTAL_CLOSE + key),\n );\n if (close === -1) return undefined;\n // The content stays where the server put it (the region adopts it in place); only the markers go.\n const content: Node[] = [];\n for (const node of nodes.slice(open + 1, close)) {\n if (node.nodeType === 8 && isRegionMarker(node as Comment)) body.removeChild(node);\n else content.push(node);\n }\n for (const node of [nodes[open], nodes[close]]) {\n if (node !== undefined) body.removeChild(node);\n }\n for (const node of content) {\n if (node.nodeType !== 1) continue;\n const element = node as Element;\n const own = element.getAttribute(\"data-hk\");\n if (own !== null) current.registry.set(own, element);\n for (const keyed of Array.from(element.querySelectorAll(\"[data-hk]\"))) {\n const hk = keyed.getAttribute(\"data-hk\");\n if (hk !== null) current.registry.set(hk, keyed);\n }\n }\n return content;\n}\n\n/**\n * Removes the server blocks of portals that were not claimed during the pass: the client did not render\n * those portals, so their markup must not stay in the page. Each block goes with its comments. A block\n * without its closing comment loses only its opening one.\n * @internal\n */\nexport function releaseUnclaimedPortals(body: Node): void {\n const nodes = Array.from(body.childNodes);\n for (let open = 0; open < nodes.length; open += 1) {\n const opening = nodes[open];\n if (opening === undefined || opening.nodeType !== 8) continue;\n const data = (opening as Comment).data;\n if (!data.startsWith(PORTAL_OPEN)) continue;\n const close = nodes.findIndex(\n (node, index) =>\n index > open && isComment(node, PORTAL_CLOSE + data.slice(PORTAL_OPEN.length)),\n );\n const last = close === -1 ? open : close;\n for (const node of nodes.slice(open, last + 1)) {\n if (node.parentNode === body) body.removeChild(node);\n }\n open = last;\n }\n}\n\nfunction isComment(node: Node, data: string): boolean {\n return node.nodeType === 8 && (node as Comment).data === data;\n}\n\nfunction isRegionMarker(comment: Comment): boolean {\n return comment.data === \"[\" || comment.data === \"]\";\n}\n"],"mappings":"A,+BAcA,IAAIA,EAA+B,KAGnC,SAAgBC,EACdC,EACAC,EACM,CACNH,EAAQ,CAAEE,WAAUC,cAAa,wBAAS,IAAI,QAAW,OAAQ,CAAC,CAAE,CACtE,CAGA,SAAgBC,GAAoB,CAClCJ,EAAQ,IACV,CAkBA,SAAgBK,GAAsB,CACpC,OAAOL,IAAU,IACnB,CAEA,SAASM,EAASC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U,GAAKF,EAAOE,EACnC,IAAK,IAAMnC,KAAQgC,EAAM,MAAMC,EAAMU,EAAO,CAAC,EACvC3C,EAAK,aAAe+B,GAAMA,EAAK,YAAY/B,CAAI,EAErDiC,EAAOU,CACT,CACF,CAEA,SAAST,EAAUlC,EAAYC,EAAuB,CACpD,OAAOD,EAAK,WAAa,GAAMA,EAAiB,OAASC,CAC3D,CAEA,SAASoC,EAAeO,EAA2B,CACjD,OAAOA,EAAQ,OAAS,KAAOA,EAAQ,OAAS,GAClD,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"css-units.js","names":["UNITLESS","cssValueText","
|
|
1
|
+
{"version":3,"file":"css-units.js","names":["UNITLESS","cssValueText","property","value","bare"],"sources":["../../../src/internal/css-units.ts"],"sourcesContent":["/**\n * React's unitless style properties. A number given to any other property is in pixels (`0` stays\n * `0`); these properties take the bare number. Vendor prefixes do not change the answer.\n *\n * The compiler never needs this table for static values, and `class-style.ts` and the server\n * stylesheet writer are the only importers, so it is linked only where a style is written.\n * @internal\n */\nconst UNITLESS =\n /^(?:animation-iteration-count|aspect-ratio|border-image-(?:outset|slice|width)|box-(?:flex(?:-group)?|ordinal-group)|column-count|columns|flex(?:-(?:grow|positive|shrink|negative|order))?|grid-(?:area|(?:row|column)(?:-(?:end|span|start))?)|font-weight|line-(?:clamp|height)|opacity|order|orphans|scale|tab-size|widows|z-index|zoom|(?:fill|flood|stop|stroke)-opacity|stroke-(?:dasharray|dashoffset|miterlimit|width))$/;\n\n/**\n * The CSS text of one style value. A finite or non-finite number gets `px` unless it is zero, a\n * custom property (`--x`) or unitless; every other value is `String(value)`.\n * @param property The CSS property in kebab-case (`toCssProperty` output).\n * @param value The style value.\n * @internal\n */\nexport function cssValueText(property: string, value: unknown): string {\n if (typeof value !== \"number\" || value === 0 || property.startsWith(\"--\")) return String(value);\n const bare = property.replace(/^-(?:webkit|moz|ms|o)-/, \"\");\n return UNITLESS.test(bare) ? String(value) : `${value}px`;\n}\n"],"mappings":"AAQA,MAAMA,EACJ,oaASF,SAAgBC,EAAaC,EAAkBC,EAAwB,CACrE,GAAI,OAAOA,GAAU,UAAYA,IAAU,GAAKD,EAAS,WAAW,IAAI,EAAG,OAAO,OAAOC,CAAK,EAC9F,IAAMC,EAAOF,EAAS,QAAQ,yBAA0B,EAAE,EAC1D,OAAOF,EAAS,KAAKI,CAAI,EAAI,OAAOD,CAAK,EAAI,GAAGA,EAAM,GACxD,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diagnostics.js","names":["warnOnce","invalidAttributeName","name"],"sources":["../../../src/internal/diagnostics.ts"],"sourcesContent":["/**\n * The diagnostic codes of the DOM runtime: `UNSAFE_URL_BLOCKED` (a URL attribute that would run\n * script was not written), `INVALID_ATTRIBUTE_NAME` (a name that cannot appear in markup) and\n * `DUPLICATE_CLASS_ATTRIBUTE` (one element carries `class` and `className`, so the parser drops one)\n * `SRCDOC_DYNAMIC` (a value computed at run time was written to `srcdoc`, an HTML sink) and\n * `DYNAMIC_SVG_CASE` (`Dynamic` was given an SVG element name in a case SVG does not spell it in).\n * @since 1.0.0\n */\nexport type WebWarningCode =\n | \"UNSAFE_URL_BLOCKED\"\n | \"INVALID_ATTRIBUTE_NAME\"\n | \"DUPLICATE_CLASS_ATTRIBUTE\"\n | \"SRCDOC_DYNAMIC\"\n | \"DYNAMIC_SVG_CASE\";\n\n/** The codes reported, and the `code:key` pairs of the warnings that pass a key. */\nconst seen = new Set<string>();\n\n/**\n * Prints a development warning as `[shadow CODE] detail`, at most once per code for the life of the\n * page or process (the same pattern as core's `warn`): for a custom renderer that refuses a value the\n * way the built-in ones do. Production builds print nothing.\n *\n * @param code The diagnostic code. A code that was already reported is ignored, whatever the detail.\n * @param detail The text after the code.\n * @param key Optional. With a key the warning is once per `code` and `key` instead of once per code, for a\n * warning about a name where each name deserves a report. Pass a bounded set of keys: each is remembered.\n * @example\n * import { isUnsafeUrlAttribute, warnOnce } from \"@shadow-js/web/extend\";\n *\n * function setLink(el: Element, url: string): void {\n * if (isUnsafeUrlAttribute(\"href\", url)) {\n * warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL: ${url}`);\n * return;\n * }\n * el.setAttribute(\"href\", url);\n * }\n * @since 1.0.0\n */\nexport function warnOnce(code: WebWarningCode, detail: string, key?: string): void {\n if (!__DEV__) return;\n const id = key === undefined ? code : `${code}:${key}`;\n if (seen.has(id)) return;\n seen.add(id);\n console.warn(`[shadow ${code}] ${detail}`);\n}\n\n/**\n * The text of the `SRCDOC_DYNAMIC` warning, shared by the client and the server writer. `srcdoc` is a whole HTML\n * document the frame runs, so it has the trust of `innerHTML`, not of a URL: no scheme check applies to it.\n * @internal\n */\nexport const SRCDOC_DYNAMIC_DETAIL =\n 'A computed value was written to \"srcdoc\". It is an HTML document the frame runs, with the trust of innerHTML: sanitize it, and add the sandbox attribute to the frame.';\n\n/** Forgets which codes were already reported. Used by tests; not part of the public surface. @internal */\nexport function resetWebWarningDedupe(): void {\n seen.clear();\n}\n\n/**\n * Error thrown for attribute names that cannot appear in markup. Dev builds carry the full text;\n * production keeps the code and the name (the same split as core's messages).\n * @internal\n */\nexport function invalidAttributeName(name: string): TypeError {\n if (!__DEV__) return new TypeError(`SHADOW_INVALID_ATTRIBUTE_NAME: \"${name}\"`);\n return new TypeError(`[shadow INVALID_ATTRIBUTE_NAME] \"${name}\" is not a valid attribute name.`);\n}\n"],"mappings":"AAuCA,SAAgBA,
|
|
1
|
+
{"version":3,"file":"diagnostics.js","names":["warnOnce","code","detail","key","invalidAttributeName","name"],"sources":["../../../src/internal/diagnostics.ts"],"sourcesContent":["/**\n * The diagnostic codes of the DOM runtime: `UNSAFE_URL_BLOCKED` (a URL attribute that would run\n * script was not written), `INVALID_ATTRIBUTE_NAME` (a name that cannot appear in markup) and\n * `DUPLICATE_CLASS_ATTRIBUTE` (one element carries `class` and `className`, so the parser drops one)\n * `SRCDOC_DYNAMIC` (a value computed at run time was written to `srcdoc`, an HTML sink) and\n * `DYNAMIC_SVG_CASE` (`Dynamic` was given an SVG element name in a case SVG does not spell it in).\n * @since 1.0.0\n */\nexport type WebWarningCode =\n | \"UNSAFE_URL_BLOCKED\"\n | \"INVALID_ATTRIBUTE_NAME\"\n | \"DUPLICATE_CLASS_ATTRIBUTE\"\n | \"SRCDOC_DYNAMIC\"\n | \"DYNAMIC_SVG_CASE\";\n\n/** The codes reported, and the `code:key` pairs of the warnings that pass a key. */\nconst seen = new Set<string>();\n\n/**\n * Prints a development warning as `[shadow CODE] detail`, at most once per code for the life of the\n * page or process (the same pattern as core's `warn`): for a custom renderer that refuses a value the\n * way the built-in ones do. Production builds print nothing.\n *\n * @param code The diagnostic code. A code that was already reported is ignored, whatever the detail.\n * @param detail The text after the code.\n * @param key Optional. With a key the warning is once per `code` and `key` instead of once per code, for a\n * warning about a name where each name deserves a report. Pass a bounded set of keys: each is remembered.\n * @example\n * import { isUnsafeUrlAttribute, warnOnce } from \"@shadow-js/web/extend\";\n *\n * function setLink(el: Element, url: string): void {\n * if (isUnsafeUrlAttribute(\"href\", url)) {\n * warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL: ${url}`);\n * return;\n * }\n * el.setAttribute(\"href\", url);\n * }\n * @since 1.0.0\n */\nexport function warnOnce(code: WebWarningCode, detail: string, key?: string): void {\n if (!__DEV__) return;\n const id = key === undefined ? code : `${code}:${key}`;\n if (seen.has(id)) return;\n seen.add(id);\n console.warn(`[shadow ${code}] ${detail}`);\n}\n\n/**\n * The text of the `SRCDOC_DYNAMIC` warning, shared by the client and the server writer. `srcdoc` is a whole HTML\n * document the frame runs, so it has the trust of `innerHTML`, not of a URL: no scheme check applies to it.\n * @internal\n */\nexport const SRCDOC_DYNAMIC_DETAIL =\n 'A computed value was written to \"srcdoc\". It is an HTML document the frame runs, with the trust of innerHTML: sanitize it, and add the sandbox attribute to the frame.';\n\n/** Forgets which codes were already reported. Used by tests; not part of the public surface. @internal */\nexport function resetWebWarningDedupe(): void {\n seen.clear();\n}\n\n/**\n * Error thrown for attribute names that cannot appear in markup. Dev builds carry the full text;\n * production keeps the code and the name (the same split as core's messages).\n * @internal\n */\nexport function invalidAttributeName(name: string): TypeError {\n if (!__DEV__) return new TypeError(`SHADOW_INVALID_ATTRIBUTE_NAME: \"${name}\"`);\n return new TypeError(`[shadow INVALID_ATTRIBUTE_NAME] \"${name}\" is not a valid attribute name.`);\n}\n"],"mappings":"AAuCA,SAAgBA,EAASC,EAAsBC,EAAgBC,EAAoB,CAMnF,CAoBA,SAAgBC,EAAqBC,EAAyB,CAC9C,MAAO,gBAAI,UAAU,mCAAmCA,EAAK,EAAE,CAE/E,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"early-events.js","names":["DEFAULT_EARLY_EVENTS","EARLY_CAPTURE_KEY","EVENT_NAME","captureScriptBody","names","name","readCapture","value","queue","listener","item","reissue","
|
|
1
|
+
{"version":3,"file":"early-events.js","names":["DEFAULT_EARLY_EVENTS","EARLY_CAPTURE_KEY","EVENT_NAME","captureScriptBody","names","name","readCapture","value","queue","listener","item","reissue","event","init","replayEarlyEvents","capture","target","withoutDefaultAction","prevented"],"sources":["../../../src/internal/early-events.ts"],"sourcesContent":["/**\n * Early event capture (ADR-016): a tiny inline script, placed before the bundle, records the events a\n * user makes before the application has hydrated. `hydrate()` then replays them once its handlers are\n * attached, so a click made while the page was still loading is not lost. The script is generated by\n * `generateHydrationScript` on the server; the replay is the client half, and it does nothing when the\n * page has no captured events.\n */\n\n/** The event types recorded when a page does not name its own. @internal */\nexport const DEFAULT_EARLY_EVENTS: readonly string[] = [\"click\", \"input\"];\n\n/** The window property the capture script writes. Its shape is checked before use. @internal */\nexport const EARLY_CAPTURE_KEY = \"__SHADOWJS_EARLY__\";\n\n/**\n * The most events the capture script keeps. A page whose bundle never loads would otherwise hold every\n * click and keystroke of the visit; the first ones are the ones worth replaying. @internal\n */\nexport const MAX_EARLY_EVENTS = 100;\n\n/** Event names are plain lower-case words: anything else would end up inside the script text. */\nconst EVENT_NAME = /^[a-z]+$/;\n\n/**\n * The inline script body. A capture listener on the document (capture phase, so it sees events even\n * when a page stops their propagation) queues each event; the queue and the listener are kept on\n * `window` for the replay.\n * @internal\n */\nexport function captureScriptBody(names: readonly string[]): string {\n const list = JSON.stringify(names.filter((name) => EVENT_NAME.test(name)));\n return (\n \"(function(){var d=document,n=\" +\n list +\n `,q=[];function c(e){if(q.length<${MAX_EARLY_EVENTS})q.push(e)}` +\n \"for(var i=0;i<n.length;i++)d.addEventListener(n[i],c,true);\" +\n `window.${EARLY_CAPTURE_KEY}={queue:q,names:n,listener:c};})();`\n );\n}\n\ninterface Capture {\n readonly queue: Event[];\n readonly names: string[];\n readonly listener: (event: Event) => void;\n}\n\n/** The capture the script left on the window, validated, or undefined. */\nfunction readCapture(): Capture | undefined {\n const value: unknown = Reflect.get(globalThis, EARLY_CAPTURE_KEY);\n if (typeof value !== \"object\" || value === null) return undefined;\n const queue: unknown = Reflect.get(value, \"queue\");\n const names: unknown = Reflect.get(value, \"names\");\n const listener: unknown = Reflect.get(value, \"listener\");\n if (!Array.isArray(queue) || !Array.isArray(names) || typeof listener !== \"function\") {\n return undefined;\n }\n const events = queue.filter((item): item is Event => item instanceof Event);\n const kinds = names.filter((name): name is string => typeof name === \"string\");\n return { queue: events, names: kinds, listener: listener as (event: Event) => void };\n}\n\n/** A new event of the same type that bubbles like the original and carries its pointer position. */\nfunction reissue(event: Event): Event {\n const init: EventInit = { bubbles: true, cancelable: event.cancelable, composed: true };\n if (event instanceof MouseEvent) {\n return new MouseEvent(event.type, {\n ...init,\n clientX: event.clientX,\n clientY: event.clientY,\n button: event.button,\n buttons: event.buttons,\n altKey: event.altKey,\n ctrlKey: event.ctrlKey,\n metaKey: event.metaKey,\n shiftKey: event.shiftKey,\n });\n }\n return new Event(event.type, init);\n}\n\n/**\n * Stops the capture and replays what it recorded, in order, on the elements they were made on. Called\n * by `hydrate()` after the handlers are attached. Does nothing when no capture ran.\n * @internal\n */\nexport function replayEarlyEvents(): void {\n const capture = readCapture();\n if (capture === undefined) return;\n Reflect.deleteProperty(globalThis, EARLY_CAPTURE_KEY);\n for (const name of capture.names) document.removeEventListener(name, capture.listener, true);\n for (const event of capture.queue) {\n const target = event.target;\n if (target instanceof Node) target.dispatchEvent(withoutDefaultAction(reissue(event)));\n }\n}\n\n/**\n * The replayed event runs the page's handlers, not the browser's default action: the real event\n * already ran it when the user made it. A dispatched `click` on a link follows the link, so without\n * this a link was followed twice. The native flag is set right away, which cancels the default action,\n * and the handlers still see `defaultPrevented` as false (a router skips a click that is already\n * prevented) until one of them prevents it itself.\n */\nfunction withoutDefaultAction(event: Event): Event {\n event.preventDefault();\n let prevented = false;\n Object.defineProperties(event, {\n defaultPrevented: { get: () => prevented },\n preventDefault: {\n value: () => {\n prevented = true;\n },\n },\n });\n return event;\n}\n"],"mappings":"AASA,MAAaA,EAA0C,CAAC,QAAS,OAAO,EAG3DC,EAAoB,qBAS3BC,EAAa,WAQnB,SAAgBC,EAAkBC,EAAkC,CAElE,MACE,gCAFW,KAAK,UAAUA,EAAM,OAAQC,GAASH,EAAW,KAAKG,CAAI,CAAC,CAGnE,EACH,mHAEUJ,EAAkB,oCAEhC,CASA,SAASK,GAAmC,CAC1C,IAAMC,EAAiB,QAAQ,IAAI,WAAYN,CAAiB,EAChE,GAAI,OAAOM,GAAU,WAAYA,EAAgB,OACjD,IAAMC,EAAiB,QAAQ,IAAID,EAAO,OAAO,EAC3CH,EAAiB,QAAQ,IAAIG,EAAO,OAAO,EAC3CE,EAAoB,QAAQ,IAAIF,EAAO,UAAU,EACvD,GAAK,MAAM,QAAQC,CAAK,GAAM,MAAM,QAAQJ,CAAK,GAAK,OAAOK,GAAa,WAK1E,MAAO,CAAE,MAFMD,EAAM,OAAQE,GAAwBA,aAAgB,KAEhD,EAAG,MADVN,EAAM,OAAQC,GAAyB,OAAOA,GAAS,QAClC,EAAaI,UAAmC,CACrF,CAGA,SAASE,EAAQC,EAAqB,CACpC,IAAMC,EAAkB,CAAE,QAAS,GAAM,WAAYD,EAAM,WAAY,SAAU,EAAK,EActF,OAbIA,aAAiB,WACZ,IAAI,WAAWA,EAAM,KAAM,CAChC,GAAGC,EACH,QAASD,EAAM,QACf,QAASA,EAAM,QACf,OAAQA,EAAM,OACd,QAASA,EAAM,QACf,OAAQA,EAAM,OACd,QAASA,EAAM,QACf,QAASA,EAAM,QACf,SAAUA,EAAM,QAClB,CAAC,EAEI,IAAI,MAAMA,EAAM,KAAMC,CAAI,CACnC,CAOA,SAAgBC,GAA0B,CACxC,IAAMC,EAAUT,EAAY,EAC5B,GAAIS,IAAY,IAAA,GAChB,SAAQ,eAAe,WAAYd,CAAiB,EACpD,IAAK,IAAMI,KAAQU,EAAQ,MAAO,SAAS,oBAAoBV,EAAMU,EAAQ,SAAU,EAAI,EAC3F,IAAK,IAAMH,KAASG,EAAQ,MAAO,CACjC,IAAMC,EAASJ,EAAM,OACjBI,aAAkB,MAAMA,EAAO,cAAcC,EAAqBN,EAAQC,CAAK,CAAC,CAAC,CACvF,CALoD,CAMtD,CASA,SAASK,EAAqBL,EAAqB,CACjDA,EAAM,eAAe,EACrB,IAAIM,EAAY,GAShB,OARA,OAAO,iBAAiBN,EAAO,CAC7B,iBAAkB,CAAE,QAAWM,CAAU,EACzC,eAAgB,CACd,UAAa,CACXA,EAAY,EACd,CACF,CACF,CAAC,EACMN,CACT,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hydration-hooks.js","names":["claims","fn"],"sources":["../../../src/internal/hydration-hooks.ts"],"sourcesContent":["/**\n * The claiming half of hydration, as a hook. `hydrate()` installs the real implementation for the\n * length of its pass; outside a pass the hooks are idle: nothing is claimed, and the renderer builds\n * the same DOM it builds on a fresh page. Templates, regions, `Dynamic`, `Portal` and `NoHydration`\n * call through {@link claims}, so only code that reaches `hydrate()` carries the claiming code (the\n * registry, the server-block lifting and the portal scan). A custom renderer reads the same hook.\n * @since 1.0.0\n */\nexport interface Claims {\n /** Claims the server element for `key` (see `claimElement`). */\n claimElement(key: string | undefined): Element | null;\n /** Adopts the next server region of `parent` (see `takeRegion`). */\n takeRegion(parent: Node, anchorNode: Node | null): Node[] | undefined;\n /** The content of every region lifted out of a claimed element (see `liftedRegions`). */\n liftedRegions(): readonly (readonly Node[])[] | undefined;\n /** Adopts the server block of a portal (see `claimPortal`). */\n claimPortal(key: string | undefined): Node[] | undefined;\n /** True while a hydration pass claims server DOM (see `isClaiming`). */\n isClaiming(): boolean;\n /** Runs `fn` with claiming off (see `withoutClaiming`). */\n withoutClaiming<T>(fn: () => T): T;\n}\n\nconst idle: Claims = {\n claimElement: () => null,\n takeRegion: () => undefined,\n liftedRegions: () => undefined,\n claimPortal: () => undefined,\n isClaiming: () => false,\n withoutClaiming: (fn) => fn(),\n};\n\n/**\n * The claims in effect. Read at each call (never captured), so a region that is updated after its\n * hydration pass ended builds fresh DOM. Only `hydrate()` replaces it, and restores it in `finally`.\n * Outside a hydration pass every method is a no-op.\n *\n * @example\n * import { claims, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createCard(): Element {\n * // Adopts the server's element during hydrate(); builds a new one otherwise.\n * return claims.current.claimElement(nextKey()) ?? document.createElement(\"article\");\n * }\n * @see Claims\n * @since 1.0.0\n */\nexport const claims: { current: Claims } = { current: idle };\n"],"mappings":"AA+CA,MAAaA,EAA8B,CAAE,QAAS,CAvBpD,iBAAoB,KACpB,eAAkB,IAAA,GAClB,kBAAqB,IAAA,GACrB,gBAAmB,IAAA,GACnB,eAAkB,GAClB,
|
|
1
|
+
{"version":3,"file":"hydration-hooks.js","names":["claims","fn"],"sources":["../../../src/internal/hydration-hooks.ts"],"sourcesContent":["/**\n * The claiming half of hydration, as a hook. `hydrate()` installs the real implementation for the\n * length of its pass; outside a pass the hooks are idle: nothing is claimed, and the renderer builds\n * the same DOM it builds on a fresh page. Templates, regions, `Dynamic`, `Portal` and `NoHydration`\n * call through {@link claims}, so only code that reaches `hydrate()` carries the claiming code (the\n * registry, the server-block lifting and the portal scan). A custom renderer reads the same hook.\n * @since 1.0.0\n */\nexport interface Claims {\n /** Claims the server element for `key` (see `claimElement`). */\n claimElement(key: string | undefined): Element | null;\n /** Adopts the next server region of `parent` (see `takeRegion`). */\n takeRegion(parent: Node, anchorNode: Node | null): Node[] | undefined;\n /** The content of every region lifted out of a claimed element (see `liftedRegions`). */\n liftedRegions(): readonly (readonly Node[])[] | undefined;\n /** Adopts the server block of a portal (see `claimPortal`). */\n claimPortal(key: string | undefined): Node[] | undefined;\n /** True while a hydration pass claims server DOM (see `isClaiming`). */\n isClaiming(): boolean;\n /** Runs `fn` with claiming off (see `withoutClaiming`). */\n withoutClaiming<T>(fn: () => T): T;\n}\n\nconst idle: Claims = {\n claimElement: () => null,\n takeRegion: () => undefined,\n liftedRegions: () => undefined,\n claimPortal: () => undefined,\n isClaiming: () => false,\n withoutClaiming: (fn) => fn(),\n};\n\n/**\n * The claims in effect. Read at each call (never captured), so a region that is updated after its\n * hydration pass ended builds fresh DOM. Only `hydrate()` replaces it, and restores it in `finally`.\n * Outside a hydration pass every method is a no-op.\n *\n * @example\n * import { claims, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createCard(): Element {\n * // Adopts the server's element during hydrate(); builds a new one otherwise.\n * return claims.current.claimElement(nextKey()) ?? document.createElement(\"article\");\n * }\n * @see Claims\n * @since 1.0.0\n */\nexport const claims: { current: Claims } = { current: idle };\n"],"mappings":"AA+CA,MAAaA,EAA8B,CAAE,QAAS,CAvBpD,iBAAoB,KACpB,eAAkB,IAAA,GAClB,kBAAqB,IAAA,GACrB,gBAAmB,IAAA,GACnB,eAAkB,GAClB,gBAAkBC,GAAOA,EAAG,CAkBwB,CAAK,E"}
|