@velarscript/web 0.31.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/analysis/calls/intrinsics/config.d.ts +10 -0
- package/dist/analysis/calls/intrinsics/config.d.ts.map +1 -0
- package/dist/analysis/calls/intrinsics/config.js +19 -0
- package/dist/analysis/calls/intrinsics/config.js.map +1 -0
- package/dist/analysis/calls/intrinsics/forms.d.ts +10 -0
- package/dist/analysis/calls/intrinsics/forms.d.ts.map +1 -0
- package/dist/analysis/calls/intrinsics/forms.js +38 -0
- package/dist/analysis/calls/intrinsics/forms.js.map +1 -0
- package/dist/analysis/calls/intrinsics/http.d.ts +10 -0
- package/dist/analysis/calls/intrinsics/http.d.ts.map +1 -0
- package/dist/analysis/calls/intrinsics/http.js +37 -0
- package/dist/analysis/calls/intrinsics/http.js.map +1 -0
- package/dist/analysis/calls/intrinsics/reactive.d.ts +10 -0
- package/dist/analysis/calls/intrinsics/reactive.d.ts.map +1 -0
- package/dist/analysis/calls/intrinsics/reactive.js +30 -0
- package/dist/analysis/calls/intrinsics/reactive.js.map +1 -0
- package/dist/analysis/calls/intrinsics/storage.d.ts +16 -0
- package/dist/analysis/calls/intrinsics/storage.d.ts.map +1 -0
- package/dist/analysis/calls/intrinsics/storage.js +91 -0
- package/dist/analysis/calls/intrinsics/storage.js.map +1 -0
- package/dist/analysis/calls/intrinsics/web.d.ts +10 -0
- package/dist/analysis/calls/intrinsics/web.d.ts.map +1 -0
- package/dist/analysis/calls/intrinsics/web.js +100 -0
- package/dist/analysis/calls/intrinsics/web.js.map +1 -0
- package/dist/analysis/calls/intrinsics.d.ts +13 -0
- package/dist/analysis/calls/intrinsics.d.ts.map +1 -0
- package/dist/analysis/calls/intrinsics.js +31 -0
- package/dist/analysis/calls/intrinsics.js.map +1 -0
- package/dist/analysis/components/contracts.d.ts +19 -0
- package/dist/analysis/components/contracts.d.ts.map +1 -0
- package/dist/analysis/components/contracts.js +83 -0
- package/dist/analysis/components/contracts.js.map +1 -0
- package/dist/analysis/components/declaration.d.ts +4 -0
- package/dist/analysis/components/declaration.d.ts.map +1 -0
- package/dist/analysis/components/declaration.js +163 -0
- package/dist/analysis/components/declaration.js.map +1 -0
- package/dist/analysis/components/host.d.ts +61 -0
- package/dist/analysis/components/host.d.ts.map +1 -0
- package/dist/analysis/components/host.js +22 -0
- package/dist/analysis/components/host.js.map +1 -0
- package/dist/analysis/components/lifecycle.d.ts +22 -0
- package/dist/analysis/components/lifecycle.d.ts.map +1 -0
- package/dist/analysis/components/lifecycle.js +33 -0
- package/dist/analysis/components/lifecycle.js.map +1 -0
- package/dist/analysis/components/ownership.d.ts +74 -0
- package/dist/analysis/components/ownership.d.ts.map +1 -0
- package/dist/analysis/components/ownership.js +106 -0
- package/dist/analysis/components/ownership.js.map +1 -0
- package/dist/analysis/declarations.d.ts +99 -0
- package/dist/analysis/declarations.d.ts.map +1 -0
- package/dist/analysis/declarations.js +176 -0
- package/dist/analysis/declarations.js.map +1 -0
- package/dist/analysis/inference.d.ts +75 -0
- package/dist/analysis/inference.d.ts.map +1 -0
- package/dist/analysis/inference.js +257 -0
- package/dist/analysis/inference.js.map +1 -0
- package/dist/analysis/jsx/attributes.d.ts +103 -0
- package/dist/analysis/jsx/attributes.d.ts.map +1 -0
- package/dist/analysis/jsx/attributes.js +601 -0
- package/dist/analysis/jsx/attributes.js.map +1 -0
- package/dist/analysis/jsx/elements.d.ts +17 -0
- package/dist/analysis/jsx/elements.d.ts.map +1 -0
- package/dist/analysis/jsx/elements.js +213 -0
- package/dist/analysis/jsx/elements.js.map +1 -0
- package/dist/analysis/jsx/host.d.ts +61 -0
- package/dist/analysis/jsx/host.d.ts.map +1 -0
- package/dist/analysis/jsx/host.js +15 -0
- package/dist/analysis/jsx/host.js.map +1 -0
- package/dist/analysis/jsx/keys.d.ts +15 -0
- package/dist/analysis/jsx/keys.d.ts.map +1 -0
- package/dist/analysis/jsx/keys.js +67 -0
- package/dist/analysis/jsx/keys.js.map +1 -0
- package/dist/analysis/jsx/security.d.ts +29 -0
- package/dist/analysis/jsx/security.d.ts.map +1 -0
- package/dist/analysis/jsx/security.js +61 -0
- package/dist/analysis/jsx/security.js.map +1 -0
- package/dist/analysis/jsx-detection.d.ts +49 -0
- package/dist/analysis/jsx-detection.d.ts.map +1 -0
- package/dist/analysis/jsx-detection.js +196 -0
- package/dist/analysis/jsx-detection.js.map +1 -0
- package/dist/analysis/keyed-rebuild.d.ts +148 -0
- package/dist/analysis/keyed-rebuild.d.ts.map +1 -0
- package/dist/analysis/keyed-rebuild.js +299 -0
- package/dist/analysis/keyed-rebuild.js.map +1 -0
- package/dist/analysis/keyframes-analysis.d.ts +6 -0
- package/dist/analysis/keyframes-analysis.d.ts.map +1 -0
- package/dist/analysis/keyframes-analysis.js +79 -0
- package/dist/analysis/keyframes-analysis.js.map +1 -0
- package/dist/analysis/look/builders.d.ts +29 -0
- package/dist/analysis/look/builders.d.ts.map +1 -0
- package/dist/analysis/look/builders.js +174 -0
- package/dist/analysis/look/builders.js.map +1 -0
- package/dist/analysis/look/conditions.d.ts +13 -0
- package/dist/analysis/look/conditions.d.ts.map +1 -0
- package/dist/analysis/look/conditions.js +84 -0
- package/dist/analysis/look/conditions.js.map +1 -0
- package/dist/analysis/look/edits.d.ts +36 -0
- package/dist/analysis/look/edits.d.ts.map +1 -0
- package/dist/analysis/look/edits.js +80 -0
- package/dist/analysis/look/edits.js.map +1 -0
- package/dist/analysis/look/entries.d.ts +56 -0
- package/dist/analysis/look/entries.d.ts.map +1 -0
- package/dist/analysis/look/entries.js +223 -0
- package/dist/analysis/look/entries.js.map +1 -0
- package/dist/analysis/look/host.d.ts +47 -0
- package/dist/analysis/look/host.d.ts.map +1 -0
- package/dist/analysis/look/host.js +16 -0
- package/dist/analysis/look/host.js.map +1 -0
- package/dist/analysis/look/tokens.d.ts +75 -0
- package/dist/analysis/look/tokens.d.ts.map +1 -0
- package/dist/analysis/look/tokens.js +156 -0
- package/dist/analysis/look/tokens.js.map +1 -0
- package/dist/analysis/look/values.d.ts +45 -0
- package/dist/analysis/look/values.d.ts.map +1 -0
- package/dist/analysis/look/values.js +148 -0
- package/dist/analysis/look/values.js.map +1 -0
- package/dist/analysis/look-conditions.d.ts +47 -0
- package/dist/analysis/look-conditions.d.ts.map +1 -0
- package/dist/analysis/look-conditions.js +157 -0
- package/dist/analysis/look-conditions.js.map +1 -0
- package/dist/analysis/look-sites.d.ts +62 -0
- package/dist/analysis/look-sites.d.ts.map +1 -0
- package/dist/analysis/look-sites.js +121 -0
- package/dist/analysis/look-sites.js.map +1 -0
- package/dist/analysis/look-values.d.ts +19 -0
- package/dist/analysis/look-values.d.ts.map +1 -1
- package/dist/analysis/look-values.js +38 -0
- package/dist/analysis/look-values.js.map +1 -1
- package/dist/analysis/look-vocabulary-guidance.d.ts +76 -0
- package/dist/analysis/look-vocabulary-guidance.d.ts.map +1 -0
- package/dist/analysis/look-vocabulary-guidance.js +338 -0
- package/dist/analysis/look-vocabulary-guidance.js.map +1 -0
- package/dist/analysis/media-conditions.d.ts +33 -0
- package/dist/analysis/media-conditions.d.ts.map +1 -0
- package/dist/analysis/media-conditions.js +92 -0
- package/dist/analysis/media-conditions.js.map +1 -0
- package/dist/analysis/program-passes.d.ts +106 -0
- package/dist/analysis/program-passes.d.ts.map +1 -0
- package/dist/analysis/program-passes.js +149 -0
- package/dist/analysis/program-passes.js.map +1 -0
- package/dist/analysis/reactivity/bindings.d.ts +37 -0
- package/dist/analysis/reactivity/bindings.d.ts.map +1 -0
- package/dist/analysis/reactivity/bindings.js +88 -0
- package/dist/analysis/reactivity/bindings.js.map +1 -0
- package/dist/analysis/reactivity/derived.d.ts +39 -0
- package/dist/analysis/reactivity/derived.d.ts.map +1 -0
- package/dist/analysis/reactivity/derived.js +80 -0
- package/dist/analysis/reactivity/derived.js.map +1 -0
- package/dist/analysis/reactivity/host.d.ts +38 -0
- package/dist/analysis/reactivity/host.d.ts.map +1 -0
- package/dist/analysis/reactivity/host.js +14 -0
- package/dist/analysis/reactivity/host.js.map +1 -0
- package/dist/analysis/reactivity/retired-accessors.d.ts +82 -0
- package/dist/analysis/reactivity/retired-accessors.d.ts.map +1 -0
- package/dist/analysis/reactivity/retired-accessors.js +118 -0
- package/dist/analysis/reactivity/retired-accessors.js.map +1 -0
- package/dist/analysis/renderable.d.ts +47 -0
- package/dist/analysis/renderable.d.ts.map +1 -0
- package/dist/analysis/renderable.js +105 -0
- package/dist/analysis/renderable.js.map +1 -0
- package/dist/analysis/routes.d.ts +64 -0
- package/dist/analysis/routes.d.ts.map +1 -0
- package/dist/analysis/routes.js +182 -0
- package/dist/analysis/routes.js.map +1 -0
- package/dist/analysis/url-attributes.d.ts +12 -0
- package/dist/analysis/url-attributes.d.ts.map +1 -0
- package/dist/analysis/url-attributes.js +48 -0
- package/dist/analysis/url-attributes.js.map +1 -0
- package/dist/analysis/watch-cycles.d.ts +102 -0
- package/dist/analysis/watch-cycles.d.ts.map +1 -1
- package/dist/analysis/watch-cycles.js +240 -1
- package/dist/analysis/watch-cycles.js.map +1 -1
- package/dist/analysis/watch-subject.d.ts +45 -0
- package/dist/analysis/watch-subject.d.ts.map +1 -0
- package/dist/analysis/watch-subject.js +272 -0
- package/dist/analysis/watch-subject.js.map +1 -0
- package/dist/analysis/web-types.d.ts +27 -0
- package/dist/analysis/web-types.d.ts.map +1 -0
- package/dist/analysis/web-types.js +170 -0
- package/dist/analysis/web-types.js.map +1 -0
- package/dist/analyzer.d.ts +18 -617
- package/dist/analyzer.d.ts.map +1 -1
- package/dist/analyzer.js +211 -4853
- package/dist/analyzer.js.map +1 -1
- package/dist/compiler.d.ts +20 -0
- package/dist/compiler.d.ts.map +1 -1
- package/dist/compiler.js +31 -864
- package/dist/compiler.js.map +1 -1
- package/dist/documentation.d.ts +28 -0
- package/dist/documentation.d.ts.map +1 -0
- package/dist/documentation.js +67 -0
- package/dist/documentation.js.map +1 -0
- package/dist/editor/completions.d.ts +12 -0
- package/dist/editor/completions.d.ts.map +1 -0
- package/dist/editor/completions.js +6 -0
- package/dist/editor/completions.js.map +1 -0
- package/dist/editor/jsx-completion.d.ts +12 -0
- package/dist/editor/jsx-completion.d.ts.map +1 -0
- package/dist/editor/jsx-completion.js +137 -0
- package/dist/editor/jsx-completion.js.map +1 -0
- package/dist/editor/look-completion.d.ts +29 -0
- package/dist/editor/look-completion.d.ts.map +1 -0
- package/dist/editor/look-completion.js +159 -0
- package/dist/editor/look-completion.js.map +1 -0
- package/dist/editor.d.ts.map +1 -1
- package/dist/editor.js +12 -288
- package/dist/editor.js.map +1 -1
- package/dist/emit/components.d.ts +33 -0
- package/dist/emit/components.d.ts.map +1 -0
- package/dist/emit/components.js +135 -0
- package/dist/emit/components.js.map +1 -0
- package/dist/emit/jsx.d.ts +57 -0
- package/dist/emit/jsx.d.ts.map +1 -0
- package/dist/emit/jsx.js +384 -0
- package/dist/emit/jsx.js.map +1 -0
- package/dist/emit/look-css.d.ts +44 -0
- package/dist/emit/look-css.d.ts.map +1 -0
- package/dist/emit/look-css.js +177 -0
- package/dist/emit/look-css.js.map +1 -0
- package/dist/emit/look.d.ts +39 -0
- package/dist/emit/look.d.ts.map +1 -0
- package/dist/emit/look.js +218 -0
- package/dist/emit/look.js.map +1 -0
- package/dist/emit/runtime-imports.d.ts +40 -0
- package/dist/emit/runtime-imports.d.ts.map +1 -0
- package/dist/emit/runtime-imports.js +188 -0
- package/dist/emit/runtime-imports.js.map +1 -0
- package/dist/emitter.d.ts +15 -68
- package/dist/emitter.d.ts.map +1 -1
- package/dist/emitter.js +79 -1008
- package/dist/emitter.js.map +1 -1
- package/dist/look/animation.d.ts +7 -0
- package/dist/look/animation.d.ts.map +1 -0
- package/dist/look/animation.js +13 -0
- package/dist/look/animation.js.map +1 -0
- package/dist/look/builders.d.ts +35 -0
- package/dist/look/builders.d.ts.map +1 -0
- package/dist/look/builders.js +74 -0
- package/dist/look/builders.js.map +1 -0
- package/dist/look/css-functions.d.ts +28 -0
- package/dist/look/css-functions.d.ts.map +1 -0
- package/dist/look/css-functions.js +54 -0
- package/dist/look/css-functions.js.map +1 -0
- package/dist/look/keyword-sets.d.ts +41 -0
- package/dist/look/keyword-sets.d.ts.map +1 -0
- package/dist/look/keyword-sets.js +117 -0
- package/dist/look/keyword-sets.js.map +1 -0
- package/dist/look/keywords.d.ts +55 -0
- package/dist/look/keywords.d.ts.map +1 -0
- package/dist/look/keywords.js +387 -0
- package/dist/look/keywords.js.map +1 -0
- package/dist/look/media.d.ts +19 -0
- package/dist/look/media.d.ts.map +1 -0
- package/dist/look/media.js +27 -0
- package/dist/look/media.js.map +1 -0
- package/dist/look/naming.d.ts +9 -0
- package/dist/look/naming.d.ts.map +1 -0
- package/dist/look/naming.js +45 -0
- package/dist/look/naming.js.map +1 -0
- package/dist/look/properties.d.ts +16 -0
- package/dist/look/properties.d.ts.map +1 -0
- package/dist/look/properties.js +52 -0
- package/dist/look/properties.js.map +1 -0
- package/dist/look/shorthands.d.ts +25 -0
- package/dist/look/shorthands.d.ts.map +1 -0
- package/dist/look/shorthands.js +130 -0
- package/dist/look/shorthands.js.map +1 -0
- package/dist/look/tokens.d.ts +38 -0
- package/dist/look/tokens.d.ts.map +1 -0
- package/dist/look/tokens.js +59 -0
- package/dist/look/tokens.js.map +1 -0
- package/dist/look/units.d.ts +24 -0
- package/dist/look/units.d.ts.map +1 -0
- package/dist/look/units.js +33 -0
- package/dist/look/units.js.map +1 -0
- package/dist/look.d.ts +32 -227
- package/dist/look.d.ts.map +1 -1
- package/dist/look.js +28 -933
- package/dist/look.js.map +1 -1
- package/dist/module-roster.d.ts +16 -0
- package/dist/module-roster.d.ts.map +1 -0
- package/dist/module-roster.js +28 -0
- package/dist/module-roster.js.map +1 -0
- package/dist/modules/app.d.ts +9 -0
- package/dist/modules/app.d.ts.map +1 -0
- package/dist/modules/app.js +20 -0
- package/dist/modules/app.js.map +1 -0
- package/dist/modules/browser-test.d.ts +9 -0
- package/dist/modules/browser-test.d.ts.map +1 -0
- package/dist/modules/browser-test.js +67 -0
- package/dist/modules/browser-test.js.map +1 -0
- package/dist/modules/browser.d.ts +10 -0
- package/dist/modules/browser.d.ts.map +1 -0
- package/dist/modules/browser.js +89 -0
- package/dist/modules/browser.js.map +1 -0
- package/dist/modules/config.d.ts +9 -0
- package/dist/modules/config.d.ts.map +1 -0
- package/dist/modules/config.js +14 -0
- package/dist/modules/config.js.map +1 -0
- package/dist/modules/files.d.ts +9 -0
- package/dist/modules/files.d.ts.map +1 -0
- package/dist/modules/files.js +16 -0
- package/dist/modules/files.js.map +1 -0
- package/dist/modules/forms.d.ts +9 -0
- package/dist/modules/forms.d.ts.map +1 -0
- package/dist/modules/forms.js +26 -0
- package/dist/modules/forms.js.map +1 -0
- package/dist/modules/http.d.ts +9 -0
- package/dist/modules/http.d.ts.map +1 -0
- package/dist/modules/http.js +127 -0
- package/dist/modules/http.js.map +1 -0
- package/dist/modules/look.d.ts +9 -0
- package/dist/modules/look.d.ts.map +1 -0
- package/dist/modules/look.js +58 -0
- package/dist/modules/look.js.map +1 -0
- package/dist/modules/realtime.d.ts +9 -0
- package/dist/modules/realtime.d.ts.map +1 -0
- package/dist/modules/realtime.js +163 -0
- package/dist/modules/realtime.js.map +1 -0
- package/dist/modules/storage.d.ts +9 -0
- package/dist/modules/storage.d.ts.map +1 -0
- package/dist/modules/storage.js +59 -0
- package/dist/modules/storage.js.map +1 -0
- package/dist/modules/types.d.ts +78 -0
- package/dist/modules/types.d.ts.map +1 -0
- package/dist/modules/types.js +154 -0
- package/dist/modules/types.js.map +1 -0
- package/dist/modules/web.d.ts +9 -0
- package/dist/modules/web.d.ts.map +1 -0
- package/dist/modules/web.js +63 -0
- package/dist/modules/web.js.map +1 -0
- package/dist/modules/websocket.d.ts +11 -0
- package/dist/modules/websocket.d.ts.map +1 -0
- package/dist/modules/websocket.js +75 -0
- package/dist/modules/websocket.js.map +1 -0
- package/dist/parser/expressions/jsx.d.ts +17 -0
- package/dist/parser/expressions/jsx.d.ts.map +1 -0
- package/dist/parser/expressions/jsx.js +43 -0
- package/dist/parser/expressions/jsx.js.map +1 -0
- package/dist/parser/expressions/keyframes.d.ts +15 -0
- package/dist/parser/expressions/keyframes.d.ts.map +1 -0
- package/dist/parser/expressions/keyframes.js +33 -0
- package/dist/parser/expressions/keyframes.js.map +1 -0
- package/dist/parser/expressions/look.d.ts +16 -0
- package/dist/parser/expressions/look.d.ts.map +1 -0
- package/dist/parser/expressions/look.js +37 -0
- package/dist/parser/expressions/look.js.map +1 -0
- package/dist/parser/expressions/visual-block.d.ts +17 -0
- package/dist/parser/expressions/visual-block.d.ts.map +1 -0
- package/dist/parser/expressions/visual-block.js +21 -0
- package/dist/parser/expressions/visual-block.js.map +1 -0
- package/dist/parser/keyframes-source.d.ts +24 -0
- package/dist/parser/keyframes-source.d.ts.map +1 -0
- package/dist/parser/keyframes-source.js +133 -0
- package/dist/parser/keyframes-source.js.map +1 -0
- package/dist/parser/look-source.d.ts +25 -0
- package/dist/parser/look-source.d.ts.map +1 -0
- package/dist/parser/look-source.js +189 -0
- package/dist/parser/look-source.js.map +1 -0
- package/dist/parser/spans.d.ts +24 -0
- package/dist/parser/spans.d.ts.map +1 -0
- package/dist/parser/spans.js +113 -0
- package/dist/parser/spans.js.map +1 -0
- package/dist/parser/statements/components.d.ts +37 -0
- package/dist/parser/statements/components.d.ts.map +1 -0
- package/dist/parser/statements/components.js +185 -0
- package/dist/parser/statements/components.js.map +1 -0
- package/dist/parser/statements/heads.d.ts +38 -0
- package/dist/parser/statements/heads.d.ts.map +1 -0
- package/dist/parser/statements/heads.js +55 -0
- package/dist/parser/statements/heads.js.map +1 -0
- package/dist/parser/statements/imports.d.ts +9 -0
- package/dist/parser/statements/imports.d.ts.map +1 -0
- package/dist/parser/statements/imports.js +31 -0
- package/dist/parser/statements/imports.js.map +1 -0
- package/dist/parser/statements/reactive.d.ts +31 -0
- package/dist/parser/statements/reactive.d.ts.map +1 -0
- package/dist/parser/statements/reactive.js +68 -0
- package/dist/parser/statements/reactive.js.map +1 -0
- package/dist/parser/statements/unsafe-css.d.ts +21 -0
- package/dist/parser/statements/unsafe-css.d.ts.map +1 -0
- package/dist/parser/statements/unsafe-css.js +42 -0
- package/dist/parser/statements/unsafe-css.js.map +1 -0
- package/dist/parser.d.ts +37 -50
- package/dist/parser.d.ts.map +1 -1
- package/dist/parser.js +98 -882
- package/dist/parser.js.map +1 -1
- package/dist/runtime-sources.generated.d.ts +1 -1
- package/dist/runtime-sources.generated.d.ts.map +1 -1
- package/dist/runtime-sources.generated.js +4 -4
- package/dist/runtime-sources.generated.js.map +1 -1
- package/package.json +2 -2
|
@@ -6,13 +6,13 @@
|
|
|
6
6
|
// JavaScript parser checks; these constants are how it is read back in.
|
|
7
7
|
import { VELAR_ERROR_NORMALIZATION_RUNTIME, VELAR_INDEX_ERROR_RUNTIME, VELAR_STRICT_JSON_RUNTIME, VELAR_TEXT_METHOD_RUNTIME, VELAR_TYPE_REGISTRY_RUNTIME, VELAR_UTF8_RUNTIME } from "@velarscript/compiler/extension";
|
|
8
8
|
/** The captured DOM ABI both `velar/web` and an emitted program's own JSX reach the document through. */
|
|
9
|
-
export const WEB_DOM_HOST_RUNTIME = "const __velarDomNativeObject = globalThis.Object;\nconst __velarDomNativeArray = globalThis.Array;\nconst __velarDomNativeSet = globalThis.Set;\nconst __velarDomNativeNumber = globalThis.Number;\nconst __velarDomNativeString = globalThis.String;\nconst __velarDomNativeSymbol = globalThis.Symbol;\nconst __velarDomReflectApply = Object.getOwnPropertyDescriptor(Reflect, \"apply\")?.value;\nconst __velarDomGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor(Object, \"getOwnPropertyDescriptor\")?.value;\nconst __velarDomGetOwnPropertyNames = Object.getOwnPropertyDescriptor(Object, \"getOwnPropertyNames\")?.value;\nconst __velarDomGetOwnPropertySymbols = Object.getOwnPropertyDescriptor(Object, \"getOwnPropertySymbols\")?.value;\nconst __velarDomGetPrototypeOf = Object.getOwnPropertyDescriptor(Object, \"getPrototypeOf\")?.value;\nconst __velarDomDefineProperty = Object.getOwnPropertyDescriptor(Object, \"defineProperty\")?.value;\nconst __velarDomArrayIsArray = Object.getOwnPropertyDescriptor(Array, \"isArray\")?.value;\nconst __velarDomNumberIsFinite = Object.getOwnPropertyDescriptor(Number, \"isFinite\")?.value;\nconst __velarDomNumberIsInteger = Object.getOwnPropertyDescriptor(Number, \"isInteger\")?.value;\nconst __velarDomSymbolHasInstance = typeof __velarDomNativeSymbol === \"function\" ? __velarDomNativeSymbol.hasInstance : null;\nconst __velarDomFunctionHasInstance = __velarDomSymbolHasInstance == null\n ? null\n : Object.getOwnPropertyDescriptor(Function.prototype, __velarDomSymbolHasInstance)?.value;\nconst __velarDomSetPrototype = typeof __velarDomNativeSet === \"function\"\n ? Object.getOwnPropertyDescriptor(__velarDomNativeSet, \"prototype\")?.value\n : null;\nconst __velarDomSetHas = __velarDomSetPrototype && Object.getOwnPropertyDescriptor(__velarDomSetPrototype, \"has\")?.value;\nconst __velarDomSetAdd = __velarDomSetPrototype && Object.getOwnPropertyDescriptor(__velarDomSetPrototype, \"add\")?.value;\nconst __velarDomSetDelete = __velarDomSetPrototype && Object.getOwnPropertyDescriptor(__velarDomSetPrototype, \"delete\")?.value;\nconst __velarDomDocument = globalThis.document ?? null;\nconst __velarDomNativeNode = typeof globalThis.Node === \"function\" ? globalThis.Node : null;\nconst __velarDomNativeElement = typeof globalThis.Element === \"function\" ? globalThis.Element : null;\nconst __velarDomNativeDocument = typeof globalThis.Document === \"function\" ? globalThis.Document : null;\nconst __velarDomNativeFragment = typeof globalThis.DocumentFragment === \"function\" ? globalThis.DocumentFragment : null;\nconst __velarDomNativeCharacterData = typeof globalThis.CharacterData === \"function\" ? globalThis.CharacterData : null;\nconst __velarDomNativeDocumentType = typeof globalThis.DocumentType === \"function\" ? globalThis.DocumentType : null;\nconst __velarDomNativeNodeList = typeof globalThis.NodeList === \"function\" ? globalThis.NodeList : null;\nconst __velarDomNativeEventTarget = typeof globalThis.EventTarget === \"function\" ? globalThis.EventTarget : null;\nconst __velarDomNativeHtmlElement = typeof globalThis.HTMLElement === \"function\" ? globalThis.HTMLElement : null;\nconst __velarDomNativeSvgElement = typeof globalThis.SVGElement === \"function\" ? globalThis.SVGElement : null;\nconst __velarDomNativeStyleDeclaration = typeof globalThis.CSSStyleDeclaration === \"function\" ? globalThis.CSSStyleDeclaration : null;\nconst __velarDomNativeTokenList = typeof globalThis.DOMTokenList === \"function\" ? globalThis.DOMTokenList : null;\nconst __velarDomNativeInputElement = typeof globalThis.HTMLInputElement === \"function\" ? globalThis.HTMLInputElement : null;\nconst __velarDomNativeTextAreaElement = typeof globalThis.HTMLTextAreaElement === \"function\" ? globalThis.HTMLTextAreaElement : null;\nconst __velarDomNativeSelectElement = typeof globalThis.HTMLSelectElement === \"function\" ? globalThis.HTMLSelectElement : null;\nfunction __velarDomApply(operation, receiver, arguments_, label) {\n if (typeof operation !== \"function\" || typeof __velarDomReflectApply !== \"function\") {\n throw new TypeError(\"The browser \" + label + \" API is unavailable\");\n }\n return __velarDomReflectApply(operation, receiver, arguments_);\n}\nfunction __velarDomOwnDescriptor(value, name) {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null\n || typeof __velarDomGetOwnPropertyDescriptor !== \"function\" || typeof __velarDomReflectApply !== \"function\") return null;\n return __velarDomReflectApply(__velarDomGetOwnPropertyDescriptor, __velarDomNativeObject, [value, name]) ?? null;\n}\nfunction __velarDomMember(value, name, kind = \"value\") {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) return null;\n let current = value;\n for (let depth = 0; current && depth < 32; depth += 1) {\n const descriptor = __velarDomOwnDescriptor(current, name);\n if (descriptor) {\n const member = kind === \"get\" ? descriptor.get : kind === \"set\" ? descriptor.set : \"value\" in descriptor ? descriptor.value : null;\n return typeof member === \"function\" ? member : null;\n }\n if (typeof __velarDomGetPrototypeOf !== \"function\" || typeof __velarDomReflectApply !== \"function\") return null;\n current = __velarDomReflectApply(__velarDomGetPrototypeOf, __velarDomNativeObject, [current]);\n }\n return null;\n}\nfunction __velarDomPrototype(constructor) {\n return typeof constructor === \"function\" ? __velarDomOwnDescriptor(constructor, \"prototype\")?.value ?? null : null;\n}\nfunction __velarDomPrototypeMember(constructor, name, kind = \"value\") {\n return __velarDomMember(__velarDomPrototype(constructor), name, kind);\n}\nfunction __velarDomInstance(value, constructor) {\n if (typeof constructor !== \"function\" || typeof __velarDomFunctionHasInstance !== \"function\") return false;\n try { return __velarDomApply(__velarDomFunctionHasInstance, constructor, [value], \"Node identity\"); }\n catch { return false; }\n}\nconst __velarDomDocumentCreateElement = __velarDomMember(__velarDomDocument, \"createElement\");\nconst __velarDomDocumentCreateElementNS = __velarDomMember(__velarDomDocument, \"createElementNS\");\nconst __velarDomDocumentCreateTextNode = __velarDomMember(__velarDomDocument, \"createTextNode\");\nconst __velarDomDocumentCreateComment = __velarDomMember(__velarDomDocument, \"createComment\");\nconst __velarDomDocumentCreateFragment = __velarDomMember(__velarDomDocument, \"createDocumentFragment\");\nconst __velarDomDocumentQuerySelector = __velarDomMember(__velarDomDocument, \"querySelector\");\nconst __velarDomNodeNodeType = __velarDomPrototypeMember(__velarDomNativeNode, \"nodeType\", \"get\");\nconst __velarDomNodeChildNodes = __velarDomPrototypeMember(__velarDomNativeNode, \"childNodes\", \"get\");\nconst __velarDomNodeInsertBefore = __velarDomPrototypeMember(__velarDomNativeNode, \"insertBefore\");\nconst __velarDomNodeReplaceChildren = __velarDomPrototypeMember(__velarDomNativeNode, \"replaceChildren\");\nconst __velarDomNodeAppend = __velarDomPrototypeMember(__velarDomNativeNode, \"append\");\nconst __velarDomNodeTextContentSet = __velarDomPrototypeMember(__velarDomNativeNode, \"textContent\", \"set\");\nconst __velarDomCharacterDataDataSet = __velarDomPrototypeMember(__velarDomNativeCharacterData, \"data\", \"set\");\nconst __velarDomElementAppend = __velarDomPrototypeMember(__velarDomNativeElement, \"append\");\nconst __velarDomElementReplaceChildren = __velarDomPrototypeMember(__velarDomNativeElement, \"replaceChildren\");\nconst __velarDomDocumentAppend = __velarDomPrototypeMember(__velarDomNativeDocument, \"append\");\nconst __velarDomDocumentReplaceChildren = __velarDomPrototypeMember(__velarDomNativeDocument, \"replaceChildren\");\nconst __velarDomFragmentAppend = __velarDomPrototypeMember(__velarDomNativeFragment, \"append\");\nconst __velarDomFragmentReplaceChildren = __velarDomPrototypeMember(__velarDomNativeFragment, \"replaceChildren\");\nconst __velarDomNodeRemove = __velarDomPrototypeMember(__velarDomNativeNode, \"remove\");\nconst __velarDomElementRemove = __velarDomPrototypeMember(__velarDomNativeElement, \"remove\");\nconst __velarDomCharacterDataRemove = __velarDomPrototypeMember(__velarDomNativeCharacterData, \"remove\");\nconst __velarDomDocumentTypeRemove = __velarDomPrototypeMember(__velarDomNativeDocumentType, \"remove\");\nconst __velarDomNodeBefore = __velarDomPrototypeMember(__velarDomNativeNode, \"before\");\nconst __velarDomElementBefore = __velarDomPrototypeMember(__velarDomNativeElement, \"before\");\nconst __velarDomCharacterDataBefore = __velarDomPrototypeMember(__velarDomNativeCharacterData, \"before\");\nconst __velarDomDocumentTypeBefore = __velarDomPrototypeMember(__velarDomNativeDocumentType, \"before\");\nconst __velarDomNodeSetAttribute = __velarDomPrototypeMember(__velarDomNativeNode, \"setAttribute\");\nconst __velarDomElementSetAttribute = __velarDomPrototypeMember(__velarDomNativeElement, \"setAttribute\");\nconst __velarDomElementSetAttributeNS = __velarDomPrototypeMember(__velarDomNativeElement, \"setAttributeNS\");\nconst __velarDomNodeRemoveAttribute = __velarDomPrototypeMember(__velarDomNativeNode, \"removeAttribute\");\nconst __velarDomElementRemoveAttribute = __velarDomPrototypeMember(__velarDomNativeElement, \"removeAttribute\");\nconst __velarDomElementRemoveAttributeNS = __velarDomPrototypeMember(__velarDomNativeElement, \"removeAttributeNS\");\nconst __velarDomNodeListLength = __velarDomPrototypeMember(__velarDomNativeNodeList, \"length\", \"get\");\nconst __velarDomNodeListItem = __velarDomPrototypeMember(__velarDomNativeNodeList, \"item\");\nconst __velarDomNodeNextSibling = __velarDomPrototypeMember(__velarDomNativeNode, \"nextSibling\", \"get\");\nconst __velarDomNodeAddListener = __velarDomPrototypeMember(__velarDomNativeNode, \"addEventListener\");\nconst __velarDomNodeRemoveListener = __velarDomPrototypeMember(__velarDomNativeNode, \"removeEventListener\");\nconst __velarDomNodeInnerHtml = __velarDomPrototypeMember(__velarDomNativeNode, \"innerHTML\", \"set\");\nconst __velarDomNodeQuerySelectorAll = __velarDomPrototypeMember(__velarDomNativeNode, \"querySelectorAll\");\nconst __velarDomNodeClassList = __velarDomPrototypeMember(__velarDomNativeNode, \"classList\", \"get\");\nconst __velarDomNodeStyle = __velarDomPrototypeMember(__velarDomNativeNode, \"style\", \"get\");\nconst __velarDomNodeFieldValue = __velarDomPrototypeMember(__velarDomNativeNode, \"value\", \"get\");\nconst __velarDomNodeSetFieldValue = __velarDomPrototypeMember(__velarDomNativeNode, \"value\", \"set\");\nconst __velarDomNodeFieldNumber = __velarDomPrototypeMember(__velarDomNativeNode, \"valueAsNumber\", \"get\");\nconst __velarDomNodeFieldChecked = __velarDomPrototypeMember(__velarDomNativeNode, \"checked\", \"get\");\nconst __velarDomNodeSetFieldChecked = __velarDomPrototypeMember(__velarDomNativeNode, \"checked\", \"set\");\nconst __velarDomEventTargetAdd = __velarDomPrototypeMember(__velarDomNativeEventTarget, \"addEventListener\");\nconst __velarDomEventTargetRemove = __velarDomPrototypeMember(__velarDomNativeEventTarget, \"removeEventListener\");\nconst __velarDomElementInnerHtml = __velarDomPrototypeMember(__velarDomNativeElement, \"innerHTML\", \"set\");\nconst __velarDomElementQuerySelectorAll = __velarDomPrototypeMember(__velarDomNativeElement, \"querySelectorAll\");\nconst __velarDomElementClassList = __velarDomPrototypeMember(__velarDomNativeElement, \"classList\", \"get\");\nconst __velarDomHtmlElementStyle = __velarDomPrototypeMember(__velarDomNativeHtmlElement, \"style\", \"get\");\nconst __velarDomSvgElementStyle = __velarDomPrototypeMember(__velarDomNativeSvgElement, \"style\", \"get\");\nconst __velarDomStyleSetProperty = __velarDomPrototypeMember(__velarDomNativeStyleDeclaration, \"setProperty\");\nconst __velarDomStyleRemoveProperty = __velarDomPrototypeMember(__velarDomNativeStyleDeclaration, \"removeProperty\");\nconst __velarDomStylePropertyValue = __velarDomPrototypeMember(__velarDomNativeStyleDeclaration, \"getPropertyValue\");\nconst __velarDomStylePropertyPriority = __velarDomPrototypeMember(__velarDomNativeStyleDeclaration, \"getPropertyPriority\");\nconst __velarDomTokenListAdd = __velarDomPrototypeMember(__velarDomNativeTokenList, \"add\");\nconst __velarDomTokenListRemove = __velarDomPrototypeMember(__velarDomNativeTokenList, \"remove\");\nconst __velarDomTokenListLength = __velarDomPrototypeMember(__velarDomNativeTokenList, \"length\", \"get\");\nconst __velarDomTokenListItem = __velarDomPrototypeMember(__velarDomNativeTokenList, \"item\");\nconst __velarDomInputValueGet = __velarDomPrototypeMember(__velarDomNativeInputElement, \"value\", \"get\");\nconst __velarDomInputValueSet = __velarDomPrototypeMember(__velarDomNativeInputElement, \"value\", \"set\");\nconst __velarDomInputNumberGet = __velarDomPrototypeMember(__velarDomNativeInputElement, \"valueAsNumber\", \"get\");\nconst __velarDomInputCheckedGet = __velarDomPrototypeMember(__velarDomNativeInputElement, \"checked\", \"get\");\nconst __velarDomInputCheckedSet = __velarDomPrototypeMember(__velarDomNativeInputElement, \"checked\", \"set\");\nconst __velarDomTextAreaValueGet = __velarDomPrototypeMember(__velarDomNativeTextAreaElement, \"value\", \"get\");\nconst __velarDomTextAreaValueSet = __velarDomPrototypeMember(__velarDomNativeTextAreaElement, \"value\", \"set\");\nconst __velarDomSelectValueGet = __velarDomPrototypeMember(__velarDomNativeSelectElement, \"value\", \"get\");\nconst __velarDomSelectValueSet = __velarDomPrototypeMember(__velarDomNativeSelectElement, \"value\", \"set\");\nfunction __velarDomOwnData(value, name) {\n const descriptor = __velarDomOwnDescriptor(value, name);\n return descriptor?.enumerable && \"value\" in descriptor ? descriptor.value : undefined;\n}\nfunction __velarDomOwnMethod(value, name) {\n const method = __velarDomOwnData(value, name);\n return typeof method === \"function\" ? method : null;\n}\nfunction __velarDomNodeOperation(value, name, candidates, arguments_) {\n for (let index = 0; index < candidates.length; index += 1) {\n const candidate = candidates[index];\n if (__velarDomInstance(value, candidate[0]) && typeof candidate[1] === \"function\") {\n return __velarDomApply(candidate[1], value, arguments_, \"DOM \" + name);\n }\n }\n const own = __velarDomOwnMethod(value, name);\n if (own) return __velarDomApply(own, value, arguments_, \"DOM \" + name);\n throw new TypeError(\"The value does not expose native DOM \" + name);\n}\nfunction __velarDomCreateElement(tag) { return __velarDomApply(__velarDomDocumentCreateElement, __velarDomDocument, [tag], \"document.createElement\"); }\nfunction __velarDomCreateElementNS(namespace, tag) { return __velarDomApply(__velarDomDocumentCreateElementNS, __velarDomDocument, [namespace, tag], \"document.createElementNS\"); }\nfunction __velarDomCreateTextNode(value) { return __velarDomApply(__velarDomDocumentCreateTextNode, __velarDomDocument, [value], \"document.createTextNode\"); }\nfunction __velarDomCreateComment(value) { return __velarDomApply(__velarDomDocumentCreateComment, __velarDomDocument, [value], \"document.createComment\"); }\nfunction __velarDomCreateFragment() { return __velarDomApply(__velarDomDocumentCreateFragment, __velarDomDocument, [], \"document.createDocumentFragment\"); }\nfunction __velarDomQuerySelector(value) { return __velarDomApply(__velarDomDocumentQuerySelector, __velarDomDocument, [value], \"document.querySelector\"); }\nfunction __velarDomAppend(value, ...children) {\n return __velarDomNodeOperation(value, \"append\", [\n [__velarDomNativeNode, __velarDomNodeAppend], [__velarDomNativeElement, __velarDomElementAppend],\n [__velarDomNativeDocument, __velarDomDocumentAppend], [__velarDomNativeFragment, __velarDomFragmentAppend],\n ], children);\n}\nfunction __velarDomInsertBefore(value, child, before = null) {\n return __velarDomNodeOperation(value, \"insertBefore\", [[__velarDomNativeNode, __velarDomNodeInsertBefore]], [child, before]);\n}\nfunction __velarDomReplaceChildren(value, ...children) {\n return __velarDomNodeOperation(value, \"replaceChildren\", [\n [__velarDomNativeNode, __velarDomNodeReplaceChildren], [__velarDomNativeElement, __velarDomElementReplaceChildren],\n [__velarDomNativeDocument, __velarDomDocumentReplaceChildren], [__velarDomNativeFragment, __velarDomFragmentReplaceChildren],\n ], children);\n}\nfunction __velarDomRemove(value) {\n return __velarDomNodeOperation(value, \"remove\", [\n [__velarDomNativeNode, __velarDomNodeRemove], [__velarDomNativeElement, __velarDomElementRemove],\n [__velarDomNativeCharacterData, __velarDomCharacterDataRemove], [__velarDomNativeDocumentType, __velarDomDocumentTypeRemove],\n ], []);\n}\nfunction __velarDomBefore(value, child) {\n return __velarDomNodeOperation(value, \"before\", [\n [__velarDomNativeNode, __velarDomNodeBefore], [__velarDomNativeElement, __velarDomElementBefore],\n [__velarDomNativeCharacterData, __velarDomCharacterDataBefore], [__velarDomNativeDocumentType, __velarDomDocumentTypeBefore],\n ], [child]);\n}\nfunction __velarDomSetAttribute(value, name, next) {\n return __velarDomNodeOperation(value, \"setAttribute\", [\n [__velarDomNativeNode, __velarDomNodeSetAttribute], [__velarDomNativeElement, __velarDomElementSetAttribute],\n ], [name, next]);\n}\nfunction __velarDomSetAttributeNS(value, namespace, name, next) {\n return __velarDomNodeOperation(value, \"setAttributeNS\", [[__velarDomNativeElement, __velarDomElementSetAttributeNS]], [namespace, name, next]);\n}\nfunction __velarDomRemoveAttribute(value, name) {\n return __velarDomNodeOperation(value, \"removeAttribute\", [\n [__velarDomNativeNode, __velarDomNodeRemoveAttribute], [__velarDomNativeElement, __velarDomElementRemoveAttribute],\n ], [name]);\n}\nfunction __velarDomRemoveAttributeNS(value, namespace, name) {\n return __velarDomNodeOperation(value, \"removeAttributeNS\", [[__velarDomNativeElement, __velarDomElementRemoveAttributeNS]], [namespace, name]);\n}\n// Accessor twin of __velarDomNodeOperation: the framework reads and writes a\n// handful of host properties (style, classList, innerHTML, field value) whose\n// prototypes are as replaceable as the methods above, so they go through the\n// same captured-then-own-data-descriptor path instead of ambient '.' access.\nfunction __velarDomNodeAccessor(value, name, candidates, arguments_, write) {\n for (let index = 0; index < candidates.length; index += 1) {\n const candidate = candidates[index];\n if (__velarDomInstance(value, candidate[0]) && typeof candidate[1] === \"function\") {\n return __velarDomApply(candidate[1], value, arguments_, \"DOM \" + name);\n }\n }\n const descriptor = __velarDomOwnDescriptor(value, name);\n if (!write) {\n if (descriptor && \"value\" in descriptor) return descriptor.value;\n throw new TypeError(\"The value does not expose native DOM \" + name);\n }\n if (typeof __velarDomDefineProperty !== \"function\" || typeof __velarDomReflectApply !== \"function\"\n || (descriptor && (!(\"value\" in descriptor) || descriptor.writable !== true))) {\n throw new TypeError(\"The value does not expose native DOM \" + name);\n }\n return __velarDomReflectApply(__velarDomDefineProperty, __velarDomNativeObject, [value, name, descriptor\n ? { ...descriptor, value: arguments_[0] }\n : { value: arguments_[0], writable: true, enumerable: true, configurable: true }]);\n}\nfunction __velarDomNextSibling(value) {\n if (__velarDomInstance(value, __velarDomNativeNode) && typeof __velarDomNodeNextSibling === \"function\") {\n return __velarDomApply(__velarDomNodeNextSibling, value, [], \"Node.nextSibling\");\n }\n return null;\n}\nfunction __velarDomAddListener(value, name, listener, options) {\n return __velarDomNodeOperation(value, \"addEventListener\", [\n [__velarDomNativeNode, __velarDomNodeAddListener], [__velarDomNativeEventTarget, __velarDomEventTargetAdd],\n ], [name, listener, options]);\n}\nfunction __velarDomRemoveListener(value, name, listener, options) {\n return __velarDomNodeOperation(value, \"removeEventListener\", [\n [__velarDomNativeNode, __velarDomNodeRemoveListener], [__velarDomNativeEventTarget, __velarDomEventTargetRemove],\n ], [name, listener, options]);\n}\n// The in-place text update. A scalar interpolation owns one text node for its\n// whole life and rewrites its character data rather than replacing the node, so\n// 'data' joins the captured accessor ABI beside 'innerHTML' and 'value': a\n// planted CharacterData.prototype setter must not be able to observe or divert\n// what the framework writes into its own node.\nfunction __velarDomSetData(value, next) {\n return __velarDomNodeAccessor(value, \"data\", [[__velarDomNativeCharacterData, __velarDomCharacterDataDataSet]], [next], true);\n}\nfunction __velarDomSetHtml(value, next) {\n return __velarDomNodeAccessor(value, \"innerHTML\", [\n [__velarDomNativeNode, __velarDomNodeInnerHtml], [__velarDomNativeElement, __velarDomElementInnerHtml],\n ], [next], true);\n}\nfunction __velarDomQuerySelectorAll(value, selector) {\n return __velarDomNodeOperation(value, \"querySelectorAll\", [\n [__velarDomNativeNode, __velarDomNodeQuerySelectorAll], [__velarDomNativeElement, __velarDomElementQuerySelectorAll],\n ], [selector]);\n}\nfunction __velarDomStyle(value) {\n return __velarDomNodeAccessor(value, \"style\", [\n [__velarDomNativeNode, __velarDomNodeStyle], [__velarDomNativeHtmlElement, __velarDomHtmlElementStyle],\n [__velarDomNativeSvgElement, __velarDomSvgElementStyle],\n ], [], false);\n}\nfunction __velarDomStyleValue(value, property) {\n return __velarDomNodeOperation(__velarDomStyle(value), \"getPropertyValue\", [[__velarDomNativeStyleDeclaration, __velarDomStylePropertyValue]], [property]);\n}\nfunction __velarDomStylePriority(value, property) {\n return __velarDomNodeOperation(__velarDomStyle(value), \"getPropertyPriority\", [[__velarDomNativeStyleDeclaration, __velarDomStylePropertyPriority]], [property]);\n}\nfunction __velarDomStyleWrite(value, property, next, priority = \"\") {\n return __velarDomNodeOperation(__velarDomStyle(value), \"setProperty\", [[__velarDomNativeStyleDeclaration, __velarDomStyleSetProperty]], [property, next, priority]);\n}\nfunction __velarDomStyleClear(value, property) {\n return __velarDomNodeOperation(__velarDomStyle(value), \"removeProperty\", [[__velarDomNativeStyleDeclaration, __velarDomStyleRemoveProperty]], [property]);\n}\nfunction __velarDomClassList(value) {\n return __velarDomNodeAccessor(value, \"classList\", [\n [__velarDomNativeNode, __velarDomNodeClassList], [__velarDomNativeElement, __velarDomElementClassList],\n ], [], false);\n}\nfunction __velarDomClassInsert(value, name) {\n return __velarDomNodeOperation(__velarDomClassList(value), \"add\", [[__velarDomNativeTokenList, __velarDomTokenListAdd]], [name]);\n}\nfunction __velarDomClassRemove(value, name) {\n return __velarDomNodeOperation(__velarDomClassList(value), \"remove\", [[__velarDomNativeTokenList, __velarDomTokenListRemove]], [name]);\n}\nfunction __velarDomClassNames(value) {\n const list = __velarDomClassList(value);\n const length = __velarDomInstance(list, __velarDomNativeTokenList) && typeof __velarDomTokenListLength === \"function\"\n ? __velarDomApply(__velarDomTokenListLength, list, [], \"DOMTokenList.length\")\n : __velarDomOwnData(list, \"length\");\n // A data-only seam that exposes no bounded token list simply owns no base\n // classes; only a real token list can contribute names the framework must\n // preserve while it manages the rest.\n if (!__velarDomIsInteger(length) || length < 0 || length > 1000000) return new __velarDomNativeArray(0);\n const output = new __velarDomNativeArray(length);\n for (let index = 0; index < length; index += 1) {\n output[index] = __velarDomNodeOperation(list, \"item\", [[__velarDomNativeTokenList, __velarDomTokenListItem]], [index]);\n }\n return output;\n}\nfunction __velarDomFieldValue(value) {\n return __velarDomNodeAccessor(value, \"value\", [\n [__velarDomNativeNode, __velarDomNodeFieldValue], [__velarDomNativeInputElement, __velarDomInputValueGet],\n [__velarDomNativeTextAreaElement, __velarDomTextAreaValueGet], [__velarDomNativeSelectElement, __velarDomSelectValueGet],\n ], [], false);\n}\nfunction __velarDomSetFieldValue(value, next) {\n return __velarDomNodeAccessor(value, \"value\", [\n [__velarDomNativeNode, __velarDomNodeSetFieldValue], [__velarDomNativeInputElement, __velarDomInputValueSet],\n [__velarDomNativeTextAreaElement, __velarDomTextAreaValueSet], [__velarDomNativeSelectElement, __velarDomSelectValueSet],\n ], [next], true);\n}\nfunction __velarDomFieldNumber(value) {\n return __velarDomNodeAccessor(value, \"valueAsNumber\", [\n [__velarDomNativeNode, __velarDomNodeFieldNumber], [__velarDomNativeInputElement, __velarDomInputNumberGet],\n ], [], false);\n}\nfunction __velarDomFieldChecked(value) {\n return __velarDomNodeAccessor(value, \"checked\", [\n [__velarDomNativeNode, __velarDomNodeFieldChecked], [__velarDomNativeInputElement, __velarDomInputCheckedGet],\n ], [], false);\n}\nfunction __velarDomSetFieldChecked(value, next) {\n return __velarDomNodeAccessor(value, \"checked\", [\n [__velarDomNativeNode, __velarDomNodeSetFieldChecked], [__velarDomNativeInputElement, __velarDomInputCheckedSet],\n ], [next], true);\n}\nfunction __velarDomNodeType(value) {\n if (__velarDomInstance(value, __velarDomNativeNode) && typeof __velarDomNodeNodeType === \"function\") {\n return __velarDomApply(__velarDomNodeNodeType, value, [], \"Node.nodeType\");\n }\n const nodeType = __velarDomOwnData(value, \"nodeType\");\n return typeof nodeType === \"number\" ? nodeType : null;\n}\nfunction __velarDomSetText(value, next) {\n if (__velarDomInstance(value, __velarDomNativeNode) && typeof __velarDomNodeTextContentSet === \"function\") {\n return __velarDomApply(__velarDomNodeTextContentSet, value, [next], \"Node.textContent\");\n }\n const descriptor = __velarDomOwnDescriptor(value, \"textContent\");\n if (!descriptor?.enumerable || !(\"value\" in descriptor) || descriptor.writable !== true\n || typeof __velarDomDefineProperty !== \"function\" || typeof __velarDomReflectApply !== \"function\") {\n throw new TypeError(\"The value does not expose native DOM textContent\");\n }\n return __velarDomReflectApply(__velarDomDefineProperty, __velarDomNativeObject, [value, \"textContent\", { ...descriptor, value: next }]);\n}\nfunction __velarDomIsNode(value) {\n return __velarDomInstance(value, __velarDomNativeNode) || __velarDomNodeType(value) !== null;\n}\nfunction __velarDomCollectionSnapshot(value, name) {\n let length = null;\n let read = null;\n if (__velarDomInstance(value, __velarDomNativeNodeList) && typeof __velarDomNodeListLength === \"function\" && typeof __velarDomNodeListItem === \"function\") {\n length = __velarDomApply(__velarDomNodeListLength, value, [], name + \".length\");\n read = (index) => __velarDomApply(__velarDomNodeListItem, value, [index], name + \".item\");\n } else if (__velarDomIsArray(value)) {\n length = __velarDomOwnDescriptor(value, \"length\")?.value;\n read = (index) => __velarDomOwnDescriptor(value, index)?.value;\n }\n if (!__velarDomIsInteger(length) || length < 0 || length > 1000000 || read === null) throw new TypeError(name + \" is not a bounded native collection\");\n const output = new __velarDomNativeArray(length);\n for (let index = 0; index < length; index += 1) output[index] = read(index);\n return output;\n}\nfunction __velarDomChildNodes(value) {\n let children;\n if (__velarDomInstance(value, __velarDomNativeNode) && typeof __velarDomNodeChildNodes === \"function\") {\n children = __velarDomApply(__velarDomNodeChildNodes, value, [], \"Node.childNodes\");\n } else children = __velarDomOwnData(value, \"childNodes\");\n return __velarDomCollectionSnapshot(children, \"Node.childNodes\");\n}\nfunction __velarDomIsArray(value) {\n return typeof __velarDomArrayIsArray === \"function\" && typeof __velarDomReflectApply === \"function\"\n && __velarDomReflectApply(__velarDomArrayIsArray, __velarDomNativeArray, [value]);\n}\nfunction __velarDomIsFinite(value) {\n return typeof __velarDomNumberIsFinite === \"function\" && typeof __velarDomReflectApply === \"function\"\n && __velarDomReflectApply(__velarDomNumberIsFinite, __velarDomNativeNumber, [value]);\n}\nfunction __velarDomIsInteger(value) {\n return typeof __velarDomNumberIsInteger === \"function\" && typeof __velarDomReflectApply === \"function\"\n && __velarDomReflectApply(__velarDomNumberIsInteger, __velarDomNativeNumber, [value]);\n}\nfunction __velarDomString(value) { return __velarDomApply(__velarDomNativeString, undefined, [value], \"String\"); }\nfunction __velarDomListSnapshot(value, name) {\n if (!__velarDomIsArray(value)) throw new TypeError(name + \" requires a List\");\n const lengthDescriptor = __velarDomOwnDescriptor(value, \"length\");\n if (!lengthDescriptor || lengthDescriptor.writable !== true || lengthDescriptor.enumerable\n || lengthDescriptor.configurable || !(\"value\" in lengthDescriptor)) {\n throw new TypeError(name + \" requires an ordinary mutable List length\");\n }\n const length = lengthDescriptor.value;\n if (!__velarDomIsInteger(length) || length < 0 || length > 1000000) throw new RangeError(name + \" cannot exceed 1000000 items\");\n const names = __velarDomApply(__velarDomGetOwnPropertyNames, __velarDomNativeObject, [value]);\n const symbols = __velarDomApply(__velarDomGetOwnPropertySymbols, __velarDomNativeObject, [value]);\n if (symbols.length > 0 || names.length !== length + 1) throw new TypeError(name + \" requires a dense List without extra fields\");\n const output = new __velarDomNativeArray(length);\n for (let index = 0; index < length; index += 1) {\n const descriptor = __velarDomOwnDescriptor(value, index);\n if (!descriptor?.enumerable || !descriptor.configurable || !descriptor.writable || !(\"value\" in descriptor)) {\n throw new TypeError(name + \" requires ordinary mutable List elements\");\n }\n output[index] = descriptor.value;\n }\n return output;\n}\nfunction __velarDomCreateSet() {\n if (typeof __velarDomNativeSet !== \"function\") throw new TypeError(\"The browser Set API is unavailable\");\n return new __velarDomNativeSet();\n}\nfunction __velarDomSetContains(value, item) { return __velarDomApply(__velarDomSetHas, value, [item], \"Set.has\"); }\nfunction __velarDomSetInsert(value, item) { return __velarDomApply(__velarDomSetAdd, value, [item], \"Set.add\"); }\nfunction __velarDomSetRemove(value, item) { return __velarDomApply(__velarDomSetDelete, value, [item], \"Set.delete\"); }\n";
|
|
9
|
+
export const WEB_DOM_HOST_RUNTIME = "const __velarDomNativeObject = globalThis.Object;\nconst __velarDomNativeArray = globalThis.Array;\nconst __velarDomNativeSet = globalThis.Set;\nconst __velarDomNativeNumber = globalThis.Number;\nconst __velarDomNativeString = globalThis.String;\nconst __velarDomNativeSymbol = globalThis.Symbol;\nconst __velarDomReflectApply = Object.getOwnPropertyDescriptor(Reflect, \"apply\")?.value;\nconst __velarDomGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor(Object, \"getOwnPropertyDescriptor\")?.value;\nconst __velarDomGetOwnPropertyNames = Object.getOwnPropertyDescriptor(Object, \"getOwnPropertyNames\")?.value;\nconst __velarDomGetOwnPropertySymbols = Object.getOwnPropertyDescriptor(Object, \"getOwnPropertySymbols\")?.value;\nconst __velarDomGetPrototypeOf = Object.getOwnPropertyDescriptor(Object, \"getPrototypeOf\")?.value;\nconst __velarDomDefineProperty = Object.getOwnPropertyDescriptor(Object, \"defineProperty\")?.value;\nconst __velarDomArrayIsArray = Object.getOwnPropertyDescriptor(Array, \"isArray\")?.value;\nconst __velarDomNumberIsFinite = Object.getOwnPropertyDescriptor(Number, \"isFinite\")?.value;\nconst __velarDomNumberIsInteger = Object.getOwnPropertyDescriptor(Number, \"isInteger\")?.value;\nconst __velarDomSymbolHasInstance = typeof __velarDomNativeSymbol === \"function\" ? __velarDomNativeSymbol.hasInstance : null;\nconst __velarDomFunctionHasInstance = __velarDomSymbolHasInstance == null\n ? null\n : Object.getOwnPropertyDescriptor(Function.prototype, __velarDomSymbolHasInstance)?.value;\nconst __velarDomSetPrototype = typeof __velarDomNativeSet === \"function\"\n ? Object.getOwnPropertyDescriptor(__velarDomNativeSet, \"prototype\")?.value\n : null;\nconst __velarDomSetHas = __velarDomSetPrototype && Object.getOwnPropertyDescriptor(__velarDomSetPrototype, \"has\")?.value;\nconst __velarDomSetAdd = __velarDomSetPrototype && Object.getOwnPropertyDescriptor(__velarDomSetPrototype, \"add\")?.value;\nconst __velarDomSetDelete = __velarDomSetPrototype && Object.getOwnPropertyDescriptor(__velarDomSetPrototype, \"delete\")?.value;\nconst __velarDomDocument = globalThis.document ?? null;\nconst __velarDomNativeNode = typeof globalThis.Node === \"function\" ? globalThis.Node : null;\nconst __velarDomNativeElement = typeof globalThis.Element === \"function\" ? globalThis.Element : null;\nconst __velarDomNativeDocument = typeof globalThis.Document === \"function\" ? globalThis.Document : null;\nconst __velarDomNativeFragment = typeof globalThis.DocumentFragment === \"function\" ? globalThis.DocumentFragment : null;\nconst __velarDomNativeCharacterData = typeof globalThis.CharacterData === \"function\" ? globalThis.CharacterData : null;\nconst __velarDomNativeDocumentType = typeof globalThis.DocumentType === \"function\" ? globalThis.DocumentType : null;\nconst __velarDomNativeNodeList = typeof globalThis.NodeList === \"function\" ? globalThis.NodeList : null;\nconst __velarDomNativeEventTarget = typeof globalThis.EventTarget === \"function\" ? globalThis.EventTarget : null;\nconst __velarDomNativeHtmlElement = typeof globalThis.HTMLElement === \"function\" ? globalThis.HTMLElement : null;\nconst __velarDomNativeSvgElement = typeof globalThis.SVGElement === \"function\" ? globalThis.SVGElement : null;\nconst __velarDomNativeStyleDeclaration = typeof globalThis.CSSStyleDeclaration === \"function\" ? globalThis.CSSStyleDeclaration : null;\nconst __velarDomNativeTokenList = typeof globalThis.DOMTokenList === \"function\" ? globalThis.DOMTokenList : null;\nconst __velarDomNativeInputElement = typeof globalThis.HTMLInputElement === \"function\" ? globalThis.HTMLInputElement : null;\nconst __velarDomNativeTextAreaElement = typeof globalThis.HTMLTextAreaElement === \"function\" ? globalThis.HTMLTextAreaElement : null;\nconst __velarDomNativeSelectElement = typeof globalThis.HTMLSelectElement === \"function\" ? globalThis.HTMLSelectElement : null;\nfunction __velarDomApply(operation, receiver, arguments_, label) {\n if (typeof operation !== \"function\" || typeof __velarDomReflectApply !== \"function\") {\n throw new TypeError(\"The browser \" + label + \" API is unavailable\");\n }\n return __velarDomReflectApply(operation, receiver, arguments_);\n}\nfunction __velarDomOwnDescriptor(value, name) {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null\n || typeof __velarDomGetOwnPropertyDescriptor !== \"function\" || typeof __velarDomReflectApply !== \"function\") return null;\n return __velarDomReflectApply(__velarDomGetOwnPropertyDescriptor, __velarDomNativeObject, [value, name]) ?? null;\n}\nfunction __velarDomMember(value, name, kind = \"value\") {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) return null;\n let current = value;\n for (let depth = 0; current && depth < 32; depth += 1) {\n const descriptor = __velarDomOwnDescriptor(current, name);\n if (descriptor) {\n const member = kind === \"get\" ? descriptor.get : kind === \"set\" ? descriptor.set : \"value\" in descriptor ? descriptor.value : null;\n return typeof member === \"function\" ? member : null;\n }\n if (typeof __velarDomGetPrototypeOf !== \"function\" || typeof __velarDomReflectApply !== \"function\") return null;\n current = __velarDomReflectApply(__velarDomGetPrototypeOf, __velarDomNativeObject, [current]);\n }\n return null;\n}\nfunction __velarDomPrototype(constructor) {\n return typeof constructor === \"function\" ? __velarDomOwnDescriptor(constructor, \"prototype\")?.value ?? null : null;\n}\nfunction __velarDomPrototypeMember(constructor, name, kind = \"value\") {\n return __velarDomMember(__velarDomPrototype(constructor), name, kind);\n}\nfunction __velarDomInstance(value, constructor) {\n if (typeof constructor !== \"function\" || typeof __velarDomFunctionHasInstance !== \"function\") return false;\n try { return __velarDomApply(__velarDomFunctionHasInstance, constructor, [value], \"Node identity\"); }\n catch { return false; }\n}\nconst __velarDomDocumentCreateElement = __velarDomMember(__velarDomDocument, \"createElement\");\nconst __velarDomDocumentCreateElementNS = __velarDomMember(__velarDomDocument, \"createElementNS\");\nconst __velarDomDocumentCreateTextNode = __velarDomMember(__velarDomDocument, \"createTextNode\");\nconst __velarDomDocumentCreateComment = __velarDomMember(__velarDomDocument, \"createComment\");\nconst __velarDomDocumentCreateFragment = __velarDomMember(__velarDomDocument, \"createDocumentFragment\");\nconst __velarDomDocumentQuerySelector = __velarDomMember(__velarDomDocument, \"querySelector\");\nconst __velarDomNodeNodeType = __velarDomPrototypeMember(__velarDomNativeNode, \"nodeType\", \"get\");\nconst __velarDomElementNamespaceURI = __velarDomPrototypeMember(__velarDomNativeElement, \"namespaceURI\", \"get\");\nconst __velarDomNodeChildNodes = __velarDomPrototypeMember(__velarDomNativeNode, \"childNodes\", \"get\");\nconst __velarDomNodeInsertBefore = __velarDomPrototypeMember(__velarDomNativeNode, \"insertBefore\");\nconst __velarDomNodeReplaceChildren = __velarDomPrototypeMember(__velarDomNativeNode, \"replaceChildren\");\nconst __velarDomNodeAppend = __velarDomPrototypeMember(__velarDomNativeNode, \"append\");\nconst __velarDomNodeTextContentSet = __velarDomPrototypeMember(__velarDomNativeNode, \"textContent\", \"set\");\nconst __velarDomCharacterDataDataSet = __velarDomPrototypeMember(__velarDomNativeCharacterData, \"data\", \"set\");\nconst __velarDomElementAppend = __velarDomPrototypeMember(__velarDomNativeElement, \"append\");\nconst __velarDomElementReplaceChildren = __velarDomPrototypeMember(__velarDomNativeElement, \"replaceChildren\");\nconst __velarDomDocumentAppend = __velarDomPrototypeMember(__velarDomNativeDocument, \"append\");\nconst __velarDomDocumentReplaceChildren = __velarDomPrototypeMember(__velarDomNativeDocument, \"replaceChildren\");\nconst __velarDomFragmentAppend = __velarDomPrototypeMember(__velarDomNativeFragment, \"append\");\nconst __velarDomFragmentReplaceChildren = __velarDomPrototypeMember(__velarDomNativeFragment, \"replaceChildren\");\nconst __velarDomNodeRemove = __velarDomPrototypeMember(__velarDomNativeNode, \"remove\");\nconst __velarDomElementRemove = __velarDomPrototypeMember(__velarDomNativeElement, \"remove\");\nconst __velarDomCharacterDataRemove = __velarDomPrototypeMember(__velarDomNativeCharacterData, \"remove\");\nconst __velarDomDocumentTypeRemove = __velarDomPrototypeMember(__velarDomNativeDocumentType, \"remove\");\nconst __velarDomNodeBefore = __velarDomPrototypeMember(__velarDomNativeNode, \"before\");\nconst __velarDomElementBefore = __velarDomPrototypeMember(__velarDomNativeElement, \"before\");\nconst __velarDomCharacterDataBefore = __velarDomPrototypeMember(__velarDomNativeCharacterData, \"before\");\nconst __velarDomDocumentTypeBefore = __velarDomPrototypeMember(__velarDomNativeDocumentType, \"before\");\nconst __velarDomNodeSetAttribute = __velarDomPrototypeMember(__velarDomNativeNode, \"setAttribute\");\nconst __velarDomElementSetAttribute = __velarDomPrototypeMember(__velarDomNativeElement, \"setAttribute\");\nconst __velarDomElementSetAttributeNS = __velarDomPrototypeMember(__velarDomNativeElement, \"setAttributeNS\");\nconst __velarDomNodeRemoveAttribute = __velarDomPrototypeMember(__velarDomNativeNode, \"removeAttribute\");\nconst __velarDomElementRemoveAttribute = __velarDomPrototypeMember(__velarDomNativeElement, \"removeAttribute\");\nconst __velarDomElementRemoveAttributeNS = __velarDomPrototypeMember(__velarDomNativeElement, \"removeAttributeNS\");\nconst __velarDomNodeListLength = __velarDomPrototypeMember(__velarDomNativeNodeList, \"length\", \"get\");\nconst __velarDomNodeListItem = __velarDomPrototypeMember(__velarDomNativeNodeList, \"item\");\nconst __velarDomNodeNextSibling = __velarDomPrototypeMember(__velarDomNativeNode, \"nextSibling\", \"get\");\nconst __velarDomNodeAddListener = __velarDomPrototypeMember(__velarDomNativeNode, \"addEventListener\");\nconst __velarDomNodeRemoveListener = __velarDomPrototypeMember(__velarDomNativeNode, \"removeEventListener\");\nconst __velarDomNodeInnerHtml = __velarDomPrototypeMember(__velarDomNativeNode, \"innerHTML\", \"set\");\nconst __velarDomNodeQuerySelectorAll = __velarDomPrototypeMember(__velarDomNativeNode, \"querySelectorAll\");\nconst __velarDomNodeClassList = __velarDomPrototypeMember(__velarDomNativeNode, \"classList\", \"get\");\nconst __velarDomNodeStyle = __velarDomPrototypeMember(__velarDomNativeNode, \"style\", \"get\");\nconst __velarDomNodeFieldValue = __velarDomPrototypeMember(__velarDomNativeNode, \"value\", \"get\");\nconst __velarDomNodeSetFieldValue = __velarDomPrototypeMember(__velarDomNativeNode, \"value\", \"set\");\nconst __velarDomNodeFieldNumber = __velarDomPrototypeMember(__velarDomNativeNode, \"valueAsNumber\", \"get\");\nconst __velarDomNodeFieldChecked = __velarDomPrototypeMember(__velarDomNativeNode, \"checked\", \"get\");\nconst __velarDomNodeSetFieldChecked = __velarDomPrototypeMember(__velarDomNativeNode, \"checked\", \"set\");\nconst __velarDomEventTargetAdd = __velarDomPrototypeMember(__velarDomNativeEventTarget, \"addEventListener\");\nconst __velarDomEventTargetRemove = __velarDomPrototypeMember(__velarDomNativeEventTarget, \"removeEventListener\");\nconst __velarDomElementInnerHtml = __velarDomPrototypeMember(__velarDomNativeElement, \"innerHTML\", \"set\");\nconst __velarDomElementQuerySelectorAll = __velarDomPrototypeMember(__velarDomNativeElement, \"querySelectorAll\");\nconst __velarDomElementClassList = __velarDomPrototypeMember(__velarDomNativeElement, \"classList\", \"get\");\nconst __velarDomHtmlElementStyle = __velarDomPrototypeMember(__velarDomNativeHtmlElement, \"style\", \"get\");\nconst __velarDomSvgElementStyle = __velarDomPrototypeMember(__velarDomNativeSvgElement, \"style\", \"get\");\nconst __velarDomStyleSetProperty = __velarDomPrototypeMember(__velarDomNativeStyleDeclaration, \"setProperty\");\nconst __velarDomStyleRemoveProperty = __velarDomPrototypeMember(__velarDomNativeStyleDeclaration, \"removeProperty\");\nconst __velarDomStylePropertyValue = __velarDomPrototypeMember(__velarDomNativeStyleDeclaration, \"getPropertyValue\");\nconst __velarDomStylePropertyPriority = __velarDomPrototypeMember(__velarDomNativeStyleDeclaration, \"getPropertyPriority\");\nconst __velarDomTokenListAdd = __velarDomPrototypeMember(__velarDomNativeTokenList, \"add\");\nconst __velarDomTokenListRemove = __velarDomPrototypeMember(__velarDomNativeTokenList, \"remove\");\nconst __velarDomTokenListLength = __velarDomPrototypeMember(__velarDomNativeTokenList, \"length\", \"get\");\nconst __velarDomTokenListItem = __velarDomPrototypeMember(__velarDomNativeTokenList, \"item\");\nconst __velarDomInputValueGet = __velarDomPrototypeMember(__velarDomNativeInputElement, \"value\", \"get\");\nconst __velarDomInputValueSet = __velarDomPrototypeMember(__velarDomNativeInputElement, \"value\", \"set\");\nconst __velarDomInputNumberGet = __velarDomPrototypeMember(__velarDomNativeInputElement, \"valueAsNumber\", \"get\");\nconst __velarDomInputCheckedGet = __velarDomPrototypeMember(__velarDomNativeInputElement, \"checked\", \"get\");\nconst __velarDomInputCheckedSet = __velarDomPrototypeMember(__velarDomNativeInputElement, \"checked\", \"set\");\nconst __velarDomTextAreaValueGet = __velarDomPrototypeMember(__velarDomNativeTextAreaElement, \"value\", \"get\");\nconst __velarDomTextAreaValueSet = __velarDomPrototypeMember(__velarDomNativeTextAreaElement, \"value\", \"set\");\nconst __velarDomSelectValueGet = __velarDomPrototypeMember(__velarDomNativeSelectElement, \"value\", \"get\");\nconst __velarDomSelectValueSet = __velarDomPrototypeMember(__velarDomNativeSelectElement, \"value\", \"set\");\nfunction __velarDomOwnData(value, name) {\n const descriptor = __velarDomOwnDescriptor(value, name);\n return descriptor?.enumerable && \"value\" in descriptor ? descriptor.value : undefined;\n}\nfunction __velarDomOwnMethod(value, name) {\n const method = __velarDomOwnData(value, name);\n return typeof method === \"function\" ? method : null;\n}\nfunction __velarDomNodeOperation(value, name, candidates, arguments_) {\n for (let index = 0; index < candidates.length; index += 1) {\n const candidate = candidates[index];\n if (__velarDomInstance(value, candidate[0]) && typeof candidate[1] === \"function\") {\n return __velarDomApply(candidate[1], value, arguments_, \"DOM \" + name);\n }\n }\n const own = __velarDomOwnMethod(value, name);\n if (own) return __velarDomApply(own, value, arguments_, \"DOM \" + name);\n throw new TypeError(\"The value does not expose native DOM \" + name);\n}\nfunction __velarDomCreateElement(tag) { return __velarDomApply(__velarDomDocumentCreateElement, __velarDomDocument, [tag], \"document.createElement\"); }\nfunction __velarDomCreateElementNS(namespace, tag) { return __velarDomApply(__velarDomDocumentCreateElementNS, __velarDomDocument, [namespace, tag], \"document.createElementNS\"); }\nfunction __velarDomCreateTextNode(value) { return __velarDomApply(__velarDomDocumentCreateTextNode, __velarDomDocument, [value], \"document.createTextNode\"); }\nfunction __velarDomCreateComment(value) { return __velarDomApply(__velarDomDocumentCreateComment, __velarDomDocument, [value], \"document.createComment\"); }\nfunction __velarDomCreateFragment() { return __velarDomApply(__velarDomDocumentCreateFragment, __velarDomDocument, [], \"document.createDocumentFragment\"); }\nfunction __velarDomQuerySelector(value) { return __velarDomApply(__velarDomDocumentQuerySelector, __velarDomDocument, [value], \"document.querySelector\"); }\nfunction __velarDomAppend(value, ...children) {\n return __velarDomNodeOperation(value, \"append\", [\n [__velarDomNativeNode, __velarDomNodeAppend], [__velarDomNativeElement, __velarDomElementAppend],\n [__velarDomNativeDocument, __velarDomDocumentAppend], [__velarDomNativeFragment, __velarDomFragmentAppend],\n ], children);\n}\nfunction __velarDomInsertBefore(value, child, before = null) {\n return __velarDomNodeOperation(value, \"insertBefore\", [[__velarDomNativeNode, __velarDomNodeInsertBefore]], [child, before]);\n}\nfunction __velarDomReplaceChildren(value, ...children) {\n return __velarDomNodeOperation(value, \"replaceChildren\", [\n [__velarDomNativeNode, __velarDomNodeReplaceChildren], [__velarDomNativeElement, __velarDomElementReplaceChildren],\n [__velarDomNativeDocument, __velarDomDocumentReplaceChildren], [__velarDomNativeFragment, __velarDomFragmentReplaceChildren],\n ], children);\n}\nfunction __velarDomRemove(value) {\n return __velarDomNodeOperation(value, \"remove\", [\n [__velarDomNativeNode, __velarDomNodeRemove], [__velarDomNativeElement, __velarDomElementRemove],\n [__velarDomNativeCharacterData, __velarDomCharacterDataRemove], [__velarDomNativeDocumentType, __velarDomDocumentTypeRemove],\n ], []);\n}\nfunction __velarDomBefore(value, child) {\n return __velarDomNodeOperation(value, \"before\", [\n [__velarDomNativeNode, __velarDomNodeBefore], [__velarDomNativeElement, __velarDomElementBefore],\n [__velarDomNativeCharacterData, __velarDomCharacterDataBefore], [__velarDomNativeDocumentType, __velarDomDocumentTypeBefore],\n ], [child]);\n}\nfunction __velarDomSetAttribute(value, name, next) {\n return __velarDomNodeOperation(value, \"setAttribute\", [\n [__velarDomNativeNode, __velarDomNodeSetAttribute], [__velarDomNativeElement, __velarDomElementSetAttribute],\n ], [name, next]);\n}\nfunction __velarDomSetAttributeNS(value, namespace, name, next) {\n return __velarDomNodeOperation(value, \"setAttributeNS\", [[__velarDomNativeElement, __velarDomElementSetAttributeNS]], [namespace, name, next]);\n}\nfunction __velarDomRemoveAttribute(value, name) {\n return __velarDomNodeOperation(value, \"removeAttribute\", [\n [__velarDomNativeNode, __velarDomNodeRemoveAttribute], [__velarDomNativeElement, __velarDomElementRemoveAttribute],\n ], [name]);\n}\nfunction __velarDomRemoveAttributeNS(value, namespace, name) {\n return __velarDomNodeOperation(value, \"removeAttributeNS\", [[__velarDomNativeElement, __velarDomElementRemoveAttributeNS]], [namespace, name]);\n}\n// Accessor twin of __velarDomNodeOperation: the framework reads and writes a\n// handful of host properties (style, classList, innerHTML, field value) whose\n// prototypes are as replaceable as the methods above, so they go through the\n// same captured-then-own-data-descriptor path instead of ambient '.' access.\nfunction __velarDomNodeAccessor(value, name, candidates, arguments_, write) {\n for (let index = 0; index < candidates.length; index += 1) {\n const candidate = candidates[index];\n if (__velarDomInstance(value, candidate[0]) && typeof candidate[1] === \"function\") {\n return __velarDomApply(candidate[1], value, arguments_, \"DOM \" + name);\n }\n }\n const descriptor = __velarDomOwnDescriptor(value, name);\n if (!write) {\n if (descriptor && \"value\" in descriptor) return descriptor.value;\n throw new TypeError(\"The value does not expose native DOM \" + name);\n }\n if (typeof __velarDomDefineProperty !== \"function\" || typeof __velarDomReflectApply !== \"function\"\n || (descriptor && (!(\"value\" in descriptor) || descriptor.writable !== true))) {\n throw new TypeError(\"The value does not expose native DOM \" + name);\n }\n return __velarDomReflectApply(__velarDomDefineProperty, __velarDomNativeObject, [value, name, descriptor\n ? { ...descriptor, value: arguments_[0] }\n : { value: arguments_[0], writable: true, enumerable: true, configurable: true }]);\n}\nfunction __velarDomNextSibling(value) {\n if (__velarDomInstance(value, __velarDomNativeNode) && typeof __velarDomNodeNextSibling === \"function\") {\n return __velarDomApply(__velarDomNodeNextSibling, value, [], \"Node.nextSibling\");\n }\n return null;\n}\nfunction __velarDomAddListener(value, name, listener, options) {\n return __velarDomNodeOperation(value, \"addEventListener\", [\n [__velarDomNativeNode, __velarDomNodeAddListener], [__velarDomNativeEventTarget, __velarDomEventTargetAdd],\n ], [name, listener, options]);\n}\nfunction __velarDomRemoveListener(value, name, listener, options) {\n return __velarDomNodeOperation(value, \"removeEventListener\", [\n [__velarDomNativeNode, __velarDomNodeRemoveListener], [__velarDomNativeEventTarget, __velarDomEventTargetRemove],\n ], [name, listener, options]);\n}\n// The in-place text update. A scalar interpolation owns one text node for its\n// whole life and rewrites its character data rather than replacing the node, so\n// 'data' joins the captured accessor ABI beside 'innerHTML' and 'value': a\n// planted CharacterData.prototype setter must not be able to observe or divert\n// what the framework writes into its own node.\nfunction __velarDomSetData(value, next) {\n return __velarDomNodeAccessor(value, \"data\", [[__velarDomNativeCharacterData, __velarDomCharacterDataDataSet]], [next], true);\n}\nfunction __velarDomSetHtml(value, next) {\n return __velarDomNodeAccessor(value, \"innerHTML\", [\n [__velarDomNativeNode, __velarDomNodeInnerHtml], [__velarDomNativeElement, __velarDomElementInnerHtml],\n ], [next], true);\n}\nfunction __velarDomQuerySelectorAll(value, selector) {\n return __velarDomNodeOperation(value, \"querySelectorAll\", [\n [__velarDomNativeNode, __velarDomNodeQuerySelectorAll], [__velarDomNativeElement, __velarDomElementQuerySelectorAll],\n ], [selector]);\n}\nfunction __velarDomStyle(value) {\n return __velarDomNodeAccessor(value, \"style\", [\n [__velarDomNativeNode, __velarDomNodeStyle], [__velarDomNativeHtmlElement, __velarDomHtmlElementStyle],\n [__velarDomNativeSvgElement, __velarDomSvgElementStyle],\n ], [], false);\n}\nfunction __velarDomStyleValue(value, property) {\n return __velarDomNodeOperation(__velarDomStyle(value), \"getPropertyValue\", [[__velarDomNativeStyleDeclaration, __velarDomStylePropertyValue]], [property]);\n}\nfunction __velarDomStylePriority(value, property) {\n return __velarDomNodeOperation(__velarDomStyle(value), \"getPropertyPriority\", [[__velarDomNativeStyleDeclaration, __velarDomStylePropertyPriority]], [property]);\n}\nfunction __velarDomStyleWrite(value, property, next, priority = \"\") {\n return __velarDomNodeOperation(__velarDomStyle(value), \"setProperty\", [[__velarDomNativeStyleDeclaration, __velarDomStyleSetProperty]], [property, next, priority]);\n}\nfunction __velarDomStyleClear(value, property) {\n return __velarDomNodeOperation(__velarDomStyle(value), \"removeProperty\", [[__velarDomNativeStyleDeclaration, __velarDomStyleRemoveProperty]], [property]);\n}\nfunction __velarDomClassList(value) {\n return __velarDomNodeAccessor(value, \"classList\", [\n [__velarDomNativeNode, __velarDomNodeClassList], [__velarDomNativeElement, __velarDomElementClassList],\n ], [], false);\n}\nfunction __velarDomClassInsert(value, name) {\n return __velarDomNodeOperation(__velarDomClassList(value), \"add\", [[__velarDomNativeTokenList, __velarDomTokenListAdd]], [name]);\n}\nfunction __velarDomClassRemove(value, name) {\n return __velarDomNodeOperation(__velarDomClassList(value), \"remove\", [[__velarDomNativeTokenList, __velarDomTokenListRemove]], [name]);\n}\nfunction __velarDomClassNames(value) {\n const list = __velarDomClassList(value);\n const length = __velarDomInstance(list, __velarDomNativeTokenList) && typeof __velarDomTokenListLength === \"function\"\n ? __velarDomApply(__velarDomTokenListLength, list, [], \"DOMTokenList.length\")\n : __velarDomOwnData(list, \"length\");\n // A data-only seam that exposes no bounded token list simply owns no base\n // classes; only a real token list can contribute names the framework must\n // preserve while it manages the rest.\n if (!__velarDomIsInteger(length) || length < 0 || length > 1000000) return new __velarDomNativeArray(0);\n const output = new __velarDomNativeArray(length);\n for (let index = 0; index < length; index += 1) {\n output[index] = __velarDomNodeOperation(list, \"item\", [[__velarDomNativeTokenList, __velarDomTokenListItem]], [index]);\n }\n return output;\n}\nfunction __velarDomFieldValue(value) {\n return __velarDomNodeAccessor(value, \"value\", [\n [__velarDomNativeNode, __velarDomNodeFieldValue], [__velarDomNativeInputElement, __velarDomInputValueGet],\n [__velarDomNativeTextAreaElement, __velarDomTextAreaValueGet], [__velarDomNativeSelectElement, __velarDomSelectValueGet],\n ], [], false);\n}\nfunction __velarDomSetFieldValue(value, next) {\n return __velarDomNodeAccessor(value, \"value\", [\n [__velarDomNativeNode, __velarDomNodeSetFieldValue], [__velarDomNativeInputElement, __velarDomInputValueSet],\n [__velarDomNativeTextAreaElement, __velarDomTextAreaValueSet], [__velarDomNativeSelectElement, __velarDomSelectValueSet],\n ], [next], true);\n}\nfunction __velarDomFieldNumber(value) {\n return __velarDomNodeAccessor(value, \"valueAsNumber\", [\n [__velarDomNativeNode, __velarDomNodeFieldNumber], [__velarDomNativeInputElement, __velarDomInputNumberGet],\n ], [], false);\n}\nfunction __velarDomFieldChecked(value) {\n return __velarDomNodeAccessor(value, \"checked\", [\n [__velarDomNativeNode, __velarDomNodeFieldChecked], [__velarDomNativeInputElement, __velarDomInputCheckedGet],\n ], [], false);\n}\nfunction __velarDomSetFieldChecked(value, next) {\n return __velarDomNodeAccessor(value, \"checked\", [\n [__velarDomNativeNode, __velarDomNodeSetFieldChecked], [__velarDomNativeInputElement, __velarDomInputCheckedSet],\n ], [next], true);\n}\nfunction __velarDomNodeType(value) {\n if (__velarDomInstance(value, __velarDomNativeNode) && typeof __velarDomNodeNodeType === \"function\") {\n return __velarDomApply(__velarDomNodeNodeType, value, [], \"Node.nodeType\");\n }\n const nodeType = __velarDomOwnData(value, \"nodeType\");\n return typeof nodeType === \"number\" ? nodeType : null;\n}\n// WB-U1: which document a node belongs to, read the way every other host field\n// here is read. The root fatal state needs it because the position it replaces\n// is a mount target the program named at runtime -- unlike a region, whose\n// namespace the lowering already knows -- and an HTML '<section>' inside\n// '<svg>' is content a browser lays out none of.\nfunction __velarDomNamespace(value) {\n if (__velarDomInstance(value, __velarDomNativeElement) && typeof __velarDomElementNamespaceURI === \"function\") {\n const namespace = __velarDomApply(__velarDomElementNamespaceURI, value, [], \"Element.namespaceURI\");\n return typeof namespace === \"string\" ? namespace : null;\n }\n const namespace = __velarDomOwnData(value, \"namespaceURI\");\n return typeof namespace === \"string\" ? namespace : null;\n}\nfunction __velarDomSetText(value, next) {\n if (__velarDomInstance(value, __velarDomNativeNode) && typeof __velarDomNodeTextContentSet === \"function\") {\n return __velarDomApply(__velarDomNodeTextContentSet, value, [next], \"Node.textContent\");\n }\n const descriptor = __velarDomOwnDescriptor(value, \"textContent\");\n if (!descriptor?.enumerable || !(\"value\" in descriptor) || descriptor.writable !== true\n || typeof __velarDomDefineProperty !== \"function\" || typeof __velarDomReflectApply !== \"function\") {\n throw new TypeError(\"The value does not expose native DOM textContent\");\n }\n return __velarDomReflectApply(__velarDomDefineProperty, __velarDomNativeObject, [value, \"textContent\", { ...descriptor, value: next }]);\n}\nfunction __velarDomIsNode(value) {\n return __velarDomInstance(value, __velarDomNativeNode) || __velarDomNodeType(value) !== null;\n}\nfunction __velarDomCollectionSnapshot(value, name) {\n let length = null;\n let read = null;\n if (__velarDomInstance(value, __velarDomNativeNodeList) && typeof __velarDomNodeListLength === \"function\" && typeof __velarDomNodeListItem === \"function\") {\n length = __velarDomApply(__velarDomNodeListLength, value, [], name + \".length\");\n read = (index) => __velarDomApply(__velarDomNodeListItem, value, [index], name + \".item\");\n } else if (__velarDomIsArray(value)) {\n length = __velarDomOwnDescriptor(value, \"length\")?.value;\n read = (index) => __velarDomOwnDescriptor(value, index)?.value;\n }\n if (!__velarDomIsInteger(length) || length < 0 || length > 1000000 || read === null) throw new TypeError(name + \" is not a bounded native collection\");\n const output = new __velarDomNativeArray(length);\n for (let index = 0; index < length; index += 1) output[index] = read(index);\n return output;\n}\nfunction __velarDomChildNodes(value) {\n let children;\n if (__velarDomInstance(value, __velarDomNativeNode) && typeof __velarDomNodeChildNodes === \"function\") {\n children = __velarDomApply(__velarDomNodeChildNodes, value, [], \"Node.childNodes\");\n } else children = __velarDomOwnData(value, \"childNodes\");\n return __velarDomCollectionSnapshot(children, \"Node.childNodes\");\n}\nfunction __velarDomIsArray(value) {\n return typeof __velarDomArrayIsArray === \"function\" && typeof __velarDomReflectApply === \"function\"\n && __velarDomReflectApply(__velarDomArrayIsArray, __velarDomNativeArray, [value]);\n}\nfunction __velarDomIsFinite(value) {\n return typeof __velarDomNumberIsFinite === \"function\" && typeof __velarDomReflectApply === \"function\"\n && __velarDomReflectApply(__velarDomNumberIsFinite, __velarDomNativeNumber, [value]);\n}\nfunction __velarDomIsInteger(value) {\n return typeof __velarDomNumberIsInteger === \"function\" && typeof __velarDomReflectApply === \"function\"\n && __velarDomReflectApply(__velarDomNumberIsInteger, __velarDomNativeNumber, [value]);\n}\nfunction __velarDomString(value) { return __velarDomApply(__velarDomNativeString, undefined, [value], \"String\"); }\nfunction __velarDomListSnapshot(value, name) {\n if (!__velarDomIsArray(value)) throw new TypeError(name + \" requires a List\");\n const lengthDescriptor = __velarDomOwnDescriptor(value, \"length\");\n if (!lengthDescriptor || lengthDescriptor.writable !== true || lengthDescriptor.enumerable\n || lengthDescriptor.configurable || !(\"value\" in lengthDescriptor)) {\n throw new TypeError(name + \" requires an ordinary mutable List length\");\n }\n const length = lengthDescriptor.value;\n if (!__velarDomIsInteger(length) || length < 0 || length > 1000000) throw new RangeError(name + \" cannot exceed 1000000 items\");\n const names = __velarDomApply(__velarDomGetOwnPropertyNames, __velarDomNativeObject, [value]);\n const symbols = __velarDomApply(__velarDomGetOwnPropertySymbols, __velarDomNativeObject, [value]);\n if (symbols.length > 0 || names.length !== length + 1) throw new TypeError(name + \" requires a dense List without extra fields\");\n const output = new __velarDomNativeArray(length);\n for (let index = 0; index < length; index += 1) {\n const descriptor = __velarDomOwnDescriptor(value, index);\n if (!descriptor?.enumerable || !descriptor.configurable || !descriptor.writable || !(\"value\" in descriptor)) {\n throw new TypeError(name + \" requires ordinary mutable List elements\");\n }\n output[index] = descriptor.value;\n }\n return output;\n}\nfunction __velarDomCreateSet() {\n if (typeof __velarDomNativeSet !== \"function\") throw new TypeError(\"The browser Set API is unavailable\");\n return new __velarDomNativeSet();\n}\nfunction __velarDomSetContains(value, item) { return __velarDomApply(__velarDomSetHas, value, [item], \"Set.has\"); }\nfunction __velarDomSetInsert(value, item) { return __velarDomApply(__velarDomSetAdd, value, [item], \"Set.add\"); }\nfunction __velarDomSetRemove(value, item) { return __velarDomApply(__velarDomSetDelete, value, [item], \"Set.delete\"); }\n";
|
|
10
10
|
/** The captured Object/Array/Set/Map ABI the dependency graph is built out of. */
|
|
11
11
|
export const WEB_REACTIVITY_HOST_RUNTIME = "const __velarGraphNativeObject = globalThis.Object;\nconst __velarGraphNativeArray = globalThis.Array;\nconst __velarGraphNativeSet = globalThis.Set;\nconst __velarGraphNativeMap = globalThis.Map;\nconst __velarGraphNativeWeakSet = globalThis.WeakSet;\nconst __velarGraphNativeWeakMap = globalThis.WeakMap;\nconst __velarGraphNativeProxy = globalThis.Proxy;\nconst __velarGraphReflectApply = Object.getOwnPropertyDescriptor(Reflect, \"apply\")?.value;\nconst __velarGraphArrayIsArray = Object.getOwnPropertyDescriptor(Array, \"isArray\")?.value;\nconst __velarGraphArrayPrototype = Object.getOwnPropertyDescriptor(__velarGraphNativeArray, \"prototype\")?.value;\nconst __velarGraphArraySort = __velarGraphArrayPrototype && Object.getOwnPropertyDescriptor(__velarGraphArrayPrototype, \"sort\")?.value;\nconst __velarGraphObjectIs = Object.getOwnPropertyDescriptor(Object, \"is\")?.value;\nconst __velarGraphObjectFreeze = Object.getOwnPropertyDescriptor(Object, \"freeze\")?.value;\nconst __velarGraphObjectDefineProperty = Object.getOwnPropertyDescriptor(Object, \"defineProperty\")?.value;\nconst __velarGraphObjectIsExtensible = Object.getOwnPropertyDescriptor(Object, \"isExtensible\")?.value;\nconst __velarGraphObjectGetPrototypeOf = Object.getOwnPropertyDescriptor(Object, \"getPrototypeOf\")?.value;\nconst __velarGraphObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor(Object, \"getOwnPropertyDescriptor\")?.value;\nconst __velarGraphObjectGetOwnPropertyNames = Object.getOwnPropertyDescriptor(Object, \"getOwnPropertyNames\")?.value;\nconst __velarGraphObjectCreate = Object.getOwnPropertyDescriptor(Object, \"create\")?.value;\nconst __velarGraphSetPrototype = Object.getOwnPropertyDescriptor(__velarGraphNativeSet, \"prototype\")?.value;\nconst __velarGraphSetHas = __velarGraphSetPrototype && Object.getOwnPropertyDescriptor(__velarGraphSetPrototype, \"has\")?.value;\nconst __velarGraphSetAdd = __velarGraphSetPrototype && Object.getOwnPropertyDescriptor(__velarGraphSetPrototype, \"add\")?.value;\nconst __velarGraphSetDelete = __velarGraphSetPrototype && Object.getOwnPropertyDescriptor(__velarGraphSetPrototype, \"delete\")?.value;\nconst __velarGraphSetClear = __velarGraphSetPrototype && Object.getOwnPropertyDescriptor(__velarGraphSetPrototype, \"clear\")?.value;\nconst __velarGraphSetValues = __velarGraphSetPrototype && Object.getOwnPropertyDescriptor(__velarGraphSetPrototype, \"values\")?.value;\nconst __velarGraphSetSize = __velarGraphSetPrototype && Object.getOwnPropertyDescriptor(__velarGraphSetPrototype, \"size\")?.get;\nconst __velarGraphMapPrototype = Object.getOwnPropertyDescriptor(__velarGraphNativeMap, \"prototype\")?.value;\nconst __velarGraphMapHas = __velarGraphMapPrototype && Object.getOwnPropertyDescriptor(__velarGraphMapPrototype, \"has\")?.value;\nconst __velarGraphMapGet = __velarGraphMapPrototype && Object.getOwnPropertyDescriptor(__velarGraphMapPrototype, \"get\")?.value;\nconst __velarGraphMapSet = __velarGraphMapPrototype && Object.getOwnPropertyDescriptor(__velarGraphMapPrototype, \"set\")?.value;\nconst __velarGraphMapDelete = __velarGraphMapPrototype && Object.getOwnPropertyDescriptor(__velarGraphMapPrototype, \"delete\")?.value;\nconst __velarGraphMapClear = __velarGraphMapPrototype && Object.getOwnPropertyDescriptor(__velarGraphMapPrototype, \"clear\")?.value;\nconst __velarGraphMapValues = __velarGraphMapPrototype && Object.getOwnPropertyDescriptor(__velarGraphMapPrototype, \"values\")?.value;\nconst __velarGraphMapKeys = __velarGraphMapPrototype && Object.getOwnPropertyDescriptor(__velarGraphMapPrototype, \"keys\")?.value;\nconst __velarGraphMapSize = __velarGraphMapPrototype && Object.getOwnPropertyDescriptor(__velarGraphMapPrototype, \"size\")?.get;\nconst __velarGraphWeakSetPrototype = Object.getOwnPropertyDescriptor(__velarGraphNativeWeakSet, \"prototype\")?.value;\nconst __velarGraphWeakSetHas = __velarGraphWeakSetPrototype && Object.getOwnPropertyDescriptor(__velarGraphWeakSetPrototype, \"has\")?.value;\nconst __velarGraphWeakSetAdd = __velarGraphWeakSetPrototype && Object.getOwnPropertyDescriptor(__velarGraphWeakSetPrototype, \"add\")?.value;\nconst __velarGraphWeakSetDelete = __velarGraphWeakSetPrototype && Object.getOwnPropertyDescriptor(__velarGraphWeakSetPrototype, \"delete\")?.value;\nconst __velarGraphWeakMapPrototype = Object.getOwnPropertyDescriptor(__velarGraphNativeWeakMap, \"prototype\")?.value;\nconst __velarGraphWeakMapHas = __velarGraphWeakMapPrototype && Object.getOwnPropertyDescriptor(__velarGraphWeakMapPrototype, \"has\")?.value;\nconst __velarGraphWeakMapGet = __velarGraphWeakMapPrototype && Object.getOwnPropertyDescriptor(__velarGraphWeakMapPrototype, \"get\")?.value;\nconst __velarGraphWeakMapSet = __velarGraphWeakMapPrototype && Object.getOwnPropertyDescriptor(__velarGraphWeakMapPrototype, \"set\")?.value;\nconst __velarGraphWeakMapDelete = __velarGraphWeakMapPrototype && Object.getOwnPropertyDescriptor(__velarGraphWeakMapPrototype, \"delete\")?.value;\nconst __velarGraphReflectGet = Object.getOwnPropertyDescriptor(Reflect, \"get\")?.value;\nconst __velarGraphReflectSet = Object.getOwnPropertyDescriptor(Reflect, \"set\")?.value;\nconst __velarGraphReflectHas = Object.getOwnPropertyDescriptor(Reflect, \"has\")?.value;\nconst __velarGraphReflectDeleteProperty = Object.getOwnPropertyDescriptor(Reflect, \"deleteProperty\")?.value;\nfunction __velarGraphApply(operation, receiver, arguments_, label) {\n if (typeof operation !== \"function\" || typeof __velarGraphReflectApply !== \"function\") {\n throw new TypeError(\"The JavaScript \" + label + \" API is unavailable\");\n }\n return __velarGraphReflectApply(operation, receiver, arguments_);\n}\nfunction __velarGraphCreateSet(values) {\n const output = new __velarGraphNativeSet();\n if (values !== undefined) for (const value of values) __velarGraphSetInsert(output, value);\n return output;\n}\nfunction __velarGraphCreateMap(values) {\n const output = new __velarGraphNativeMap();\n if (values !== undefined) for (const entry of values) __velarGraphMapWrite(output, entry[0], entry[1]);\n return output;\n}\nfunction __velarGraphCreateWeakSet() { return new __velarGraphNativeWeakSet(); }\nfunction __velarGraphCreateWeakMap() { return new __velarGraphNativeWeakMap(); }\nfunction __velarGraphSetContains(value, item) { return __velarGraphApply(__velarGraphSetHas, value, [item], \"Set.has\"); }\nfunction __velarGraphSetInsert(value, item) { return __velarGraphApply(__velarGraphSetAdd, value, [item], \"Set.add\"); }\nfunction __velarGraphSetRemove(value, item) { return __velarGraphApply(__velarGraphSetDelete, value, [item], \"Set.delete\"); }\nfunction __velarGraphSetEmpty(value) { return __velarGraphApply(__velarGraphSetClear, value, [], \"Set.clear\"); }\nfunction __velarGraphSetItems(value) { return __velarGraphApply(__velarGraphSetValues, value, [], \"Set.values\"); }\nfunction __velarGraphSetCount(value) { return __velarGraphApply(__velarGraphSetSize, value, [], \"Set.size\"); }\nfunction __velarGraphMapContains(value, key) { return __velarGraphApply(__velarGraphMapHas, value, [key], \"Map.has\"); }\nfunction __velarGraphMapRead(value, key) { return __velarGraphApply(__velarGraphMapGet, value, [key], \"Map.get\"); }\nfunction __velarGraphMapWrite(value, key, item) { return __velarGraphApply(__velarGraphMapSet, value, [key, item], \"Map.set\"); }\nfunction __velarGraphMapRemove(value, key) { return __velarGraphApply(__velarGraphMapDelete, value, [key], \"Map.delete\"); }\nfunction __velarGraphMapItems(value) { return __velarGraphApply(__velarGraphMapValues, value, [], \"Map.values\"); }\nfunction __velarGraphMapEmpty(value) { return __velarGraphApply(__velarGraphMapClear, value, [], \"Map.clear\"); }\nfunction __velarGraphMapKeyItems(value) { return __velarGraphApply(__velarGraphMapKeys, value, [], \"Map.keys\"); }\nfunction __velarGraphMapCount(value) { return __velarGraphApply(__velarGraphMapSize, value, [], \"Map.size\"); }\nfunction __velarGraphWeakSetContains(value, item) { return __velarGraphApply(__velarGraphWeakSetHas, value, [item], \"WeakSet.has\"); }\nfunction __velarGraphWeakSetInsert(value, item) { return __velarGraphApply(__velarGraphWeakSetAdd, value, [item], \"WeakSet.add\"); }\nfunction __velarGraphWeakSetRemove(value, item) { return __velarGraphApply(__velarGraphWeakSetDelete, value, [item], \"WeakSet.delete\"); }\nfunction __velarGraphWeakMapContains(value, key) { return __velarGraphApply(__velarGraphWeakMapHas, value, [key], \"WeakMap.has\"); }\nfunction __velarGraphWeakMapRead(value, key) { return __velarGraphApply(__velarGraphWeakMapGet, value, [key], \"WeakMap.get\"); }\nfunction __velarGraphWeakMapWrite(value, key, item) { return __velarGraphApply(__velarGraphWeakMapSet, value, [key, item], \"WeakMap.set\"); }\nfunction __velarGraphWeakMapRemove(value, key) { return __velarGraphApply(__velarGraphWeakMapDelete, value, [key], \"WeakMap.delete\"); }\nfunction __velarGraphIsList(value) { return __velarGraphApply(__velarGraphArrayIsArray, __velarGraphNativeArray, [value], \"Array.isArray\"); }\n// D114 F2: a plain record, as against a List, a Map, a Set or a class instance -- what a proxy is built over, what a report option must be, and which word a nested write is described with.\nfunction __velarGraphIsRecord(value) { const prototype = __velarGraphPrototype(value); return prototype === null || prototype === __velarGraphNativeObject.prototype; }\nfunction __velarGraphOrder(value, compare) { return __velarGraphApply(__velarGraphArraySort, value, [compare], \"Array.sort\"); }\nfunction __velarGraphSame(left, right) { return __velarGraphApply(__velarGraphObjectIs, __velarGraphNativeObject, [left, right], \"Object.is\"); }\nfunction __velarGraphFreeze(value) { return __velarGraphApply(__velarGraphObjectFreeze, __velarGraphNativeObject, [value], \"Object.freeze\"); }\nfunction __velarGraphDefine(value, key, descriptor) { return __velarGraphApply(__velarGraphObjectDefineProperty, __velarGraphNativeObject, [value, key, descriptor], \"Object.defineProperty\"); }\nfunction __velarGraphIsExtensible(value) { return __velarGraphApply(__velarGraphObjectIsExtensible, __velarGraphNativeObject, [value], \"Object.isExtensible\"); }\nfunction __velarGraphPrototype(value) { return __velarGraphApply(__velarGraphObjectGetPrototypeOf, __velarGraphNativeObject, [value], \"Object.getPrototypeOf\"); }\nfunction __velarGraphOwnDescriptor(value, key) { return __velarGraphApply(__velarGraphObjectGetOwnPropertyDescriptor, __velarGraphNativeObject, [value, key], \"Object.getOwnPropertyDescriptor\"); }\nfunction __velarGraphOwnNames(value) { return __velarGraphApply(__velarGraphObjectGetOwnPropertyNames, __velarGraphNativeObject, [value], \"Object.getOwnPropertyNames\"); }\nfunction __velarGraphCreateRecord() { return __velarGraphApply(__velarGraphObjectCreate, __velarGraphNativeObject, [null], \"Object.create\"); }\nfunction __velarGraphGet(value, key, receiver) { return __velarGraphApply(__velarGraphReflectGet, null, [value, key, receiver], \"Reflect.get\"); }\nfunction __velarGraphSet(value, key, item, receiver) { return __velarGraphApply(__velarGraphReflectSet, null, [value, key, item, receiver], \"Reflect.set\"); }\nfunction __velarGraphHas(value, key) { return __velarGraphApply(__velarGraphReflectHas, null, [value, key], \"Reflect.has\"); }\nfunction __velarGraphDelete(value, key) { return __velarGraphApply(__velarGraphReflectDeleteProperty, null, [value, key], \"Reflect.deleteProperty\"); }\n";
|
|
12
12
|
export const WEB_ERROR_HOST_RUNTIME_BODY = "const __velarWebErrorNativeObject = globalThis.Object;\nconst __velarWebErrorNativeNumber = globalThis.Number;\nconst __velarWebErrorNativePromise = globalThis.Promise;\nconst __velarWebErrorOwnSymbolsOperation = Object.getOwnPropertyDescriptor(Object, \"getOwnPropertySymbols\")?.value;\nconst __velarWebErrorFreezeOperation = Object.getOwnPropertyDescriptor(Object, \"freeze\")?.value;\nconst __velarWebErrorFiniteOperation = Object.getOwnPropertyDescriptor(Number, \"isFinite\")?.value;\nconst __velarWebErrorPromisePrototype = Object.getOwnPropertyDescriptor(__velarWebErrorNativePromise, \"prototype\")?.value;\nconst __velarWebErrorThenOperation = __velarWebErrorPromisePrototype\n ? Object.getOwnPropertyDescriptor(__velarWebErrorPromisePrototype, \"then\")?.value\n : null;\nfunction __velarWebErrorOwnSymbols(value) {\n return __velarErrorApply(__velarWebErrorOwnSymbolsOperation, __velarWebErrorNativeObject, [value], \"Object.getOwnPropertySymbols\");\n}\nfunction __velarWebErrorFreeze(value) {\n return __velarErrorApply(__velarWebErrorFreezeOperation, __velarWebErrorNativeObject, [value], \"Object.freeze\");\n}\nfunction __velarWebErrorFinite(value) {\n return __velarErrorApply(__velarWebErrorFiniteOperation, __velarWebErrorNativeNumber, [value], \"Number.isFinite\");\n}\nfunction __velarObservePromise(value, onRejected) {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) return null;\n try { return __velarErrorApply(__velarWebErrorThenOperation, value, [undefined, onRejected], \"Promise.then\"); }\n catch { return null; }\n}\n";
|
|
13
13
|
/** Error normalization plus the Web-owned promise and freeze operations layered on it. */
|
|
14
14
|
export const WEB_ERROR_HOST_RUNTIME = VELAR_ERROR_NORMALIZATION_RUNTIME + "\n" + WEB_ERROR_HOST_RUNTIME_BODY;
|
|
15
|
-
export const WEB_FOUNDATION_BODY = "const __velarRuntimeKey = Symbol.for(\"velar.runtime.v1\");\nconst __velarFoundationReflectApply = Object.getOwnPropertyDescriptor(Reflect, \"apply\")?.value;\nconst __velarFoundationQueueMicrotask = globalThis.queueMicrotask;\nconst __velarFoundationSetTimeout = globalThis.setTimeout;\nconst __velarFoundationDate = globalThis.Date;\nconst __velarFoundationDateNow = typeof __velarFoundationDate === \"function\"\n ? Object.getOwnPropertyDescriptor(__velarFoundationDate, \"now\")?.value\n : null;\nconst __velarFoundationConsole = globalThis.console ?? null;\nconst __velarFoundationConsoleError = __velarFoundationConsole !== null\n ? Object.getOwnPropertyDescriptor(__velarFoundationConsole, \"error\")?.value ?? null\n : null;\nfunction __velarFoundationTrace(error) {\n if (typeof __velarFoundationConsoleError !== \"function\" || typeof __velarFoundationReflectApply !== \"function\") return;\n let trace = \"An unhandled VelarScript failure was reported\";\n try { const stack = error.stack; if (typeof stack === \"string\" && stack !== \"\") trace = stack; } catch {}\n if (trace === \"An unhandled VelarScript failure was reported\") {\n try { const message = error.message; if (typeof message === \"string\" && message !== \"\") trace = message; } catch {}\n }\n try { __velarFoundationReflectApply(__velarFoundationConsoleError, __velarFoundationConsole, [\"Unhandled VelarScript error report: \" + trace]); } catch {}\n}\nfunction __velarEnqueue(callback) {\n if (typeof __velarFoundationQueueMicrotask !== \"function\" || typeof __velarFoundationReflectApply !== \"function\") {\n throw new TypeError(\"The browser queueMicrotask API is unavailable\");\n }\n return __velarFoundationReflectApply(__velarFoundationQueueMicrotask, globalThis, [callback]);\n}\nfunction __velarNow() {\n if (typeof __velarFoundationDateNow !== \"function\" || typeof __velarFoundationReflectApply !== \"function\") {\n throw new TypeError(\"The browser Date.now API is unavailable\");\n }\n return __velarFoundationReflectApply(__velarFoundationDateNow, __velarFoundationDate, []);\n}\nconst __velarRuntimeFields = Object.freeze([\n \"version\", \"domQueue\", \"watchQueue\", \"flushPending\", \"activeObserver\", \"errorHandlers\",\n \"actionFailures\", \"unhandledFailures\", \"lookSources\", \"classSources\", \"dependencies\", \"rawToProxy\", \"proxyToRaw\",\n \"versions\", \"parents\", \"toRaw\", \"reactive\", \"track\", \"trackDeep\", \"trigger\", \"versionOf\",\n \"collectionRead\", \"collectionTrigger\", \"collectionUnlink\", \"trackSubscribers\", \"runTracked\", \"cleanupObserver\", \"computed\",\n \"schedule\", \"report\", \"applyLook\", \"installLook\",\n]);\n\nfunction __velarRuntimeCollection(value, kind) {\n try {\n if (kind === \"Set\") __velarGraphSetContains(value, value);\n else if (kind === \"WeakSet\") __velarGraphWeakSetContains(value, value);\n else __velarGraphWeakMapContains(value, value);\n return true;\n } catch { return false; }\n}\n\nfunction __velarReportOptions(value) {\n if (value === undefined) value = {};\n if (!value || typeof value !== \"object\" || __velarGraphIsList(value) || !__velarGraphIsRecord(value)\n || __velarWebErrorOwnSymbols(value).length > 0) {\n throw new TypeError(\"VelarScript error report options must be a record\");\n }\n const allowed = __velarGraphCreateSet([\"phase\", \"detail\", \"component\", \"unhandled\"]);\n const output = { phase: \"runtime\", detail: \"\", component: \"\", unhandled: false };\n for (const name of __velarGraphOwnNames(value)) {\n if (!__velarGraphSetContains(allowed, name)) throw new TypeError(\"Unknown VelarScript error report option '\" + name + \"'\");\n const descriptor = __velarGraphOwnDescriptor(value, name);\n if (!descriptor || !(\"value\" in descriptor)) throw new TypeError(\"VelarScript error report options cannot use accessors\");\n const next = descriptor.value;\n if (name === \"unhandled\") {\n if (typeof next !== \"boolean\") throw new TypeError(\"VelarScript error report unhandled must be bool\");\n output.unhandled = next;\n } else {\n if (typeof next !== \"string\") throw new TypeError(\"VelarScript error report \" + name + \" must be a string\");\n const maximum = name === \"phase\" ? 256 : name === \"component\" ? 1024 : 65536;\n if (next.length > maximum) throw new RangeError(\"VelarScript error report \" + name + \" is too long\");\n output[name] = next;\n }\n }\n return output;\n}\n\n// D90 R21: the number stamped on each observer when it is created, and the\n// order the flush runs the watch tier in -- execution order is the order the\n// author wrote the watches, and \"wrote\" spans more than one file: watches of\n// one module register as that module initializes, instances of one component\n// register as they mount, and modules register in the order the import graph\n// initializes them. Every one of those is registration order, so one counter\n// answers all three.\n//\n// It has to be application-wide, not per module. Each emitted module carries\n// its own copy of this runtime, so a module-scope counter would restart at zero\n// in the second module and the two modules' watches would compare equal. The\n// counter therefore lives on one global slot every copy reads, the same way the\n// runtime registry itself does.\nconst __velarObserverSequenceKey = Symbol.for(\"velar.web.observer.sequence.v1\");\nconst __velarObserverSequenceCell = (() => {\n const descriptor = __velarGraphOwnDescriptor(globalThis, __velarObserverSequenceKey);\n if (descriptor) {\n if (!(\"value\" in descriptor) || descriptor.enumerable || descriptor.configurable || descriptor.writable\n || !__velarGraphIsList(descriptor.value)) {\n throw new TypeError(\"VelarScript Web observer sequence ownership is invalid\");\n }\n return descriptor.value;\n }\n const cell = [0];\n __velarGraphDefine(globalThis, __velarObserverSequenceKey, {\n value: cell,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return cell;\n})();\n\nfunction __velarNextObserverSequence() {\n __velarObserverSequenceCell[0] += 1;\n return __velarObserverSequenceCell[0];\n}\n\n\n// D114 P6 item 4 (LC-C1): how many `tick()` promises are waiting on the flush\n// right now.\n//\n// The charter says an unowned flush failure surfaces at `tick()`. That was only\n// true off the browser: in a browser the runtime threw the failure from a\n// microtask, which the host error event catches and the page survives, and the\n// awaiting `tick()` resolved as though the update had been fine -- so\n// `velar/web-test` stepped silently over a broken update in the one host\n// `tick()` is documented for. An awaiting caller is a claimant: when one is\n// waiting, the failure is parked for it and it rejects; when none is, the\n// failure goes to the host as before.\n//\n// The count lives on one global slot for the reason the observer sequence does:\n// each emitted module carries its own copy of this runtime, the `tick()` that\n// waits and the flush that fails can be in two of them, and a module-scope\n// counter would let the second copy answer \"nobody is waiting\" while the first\n// one is.\nconst __velarTickWaitKey = Symbol.for(\"velar.web.tick.waiters.v1\");\nconst __velarTickWaitCell = (() => {\n const descriptor = __velarGraphOwnDescriptor(globalThis, __velarTickWaitKey);\n if (descriptor) {\n if (!(\"value\" in descriptor) || descriptor.enumerable || descriptor.configurable || descriptor.writable\n || !__velarGraphIsList(descriptor.value)) {\n throw new TypeError(\"VelarScript Web tick ownership is invalid\");\n }\n return descriptor.value;\n }\n const cell = [0];\n __velarGraphDefine(globalThis, __velarTickWaitKey, {\n value: cell,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return cell;\n})();\n\nfunction __velarTickWaiting() {\n return __velarTickWaitCell[0] > 0;\n}\n\nfunction __velarEnterTickWait() {\n __velarTickWaitCell[0] += 1;\n}\n\nfunction __velarLeaveTickWait() {\n if (__velarTickWaitCell[0] > 0) __velarTickWaitCell[0] -= 1;\n}\n" + "// D114 W/A1, as narrowed by W2: the identity a flush stamps its run counts\n// with, and the budget those runs spend. They belong to one host *task* -- but\n// the window follows work an observer started, and nothing else.\n//\n// A cycle that crosses a microtask boundary -- 'watch x: detach step()', where\n// 'step' awaits an already-resolved Promise and then writes 'x' -- is a fresh\n// flush every round, so a budget that reset per flush never saw it: two\n// observer runs, well inside 100,000, forever. Flushes chained through\n// microtasks therefore share one token, one budget and one leaders list, and\n// the macrotask sentinel below closes the window. Work that resumes after a\n// timer, an event or network I/O is a new task and opens a fresh window, which\n// is what keeps an animation that writes state every frame from being stopped.\n//\n// W2: a flush continues the open window only once an observer run inside it has\n// started asynchronous work -- a 'detach' statement, or an 'action' call, made\n// while an observer was running. Those are the two ways a synchronous observer\n// body reaches a later microtask, so they are the only ways the ring above can\n// be closed; a chain of flushes with none of them in it has no cycle to find. A\n// bulk import loop that writes a progress counter and awaits promise-only work\n// per row runs millions of observers in one uninterrupted task and is not a\n// runaway, so each of its flushes gets the fresh budget it had before W. The\n// sentinel still closes every window at the task boundary, so the animation\n// case is protected either way.\n//\n// The overrun's carried token is the same rule seen from one flush earlier: an\n// overrun schedules its continuation as a microtask, so that continuation is\n// this same task and continues these same counts by construction. It carries\n// them whether or not an observer started anything, because the continuation is\n// the overrun's own unfinished work rather than a new write.\nconst __velarFlushBudgetPerTask = 100000;\nlet __velarFlushToken = null;\nlet __velarFlushBudget = 0;\n// One-shot, consumed by the next settle: the flush an overrun scheduled\n// continues the window it was scheduled from, whatever that window recorded.\nlet __velarFlushCarried = false;\n// One sentinel is enough for a window: the first one to fire closes it, and\n// arming a second on every flush would leave a timer per flush behind.\nlet __velarTaskSentinelArmed = false;\n\n// The two facts W2 needs live on one global slot, for the same reason the\n// observer sequence above does: every emitted module carries its own copy of\n// this runtime, and the two ends of the question are in different copies. The\n// settle that asks it belongs to whichever copy created the registry -- in an\n// application that imports velar/app, that is velar/app's -- while the places\n// that answer it, a 'detach' statement's detached-task helper and an action's\n// run, are emitted into the application module. Two module-scope variables\n// would never meet.\n//\n// Slot 0 is how deep the settle currently is inside 'observer.run()'. It is a\n// depth rather than a flag because an observer created by a running one runs\n// nested. '__velarRuntime.activeObserver' cannot stand in for it: a watch body\n// runs untracked, precisely so its own reads do not become dependencies of the\n// watched expression, so the active observer is null exactly where the 'detach'\n// that closes a cycle is written.\n//\n// Slot 1 is the fact recorded on the open window: an observer run in it started\n// asynchronous work.\nconst __velarAsyncWorkKey = Symbol.for(\"velar.web.observer.asyncwork.v1\");\nconst __velarAsyncWorkCell = (() => {\n const descriptor = __velarGraphOwnDescriptor(globalThis, __velarAsyncWorkKey);\n if (descriptor) {\n if (!(\"value\" in descriptor) || descriptor.enumerable || descriptor.configurable || descriptor.writable\n || !__velarGraphIsList(descriptor.value)) {\n throw new TypeError(\"VelarScript Web observer async-work ownership is invalid\");\n }\n return descriptor.value;\n }\n const cell = [0, false];\n __velarGraphDefine(globalThis, __velarAsyncWorkKey, {\n value: cell,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return cell;\n})();\n\n// What the two compiler-owned lowering points call: the detached-task helper a\n// 'detach' statement lowers to, where a detached Promise enters the runtime,\n// and an action's run, where an action call does. Outside an observer run there\n// is nothing to record -- an action a handler or '@main' starts is the host\n// task's own work, not a ring an observer closed -- so the same unconditional\n// call is correct at both sites.\nfunction __velarNoteAsyncWork() {\n if (__velarAsyncWorkCell[0] > 0) __velarAsyncWorkCell[1] = true;\n return null;\n}\n\nfunction __velarCloseTaskWindow() {\n __velarTaskSentinelArmed = false;\n __velarFlushToken = null;\n __velarAsyncWorkCell[1] = false;\n return null;\n}\n\n// The macrotask boundary the run-count window ends at. 'setTimeout' is the one\n// scheduling operation every host this runtime supports publishes -- page,\n// worker, and the Node process a 'velar test' run drives the emitted runtime\n// in -- and it is captured at module initialization like every other ambient\n// operation here. A host that publishes none is not left without a gate: the\n// window then closes as soon as the flush chain comes to rest, which is the\n// per-flush budget this runtime had before, so the synchronous cycles stay\n// covered and only the asynchronous one goes back to being invisible.\nfunction __velarArmTaskSentinel() {\n if (__velarTaskSentinelArmed) return true;\n if (typeof __velarFoundationSetTimeout !== \"function\" || typeof __velarFoundationReflectApply !== \"function\") return false;\n __velarTaskSentinelArmed = true;\n try { __velarFoundationReflectApply(__velarFoundationSetTimeout, globalThis, [__velarCloseTaskWindow, 0]); }\n catch { __velarTaskSentinelArmed = false; return false; }\n return true;\n}\n\n// The three observers that have run most in the task window running now, kept\n// as the run counts are stamped rather than reconstructed afterwards: the queue at\n// the moment the budget runs out holds only whichever half of a cycle has not\n// just run, so it cannot name the ring on its own. An observer that has run\n// once is not a candidate, which is every observer of an ordinary flush.\nconst __velarFlushLeaders = [];\n\nfunction __velarFlushLead(observer) {\n let kept = 0;\n for (let index = 0; index < __velarFlushLeaders.length; index += 1) {\n if (__velarFlushLeaders[index] === observer) continue;\n __velarFlushLeaders[kept] = __velarFlushLeaders[index];\n kept += 1;\n }\n __velarFlushLeaders.length = kept;\n let position = kept;\n while (position > 0 && __velarFlushLeaders[position - 1].flushRuns < observer.flushRuns) {\n __velarFlushLeaders[position] = __velarFlushLeaders[position - 1];\n position -= 1;\n }\n __velarFlushLeaders[position] = observer;\n if (__velarFlushLeaders.length > 3) __velarFlushLeaders.length = 3;\n}\n\n// D90 R21: compile time no longer refuses two watches that write one state, so\n// this budget is the only gate left against a mutual-write cycle -- and a\n// report that names nobody hands the author a number with no line to go to.\n// The observers that ran most in this flush chain are the cycle; flushRuns\n// already counts exactly that, so the highest few are named. A watch's label is\n// its subject as the author spelled it, which in a write cycle is also the\n// state each watch is reacting to, and the scope it was registered in supplies\n// the component the report has always had a field for.\n//\n// Nothing here asks who wrote what. That question is gone from the language,\n// and answering it would need the write frames R21 deleted.\nfunction __velarFlushRunaway(stalled, token) {\n const ranked = [];\n const seen = __velarGraphCreateSet();\n const consider = (observer) => {\n if (observer.flushToken !== token || __velarGraphSetContains(seen, observer)) return;\n __velarGraphSetInsert(seen, observer);\n ranked[ranked.length] = observer;\n };\n // A cycle alternates, so the queue at the instant the budget ran out holds\n // only the half of the ring that has not just run. The leaders carry the\n // other half.\n for (let index = 0; index < __velarFlushLeaders.length; index += 1) consider(__velarFlushLeaders[index]);\n for (let index = 0; index < stalled.length; index += 1) consider(stalled[index]);\n __velarGraphOrder(ranked, (left, right) => right.flushRuns - left.flushRuns);\n const limit = ranked.length < 3 ? ranked.length : 3;\n let detail = \"\";\n let component = \"\";\n for (let index = 0; index < limit; index += 1) {\n const observer = ranked[index];\n const named = observer.mode === \"watch\" && typeof observer.label === \"string\" && observer.label !== \"\"\n ? \"the watch on '\" + observer.label + \"'\"\n : \"a \" + observer.mode + \" observer\";\n detail += (detail === \"\" ? \"Ran most in this task: \" : \", \") + named\n + \" (\" + observer.flushRuns + (observer.flushRuns === 1 ? \" run)\" : \" runs)\");\n if (component === \"\" && typeof observer.component === \"string\") component = observer.component;\n }\n return { detail, component };\n}\n\nfunction __velarScheduleFlush() {\n if (__velarRuntime.flushPending) return;\n __velarRuntime.flushPending = true;\n __velarEnqueue(__velarFlush);\n}\n\n// Only the observers that actually re-entered the queue during the overrun\n// belong to the runaway cycle. An observer queued once by an unrelated write\n// in the same turn is innocent, and stopping it is irreversible, so it is\n// put back for the next microtask instead.\n//\n// Every overrun must still remove something, or the requeue turns the\n// microtask chain into the freeze the budget exists to end: a cycle spread\n// across more observers than the budget can run four times over re-enters\n// none of them four times, so a fixed threshold of four stops nobody and the\n// next flush repeats it forever. Two rules make the progress unconditional.\n// The threshold falls to the highest run count actually present, so any\n// queued observer this flush chain has already run is stopped; and the token\n// is carried into the flush the overrun schedules, so run counts accumulate\n// across the chain and the observers the chain has not reached yet are a\n// pool that only shrinks.\nfunction __velarFlushOverflow(token) {\n const stalled = [];\n for (const observer of __velarGraphSetItems(__velarRuntime.domQueue)) stalled[stalled.length] = observer;\n for (const observer of __velarGraphSetItems(__velarRuntime.watchQueue)) stalled[stalled.length] = observer;\n __velarGraphSetEmpty(__velarRuntime.domQueue);\n __velarGraphSetEmpty(__velarRuntime.watchQueue);\n let threshold = 0;\n for (let index = 0; index < stalled.length; index += 1) {\n const observer = stalled[index];\n if (observer.flushToken === token && observer.flushRuns > threshold) threshold = observer.flushRuns;\n }\n if (threshold > 4) threshold = 4;\n let requeued = false;\n for (let index = 0; index < stalled.length; index += 1) {\n const observer = stalled[index];\n if (threshold > 0 && observer.flushToken === token && observer.flushRuns >= threshold) {\n if (typeof observer.stop === \"function\") observer.stop();\n else observer.stopped = true;\n continue;\n }\n if (observer.stopped) continue;\n __velarGraphSetInsert(observer.mode === \"watch\" ? __velarRuntime.watchQueue : __velarRuntime.domQueue, observer);\n requeued = true;\n }\n const runaway = __velarFlushRunaway(stalled, token);\n // The window keeps its token and its run counts -- the requeued flush is one\n // more flush of the same task, and the pool of observers it has not reached\n // yet only shrinks -- but the budget is granted again. Without that, the\n // exhausted count would trip the very next flush of the same task, and the\n // observers stopped for it would be whatever was queued at that moment: the\n // innocent ones this overrun just put back, or an unrelated later write.\n __velarFlushBudget = __velarFlushBudgetPerTask;\n __velarFlushCarried = requeued;\n __velarRuntime.report(new RangeError(\"Reactive updates cannot run more than \" + __velarFlushBudgetPerTask + \" observers in one task\"),\n { phase: \"update\", detail: runaway.detail, component: runaway.component, unhandled: true });\n if (requeued) __velarScheduleFlush();\n}\n\n// The one entry point: the microtask __velarScheduleFlush enqueues, and the\n// synchronous drain the emitted tick() performs. It used to open and close D90\n// R1-a-scope's flush-scoped writer registry around the settle; R21 deleted the\n// registry with the referee that read it, so the name is all that remains and\n// it remains because __velarEnqueue and tick() both hold it.\n//\n// D114 W/A1: it is also where the task window is closed or handed on. Both\n// entries pass through here, including tick()'s drain, so the sentinel is armed\n// once per window however the flush was reached, and a host without a timer\n// falls back to closing the window here, one flush at a time.\nfunction __velarFlush() {\n try { __velarFlushSettle(); }\n // Without a timer the window closes as soon as the chain comes to rest,\n // which is the per-flush budget this runtime had before -- except that a\n // flush already scheduled keeps it open, so an overrun's carried counts and\n // the queues a settle could not finish reach the flush that continues them.\n finally { if (!__velarArmTaskSentinel() && !__velarRuntime.flushPending) __velarCloseTaskWindow(); }\n}\n\n// Glitch-free order: every derived value and every watch settles to a fixed\n// point before a single DOM node is written, so no watch and no rendered\n// position can read a half-updated world and no corrective watch can push an\n// invalid value through the DOM first. That is D90 R1 and it is unchanged.\n//\n// D90 R21 changed the other axis. Within the settle the watches run in\n// registration order -- source order in a module, mount order across instances\n// of one component, module-initialization order across modules -- and a watch\n// that writes state is not promoted ahead of one that only observes. Whoever is\n// written first runs first, two watches writing one state both take effect in\n// that order, and a later write that clobbers an earlier one is the author's.\n//\n// Queue insertion order is not registration order and cannot stand in for it:\n// two watches on two different states, both dirtied by one action, enter the\n// queue in the order the action wrote the states. So each pass takes the queue\n// as it stands and runs it by sequence number. Watches queued by this pass are\n// picked up by the next one, in their own order.\n//\n// D114 W/A1, narrowed by W2: a flush that starts while the task window is still\n// open continues it -- the same token, so flushRuns keeps accumulating on every\n// observer, the same leaders, and the same remaining budget -- but only when an\n// observer run in that window started asynchronous work, or when the overrun\n// itself scheduled this flush. Every other flush opens a new window, which is\n// the per-flush budget this runtime had before W.\nfunction __velarFlushSettle() {\n __velarRuntime.flushPending = false;\n const carried = __velarFlushCarried;\n __velarFlushCarried = false;\n if (__velarFlushToken === null || !(carried || __velarAsyncWorkCell[1])) {\n __velarFlushToken = {};\n __velarFlushBudget = __velarFlushBudgetPerTask;\n __velarFlushLeaders.length = 0;\n __velarAsyncWorkCell[1] = false;\n }\n const token = __velarFlushToken;\n const step = (observer) => {\n __velarGraphSetRemove(observer.mode === \"watch\" ? __velarRuntime.watchQueue : __velarRuntime.domQueue, observer);\n if (observer.flushToken === token) observer.flushRuns += 1;\n else { observer.flushToken = token; observer.flushRuns = 1; }\n if (observer.flushRuns > 1) __velarFlushLead(observer);\n // The span the two lowering points ask about. It is the run itself rather\n // than the whole settle: work started by the flush's own bookkeeping is\n // not an observer's, and a nested observer created by a running one is.\n __velarAsyncWorkCell[0] += 1;\n try { observer.run(); }\n finally { __velarAsyncWorkCell[0] -= 1; }\n };\n while (__velarGraphSetCount(__velarRuntime.domQueue) || __velarGraphSetCount(__velarRuntime.watchQueue)) {\n while (true) {\n let ran = false;\n for (const observer of __velarGraphSetItems(__velarRuntime.domQueue)) {\n if (observer.mode !== \"computed\") continue;\n if ((__velarFlushBudget -= 1) < 0) { __velarFlushOverflow(token); return; }\n step(observer);\n ran = true;\n }\n if (ran) continue;\n const pending = [];\n for (const observer of __velarGraphSetItems(__velarRuntime.watchQueue)) pending[pending.length] = observer;\n __velarGraphOrder(pending, (left, right) => left.sequence - right.sequence);\n for (let index = 0; index < pending.length; index += 1) {\n const observer = pending[index];\n // A watch this pass already re-ran or stopped is no longer queued; the\n // snapshot is a plan, and the queue is what says whether it still owes\n // a run.\n if (observer.stopped || !__velarGraphSetContains(__velarRuntime.watchQueue, observer)) continue;\n if ((__velarFlushBudget -= 1) < 0) { __velarFlushOverflow(token); return; }\n step(observer);\n ran = true;\n }\n if (!ran) break;\n }\n for (const observer of __velarGraphSetItems(__velarRuntime.domQueue)) {\n if (observer.mode === \"computed\") break;\n if ((__velarFlushBudget -= 1) < 0) { __velarFlushOverflow(token); return; }\n step(observer);\n }\n }\n if (__velarGraphSetCount(__velarRuntime.domQueue) || __velarGraphSetCount(__velarRuntime.watchQueue)) __velarScheduleFlush();\n}\n\n" + "function __velarCreateRuntime() {\n const runtime = Object.create(null);\n const domQueue = Object.freeze(__velarGraphCreateSet());\n const watchQueue = Object.freeze(__velarGraphCreateSet());\n const errorHandlers = Object.freeze(__velarGraphCreateSet());\n const unhandledFailures = Object.freeze(__velarGraphCreateSet());\n const actionFailures = Object.freeze(__velarGraphCreateWeakSet());\n const lookSources = Object.freeze(__velarGraphCreateWeakMap());\n const classSources = Object.freeze(__velarGraphCreateWeakMap());\n const dependencies = Object.freeze(__velarGraphCreateWeakMap());\n const rawToProxy = Object.freeze(__velarGraphCreateWeakMap());\n const proxyToRaw = Object.freeze(__velarGraphCreateWeakMap());\n const versions = Object.freeze(__velarGraphCreateWeakMap());\n const parents = Object.freeze(__velarGraphCreateWeakMap());\n const subscriptionStops = __velarGraphCreateWeakMap();\n const collectionBrands = __velarGraphCreateWeakMap();\n const iterateKey = Symbol.for(\"velar.reactive.iterate.v1\");\n const structureKey = Symbol.for(\"velar.reactive.structure.v1\");\n const deepKey = Symbol.for(\"velar.reactive.deep.v1\");\n let lookImplementation = null;\n const toRaw = (value) => {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) return value;\n return __velarGraphWeakMapRead(proxyToRaw, value) ?? value;\n };\n const trackSubscribers = (subscribers) => {\n const observer = runtime.activeObserver;\n if (!observer || observer.stopped) return;\n __velarGraphSetInsert(subscribers, observer);\n __velarGraphSetInsert(observer.dependencies, subscribers);\n };\n const runTracked = (observer, read) => {\n const previousDependencies = observer.dependencies;\n // Every run needs a second dependency set to diff against, and an observer\n // that re-runs thousands of times per second would otherwise allocate one\n // per run. The emptied previous set is kept as the next run's buffer.\n const spare = observer.spareDependencies;\n observer.spareDependencies = null;\n observer.dependencies = spare ?? __velarGraphCreateSet();\n const previousObserver = runtime.activeObserver;\n runtime.activeObserver = observer;\n try { return read(); }\n finally {\n runtime.activeObserver = previousObserver;\n for (const subscribers of __velarGraphSetItems(previousDependencies)) {\n if (__velarGraphSetContains(observer.dependencies, subscribers)) continue;\n // A stop fires exactly when an actual removal empties the set. Firing\n // on an already-empty set would let two detaching computeds whose\n // cleanups have not yet emptied their dependency sets re-trigger each\n // other without bound.\n if (__velarGraphSetRemove(subscribers, observer) && __velarGraphSetCount(subscribers) === 0) {\n const stop = __velarGraphWeakMapRead(subscriptionStops, subscribers);\n if (stop) stop();\n }\n }\n __velarGraphSetEmpty(previousDependencies);\n observer.spareDependencies = previousDependencies;\n }\n };\n const cleanupObserver = (observer) => {\n for (const subscribers of __velarGraphSetItems(observer.dependencies)) {\n if (__velarGraphSetRemove(subscribers, observer) && __velarGraphSetCount(subscribers) === 0) {\n const stop = __velarGraphWeakMapRead(subscriptionStops, subscribers);\n if (stop) stop();\n }\n }\n __velarGraphSetEmpty(observer.dependencies);\n };\n const track = (target, key) => {\n target = toRaw(target);\n if ((typeof target !== \"object\" && typeof target !== \"function\") || target === null) return;\n let byKey = __velarGraphWeakMapRead(dependencies, target);\n if (!byKey) { byKey = __velarGraphCreateMap(); __velarGraphWeakMapWrite(dependencies, target, byKey); }\n let subscribers = __velarGraphMapRead(byKey, key);\n if (!subscribers) {\n subscribers = __velarGraphCreateSet();\n __velarGraphMapWrite(byKey, key, subscribers);\n const ownedSubscribers = subscribers;\n __velarGraphWeakMapWrite(subscriptionStops, subscribers, () => {\n if (__velarGraphMapRead(byKey, key) !== ownedSubscribers) return;\n __velarGraphMapRemove(byKey, key);\n if (__velarGraphMapCount(byKey) === 0) __velarGraphWeakMapRemove(dependencies, target);\n });\n }\n trackSubscribers(subscribers);\n };\n // P2b-9: the path a write travelled, in the words the author would recognise.\n // Only the shape is named -- never a value -- because this reaches a report.\n // The kind travels beside the phrase rather than being read back out of it:\n // the reader of this is the runaway report, and it decides which remedy to\n // give from the kind, not by looking inside a sentence.\n const describeSubject = (target, key) => {\n const container = __velarGraphIsList(target) ? \"List\" : __velarGraphIsRecord(target) ? \"record\" : \"collection\";\n if (key === iterateKey || key === structureKey) return { kind: \"collection\", text: \"the size or contents of a \" + container };\n if (key === deepKey) return { kind: \"value\", text: \"a nested value of a \" + container };\n if (typeof key === \"number\") return { kind: \"value\", text: \"element \" + key + \" of a \" + container };\n if (typeof key === \"string\") return { kind: \"value\", text: \"field '\" + key + \"'\" };\n return { kind: \"value\", text: \"a tracked value\" };\n };\n const notify = (target, key) => {\n const byKey = __velarGraphWeakMapRead(dependencies, target);\n const subscribers = byKey ? __velarGraphMapRead(byKey, key) : null;\n if (subscribers) for (const observer of __velarGraphSetItems(subscribers)) {\n // A write that lands while its own reader is still running is the\n // self-invalidating shape, and it is the only one whose path is worth\n // describing -- so the description is built there and nowhere else, which\n // keeps every ordinary write to one property read on this path. The\n // observer's own budget owns the report; this only tells it what to name.\n if (observer.running) {\n const subject = describeSubject(target, key);\n observer.selfInvalidationSubject = subject.text;\n observer.selfInvalidationKind = subject.kind;\n }\n observer.notify();\n }\n };\n const bump = (target) => {\n __velarGraphWeakMapWrite(versions, target, (__velarGraphWeakMapRead(versions, target) ?? 0) + 1);\n };\n const trigger = (target, key, iterate = false, structure = false, indexFrom = null, allKeys = false) => {\n target = toRaw(target);\n if ((typeof target !== \"object\" && typeof target !== \"function\") || target === null) return;\n bump(target);\n notify(target, key);\n if (allKeys || indexFrom !== null) {\n const byKey = __velarGraphWeakMapRead(dependencies, target);\n if (byKey) for (const candidate of __velarGraphMapKeyItems(byKey)) {\n if (candidate === key) continue;\n if (allKeys || (typeof candidate === \"number\" && candidate >= indexFrom)) notify(target, candidate);\n }\n }\n if (iterate) notify(target, iterateKey);\n if (structure) notify(target, structureKey);\n notify(target, deepKey);\n const owners = __velarGraphWeakMapRead(parents, target);\n // A mutation of an unowned value -- the overwhelmingly common case -- must\n // not pay for the cycle bookkeeping that only an ancestor walk needs.\n if (!owners) return;\n const visited = __velarGraphCreateSet();\n __velarGraphSetInsert(visited, target);\n const bubble = (current) => {\n if (__velarGraphSetContains(visited, current)) return;\n __velarGraphSetInsert(visited, current);\n bump(current);\n notify(current, deepKey);\n const next = __velarGraphWeakMapRead(parents, current);\n if (next) for (const owner of __velarGraphSetItems(next)) bubble(owner);\n };\n for (const owner of __velarGraphSetItems(owners)) bubble(owner);\n };\n const link = (child, parent) => {\n if (child === null || (typeof child !== \"object\" && typeof child !== \"function\")) return;\n linkOwner(toRaw(child), parent, true);\n };\n // 'structural' separates a slot being filled from a slot merely being read.\n // A read proves the child is in the parent right now; only a write adds an\n // occurrence, and only a write can create the duplicate the running count\n // cannot see for itself.\n const linkOwner = (child, parent, structural = false) => {\n parent = toRaw(parent);\n if (parent === null || (typeof parent !== \"object\" && typeof parent !== \"function\") || child === parent) return;\n let owners = __velarGraphWeakMapRead(parents, child);\n if (!owners) { owners = __velarGraphCreateSet(); __velarGraphWeakMapWrite(parents, child, owners); }\n const known = __velarGraphSetContains(owners, parent);\n __velarGraphSetInsert(owners, parent);\n const counts = __velarGraphWeakMapRead(containment, parent);\n if (!counts) return;\n if (structural && known) { __velarGraphWeakMapRemove(containment, parent); return; }\n if ((__velarGraphMapRead(counts, child) ?? 0) < 1) __velarGraphMapWrite(counts, child, 1);\n };\n // Removing the last owner of a value detaches everything only that value\n // owned. Without the cascade, replacing a state root leaves every surviving\n // descendant pointing at the dead root: the root stays strongly reachable\n // and each later deep mutation walks one more generation.\n const release = (root) => {\n const pending = [root];\n let index = 0;\n while (index < pending.length) {\n const current = pending[index];\n index += 1;\n forEachOwnedValue(current, (value) => {\n const owners = __velarGraphWeakMapRead(parents, value);\n if (!owners || !__velarGraphSetContains(owners, current)) return;\n __velarGraphSetRemove(owners, current);\n if (__velarGraphSetCount(owners) > 0) return;\n __velarGraphWeakMapRemove(parents, value);\n pending[pending.length] = value;\n });\n }\n };\n const unlink = (child, parent) => {\n child = toRaw(child);\n parent = toRaw(parent);\n const owners = child !== null && (typeof child === \"object\" || typeof child === \"function\")\n ? __velarGraphWeakMapRead(parents, child)\n : null;\n if (!owners) return;\n __velarGraphSetRemove(owners, parent);\n if (__velarGraphSetCount(owners) > 0) return;\n __velarGraphWeakMapRemove(parents, child);\n release(child);\n };\n // Map and Set membership is decided once per value and remembered: the only\n // cross-realm test JavaScript offers is invoking a prototype accessor and\n // catching, and a record write must not pay two thrown exceptions per field.\n const collectionBrand = (value) => {\n const known = __velarGraphWeakMapRead(collectionBrands, value);\n if (known !== undefined) return known;\n let brand = 0;\n try { __velarGraphMapCount(value); brand = 1; }\n catch {\n try { __velarGraphSetCount(value); brand = 2; }\n catch { brand = 0; }\n }\n __velarGraphWeakMapWrite(collectionBrands, value, brand);\n return brand;\n };\n const forEachOwnedValue = (parent, visit) => {\n if (parent === null || (typeof parent !== \"object\" && typeof parent !== \"function\")) return;\n if (__velarGraphIsList(parent)) {\n for (let index = 0; index < parent.length; index += 1) {\n const value = toRaw(__velarGraphOwnDescriptor(parent, index)?.value);\n if (value !== null && (typeof value === \"object\" || typeof value === \"function\")) visit(value);\n }\n return;\n }\n const brand = collectionBrand(parent);\n if (brand === 1) {\n for (const value of __velarGraphMapItems(parent)) {\n const owned = toRaw(value);\n if (owned !== null && (typeof owned === \"object\" || typeof owned === \"function\")) visit(owned);\n }\n // A Map key is linked to its Map exactly like a value, so releasing the\n // Map has to release object keys too.\n for (const value of __velarGraphMapKeyItems(parent)) {\n const owned = toRaw(value);\n if (owned !== null && (typeof owned === \"object\" || typeof owned === \"function\")) visit(owned);\n }\n return;\n }\n if (brand === 2) {\n for (const value of __velarGraphSetItems(parent)) {\n const owned = toRaw(value);\n if (owned !== null && (typeof owned === \"object\" || typeof owned === \"function\")) visit(owned);\n }\n return;\n }\n if (typeof parent !== \"object\") return;\n for (const name of __velarGraphOwnNames(parent)) {\n const descriptor = __velarGraphOwnDescriptor(parent, name);\n if (!descriptor || !(\"value\" in descriptor)) continue;\n const value = toRaw(descriptor.value);\n if (value !== null && (typeof value === \"object\" || typeof value === \"function\")) visit(value);\n }\n };\n // Containment used to be re-derived by scanning the whole container on every\n // element write, which made one assignment into a rendered List cost O(list\n // length). The occurrence index answers the same question -- does the parent\n // still reference this child anywhere? -- in constant time: it is built once\n // from the container's real contents and then maintained by the same link and\n // release calls that change them.\n const containment = __velarGraphCreateWeakMap();\n const countOccurrence = (counts, value) => {\n value = toRaw(value);\n if (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) return;\n __velarGraphMapWrite(counts, value, (__velarGraphMapRead(counts, value) ?? 0) + 1);\n };\n // Mirrors exactly what the old scan looked at, Map keys included as owned\n // values are, so the index cannot answer a question the scan answered\n // differently.\n const buildContainment = (parent) => {\n const counts = __velarGraphCreateMap();\n if (__velarGraphIsList(parent)) {\n for (let index = 0; index < parent.length; index += 1) countOccurrence(counts, __velarGraphOwnDescriptor(parent, index)?.value);\n return counts;\n }\n const brand = collectionBrand(parent);\n if (brand === 1) {\n for (const value of __velarGraphMapItems(parent)) countOccurrence(counts, value);\n return counts;\n }\n if (brand === 2) {\n for (const value of __velarGraphSetItems(parent)) countOccurrence(counts, value);\n return counts;\n }\n if (!parent || typeof parent !== \"object\") return counts;\n for (const name of __velarGraphOwnNames(parent)) {\n const descriptor = __velarGraphOwnDescriptor(parent, name);\n if (descriptor && \"value\" in descriptor) countOccurrence(counts, descriptor.value);\n }\n return counts;\n };\n // The one guard every detach path shares: a primitive was never linked, and\n // an object with no owners has nothing to release, so neither may reach the\n // containment bookkeeping.\n const releaseChild = (parent, child) => {\n if (child === null || (typeof child !== \"object\" && typeof child !== \"function\")\n || !__velarGraphWeakMapContains(parents, child)) return;\n parent = toRaw(parent);\n if (parent === null || (typeof parent !== \"object\" && typeof parent !== \"function\")) return;\n child = toRaw(child);\n // A freshly built index already reflects the slot that was just cleared;\n // a maintained one still counts it, so only that one takes the decrement.\n let counts = __velarGraphWeakMapRead(containment, parent);\n let remaining;\n if (counts) remaining = (__velarGraphMapRead(counts, child) ?? 0) - 1;\n else {\n counts = buildContainment(parent);\n __velarGraphWeakMapWrite(containment, parent, counts);\n remaining = __velarGraphMapRead(counts, child) ?? 0;\n }\n if (remaining > 0) { __velarGraphMapWrite(counts, child, remaining); return; }\n __velarGraphMapRemove(counts, child);\n unlink(child, parent);\n };\n // The registry operation stays exactly two parameters wide; 'structural'\n // belongs to the internal call, which knows whether a slot is being filled or\n // merely read, and every caller outside this file fills one.\n const reactive = (value, parent = null) => reactiveValue(value, parent, true);\n const reactiveValue = (value, parent, structural) => {\n if (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) return value;\n value = toRaw(value);\n if (parent !== null) linkOwner(value, parent, structural);\n if (typeof value !== \"object\" || __velarGraphIsList(value) || !__velarGraphIsExtensible(value)) return value;\n if (!__velarGraphIsRecord(value)) {\n // D114 P6 item 7 (ST-U4): the one place an unwrapped class instance is\n // handed back out of a state graph. In a development host its fields are\n // observed from here so a `computed` or `watch` that reads one is told\n // the read can never update; in a production build the detector's hooks\n // (stale-class.js) are null and this is one already-false test on the hot\n // path. The owner is handed over rather than the cell's name, because the\n // report names the path from the cell down to the instance.\n if (__velarStaleClassHooks !== null && parent !== null) __velarObserveClassFields(value, parent);\n return value;\n }\n let proxy = __velarGraphWeakMapRead(rawToProxy, value);\n if (proxy) return proxy;\n proxy = new __velarGraphNativeProxy(value, {\n get(target, key) {\n track(target, key);\n return reactiveValue(__velarGraphGet(target, key, target), target, false);\n },\n set(target, key, next) {\n next = toRaw(next);\n const present = __velarGraphHas(target, key);\n const previous = toRaw(__velarGraphGet(target, key, target));\n // Creating an absent key is a structural change even when the value\n // written equals the absent key's 'undefined' reading.\n const changed = !present || !__velarGraphSame(previous, next);\n const written = __velarGraphSet(target, key, next, target);\n if (!written || !changed) return written;\n link(next, target);\n releaseChild(target, previous);\n trigger(target, key, true, !present);\n return true;\n },\n has(target, key) { track(target, key); return __velarGraphHas(target, key); },\n deleteProperty(target, key) {\n if (!__velarGraphHas(target, key)) return true;\n const previous = toRaw(__velarGraphGet(target, key, target));\n const deleted = __velarGraphDelete(target, key);\n if (deleted) {\n releaseChild(target, previous);\n trigger(target, key, true, true);\n }\n return deleted;\n },\n });\n __velarGraphWeakMapWrite(rawToProxy, value, proxy);\n __velarGraphWeakMapWrite(proxyToRaw, proxy, value);\n return proxy;\n };\n const trackDeep = (value) => { value = toRaw(value); track(value, deepKey); return value; };\n const versionOf = (value) => {\n value = toRaw(value);\n return value && (typeof value === \"object\" || typeof value === \"function\")\n ? __velarGraphWeakMapRead(versions, value) ?? 0\n : 0;\n };\n const collectionRead = (value, key, child) => {\n value = toRaw(value);\n track(value, key);\n // Only containers already connected to a state graph own children read\n // through them. Fresh derived Lists (filter/map/etc.) stay ephemeral and\n // cannot become strongly retained parents of every item merely by being\n // iterated during rendering.\n return reactiveValue(child, __velarGraphWeakMapContains(parents, value) ? value : null, false);\n };\n const collectionTrigger = (value, key, iterate = true, structure = false, indexFrom = null, allKeys = false) => trigger(toRaw(value), key, iterate, structure, indexFrom, allKeys);\n const collectionUnlink = (value, child) => {\n releaseChild(toRaw(value), toRaw(child));\n };\n const computed = (read) => {\n if (typeof read !== \"function\") throw new TypeError(\"computed requires a function\");\n let dirty = true;\n let evaluating = false;\n let recursed = false;\n let initialized = false;\n let value;\n let failed = false;\n let failure;\n const subscribers = __velarGraphCreateSet();\n const notifyDependents = (skip = null) => {\n for (const dependent of __velarGraphSetItems(subscribers)) if (dependent !== skip) dependent.notify();\n };\n const invalidateComputedDependents = () => {\n for (const dependent of __velarGraphSetItems(subscribers)) {\n if (dependent.mode === \"computed\") dependent.notify();\n }\n };\n const observer = {\n mode: \"computed\",\n stopped: false,\n running: false,\n selfInvalidations: 0,\n // P2b-9: filled in by the graph's notify when a write lands while this\n // value is still being derived, so the runaway report names the path.\n selfInvalidationSubject: \"\",\n selfInvalidationKind: \"\",\n dependencies: __velarGraphCreateSet(),\n notify() {\n // Stopping is shared discipline with DOM and watch observers: a flush\n // overflow marks queued computed observers stopped, and a stopped\n // observer must go inert instead of re-entering the storm on the next\n // write.\n if (observer.stopped) return;\n // The 100 self-invalidation cap covers computed observers too. A\n // computed whose own turn (evaluation plus dependent notification)\n // keeps invalidating it is stopped with the same owned report a\n // render or watch observer gets, instead of running to the whole\n // flush budget.\n if (observer.running) {\n observer.selfInvalidations += 1;\n if (observer.selfInvalidations > 100) {\n observer.stopped = true;\n cleanupObserver(observer);\n reportUntracked(new RangeError(\"A computed value cannot invalidate itself more than 100 times\"\n + (observer.selfInvalidationSubject ? \": it writes \" + observer.selfInvalidationSubject + \" while reading it\" : \"\")));\n return;\n }\n } else {\n observer.selfInvalidations = 0;\n }\n if (dirty) return;\n dirty = true;\n if (__velarGraphSetCount(subscribers) === 0) {\n cleanupObserver(observer);\n return;\n }\n schedule(observer);\n // A downstream computed must become dirty immediately so a same-turn\n // read cannot observe its cached result while an upstream dependency\n // is already stale. DOM and watch observers still wait for evaluation\n // to prove that the public result actually changed.\n invalidateComputedDependents();\n },\n run() {\n if (observer.stopped || !dirty || __velarGraphSetCount(subscribers) === 0) return;\n observer.running = true;\n try {\n if (evaluate(false)) notifyDependents();\n } finally { observer.running = false; }\n },\n };\n const detach = () => {\n cleanupObserver(observer);\n dirty = true;\n };\n __velarGraphWeakMapWrite(subscriptionStops, subscribers, detach);\n const evaluate = (throwFailure) => {\n if (evaluating) {\n recursed = true;\n throw new RangeError(\"A computed value cannot read itself recursively\");\n }\n const previous = value;\n const previouslyFailed = failed;\n const previousFailure = failure;\n const hadValue = initialized;\n evaluating = true;\n recursed = false;\n failed = false;\n failure = undefined;\n try { value = runTracked(observer, read); }\n catch (error) { failed = true; failure = error; }\n finally {\n evaluating = false;\n initialized = true;\n dirty = false;\n }\n // A computed that failed because its own recursion guard tripped sits on\n // a dependency cycle. The failure is cached and served, but the cyclic\n // edges must not persist: two failed computeds that keep notifying each\n // other would otherwise ping-pong the next flush into the whole-flush\n // budget. Detaching unwinds the cycle (a peer whose last subscriber\n // leaves detaches with it) and a later read simply re-attempts.\n if (failed && recursed) detach();\n else if (__velarGraphSetCount(subscribers) === 0) detach();\n recursed = false;\n const changed = !hadValue || previouslyFailed !== failed || (failed ? previousFailure !== failure : !__velarGraphSame(previous, value));\n if (throwFailure && failed) throw failure;\n return changed;\n };\n const access = () => {\n const consumer = runtime.activeObserver;\n if (consumer !== observer) trackSubscribers(subscribers);\n if (dirty && !observer.stopped) {\n // A cyclic read re-enters access while the outer evaluation is still\n // running, so the running span is restored, never cleared.\n const wasRunning = observer.running;\n observer.running = true;\n try {\n const changed = evaluate(false);\n if (changed && initialized) notifyDependents(consumer);\n } finally { observer.running = wasRunning; }\n }\n if (failed) throw failure;\n return value;\n };\n return __velarGraphFreeze(access);\n };\n // The loud channel for a failure nothing owns.\n //\n // D114 P6 item 4 (LC-C1) and F9-web (WB-C1): every `tick()` waiting on the\n // flush is a claimant, in every host. A caller waiting on the flush is the\n // one place a failure nobody handled can be delivered *to somebody*, so the\n // flush's first unowned failure is parked and every pending `tick()` rejects\n // with it -- the promise that awaiting `tick()` cannot step over a broken\n // update is one the second concurrent awaiter has to keep too.\n //\n // Everything else goes to the host, and there is no second channel beside a\n // claimant: a later failure in the same flush, whose claimants are already\n // spoken for, and every failure raised with nobody waiting at all. In a\n // browser that is the microtask throw the host error event catches and the\n // page survives; in a non-browser host (a headless 'velar test' process, a\n // worker) the same throw would terminate the process, which the runtime\n // boundary forbids, so there it is traced to the report channel. Nothing is\n // parked for a `tick()` that is not yet waiting, because a caller who arrives\n // after the flush was never waiting on it.\n const escalate = (error) => {\n if (__velarTickWaiting() && __velarGraphSetCount(unhandledFailures) === 0) {\n __velarGraphSetInsert(unhandledFailures, error);\n return;\n }\n if (__velarDomDocument !== null) {\n __velarEnqueue(() => { throw error; });\n return;\n }\n __velarFoundationTrace(error);\n };\n const report = (value, options) => {\n const error = __velarNormalizeError(value);\n const checked = __velarReportOptions(options);\n const timestamp = __velarNow();\n if (!__velarWebErrorFinite(timestamp)) throw new TypeError(\"The browser returned an invalid error timestamp\");\n const errorReport = __velarWebErrorFreeze({\n error,\n phase: checked.phase,\n detail: checked.detail,\n component: checked.component,\n timestamp,\n });\n let handled = false;\n for (const handler of __velarGraphSetItems(errorHandlers)) {\n handled = true;\n try {\n const result = handler(errorReport);\n __velarObservePromise(result, (failure) => escalate(__velarNormalizeError(failure)));\n } catch (failure) { escalate(__velarNormalizeError(failure)); }\n }\n if (checked.unhandled && !handled) escalate(error);\n return errorReport;\n };\n // A report raised from inside a tracked evaluation (the computed cap) must\n // not let handler reads become dependencies of the failing observer.\n const reportUntracked = (error) => {\n const previousObserver = runtime.activeObserver;\n runtime.activeObserver = null;\n try { report(error, { phase: \"update\", detail: \"\", component: \"\", unhandled: true }); }\n finally { runtime.activeObserver = previousObserver; }\n };\n // The queue insert stays on the registry -- computed observers are created by\n // whichever module stamped it first (velar/app under ESM import order, or the\n // application prelude) and must schedule correctly whichever that was -- but\n // the drain it calls is the module-scope one below, and there is now exactly\n // one of those. A queue that outgrows its bound is the flush budget's failure\n // to own, not an exception thrown out of the assignment that happened to\n // cross the line: throwing here left the writing cell's subscriber walk half\n // finished, with the remaining observers subscribed and never notified again.\n const schedule = (observer) => {\n __velarGraphSetInsert(observer.mode === \"watch\" ? watchQueue : domQueue, observer);\n __velarScheduleFlush();\n };\n const applyLook = (...arguments_) => {\n if (!lookImplementation) throw new TypeError(\"Link Look requires the VelarScript Web runtime\");\n return lookImplementation(...arguments_);\n };\n const installLook = (implementation) => {\n if (typeof implementation !== \"function\") throw new TypeError(\"VelarScript Look integration requires a function\");\n lookImplementation ??= implementation;\n return null;\n };\n const fields = {\n version: \"0.12\", domQueue, watchQueue, flushPending: false, activeObserver: null, errorHandlers,\n actionFailures, unhandledFailures, lookSources, classSources, dependencies, rawToProxy, proxyToRaw, versions, parents,\n toRaw, reactive, track, trackDeep, trigger, versionOf, collectionRead, collectionTrigger, collectionUnlink,\n trackSubscribers, runTracked, cleanupObserver, computed,\n schedule, report, applyLook, installLook,\n };\n for (const name of __velarRuntimeFields) Object.defineProperty(runtime, name, {\n value: fields[name],\n enumerable: false,\n configurable: false,\n writable: name === \"flushPending\" || name === \"activeObserver\",\n });\n return Object.preventExtensions(runtime);\n}\n\nfunction __velarRequireRuntime(value) {\n if (!value || typeof value !== \"object\") throw new TypeError(\"VelarScript Web runtime ownership is invalid\");\n // The schema comparison comes first, ahead of ownership and the field roster:\n // a schema bump normally changes the roster too, so leaving it last reported\n // \"fields are invalid\" and never named the one fact that identifies the\n // cause. The version is read through its descriptor rather than the property\n // so an unvalidated object cannot answer it with a getter.\n const __velarVersionDescriptor = Object.getOwnPropertyDescriptor(value, \"version\");\n const __velarVersion = __velarVersionDescriptor && \"value\" in __velarVersionDescriptor ? __velarVersionDescriptor.value : undefined;\n if (__velarVersion !== \"0.12\") {\n throw new TypeError(\"VelarScript Web runtime schema \" + (typeof __velarVersion === \"string\" ? __velarVersion : \"(unknown)\") + \" does not match this module's schema 0.12; one build mixed two generations of @velarscript/* — run 'npm ls @velarscript/compiler' and pin one version\");\n }\n if (Object.getPrototypeOf(value) !== null || Object.isExtensible(value)\n || Object.getOwnPropertySymbols(value).length > 0) throw new TypeError(\"VelarScript Web runtime ownership is invalid\");\n const names = Object.getOwnPropertyNames(value);\n if (names.length !== __velarRuntimeFields.length || __velarRuntimeFields.some((name) => !names.includes(name))) {\n throw new TypeError(\"VelarScript Web runtime fields are invalid\");\n }\n for (const name of __velarRuntimeFields) {\n const descriptor = Object.getOwnPropertyDescriptor(value, name);\n const mutable = name === \"flushPending\" || name === \"activeObserver\";\n if (!descriptor || !(\"value\" in descriptor) || descriptor.enumerable || descriptor.configurable || descriptor.writable !== mutable) {\n throw new TypeError(\"VelarScript Web runtime field '\" + name + \"' is invalid\");\n }\n }\n if (!__velarRuntimeCollection(value.domQueue, \"Set\") || !__velarRuntimeCollection(value.watchQueue, \"Set\")\n || typeof value.flushPending !== \"boolean\" || (value.activeObserver !== null && typeof value.activeObserver !== \"object\")\n || !__velarRuntimeCollection(value.errorHandlers, \"Set\") || !__velarRuntimeCollection(value.actionFailures, \"WeakSet\")\n || !__velarRuntimeCollection(value.unhandledFailures, \"Set\")\n || !__velarRuntimeCollection(value.lookSources, \"WeakMap\") || !__velarRuntimeCollection(value.classSources, \"WeakMap\")\n || !__velarRuntimeCollection(value.dependencies, \"WeakMap\") || !__velarRuntimeCollection(value.rawToProxy, \"WeakMap\")\n || !__velarRuntimeCollection(value.proxyToRaw, \"WeakMap\") || !__velarRuntimeCollection(value.versions, \"WeakMap\")\n || !__velarRuntimeCollection(value.parents, \"WeakMap\")\n || typeof value.toRaw !== \"function\" || typeof value.reactive !== \"function\" || typeof value.track !== \"function\"\n || typeof value.trackDeep !== \"function\" || typeof value.trigger !== \"function\" || typeof value.versionOf !== \"function\"\n || typeof value.collectionRead !== \"function\" || typeof value.collectionTrigger !== \"function\" || typeof value.collectionUnlink !== \"function\"\n || typeof value.trackSubscribers !== \"function\" || typeof value.runTracked !== \"function\"\n || typeof value.cleanupObserver !== \"function\" || typeof value.computed !== \"function\" || typeof value.schedule !== \"function\"\n || typeof value.report !== \"function\" || typeof value.applyLook !== \"function\" || typeof value.installLook !== \"function\") {\n throw new TypeError(\"VelarScript Web runtime values are invalid\");\n }\n return value;\n}\n\nconst __velarRuntime = (() => {\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, __velarRuntimeKey);\n if (descriptor) {\n if (!(\"value\" in descriptor) || descriptor.enumerable || descriptor.configurable || descriptor.writable) {\n throw new TypeError(\"VelarScript Web runtime registry ownership is invalid\");\n }\n return __velarRequireRuntime(descriptor.value);\n }\n const runtime = __velarCreateRuntime();\n Object.defineProperty(globalThis, __velarRuntimeKey, {\n value: runtime,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return runtime;\n})();\n" + "/**\n * D114 P6 item 7 (ST-U4), completed by F9-web (WB-I3 / WB-I4 / WB-U4): the\n * development host's detector for a `computed`, a `watch` subject or a DOM\n * interpolation that reads a field of a class instance held in `state`.\n *\n * web-api's rule stands and is not changing: classes are never wrapped, because\n * a proxy over an instance would change what `self` is and what identity means.\n * The consequence had no name: `state box = Counter()` with\n * `computed shown = box.value` compiles clean, renders once, and never updates\n * again, because `box.bump()` writes a field nothing is watching. Only\n * replacing the cell publishes. `<p>{box.value}</p>` is the same fact one step\n * closer to the page -- the text node is written once and never again -- so the\n * three readers are one rule and earn one sentence.\n *\n * So the instance's own data fields are observed while a development host is\n * present -- the same trade the frozen-read detector makes, in the same\n * channel. The instance is not replaced: an accessor pair over the value it\n * already held keeps its identity, its prototype, and what `self` means inside\n * its own methods, which a proxy could not. A production build publishes no\n * hooks, so none of this exists there.\n *\n * Three things this file owns that the report did not have before:\n *\n * - **What to write instead (WB-I3).** The remedy used to be spelled\n * `cell = Class(...)` whatever shape the value was in, and the walk that\n * finds the cell climbs through records and Lists -- so `state holder =\n * {box: Box()}` was told to write `holder = Box(...)`, which does not\n * compile. The walk now carries the path it climbed, and the remedy is\n * written for the shape that actually holds the instance.\n * - **When the read has actually gone stale (WB-I4).** A `const` field is one\n * nothing can change, so a read of it can never go stale and the sentence\n * \"changing 'value' publishes nothing\" describes something that will not\n * happen. The emitted class makes `const` and `let` the same ordinary data\n * property, so the runtime cannot tell them apart by looking -- but it does\n * not have to: the report is made when the field is **written** under a\n * reader that cannot see it, which is the frozen-read detector's own rule\n * (\"a report is made when one of them later changes -- never when it is\n * read\"). A field nothing writes is never reported, and `const` is exactly\n * the case where nothing can.\n * - **The member the line reads (WB-U4).** `get shown()` backed by a field\n * `inner` was reported as `inner`, a name the author's line never contains\n * and may not know exists. A read that enters through the class's own\n * getter or method records that member for as long as it runs, so the\n * report can name both.\n */\nconst __velarStaleClassHooks = (() => {\n const hooks = globalThis.__velarDevelopmentHooks;\n return hooks && typeof hooks.frozenRead === \"function\" ? hooks : null;\n})();\nconst __velarStaleClassSeen = __velarStaleClassHooks === null ? null : __velarGraphCreateWeakSet();\nconst __velarStaleClassWrapped = __velarStaleClassHooks === null ? null : __velarGraphCreateWeakSet();\nconst __velarStaleClassReported = __velarStaleClassHooks === null ? null : __velarGraphCreateSet();\n// The class member a read is currently inside, or null when the reading line\n// names the field itself. Outermost wins: a method that reads through a getter\n// of its own is still entered as the method the author wrote.\nlet __velarStaleClassMember = null;\n\n/** The written class name, or null where the value is not an instance of one. */\nfunction __velarStaleClassName(instance) {\n const prototype = __velarGraphPrototype(instance);\n if (prototype === null) return null;\n const constructor = __velarGraphOwnDescriptor(prototype, \"constructor\");\n const value = constructor && \"value\" in constructor ? constructor.value : null;\n if (typeof value !== \"function\") return null;\n const named = __velarGraphOwnDescriptor(value, \"name\");\n const name = named && \"value\" in named ? named.value : null;\n return typeof name === \"string\" && name !== \"\" ? name : null;\n}\n\n/**\n * Which slot of `owner` holds `child`: a record field, a List index, or null\n * where the owner is a shape whose slot has no spelling an author can write --\n * a `Map`, a `Set`, or an owner that no longer references the child at all. A\n * slot that cannot be named is a remedy that cannot be written, and the report\n * says so rather than inventing one.\n */\nfunction __velarStaleClassSlot(owner, child) {\n if (owner === null || typeof owner !== \"object\") return null;\n if (__velarGraphIsList(owner)) {\n for (let index = 0; index < owner.length; index += 1) {\n const descriptor = __velarGraphOwnDescriptor(owner, index);\n if (descriptor && \"value\" in descriptor && descriptor.value === child) return { index, field: null };\n }\n return null;\n }\n if (!__velarGraphIsRecord(owner)) return null;\n for (const name of __velarGraphOwnNames(owner)) {\n const descriptor = __velarGraphOwnDescriptor(owner, name);\n if (descriptor && \"value\" in descriptor && descriptor.value === child) return { index: -1, field: name };\n }\n return null;\n}\n\n/**\n * The `state` cell a value was reached through and the path from that cell down\n * to it, or null when no cell is above it. The walk is bounded and\n * breadth-first over the same ownership graph a deep change bubbles up, so a\n * class instance held one or two records below a state cell is found -- and a\n * value that is not under one is not reported about at all, because the report\n * has to name the place whose replacement publishes.\n *\n * `steps` is null when some owner on the path holds the value in a slot with no\n * written spelling; the cell is still named, and the remedy drops to the one\n * sentence that is true for every shape.\n */\nfunction __velarStaleClassLocation(instance, parent) {\n const seen = __velarGraphCreateSet();\n let frontier = [{ value: parent, child: instance, steps: [] }];\n for (let depth = 0; depth < 8 && frontier.length > 0; depth += 1) {\n const next = [];\n for (const entry of frontier) {\n const candidate = entry.value;\n if (candidate === null || (typeof candidate !== \"object\" && typeof candidate !== \"function\")) continue;\n if (__velarGraphSetContains(seen, candidate)) continue;\n __velarGraphSetInsert(seen, candidate);\n const descriptor = __velarGraphOwnDescriptor(candidate, \"velarStateName\");\n const name = descriptor && \"value\" in descriptor ? descriptor.value : null;\n // A cell holds its value in a closure rather than in a slot, so the step\n // into it is the cell itself and the path collected so far is complete.\n if (typeof name === \"string\" && name !== \"\") return { cell: name, steps: entry.steps };\n const owners = __velarGraphWeakMapRead(__velarRuntime.parents, candidate);\n if (!owners) continue;\n const slot = __velarStaleClassSlot(candidate, entry.child);\n let steps = null;\n if (slot !== null && entry.steps !== null) {\n steps = [slot];\n for (let index = 0; index < entry.steps.length; index += 1) steps[steps.length] = entry.steps[index];\n }\n for (const above of __velarGraphSetItems(owners)) next[next.length] = { value: above, child: candidate, steps };\n }\n frontier = next;\n }\n return null;\n}\n\n/** `holder.box`, `boxes[0]`, `groups[0].box` -- the path an author can read the value through. */\nfunction __velarStaleClassPath(cell, steps, count) {\n let text = cell;\n for (let index = 0; index < count; index += 1) {\n const step = steps[index];\n text += step.field === null ? \"[\" + step.index + \"]\" : \".\" + step.field;\n }\n return text;\n}\n\n/**\n * The write that publishes, for the shape the instance is actually in. The flat\n * case replaces the cell; a record below it is replaced with the field written\n * over, which is the update every other record in `state` takes; a List element\n * is replaced by index.\n */\nfunction __velarStaleClassRemedy(location, className) {\n const steps = location.steps;\n if (steps === null) return \"only replacing the value in state '\" + location.cell + \"' that holds it publishes.\";\n if (steps.length === 0) return \"only replacing the cell -- '\" + location.cell + \" = \" + className + \"(...)' -- publishes.\";\n const last = steps[steps.length - 1];\n const owner = __velarStaleClassPath(location.cell, steps, steps.length - 1);\n if (last.field === null) {\n return \"only replacing the element -- '\" + owner + \"[\" + last.index + \"] = \" + className + \"(...)' -- publishes.\";\n }\n return \"only replacing it -- '\" + owner + \" = {...\" + owner + \", \" + last.field + \": \" + className + \"(...)}' -- publishes.\";\n}\n\n/** The reading line, captured where the read happens rather than where the report is made. */\nfunction __velarStaleClassSite() {\n const site = new Error(\"velar stale class read\");\n try { return typeof site.stack === \"string\" ? site.stack : \"\"; } catch { return \"\"; }\n}\n\n/**\n * One mistake, one sentence, once per place, class and field -- whichever of\n * the three readers reached it first. Only the words that name the reader\n * change: a `computed` and a `watch` subject are a reactive value, and a\n * position in the document is the interpolation that wrote it.\n */\nfunction __velarReportStaleClassField(location, className, field, member, mode, stack) {\n const named = typeof member === \"string\" && member !== \"\" && member !== field ? member : null;\n const path = location.steps === null || location.steps.length === 0\n ? \"\" : \" at '\" + __velarStaleClassPath(location.cell, location.steps, location.steps.length) + \"'\";\n // Keyed by the place and the field, not by the member: two members that read\n // one field are two lines about one field that does not publish, and the\n // report names whichever reader reached it first, as it always has.\n const key = location.cell + \"|\" + path + \"|\" + className + \"|\" + field;\n if (__velarGraphSetContains(__velarStaleClassReported, key)) return;\n __velarGraphSetInsert(__velarStaleClassReported, key);\n const reader = mode === \"dom\" ? \"interpolation\" : \"value\";\n __velarStaleClassHooks.frozenRead({\n message: \"This \" + (mode === \"dom\" ? \"interpolation\" : \"reactive value\") + \" reads '\" + (named ?? field) + \"' on the \"\n + className + \" held in state '\" + location.cell + \"'\" + path + \".\"\n + (named === null ? \"\" : \" '\" + named + \"' reads the field '\" + field + \"'.\")\n + \" A class instance is never wrapped, so changing '\" + field\n + \"' publishes nothing and this \" + reader + \" stays as it is: \"\n + __velarStaleClassRemedy(location, className)\n + \" Hold the field in its own 'state' if it is meant to be followed.\",\n stack,\n });\n}\n\n/**\n * Observes one instance's own writable data fields. Fields the class did not\n * declare as plain values -- a getter it wrote itself, a sealed field -- are\n * left exactly as they are: this detector may not change what the program does,\n * only notice what it cannot see.\n *\n * The report is made when a reader that cannot follow the field meets a real\n * change to it, in whichever order the two arrive: a read that is already stale\n * reports on the spot, and a read of a value that changes later reports at the\n * change, on the line the read was made. A field that never changes is never\n * reported, which is what keeps a `const` field silent (WB-I4).\n */\nfunction __velarObserveClassFields(instance, parent) {\n if (__velarGraphWeakSetContains(__velarStaleClassSeen, instance)) return;\n __velarGraphWeakSetInsert(__velarStaleClassSeen, instance);\n const className = __velarStaleClassName(instance);\n if (className === null) return;\n const location = __velarStaleClassLocation(instance, parent);\n if (location === null) return;\n let observed = false;\n for (const field of __velarGraphOwnNames(instance)) {\n const descriptor = __velarGraphOwnDescriptor(instance, field);\n if (!descriptor || !(\"value\" in descriptor) || !descriptor.writable || !descriptor.configurable) continue;\n observed = true;\n let held = descriptor.value;\n let waiting = null;\n let moved = false;\n __velarGraphDefine(instance, field, {\n enumerable: descriptor.enumerable,\n configurable: true,\n // Named, not shorthand, for the frozen-read detector's reason: the\n // development host walks past its own frames to find the reading line,\n // and every engine spells an anonymous accessor differently.\n get: function __velarStaleClassFieldRead() {\n const observer = __velarRuntime.activeObserver;\n // Every mode an observer has is a reader that re-runs only when a\n // dependency it tracked changes, and this field is never one: the\n // rendering tier (\"dom\") is as stuck as the derivation tier.\n if (observer !== null && (observer.mode === \"computed\" || observer.mode === \"watch\" || observer.mode === \"dom\")) {\n if (moved) __velarReportStaleClassField(location, className, field, __velarStaleClassMember, observer.mode, __velarStaleClassSite());\n else if (waiting === null) waiting = { mode: observer.mode, member: __velarStaleClassMember, site: __velarStaleClassSite() };\n }\n return held;\n },\n set: function __velarStaleClassFieldWrite(next) {\n if (__velarGraphSame(held, next)) return;\n held = next;\n moved = true;\n if (waiting === null) return;\n const claim = waiting;\n waiting = null;\n __velarReportStaleClassField(location, className, field, claim.member, claim.mode, claim.site);\n },\n });\n }\n if (observed) __velarObserveClassMembers(instance);\n}\n\n/**\n * Records which of the class's own members a read entered through, so a report\n * can name the one the author's line contains as well as the field underneath\n * it. Only the prototype of an instance whose fields this detector already took\n * over is touched, and only in a development host: an object it observes\n * nothing on is one it has no report to make about either.\n */\nfunction __velarObserveClassMembers(instance) {\n const prototype = __velarGraphPrototype(instance);\n if (prototype === null || __velarGraphWeakSetContains(__velarStaleClassWrapped, prototype)) return;\n __velarGraphWeakSetInsert(__velarStaleClassWrapped, prototype);\n for (const member of __velarGraphOwnNames(prototype)) {\n // The compiler owns its own contracts -- `@dispose:` emits `__velar:dispose`\n // -- and a member the author did not write is not one their line names.\n if (member === \"constructor\" || member.indexOf(\"__velar\") === 0 || member.indexOf(\":\") >= 0) continue;\n const descriptor = __velarGraphOwnDescriptor(prototype, member);\n if (!descriptor || !descriptor.configurable) continue;\n if (typeof descriptor.get === \"function\" && descriptor.set === undefined) {\n const read = descriptor.get;\n __velarGraphDefine(prototype, member, {\n enumerable: descriptor.enumerable,\n configurable: true,\n get: function __velarStaleClassMemberRead() { return __velarStaleClassEnter(member, read, this, []); },\n });\n continue;\n }\n if (!(\"value\" in descriptor) || typeof descriptor.value !== \"function\") continue;\n const call = descriptor.value;\n __velarGraphDefine(prototype, member, {\n enumerable: descriptor.enumerable,\n configurable: true,\n writable: descriptor.writable,\n value: function __velarStaleClassMemberCall(...values) { return __velarStaleClassEnter(member, call, this, values); },\n });\n }\n}\n\nfunction __velarStaleClassEnter(member, operation, receiver, values) {\n const outer = __velarStaleClassMember;\n if (outer === null) __velarStaleClassMember = member;\n try { return __velarGraphApply(operation, receiver, values, \"class member\"); }\n finally { __velarStaleClassMember = outer; }\n}\n";
|
|
15
|
+
export const WEB_FOUNDATION_BODY = "const __velarRuntimeKey = Symbol.for(\"velar.runtime.v1\");\nconst __velarFoundationReflectApply = Object.getOwnPropertyDescriptor(Reflect, \"apply\")?.value;\nconst __velarFoundationQueueMicrotask = globalThis.queueMicrotask;\nconst __velarFoundationSetTimeout = globalThis.setTimeout;\nconst __velarFoundationDate = globalThis.Date;\nconst __velarFoundationDateNow = typeof __velarFoundationDate === \"function\"\n ? Object.getOwnPropertyDescriptor(__velarFoundationDate, \"now\")?.value\n : null;\nconst __velarFoundationConsole = globalThis.console ?? null;\nconst __velarFoundationConsoleError = __velarFoundationConsole !== null\n ? Object.getOwnPropertyDescriptor(__velarFoundationConsole, \"error\")?.value ?? null\n : null;\n// D114 WB-D1 (CO-I6 on the Web face): the host-frame policy has one\n// implementation, `__velarHostErrorTrace` in packages/compiler/runtime/error.js,\n// and this is one of its callers rather than a third writer of the same\n// sentence. Reading `error.stack` here printed exactly the two classes of frame\n// that policy exists to hide -- the runtime's own `__velar` helpers and Node's\n// internals -- with no \"(N frames hidden; ...)\" line and no answer to\n// `velar run --stack`, which is the launcher path's promise repeated on a\n// channel that did not keep it. The message-only fallback this used to spell a\n// second time is that function's own second answer.\n//\n// The name arrives with the error-normalization runtime: an inlined Web program\n// carries it in `WEB_ERROR_HOST_RUNTIME`, and a project build imports it beside\n// `normalizeError` (packages/web/src/emit/runtime-imports.ts).\nfunction __velarFoundationTrace(error) {\n if (typeof __velarFoundationConsoleError !== \"function\" || typeof __velarFoundationReflectApply !== \"function\") return;\n let trace = \"An unhandled VelarScript failure was reported\";\n try { trace = __velarHostErrorTrace(error, trace); } catch {}\n try { __velarFoundationReflectApply(__velarFoundationConsoleError, __velarFoundationConsole, [\"Unhandled VelarScript error report: \" + trace]); } catch {}\n}\nfunction __velarEnqueue(callback) {\n if (typeof __velarFoundationQueueMicrotask !== \"function\" || typeof __velarFoundationReflectApply !== \"function\") {\n throw new TypeError(\"The browser queueMicrotask API is unavailable\");\n }\n return __velarFoundationReflectApply(__velarFoundationQueueMicrotask, globalThis, [callback]);\n}\nfunction __velarNow() {\n if (typeof __velarFoundationDateNow !== \"function\" || typeof __velarFoundationReflectApply !== \"function\") {\n throw new TypeError(\"The browser Date.now API is unavailable\");\n }\n return __velarFoundationReflectApply(__velarFoundationDateNow, __velarFoundationDate, []);\n}\nconst __velarRuntimeFields = Object.freeze([\n \"version\", \"domQueue\", \"watchQueue\", \"flushPending\", \"activeObserver\", \"errorHandlers\",\n \"actionFailures\", \"unhandledFailures\", \"lookSources\", \"classSources\", \"dependencies\", \"rawToProxy\", \"proxyToRaw\",\n \"versions\", \"parents\", \"toRaw\", \"reactive\", \"track\", \"trackDeep\", \"trigger\", \"versionOf\",\n \"collectionRead\", \"collectionTrigger\", \"collectionUnlink\", \"trackSubscribers\", \"runTracked\", \"cleanupObserver\", \"computed\",\n \"schedule\", \"report\", \"applyLook\", \"installLook\",\n]);\n\nfunction __velarRuntimeCollection(value, kind) {\n try {\n if (kind === \"Set\") __velarGraphSetContains(value, value);\n else if (kind === \"WeakSet\") __velarGraphWeakSetContains(value, value);\n else __velarGraphWeakMapContains(value, value);\n return true;\n } catch { return false; }\n}\n\nfunction __velarReportOptions(value) {\n if (value === undefined) value = {};\n if (!value || typeof value !== \"object\" || __velarGraphIsList(value) || !__velarGraphIsRecord(value)\n || __velarWebErrorOwnSymbols(value).length > 0) {\n throw new TypeError(\"VelarScript error report options must be a record\");\n }\n const allowed = __velarGraphCreateSet([\"phase\", \"detail\", \"component\", \"unhandled\"]);\n const output = { phase: \"runtime\", detail: \"\", component: \"\", unhandled: false };\n for (const name of __velarGraphOwnNames(value)) {\n if (!__velarGraphSetContains(allowed, name)) throw new TypeError(\"Unknown VelarScript error report option '\" + name + \"'\");\n const descriptor = __velarGraphOwnDescriptor(value, name);\n if (!descriptor || !(\"value\" in descriptor)) throw new TypeError(\"VelarScript error report options cannot use accessors\");\n const next = descriptor.value;\n if (name === \"unhandled\") {\n if (typeof next !== \"boolean\") throw new TypeError(\"VelarScript error report unhandled must be bool\");\n output.unhandled = next;\n } else {\n if (typeof next !== \"string\") throw new TypeError(\"VelarScript error report \" + name + \" must be a string\");\n const maximum = name === \"phase\" ? 256 : name === \"component\" ? 1024 : 65536;\n if (next.length > maximum) throw new RangeError(\"VelarScript error report \" + name + \" is too long\");\n output[name] = next;\n }\n }\n return output;\n}\n\n// D90 R21: the number stamped on each observer when it is created, and the\n// order the flush runs the watch tier in -- execution order is the order the\n// author wrote the watches, and \"wrote\" spans more than one file: watches of\n// one module register as that module initializes, instances of one component\n// register as they mount, and modules register in the order the import graph\n// initializes them. Every one of those is registration order, so one counter\n// answers all three.\n//\n// It has to be application-wide, not per module. Each emitted module carries\n// its own copy of this runtime, so a module-scope counter would restart at zero\n// in the second module and the two modules' watches would compare equal. The\n// counter therefore lives on one global slot every copy reads, the same way the\n// runtime registry itself does.\nconst __velarObserverSequenceKey = Symbol.for(\"velar.web.observer.sequence.v1\");\nconst __velarObserverSequenceCell = (() => {\n const descriptor = __velarGraphOwnDescriptor(globalThis, __velarObserverSequenceKey);\n if (descriptor) {\n if (!(\"value\" in descriptor) || descriptor.enumerable || descriptor.configurable || descriptor.writable\n || !__velarGraphIsList(descriptor.value)) {\n throw new TypeError(\"VelarScript Web observer sequence ownership is invalid\");\n }\n return descriptor.value;\n }\n const cell = [0];\n __velarGraphDefine(globalThis, __velarObserverSequenceKey, {\n value: cell,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return cell;\n})();\n\nfunction __velarNextObserverSequence() {\n __velarObserverSequenceCell[0] += 1;\n return __velarObserverSequenceCell[0];\n}\n\n\n// D114 P6 item 4 (LC-C1): how many `tick()` promises are waiting on the flush\n// right now.\n//\n// The charter says an unowned flush failure surfaces at `tick()`. That was only\n// true off the browser: in a browser the runtime threw the failure from a\n// microtask, which the host error event catches and the page survives, and the\n// awaiting `tick()` resolved as though the update had been fine -- so\n// `velar/web-test` stepped silently over a broken update in the one host\n// `tick()` is documented for. An awaiting caller is a claimant: when one is\n// waiting, the failure is parked for it and it rejects; when none is, the\n// failure goes to the host as before.\n//\n// The count lives on one global slot for the reason the observer sequence does:\n// each emitted module carries its own copy of this runtime, the `tick()` that\n// waits and the flush that fails can be in two of them, and a module-scope\n// counter would let the second copy answer \"nobody is waiting\" while the first\n// one is.\nconst __velarTickWaitKey = Symbol.for(\"velar.web.tick.waiters.v1\");\nconst __velarTickWaitCell = (() => {\n const descriptor = __velarGraphOwnDescriptor(globalThis, __velarTickWaitKey);\n if (descriptor) {\n if (!(\"value\" in descriptor) || descriptor.enumerable || descriptor.configurable || descriptor.writable\n || !__velarGraphIsList(descriptor.value)) {\n throw new TypeError(\"VelarScript Web tick ownership is invalid\");\n }\n return descriptor.value;\n }\n const cell = [0];\n __velarGraphDefine(globalThis, __velarTickWaitKey, {\n value: cell,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return cell;\n})();\n\nfunction __velarTickWaiting() {\n return __velarTickWaitCell[0] > 0;\n}\n\nfunction __velarEnterTickWait() {\n __velarTickWaitCell[0] += 1;\n}\n\nfunction __velarLeaveTickWait() {\n if (__velarTickWaitCell[0] > 0) __velarTickWaitCell[0] -= 1;\n}\n" + "// D114 W/A1, as narrowed by W2: the identity a flush stamps its run counts\n// with, and the budget those runs spend. They belong to one host *task* -- but\n// the window follows work an observer started, and nothing else.\n//\n// A cycle that crosses a microtask boundary -- 'watch x: detach step()', where\n// 'step' awaits an already-resolved Promise and then writes 'x' -- is a fresh\n// flush every round, so a budget that reset per flush never saw it: two\n// observer runs, well inside 100,000, forever. Flushes chained through\n// microtasks therefore share one token, one budget and one leaders list, and\n// the macrotask sentinel below closes the window. Work that resumes after a\n// timer, an event or network I/O is a new task and opens a fresh window, which\n// is what keeps an animation that writes state every frame from being stopped.\n//\n// W2: a flush continues the open window only once an observer run inside it has\n// started asynchronous work -- a 'detach' statement, or an 'action' call, made\n// while an observer was running. Those are the two ways a synchronous observer\n// body reaches a later microtask, so they are the only ways the ring above can\n// be closed; a chain of flushes with none of them in it has no cycle to find. A\n// bulk import loop that writes a progress counter and awaits promise-only work\n// per row runs millions of observers in one uninterrupted task and is not a\n// runaway, so each of its flushes gets the fresh budget it had before W. The\n// sentinel still closes every window at the task boundary, so the animation\n// case is protected either way.\n//\n// The overrun's carried token is the same rule seen from one flush earlier: an\n// overrun schedules its continuation as a microtask, so that continuation is\n// this same task and continues these same counts by construction. It carries\n// them whether or not an observer started anything, because the continuation is\n// the overrun's own unfinished work rather than a new write.\nconst __velarFlushBudgetPerTask = 100000;\nlet __velarFlushToken = null;\nlet __velarFlushBudget = 0;\n// One-shot, consumed by the next settle: the flush an overrun scheduled\n// continues the window it was scheduled from, whatever that window recorded.\nlet __velarFlushCarried = false;\n// One sentinel is enough for a window: the first one to fire closes it, and\n// arming a second on every flush would leave a timer per flush behind.\nlet __velarTaskSentinelArmed = false;\n\n// The two facts W2 needs live on one global slot, for the same reason the\n// observer sequence above does: every emitted module carries its own copy of\n// this runtime, and the two ends of the question are in different copies. The\n// settle that asks it belongs to whichever copy created the registry -- in an\n// application that imports velar/app, that is velar/app's -- while the places\n// that answer it, a 'detach' statement's detached-task helper and an action's\n// run, are emitted into the application module. Two module-scope variables\n// would never meet.\n//\n// Slot 0 is how deep the settle currently is inside 'observer.run()'. It is a\n// depth rather than a flag because an observer created by a running one runs\n// nested. '__velarRuntime.activeObserver' cannot stand in for it: a watch body\n// runs untracked, precisely so its own reads do not become dependencies of the\n// watched expression, so the active observer is null exactly where the 'detach'\n// that closes a cycle is written.\n//\n// Slot 1 is the fact recorded on the open window: an observer run in it started\n// asynchronous work.\nconst __velarAsyncWorkKey = Symbol.for(\"velar.web.observer.asyncwork.v1\");\nconst __velarAsyncWorkCell = (() => {\n const descriptor = __velarGraphOwnDescriptor(globalThis, __velarAsyncWorkKey);\n if (descriptor) {\n if (!(\"value\" in descriptor) || descriptor.enumerable || descriptor.configurable || descriptor.writable\n || !__velarGraphIsList(descriptor.value)) {\n throw new TypeError(\"VelarScript Web observer async-work ownership is invalid\");\n }\n return descriptor.value;\n }\n const cell = [0, false];\n __velarGraphDefine(globalThis, __velarAsyncWorkKey, {\n value: cell,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return cell;\n})();\n\n// What the two compiler-owned lowering points call: the detached-task helper a\n// 'detach' statement lowers to, where a detached Promise enters the runtime,\n// and an action's run, where an action call does. Outside an observer run there\n// is nothing to record -- an action a handler or '@main' starts is the host\n// task's own work, not a ring an observer closed -- so the same unconditional\n// call is correct at both sites.\nfunction __velarNoteAsyncWork() {\n if (__velarAsyncWorkCell[0] > 0) __velarAsyncWorkCell[1] = true;\n return null;\n}\n\nfunction __velarCloseTaskWindow() {\n __velarTaskSentinelArmed = false;\n __velarFlushToken = null;\n __velarAsyncWorkCell[1] = false;\n return null;\n}\n\n// The macrotask boundary the run-count window ends at. 'setTimeout' is the one\n// scheduling operation every host this runtime supports publishes -- page,\n// worker, and the Node process a 'velar test' run drives the emitted runtime\n// in -- and it is captured at module initialization like every other ambient\n// operation here. A host that publishes none is not left without a gate: the\n// window then closes as soon as the flush chain comes to rest, which is the\n// per-flush budget this runtime had before, so the synchronous cycles stay\n// covered and only the asynchronous one goes back to being invisible.\nfunction __velarArmTaskSentinel() {\n if (__velarTaskSentinelArmed) return true;\n if (typeof __velarFoundationSetTimeout !== \"function\" || typeof __velarFoundationReflectApply !== \"function\") return false;\n __velarTaskSentinelArmed = true;\n try { __velarFoundationReflectApply(__velarFoundationSetTimeout, globalThis, [__velarCloseTaskWindow, 0]); }\n catch { __velarTaskSentinelArmed = false; return false; }\n return true;\n}\n\n// The three observers that have run most in the task window running now, kept\n// as the run counts are stamped rather than reconstructed afterwards: the queue at\n// the moment the budget runs out holds only whichever half of a cycle has not\n// just run, so it cannot name the ring on its own. An observer that has run\n// once is not a candidate, which is every observer of an ordinary flush.\nconst __velarFlushLeaders = [];\n\nfunction __velarFlushLead(observer) {\n let kept = 0;\n for (let index = 0; index < __velarFlushLeaders.length; index += 1) {\n if (__velarFlushLeaders[index] === observer) continue;\n __velarFlushLeaders[kept] = __velarFlushLeaders[index];\n kept += 1;\n }\n __velarFlushLeaders.length = kept;\n let position = kept;\n while (position > 0 && __velarFlushLeaders[position - 1].flushRuns < observer.flushRuns) {\n __velarFlushLeaders[position] = __velarFlushLeaders[position - 1];\n position -= 1;\n }\n __velarFlushLeaders[position] = observer;\n if (__velarFlushLeaders.length > 3) __velarFlushLeaders.length = 3;\n}\n\n// D90 R21: compile time no longer refuses two watches that write one state, so\n// this budget is the only gate left against a mutual-write cycle -- and a\n// report that names nobody hands the author a number with no line to go to.\n// The observers that ran most in this flush chain are the cycle; flushRuns\n// already counts exactly that, so the highest few are named. A watch's label is\n// its subject as the author spelled it, which in a write cycle is also the\n// state each watch is reacting to, and the scope it was registered in supplies\n// the component the report has always had a field for.\n//\n// Nothing here asks who wrote what. That question is gone from the language,\n// and answering it would need the write frames R21 deleted.\nfunction __velarFlushRunaway(stalled, token) {\n const ranked = [];\n const seen = __velarGraphCreateSet();\n const consider = (observer) => {\n if (observer.flushToken !== token || __velarGraphSetContains(seen, observer)) return;\n __velarGraphSetInsert(seen, observer);\n ranked[ranked.length] = observer;\n };\n // A cycle alternates, so the queue at the instant the budget ran out holds\n // only the half of the ring that has not just run. The leaders carry the\n // other half.\n for (let index = 0; index < __velarFlushLeaders.length; index += 1) consider(__velarFlushLeaders[index]);\n for (let index = 0; index < stalled.length; index += 1) consider(stalled[index]);\n __velarGraphOrder(ranked, (left, right) => right.flushRuns - left.flushRuns);\n const limit = ranked.length < 3 ? ranked.length : 3;\n let detail = \"\";\n let component = \"\";\n for (let index = 0; index < limit; index += 1) {\n const observer = ranked[index];\n const named = observer.mode === \"watch\" && typeof observer.label === \"string\" && observer.label !== \"\"\n ? \"the watch on '\" + observer.label + \"'\"\n : \"a \" + observer.mode + \" observer\";\n detail += (detail === \"\" ? \"Ran most in this task: \" : \", \") + named\n + \" (\" + observer.flushRuns + (observer.flushRuns === 1 ? \" run)\" : \" runs)\");\n if (component === \"\" && typeof observer.component === \"string\") component = observer.component;\n }\n return { detail, component };\n}\n\nfunction __velarScheduleFlush() {\n if (__velarRuntime.flushPending) return;\n __velarRuntime.flushPending = true;\n __velarEnqueue(__velarFlush);\n}\n\n// Only the observers that actually re-entered the queue during the overrun\n// belong to the runaway cycle. An observer queued once by an unrelated write\n// in the same turn is innocent, and stopping it is irreversible, so it is\n// put back for the next microtask instead.\n//\n// Every overrun must still remove something, or the requeue turns the\n// microtask chain into the freeze the budget exists to end: a cycle spread\n// across more observers than the budget can run four times over re-enters\n// none of them four times, so a fixed threshold of four stops nobody and the\n// next flush repeats it forever. Two rules make the progress unconditional.\n// The threshold falls to the highest run count actually present, so any\n// queued observer this flush chain has already run is stopped; and the token\n// is carried into the flush the overrun schedules, so run counts accumulate\n// across the chain and the observers the chain has not reached yet are a\n// pool that only shrinks.\nfunction __velarFlushOverflow(token) {\n const stalled = [];\n for (const observer of __velarGraphSetItems(__velarRuntime.domQueue)) stalled[stalled.length] = observer;\n for (const observer of __velarGraphSetItems(__velarRuntime.watchQueue)) stalled[stalled.length] = observer;\n __velarGraphSetEmpty(__velarRuntime.domQueue);\n __velarGraphSetEmpty(__velarRuntime.watchQueue);\n let threshold = 0;\n for (let index = 0; index < stalled.length; index += 1) {\n const observer = stalled[index];\n if (observer.flushToken === token && observer.flushRuns > threshold) threshold = observer.flushRuns;\n }\n if (threshold > 4) threshold = 4;\n let requeued = false;\n for (let index = 0; index < stalled.length; index += 1) {\n const observer = stalled[index];\n if (threshold > 0 && observer.flushToken === token && observer.flushRuns >= threshold) {\n if (typeof observer.stop === \"function\") observer.stop();\n else observer.stopped = true;\n continue;\n }\n if (observer.stopped) continue;\n __velarGraphSetInsert(observer.mode === \"watch\" ? __velarRuntime.watchQueue : __velarRuntime.domQueue, observer);\n requeued = true;\n }\n const runaway = __velarFlushRunaway(stalled, token);\n // The window keeps its token and its run counts -- the requeued flush is one\n // more flush of the same task, and the pool of observers it has not reached\n // yet only shrinks -- but the budget is granted again. Without that, the\n // exhausted count would trip the very next flush of the same task, and the\n // observers stopped for it would be whatever was queued at that moment: the\n // innocent ones this overrun just put back, or an unrelated later write.\n __velarFlushBudget = __velarFlushBudgetPerTask;\n __velarFlushCarried = requeued;\n __velarRuntime.report(new RangeError(\"Reactive updates cannot run more than \" + __velarFlushBudgetPerTask + \" observers in one task\"),\n { phase: \"update\", detail: runaway.detail, component: runaway.component, unhandled: true });\n if (requeued) __velarScheduleFlush();\n}\n\n// The one entry point: the microtask __velarScheduleFlush enqueues, and the\n// synchronous drain the emitted tick() performs. It used to open and close D90\n// R1-a-scope's flush-scoped writer registry around the settle; R21 deleted the\n// registry with the referee that read it, so the name is all that remains and\n// it remains because __velarEnqueue and tick() both hold it.\n//\n// D114 W/A1: it is also where the task window is closed or handed on. Both\n// entries pass through here, including tick()'s drain, so the sentinel is armed\n// once per window however the flush was reached, and a host without a timer\n// falls back to closing the window here, one flush at a time.\nfunction __velarFlush() {\n try { __velarFlushSettle(); }\n // Without a timer the window closes as soon as the chain comes to rest,\n // which is the per-flush budget this runtime had before -- except that a\n // flush already scheduled keeps it open, so an overrun's carried counts and\n // the queues a settle could not finish reach the flush that continues them.\n finally { if (!__velarArmTaskSentinel() && !__velarRuntime.flushPending) __velarCloseTaskWindow(); }\n}\n\n// Glitch-free order: every derived value and every watch settles to a fixed\n// point before a single DOM node is written, so no watch and no rendered\n// position can read a half-updated world and no corrective watch can push an\n// invalid value through the DOM first. That is D90 R1 and it is unchanged.\n//\n// D90 R21 changed the other axis. Within the settle the watches run in\n// registration order -- source order in a module, mount order across instances\n// of one component, module-initialization order across modules -- and a watch\n// that writes state is not promoted ahead of one that only observes. Whoever is\n// written first runs first, two watches writing one state both take effect in\n// that order, and a later write that clobbers an earlier one is the author's.\n//\n// Queue insertion order is not registration order and cannot stand in for it:\n// two watches on two different states, both dirtied by one action, enter the\n// queue in the order the action wrote the states. So each pass takes the queue\n// as it stands and runs it by sequence number. Watches queued by this pass are\n// picked up by the next one, in their own order.\n//\n// D114 W/A1, narrowed by W2: a flush that starts while the task window is still\n// open continues it -- the same token, so flushRuns keeps accumulating on every\n// observer, the same leaders, and the same remaining budget -- but only when an\n// observer run in that window started asynchronous work, or when the overrun\n// itself scheduled this flush. Every other flush opens a new window, which is\n// the per-flush budget this runtime had before W.\nfunction __velarFlushSettle() {\n __velarRuntime.flushPending = false;\n const carried = __velarFlushCarried;\n __velarFlushCarried = false;\n if (__velarFlushToken === null || !(carried || __velarAsyncWorkCell[1])) {\n __velarFlushToken = {};\n __velarFlushBudget = __velarFlushBudgetPerTask;\n __velarFlushLeaders.length = 0;\n __velarAsyncWorkCell[1] = false;\n }\n const token = __velarFlushToken;\n const step = (observer) => {\n __velarGraphSetRemove(observer.mode === \"watch\" ? __velarRuntime.watchQueue : __velarRuntime.domQueue, observer);\n if (observer.flushToken === token) observer.flushRuns += 1;\n else { observer.flushToken = token; observer.flushRuns = 1; }\n if (observer.flushRuns > 1) __velarFlushLead(observer);\n // The span the two lowering points ask about. It is the run itself rather\n // than the whole settle: work started by the flush's own bookkeeping is\n // not an observer's, and a nested observer created by a running one is.\n __velarAsyncWorkCell[0] += 1;\n try { observer.run(); }\n finally { __velarAsyncWorkCell[0] -= 1; }\n };\n while (__velarGraphSetCount(__velarRuntime.domQueue) || __velarGraphSetCount(__velarRuntime.watchQueue)) {\n while (true) {\n let ran = false;\n for (const observer of __velarGraphSetItems(__velarRuntime.domQueue)) {\n if (observer.mode !== \"computed\") continue;\n if ((__velarFlushBudget -= 1) < 0) { __velarFlushOverflow(token); return; }\n step(observer);\n ran = true;\n }\n if (ran) continue;\n const pending = [];\n for (const observer of __velarGraphSetItems(__velarRuntime.watchQueue)) pending[pending.length] = observer;\n __velarGraphOrder(pending, (left, right) => left.sequence - right.sequence);\n for (let index = 0; index < pending.length; index += 1) {\n const observer = pending[index];\n // A watch this pass already re-ran or stopped is no longer queued; the\n // snapshot is a plan, and the queue is what says whether it still owes\n // a run.\n if (observer.stopped || !__velarGraphSetContains(__velarRuntime.watchQueue, observer)) continue;\n if ((__velarFlushBudget -= 1) < 0) { __velarFlushOverflow(token); return; }\n step(observer);\n ran = true;\n }\n if (!ran) break;\n }\n for (const observer of __velarGraphSetItems(__velarRuntime.domQueue)) {\n if (observer.mode === \"computed\") break;\n if ((__velarFlushBudget -= 1) < 0) { __velarFlushOverflow(token); return; }\n step(observer);\n }\n }\n if (__velarGraphSetCount(__velarRuntime.domQueue) || __velarGraphSetCount(__velarRuntime.watchQueue)) __velarScheduleFlush();\n}\n\n" + "function __velarCreateRuntime() {\n const runtime = Object.create(null);\n const domQueue = Object.freeze(__velarGraphCreateSet());\n const watchQueue = Object.freeze(__velarGraphCreateSet());\n const errorHandlers = Object.freeze(__velarGraphCreateSet());\n const unhandledFailures = Object.freeze(__velarGraphCreateSet());\n const actionFailures = Object.freeze(__velarGraphCreateWeakSet());\n const lookSources = Object.freeze(__velarGraphCreateWeakMap());\n const classSources = Object.freeze(__velarGraphCreateWeakMap());\n const dependencies = Object.freeze(__velarGraphCreateWeakMap());\n const rawToProxy = Object.freeze(__velarGraphCreateWeakMap());\n const proxyToRaw = Object.freeze(__velarGraphCreateWeakMap());\n const versions = Object.freeze(__velarGraphCreateWeakMap());\n const parents = Object.freeze(__velarGraphCreateWeakMap());\n const subscriptionStops = __velarGraphCreateWeakMap();\n const collectionBrands = __velarGraphCreateWeakMap();\n const iterateKey = Symbol.for(\"velar.reactive.iterate.v1\");\n const structureKey = Symbol.for(\"velar.reactive.structure.v1\");\n const deepKey = Symbol.for(\"velar.reactive.deep.v1\");\n let lookImplementation = null;\n const toRaw = (value) => {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) return value;\n return __velarGraphWeakMapRead(proxyToRaw, value) ?? value;\n };\n const trackSubscribers = (subscribers) => {\n const observer = runtime.activeObserver;\n if (!observer || observer.stopped) return;\n __velarGraphSetInsert(subscribers, observer);\n __velarGraphSetInsert(observer.dependencies, subscribers);\n };\n const runTracked = (observer, read) => {\n const previousDependencies = observer.dependencies;\n // Every run needs a second dependency set to diff against, and an observer\n // that re-runs thousands of times per second would otherwise allocate one\n // per run. The emptied previous set is kept as the next run's buffer.\n const spare = observer.spareDependencies;\n observer.spareDependencies = null;\n observer.dependencies = spare ?? __velarGraphCreateSet();\n const previousObserver = runtime.activeObserver;\n runtime.activeObserver = observer;\n try { return read(); }\n finally {\n runtime.activeObserver = previousObserver;\n for (const subscribers of __velarGraphSetItems(previousDependencies)) {\n if (__velarGraphSetContains(observer.dependencies, subscribers)) continue;\n // A stop fires exactly when an actual removal empties the set. Firing\n // on an already-empty set would let two detaching computeds whose\n // cleanups have not yet emptied their dependency sets re-trigger each\n // other without bound.\n if (__velarGraphSetRemove(subscribers, observer) && __velarGraphSetCount(subscribers) === 0) {\n const stop = __velarGraphWeakMapRead(subscriptionStops, subscribers);\n if (stop) stop();\n }\n }\n __velarGraphSetEmpty(previousDependencies);\n observer.spareDependencies = previousDependencies;\n }\n };\n const cleanupObserver = (observer) => {\n for (const subscribers of __velarGraphSetItems(observer.dependencies)) {\n if (__velarGraphSetRemove(subscribers, observer) && __velarGraphSetCount(subscribers) === 0) {\n const stop = __velarGraphWeakMapRead(subscriptionStops, subscribers);\n if (stop) stop();\n }\n }\n __velarGraphSetEmpty(observer.dependencies);\n };\n const track = (target, key) => {\n target = toRaw(target);\n if ((typeof target !== \"object\" && typeof target !== \"function\") || target === null) return;\n let byKey = __velarGraphWeakMapRead(dependencies, target);\n if (!byKey) { byKey = __velarGraphCreateMap(); __velarGraphWeakMapWrite(dependencies, target, byKey); }\n let subscribers = __velarGraphMapRead(byKey, key);\n if (!subscribers) {\n subscribers = __velarGraphCreateSet();\n __velarGraphMapWrite(byKey, key, subscribers);\n const ownedSubscribers = subscribers;\n __velarGraphWeakMapWrite(subscriptionStops, subscribers, () => {\n if (__velarGraphMapRead(byKey, key) !== ownedSubscribers) return;\n __velarGraphMapRemove(byKey, key);\n if (__velarGraphMapCount(byKey) === 0) __velarGraphWeakMapRemove(dependencies, target);\n });\n }\n trackSubscribers(subscribers);\n };\n // P2b-9: the path a write travelled, in the words the author would recognise.\n // Only the shape is named -- never a value -- because this reaches a report.\n // The kind travels beside the phrase rather than being read back out of it:\n // the reader of this is the runaway report, and it decides which remedy to\n // give from the kind, not by looking inside a sentence.\n const describeSubject = (target, key) => {\n const container = __velarGraphIsList(target) ? \"List\" : __velarGraphIsRecord(target) ? \"record\" : \"collection\";\n if (key === iterateKey || key === structureKey) return { kind: \"collection\", text: \"the size or contents of a \" + container };\n if (key === deepKey) return { kind: \"value\", text: \"a nested value of a \" + container };\n if (typeof key === \"number\") return { kind: \"value\", text: \"element \" + key + \" of a \" + container };\n if (typeof key === \"string\") return { kind: \"value\", text: \"field '\" + key + \"'\" };\n return { kind: \"value\", text: \"a tracked value\" };\n };\n const notify = (target, key) => {\n const byKey = __velarGraphWeakMapRead(dependencies, target);\n const subscribers = byKey ? __velarGraphMapRead(byKey, key) : null;\n if (subscribers) for (const observer of __velarGraphSetItems(subscribers)) {\n // A write that lands while its own reader is still running is the\n // self-invalidating shape, and it is the only one whose path is worth\n // describing -- so the description is built there and nowhere else, which\n // keeps every ordinary write to one property read on this path. The\n // observer's own budget owns the report; this only tells it what to name.\n if (observer.running) {\n const subject = describeSubject(target, key);\n observer.selfInvalidationSubject = subject.text;\n observer.selfInvalidationKind = subject.kind;\n }\n observer.notify();\n }\n };\n const bump = (target) => {\n __velarGraphWeakMapWrite(versions, target, (__velarGraphWeakMapRead(versions, target) ?? 0) + 1);\n };\n const trigger = (target, key, iterate = false, structure = false, indexFrom = null, allKeys = false) => {\n target = toRaw(target);\n if ((typeof target !== \"object\" && typeof target !== \"function\") || target === null) return;\n bump(target);\n notify(target, key);\n if (allKeys || indexFrom !== null) {\n const byKey = __velarGraphWeakMapRead(dependencies, target);\n if (byKey) for (const candidate of __velarGraphMapKeyItems(byKey)) {\n if (candidate === key) continue;\n if (allKeys || (typeof candidate === \"number\" && candidate >= indexFrom)) notify(target, candidate);\n }\n }\n if (iterate) notify(target, iterateKey);\n if (structure) notify(target, structureKey);\n notify(target, deepKey);\n const owners = __velarGraphWeakMapRead(parents, target);\n // A mutation of an unowned value -- the overwhelmingly common case -- must\n // not pay for the cycle bookkeeping that only an ancestor walk needs.\n if (!owners) return;\n const visited = __velarGraphCreateSet();\n __velarGraphSetInsert(visited, target);\n const bubble = (current) => {\n if (__velarGraphSetContains(visited, current)) return;\n __velarGraphSetInsert(visited, current);\n bump(current);\n notify(current, deepKey);\n const next = __velarGraphWeakMapRead(parents, current);\n if (next) for (const owner of __velarGraphSetItems(next)) bubble(owner);\n };\n for (const owner of __velarGraphSetItems(owners)) bubble(owner);\n };\n const link = (child, parent) => {\n if (child === null || (typeof child !== \"object\" && typeof child !== \"function\")) return;\n linkOwner(toRaw(child), parent, true);\n };\n // 'structural' separates a slot being filled from a slot merely being read.\n // A read proves the child is in the parent right now; only a write adds an\n // occurrence, and only a write can create the duplicate the running count\n // cannot see for itself.\n const linkOwner = (child, parent, structural = false) => {\n parent = toRaw(parent);\n if (parent === null || (typeof parent !== \"object\" && typeof parent !== \"function\") || child === parent) return;\n let owners = __velarGraphWeakMapRead(parents, child);\n if (!owners) { owners = __velarGraphCreateSet(); __velarGraphWeakMapWrite(parents, child, owners); }\n const known = __velarGraphSetContains(owners, parent);\n __velarGraphSetInsert(owners, parent);\n const counts = __velarGraphWeakMapRead(containment, parent);\n if (!counts) return;\n if (structural && known) { __velarGraphWeakMapRemove(containment, parent); return; }\n if ((__velarGraphMapRead(counts, child) ?? 0) < 1) __velarGraphMapWrite(counts, child, 1);\n };\n // Removing the last owner of a value detaches everything only that value\n // owned. Without the cascade, replacing a state root leaves every surviving\n // descendant pointing at the dead root: the root stays strongly reachable\n // and each later deep mutation walks one more generation.\n const release = (root) => {\n const pending = [root];\n let index = 0;\n while (index < pending.length) {\n const current = pending[index];\n index += 1;\n forEachOwnedValue(current, (value) => {\n const owners = __velarGraphWeakMapRead(parents, value);\n if (!owners || !__velarGraphSetContains(owners, current)) return;\n __velarGraphSetRemove(owners, current);\n if (__velarGraphSetCount(owners) > 0) return;\n __velarGraphWeakMapRemove(parents, value);\n pending[pending.length] = value;\n });\n }\n };\n const unlink = (child, parent) => {\n child = toRaw(child);\n parent = toRaw(parent);\n const owners = child !== null && (typeof child === \"object\" || typeof child === \"function\")\n ? __velarGraphWeakMapRead(parents, child)\n : null;\n if (!owners) return;\n __velarGraphSetRemove(owners, parent);\n if (__velarGraphSetCount(owners) > 0) return;\n __velarGraphWeakMapRemove(parents, child);\n release(child);\n };\n // Map and Set membership is decided once per value and remembered: the only\n // cross-realm test JavaScript offers is invoking a prototype accessor and\n // catching, and a record write must not pay two thrown exceptions per field.\n const collectionBrand = (value) => {\n const known = __velarGraphWeakMapRead(collectionBrands, value);\n if (known !== undefined) return known;\n let brand = 0;\n try { __velarGraphMapCount(value); brand = 1; }\n catch {\n try { __velarGraphSetCount(value); brand = 2; }\n catch { brand = 0; }\n }\n __velarGraphWeakMapWrite(collectionBrands, value, brand);\n return brand;\n };\n const forEachOwnedValue = (parent, visit) => {\n if (parent === null || (typeof parent !== \"object\" && typeof parent !== \"function\")) return;\n if (__velarGraphIsList(parent)) {\n for (let index = 0; index < parent.length; index += 1) {\n const value = toRaw(__velarGraphOwnDescriptor(parent, index)?.value);\n if (value !== null && (typeof value === \"object\" || typeof value === \"function\")) visit(value);\n }\n return;\n }\n const brand = collectionBrand(parent);\n if (brand === 1) {\n for (const value of __velarGraphMapItems(parent)) {\n const owned = toRaw(value);\n if (owned !== null && (typeof owned === \"object\" || typeof owned === \"function\")) visit(owned);\n }\n // A Map key is linked to its Map exactly like a value, so releasing the\n // Map has to release object keys too.\n for (const value of __velarGraphMapKeyItems(parent)) {\n const owned = toRaw(value);\n if (owned !== null && (typeof owned === \"object\" || typeof owned === \"function\")) visit(owned);\n }\n return;\n }\n if (brand === 2) {\n for (const value of __velarGraphSetItems(parent)) {\n const owned = toRaw(value);\n if (owned !== null && (typeof owned === \"object\" || typeof owned === \"function\")) visit(owned);\n }\n return;\n }\n if (typeof parent !== \"object\") return;\n for (const name of __velarGraphOwnNames(parent)) {\n const descriptor = __velarGraphOwnDescriptor(parent, name);\n if (!descriptor || !(\"value\" in descriptor)) continue;\n const value = toRaw(descriptor.value);\n if (value !== null && (typeof value === \"object\" || typeof value === \"function\")) visit(value);\n }\n };\n // Containment used to be re-derived by scanning the whole container on every\n // element write, which made one assignment into a rendered List cost O(list\n // length). The occurrence index answers the same question -- does the parent\n // still reference this child anywhere? -- in constant time: it is built once\n // from the container's real contents and then maintained by the same link and\n // release calls that change them.\n const containment = __velarGraphCreateWeakMap();\n const countOccurrence = (counts, value) => {\n value = toRaw(value);\n if (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) return;\n __velarGraphMapWrite(counts, value, (__velarGraphMapRead(counts, value) ?? 0) + 1);\n };\n // Mirrors exactly what the old scan looked at, Map keys included as owned\n // values are, so the index cannot answer a question the scan answered\n // differently.\n const buildContainment = (parent) => {\n const counts = __velarGraphCreateMap();\n if (__velarGraphIsList(parent)) {\n for (let index = 0; index < parent.length; index += 1) countOccurrence(counts, __velarGraphOwnDescriptor(parent, index)?.value);\n return counts;\n }\n const brand = collectionBrand(parent);\n if (brand === 1) {\n for (const value of __velarGraphMapItems(parent)) countOccurrence(counts, value);\n return counts;\n }\n if (brand === 2) {\n for (const value of __velarGraphSetItems(parent)) countOccurrence(counts, value);\n return counts;\n }\n if (!parent || typeof parent !== \"object\") return counts;\n for (const name of __velarGraphOwnNames(parent)) {\n const descriptor = __velarGraphOwnDescriptor(parent, name);\n if (descriptor && \"value\" in descriptor) countOccurrence(counts, descriptor.value);\n }\n return counts;\n };\n // The one guard every detach path shares: a primitive was never linked, and\n // an object with no owners has nothing to release, so neither may reach the\n // containment bookkeeping.\n const releaseChild = (parent, child) => {\n if (child === null || (typeof child !== \"object\" && typeof child !== \"function\")\n || !__velarGraphWeakMapContains(parents, child)) return;\n parent = toRaw(parent);\n if (parent === null || (typeof parent !== \"object\" && typeof parent !== \"function\")) return;\n child = toRaw(child);\n // A freshly built index already reflects the slot that was just cleared;\n // a maintained one still counts it, so only that one takes the decrement.\n let counts = __velarGraphWeakMapRead(containment, parent);\n let remaining;\n if (counts) remaining = (__velarGraphMapRead(counts, child) ?? 0) - 1;\n else {\n counts = buildContainment(parent);\n __velarGraphWeakMapWrite(containment, parent, counts);\n remaining = __velarGraphMapRead(counts, child) ?? 0;\n }\n if (remaining > 0) { __velarGraphMapWrite(counts, child, remaining); return; }\n __velarGraphMapRemove(counts, child);\n unlink(child, parent);\n };\n // The registry operation stays exactly two parameters wide; 'structural'\n // belongs to the internal call, which knows whether a slot is being filled or\n // merely read, and every caller outside this file fills one.\n const reactive = (value, parent = null) => reactiveValue(value, parent, true);\n const reactiveValue = (value, parent, structural) => {\n if (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) return value;\n value = toRaw(value);\n if (parent !== null) linkOwner(value, parent, structural);\n if (typeof value !== \"object\" || __velarGraphIsList(value) || !__velarGraphIsExtensible(value)) return value;\n if (!__velarGraphIsRecord(value)) {\n // D114 P6 item 7 (ST-U4): the one place an unwrapped class instance is\n // handed back out of a state graph. In a development host its fields are\n // observed from here so a `computed` or `watch` that reads one is told\n // the read can never update; in a production build the detector's hooks\n // (stale-class.js) are null and this is one already-false test on the hot\n // path. The owner is handed over rather than the cell's name, because the\n // report names the path from the cell down to the instance.\n if (__velarStaleClassHooks !== null && parent !== null) __velarObserveClassFields(value, parent);\n return value;\n }\n let proxy = __velarGraphWeakMapRead(rawToProxy, value);\n if (proxy) return proxy;\n proxy = new __velarGraphNativeProxy(value, {\n get(target, key) {\n track(target, key);\n return reactiveValue(__velarGraphGet(target, key, target), target, false);\n },\n set(target, key, next) {\n next = toRaw(next);\n const present = __velarGraphHas(target, key);\n const previous = toRaw(__velarGraphGet(target, key, target));\n // Creating an absent key is a structural change even when the value\n // written equals the absent key's 'undefined' reading.\n const changed = !present || !__velarGraphSame(previous, next);\n const written = __velarGraphSet(target, key, next, target);\n if (!written || !changed) return written;\n link(next, target);\n releaseChild(target, previous);\n trigger(target, key, true, !present);\n return true;\n },\n has(target, key) { track(target, key); return __velarGraphHas(target, key); },\n deleteProperty(target, key) {\n if (!__velarGraphHas(target, key)) return true;\n const previous = toRaw(__velarGraphGet(target, key, target));\n const deleted = __velarGraphDelete(target, key);\n if (deleted) {\n releaseChild(target, previous);\n trigger(target, key, true, true);\n }\n return deleted;\n },\n });\n __velarGraphWeakMapWrite(rawToProxy, value, proxy);\n __velarGraphWeakMapWrite(proxyToRaw, proxy, value);\n return proxy;\n };\n const trackDeep = (value) => { value = toRaw(value); track(value, deepKey); return value; };\n const versionOf = (value) => {\n value = toRaw(value);\n return value && (typeof value === \"object\" || typeof value === \"function\")\n ? __velarGraphWeakMapRead(versions, value) ?? 0\n : 0;\n };\n const collectionRead = (value, key, child) => {\n value = toRaw(value);\n track(value, key);\n // Only containers already connected to a state graph own children read\n // through them. Fresh derived Lists (filter/map/etc.) stay ephemeral and\n // cannot become strongly retained parents of every item merely by being\n // iterated during rendering.\n return reactiveValue(child, __velarGraphWeakMapContains(parents, value) ? value : null, false);\n };\n const collectionTrigger = (value, key, iterate = true, structure = false, indexFrom = null, allKeys = false) => trigger(toRaw(value), key, iterate, structure, indexFrom, allKeys);\n const collectionUnlink = (value, child) => {\n releaseChild(toRaw(value), toRaw(child));\n };\n const computed = (read) => {\n if (typeof read !== \"function\") throw new TypeError(\"computed requires a function\");\n let dirty = true;\n let evaluating = false;\n let recursed = false;\n let initialized = false;\n let value;\n let failed = false;\n let failure;\n const subscribers = __velarGraphCreateSet();\n const notifyDependents = (skip = null) => {\n for (const dependent of __velarGraphSetItems(subscribers)) if (dependent !== skip) dependent.notify();\n };\n const invalidateComputedDependents = () => {\n for (const dependent of __velarGraphSetItems(subscribers)) {\n if (dependent.mode === \"computed\") dependent.notify();\n }\n };\n const observer = {\n mode: \"computed\",\n stopped: false,\n running: false,\n selfInvalidations: 0,\n // P2b-9: filled in by the graph's notify when a write lands while this\n // value is still being derived, so the runaway report names the path.\n selfInvalidationSubject: \"\",\n selfInvalidationKind: \"\",\n dependencies: __velarGraphCreateSet(),\n notify() {\n // Stopping is shared discipline with DOM and watch observers: a flush\n // overflow marks queued computed observers stopped, and a stopped\n // observer must go inert instead of re-entering the storm on the next\n // write.\n if (observer.stopped) return;\n // The 100 self-invalidation cap covers computed observers too. A\n // computed whose own turn (evaluation plus dependent notification)\n // keeps invalidating it is stopped with the same owned report a\n // render or watch observer gets, instead of running to the whole\n // flush budget.\n if (observer.running) {\n observer.selfInvalidations += 1;\n if (observer.selfInvalidations > 100) {\n observer.stopped = true;\n cleanupObserver(observer);\n reportUntracked(new RangeError(\"A computed value cannot invalidate itself more than 100 times\"\n + (observer.selfInvalidationSubject ? \": it writes \" + observer.selfInvalidationSubject + \" while reading it\" : \"\")));\n return;\n }\n } else {\n observer.selfInvalidations = 0;\n }\n if (dirty) return;\n dirty = true;\n if (__velarGraphSetCount(subscribers) === 0) {\n cleanupObserver(observer);\n return;\n }\n schedule(observer);\n // A downstream computed must become dirty immediately so a same-turn\n // read cannot observe its cached result while an upstream dependency\n // is already stale. DOM and watch observers still wait for evaluation\n // to prove that the public result actually changed.\n invalidateComputedDependents();\n },\n run() {\n if (observer.stopped || !dirty || __velarGraphSetCount(subscribers) === 0) return;\n observer.running = true;\n try {\n if (evaluate(false)) notifyDependents();\n } finally { observer.running = false; }\n },\n };\n const detach = () => {\n cleanupObserver(observer);\n dirty = true;\n };\n __velarGraphWeakMapWrite(subscriptionStops, subscribers, detach);\n const evaluate = (throwFailure) => {\n if (evaluating) {\n recursed = true;\n throw new RangeError(\"A computed value cannot read itself recursively\");\n }\n const previous = value;\n const previouslyFailed = failed;\n const previousFailure = failure;\n const hadValue = initialized;\n evaluating = true;\n recursed = false;\n failed = false;\n failure = undefined;\n try { value = runTracked(observer, read); }\n catch (error) { failed = true; failure = error; }\n finally {\n evaluating = false;\n initialized = true;\n dirty = false;\n }\n // A computed that failed because its own recursion guard tripped sits on\n // a dependency cycle. The failure is cached and served, but the cyclic\n // edges must not persist: two failed computeds that keep notifying each\n // other would otherwise ping-pong the next flush into the whole-flush\n // budget. Detaching unwinds the cycle (a peer whose last subscriber\n // leaves detaches with it) and a later read simply re-attempts.\n if (failed && recursed) detach();\n else if (__velarGraphSetCount(subscribers) === 0) detach();\n recursed = false;\n const changed = !hadValue || previouslyFailed !== failed || (failed ? previousFailure !== failure : !__velarGraphSame(previous, value));\n if (throwFailure && failed) throw failure;\n return changed;\n };\n const access = () => {\n const consumer = runtime.activeObserver;\n if (consumer !== observer) trackSubscribers(subscribers);\n if (dirty && !observer.stopped) {\n // A cyclic read re-enters access while the outer evaluation is still\n // running, so the running span is restored, never cleared.\n const wasRunning = observer.running;\n observer.running = true;\n try {\n const changed = evaluate(false);\n if (changed && initialized) notifyDependents(consumer);\n } finally { observer.running = wasRunning; }\n }\n if (failed) throw failure;\n return value;\n };\n return __velarGraphFreeze(access);\n };\n // The loud channel for a failure nothing owns.\n //\n // D114 P6 item 4 (LC-C1) and F9-web (WB-C1): every `tick()` waiting on the\n // flush is a claimant, in every host. A caller waiting on the flush is the\n // one place a failure nobody handled can be delivered *to somebody*, so the\n // flush's first unowned failure is parked and every pending `tick()` rejects\n // with it -- the promise that awaiting `tick()` cannot step over a broken\n // update is one the second concurrent awaiter has to keep too.\n //\n // Everything else goes to the host, and there is no second channel beside a\n // claimant: a later failure in the same flush, whose claimants are already\n // spoken for, and every failure raised with nobody waiting at all. In a\n // browser that is the microtask throw the host error event catches and the\n // page survives; in a non-browser host (a headless 'velar test' process, a\n // worker) the same throw would terminate the process, which the runtime\n // boundary forbids, so there it is traced to the report channel. Nothing is\n // parked for a `tick()` that is not yet waiting, because a caller who arrives\n // after the flush was never waiting on it.\n const escalate = (error) => {\n if (__velarTickWaiting() && __velarGraphSetCount(unhandledFailures) === 0) {\n __velarGraphSetInsert(unhandledFailures, error);\n return;\n }\n if (__velarDomDocument !== null) {\n __velarEnqueue(() => { throw error; });\n return;\n }\n __velarFoundationTrace(error);\n };\n const report = (value, options) => {\n const error = __velarNormalizeError(value);\n const checked = __velarReportOptions(options);\n const timestamp = __velarNow();\n if (!__velarWebErrorFinite(timestamp)) throw new TypeError(\"The browser returned an invalid error timestamp\");\n const errorReport = __velarWebErrorFreeze({\n error,\n phase: checked.phase,\n detail: checked.detail,\n component: checked.component,\n timestamp,\n });\n let handled = false;\n for (const handler of __velarGraphSetItems(errorHandlers)) {\n handled = true;\n try {\n const result = handler(errorReport);\n __velarObservePromise(result, (failure) => escalate(__velarNormalizeError(failure)));\n } catch (failure) { escalate(__velarNormalizeError(failure)); }\n }\n if (checked.unhandled && !handled) escalate(error);\n return errorReport;\n };\n // A report raised from inside a tracked evaluation (the computed cap) must\n // not let handler reads become dependencies of the failing observer.\n const reportUntracked = (error) => {\n const previousObserver = runtime.activeObserver;\n runtime.activeObserver = null;\n try { report(error, { phase: \"update\", detail: \"\", component: \"\", unhandled: true }); }\n finally { runtime.activeObserver = previousObserver; }\n };\n // The queue insert stays on the registry -- computed observers are created by\n // whichever module stamped it first (velar/app under ESM import order, or the\n // application prelude) and must schedule correctly whichever that was -- but\n // the drain it calls is the module-scope one below, and there is now exactly\n // one of those. A queue that outgrows its bound is the flush budget's failure\n // to own, not an exception thrown out of the assignment that happened to\n // cross the line: throwing here left the writing cell's subscriber walk half\n // finished, with the remaining observers subscribed and never notified again.\n const schedule = (observer) => {\n __velarGraphSetInsert(observer.mode === \"watch\" ? watchQueue : domQueue, observer);\n __velarScheduleFlush();\n };\n const applyLook = (...arguments_) => {\n if (!lookImplementation) throw new TypeError(\"Link Look requires the VelarScript Web runtime\");\n return lookImplementation(...arguments_);\n };\n const installLook = (implementation) => {\n if (typeof implementation !== \"function\") throw new TypeError(\"VelarScript Look integration requires a function\");\n lookImplementation ??= implementation;\n return null;\n };\n const fields = {\n version: \"0.12\", domQueue, watchQueue, flushPending: false, activeObserver: null, errorHandlers,\n actionFailures, unhandledFailures, lookSources, classSources, dependencies, rawToProxy, proxyToRaw, versions, parents,\n toRaw, reactive, track, trackDeep, trigger, versionOf, collectionRead, collectionTrigger, collectionUnlink,\n trackSubscribers, runTracked, cleanupObserver, computed,\n schedule, report, applyLook, installLook,\n };\n for (const name of __velarRuntimeFields) Object.defineProperty(runtime, name, {\n value: fields[name],\n enumerable: false,\n configurable: false,\n writable: name === \"flushPending\" || name === \"activeObserver\",\n });\n return Object.preventExtensions(runtime);\n}\n\nfunction __velarRequireRuntime(value) {\n if (!value || typeof value !== \"object\") throw new TypeError(\"VelarScript Web runtime ownership is invalid\");\n // The schema comparison comes first, ahead of ownership and the field roster:\n // a schema bump normally changes the roster too, so leaving it last reported\n // \"fields are invalid\" and never named the one fact that identifies the\n // cause. The version is read through its descriptor rather than the property\n // so an unvalidated object cannot answer it with a getter.\n const __velarVersionDescriptor = Object.getOwnPropertyDescriptor(value, \"version\");\n const __velarVersion = __velarVersionDescriptor && \"value\" in __velarVersionDescriptor ? __velarVersionDescriptor.value : undefined;\n if (__velarVersion !== \"0.12\") {\n throw new TypeError(\"VelarScript Web runtime schema \" + (typeof __velarVersion === \"string\" ? __velarVersion : \"(unknown)\") + \" does not match this module's schema 0.12; one build mixed two generations of @velarscript/* — run 'npm ls @velarscript/compiler' and pin one version\");\n }\n if (Object.getPrototypeOf(value) !== null || Object.isExtensible(value)\n || Object.getOwnPropertySymbols(value).length > 0) throw new TypeError(\"VelarScript Web runtime ownership is invalid\");\n const names = Object.getOwnPropertyNames(value);\n if (names.length !== __velarRuntimeFields.length || __velarRuntimeFields.some((name) => !names.includes(name))) {\n throw new TypeError(\"VelarScript Web runtime fields are invalid\");\n }\n for (const name of __velarRuntimeFields) {\n const descriptor = Object.getOwnPropertyDescriptor(value, name);\n const mutable = name === \"flushPending\" || name === \"activeObserver\";\n if (!descriptor || !(\"value\" in descriptor) || descriptor.enumerable || descriptor.configurable || descriptor.writable !== mutable) {\n throw new TypeError(\"VelarScript Web runtime field '\" + name + \"' is invalid\");\n }\n }\n if (!__velarRuntimeCollection(value.domQueue, \"Set\") || !__velarRuntimeCollection(value.watchQueue, \"Set\")\n || typeof value.flushPending !== \"boolean\" || (value.activeObserver !== null && typeof value.activeObserver !== \"object\")\n || !__velarRuntimeCollection(value.errorHandlers, \"Set\") || !__velarRuntimeCollection(value.actionFailures, \"WeakSet\")\n || !__velarRuntimeCollection(value.unhandledFailures, \"Set\")\n || !__velarRuntimeCollection(value.lookSources, \"WeakMap\") || !__velarRuntimeCollection(value.classSources, \"WeakMap\")\n || !__velarRuntimeCollection(value.dependencies, \"WeakMap\") || !__velarRuntimeCollection(value.rawToProxy, \"WeakMap\")\n || !__velarRuntimeCollection(value.proxyToRaw, \"WeakMap\") || !__velarRuntimeCollection(value.versions, \"WeakMap\")\n || !__velarRuntimeCollection(value.parents, \"WeakMap\")\n || typeof value.toRaw !== \"function\" || typeof value.reactive !== \"function\" || typeof value.track !== \"function\"\n || typeof value.trackDeep !== \"function\" || typeof value.trigger !== \"function\" || typeof value.versionOf !== \"function\"\n || typeof value.collectionRead !== \"function\" || typeof value.collectionTrigger !== \"function\" || typeof value.collectionUnlink !== \"function\"\n || typeof value.trackSubscribers !== \"function\" || typeof value.runTracked !== \"function\"\n || typeof value.cleanupObserver !== \"function\" || typeof value.computed !== \"function\" || typeof value.schedule !== \"function\"\n || typeof value.report !== \"function\" || typeof value.applyLook !== \"function\" || typeof value.installLook !== \"function\") {\n throw new TypeError(\"VelarScript Web runtime values are invalid\");\n }\n return value;\n}\n\nconst __velarRuntime = (() => {\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, __velarRuntimeKey);\n if (descriptor) {\n if (!(\"value\" in descriptor) || descriptor.enumerable || descriptor.configurable || descriptor.writable) {\n throw new TypeError(\"VelarScript Web runtime registry ownership is invalid\");\n }\n return __velarRequireRuntime(descriptor.value);\n }\n const runtime = __velarCreateRuntime();\n Object.defineProperty(globalThis, __velarRuntimeKey, {\n value: runtime,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return runtime;\n})();\n" + "/**\n * D114 P6 item 7 (ST-U4), completed by F9-web (WB-I3 / WB-I4 / WB-U4): the\n * development host's detector for a `computed`, a `watch` subject or a DOM\n * interpolation that reads a field of a class instance held in `state`.\n *\n * web-api's rule stands and is not changing: classes are never wrapped, because\n * a proxy over an instance would change what `self` is and what identity means.\n * The consequence had no name: `state box = Counter()` with\n * `computed shown = box.value` compiles clean, renders once, and never updates\n * again, because `box.bump()` writes a field nothing is watching. Only\n * replacing the cell publishes. `<p>{box.value}</p>` is the same fact one step\n * closer to the page -- the text node is written once and never again -- so the\n * three readers are one rule and earn one sentence.\n *\n * So the instance's own data fields are observed while a development host is\n * present -- the same trade the frozen-read detector makes, in the same\n * channel. The instance is not replaced: an accessor pair over the value it\n * already held keeps its identity, its prototype, and what `self` means inside\n * its own methods, which a proxy could not. A production build publishes no\n * hooks, so none of this exists there.\n *\n * Three things this file owns that the report did not have before:\n *\n * - **What to write instead (WB-I3).** The remedy used to be spelled\n * `cell = Class(...)` whatever shape the value was in, and the walk that\n * finds the cell climbs through records and Lists -- so `state holder =\n * {box: Box()}` was told to write `holder = Box(...)`, which does not\n * compile. The walk now carries the path it climbed, and the remedy is\n * written for the shape that actually holds the instance.\n * - **When the read has actually gone stale (WB-I4).** A `const` field is one\n * nothing can change, so a read of it can never go stale and the sentence\n * \"changing 'value' publishes nothing\" describes something that will not\n * happen. The emitted class makes `const` and `let` the same ordinary data\n * property, so the runtime cannot tell them apart by looking -- but it does\n * not have to: the report is made when the field is **written** under a\n * reader that cannot see it, which is the frozen-read detector's own rule\n * (\"a report is made when one of them later changes -- never when it is\n * read\"). A field nothing writes is never reported, and `const` is exactly\n * the case where nothing can.\n * - **The member the line reads (WB-U4).** `get shown()` backed by a field\n * `inner` was reported as `inner`, a name the author's line never contains\n * and may not know exists. A read that enters through the class's own\n * getter or method records that member for as long as it runs, so the\n * report can name both.\n */\nconst __velarStaleClassHooks = (() => {\n const hooks = globalThis.__velarDevelopmentHooks;\n return hooks && typeof hooks.frozenRead === \"function\" ? hooks : null;\n})();\nconst __velarStaleClassSeen = __velarStaleClassHooks === null ? null : __velarGraphCreateWeakSet();\nconst __velarStaleClassWrapped = __velarStaleClassHooks === null ? null : __velarGraphCreateWeakSet();\nconst __velarStaleClassReported = __velarStaleClassHooks === null ? null : __velarGraphCreateSet();\n// The class member a read is currently inside, or null when the reading line\n// names the field itself. Outermost wins: a method that reads through a getter\n// of its own is still entered as the method the author wrote.\nlet __velarStaleClassMember = null;\n\n/** The written class name, or null where the value is not an instance of one. */\nfunction __velarStaleClassName(instance) {\n const prototype = __velarGraphPrototype(instance);\n if (prototype === null) return null;\n const constructor = __velarGraphOwnDescriptor(prototype, \"constructor\");\n const value = constructor && \"value\" in constructor ? constructor.value : null;\n if (typeof value !== \"function\") return null;\n const named = __velarGraphOwnDescriptor(value, \"name\");\n const name = named && \"value\" in named ? named.value : null;\n return typeof name === \"string\" && name !== \"\" ? name : null;\n}\n\n/**\n * Which slot of `owner` holds `child`: a record field, a List index, or null\n * where the owner is a shape whose slot has no spelling an author can write --\n * a `Map`, a `Set`, or an owner that no longer references the child at all. A\n * slot that cannot be named is a remedy that cannot be written, and the report\n * says so rather than inventing one.\n */\nfunction __velarStaleClassSlot(owner, child) {\n if (owner === null || typeof owner !== \"object\") return null;\n if (__velarGraphIsList(owner)) {\n for (let index = 0; index < owner.length; index += 1) {\n const descriptor = __velarGraphOwnDescriptor(owner, index);\n if (descriptor && \"value\" in descriptor && descriptor.value === child) return { index, field: null };\n }\n return null;\n }\n if (!__velarGraphIsRecord(owner)) return null;\n for (const name of __velarGraphOwnNames(owner)) {\n const descriptor = __velarGraphOwnDescriptor(owner, name);\n if (descriptor && \"value\" in descriptor && descriptor.value === child) return { index: -1, field: name };\n }\n return null;\n}\n\n/**\n * The `state` cell a value was reached through and the path from that cell down\n * to it, or null when no cell is above it. The walk is bounded and\n * breadth-first over the same ownership graph a deep change bubbles up, so a\n * class instance held one or two records below a state cell is found -- and a\n * value that is not under one is not reported about at all, because the report\n * has to name the place whose replacement publishes.\n *\n * `steps` is null when some owner on the path holds the value in a slot with no\n * written spelling; the cell is still named, and the remedy drops to the one\n * sentence that is true for every shape.\n */\nfunction __velarStaleClassLocation(instance, parent) {\n const seen = __velarGraphCreateSet();\n let frontier = [{ value: parent, child: instance, steps: [] }];\n for (let depth = 0; depth < 8 && frontier.length > 0; depth += 1) {\n const next = [];\n for (const entry of frontier) {\n const candidate = entry.value;\n if (candidate === null || (typeof candidate !== \"object\" && typeof candidate !== \"function\")) continue;\n if (__velarGraphSetContains(seen, candidate)) continue;\n __velarGraphSetInsert(seen, candidate);\n const descriptor = __velarGraphOwnDescriptor(candidate, \"velarStateName\");\n const name = descriptor && \"value\" in descriptor ? descriptor.value : null;\n // A cell holds its value in a closure rather than in a slot, so the step\n // into it is the cell itself and the path collected so far is complete.\n if (typeof name === \"string\" && name !== \"\") return { cell: name, steps: entry.steps };\n const owners = __velarGraphWeakMapRead(__velarRuntime.parents, candidate);\n if (!owners) continue;\n const slot = __velarStaleClassSlot(candidate, entry.child);\n let steps = null;\n if (slot !== null && entry.steps !== null) {\n steps = [slot];\n for (let index = 0; index < entry.steps.length; index += 1) steps[steps.length] = entry.steps[index];\n }\n for (const above of __velarGraphSetItems(owners)) next[next.length] = { value: above, child: candidate, steps };\n }\n frontier = next;\n }\n return null;\n}\n\n/** `holder.box`, `boxes[0]`, `groups[0].box` -- the path an author can read the value through. */\nfunction __velarStaleClassPath(cell, steps, count) {\n let text = cell;\n for (let index = 0; index < count; index += 1) {\n const step = steps[index];\n text += step.field === null ? \"[\" + step.index + \"]\" : \".\" + step.field;\n }\n return text;\n}\n\n/**\n * The write that publishes, for the shape the instance is actually in. The flat\n * case replaces the cell; a record below it is replaced with the field written\n * over, which is the update every other record in `state` takes; a List element\n * is replaced by index.\n */\nfunction __velarStaleClassRemedy(location, className) {\n const steps = location.steps;\n if (steps === null) return \"only replacing the value in state '\" + location.cell + \"' that holds it publishes.\";\n if (steps.length === 0) return \"only replacing the cell -- '\" + location.cell + \" = \" + className + \"(...)' -- publishes.\";\n const last = steps[steps.length - 1];\n const owner = __velarStaleClassPath(location.cell, steps, steps.length - 1);\n if (last.field === null) {\n return \"only replacing the element -- '\" + owner + \"[\" + last.index + \"] = \" + className + \"(...)' -- publishes.\";\n }\n return \"only replacing it -- '\" + owner + \" = {...\" + owner + \", \" + last.field + \": \" + className + \"(...)}' -- publishes.\";\n}\n\n/** The reading line, captured where the read happens rather than where the report is made. */\nfunction __velarStaleClassSite() {\n const site = new Error(\"velar stale class read\");\n try { return typeof site.stack === \"string\" ? site.stack : \"\"; } catch { return \"\"; }\n}\n\n/**\n * One mistake, one sentence, once per place, class and field -- whichever of\n * the three readers reached it first. Only the words that name the reader\n * change: a `computed` and a `watch` subject are a reactive value, and a\n * position in the document is the interpolation that wrote it.\n */\nfunction __velarReportStaleClassField(location, className, field, member, mode, stack) {\n const named = typeof member === \"string\" && member !== \"\" && member !== field ? member : null;\n const path = location.steps === null || location.steps.length === 0\n ? \"\" : \" at '\" + __velarStaleClassPath(location.cell, location.steps, location.steps.length) + \"'\";\n // Keyed by the place and the field, not by the member: two members that read\n // one field are two lines about one field that does not publish, and the\n // report names whichever reader reached it first, as it always has.\n const key = location.cell + \"|\" + path + \"|\" + className + \"|\" + field;\n if (__velarGraphSetContains(__velarStaleClassReported, key)) return;\n __velarGraphSetInsert(__velarStaleClassReported, key);\n const reader = mode === \"dom\" ? \"interpolation\" : \"value\";\n __velarStaleClassHooks.frozenRead({\n message: \"This \" + (mode === \"dom\" ? \"interpolation\" : \"reactive value\") + \" reads '\" + (named ?? field) + \"' on the \"\n + className + \" held in state '\" + location.cell + \"'\" + path + \".\"\n + (named === null ? \"\" : \" '\" + named + \"' reads the field '\" + field + \"'.\")\n + \" A class instance is never wrapped, so changing '\" + field\n + \"' publishes nothing and this \" + reader + \" stays as it is: \"\n + __velarStaleClassRemedy(location, className)\n + \" Hold the field in its own 'state' if it is meant to be followed.\",\n stack,\n });\n}\n\n/**\n * Observes one instance's own writable data fields. Fields the class did not\n * declare as plain values -- a getter it wrote itself, a sealed field -- are\n * left exactly as they are: this detector may not change what the program does,\n * only notice what it cannot see.\n *\n * The report is made when a reader that cannot follow the field meets a real\n * change to it, in whichever order the two arrive: a read that is already stale\n * reports on the spot, and a read of a value that changes later reports at the\n * change, on the line the read was made. A field that never changes is never\n * reported, which is what keeps a `const` field silent (WB-I4).\n */\nfunction __velarObserveClassFields(instance, parent) {\n if (__velarGraphWeakSetContains(__velarStaleClassSeen, instance)) return;\n __velarGraphWeakSetInsert(__velarStaleClassSeen, instance);\n const className = __velarStaleClassName(instance);\n if (className === null) return;\n const location = __velarStaleClassLocation(instance, parent);\n if (location === null) return;\n let observed = false;\n for (const field of __velarGraphOwnNames(instance)) {\n const descriptor = __velarGraphOwnDescriptor(instance, field);\n if (!descriptor || !(\"value\" in descriptor) || !descriptor.writable || !descriptor.configurable) continue;\n observed = true;\n let held = descriptor.value;\n let waiting = null;\n let moved = false;\n __velarGraphDefine(instance, field, {\n enumerable: descriptor.enumerable,\n configurable: true,\n // Named, not shorthand, for the frozen-read detector's reason: the\n // development host walks past its own frames to find the reading line,\n // and every engine spells an anonymous accessor differently.\n get: function __velarStaleClassFieldRead() {\n const observer = __velarRuntime.activeObserver;\n // Every mode an observer has is a reader that re-runs only when a\n // dependency it tracked changes, and this field is never one: the\n // rendering tier (\"dom\") is as stuck as the derivation tier.\n if (observer !== null && (observer.mode === \"computed\" || observer.mode === \"watch\" || observer.mode === \"dom\")) {\n if (moved) __velarReportStaleClassField(location, className, field, __velarStaleClassMember, observer.mode, __velarStaleClassSite());\n else if (waiting === null) waiting = { mode: observer.mode, member: __velarStaleClassMember, site: __velarStaleClassSite() };\n }\n return held;\n },\n set: function __velarStaleClassFieldWrite(next) {\n if (__velarGraphSame(held, next)) return;\n held = next;\n moved = true;\n if (waiting === null) return;\n const claim = waiting;\n waiting = null;\n __velarReportStaleClassField(location, className, field, claim.member, claim.mode, claim.site);\n },\n });\n }\n if (observed) __velarObserveClassMembers(instance);\n}\n\n/**\n * Records which of the class's own members a read entered through, so a report\n * can name the one the author's line contains as well as the field underneath\n * it. Only the prototype of an instance whose fields this detector already took\n * over is touched, and only in a development host: an object it observes\n * nothing on is one it has no report to make about either.\n */\nfunction __velarObserveClassMembers(instance) {\n const prototype = __velarGraphPrototype(instance);\n if (prototype === null || __velarGraphWeakSetContains(__velarStaleClassWrapped, prototype)) return;\n __velarGraphWeakSetInsert(__velarStaleClassWrapped, prototype);\n for (const member of __velarGraphOwnNames(prototype)) {\n // The compiler owns its own contracts -- `@dispose:` emits `__velar:dispose`\n // -- and a member the author did not write is not one their line names.\n if (member === \"constructor\" || member.indexOf(\"__velar\") === 0 || member.indexOf(\":\") >= 0) continue;\n const descriptor = __velarGraphOwnDescriptor(prototype, member);\n if (!descriptor || !descriptor.configurable) continue;\n if (typeof descriptor.get === \"function\" && descriptor.set === undefined) {\n const read = descriptor.get;\n __velarGraphDefine(prototype, member, {\n enumerable: descriptor.enumerable,\n configurable: true,\n get: function __velarStaleClassMemberRead() { return __velarStaleClassEnter(member, read, this, []); },\n });\n continue;\n }\n if (!(\"value\" in descriptor) || typeof descriptor.value !== \"function\") continue;\n const call = descriptor.value;\n __velarGraphDefine(prototype, member, {\n enumerable: descriptor.enumerable,\n configurable: true,\n writable: descriptor.writable,\n value: function __velarStaleClassMemberCall(...values) { return __velarStaleClassEnter(member, call, this, values); },\n });\n }\n}\n\nfunction __velarStaleClassEnter(member, operation, receiver, values) {\n const outer = __velarStaleClassMember;\n if (outer === null) __velarStaleClassMember = member;\n try { return __velarGraphApply(operation, receiver, values, \"class member\"); }\n finally { __velarStaleClassMember = outer; }\n}\n";
|
|
16
16
|
/**
|
|
17
17
|
* The reactive runtime an application installs once: the captured host ABI,
|
|
18
18
|
* the flush budget and its runaway report, and the dependency graph itself.
|
|
@@ -72,7 +72,7 @@ export const WEB_STORAGE_HOST_RUNTIME = WEB_HOST_ABI_RUNTIME + "\n" + "const sto
|
|
|
72
72
|
export const WEB_LOOK_MODULE = VELAR_TYPE_REGISTRY_RUNTIME + "\n" + "\nconst lookMissingField = Object.freeze({});\nconst lookReflectApply = Object.getOwnPropertyDescriptor(Reflect, \"apply\")?.value;\nconst lookGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor(Object, \"getOwnPropertyDescriptor\")?.value;\nconst lookRegExpTest = Object.getOwnPropertyDescriptor(RegExp.prototype, \"test\")?.value;\nfunction lookOwnData(value, name) {\n if (value === null || (typeof value !== \"object\" && typeof value !== \"function\")\n || typeof lookReflectApply !== \"function\" || typeof lookGetOwnPropertyDescriptor !== \"function\") return lookMissingField;\n const descriptor = lookReflectApply(lookGetOwnPropertyDescriptor, Object, [value, name]);\n return descriptor && descriptor.enumerable && \"value\" in descriptor ? descriptor.value : lookMissingField;\n}\nfunction lookMatches(pattern, value) {\n return typeof lookReflectApply === \"function\" && typeof lookRegExpTest === \"function\"\n ? lookReflectApply(lookRegExpTest, pattern, [value])\n : false;\n}\nfunction lookText(value, label) {\n if (typeof value !== \"string\") throw new TypeError(label + \" must be text\");\n if (value.length === 0 || value.length > 65536) throw new RangeError(label + \" must contain 1 through 65536 characters\");\n return value;\n}\nfunction lookFinite(value, label) {\n if (typeof value !== \"number\" || !Number.isFinite(value)) throw new TypeError(label + \" must be a finite number\");\n return value;\n}\nfunction lookRange(value, label, minimum, maximum) {\n value = lookFinite(value, label);\n if (value < minimum || value > maximum) throw new RangeError(label + \" must be from \" + minimum + \" through \" + maximum);\n return value;\n}\n// D114 P6 item 2 (LK-I3): a slot CSS spells as a percentage takes the\n// language's own `Percentage`, so the guard reads the number out of the written\n// unit and states the bound in the unit the author wrote.\nfunction lookPercentageRange(value, label, minimum, maximum) {\n if (typeof value !== \"string\" || !lookMatches(/^[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)%$/, value)) {\n throw new TypeError(label + \" must be a percentage such as 50%\");\n }\n const percent = Number(value.slice(0, -1));\n if (!Number.isFinite(percent) || percent < minimum || percent > maximum) {\n throw new RangeError(label + \" must be from \" + minimum + \"% through \" + maximum + \"%\");\n }\n return value;\n}\nfunction lookVisual(value, label) {\n if (typeof value === \"number\") return String(lookFinite(value, label));\n return lookText(value, label);\n}\nfunction lookNonNegativeVisual(value, label) {\n const visual = lookVisual(value, label);\n if (lookMatches(/^\\s*-/, visual)) throw new RangeError(label + \" cannot be negative\");\n return visual;\n}\nfunction lookResult(value) {\n if (value.length > 1024 * 1024) throw new RangeError(\"A constructed Look value cannot exceed 1 MiB\");\n return value;\n}\n// A standard module ships to the browser as its own source, so it carries the\n// CSS string serializer rather than reaching for the emitted runtime's copy.\n// css-string.ts publishes the one implementation both spellings read.\n" + CSS_STRING_RUNTIME_BODY + "// charter section 3549: the two transition longhands take the vocabularies the\n// matching builders take. The longhand read a closed set while the builder read\n// nothing, so 'backgroundColor' -- the camelCase spelling every other Look\n// property is written with -- compiled clean and reached the browser as a\n// declaration it discards. The set is the analyzer's, derived from the Look\n// property table rather than restated here.\nconst transitionProperties = [\"inherit\",\"initial\",\"revert\",\"revert-layer\",\"unset\",\"none\",\"all\",\"box-sizing\",\"z-index\",\"clip\",\"clip-path\",\"object-fit\",\"object-position\",\"aspect-ratio\",\"grid-template-columns\",\"grid-template-rows\",\"grid-template-areas\",\"grid-auto-columns\",\"grid-auto-rows\",\"grid-auto-flow\",\"grid-column\",\"grid-column-start\",\"grid-column-end\",\"grid-row\",\"grid-row-start\",\"grid-row-end\",\"grid-area\",\"flex\",\"flex-direction\",\"flex-grow\",\"flex-shrink\",\"flex-basis\",\"flex-wrap\",\"order\",\"gap\",\"row-gap\",\"column-gap\",\"align-items\",\"justify-items\",\"justify-content\",\"align-content\",\"align-self\",\"justify-self\",\"place-items\",\"place-content\",\"place-self\",\"width\",\"height\",\"min-width\",\"max-width\",\"min-height\",\"max-height\",\"inline-size\",\"block-size\",\"min-inline-size\",\"max-inline-size\",\"min-block-size\",\"max-block-size\",\"inset\",\"top\",\"right\",\"bottom\",\"left\",\"inset-inline\",\"inset-block\",\"inset-inline-start\",\"inset-inline-end\",\"inset-block-start\",\"inset-block-end\",\"padding\",\"padding-top\",\"padding-right\",\"padding-bottom\",\"padding-left\",\"padding-inline\",\"padding-block\",\"padding-inline-start\",\"padding-inline-end\",\"padding-block-start\",\"padding-block-end\",\"margin\",\"margin-top\",\"margin-right\",\"margin-bottom\",\"margin-left\",\"margin-inline\",\"margin-block\",\"margin-inline-start\",\"margin-inline-end\",\"margin-block-start\",\"margin-block-end\",\"background\",\"background-color\",\"background-image\",\"background-position\",\"background-size\",\"background-repeat\",\"background-attachment\",\"background-clip\",\"background-origin\",\"background-blend-mode\",\"border\",\"border-width\",\"border-style\",\"border-color\",\"border-top\",\"border-right\",\"border-bottom\",\"border-left\",\"border-top-width\",\"border-right-width\",\"border-bottom-width\",\"border-left-width\",\"border-top-style\",\"border-right-style\",\"border-bottom-style\",\"border-left-style\",\"border-top-color\",\"border-right-color\",\"border-bottom-color\",\"border-left-color\",\"border-radius\",\"border-top-left-radius\",\"border-top-right-radius\",\"border-bottom-right-radius\",\"border-bottom-left-radius\",\"outline\",\"outline-width\",\"outline-style\",\"outline-color\",\"outline-offset\",\"box-shadow\",\"text-shadow\",\"opacity\",\"filter\",\"backdrop-filter\",\"color\",\"font-family\",\"font-size\",\"font-weight\",\"font-style\",\"font-stretch\",\"font-variant\",\"font-kerning\",\"font-optical-sizing\",\"font-feature-settings\",\"font-variation-settings\",\"line-height\",\"vertical-align\",\"letter-spacing\",\"word-spacing\",\"text-align\",\"text-indent\",\"text-decoration\",\"text-decoration-color\",\"text-decoration-line\",\"text-decoration-style\",\"text-decoration-thickness\",\"text-underline-offset\",\"text-underline-position\",\"text-transform\",\"text-rendering\",\"white-space\",\"text-overflow\",\"text-wrap\",\"overflow-wrap\",\"word-break\",\"hyphens\",\"tab-size\",\"writing-mode\",\"text-orientation\",\"direction\",\"unicode-bidi\",\"list-style\",\"list-style-type\",\"list-style-position\",\"list-style-image\",\"fill\",\"stroke\",\"stroke-width\",\"stroke-linecap\",\"stroke-linejoin\",\"stroke-dasharray\",\"stroke-dashoffset\",\"translate\",\"scale\",\"rotate\",\"transform\",\"transform-origin\",\"accent-color\",\"caret-color\",\"color-scheme\",\"scroll-margin\",\"scroll-margin-top\",\"scroll-margin-right\",\"scroll-margin-bottom\",\"scroll-margin-left\",\"scroll-padding\",\"scroll-padding-top\",\"scroll-padding-right\",\"scroll-padding-bottom\",\"scroll-padding-left\",\"scroll-snap-align\",\"scroll-snap-stop\",\"scroll-snap-type\",\"overscroll-behavior\",\"overscroll-behavior-x\",\"overscroll-behavior-y\",\"scrollbar-color\",\"scrollbar-width\"];\nfunction lookTransitionProperty(value) {\n value = lookText(value, \"Transition property\");\n if (transitionProperties.includes(value)) return value;\n // The longhand's diagnostic teaches the CSS spelling, so the rejection here\n // teaches the same one rather than only naming the value.\n let dashed = \"\";\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n dashed += code >= 65 && code <= 90 ? \"-\" + value[index].toLowerCase() : value[index];\n }\n if (dashed !== value && transitionProperties.includes(dashed)) {\n throw new TypeError(\"Transition property '\" + value + \"' is not a CSS property name; did you mean '\" + dashed + \"'?\");\n }\n throw new TypeError(\"Transition property '\" + value + \"' is not an animatable CSS property name\");\n}\nfunction lookType(name, predicate) {\n return __velarRegisterRuntimeType(Object.freeze({\n is(value) { return predicate(value); },\n parse(value) {\n if (!predicate(value)) throw new TypeError(name + \" received an invalid visual value\");\n return value;\n },\n }));\n}\nconst lengthPattern = /^[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:px|rem|em|vw|vh|vmin|vmax)$/;\nconst percentagePattern = /^[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)%$/;\nconst trackFractionPattern = /^[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)fr$/;\nconst durationPattern = /^[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:ms|s)$/;\nconst anglePattern = /^[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:deg|turn)$/;\nconst calculatedLengthPattern = /^(?:calc|min|max|clamp)\\(/;\nconst textVisual = (value) => typeof value === \"string\" && value.length > 0 && value.length <= 1024 * 1024;\n\nexport const Look = lookType(\"Look\", (value) => value !== null && typeof value === \"object\" && lookOwnData(value, \"__velarLook\") === true);\nexport const Length = lookType(\"Length\", (value) => typeof value === \"string\" && (lookMatches(lengthPattern, value) || lookMatches(calculatedLengthPattern, value)));\nexport const Percentage = lookType(\"Percentage\", (value) => typeof value === \"string\" && lookMatches(percentagePattern, value));\nexport const LengthPercentage = lookType(\"LengthPercentage\", (value) => typeof value === \"string\" && (lookMatches(lengthPattern, value) || lookMatches(percentagePattern, value) || lookMatches(calculatedLengthPattern, value)));\nexport const TrackFraction = lookType(\"TrackFraction\", (value) => typeof value === \"string\" && lookMatches(trackFractionPattern, value));\nexport const Duration = lookType(\"Duration\", (value) => typeof value === \"string\" && lookMatches(durationPattern, value));\nexport const Angle = lookType(\"Angle\", (value) => typeof value === \"string\" && lookMatches(anglePattern, value));\nexport const Color = lookType(\"Color\", textVisual);\nexport const Border = lookType(\"Border\", textVisual);\nexport const Shadow = lookType(\"Shadow\", textVisual);\nexport const Filter = lookType(\"Filter\", textVisual);\nexport const Image = lookType(\"Image\", textVisual);\nexport const Track = lookType(\"Track\", textVisual);\nexport const TrackList = lookType(\"TrackList\", textVisual);\nexport const Transition = lookType(\"Transition\", textVisual);\nexport const Spacing = lookType(\"Spacing\", textVisual);\nexport const Keyframes = lookType(\"Keyframes\", (value) => lookOwnData(value, \"__velarKeyframes\") === true\n && typeof lookOwnData(value, \"name\") === \"string\");\nexport const Animation = lookType(\"Animation\", (value) => lookOwnData(value, \"__velarAnimation\") === true\n && typeof lookOwnData(value, \"css\") === \"string\");\n\n// D103: every written token() call is folded to its CSS text while the module\n// compiles, because the analyzer has already proved the name is a literal\n// custom property identifier. This implementation is what the published module\n// interface promises anyway — the builder is an ordinary value that may be\n// aliased, passed on, and called outside a look: block — so the same name check\n// answers here rather than trusting a caller the compiler never saw.\nconst lookTokenNamePattern = /^--[A-Za-z0-9_-]+$/u;\nexport function token(name) {\n name = lookText(name, \"Design token name\");\n if (!lookMatches(lookTokenNamePattern, name)) {\n throw new TypeError(\"Design token name '\" + name + \"' is not a CSS custom property identifier: write '--' followed by one or more letters, digits, hyphens, or underscores\");\n }\n return \"var(\" + name + \")\";\n}\nexport function color(value) { return lookText(value, \"Color\"); }\nexport function rgb(red, green, blue) {\n const channels = [red, green, blue].map((value, index) => lookRange(value, \"RGB channel \" + (index + 1), 0, 255));\n return lookResult(\"rgb(\" + channels.join(\" \") + \")\");\n}\nexport function rgba(red, green, blue, alpha) {\n const channels = [red, green, blue].map((value, index) => lookRange(value, \"RGB channel \" + (index + 1), 0, 255));\n return lookResult(\"rgb(\" + channels.join(\" \") + \" / \" + lookRange(alpha, \"RGB alpha\", 0, 1) + \")\");\n}\nexport function hsl(hue, saturation, lightness) {\n return lookResult(\"hsl(\" + lookFinite(hue, \"HSL hue\") + \" \" + lookPercentageRange(saturation, \"HSL saturation\", 0, 100)\n + \" \" + lookPercentageRange(lightness, \"HSL lightness\", 0, 100) + \")\");\n}\nexport function alpha(value, opacity) {\n return lookResult(\"color-mix(in srgb, \" + lookText(value, \"Color\") + \" \" + (lookRange(opacity, \"Color opacity\", 0, 1) * 100) + \"%, transparent)\");\n}\nexport function lighten(value, amount) {\n return lookResult(\"color-mix(in srgb, \" + lookText(value, \"Color\") + \", white \" + (lookRange(amount, \"Color amount\", 0, 1) * 100) + \"%)\");\n}\nexport function darken(value, amount) {\n return lookResult(\"color-mix(in srgb, \" + lookText(value, \"Color\") + \", black \" + (lookRange(amount, \"Color amount\", 0, 1) * 100) + \"%)\");\n}\nexport function border(width, value, style = \"solid\") {\n if (typeof style !== \"string\" || ![\"none\", \"hidden\", \"dotted\", \"dashed\", \"solid\", \"double\", \"groove\", \"ridge\", \"inset\", \"outset\"].includes(style)) {\n throw new TypeError(\"Border style is invalid\");\n }\n return lookResult(lookVisual(width, \"Border width\") + \" \" + style + \" \" + lookText(value, \"Border color\"));\n}\nexport function shadow(x, y, blur, value, spread = \"0px\", inset = false) {\n if (typeof inset !== \"boolean\") throw new TypeError(\"Shadow inset must be bool\");\n return lookResult((inset ? \"inset \" : \"\") + lookVisual(x, \"Shadow x\") + \" \" + lookVisual(y, \"Shadow y\") + \" \"\n + lookVisual(blur, \"Shadow blur\") + \" \" + lookVisual(spread, \"Shadow spread\") + \" \" + lookText(value, \"Shadow color\"));\n}\nexport function blur(radius) { return lookResult(\"blur(\" + lookNonNegativeVisual(radius, \"Filter blur radius\") + \")\"); }\nexport function brightness(amount) { return lookResult(\"brightness(\" + lookRange(amount, \"Filter brightness\", 0, 1000000) + \")\"); }\nexport function contrast(amount) { return lookResult(\"contrast(\" + lookRange(amount, \"Filter contrast\", 0, 1000000) + \")\"); }\nexport function dropShadow(x, y, blur, value) {\n return lookResult(\"drop-shadow(\" + lookVisual(x, \"Drop shadow x\") + \" \" + lookVisual(y, \"Drop shadow y\") + \" \"\n + lookNonNegativeVisual(blur, \"Drop shadow blur\") + \" \" + lookText(value, \"Drop shadow color\") + \")\");\n}\nexport function grayscale(amount) { return lookResult(\"grayscale(\" + lookRange(amount, \"Filter grayscale\", 0, 1) + \")\"); }\nexport function hueRotate(angle) { return lookResult(\"hue-rotate(\" + lookVisual(angle, \"Filter hue rotation\") + \")\"); }\nexport function invert(amount) { return lookResult(\"invert(\" + lookRange(amount, \"Filter inversion\", 0, 1) + \")\"); }\nexport function filterOpacity(amount) { return lookResult(\"opacity(\" + lookRange(amount, \"Filter opacity\", 0, 1) + \")\"); }\nexport function saturate(amount) { return lookResult(\"saturate(\" + lookRange(amount, \"Filter saturation\", 0, 1000000) + \")\"); }\nexport function sepia(amount) { return lookResult(\"sepia(\" + lookRange(amount, \"Filter sepia\", 0, 1) + \")\"); }\nexport function filters(first, ...rest) {\n const values = [first, ...rest];\n if (values.length > 64) throw new RangeError(\"filters cannot compose more than 64 values\");\n return lookResult(values.map((value, index) => lookText(value, \"Filter \" + (index + 1))).join(\" \"));\n}\nexport function linearGradient(angle, start, end) {\n return lookResult(\"linear-gradient(\" + lookVisual(angle, \"Gradient angle\") + \", \" + lookText(start, \"Gradient start\") + \", \" + lookText(end, \"Gradient end\") + \")\");\n}\nexport function asset(path) { return lookResult(\"url(\" + __velarCssString(lookText(path, \"Asset path\")) + \")\"); }\nexport function minmax(minimum, maximum) { return lookResult(\"minmax(\" + lookVisual(minimum, \"Minimum track\") + \", \" + lookVisual(maximum, \"Maximum track\") + \")\"); }\nexport function repeat(count, size) { return lookResult(\"repeat(\" + lookVisual(count, \"Repeat count\") + \", \" + lookVisual(size, \"Repeat size\") + \")\"); }\nexport function tracks(first, ...rest) {\n const values = [first, ...rest];\n if (values.length > 1024) throw new RangeError(\"tracks cannot contain more than 1024 values\");\n return lookResult(values.map((value, index) => lookVisual(value, \"Track \" + (index + 1))).join(\" \"));\n}\nexport function transition(property, duration, easing = \"ease\", delay) {\n const suffix = delay === undefined ? \"\" : \" \" + lookVisual(delay, \"Transition delay\");\n return lookResult(lookTransitionProperty(property) + \" \" + lookVisual(duration, \"Transition duration\") + \" \" + lookText(easing, \"Transition easing\") + suffix);\n}\nexport function spacing(first, second, third, fourth) {\n return lookResult([first, second, third, fourth].filter((value) => value !== undefined)\n .map((value, index) => lookVisual(value, \"Spacing value \" + (index + 1))).join(\" \"));\n}\nexport function min(first, second) { return lookResult(\"min(\" + lookVisual(first, \"min value\") + \", \" + lookVisual(second, \"min value\") + \")\"); }\nexport function max(first, second) { return lookResult(\"max(\" + lookVisual(first, \"max value\") + \", \" + lookVisual(second, \"max value\") + \")\"); }\nexport function clamp(minimum, preferred, maximum) {\n return lookResult(\"clamp(\" + lookVisual(minimum, \"clamp minimum\") + \", \" + lookVisual(preferred, \"clamp preferred\") + \", \" + lookVisual(maximum, \"clamp maximum\") + \")\");\n}\nexport function animate(frames, duration, easing = \"ease\", delay = \"0ms\", count = 1, loop = false, direction = \"normal\", fill = \"none\") {\n if (lookOwnData(frames, \"__velarKeyframes\") !== true) throw new TypeError(\"animate frames must be a Keyframes value\");\n const name = lookText(lookOwnData(frames, \"name\"), \"Keyframes name\");\n if (!lookMatches(durationPattern, duration)) throw new TypeError(\"Animation duration must be a Duration value\");\n if (!lookMatches(durationPattern, delay)) throw new TypeError(\"Animation delay must be a Duration value\");\n if (![\"linear\", \"ease\", \"ease-in\", \"ease-out\", \"ease-in-out\", \"step-start\", \"step-end\"].includes(easing)) throw new TypeError(\"Animation easing is invalid\");\n if (![\"normal\", \"reverse\", \"alternate\", \"alternate-reverse\"].includes(direction)) throw new TypeError(\"Animation direction is invalid\");\n if (![\"none\", \"forwards\", \"backwards\", \"both\"].includes(fill)) throw new TypeError(\"Animation fill is invalid\");\n if (typeof loop !== \"boolean\") throw new TypeError(\"Animation loop must be bool\");\n count = lookFinite(count, \"Animation count\");\n if (!Number.isInteger(count) || count <= 0 || count > 1000000) throw new RangeError(\"Animation count must be a positive integer no greater than 1000000\");\n const css = [name, duration, easing, delay, loop ? \"infinite\" : String(count), direction, fill].join(\" \");\n return Object.freeze({ __velarAnimation: true, css: lookResult(css) });\n}\n" + " ";
|
|
73
73
|
export const WEB_APP_MODULE = WEB_RUNTIME_FOUNDATION + "\n" + "\nexport function onError(handler) {\n if (typeof handler !== \"function\") throw new TypeError(\"onError requires a callback\");\n if (!__velarGraphSetContains(__velarRuntime.errorHandlers, handler) && __velarGraphSetCount(__velarRuntime.errorHandlers) >= 1000) throw new RangeError(\"An application cannot install more than 1000 error handlers\");\n __velarGraphSetInsert(__velarRuntime.errorHandlers, handler);\n return () => { __velarGraphSetRemove(__velarRuntime.errorHandlers, handler); return null; };\n}\n\nexport function reportError(error, phase = \"manual\", detail = \"\") {\n if (!__velarIsError(error)) throw new TypeError(\"reportError requires an Error\");\n if (typeof phase !== \"string\" || typeof detail !== \"string\") throw new TypeError(\"reportError phase and detail must be strings\");\n if (phase.length > 256 || detail.length > 65536) throw new RangeError(\"reportError phase/detail text is too long\");\n __velarRuntime.report(error, { phase, detail, unhandled: false });\n return null;\n}\n" + " ";
|
|
74
74
|
export const WEB_CONFIG_MODULE = VELAR_TYPE_REGISTRY_RUNTIME + "\n" + "const source = \"__VELAR_PUBLIC_CONFIG__\";\nfunction freeze(value) {\n if (!value || typeof value !== \"object\" || Object.isFrozen(value)) return value;\n for (const child of Object.values(value)) freeze(child);\n return Object.freeze(value);\n}\nconst value = freeze(source);\nexport function publicConfig(Type) { Type = __velarRequireRuntimeType(Type, \"publicConfig\"); return Type.parse(value); }\nexport function has(key) { if (typeof key !== \"string\") throw new TypeError(\"Config keys must be strings\"); return Object.prototype.hasOwnProperty.call(value, key); }\nexport function keys() { return Object.keys(value).sort(); }\n";
|
|
75
|
-
export const WEB_WEB_MODULE = VELAR_ERROR_NORMALIZATION_RUNTIME + "\n" + WEB_LIST_GUARD_RUNTIME + "\n" + WEB_OPTIONS_GUARD_RUNTIME + "\n" + VELAR_TYPE_REGISTRY_RUNTIME + "\n" + WEB_BROWSER_HOST_RUNTIME + "\n" + WEB_DOM_HOST_RUNTIME + "\n" + "const appBase = \"__VELAR_WEB_BASE__\";\nlet nextDomId = 1;\nfunction webLocationField(name, getter) {\n return __velarBrowserField(__velarBrowserLocation, name, getter, __velarBrowserLocationConstructor);\n}\nfunction webUrl(value, base) {\n if (typeof __velarBrowserUrlConstructor !== \"function\") throw new TypeError(\"The browser URL API is unavailable\");\n return new __velarBrowserUrlConstructor(value, base);\n}\nfunction webUrlField(value, name, getter) {\n return __velarBrowserField(value, name, getter, __velarBrowserUrlConstructor);\n}\nconst webEventMissingField = Object.freeze({});\nconst webEventReflectApply = Object.getOwnPropertyDescriptor(Reflect, \"apply\")?.value;\nfunction webEventConstructor(name) {\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, name);\n return descriptor && \"value\" in descriptor && typeof descriptor.value === \"function\" ? descriptor.value : null;\n}\nfunction webEventPrototypeMember(constructor, name, kind) {\n let prototype = typeof constructor === \"function\" ? Object.getOwnPropertyDescriptor(constructor, \"prototype\")?.value : null;\n while (prototype && prototype !== Object.prototype) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, name);\n if (descriptor) {\n const member = kind === \"get\" ? descriptor.get : \"value\" in descriptor ? descriptor.value : null;\n return typeof member === \"function\" ? member : null;\n }\n prototype = Object.getPrototypeOf(prototype);\n }\n return null;\n}\nconst webNativeEvent = webEventConstructor(\"Event\");\nconst webNativeMouseEvent = webEventConstructor(\"MouseEvent\");\nconst webEventDefaultPrevented = webEventPrototypeMember(webNativeEvent, \"defaultPrevented\", \"get\");\nconst webEventPreventDefault = webEventPrototypeMember(webNativeEvent, \"preventDefault\", \"value\");\nconst webEventButton = webEventPrototypeMember(webNativeMouseEvent, \"button\", \"get\");\nconst webEventMetaKey = webEventPrototypeMember(webNativeMouseEvent, \"metaKey\", \"get\");\nconst webEventCtrlKey = webEventPrototypeMember(webNativeMouseEvent, \"ctrlKey\", \"get\");\nconst webEventShiftKey = webEventPrototypeMember(webNativeMouseEvent, \"shiftKey\", \"get\");\nconst webEventAltKey = webEventPrototypeMember(webNativeMouseEvent, \"altKey\", \"get\");\nfunction webEventField(event, name, nativeGetter) {\n if (typeof nativeGetter === \"function\" && typeof webEventReflectApply === \"function\") {\n try { return webEventReflectApply(nativeGetter, event, []); } catch {}\n }\n if (event === null || (typeof event !== \"object\" && typeof event !== \"function\")) return webEventMissingField;\n const descriptor = Object.getOwnPropertyDescriptor(event, name);\n return descriptor?.enumerable && \"value\" in descriptor ? descriptor.value : webEventMissingField;\n}\nfunction webEventCall(event, name, nativeMethod) {\n if (typeof nativeMethod === \"function\" && typeof webEventReflectApply === \"function\") {\n try { return webEventReflectApply(nativeMethod, event, []); } catch {}\n }\n const method = webEventField(event, name, null);\n if (typeof method !== \"function\" || typeof webEventReflectApply !== \"function\") throw new TypeError(\"Link received an invalid click event\");\n return webEventReflectApply(method, event, []);\n}\nfunction reportLinkEventFailure(failure) {\n const error = __velarNormalizeError(failure);\n const runtime = globalThis[Symbol.for(\"velar.runtime.v1\")];\n if (runtime && typeof runtime.report === \"function\") runtime.report(error, { phase: \"event\", detail: \"link\", unhandled: true });\n else __velarBrowserCallCaptured(__velarBrowserQueueMicrotask, __velarBrowserWindow, [() => { throw error; }], \"queueMicrotask\");\n}\n\n" + "export function domId(prefix = \"velar\") {\n prefix = __velarString(prefix, \"DOM ID prefix\");\n if (!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(prefix)) throw new TypeError(\"DOM ID prefixes must start with a letter and contain only letters, numbers, underscores, or hyphens\");\n if (prefix.length > 64) throw new RangeError(\"DOM ID prefixes cannot exceed 64 characters\");\n if (!Number.isSafeInteger(nextDomId)) throw new RangeError(\"The VelarScript DOM ID space is exhausted\");\n return prefix + \"-\" + nextDomId++;\n}\n\nfunction isBoundedStringMap(value) {\n let size;\n try { size = Reflect.getOwnPropertyDescriptor(Map.prototype, \"size\").get.call(value); }\n catch { return false; }\n if (size > 100000) return false;\n let codeUnits = 0;\n for (const [key, item] of Map.prototype.entries.call(value)) {\n if (typeof key !== \"string\" || typeof item !== \"string\") return false;\n codeUnits += key.length + item.length;\n if (codeUnits > 2 * 1024 * 1024) return false;\n }\n return true;\n}\n\nfunction checkedRouteContext(value) {\n try {\n const fields = __velarOptions(value, \"RouteContext\", __velarOptionFields([\"path\", \"params\", \"query\", \"hash\"]));\n if (Object.keys(fields).length !== 4 || typeof fields.path !== \"string\" || fields.path.length > 2 * 1024 * 1024\n || !isBoundedStringMap(fields.params) || !isBoundedStringMap(fields.query)\n || typeof fields.hash !== \"string\" || fields.hash.length > 2 * 1024 * 1024) return null;\n return value;\n } catch { return null; }\n}\n\nexport const RouteContext = __velarRegisterRuntimeType(Object.freeze({\n is(value) { return checkedRouteContext(value) !== null; },\n parse(value) {\n if (checkedRouteContext(value) === null) throw new TypeError(\"RouteContext requires bounded path/hash text and string params/query Maps\");\n return value;\n },\n}));\n\nfunction validateRoutePath(path) {\n if (typeof path !== \"string\" || !path.startsWith(\"/\")) throw new TypeError(\"A VelarScript route path must start with '/'\");\n if (path.length > 8192) throw new RangeError(\"A VelarScript route path cannot exceed 8192 code units\");\n if (path.includes(\"?\") || path.includes(\"#\")) throw new TypeError(\"A VelarScript route path describes only a pathname\");\n if (path.includes(\"\\\\\")) throw new TypeError(\"A VelarScript route path cannot contain a backslash\");\n if (path.length > 1 && path.endsWith(\"/\")) throw new TypeError(\"A VelarScript route path cannot end with '/'\");\n const names = new Set();\n const segments = path.split(\"/\").slice(1);\n for (const [index, segment] of segments.entries()) {\n if (!segment && path !== \"/\") throw new TypeError(\"A VelarScript route path cannot contain an empty segment\");\n if (segment === \"*\") {\n if (index !== segments.length - 1) throw new TypeError(\"A VelarScript route wildcard must be the final segment\");\n if (names.has(\"wildcard\")) throw new TypeError(\"A VelarScript route parameter named 'wildcard' conflicts with the '*' capture\");\n names.add(\"wildcard\");\n continue;\n }\n if (segment.includes(\"*\")) throw new TypeError(\"A VelarScript route wildcard must occupy its whole final segment\");\n if (!segment.startsWith(\":\")) continue;\n const name = segment.slice(1);\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name)) throw new TypeError(\"A VelarScript route parameter requires a valid name\");\n if (names.has(name)) throw new TypeError(\"A VelarScript route parameter cannot be repeated: \" + name);\n names.add(name);\n }\n return path;\n}\n\nfunction compileRoutePath(path) {\n const names = [];\n const source = path.split(\"/\").map((part) => {\n if (part === \"*\") { names.push(\"wildcard\"); return \"(.*)\"; }\n if (part.startsWith(\":\")) { names.push(part.slice(1)); return \"([^/]+)\"; }\n return part.replace(/[.*+?^$(){}|[\\]\\\\]/g, \"\\\\$&\");\n }).join(\"/\");\n return Object.freeze({ names: Object.freeze(names), pattern: new RegExp(\"^\" + source + \"/?$\") });\n}\n\nexport function route(path, component) {\n path = validateRoutePath(path);\n if (typeof component !== \"function\") throw new TypeError(\"A VelarScript route component must be callable\");\n return Object.freeze({ path, component });\n}\n\nexport function lazy(loader, exportName, loading = null, failed = null) {\n if (typeof loader !== \"function\") throw new TypeError(\"VelarScript lazy requires a module loader\");\n if (typeof exportName !== \"string\" || !exportName) throw new TypeError(\"VelarScript lazy requires an exported component name\");\n if (exportName.length > 4096) throw new RangeError(\"VelarScript lazy export names cannot exceed 4096 characters\");\n if (loading != null && typeof loading !== \"function\") throw new TypeError(\"VelarScript lazy loading fallback must be a component\");\n if (failed != null && typeof failed !== \"function\") throw new TypeError(\"VelarScript lazy failure fallback must be a component\");\n\n let resolved = null;\n let pending = null;\n const load = () => {\n if (resolved) return Promise.resolve(resolved);\n if (!pending) {\n pending = Promise.resolve().then(loader).then((module) => {\n const target = module && module[exportName];\n if (typeof target !== \"function\") throw new TypeError(\"Dynamically loaded module has no component export '\" + exportName + \"'\");\n resolved = target;\n return target;\n }).catch((error) => {\n pending = null;\n throw error;\n });\n }\n return pending;\n };\n\n return function VelarLazy(props = {}, namespace = \"html\") {\n const svg = namespace === \"svg\";\n const host = svg\n ? __velarDomCreateElementNS(\"http://www.w3.org/2000/svg\", \"g\")\n : __velarDomCreateElement(\"velar-lazy\");\n if (!svg) host.style.display = \"contents\";\n let active = loading ? loading({}, namespace) : null;\n if (active != null && !active.__velarComponent) throw new TypeError(\"VelarScript lazy loading fallback must render a component\");\n let mounted = false;\n let destroyed = false;\n if (active && active.__velarComponent) __velarDomAppend(host, active.node);\n else __velarDomAppend(host, __velarDomCreateComment(\"lazy component loading\"));\n\n const replace = (next) => {\n if (!next || !next.__velarComponent) throw new TypeError(\"VelarScript lazy fallbacks must render components\");\n if (destroyed) { next.destroy(); return; }\n if (active && active.__velarComponent) active.destroy(false);\n active = next;\n __velarDomReplaceChildren(host, next.node);\n if (mounted) next.__mount();\n };\n\n const fail = (value) => {\n const error = __velarNormalizeError(value);\n const runtime = globalThis[Symbol.for(\"velar.runtime.v1\")];\n runtime?.report?.(error, { phase: \"resource\", detail: \"lazy:\" + exportName, component: exportName, unhandled: false });\n try {\n if (failed) replace(failed({ error }, namespace));\n else {\n const message = svg\n ? __velarDomCreateElementNS(\"http://www.w3.org/2000/svg\", \"text\")\n : __velarDomCreateElement(\"div\");\n __velarDomSetAttribute(message, \"role\", \"alert\");\n __velarDomSetText(message, \"Unable to load \" + exportName);\n replace(component(message));\n }\n } catch (fallbackFailure) {\n const fallbackError = __velarNormalizeError(fallbackFailure);\n runtime?.report?.(fallbackError, { phase: \"render\", detail: \"lazy-fallback:\" + exportName, component: exportName, unhandled: false });\n if (active && active.__velarComponent) active.destroy(false);\n active = null;\n if (!destroyed) {\n const message = svg\n ? __velarDomCreateElementNS(\"http://www.w3.org/2000/svg\", \"text\")\n : __velarDomCreateElement(\"div\");\n __velarDomSetAttribute(message, \"role\", \"alert\");\n __velarDomSetText(message, \"Unable to render \" + exportName);\n __velarDomReplaceChildren(host, message);\n }\n }\n };\n\n void load().then((target) => replace(target(props, namespace))).catch(fail);\n\n return component(host, () => {\n mounted = true;\n if (active && active.__velarComponent) active.__mount();\n }, () => {\n destroyed = true;\n if (active && active.__velarComponent) active.destroy(false);\n });\n };\n}\n\nexport function navigate(to, options = {}) {\n options = __velarOptions(options, \"Navigation options\", __velarOptionFields([\"replace\", \"scroll\"]));\n const replace = options.replace ?? false;\n const scroll = options.scroll ?? true;\n __velarBool(replace, \"Navigation replace\");\n __velarBool(scroll, \"Navigation scroll\");\n const href = internalHref(to);\n if (replace) __velarBrowserCall(__velarBrowserHistory, \"replaceState\", __velarBrowserHistoryReplace, __velarBrowserHistoryConstructor, [null, \"\", href]);\n else __velarBrowserCall(__velarBrowserHistory, \"pushState\", __velarBrowserHistoryPush, __velarBrowserHistoryConstructor, [null, \"\", href]);\n if (typeof __velarBrowserPopStateEventConstructor !== \"function\") throw new TypeError(\"The browser PopStateEvent API is unavailable\");\n const event = new __velarBrowserPopStateEventConstructor(\"popstate\");\n __velarBrowserCallCaptured(__velarBrowserGlobalDispatchEvent, __velarBrowserWindow, [event], \"dispatchEvent\");\n if (scroll) __velarBrowserCallCaptured(__velarBrowserAnimationFrame, __velarBrowserWindow, [() => {\n __velarBrowserCallCaptured(__velarBrowserScrollTo, __velarBrowserWindow, [{ top: 0, left: 0 }], \"scrollTo\");\n }], \"requestAnimationFrame\");\n return null;\n}\n\nexport function redirect(to) {\n return navigate(to, { replace: true });\n}\n\nexport function back() {\n __velarBrowserCall(__velarBrowserHistory, \"back\", __velarBrowserHistoryBack, __velarBrowserHistoryConstructor);\n return null;\n}\n\nexport function forward() {\n __velarBrowserCall(__velarBrowserHistory, \"forward\", __velarBrowserHistoryForward, __velarBrowserHistoryConstructor);\n return null;\n}\n\nexport function reload() {\n __velarBrowserCall(__velarBrowserLocation, \"reload\", __velarBrowserLocationReload, __velarBrowserLocationConstructor);\n return null;\n}\n\n// The document's history is one source, so the runtime listens to it once and\n// hands every route reader that one subscription. Router re-renders from it and\n// NavLink re-marks its aria-current from it; each used to install a window\n// listener of its own, and 'currentRoute()' — which installed none — was\n// therefore the one route reader that could not follow a navigation.\n//\n// The list is replaced rather than mutated, and it is read and written with\n// index operations alone: this runs after initialization, where a live\n// Set.prototype.add is exactly the reach the DOM host ABI exists to avoid.\nlet routeSubscribers = [];\nlet removeRouteSubscription = null;\n\nfunction subscribeRoute(callback) {\n const added = [];\n for (let index = 0; index < routeSubscribers.length; index += 1) added[index] = routeSubscribers[index];\n added[added.length] = callback;\n routeSubscribers = added;\n if (removeRouteSubscription === null) {\n removeRouteSubscription = __velarBrowserListenGlobal(\"popstate\", () => {\n // A Router re-rendering destroys the NavLinks on the page it replaces, so\n // a subscriber can leave while the notification is still running. The\n // snapshot is what is walked; whether each entry is still subscribed is\n // asked again, so a departed one is not called after it left -- which is\n // what a window listener removed mid-dispatch already did.\n const notified = routeSubscribers;\n for (let index = 0; index < notified.length; index += 1) {\n const subscriber = notified[index];\n const active = routeSubscribers;\n for (let scan = 0; scan < active.length; scan += 1) {\n if (active[scan] !== subscriber) continue;\n subscriber();\n break;\n }\n }\n });\n }\n return () => {\n const remaining = [];\n let removed = false;\n for (let index = 0; index < routeSubscribers.length; index += 1) {\n const subscriber = routeSubscribers[index];\n if (!removed && subscriber === callback) { removed = true; continue; }\n remaining[remaining.length] = subscriber;\n }\n if (!removed) return;\n routeSubscribers = remaining;\n if (routeSubscribers.length > 0 || removeRouteSubscription === null) return;\n removeRouteSubscription();\n removeRouteSubscription = null;\n };\n}\n\n// Reading the route inside a reactive position is a dependency on the history,\n// the same way reading a state cell is a dependency on that cell — no second\n// spelling, and no publishing the route back out of a mounted page by hand. The\n// reactive subscription is one entry in the one listener above, taken on the\n// first tracked read and kept: the graph it feeds outlives every component, and\n// a read outside a reactive position takes nothing.\nconst routeReadSource = {};\nlet routeReadSubscribed = false;\n\nfunction trackRoute() {\n const runtime = globalThis[Symbol.for(\"velar.runtime.v1\")];\n if (!runtime || typeof runtime.track !== \"function\" || typeof runtime.trigger !== \"function\") return;\n const observer = runtime.activeObserver;\n if (!observer || observer.stopped) return;\n if (!routeReadSubscribed) {\n routeReadSubscribed = true;\n subscribeRoute(() => runtime.trigger(routeReadSource, \"path\"));\n }\n runtime.track(routeReadSource, \"path\");\n}\n\nexport function currentRoute() {\n trackRoute();\n const path = applicationPath(webLocationField(\"pathname\", __velarBrowserLocationPathname)) ?? \"/\";\n return Object.freeze({ path, params: new Map(), query: queryValues(), hash: routeHash() });\n}\n\nconst headPropFields = __velarOptionFields([\"title\", \"description\", \"canonical\", \"robots\", \"image\", \"themeColor\", \"language\"]);\n\nfunction headMetadata(props) {\n props = __velarLiveOptions(props, \"Head props\", headPropFields);\n let { title, description = \"\", canonical = \"\", robots = \"\", image = \"\", themeColor = \"\", language = \"\" } = props;\n title = __velarString(title, \"Head title\");\n description = __velarString(description, \"Head description\");\n canonical = __velarString(canonical, \"Head canonical URL\");\n robots = __velarString(robots, \"Head robots\");\n image = __velarString(image, \"Head image\");\n themeColor = __velarString(themeColor, \"Head theme color\");\n language = __velarString(language, \"Head language\");\n if (title.length > 4096) throw new RangeError(\"Head titles cannot exceed 4096 characters\");\n if (description.length > 65536) throw new RangeError(\"Head descriptions cannot exceed 64 KiB\");\n if (canonical.length > 2 * 1024 * 1024 || image.length > 2 * 1024 * 1024) throw new RangeError(\"Head URLs cannot exceed 2 MiB\");\n if (robots.length > 4096) throw new RangeError(\"Head robots cannot exceed 4096 characters\");\n if (themeColor.length > 256) throw new RangeError(\"Head theme colors cannot exceed 256 characters\");\n if (language.length > 256) throw new RangeError(\"Head language tags cannot exceed 256 characters\");\n if (language && !/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/u.test(language)) {\n throw new TypeError(\"Head language must be a simple BCP 47 language tag\");\n }\n return { title, description, canonical, robots, image, themeColor, language };\n}\n\n// Head follows Vel's ordinary rules: its props are read inside a DOM observer,\n// so a title built from state tracks that state. Reading each prop exactly once\n// at construction froze '<Head title={f\"Inbox ({unread})\"} />' at whatever\n// count the first render saw, and the frozen-read report that exists to catch\n// exactly that is muted on the snapshot path by construction.\n// The observer is created at construction so the props are validated where they\n// always were, and the document is not touched until mount: what a Head owns it\n// takes on insertion and gives back on removal.\nexport function Head(props) {\n let live = false;\n let pending = null;\n let applied = null;\n let previousTitle = \"\";\n let previousLanguage = null;\n let restorers = [];\n const release = () => {\n if (applied === null) return;\n if (document.title === applied.title) document.title = previousTitle;\n if (applied.language && document.documentElement.getAttribute(\"lang\") === applied.language) {\n if (previousLanguage == null) document.documentElement.removeAttribute(\"lang\");\n else document.documentElement.setAttribute(\"lang\", previousLanguage);\n }\n for (const restore of restorers.reverse()) restore();\n restorers = [];\n applied = null;\n };\n const take = (next) => {\n previousTitle = document.title;\n document.title = next.title;\n previousLanguage = document.documentElement.getAttribute(\"lang\");\n if (next.language) document.documentElement.setAttribute(\"lang\", next.language);\n restorers = [\n ownHead('meta[name=\"description\"]', \"meta\", \"name\", \"description\", \"content\", next.description),\n ownHead('link[rel=\"canonical\"]', \"link\", \"rel\", \"canonical\", \"href\", next.canonical),\n ownHead('meta[name=\"robots\"]', \"meta\", \"name\", \"robots\", \"content\", next.robots),\n ownHead('meta[property=\"og:image\"]', \"meta\", \"property\", \"og:image\", \"content\", next.image),\n ownHead('meta[name=\"theme-color\"]', \"meta\", \"name\", \"theme-color\", \"content\", next.themeColor),\n ];\n applied = next;\n };\n // The observer runs once here, so an invalid Head is still rejected before a\n // single DOM call is made -- and the validating read happens inside the\n // observer, where D70's frozen-read report correctly ignores it.\n const observer = webObserve(() => {\n pending = headMetadata(props);\n if (!live) return;\n release();\n take(pending);\n }, \"head\", \"Head\");\n const node = document.createComment(\"velar head\");\n return component(node, () => {\n live = true;\n take(pending);\n }, () => {\n observer.stop();\n release();\n });\n}\n\n// A DOM-phase observer built from the shared runtime registry. A component the\n// runtime implements is rendered content like any other, so its reads belong in\n// the queue every other rendered position uses: the reactive graph settles\n// first, then the document is written once.\nfunction webObserve(run, detail, componentName) {\n const runtime = globalThis[Symbol.for(\"velar.runtime.v1\")];\n if (!runtime || typeof runtime.runTracked !== \"function\" || typeof runtime.schedule !== \"function\"\n || typeof runtime.cleanupObserver !== \"function\") {\n throw new TypeError(\"A VelarScript Web component requires the VelarScript Web runtime\");\n }\n let initial = true;\n const observer = {\n mode: \"dom\",\n stopped: false,\n dependencies: new Set(),\n run() {\n if (observer.stopped) return;\n // The first run happens while the component is being constructed, and\n // construction is transactional: that failure belongs to the caller.\n // Every later run is an update, whose failure is reported.\n try { runtime.runTracked(observer, run); }\n catch (failure) {\n // Construction is transactional, and now that these components read\n // live props the first run has already subscribed to whatever it read\n // on the way to failing. A component that never came into existence\n // leaves nothing behind that a later write could re-run.\n if (initial) { observer.stop(); throw failure; }\n const error = __velarNormalizeError(failure);\n if (typeof runtime.report === \"function\") runtime.report(error, { phase: \"render\", detail, component: componentName, unhandled: true });\n else __velarBrowserCallCaptured(__velarBrowserQueueMicrotask, __velarBrowserWindow, [() => { throw error; }], \"queueMicrotask\");\n }\n finally { initial = false; }\n },\n notify() { if (!observer.stopped) runtime.schedule(observer); },\n stop() { observer.stopped = true; runtime.cleanupObserver(observer); },\n };\n observer.run();\n return observer;\n}\n\n// Reading props inside an observer is what makes a component follow its state;\n// building a subtree there is not. A component the runtime implements calls\n// another component directly rather than through the emitted instantiation\n// path, so it needs that path's guard: the reactive graph records a dependency\n// only for an observer it will run again, and a stopped one is exactly the\n// shape it refuses to record.\nfunction webUntracked(run) {\n const runtime = globalThis[Symbol.for(\"velar.runtime.v1\")];\n if (!runtime || typeof runtime.runTracked !== \"function\") {\n throw new TypeError(\"A VelarScript Web component requires the VelarScript Web runtime\");\n }\n return runtime.runTracked({ mode: \"dom\", stopped: true, dependencies: new Set(), spareDependencies: null, notify() {} }, run);\n}\n\nfunction ownHead(selector, tag, identityName, identityValue, valueName, value) {\n if (!value) return () => {};\n let element = document.head.querySelector(selector);\n const created = !element;\n if (!element) {\n element = document.createElement(tag);\n element.setAttribute(identityName, identityValue);\n document.head.append(element);\n }\n const previous = element.getAttribute(valueName);\n element.setAttribute(valueName, value);\n return () => {\n if (element.getAttribute(valueName) !== value) return;\n if (created) element.remove();\n else if (previous == null) element.removeAttribute(valueName);\n else element.setAttribute(valueName, previous);\n };\n}\n\nexport function announce(message, priority = \"polite\") {\n message = __velarString(message, \"Announcement message\");\n if (message.length > 65536) throw new RangeError(\"Announcement messages cannot exceed 64 KiB\");\n if (priority !== \"polite\" && priority !== \"assertive\") throw new TypeError(\"Announcement priority must be 'polite' or 'assertive'\");\n let region = document.querySelector('[data-velar-announcer=\"' + priority + '\"]');\n if (!region) {\n region = document.createElement(\"div\");\n region.setAttribute(\"data-velar-announcer\", priority);\n region.setAttribute(\"role\", priority === \"assertive\" ? \"alert\" : \"status\");\n region.setAttribute(\"aria-live\", priority);\n region.setAttribute(\"aria-atomic\", \"true\");\n region.style.cssText = \"position:fixed;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0\";\n document.body.append(region);\n }\n region.textContent = \"\";\n __velarBrowserCallCaptured(__velarBrowserAnimationFrame, __velarBrowserWindow, [() => { region.textContent = message; }], \"requestAnimationFrame\");\n return null;\n}\n\nconst routerPropFields = __velarOptionFields([\"routes\", \"fallback\"]);\n\nfunction routerTable(props) {\n props = __velarLiveOptions(props, \"Router props\", routerPropFields);\n let { routes, fallback = null } = props;\n const routeItems = __velarRequireList(routes, \"Router routes\");\n if (routeItems.length > 10000) throw new RangeError(\"A Router cannot contain more than 10000 routes\");\n routes = routeItems.map((item) => {\n item = __velarOptions(item, \"Router route\", __velarOptionFields([\"path\", \"component\"]));\n validateRoutePath(item.path);\n if (typeof item.component !== \"function\") throw new TypeError(\"A Router route component must be callable\");\n return Object.freeze({ path: item.path, component: item.component, matcher: compileRoutePath(item.path) });\n });\n if (fallback != null && typeof fallback !== \"function\") throw new TypeError(\"A Router fallback must be a component\");\n return { routes, fallback };\n}\n\nexport function Router(props) {\n // The host element is created by the observer's first run, after the routes\n // table has been checked: a refused table must not leave a browser node\n // behind on its way out.\n let node = null;\n let table = null;\n let active = null;\n let mounted = false;\n const notFound = ({ route }) => {\n const page = __velarDomCreateElement(\"main\");\n __velarDomSetAttribute(page, \"data-velar-not-found\", \"\");\n const title = __velarDomCreateElement(\"h1\");\n __velarDomSetText(title, \"Page not found\");\n const detail = __velarDomCreateElement(\"p\");\n __velarDomSetText(detail, \"No route matches \" + route.path);\n __velarDomAppend(page, title, detail);\n return component(page);\n };\n const render = () => {\n try {\n const path = applicationPath(webLocationField(\"pathname\", __velarBrowserLocationPathname));\n const match = path === null ? null : matchRoute(table.routes, path);\n const context = match?.context ?? { path: path ?? \"/\", params: new Map(), query: queryValues(), hash: routeHash() };\n const next = webUntracked(() => (match ? match.item.component({ route: context }) : (table.fallback ?? notFound)({ route: context })));\n if (!next || !next.__velarComponent) throw new TypeError(\"A VelarScript Router target must render a component\");\n if (active) active.destroy();\n active = next;\n __velarDomReplaceChildren(node, active.node);\n if (mounted) active.__mount();\n } catch (value) {\n const error = __velarNormalizeError(value);\n if (!mounted) throw error;\n const runtime = globalThis[Symbol.for(\"velar.runtime.v1\")];\n if (runtime && typeof runtime.report === \"function\") {\n runtime.report(error, { phase: \"render\", detail: \"router\", component: \"Router\", unhandled: true });\n } else {\n __velarBrowserCallCaptured(__velarBrowserQueueMicrotask, __velarBrowserWindow, [() => { throw error; }], \"queueMicrotask\");\n }\n }\n };\n const changed = () => render();\n let removeRouteListener = null;\n // The routes table is read inside the observer that renders from it, so a\n // table or fallback built from state re-renders the position that shows it.\n // A constant table subscribes to nothing and recomputes nothing.\n const observer = webObserve(() => {\n table = routerTable(props);\n if (node === null) node = __velarDomCreateElement(\"velar-router\");\n render();\n }, \"router\", \"Router\");\n return component(node, () => {\n mounted = true;\n removeRouteListener = subscribeRoute(changed);\n if (active) active.__mount();\n }, () => {\n observer.stop();\n if (removeRouteListener) removeRouteListener();\n if (active) active.destroy(false);\n });\n}\n\nconst linkPropFields = __velarOptionFields([\"to\", \"replace\", \"class\", \"look\", \"children\"]);\n\nfunction linkTarget(props) {\n const to = __velarString(props.to, \"Link target\");\n if (to.length > 2 * 1024 * 1024) throw new RangeError(\"Link targets cannot exceed 2 MiB\");\n requireNavigableTarget(to, \"Link target\");\n const replace = props.replace === undefined ? false : props.replace;\n __velarBool(replace, \"Link replace\");\n const external = isExternal(to);\n return { to, replace, external, href: external ? to : internalHref(to) };\n}\n\n// Which fields a Link carries is fixed where the Link is written, so the record\n// shape is checked once; the values behind those fields are read inside the\n// observer that consumes them, which is what makes '<Link to={path}>' follow\n// the state 'path' holds. 'children' is rendered content owned by the position\n// that shows it, so it is taken once, where that position builds it -- that is\n// why the shape check sits here rather than inside the observer the way Head's\n// does: reading the slot again on every update would build content nothing\n// shows. Behind a live props store both reads answer from the same cached\n// derived value, so the author's prop expression still runs exactly once.\nexport function Link(props) {\n const children = __velarLiveOptions(props, \"Link props\", linkPropFields).children;\n // The anchor is created by the observer's first run, after the target has\n // been checked: a refused target must not leave a browser node behind.\n let node = null;\n let target = null;\n let releaseHost = null;\n const observer = webObserve(() => {\n const next = linkTarget(props);\n if (node === null) node = __velarDomCreateElement(\"a\");\n if (releaseHost) { releaseHost(); releaseHost = null; }\n releaseHost = forwardHost(node, props);\n node.href = next.href;\n target = next;\n }, \"link\", \"Link\");\n try { append(node, children); }\n catch (failure) { observer.stop(); if (releaseHost) releaseHost(); throw failure; }\n const clicked = (event) => {\n try {\n const defaultPrevented = webEventField(event, \"defaultPrevented\", webEventDefaultPrevented);\n const button = webEventField(event, \"button\", webEventButton);\n const metaKey = webEventField(event, \"metaKey\", webEventMetaKey);\n const ctrlKey = webEventField(event, \"ctrlKey\", webEventCtrlKey);\n const shiftKey = webEventField(event, \"shiftKey\", webEventShiftKey);\n const altKey = webEventField(event, \"altKey\", webEventAltKey);\n if (defaultPrevented === webEventMissingField || button === webEventMissingField || metaKey === webEventMissingField\n || ctrlKey === webEventMissingField || shiftKey === webEventMissingField || altKey === webEventMissingField\n || typeof defaultPrevented !== \"boolean\" || !Number.isSafeInteger(button)\n || typeof metaKey !== \"boolean\" || typeof ctrlKey !== \"boolean\" || typeof shiftKey !== \"boolean\" || typeof altKey !== \"boolean\") {\n throw new TypeError(\"Link received an invalid click event\");\n }\n if (defaultPrevented || button !== 0 || metaKey || ctrlKey || shiftKey || altKey) return;\n if (target.external) return;\n if (webUrlField(webUrl(node.href, webLocationField(\"href\", __velarBrowserLocationHref)), \"origin\", __velarBrowserUrlOrigin)\n !== webLocationField(\"origin\", __velarBrowserLocationOrigin)) return;\n webEventCall(event, \"preventDefault\", webEventPreventDefault);\n navigate(target.to, { replace: target.replace });\n } catch (failure) { reportLinkEventFailure(failure); }\n };\n let removeClick = null;\n return component(node, () => { removeClick = __velarBrowserListen(node, \"click\", clicked); }, () => {\n observer.stop();\n if (removeClick) removeClick();\n if (releaseHost) releaseHost();\n });\n}\n\nconst navLinkPropFields = __velarOptionFields([\"to\", \"exact\", \"replace\", \"class\", \"look\", \"children\"]);\n\nfunction navLinkTarget(props) {\n const to = __velarString(props.to, \"NavLink target\");\n requireNavigableTarget(to, \"NavLink target\");\n const exact = props.exact === undefined ? false : props.exact;\n const replace = props.replace === undefined ? false : props.replace;\n __velarBool(exact, \"NavLink exact\");\n __velarBool(replace, \"NavLink replace\");\n internalHref(to);\n return { exact, path: normalizeApplicationPath(webUrlField(webUrl(to, \"https://velar.invalid\"), \"pathname\", __velarBrowserUrlPathname)) };\n}\n\nexport function NavLink(props) {\n const children = __velarLiveOptions(props, \"NavLink props\", navLinkPropFields).children;\n let linked = null;\n let target = null;\n const update = () => {\n const application = applicationPath(webLocationField(\"pathname\", __velarBrowserLocationPathname));\n const current = application === null ? null : normalizeApplicationPath(application);\n const active = current !== null\n && (current === target.path || (!target.exact && target.path !== \"/\" && current.startsWith(target.path + \"/\")));\n if (active) __velarDomSetAttribute(linked.node, \"aria-current\", \"page\");\n else __velarDomRemoveAttribute(linked.node, \"aria-current\");\n };\n // A NavLink rejects its own target before the Link it wraps sees it, so the\n // observer runs first and the message names NavLink. Its first run has no\n // Link to mark yet; the update below is that run's second half.\n const observer = webObserve(() => {\n target = navLinkTarget(props);\n if (linked !== null) update();\n }, \"navlink\", \"NavLink\");\n // The Link is handed the same live fields, not a copy of their values, so a\n // NavLink built from state moves its href as well as its aria-current.\n let removeRouteListener = null;\n try {\n linked = Link({\n get to() { return props.to; },\n get replace() { return props.replace; },\n get class() { return props.class; },\n get look() { return props.look; },\n children,\n });\n update();\n } catch (failure) {\n observer.stop();\n if (linked) linked.destroy(false);\n throw failure;\n }\n return component(linked.node, () => {\n linked.__mount();\n removeRouteListener = subscribeRoute(update);\n }, () => {\n observer.stop();\n if (removeRouteListener) removeRouteListener();\n linked.destroy(false);\n });\n}\n\nfunction forwardHost(node, props) {\n const cleanups = [];\n if (props.class != null) {\n if (typeof props.class !== \"string\") throw new TypeError(\"Link class must be a string\");\n const names = props.class.split(/\\s+/).filter(Boolean);\n node.classList.add(...names);\n cleanups.push(() => node.classList.remove(...names));\n }\n if (props.look != null) {\n const runtime = globalThis[Symbol.for(\"velar.runtime.v1\")];\n if (!runtime || typeof runtime.applyLook !== \"function\") throw new TypeError(\"Link Look requires the VelarScript Web runtime\");\n cleanups.push(runtime.applyLook(node, props.look));\n }\n return () => { for (const cleanup of cleanups.reverse()) cleanup(); };\n}\n\nfunction normalizeApplicationPath(path) {\n return path.length > 1 ? path.replace(/\\/+$/u, \"\") : \"/\";\n}\n\nfunction matchRoute(routes, pathname) {\n for (const item of routes) {\n const result = item.matcher.pattern.exec(pathname);\n if (!result) continue;\n const params = new Map();\n let decodable = true;\n for (const [index, name] of item.matcher.names.entries()) {\n try { params.set(name, decodeURIComponent(result[index + 1] ?? \"\")); }\n catch { decodable = false; break; }\n }\n if (!decodable) continue;\n return { item, context: { path: pathname, params, query: queryValues(), hash: routeHash() } };\n }\n return null;\n}\n\nfunction applicationPath(pathname) {\n if (typeof pathname !== \"string\" || pathname.length > 2 * 1024 * 1024) throw new RangeError(\"Application paths cannot exceed 2 MiB\");\n if (appBase === \"/\") return pathname;\n const prefix = appBase.slice(0, -1);\n if (pathname === prefix) return \"/\";\n return pathname.startsWith(appBase) ? \"/\" + pathname.slice(appBase.length) : null;\n}\n\nfunction internalHref(to) {\n if (typeof to !== \"string\" || !to.startsWith(\"/\") || isExternal(to)) throw new TypeError(\"VelarScript navigation targets must be application paths starting with '/'\");\n if (to.length > 2 * 1024 * 1024) throw new RangeError(\"VelarScript navigation targets cannot exceed 2 MiB\");\n const parsed = webUrl(to, \"https://velar.invalid\");\n const pathname = webUrlField(parsed, \"pathname\", __velarBrowserUrlPathname);\n const search = webUrlField(parsed, \"search\", __velarBrowserUrlSearch);\n const hash = webUrlField(parsed, \"hash\", __velarBrowserUrlHash);\n return appBase + pathname.slice(1) + search + hash;\n}\n\nfunction isExternal(to) {\n return typeof to === \"string\" && (/^[a-z][a-z\\d+.-]*:/i.test(to) || to.startsWith(\"//\"));\n}\n\n// The scheme policy a JSX URL attribute enforces, narrowed to what a Link is\n// for. 'javascript:' and 'vbscript:' are code, not locations: a Link classified\n// one as external, wrote it to node.href, and its click handler then let native\n// anchor activation run it. Only the two schemes a page can be served over are\n// navigation targets; anything else belongs to a plain <a> element.\nconst navigableSchemes = [\"http\", \"https\"];\nfunction targetScheme(to) {\n let scheme = \"\";\n for (let index = 0; index < to.length; index += 1) {\n const code = to.charCodeAt(index);\n // The user agent strips ASCII whitespace and control characters before it\n // parses the scheme, so \"java\\tscript:\" reads as \"javascript:\" to it and\n // has to read that way here too.\n if (code <= 0x20 || code === 0x7f) continue;\n if (code === 58 && scheme.length > 0) return scheme.toLowerCase();\n const letter = (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n if (letter || (scheme.length > 0 && ((code >= 48 && code <= 57) || code === 43 || code === 45 || code === 46))) {\n scheme += to[index];\n continue;\n }\n // Anything else this early means the value names no scheme: it is a\n // relative path, which is always the application's own origin.\n return \"\";\n }\n return \"\";\n}\nfunction requireNavigableTarget(to, label) {\n const scheme = targetScheme(to);\n if (scheme !== \"\" && !navigableSchemes.includes(scheme)) {\n throw new TypeError(label + \" rejected the '\" + scheme + \":' URL scheme; only http and https targets navigate, so write a plain <a> element for another scheme\");\n }\n return to;\n}\n\nfunction queryValues() {\n const search = webLocationField(\"search\", __velarBrowserLocationSearch);\n if (typeof search !== \"string\") throw new TypeError(\"Route queries require browser text\");\n if (search.length > 2 * 1024 * 1024) throw new RangeError(\"Route queries cannot exceed 2 MiB\");\n const output = new Map();\n let count = 0;\n if (typeof __velarBrowserUrlSearchParamsConstructor !== \"function\" || typeof __velarBrowserUrlSearchParamsForEach !== \"function\") {\n throw new TypeError(\"The browser URLSearchParams API is unavailable\");\n }\n const params = new __velarBrowserUrlSearchParamsConstructor(search);\n __velarBrowserCallCaptured(__velarBrowserUrlSearchParamsForEach, params, [(value, name) => {\n count += 1;\n if (count > 100000) throw new RangeError(\"Route queries cannot exceed 100000 fields\");\n output.set(name, value);\n }], \"URLSearchParams.forEach\");\n return output;\n}\n\nfunction routeHash() {\n const hash = webLocationField(\"hash\", __velarBrowserLocationHash);\n if (typeof hash !== \"string\") throw new TypeError(\"Route hashes require browser text\");\n if (hash.length > 2 * 1024 * 1024) throw new RangeError(\"Route hashes cannot exceed 2 MiB\");\n return hash;\n}\n\n" + "function component(node, mounted, cleanup) {\n let destroyed = false;\n let ready = false;\n return {\n __velarComponent: true,\n node,\n mount(target, before = null) {\n if (destroyed) throw new Error(\"Cannot mount a destroyed VelarScript component\");\n if (ready) throw new Error(\"Cannot mount a VelarScript component more than once\");\n const parent = typeof target === \"string\" ? __velarDomQuerySelector(target) : target;\n if (!parent) throw new Error(\"VelarScript mount target was not found\");\n __velarDomInsertBefore(parent, node, before);\n this.__mount();\n return null;\n },\n __mount() { if (!destroyed && !ready) { ready = true; if (mounted) mounted(); } },\n destroy(remove = true) { if (!destroyed) { destroyed = true; if (cleanup) cleanup(); if (remove) __velarDomRemove(node); } return null; },\n };\n}\n\nfunction append(parent, value, state = null) {\n state ??= { active: __velarDomCreateSet(), depth: 0, values: 0, text: 0 };\n if (value == null || value === false || value === true) return;\n state.values += 1;\n if (state.values > 1000000) throw new RangeError(\"JSX cannot render more than 1000000 values\");\n if (typeof value === \"string\") {\n state.text += value.length;\n if (state.text > 16 * 1024 * 1024) throw new RangeError(\"JSX text cannot exceed 16 MiB\");\n __velarDomAppend(parent, __velarDomCreateTextNode(value));\n return;\n }\n if (typeof value === \"number\") {\n if (!__velarDomIsFinite(value)) throw new TypeError(\"JSX numbers must be finite\");\n __velarDomAppend(parent, __velarDomCreateTextNode(__velarDomString(value)));\n return;\n }\n if (__velarDomIsNode(value)) { __velarDomAppend(parent, value); return; }\n if (__velarDomIsArray(value)) {\n if (state.depth >= 128) throw new RangeError(\"JSX Lists cannot exceed 128 nested levels\");\n if (__velarDomSetContains(state.active, value)) throw new TypeError(\"JSX cannot render a cyclic List\");\n const values = __velarRequireList(value, \"JSX children\");\n __velarDomSetInsert(state.active, value);\n state.depth += 1;\n try { for (const item of values) append(parent, item, state); }\n finally { state.depth -= 1; __velarDomSetRemove(state.active, value); }\n return;\n }\n throw new TypeError(\"JSX can render only text, finite numbers, bool, enums, WebNode values, and Lists of those values\");\n}\n";
|
|
75
|
+
export const WEB_WEB_MODULE = VELAR_ERROR_NORMALIZATION_RUNTIME + "\n" + WEB_LIST_GUARD_RUNTIME + "\n" + WEB_OPTIONS_GUARD_RUNTIME + "\n" + VELAR_TYPE_REGISTRY_RUNTIME + "\n" + WEB_BROWSER_HOST_RUNTIME + "\n" + WEB_DOM_HOST_RUNTIME + "\n" + "const appBase = \"__VELAR_WEB_BASE__\";\nlet nextDomId = 1;\nfunction webLocationField(name, getter) {\n return __velarBrowserField(__velarBrowserLocation, name, getter, __velarBrowserLocationConstructor);\n}\nfunction webUrl(value, base) {\n if (typeof __velarBrowserUrlConstructor !== \"function\") throw new TypeError(\"The browser URL API is unavailable\");\n return new __velarBrowserUrlConstructor(value, base);\n}\nfunction webUrlField(value, name, getter) {\n return __velarBrowserField(value, name, getter, __velarBrowserUrlConstructor);\n}\nconst webEventMissingField = Object.freeze({});\nconst webEventReflectApply = Object.getOwnPropertyDescriptor(Reflect, \"apply\")?.value;\nfunction webEventConstructor(name) {\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, name);\n return descriptor && \"value\" in descriptor && typeof descriptor.value === \"function\" ? descriptor.value : null;\n}\nfunction webEventPrototypeMember(constructor, name, kind) {\n let prototype = typeof constructor === \"function\" ? Object.getOwnPropertyDescriptor(constructor, \"prototype\")?.value : null;\n while (prototype && prototype !== Object.prototype) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, name);\n if (descriptor) {\n const member = kind === \"get\" ? descriptor.get : \"value\" in descriptor ? descriptor.value : null;\n return typeof member === \"function\" ? member : null;\n }\n prototype = Object.getPrototypeOf(prototype);\n }\n return null;\n}\nconst webNativeEvent = webEventConstructor(\"Event\");\nconst webNativeMouseEvent = webEventConstructor(\"MouseEvent\");\nconst webEventDefaultPrevented = webEventPrototypeMember(webNativeEvent, \"defaultPrevented\", \"get\");\nconst webEventPreventDefault = webEventPrototypeMember(webNativeEvent, \"preventDefault\", \"value\");\nconst webEventButton = webEventPrototypeMember(webNativeMouseEvent, \"button\", \"get\");\nconst webEventMetaKey = webEventPrototypeMember(webNativeMouseEvent, \"metaKey\", \"get\");\nconst webEventCtrlKey = webEventPrototypeMember(webNativeMouseEvent, \"ctrlKey\", \"get\");\nconst webEventShiftKey = webEventPrototypeMember(webNativeMouseEvent, \"shiftKey\", \"get\");\nconst webEventAltKey = webEventPrototypeMember(webNativeMouseEvent, \"altKey\", \"get\");\nfunction webEventField(event, name, nativeGetter) {\n if (typeof nativeGetter === \"function\" && typeof webEventReflectApply === \"function\") {\n try { return webEventReflectApply(nativeGetter, event, []); } catch {}\n }\n if (event === null || (typeof event !== \"object\" && typeof event !== \"function\")) return webEventMissingField;\n const descriptor = Object.getOwnPropertyDescriptor(event, name);\n return descriptor?.enumerable && \"value\" in descriptor ? descriptor.value : webEventMissingField;\n}\nfunction webEventCall(event, name, nativeMethod) {\n if (typeof nativeMethod === \"function\" && typeof webEventReflectApply === \"function\") {\n try { return webEventReflectApply(nativeMethod, event, []); } catch {}\n }\n const method = webEventField(event, name, null);\n if (typeof method !== \"function\" || typeof webEventReflectApply !== \"function\") throw new TypeError(\"Link received an invalid click event\");\n return webEventReflectApply(method, event, []);\n}\nfunction reportLinkEventFailure(failure) {\n const error = __velarNormalizeError(failure);\n const runtime = globalThis[Symbol.for(\"velar.runtime.v1\")];\n if (runtime && typeof runtime.report === \"function\") runtime.report(error, { phase: \"event\", detail: \"link\", unhandled: true });\n else __velarBrowserCallCaptured(__velarBrowserQueueMicrotask, __velarBrowserWindow, [() => { throw error; }], \"queueMicrotask\");\n}\n\n" + "export function domId(prefix = \"velar\") {\n prefix = __velarString(prefix, \"DOM ID prefix\");\n if (prefix.length > 64) throw new RangeError(\"DOM ID prefixes cannot exceed 64 characters\");\n if (!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(prefix)) throw new TypeError(\"DOM ID prefixes must start with a letter and contain only letters, numbers, underscores, or hyphens\");\n if (!Number.isSafeInteger(nextDomId)) throw new RangeError(\"The VelarScript DOM ID space is exhausted\");\n return prefix + \"-\" + nextDomId++;\n}\n\nfunction isBoundedStringMap(value) {\n let size;\n try { size = Reflect.getOwnPropertyDescriptor(Map.prototype, \"size\").get.call(value); }\n catch { return false; }\n if (size > 100000) return false;\n let codeUnits = 0;\n for (const [key, item] of Map.prototype.entries.call(value)) {\n if (typeof key !== \"string\" || typeof item !== \"string\") return false;\n codeUnits += key.length + item.length;\n if (codeUnits > 2 * 1024 * 1024) return false;\n }\n return true;\n}\n\nfunction checkedRouteContext(value) {\n try {\n const fields = __velarOptions(value, \"RouteContext\", __velarOptionFields([\"path\", \"params\", \"query\", \"hash\"]));\n if (Object.keys(fields).length !== 4 || typeof fields.path !== \"string\" || fields.path.length > 2 * 1024 * 1024\n || !isBoundedStringMap(fields.params) || !isBoundedStringMap(fields.query)\n || typeof fields.hash !== \"string\" || fields.hash.length > 2 * 1024 * 1024) return null;\n return value;\n } catch { return null; }\n}\n\nexport const RouteContext = __velarRegisterRuntimeType(Object.freeze({\n is(value) { return checkedRouteContext(value) !== null; },\n parse(value) {\n if (checkedRouteContext(value) === null) throw new TypeError(\"RouteContext requires bounded path/hash text and string params/query Maps\");\n return value;\n },\n}));\n\nfunction validateRoutePath(path) {\n if (typeof path !== \"string\" || !path.startsWith(\"/\")) throw new TypeError(\"A VelarScript route path must start with '/'\");\n if (path.length > 8192) throw new RangeError(\"A VelarScript route path cannot exceed 8192 code units\");\n if (path.includes(\"?\") || path.includes(\"#\")) throw new TypeError(\"A VelarScript route path describes only a pathname\");\n if (path.includes(\"\\\\\")) throw new TypeError(\"A VelarScript route path cannot contain a backslash\");\n if (path.length > 1 && path.endsWith(\"/\")) throw new TypeError(\"A VelarScript route path cannot end with '/'\");\n const names = new Set();\n const segments = path.split(\"/\").slice(1);\n for (const [index, segment] of segments.entries()) {\n if (!segment && path !== \"/\") throw new TypeError(\"A VelarScript route path cannot contain an empty segment\");\n if (segment === \"*\") {\n if (index !== segments.length - 1) throw new TypeError(\"A VelarScript route wildcard must be the final segment\");\n if (names.has(\"wildcard\")) throw new TypeError(\"A VelarScript route parameter named 'wildcard' conflicts with the '*' capture\");\n names.add(\"wildcard\");\n continue;\n }\n if (segment.includes(\"*\")) throw new TypeError(\"A VelarScript route wildcard must occupy its whole final segment\");\n if (!segment.startsWith(\":\")) continue;\n const name = segment.slice(1);\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name)) throw new TypeError(\"A VelarScript route parameter requires a valid name\");\n if (names.has(name)) throw new TypeError(\"A VelarScript route parameter cannot be repeated: \" + name);\n names.add(name);\n }\n return path;\n}\n\nfunction compileRoutePath(path) {\n const names = [];\n const source = path.split(\"/\").map((part) => {\n if (part === \"*\") { names.push(\"wildcard\"); return \"(.*)\"; }\n if (part.startsWith(\":\")) { names.push(part.slice(1)); return \"([^/]+)\"; }\n return part.replace(/[.*+?^$(){}|[\\]\\\\]/g, \"\\\\$&\");\n }).join(\"/\");\n return Object.freeze({ names: Object.freeze(names), pattern: new RegExp(\"^\" + source + \"/?$\") });\n}\n\nexport function route(path, component) {\n path = validateRoutePath(path);\n if (typeof component !== \"function\") throw new TypeError(\"A VelarScript route component must be callable\");\n return Object.freeze({ path, component });\n}\n\nexport function lazy(loader, exportName, loading = null, failed = null) {\n if (typeof loader !== \"function\") throw new TypeError(\"VelarScript lazy requires a module loader\");\n if (typeof exportName !== \"string\" || !exportName) throw new TypeError(\"VelarScript lazy requires an exported component name\");\n if (exportName.length > 4096) throw new RangeError(\"VelarScript lazy export names cannot exceed 4096 characters\");\n if (loading != null && typeof loading !== \"function\") throw new TypeError(\"VelarScript lazy loading fallback must be a component\");\n if (failed != null && typeof failed !== \"function\") throw new TypeError(\"VelarScript lazy failure fallback must be a component\");\n\n let resolved = null;\n let pending = null;\n const load = () => {\n if (resolved) return Promise.resolve(resolved);\n if (!pending) {\n pending = Promise.resolve().then(loader).then((module) => {\n const target = module && module[exportName];\n if (typeof target !== \"function\") throw new TypeError(\"Dynamically loaded module has no component export '\" + exportName + \"'\");\n resolved = target;\n return target;\n }).catch((error) => {\n pending = null;\n throw error;\n });\n }\n return pending;\n };\n\n return function VelarLazy(props = {}, namespace = \"html\") {\n const svg = namespace === \"svg\";\n const host = svg\n ? __velarDomCreateElementNS(\"http://www.w3.org/2000/svg\", \"g\")\n : __velarDomCreateElement(\"velar-lazy\");\n if (!svg) host.style.display = \"contents\";\n let active = loading ? loading({}, namespace) : null;\n if (active != null && !active.__velarComponent) throw new TypeError(\"VelarScript lazy loading fallback must render a component\");\n let mounted = false;\n let destroyed = false;\n if (active && active.__velarComponent) __velarDomAppend(host, active.node);\n else __velarDomAppend(host, __velarDomCreateComment(\"lazy component loading\"));\n\n const replace = (next) => {\n if (!next || !next.__velarComponent) throw new TypeError(\"VelarScript lazy fallbacks must render components\");\n if (destroyed) { next.destroy(); return; }\n if (active && active.__velarComponent) active.destroy(false);\n active = next;\n __velarDomReplaceChildren(host, next.node);\n if (mounted) next.__mount();\n };\n\n const fail = (value) => {\n const error = __velarNormalizeError(value);\n const runtime = globalThis[Symbol.for(\"velar.runtime.v1\")];\n runtime?.report?.(error, { phase: \"resource\", detail: \"lazy:\" + exportName, component: exportName, unhandled: false });\n try {\n if (failed) replace(failed({ error }, namespace));\n else {\n const message = svg\n ? __velarDomCreateElementNS(\"http://www.w3.org/2000/svg\", \"text\")\n : __velarDomCreateElement(\"div\");\n __velarDomSetAttribute(message, \"role\", \"alert\");\n __velarDomSetText(message, \"Unable to load \" + exportName);\n replace(component(message));\n }\n } catch (fallbackFailure) {\n const fallbackError = __velarNormalizeError(fallbackFailure);\n runtime?.report?.(fallbackError, { phase: \"render\", detail: \"lazy-fallback:\" + exportName, component: exportName, unhandled: false });\n if (active && active.__velarComponent) active.destroy(false);\n active = null;\n if (!destroyed) {\n const message = svg\n ? __velarDomCreateElementNS(\"http://www.w3.org/2000/svg\", \"text\")\n : __velarDomCreateElement(\"div\");\n __velarDomSetAttribute(message, \"role\", \"alert\");\n __velarDomSetText(message, \"Unable to render \" + exportName);\n __velarDomReplaceChildren(host, message);\n }\n }\n };\n\n void load().then((target) => replace(target(props, namespace))).catch(fail);\n\n return component(host, () => {\n mounted = true;\n if (active && active.__velarComponent) active.__mount();\n }, () => {\n destroyed = true;\n if (active && active.__velarComponent) active.destroy(false);\n });\n };\n}\n\nexport function navigate(to, options = {}) {\n options = __velarOptions(options, \"Navigation options\", __velarOptionFields([\"replace\", \"scroll\"]));\n const replace = options.replace ?? false;\n const scroll = options.scroll ?? true;\n __velarBool(replace, \"Navigation replace\");\n __velarBool(scroll, \"Navigation scroll\");\n const href = internalHref(to);\n if (replace) __velarBrowserCall(__velarBrowserHistory, \"replaceState\", __velarBrowserHistoryReplace, __velarBrowserHistoryConstructor, [null, \"\", href]);\n else __velarBrowserCall(__velarBrowserHistory, \"pushState\", __velarBrowserHistoryPush, __velarBrowserHistoryConstructor, [null, \"\", href]);\n if (typeof __velarBrowserPopStateEventConstructor !== \"function\") throw new TypeError(\"The browser PopStateEvent API is unavailable\");\n const event = new __velarBrowserPopStateEventConstructor(\"popstate\");\n __velarBrowserCallCaptured(__velarBrowserGlobalDispatchEvent, __velarBrowserWindow, [event], \"dispatchEvent\");\n if (scroll) __velarBrowserCallCaptured(__velarBrowserAnimationFrame, __velarBrowserWindow, [() => {\n __velarBrowserCallCaptured(__velarBrowserScrollTo, __velarBrowserWindow, [{ top: 0, left: 0 }], \"scrollTo\");\n }], \"requestAnimationFrame\");\n return null;\n}\n\nexport function redirect(to) {\n return navigate(to, { replace: true });\n}\n\nexport function back() {\n __velarBrowserCall(__velarBrowserHistory, \"back\", __velarBrowserHistoryBack, __velarBrowserHistoryConstructor);\n return null;\n}\n\nexport function forward() {\n __velarBrowserCall(__velarBrowserHistory, \"forward\", __velarBrowserHistoryForward, __velarBrowserHistoryConstructor);\n return null;\n}\n\nexport function reload() {\n __velarBrowserCall(__velarBrowserLocation, \"reload\", __velarBrowserLocationReload, __velarBrowserLocationConstructor);\n return null;\n}\n\n// The document's history is one source, so the runtime listens to it once and\n// hands every route reader that one subscription. Router re-renders from it and\n// NavLink re-marks its aria-current from it; each used to install a window\n// listener of its own, and 'currentRoute()' — which installed none — was\n// therefore the one route reader that could not follow a navigation.\n//\n// The list is replaced rather than mutated, and it is read and written with\n// index operations alone: this runs after initialization, where a live\n// Set.prototype.add is exactly the reach the DOM host ABI exists to avoid.\nlet routeSubscribers = [];\nlet removeRouteSubscription = null;\n\nfunction subscribeRoute(callback) {\n const added = [];\n for (let index = 0; index < routeSubscribers.length; index += 1) added[index] = routeSubscribers[index];\n added[added.length] = callback;\n routeSubscribers = added;\n if (removeRouteSubscription === null) {\n removeRouteSubscription = __velarBrowserListenGlobal(\"popstate\", () => {\n // A Router re-rendering destroys the NavLinks on the page it replaces, so\n // a subscriber can leave while the notification is still running. The\n // snapshot is what is walked; whether each entry is still subscribed is\n // asked again, so a departed one is not called after it left -- which is\n // what a window listener removed mid-dispatch already did.\n const notified = routeSubscribers;\n for (let index = 0; index < notified.length; index += 1) {\n const subscriber = notified[index];\n const active = routeSubscribers;\n for (let scan = 0; scan < active.length; scan += 1) {\n if (active[scan] !== subscriber) continue;\n subscriber();\n break;\n }\n }\n });\n }\n return () => {\n const remaining = [];\n let removed = false;\n for (let index = 0; index < routeSubscribers.length; index += 1) {\n const subscriber = routeSubscribers[index];\n if (!removed && subscriber === callback) { removed = true; continue; }\n remaining[remaining.length] = subscriber;\n }\n if (!removed) return;\n routeSubscribers = remaining;\n if (routeSubscribers.length > 0 || removeRouteSubscription === null) return;\n removeRouteSubscription();\n removeRouteSubscription = null;\n };\n}\n\n// Reading the route inside a reactive position is a dependency on the history,\n// the same way reading a state cell is a dependency on that cell — no second\n// spelling, and no publishing the route back out of a mounted page by hand. The\n// reactive subscription is one entry in the one listener above, taken on the\n// first tracked read and kept: the graph it feeds outlives every component, and\n// a read outside a reactive position takes nothing.\nconst routeReadSource = {};\nlet routeReadSubscribed = false;\n\nfunction trackRoute() {\n const runtime = globalThis[Symbol.for(\"velar.runtime.v1\")];\n if (!runtime || typeof runtime.track !== \"function\" || typeof runtime.trigger !== \"function\") return;\n const observer = runtime.activeObserver;\n if (!observer || observer.stopped) return;\n if (!routeReadSubscribed) {\n routeReadSubscribed = true;\n subscribeRoute(() => runtime.trigger(routeReadSource, \"path\"));\n }\n runtime.track(routeReadSource, \"path\");\n}\n\nexport function currentRoute() {\n trackRoute();\n const path = applicationPath(webLocationField(\"pathname\", __velarBrowserLocationPathname)) ?? \"/\";\n return Object.freeze({ path, params: new Map(), query: queryValues(), hash: routeHash() });\n}\n\nconst headPropFields = __velarOptionFields([\"title\", \"description\", \"canonical\", \"robots\", \"image\", \"themeColor\", \"language\"]);\n\nfunction headMetadata(props) {\n props = __velarLiveOptions(props, \"Head props\", headPropFields);\n let { title, description = \"\", canonical = \"\", robots = \"\", image = \"\", themeColor = \"\", language = \"\" } = props;\n title = __velarString(title, \"Head title\");\n description = __velarString(description, \"Head description\");\n canonical = __velarString(canonical, \"Head canonical URL\");\n robots = __velarString(robots, \"Head robots\");\n image = __velarString(image, \"Head image\");\n themeColor = __velarString(themeColor, \"Head theme color\");\n language = __velarString(language, \"Head language\");\n if (title.length > 4096) throw new RangeError(\"Head titles cannot exceed 4096 characters\");\n if (description.length > 65536) throw new RangeError(\"Head descriptions cannot exceed 64 KiB\");\n if (canonical.length > 2 * 1024 * 1024 || image.length > 2 * 1024 * 1024) throw new RangeError(\"Head URLs cannot exceed 2 MiB\");\n if (robots.length > 4096) throw new RangeError(\"Head robots cannot exceed 4096 characters\");\n if (themeColor.length > 256) throw new RangeError(\"Head theme colors cannot exceed 256 characters\");\n if (language.length > 256) throw new RangeError(\"Head language tags cannot exceed 256 characters\");\n if (language && !/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/u.test(language)) {\n throw new TypeError(\"Head language must be a simple BCP 47 language tag\");\n }\n return { title, description, canonical, robots, image, themeColor, language };\n}\n\n// Head follows Vel's ordinary rules: its props are read inside a DOM observer,\n// so a title built from state tracks that state. Reading each prop exactly once\n// at construction froze '<Head title={f\"Inbox ({unread})\"} />' at whatever\n// count the first render saw, and the frozen-read report that exists to catch\n// exactly that is muted on the snapshot path by construction.\n// The observer is created at construction so the props are validated where they\n// always were, and the document is not touched until mount: what a Head owns it\n// takes on insertion and gives back on removal.\nexport function Head(props) {\n let live = false;\n let pending = null;\n let applied = null;\n let previousTitle = \"\";\n let previousLanguage = null;\n let restorers = [];\n const release = () => {\n if (applied === null) return;\n if (document.title === applied.title) document.title = previousTitle;\n if (applied.language && document.documentElement.getAttribute(\"lang\") === applied.language) {\n if (previousLanguage == null) document.documentElement.removeAttribute(\"lang\");\n else document.documentElement.setAttribute(\"lang\", previousLanguage);\n }\n for (const restore of restorers.reverse()) restore();\n restorers = [];\n applied = null;\n };\n const take = (next) => {\n previousTitle = document.title;\n document.title = next.title;\n previousLanguage = document.documentElement.getAttribute(\"lang\");\n if (next.language) document.documentElement.setAttribute(\"lang\", next.language);\n restorers = [\n ownHead('meta[name=\"description\"]', \"meta\", \"name\", \"description\", \"content\", next.description),\n ownHead('link[rel=\"canonical\"]', \"link\", \"rel\", \"canonical\", \"href\", next.canonical),\n ownHead('meta[name=\"robots\"]', \"meta\", \"name\", \"robots\", \"content\", next.robots),\n ownHead('meta[property=\"og:image\"]', \"meta\", \"property\", \"og:image\", \"content\", next.image),\n ownHead('meta[name=\"theme-color\"]', \"meta\", \"name\", \"theme-color\", \"content\", next.themeColor),\n ];\n applied = next;\n };\n // The observer runs once here, so an invalid Head is still rejected before a\n // single DOM call is made -- and the validating read happens inside the\n // observer, where D70's frozen-read report correctly ignores it.\n const observer = webObserve(() => {\n pending = headMetadata(props);\n if (!live) return;\n release();\n take(pending);\n }, \"head\", \"Head\");\n const node = document.createComment(\"velar head\");\n return component(node, () => {\n live = true;\n take(pending);\n }, () => {\n observer.stop();\n release();\n });\n}\n\n// A DOM-phase observer built from the shared runtime registry. A component the\n// runtime implements is rendered content like any other, so its reads belong in\n// the queue every other rendered position uses: the reactive graph settles\n// first, then the document is written once.\nfunction webObserve(run, detail, componentName) {\n const runtime = globalThis[Symbol.for(\"velar.runtime.v1\")];\n if (!runtime || typeof runtime.runTracked !== \"function\" || typeof runtime.schedule !== \"function\"\n || typeof runtime.cleanupObserver !== \"function\") {\n throw new TypeError(\"A VelarScript Web component requires the VelarScript Web runtime\");\n }\n let initial = true;\n const observer = {\n mode: \"dom\",\n stopped: false,\n dependencies: new Set(),\n run() {\n if (observer.stopped) return;\n // The first run happens while the component is being constructed, and\n // construction is transactional: that failure belongs to the caller.\n // Every later run is an update, whose failure is reported.\n try { runtime.runTracked(observer, run); }\n catch (failure) {\n // Construction is transactional, and now that these components read\n // live props the first run has already subscribed to whatever it read\n // on the way to failing. A component that never came into existence\n // leaves nothing behind that a later write could re-run.\n if (initial) { observer.stop(); throw failure; }\n const error = __velarNormalizeError(failure);\n if (typeof runtime.report === \"function\") runtime.report(error, { phase: \"render\", detail, component: componentName, unhandled: true });\n else __velarBrowserCallCaptured(__velarBrowserQueueMicrotask, __velarBrowserWindow, [() => { throw error; }], \"queueMicrotask\");\n }\n finally { initial = false; }\n },\n notify() { if (!observer.stopped) runtime.schedule(observer); },\n stop() { observer.stopped = true; runtime.cleanupObserver(observer); },\n };\n observer.run();\n return observer;\n}\n\n// Reading props inside an observer is what makes a component follow its state;\n// building a subtree there is not. A component the runtime implements calls\n// another component directly rather than through the emitted instantiation\n// path, so it needs that path's guard: the reactive graph records a dependency\n// only for an observer it will run again, and a stopped one is exactly the\n// shape it refuses to record.\nfunction webUntracked(run) {\n const runtime = globalThis[Symbol.for(\"velar.runtime.v1\")];\n if (!runtime || typeof runtime.runTracked !== \"function\") {\n throw new TypeError(\"A VelarScript Web component requires the VelarScript Web runtime\");\n }\n return runtime.runTracked({ mode: \"dom\", stopped: true, dependencies: new Set(), spareDependencies: null, notify() {} }, run);\n}\n\nfunction ownHead(selector, tag, identityName, identityValue, valueName, value) {\n if (!value) return () => {};\n let element = document.head.querySelector(selector);\n const created = !element;\n if (!element) {\n element = document.createElement(tag);\n element.setAttribute(identityName, identityValue);\n document.head.append(element);\n }\n const previous = element.getAttribute(valueName);\n element.setAttribute(valueName, value);\n return () => {\n if (element.getAttribute(valueName) !== value) return;\n if (created) element.remove();\n else if (previous == null) element.removeAttribute(valueName);\n else element.setAttribute(valueName, previous);\n };\n}\n\nexport function announce(message, priority = \"polite\") {\n message = __velarString(message, \"Announcement message\");\n if (message.length > 65536) throw new RangeError(\"Announcement messages cannot exceed 64 KiB\");\n if (priority !== \"polite\" && priority !== \"assertive\") throw new TypeError(\"Announcement priority must be 'polite' or 'assertive'\");\n let region = document.querySelector('[data-velar-announcer=\"' + priority + '\"]');\n if (!region) {\n region = document.createElement(\"div\");\n region.setAttribute(\"data-velar-announcer\", priority);\n region.setAttribute(\"role\", priority === \"assertive\" ? \"alert\" : \"status\");\n region.setAttribute(\"aria-live\", priority);\n region.setAttribute(\"aria-atomic\", \"true\");\n region.style.cssText = \"position:fixed;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0\";\n document.body.append(region);\n }\n region.textContent = \"\";\n __velarBrowserCallCaptured(__velarBrowserAnimationFrame, __velarBrowserWindow, [() => { region.textContent = message; }], \"requestAnimationFrame\");\n return null;\n}\n\nconst routerPropFields = __velarOptionFields([\"routes\", \"fallback\"]);\n\nfunction routerTable(props) {\n props = __velarLiveOptions(props, \"Router props\", routerPropFields);\n let { routes, fallback = null } = props;\n const routeItems = __velarRequireList(routes, \"Router routes\");\n if (routeItems.length > 10000) throw new RangeError(\"A Router cannot contain more than 10000 routes\");\n routes = routeItems.map((item) => {\n item = __velarOptions(item, \"Router route\", __velarOptionFields([\"path\", \"component\"]));\n validateRoutePath(item.path);\n if (typeof item.component !== \"function\") throw new TypeError(\"A Router route component must be callable\");\n return Object.freeze({ path: item.path, component: item.component, matcher: compileRoutePath(item.path) });\n });\n if (fallback != null && typeof fallback !== \"function\") throw new TypeError(\"A Router fallback must be a component\");\n return { routes, fallback };\n}\n\nexport function Router(props) {\n // The host element is created by the observer's first run, after the routes\n // table has been checked: a refused table must not leave a browser node\n // behind on its way out.\n let node = null;\n let table = null;\n let active = null;\n let mounted = false;\n const notFound = ({ route }) => {\n const page = __velarDomCreateElement(\"main\");\n __velarDomSetAttribute(page, \"data-velar-not-found\", \"\");\n const title = __velarDomCreateElement(\"h1\");\n __velarDomSetText(title, \"Page not found\");\n const detail = __velarDomCreateElement(\"p\");\n __velarDomSetText(detail, \"No route matches \" + route.path);\n __velarDomAppend(page, title, detail);\n return component(page);\n };\n const render = () => {\n try {\n const path = applicationPath(webLocationField(\"pathname\", __velarBrowserLocationPathname));\n const match = path === null ? null : matchRoute(table.routes, path);\n const context = match?.context ?? { path: path ?? \"/\", params: new Map(), query: queryValues(), hash: routeHash() };\n const next = webUntracked(() => (match ? match.item.component({ route: context }) : (table.fallback ?? notFound)({ route: context })));\n if (!next || !next.__velarComponent) throw new TypeError(\"A VelarScript Router target must render a component\");\n if (active) active.destroy();\n active = next;\n __velarDomReplaceChildren(node, active.node);\n if (mounted) active.__mount();\n } catch (value) {\n const error = __velarNormalizeError(value);\n if (!mounted) throw error;\n const runtime = globalThis[Symbol.for(\"velar.runtime.v1\")];\n if (runtime && typeof runtime.report === \"function\") {\n runtime.report(error, { phase: \"render\", detail: \"router\", component: \"Router\", unhandled: true });\n } else {\n __velarBrowserCallCaptured(__velarBrowserQueueMicrotask, __velarBrowserWindow, [() => { throw error; }], \"queueMicrotask\");\n }\n }\n };\n const changed = () => render();\n let removeRouteListener = null;\n // The routes table is read inside the observer that renders from it, so a\n // table or fallback built from state re-renders the position that shows it.\n // A constant table subscribes to nothing and recomputes nothing.\n const observer = webObserve(() => {\n table = routerTable(props);\n if (node === null) node = __velarDomCreateElement(\"velar-router\");\n render();\n }, \"router\", \"Router\");\n return component(node, () => {\n mounted = true;\n removeRouteListener = subscribeRoute(changed);\n if (active) active.__mount();\n }, () => {\n observer.stop();\n if (removeRouteListener) removeRouteListener();\n if (active) active.destroy(false);\n });\n}\n\nconst linkPropFields = __velarOptionFields([\"to\", \"replace\", \"class\", \"look\", \"children\"]);\n\nfunction linkTarget(props) {\n const to = __velarString(props.to, \"Link target\");\n if (to.length > 2 * 1024 * 1024) throw new RangeError(\"Link targets cannot exceed 2 MiB\");\n requireNavigableTarget(to, \"Link target\");\n const replace = props.replace === undefined ? false : props.replace;\n __velarBool(replace, \"Link replace\");\n const external = isExternal(to);\n return { to, replace, external, href: external ? to : internalHref(to) };\n}\n\n// Which fields a Link carries is fixed where the Link is written, so the record\n// shape is checked once; the values behind those fields are read inside the\n// observer that consumes them, which is what makes '<Link to={path}>' follow\n// the state 'path' holds. 'children' is rendered content owned by the position\n// that shows it, so it is taken once, where that position builds it -- that is\n// why the shape check sits here rather than inside the observer the way Head's\n// does: reading the slot again on every update would build content nothing\n// shows. Behind a live props store both reads answer from the same cached\n// derived value, so the author's prop expression still runs exactly once.\nexport function Link(props) {\n const children = __velarLiveOptions(props, \"Link props\", linkPropFields).children;\n // The anchor is created by the observer's first run, after the target has\n // been checked: a refused target must not leave a browser node behind.\n let node = null;\n let target = null;\n let releaseHost = null;\n const observer = webObserve(() => {\n const next = linkTarget(props);\n if (node === null) node = __velarDomCreateElement(\"a\");\n if (releaseHost) { releaseHost(); releaseHost = null; }\n releaseHost = forwardHost(node, props);\n node.href = next.href;\n target = next;\n }, \"link\", \"Link\");\n try { append(node, children); }\n catch (failure) { observer.stop(); if (releaseHost) releaseHost(); throw failure; }\n const clicked = (event) => {\n try {\n const defaultPrevented = webEventField(event, \"defaultPrevented\", webEventDefaultPrevented);\n const button = webEventField(event, \"button\", webEventButton);\n const metaKey = webEventField(event, \"metaKey\", webEventMetaKey);\n const ctrlKey = webEventField(event, \"ctrlKey\", webEventCtrlKey);\n const shiftKey = webEventField(event, \"shiftKey\", webEventShiftKey);\n const altKey = webEventField(event, \"altKey\", webEventAltKey);\n if (defaultPrevented === webEventMissingField || button === webEventMissingField || metaKey === webEventMissingField\n || ctrlKey === webEventMissingField || shiftKey === webEventMissingField || altKey === webEventMissingField\n || typeof defaultPrevented !== \"boolean\" || !Number.isSafeInteger(button)\n || typeof metaKey !== \"boolean\" || typeof ctrlKey !== \"boolean\" || typeof shiftKey !== \"boolean\" || typeof altKey !== \"boolean\") {\n throw new TypeError(\"Link received an invalid click event\");\n }\n if (defaultPrevented || button !== 0 || metaKey || ctrlKey || shiftKey || altKey) return;\n if (target.external) return;\n if (webUrlField(webUrl(node.href, webLocationField(\"href\", __velarBrowserLocationHref)), \"origin\", __velarBrowserUrlOrigin)\n !== webLocationField(\"origin\", __velarBrowserLocationOrigin)) return;\n webEventCall(event, \"preventDefault\", webEventPreventDefault);\n navigate(target.to, { replace: target.replace });\n } catch (failure) { reportLinkEventFailure(failure); }\n };\n let removeClick = null;\n return component(node, () => { removeClick = __velarBrowserListen(node, \"click\", clicked); }, () => {\n observer.stop();\n if (removeClick) removeClick();\n if (releaseHost) releaseHost();\n });\n}\n\nconst navLinkPropFields = __velarOptionFields([\"to\", \"exact\", \"replace\", \"class\", \"look\", \"children\"]);\n\nfunction navLinkTarget(props) {\n const to = __velarString(props.to, \"NavLink target\");\n requireNavigableTarget(to, \"NavLink target\");\n const exact = props.exact === undefined ? false : props.exact;\n const replace = props.replace === undefined ? false : props.replace;\n __velarBool(exact, \"NavLink exact\");\n __velarBool(replace, \"NavLink replace\");\n internalHref(to);\n return { exact, path: normalizeApplicationPath(webUrlField(webUrl(to, \"https://velar.invalid\"), \"pathname\", __velarBrowserUrlPathname)) };\n}\n\nexport function NavLink(props) {\n const children = __velarLiveOptions(props, \"NavLink props\", navLinkPropFields).children;\n let linked = null;\n let target = null;\n const update = () => {\n const application = applicationPath(webLocationField(\"pathname\", __velarBrowserLocationPathname));\n const current = application === null ? null : normalizeApplicationPath(application);\n const active = current !== null\n && (current === target.path || (!target.exact && target.path !== \"/\" && current.startsWith(target.path + \"/\")));\n if (active) __velarDomSetAttribute(linked.node, \"aria-current\", \"page\");\n else __velarDomRemoveAttribute(linked.node, \"aria-current\");\n };\n // A NavLink rejects its own target before the Link it wraps sees it, so the\n // observer runs first and the message names NavLink. Its first run has no\n // Link to mark yet; the update below is that run's second half.\n const observer = webObserve(() => {\n target = navLinkTarget(props);\n if (linked !== null) update();\n }, \"navlink\", \"NavLink\");\n // The Link is handed the same live fields, not a copy of their values, so a\n // NavLink built from state moves its href as well as its aria-current.\n let removeRouteListener = null;\n try {\n linked = Link({\n get to() { return props.to; },\n get replace() { return props.replace; },\n get class() { return props.class; },\n get look() { return props.look; },\n children,\n });\n update();\n } catch (failure) {\n observer.stop();\n if (linked) linked.destroy(false);\n throw failure;\n }\n return component(linked.node, () => {\n linked.__mount();\n removeRouteListener = subscribeRoute(update);\n }, () => {\n observer.stop();\n if (removeRouteListener) removeRouteListener();\n linked.destroy(false);\n });\n}\n\nfunction forwardHost(node, props) {\n const cleanups = [];\n if (props.class != null) {\n if (typeof props.class !== \"string\") throw new TypeError(\"Link class must be a string\");\n const names = props.class.split(/\\s+/).filter(Boolean);\n node.classList.add(...names);\n cleanups.push(() => node.classList.remove(...names));\n }\n if (props.look != null) {\n const runtime = globalThis[Symbol.for(\"velar.runtime.v1\")];\n if (!runtime || typeof runtime.applyLook !== \"function\") throw new TypeError(\"Link Look requires the VelarScript Web runtime\");\n cleanups.push(runtime.applyLook(node, props.look));\n }\n return () => { for (const cleanup of cleanups.reverse()) cleanup(); };\n}\n\nfunction normalizeApplicationPath(path) {\n return path.length > 1 ? path.replace(/\\/+$/u, \"\") : \"/\";\n}\n\nfunction matchRoute(routes, pathname) {\n for (const item of routes) {\n const result = item.matcher.pattern.exec(pathname);\n if (!result) continue;\n const params = new Map();\n let decodable = true;\n for (const [index, name] of item.matcher.names.entries()) {\n try { params.set(name, decodeURIComponent(result[index + 1] ?? \"\")); }\n catch { decodable = false; break; }\n }\n if (!decodable) continue;\n return { item, context: { path: pathname, params, query: queryValues(), hash: routeHash() } };\n }\n return null;\n}\n\nfunction applicationPath(pathname) {\n if (typeof pathname !== \"string\" || pathname.length > 2 * 1024 * 1024) throw new RangeError(\"Application paths cannot exceed 2 MiB\");\n if (appBase === \"/\") return pathname;\n const prefix = appBase.slice(0, -1);\n if (pathname === prefix) return \"/\";\n return pathname.startsWith(appBase) ? \"/\" + pathname.slice(appBase.length) : null;\n}\n\nfunction internalHref(to) {\n if (typeof to !== \"string\" || !to.startsWith(\"/\") || isExternal(to)) throw new TypeError(\"VelarScript navigation targets must be application paths starting with '/'\");\n if (to.length > 2 * 1024 * 1024) throw new RangeError(\"VelarScript navigation targets cannot exceed 2 MiB\");\n const parsed = webUrl(to, \"https://velar.invalid\");\n const pathname = webUrlField(parsed, \"pathname\", __velarBrowserUrlPathname);\n const search = webUrlField(parsed, \"search\", __velarBrowserUrlSearch);\n const hash = webUrlField(parsed, \"hash\", __velarBrowserUrlHash);\n return appBase + pathname.slice(1) + search + hash;\n}\n\nfunction isExternal(to) {\n return typeof to === \"string\" && (/^[a-z][a-z\\d+.-]*:/i.test(to) || to.startsWith(\"//\"));\n}\n\n// The scheme policy a JSX URL attribute enforces, narrowed to what a Link is\n// for. 'javascript:' and 'vbscript:' are code, not locations: a Link classified\n// one as external, wrote it to node.href, and its click handler then let native\n// anchor activation run it. Only the two schemes a page can be served over are\n// navigation targets; anything else belongs to a plain <a> element.\nconst navigableSchemes = [\"http\", \"https\"];\nfunction targetScheme(to) {\n let scheme = \"\";\n for (let index = 0; index < to.length; index += 1) {\n const code = to.charCodeAt(index);\n // The user agent strips ASCII whitespace and control characters before it\n // parses the scheme, so \"java\\tscript:\" reads as \"javascript:\" to it and\n // has to read that way here too.\n if (code <= 0x20 || code === 0x7f) continue;\n if (code === 58 && scheme.length > 0) return scheme.toLowerCase();\n const letter = (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n if (letter || (scheme.length > 0 && ((code >= 48 && code <= 57) || code === 43 || code === 45 || code === 46))) {\n scheme += to[index];\n continue;\n }\n // Anything else this early means the value names no scheme: it is a\n // relative path, which is always the application's own origin.\n return \"\";\n }\n return \"\";\n}\nfunction requireNavigableTarget(to, label) {\n const scheme = targetScheme(to);\n if (scheme !== \"\" && !navigableSchemes.includes(scheme)) {\n throw new TypeError(label + \" rejected the '\" + scheme + \":' URL scheme; only http and https targets navigate, so write a plain <a> element for another scheme\");\n }\n return to;\n}\n\nfunction queryValues() {\n const search = webLocationField(\"search\", __velarBrowserLocationSearch);\n if (typeof search !== \"string\") throw new TypeError(\"Route queries require browser text\");\n if (search.length > 2 * 1024 * 1024) throw new RangeError(\"Route queries cannot exceed 2 MiB\");\n const output = new Map();\n let count = 0;\n if (typeof __velarBrowserUrlSearchParamsConstructor !== \"function\" || typeof __velarBrowserUrlSearchParamsForEach !== \"function\") {\n throw new TypeError(\"The browser URLSearchParams API is unavailable\");\n }\n const params = new __velarBrowserUrlSearchParamsConstructor(search);\n __velarBrowserCallCaptured(__velarBrowserUrlSearchParamsForEach, params, [(value, name) => {\n count += 1;\n if (count > 100000) throw new RangeError(\"Route queries cannot exceed 100000 fields\");\n output.set(name, value);\n }], \"URLSearchParams.forEach\");\n return output;\n}\n\nfunction routeHash() {\n const hash = webLocationField(\"hash\", __velarBrowserLocationHash);\n if (typeof hash !== \"string\") throw new TypeError(\"Route hashes require browser text\");\n if (hash.length > 2 * 1024 * 1024) throw new RangeError(\"Route hashes cannot exceed 2 MiB\");\n return hash;\n}\n" + "function component(node, mounted, cleanup) {\n let destroyed = false;\n let ready = false;\n return {\n __velarComponent: true,\n node,\n mount(target, before = null) {\n if (destroyed) throw new Error(\"Cannot mount a destroyed VelarScript component\");\n if (ready) throw new Error(\"Cannot mount a VelarScript component more than once\");\n const parent = typeof target === \"string\" ? __velarDomQuerySelector(target) : target;\n if (!parent) throw new Error(\"VelarScript mount target was not found\");\n __velarDomInsertBefore(parent, node, before);\n this.__mount();\n return null;\n },\n __mount() { if (!destroyed && !ready) { ready = true; if (mounted) mounted(); } },\n destroy(remove = true) { if (!destroyed) { destroyed = true; if (cleanup) cleanup(); if (remove) __velarDomRemove(node); } return null; },\n };\n}\n\nfunction append(parent, value, state = null) {\n state ??= { active: __velarDomCreateSet(), depth: 0, values: 0, text: 0 };\n if (value == null || value === false || value === true) return;\n state.values += 1;\n if (state.values > 1000000) throw new RangeError(\"JSX cannot render more than 1000000 values\");\n if (typeof value === \"string\") {\n state.text += value.length;\n if (state.text > 16 * 1024 * 1024) throw new RangeError(\"JSX text cannot exceed 16 MiB\");\n __velarDomAppend(parent, __velarDomCreateTextNode(value));\n return;\n }\n if (typeof value === \"number\") {\n if (!__velarDomIsFinite(value)) throw new TypeError(\"JSX numbers must be finite\");\n __velarDomAppend(parent, __velarDomCreateTextNode(__velarDomString(value)));\n return;\n }\n if (__velarDomIsNode(value)) { __velarDomAppend(parent, value); return; }\n if (__velarDomIsArray(value)) {\n if (state.depth >= 128) throw new RangeError(\"JSX Lists cannot exceed 128 nested levels\");\n if (__velarDomSetContains(state.active, value)) throw new TypeError(\"JSX cannot render a cyclic List\");\n const values = __velarRequireList(value, \"JSX children\");\n __velarDomSetInsert(state.active, value);\n state.depth += 1;\n try { for (const item of values) append(parent, item, state); }\n finally { state.depth -= 1; __velarDomSetRemove(state.active, value); }\n return;\n }\n throw new TypeError(\"JSX can render only text, finite numbers, bool, enums, WebNode values, and Lists of those values\");\n}\n";
|
|
76
76
|
export const WEB_FORMS_MODULE = WEB_LIST_GUARD_RUNTIME + "\n" + WEB_OPTIONS_GUARD_RUNTIME + "\n" + VELAR_TYPE_REGISTRY_RUNTIME + "\n" + "const NativeFormElement = typeof globalThis.HTMLFormElement === \"function\" ? globalThis.HTMLFormElement : null;\nconst NativeFormData = typeof globalThis.FormData === \"function\" ? globalThis.FormData : null;\nconst NativeFormMap = typeof globalThis.Map === \"function\" ? globalThis.Map : null;\nconst NativeFormWeakMap = typeof globalThis.WeakMap === \"function\" ? globalThis.WeakMap : null;\nconst NativeFormNumber = typeof globalThis.Number === \"function\" ? globalThis.Number : null;\nconst NativeFormNode = typeof globalThis.Node === \"function\" ? globalThis.Node : null;\nconst NativeFormElementBase = typeof globalThis.Element === \"function\" ? globalThis.Element : null;\nconst NativeFormHtmlElement = typeof globalThis.HTMLElement === \"function\" ? globalThis.HTMLElement : null;\nconst NativeFormDocumentConstructor = typeof globalThis.Document === \"function\" ? globalThis.Document : null;\nconst NativeFormDocument = globalThis.document ?? null;\nconst NativeFormHtmlCollection = typeof globalThis.HTMLCollection === \"function\" ? globalThis.HTMLCollection : null;\nconst NativeFormNodeList = typeof globalThis.NodeList === \"function\" ? globalThis.NodeList : null;\nconst NativeFormInput = typeof globalThis.HTMLInputElement === \"function\" ? globalThis.HTMLInputElement : null;\nconst NativeFormButton = typeof globalThis.HTMLButtonElement === \"function\" ? globalThis.HTMLButtonElement : null;\nconst NativeFormSelect = typeof globalThis.HTMLSelectElement === \"function\" ? globalThis.HTMLSelectElement : null;\nconst NativeFormTextArea = typeof globalThis.HTMLTextAreaElement === \"function\" ? globalThis.HTMLTextAreaElement : null;\nconst NativeFormFieldSet = typeof globalThis.HTMLFieldSetElement === \"function\" ? globalThis.HTMLFieldSetElement : null;\nconst NativeFormOptGroup = typeof globalThis.HTMLOptGroupElement === \"function\" ? globalThis.HTMLOptGroupElement : null;\nconst NativeFormOption = typeof globalThis.HTMLOptionElement === \"function\" ? globalThis.HTMLOptionElement : null;\nconst formReflectApply = Object.getOwnPropertyDescriptor(Reflect, \"apply\")?.value;\nconst formHasInstance = Object.getOwnPropertyDescriptor(Function.prototype, Symbol.hasInstance)?.value;\nconst formGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor(Object, \"getOwnPropertyDescriptor\")?.value;\nconst formDefineProperty = Object.getOwnPropertyDescriptor(Object, \"defineProperty\")?.value;\nconst formDataGet = typeof NativeFormData === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormData.prototype, \"get\")?.value : null;\nconst formDataGetAll = typeof NativeFormData === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormData.prototype, \"getAll\")?.value : null;\nconst formDataHas = typeof NativeFormData === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormData.prototype, \"has\")?.value : null;\nconst formDataForEach = typeof NativeFormData === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormData.prototype, \"forEach\")?.value : null;\nconst formMapGet = typeof NativeFormMap === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormMap.prototype, \"get\")?.value : null;\nconst formMapHas = typeof NativeFormMap === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormMap.prototype, \"has\")?.value : null;\nconst formMapSet = typeof NativeFormMap === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormMap.prototype, \"set\")?.value : null;\nconst formWeakMapGet = typeof NativeFormWeakMap === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormWeakMap.prototype, \"get\")?.value : null;\nconst formWeakMapHas = typeof NativeFormWeakMap === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormWeakMap.prototype, \"has\")?.value : null;\nconst formWeakMapSet = typeof NativeFormWeakMap === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormWeakMap.prototype, \"set\")?.value : null;\nconst formWeakMapDelete = typeof NativeFormWeakMap === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormWeakMap.prototype, \"delete\")?.value : null;\nconst formStringTrim = Object.getOwnPropertyDescriptor(String.prototype, \"trim\")?.value;\nconst formRegexTest = Object.getOwnPropertyDescriptor(RegExp.prototype, \"test\")?.value;\nconst formRegexSplit = Object.getOwnPropertyDescriptor(RegExp.prototype, Symbol.split)?.value;\nconst formArrayJoin = Object.getOwnPropertyDescriptor(Array.prototype, \"join\")?.value;\nconst formNumberIsFinite = Object.getOwnPropertyDescriptor(Number, \"isFinite\")?.value;\nconst formNumberIsSafeInteger = Object.getOwnPropertyDescriptor(Number, \"isSafeInteger\")?.value;\nconst formElementOwner = NativeFormElementBase ?? NativeFormElement;\nconst formHtmlOwner = NativeFormHtmlElement ?? NativeFormElement;\nconst formDocumentCreateElement = typeof NativeFormDocumentConstructor === \"function\"\n ? Object.getOwnPropertyDescriptor(NativeFormDocumentConstructor.prototype, \"createElement\")?.value\n : NativeFormDocument && typeof NativeFormDocument === \"object\" ? Object.getOwnPropertyDescriptor(NativeFormDocument, \"createElement\")?.value : null;\nconst formElementGetAttribute = typeof formElementOwner === \"function\" ? Object.getOwnPropertyDescriptor(formElementOwner.prototype, \"getAttribute\")?.value : null;\nconst formElementSetAttribute = typeof formElementOwner === \"function\" ? Object.getOwnPropertyDescriptor(formElementOwner.prototype, \"setAttribute\")?.value : null;\nconst formElementRemoveAttribute = typeof formElementOwner === \"function\" ? Object.getOwnPropertyDescriptor(formElementOwner.prototype, \"removeAttribute\")?.value : null;\nconst formElementInsertAdjacentElement = typeof formElementOwner === \"function\" ? Object.getOwnPropertyDescriptor(formElementOwner.prototype, \"insertAdjacentElement\")?.value : null;\nconst formElementRemove = typeof formElementOwner === \"function\" ? Object.getOwnPropertyDescriptor(formElementOwner.prototype, \"remove\")?.value : null;\nconst formElementQuerySelector = typeof formElementOwner === \"function\"\n ? Object.getOwnPropertyDescriptor(formElementOwner.prototype, \"querySelector\")?.value ?? Object.getOwnPropertyDescriptor(NativeFormElement?.prototype ?? {}, \"querySelector\")?.value : null;\nconst formElementQuerySelectorAll = typeof formElementOwner === \"function\"\n ? Object.getOwnPropertyDescriptor(formElementOwner.prototype, \"querySelectorAll\")?.value ?? Object.getOwnPropertyDescriptor(NativeFormElement?.prototype ?? {}, \"querySelectorAll\")?.value : null;\nconst formHtmlFocus = typeof formHtmlOwner === \"function\" ? Object.getOwnPropertyDescriptor(formHtmlOwner.prototype, \"focus\")?.value : null;\nconst formNativeReset = typeof NativeFormElement === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormElement.prototype, \"reset\")?.value : null;\nconst formElementsGet = typeof NativeFormElement === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormElement.prototype, \"elements\")?.get : null;\nconst formCollectionLengthGet = typeof NativeFormHtmlCollection === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormHtmlCollection.prototype, \"length\")?.get : null;\nconst formCollectionItem = typeof NativeFormHtmlCollection === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormHtmlCollection.prototype, \"item\")?.value : null;\nconst formNodeListLengthGet = typeof NativeFormNodeList === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormNodeList.prototype, \"length\")?.get : null;\nconst formNodeListItem = typeof NativeFormNodeList === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormNodeList.prototype, \"item\")?.value : null;\nconst formNodeTextContent = typeof NativeFormNode === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormNode.prototype, \"textContent\") : null;\nconst formElementId = typeof formElementOwner === \"function\" ? Object.getOwnPropertyDescriptor(formElementOwner.prototype, \"id\") : null;\nconst formControlContracts = [\n NativeFormInput, NativeFormButton, NativeFormSelect, NativeFormTextArea, NativeFormFieldSet, NativeFormOptGroup, NativeFormOption,\n].map((constructor) => constructor && typeof constructor === \"function\" ? {\n constructor,\n name: Object.getOwnPropertyDescriptor(constructor.prototype, \"name\") ?? null,\n disabled: Object.getOwnPropertyDescriptor(constructor.prototype, \"disabled\") ?? null,\n} : null);\nlet nextErrorId = 1;\nconst pendingFields = typeof NativeFormWeakMap === \"function\" ? new NativeFormWeakMap() : null;\nconst maxFormFields = 100000;\nconst maxFormTextCodeUnits = 16 * 1024 * 1024;\nfunction formText(value, name, maximum = 1024) { value = __velarString(value, name); if (value.length > maximum) throw new RangeError(name + \" is too long\"); return value; }\nfunction formCall(operation, receiver, arguments_, name) {\n if (typeof operation !== \"function\" || typeof formReflectApply !== \"function\") {\n throw new TypeError(\"The browser does not expose native \" + name);\n }\n return formReflectApply(operation, receiver, arguments_);\n}\nfunction formInstance(constructor, value) {\n if (typeof constructor !== \"function\" || typeof formHasInstance !== \"function\" || typeof formReflectApply !== \"function\") return false;\n try { return formReflectApply(formHasInstance, constructor, [value]); } catch { return false; }\n}\nfunction formOwnDescriptor(value, name) {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null\n || typeof formGetOwnPropertyDescriptor !== \"function\" || typeof formReflectApply !== \"function\") return null;\n return formReflectApply(formGetOwnPropertyDescriptor, __velarOptionsNativeObject, [value, name]);\n}\nfunction formHostMethod(operation, owner, receiver, arguments_, name) {\n if (formInstance(owner, receiver)) return formCall(operation, receiver, arguments_, name);\n const descriptor = formOwnDescriptor(receiver, name);\n if (descriptor?.enumerable && \"value\" in descriptor && typeof descriptor.value === \"function\") {\n return formCall(descriptor.value, receiver, arguments_, name);\n }\n throw new TypeError(\"The browser does not expose native \" + name);\n}\nfunction formHostRead(descriptor, owner, receiver, name) {\n if (formInstance(owner, receiver) && typeof descriptor?.get === \"function\") return formCall(descriptor.get, receiver, [], name);\n const own = formOwnDescriptor(receiver, name);\n if (own?.enumerable && \"value\" in own) return own.value;\n throw new TypeError(\"The browser does not expose a data-only \" + name);\n}\nfunction formHostWrite(descriptor, owner, receiver, name, value) {\n if (formInstance(owner, receiver) && typeof descriptor?.set === \"function\") {\n formCall(descriptor.set, receiver, [value], name);\n return;\n }\n const own = formOwnDescriptor(receiver, name);\n if (!own?.enumerable || !(\"value\" in own) || !own.writable || typeof formDefineProperty !== \"function\") {\n throw new TypeError(\"The browser does not expose a writable data-only \" + name);\n }\n formReflectApply(formDefineProperty, __velarOptionsNativeObject, [receiver, name, {...own, value}]);\n}\nfunction formControlContract(value, field, writing = false) {\n for (let index = 0; index < formControlContracts.length; index += 1) {\n const contract = formControlContracts[index];\n if (!contract || !formInstance(contract.constructor, value)) continue;\n const descriptor = contract[field];\n if (writing ? typeof descriptor?.set === \"function\" : typeof descriptor?.get === \"function\") return [contract.constructor, descriptor];\n throw new TypeError(\"The browser form control does not expose native \" + field);\n }\n return [null, null];\n}\nfunction formControlRead(value, field) {\n const [owner, descriptor] = formControlContract(value, field, false);\n return formHostRead(descriptor, owner, value, field);\n}\nfunction formControlWrite(value, field, item) {\n const [owner, descriptor] = formControlContract(value, field, true);\n formHostWrite(descriptor, owner, value, field, item);\n}\nfunction formSnapshotCollection(value, name, maximum) {\n if (__velarListReflectApply(__velarListArrayIsArray, __velarListNativeArray, [value])) {\n const output = __velarRequireList(value, name);\n if (output.length > maximum) throw new RangeError(name + \" cannot exceed \" + maximum + \" items\");\n return output;\n }\n let count;\n let itemOperation;\n if (formInstance(NativeFormHtmlCollection, value)) {\n count = formCall(formCollectionLengthGet, value, [], \"HTMLCollection.length\");\n itemOperation = formCollectionItem;\n } else if (formInstance(NativeFormNodeList, value)) {\n count = formCall(formNodeListLengthGet, value, [], \"NodeList.length\");\n itemOperation = formNodeListItem;\n } else {\n const length = formOwnDescriptor(value, \"length\");\n if (!length?.enumerable || !(\"value\" in length)) throw new TypeError(name + \" requires a bounded data-only collection\");\n count = length.value;\n }\n if (typeof formNumberIsSafeInteger !== \"function\" || !formReflectApply(formNumberIsSafeInteger, NativeFormNumber, [count]) || count < 0) {\n throw new TypeError(name + \" has an invalid length\");\n }\n if (count > maximum) throw new RangeError(name + \" cannot exceed \" + maximum + \" items\");\n const output = new __velarListNativeArray(count);\n for (let index = 0; index < count; index += 1) {\n let item;\n if (typeof itemOperation === \"function\") item = formCall(itemOperation, value, [index], name + \".item\");\n else {\n const descriptor = formOwnDescriptor(value, index);\n if (!descriptor?.enumerable || !(\"value\" in descriptor)) throw new TypeError(name + \" requires data-only indexed values\");\n item = descriptor.value;\n }\n formListSet(output, index, item);\n }\n return output;\n}\nfunction formGetAttribute(element, name) { return formHostMethod(formElementGetAttribute, formElementOwner, element, [name], \"getAttribute\"); }\nfunction formSetAttribute(element, name, value) { return formHostMethod(formElementSetAttribute, formElementOwner, element, [name, value], \"setAttribute\"); }\nfunction formRemoveAttribute(element, name) { return formHostMethod(formElementRemoveAttribute, formElementOwner, element, [name], \"removeAttribute\"); }\nfunction formAttributeTokens(value) {\n value = formText(value, \"Form accessibility metadata\", 65536);\n if (!value) return new __velarListNativeArray();\n const raw = formCall(formRegexSplit, /\\s+/u, [value], \"RegExp split\");\n const input = __velarRequireList(raw, \"Form accessibility metadata tokens\");\n const output = new __velarListNativeArray();\n const seen = typeof NativeFormMap === \"function\" ? new NativeFormMap() : null;\n if (!seen) throw new TypeError(\"The browser Map API is unavailable\");\n for (let index = 0; index < input.length; index += 1) {\n const token = input[index];\n if (!token || formCall(formMapHas, seen, [token], \"Map.has\")) continue;\n formCall(formMapSet, seen, [token, true], \"Map.set\");\n formListSet(output, output.length, token);\n }\n return output;\n}\nfunction formJoinTokens(tokens) { return formCall(formArrayJoin, tokens, [\" \"], \"Array.join\"); }\nfunction formData(form) {\n if (typeof NativeFormData !== \"function\") throw new TypeError(\"The browser FormData API is unavailable\");\n return new NativeFormData(form);\n}\nfunction formListSet(values, index, value) {\n __velarListReflectApply(__velarListDefineProperty, __velarListNativeObject, [values, index, {\n value, enumerable: true, configurable: true, writable: true,\n }]);\n}\nfunction formNumber(value) {\n if (typeof value !== \"string\") return null;\n if (typeof NativeFormNumber !== \"function\" || typeof formNumberIsFinite !== \"function\") {\n throw new TypeError(\"The browser number parsing intrinsics are unavailable\");\n }\n const text = formCall(formStringTrim, value, [], \"String.trim\");\n if (!formCall(formRegexTest, /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/u, [text], \"RegExp.test\")) return null;\n const number = formReflectApply(NativeFormNumber, undefined, [text]);\n return formReflectApply(formNumberIsFinite, NativeFormNumber, [number]) ? number : null;\n}\nfunction formValue(value, name) {\n if (typeof value === \"string\" && value.length > maxFormTextCodeUnits) throw new RangeError(name + \" cannot exceed 16 MiB\");\n return value;\n}\nfunction formList(values, name) {\n const output = __velarRequireList(values, name);\n if (output.length > maxFormFields) throw new RangeError(name + \" cannot exceed 100000 values\");\n return output;\n}\nfunction formElements(form) {\n const elements = formHostRead({get: formElementsGet}, NativeFormElement, form, \"elements\");\n return formSnapshotCollection(elements, \"Form controls\", maxFormFields);\n}\nfunction formErrorNodes(form) {\n const nodes = formHostMethod(formElementQuerySelectorAll, formElementOwner, form, [\"[data-velar-field-error]\"], \"querySelectorAll\");\n return formSnapshotCollection(nodes, \"Form field errors\", maxFormFields);\n}\nfunction formType(value) { return __velarRequireRuntimeType(value, \"Form reading\"); }\nfunction decoderField(value) {\n value = __velarOptions(value, \"Form decoder field\", __velarOptionFields([\"name\", \"kind\", \"optional\", \"enumValues\"]));\n const name = formText(value.name, \"Form decoder field name\");\n const kind = formText(value.kind, \"Form decoder field kind\", 64);\n if (kind !== \"string\" && kind !== \"number\" && kind !== \"bool\" && kind !== \"enum\" && kind !== \"strings\") {\n throw new TypeError(\"Form decoder field '\" + name + \"' uses an unsupported decoder\");\n }\n if (typeof value.optional !== \"boolean\") throw new TypeError(\"Form decoder optional must be bool\");\n let enumValues = null;\n if (kind === \"enum\") {\n enumValues = __velarRequireList(value.enumValues, \"Form enum values\");\n if (enumValues.length > maxFormFields) throw new RangeError(\"Form enum values cannot exceed 100000 entries\");\n for (let index = 0; index < enumValues.length; index += 1) {\n if (typeof enumValues[index] !== \"string\") throw new TypeError(\"Form enum values must be strings\");\n }\n } else if (value.enumValues != null) {\n throw new TypeError(\"Only enum form decoders can declare enum values\");\n }\n return __velarFreezeOptionsValue({ name, kind, optional: value.optional, enumValues });\n}\n\nexport function values(form) {\n requireForm(form);\n if (typeof NativeFormMap !== \"function\") throw new TypeError(\"The browser Map API is unavailable\");\n const output = new NativeFormMap();\n let count = 0;\n const data = formData(form);\n formCall(formDataForEach, data, [(value, name) => {\n count += 1;\n if (count > maxFormFields) throw new RangeError(\"Forms cannot exceed 100000 submitted fields\");\n const checkedName = formText(name, \"Submitted form field name\");\n formValue(value, \"Form field '\" + checkedName + \"'\");\n if (!formCall(formMapHas, output, [checkedName], \"Map.has\")) formCall(formMapSet, output, [checkedName, value], \"Map.set\");\n else {\n const current = formCall(formMapGet, output, [checkedName], \"Map.get\");\n if (__velarListReflectApply(__velarListArrayIsArray, __velarListNativeArray, [current])) {\n formListSet(current, current.length, value);\n } else {\n const repeated = new __velarListNativeArray(2);\n formListSet(repeated, 0, current);\n formListSet(repeated, 1, value);\n formCall(formMapSet, output, [checkedName, repeated], \"Map.set\");\n }\n }\n }], \"FormData.forEach\");\n return output;\n}\n\nexport function read(form, type, fields) {\n requireForm(form);\n type = formType(type);\n const decoderItems = __velarRequireList(fields, \"Form decoder fields\");\n if (decoderItems.length > maxFormFields) throw new RangeError(\"Form decoders cannot exceed 100000 fields\");\n fields = decoderItems;\n for (let index = 0; index < fields.length; index += 1) fields[index] = decoderField(fields[index]);\n const data = formData(form);\n const output = __velarOptionsReflectApply(__velarOptionsCreate, __velarOptionsNativeObject, [null]);\n for (let fieldIndex = 0; fieldIndex < fields.length; fieldIndex += 1) {\n const field = fields[fieldIndex];\n const name = field.name;\n const value = formValue(formCall(formDataGet, data, [name], \"FormData.get\"), \"Form field '\" + name + \"'\");\n if (field.kind === \"string\") {\n if (value == null) output[name] = field.optional ? null : \"\";\n else if (typeof value === \"string\") output[name] = value;\n else throw new TypeError(\"Form field '\" + name + \"' is not textual\");\n } else if (field.kind === \"number\") {\n if (value == null || (typeof value === \"string\" && formCall(formStringTrim, value, [], \"String.trim\") === \"\")) {\n if (field.optional) output[name] = null;\n else throw new TypeError(\"Form field '\" + name + \"' requires a finite number\");\n } else {\n const number = formNumber(value);\n if (number === null) throw new TypeError(\"Form field '\" + name + \"' requires a finite decimal number\");\n output[name] = number;\n }\n } else if (field.kind === \"bool\") {\n output[name] = formCall(formDataHas, data, [name], \"FormData.has\");\n } else if (field.kind === \"enum\") {\n if (value == null || value === \"\") {\n if (field.optional) output[name] = null;\n else throw new TypeError(\"Form field '\" + name + \"' requires a known enum value\");\n } else if (typeof value === \"string\") {\n let known = false;\n for (let index = 0; index < field.enumValues.length; index += 1) {\n if (field.enumValues[index] === value) { known = true; break; }\n }\n if (!known) throw new TypeError(\"Form field '\" + name + \"' requires a known enum value\");\n output[name] = value;\n } else {\n throw new TypeError(\"Form field '\" + name + \"' requires a known enum value\");\n }\n } else if (field.kind === \"strings\") {\n const items = formList(formCall(formDataGetAll, data, [name], \"FormData.getAll\"), \"Form field '\" + name + \"'\");\n for (let index = 0; index < items.length; index += 1) {\n const item = items[index];\n formValue(item, \"Form field '\" + name + \"'\");\n if (typeof item !== \"string\") throw new TypeError(\"Form field '\" + name + \"' is not textual\");\n }\n output[name] = items;\n } else {\n throw new TypeError(\"Form field '\" + name + \"' uses an unsupported decoder\");\n }\n }\n return type.parse(output);\n}\n\nexport function fieldValue(form, name) {\n return firstValue(form, name);\n}\n\nexport function textValue(form, name, fallback = \"\") {\n name = formText(name, \"Form field name\");\n fallback = formText(fallback, \"Form text fallback\", maxFormTextCodeUnits);\n const value = firstValue(form, name);\n if (value == null) return fallback;\n if (typeof value !== \"string\") throw new TypeError(\"Form field '\" + name + \"' is not textual\");\n return value;\n}\n\nexport function numberValue(form, name) {\n return formNumber(textValue(form, name));\n}\n\nexport function checkedValue(form, name) {\n requireForm(form);\n name = formText(name, \"Form field name\");\n const data = formData(form);\n return formCall(formDataHas, data, [name], \"FormData.has\");\n}\n\nexport function fieldValues(form, name) {\n requireForm(form);\n name = formText(name, \"Form field name\");\n const data = formData(form);\n const values = formList(formCall(formDataGetAll, data, [name], \"FormData.getAll\"), \"Form field '\" + name + \"'\");\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index];\n formValue(value, \"Form field '\" + name + \"'\");\n if (typeof value !== \"string\") throw new TypeError(\"Form field '\" + name + \"' is not textual\");\n }\n return values;\n}\n\nexport function setError(form, name, message) {\n requireForm(form);\n name = formText(name, \"Form field name\");\n message = formText(message, \"Form error message\", 65536);\n const field = namedField(form, name);\n if (!field) throw new Error(\"Form field '\" + name + \"' was not found\");\n const errorNodes = formErrorNodes(form);\n let error = null;\n for (let index = 0; index < errorNodes.length; index += 1) {\n if (formGetAttribute(errorNodes[index], \"data-velar-field-error\") === name) { error = errorNodes[index]; break; }\n }\n if (!error) {\n error = formHostMethod(formDocumentCreateElement, NativeFormDocumentConstructor, NativeFormDocument, [\"p\"], \"createElement\");\n formHostWrite(formElementId, formElementOwner, error, \"id\", \"velar-field-error-\" + nextErrorId++);\n formSetAttribute(error, \"data-velar-field-error\", name);\n formSetAttribute(error, \"role\", \"alert\");\n formHostMethod(formElementInsertAdjacentElement, formElementOwner, field, [\"afterend\", error], \"insertAdjacentElement\");\n }\n formHostWrite(formNodeTextContent, NativeFormNode, error, \"textContent\", message);\n formSetAttribute(field, \"aria-invalid\", \"true\");\n const described = formAttributeTokens(formGetAttribute(field, \"aria-describedby\") ?? \"\");\n const errorId = formText(formHostRead(formElementId, formElementOwner, error, \"id\"), \"Form error id\");\n let hasErrorId = false;\n for (let index = 0; index < described.length; index += 1) if (described[index] === errorId) { hasErrorId = true; break; }\n if (!hasErrorId) formListSet(described, described.length, errorId);\n formSetAttribute(field, \"aria-describedby\", formJoinTokens(described));\n return null;\n}\n\nexport function clearError(form, name) {\n requireForm(form);\n name = formText(name, \"Form field name\");\n const field = namedField(form, name);\n const errorNodes = formErrorNodes(form);\n const removedIds = typeof NativeFormMap === \"function\" ? new NativeFormMap() : null;\n if (!removedIds) throw new TypeError(\"The browser Map API is unavailable\");\n for (let index = 0; index < errorNodes.length; index += 1) {\n const error = errorNodes[index];\n if (formGetAttribute(error, \"data-velar-field-error\") !== name) continue;\n const errorId = formHostRead(formElementId, formElementOwner, error, \"id\");\n if (typeof errorId === \"string\" && errorId) formCall(formMapSet, removedIds, [errorId, true], \"Map.set\");\n formHostMethod(formElementRemove, formElementOwner, error, [], \"remove\");\n }\n if (field) {\n formRemoveAttribute(field, \"aria-invalid\");\n const described = formAttributeTokens(formGetAttribute(field, \"aria-describedby\") ?? \"\");\n const retained = new __velarListNativeArray();\n for (let index = 0; index < described.length; index += 1) {\n const id = described[index];\n if (!formCall(formMapHas, removedIds, [id], \"Map.has\")) formListSet(retained, retained.length, id);\n }\n if (retained.length) formSetAttribute(field, \"aria-describedby\", formJoinTokens(retained));\n else formRemoveAttribute(field, \"aria-describedby\");\n }\n return null;\n}\n\nexport function clearErrors(form) {\n requireForm(form);\n const nodes = formErrorNodes(form);\n const seen = typeof NativeFormMap === \"function\" ? new NativeFormMap() : null;\n if (!seen) throw new TypeError(\"The browser Map API is unavailable\");\n const names = new __velarListNativeArray();\n for (let index = 0; index < nodes.length; index += 1) {\n const name = formText(formGetAttribute(nodes[index], \"data-velar-field-error\") ?? \"\", \"Form error field name\");\n if (!name || formCall(formMapHas, seen, [name], \"Map.has\")) continue;\n formCall(formMapSet, seen, [name, true], \"Map.set\");\n formListSet(names, names.length, name);\n }\n for (let index = 0; index < names.length; index += 1) clearError(form, names[index]);\n return null;\n}\n\nexport function errors(form) {\n requireForm(form);\n const nodes = formErrorNodes(form);\n const output = typeof NativeFormMap === \"function\" ? new NativeFormMap() : null;\n if (!output) throw new TypeError(\"The browser Map API is unavailable\");\n for (let index = 0; index < nodes.length; index += 1) {\n const item = nodes[index];\n const name = formText(formGetAttribute(item, \"data-velar-field-error\") ?? \"\", \"Form error field name\");\n const message = formText(formHostRead(formNodeTextContent, NativeFormNode, item, \"textContent\") ?? \"\", \"Form error message\", 65536);\n if (name) formCall(formMapSet, output, [name, message], \"Map.set\");\n }\n return output;\n}\n\nexport function focusFirstError(form) {\n requireForm(form);\n const error = formHostMethod(formElementQuerySelector, formElementOwner, form, [\"[data-velar-field-error]\"], \"querySelector\");\n const field = error ? namedField(form, formText(formGetAttribute(error, \"data-velar-field-error\") ?? \"\", \"Form error field name\")) : null;\n if (!field) return false;\n formHostMethod(formHtmlFocus, formHtmlOwner, field, [], \"focus\");\n return true;\n}\n\nexport function setPending(form, pending) {\n requireForm(form);\n if (typeof pending !== \"boolean\") throw new TypeError(\"setPending requires a boolean\");\n if (!pendingFields) throw new TypeError(\"The browser WeakMap API is unavailable\");\n if (pending) {\n const elements = formElements(form);\n const snapshot = new __velarListNativeArray();\n for (let index = 0; index < elements.length; index += 1) {\n const field = elements[index];\n if (!field || typeof field !== \"object\") throw new TypeError(\"Form controls must expose a bool disabled state\");\n const disabled = formControlRead(field, \"disabled\");\n if (typeof disabled !== \"boolean\") throw new TypeError(\"Form controls must expose a bool disabled state\");\n const pair = new __velarListNativeArray(2);\n formListSet(pair, 0, field);\n formListSet(pair, 1, disabled);\n formListSet(snapshot, snapshot.length, pair);\n }\n if (!formCall(formWeakMapHas, pendingFields, [form], \"WeakMap.has\")) formCall(formWeakMapSet, pendingFields, [form, snapshot], \"WeakMap.set\");\n formSetAttribute(form, \"aria-busy\", \"true\");\n for (let index = 0; index < snapshot.length; index += 1) formControlWrite(snapshot[index][0], \"disabled\", true);\n } else {\n formRemoveAttribute(form, \"aria-busy\");\n const snapshot = formCall(formWeakMapGet, pendingFields, [form], \"WeakMap.get\") ?? new __velarListNativeArray();\n for (let index = 0; index < snapshot.length; index += 1) formControlWrite(snapshot[index][0], \"disabled\", snapshot[index][1]);\n formCall(formWeakMapDelete, pendingFields, [form], \"WeakMap.delete\");\n }\n return null;\n}\n\nexport function reset(form) {\n requireForm(form);\n if (!pendingFields) throw new TypeError(\"The browser WeakMap API is unavailable\");\n if (formCall(formWeakMapHas, pendingFields, [form], \"WeakMap.has\")) setPending(form, false);\n clearErrors(form);\n formHostMethod(formNativeReset, NativeFormElement, form, [], \"reset\");\n return null;\n}\n\nfunction namedField(form, name) {\n const elements = formElements(form);\n for (let index = 0; index < elements.length; index += 1) if (formControlRead(elements[index], \"name\") === name) return elements[index];\n return null;\n}\n\nfunction firstValue(form, name) {\n requireForm(form);\n name = formText(name, \"Form field name\");\n const data = formData(form);\n return formValue(formCall(formDataGet, data, [name], \"FormData.get\"), \"Form field '\" + name + \"'\");\n}\n\nfunction requireForm(value) {\n let accepted = false;\n if (typeof NativeFormElement === \"function\" && typeof formHasInstance === \"function\" && typeof formReflectApply === \"function\") {\n try { accepted = formReflectApply(formHasInstance, NativeFormElement, [value]); } catch {}\n }\n if (!accepted) throw new TypeError(\"VelarScript form helpers require a form element\");\n}\n";
|
|
77
77
|
export const WEB_HTTP_MODULE = WEB_LIST_GUARD_RUNTIME + "\n" + WEB_OPTIONS_GUARD_RUNTIME + "\n" + VELAR_STRICT_JSON_RUNTIME + "\n" + VELAR_UTF8_RUNTIME + "\n" + VELAR_TYPE_REGISTRY_RUNTIME + "\n" + WEB_FILE_REGISTRY_RUNTIME + "\n" + "const formBodies = new WeakMap();\nconst nativeFetch = typeof globalThis.fetch === \"function\" ? globalThis.fetch : null;\nconst NativeHeaders = typeof globalThis.Headers === \"function\" ? globalThis.Headers : null;\nconst NativeResponse = typeof globalThis.Response === \"function\" ? globalThis.Response : null;\nconst NativeAbortController = typeof globalThis.AbortController === \"function\" ? globalThis.AbortController : null;\nconst NativeFormData = typeof globalThis.FormData === \"function\" ? globalThis.FormData : null;\nconst NativeBlob = typeof globalThis.Blob === \"function\" ? globalThis.Blob : null;\nconst NativeTextDecoder = typeof globalThis.TextDecoder === \"function\" ? globalThis.TextDecoder : null;\nconst NativeUint8Array = typeof globalThis.Uint8Array === \"function\" ? globalThis.Uint8Array : null;\nconst NativeMap = typeof globalThis.Map === \"function\" ? globalThis.Map : null;\nconst nativeReflectApply = Object.getOwnPropertyDescriptor(Reflect, \"apply\")?.value;\nconst nativeMapSize = Object.getOwnPropertyDescriptor(Map.prototype, \"size\")?.get;\nconst nativeMapGet = Object.getOwnPropertyDescriptor(Map.prototype, \"get\")?.value;\nconst nativeMapHas = Object.getOwnPropertyDescriptor(Map.prototype, \"has\")?.value;\nconst nativeMapSet = Object.getOwnPropertyDescriptor(Map.prototype, \"set\")?.value;\nconst nativeMapForEach = Object.getOwnPropertyDescriptor(Map.prototype, \"forEach\")?.value;\nconst nativeWeakMapGet = Object.getOwnPropertyDescriptor(WeakMap.prototype, \"get\")?.value;\nconst nativeWeakMapSet = Object.getOwnPropertyDescriptor(WeakMap.prototype, \"set\")?.value;\nconst nativeHeadersSet = typeof NativeHeaders === \"function\" ? Object.getOwnPropertyDescriptor(NativeHeaders.prototype, \"set\")?.value : null;\nconst nativeHeadersHas = typeof NativeHeaders === \"function\" ? Object.getOwnPropertyDescriptor(NativeHeaders.prototype, \"has\")?.value : null;\nconst nativeHeadersForEach = typeof NativeHeaders === \"function\" ? Object.getOwnPropertyDescriptor(NativeHeaders.prototype, \"forEach\")?.value : null;\nconst nativeResponseOk = typeof NativeResponse === \"function\" ? Object.getOwnPropertyDescriptor(NativeResponse.prototype, \"ok\")?.get : null;\nconst nativeResponseStatus = typeof NativeResponse === \"function\" ? Object.getOwnPropertyDescriptor(NativeResponse.prototype, \"status\")?.get : null;\nconst nativeResponseStatusText = typeof NativeResponse === \"function\" ? Object.getOwnPropertyDescriptor(NativeResponse.prototype, \"statusText\")?.get : null;\nconst nativeResponseUrl = typeof NativeResponse === \"function\" ? Object.getOwnPropertyDescriptor(NativeResponse.prototype, \"url\")?.get : null;\nconst nativeResponseHeaders = typeof NativeResponse === \"function\" ? Object.getOwnPropertyDescriptor(NativeResponse.prototype, \"headers\")?.get : null;\nconst nativeResponseBody = typeof NativeResponse === \"function\" ? Object.getOwnPropertyDescriptor(NativeResponse.prototype, \"body\")?.get : null;\nconst nativeAbort = typeof NativeAbortController === \"function\" ? Object.getOwnPropertyDescriptor(NativeAbortController.prototype, \"abort\")?.value : null;\nconst nativeAbortSignal = typeof NativeAbortController === \"function\" ? Object.getOwnPropertyDescriptor(NativeAbortController.prototype, \"signal\")?.get : null;\nconst nativeFormAppend = typeof NativeFormData === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormData.prototype, \"append\")?.value : null;\nconst nativeFormDelete = typeof NativeFormData === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormData.prototype, \"delete\")?.value : null;\nconst nativeFormHas = typeof NativeFormData === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormData.prototype, \"has\")?.value : null;\nconst nativeFormGetAll = typeof NativeFormData === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormData.prototype, \"getAll\")?.value : null;\nconst nativeFormForEach = typeof NativeFormData === \"function\" ? Object.getOwnPropertyDescriptor(NativeFormData.prototype, \"forEach\")?.value : null;\nconst nativeTextDecode = typeof NativeTextDecoder === \"function\" ? Object.getOwnPropertyDescriptor(NativeTextDecoder.prototype, \"decode\")?.value : null;\nconst nativeSetTimeout = typeof globalThis.setTimeout === \"function\" ? globalThis.setTimeout : null;\nconst nativeClearTimeout = typeof globalThis.clearTimeout === \"function\" ? globalThis.clearTimeout : null;\nconst nativeStreamGetReader = typeof ReadableStream === \"function\" ? Object.getOwnPropertyDescriptor(ReadableStream.prototype, \"getReader\")?.value : null;\nconst nativeStreamCancel = typeof ReadableStream === \"function\" ? Object.getOwnPropertyDescriptor(ReadableStream.prototype, \"cancel\")?.value : null;\nconst nativeReaderRead = typeof ReadableStreamDefaultReader === \"function\" ? Object.getOwnPropertyDescriptor(ReadableStreamDefaultReader.prototype, \"read\")?.value : null;\nconst nativeReaderCancel = typeof ReadableStreamDefaultReader === \"function\" ? Object.getOwnPropertyDescriptor(ReadableStreamDefaultReader.prototype, \"cancel\")?.value : null;\nconst nativeTypedArrayPrototype = typeof NativeUint8Array === \"function\" ? Object.getPrototypeOf(NativeUint8Array.prototype) : null;\nconst nativeTypedArrayTag = nativeTypedArrayPrototype ? Object.getOwnPropertyDescriptor(nativeTypedArrayPrototype, Symbol.toStringTag)?.get : null;\nconst nativeTypedArrayByteLength = nativeTypedArrayPrototype ? Object.getOwnPropertyDescriptor(nativeTypedArrayPrototype, \"byteLength\")?.get : null;\nconst nativeUint8ArraySet = Object.getOwnPropertyDescriptor(nativeTypedArrayPrototype, \"set\")?.value;\n\nfunction httpBytesKind(value) {\n if (typeof nativeReflectApply !== \"function\" || typeof nativeTypedArrayTag !== \"function\") return null;\n try { return nativeReflectApply(nativeTypedArrayTag, value, []); } catch { return null; }\n}\nconst __velarHttpBytes = Object.freeze({\n is(value) { return httpBytesKind(value) === \"Uint8Array\"; },\n parse(value) {\n if (httpBytesKind(value) !== \"Uint8Array\" || typeof NativeUint8Array !== \"function\"\n || typeof nativeTypedArrayByteLength !== \"function\" || typeof nativeUint8ArraySet !== \"function\") {\n throw new TypeError(\"Bytes requires Uint8Array\");\n }\n const output = new NativeUint8Array(nativeReflectApply(nativeTypedArrayByteLength, value, []));\n nativeReflectApply(nativeUint8ArraySet, output, [value]);\n return output;\n },\n});\n\nfunction runtimeHttpType(Type) { return __velarRequireRuntimeType(Type, \"HTTP parsing\"); }\n\nfunction requireHttpHost() {\n if (typeof nativeFetch !== \"function\" || typeof NativeHeaders !== \"function\" || typeof NativeResponse !== \"function\"\n || typeof NativeAbortController !== \"function\" || typeof NativeFormData !== \"function\" || typeof NativeBlob !== \"function\"\n || typeof NativeTextDecoder !== \"function\" || typeof NativeUint8Array !== \"function\" || typeof NativeMap !== \"function\"\n || typeof nativeReflectApply !== \"function\" || typeof nativeMapSize !== \"function\" || typeof nativeMapGet !== \"function\"\n || typeof nativeMapHas !== \"function\" || typeof nativeMapSet !== \"function\" || typeof nativeMapForEach !== \"function\"\n || typeof nativeWeakMapGet !== \"function\" || typeof nativeWeakMapSet !== \"function\" || typeof nativeHeadersSet !== \"function\"\n || typeof nativeHeadersHas !== \"function\" || typeof nativeHeadersForEach !== \"function\" || typeof nativeResponseOk !== \"function\"\n || typeof nativeResponseStatus !== \"function\" || typeof nativeResponseStatusText !== \"function\" || typeof nativeResponseUrl !== \"function\"\n || typeof nativeResponseHeaders !== \"function\" || typeof nativeResponseBody !== \"function\" || typeof nativeAbort !== \"function\"\n || typeof nativeAbortSignal !== \"function\"\n || typeof nativeFormAppend !== \"function\" || typeof nativeFormDelete !== \"function\" || typeof nativeFormHas !== \"function\"\n || typeof nativeFormGetAll !== \"function\" || typeof nativeFormForEach !== \"function\" || typeof nativeTextDecode !== \"function\"\n || typeof nativeSetTimeout !== \"function\" || typeof nativeClearTimeout !== \"function\") {\n throw new TypeError(\"The Web HTTP host ABI is unavailable\");\n }\n}\n\nfunction headerMap(value) {\n requireHttpHost();\n const output = new NativeHeaders();\n nativeReflectApply(nativeMapForEach, value, [(item, name) => nativeReflectApply(nativeHeadersSet, output, [name, item])]);\n return output;\n}\n\nfunction methodOf(value) {\n const method = __velarString(value, \"HTTP method\").toUpperCase();\n if (method.length > 32) throw new RangeError(\"HTTP methods cannot exceed 32 characters\");\n if (!/^[!#$%&'*+.^_\\x60|~0-9A-Z-]+$/u.test(method) || [\"CONNECT\", \"TRACE\", \"TRACK\"].includes(method)) throw new TypeError(\"HTTP method is invalid or forbidden by Fetch\");\n return method;\n}\n\nfunction headersOf(value) {\n if (value == null) { requireHttpHost(); return new NativeMap(); }\n try { requireHttpHost(); nativeReflectApply(nativeMapSize, value, []); }\n catch { throw new TypeError(\"HTTP headers must be Map<string, string>\"); }\n const headers = new NativeMap();\n let units = 0;\n nativeReflectApply(nativeMapForEach, value, [(item, name) => {\n if (typeof name !== \"string\" || typeof item !== \"string\" || !/^[!#$%&'*+.^_|~0-9A-Za-z-]+$/u.test(name) || /[\\r\\n]/u.test(item)) {\n throw new TypeError(\"HTTP headers must use valid string names and single-line values\");\n }\n units += name.length + item.length;\n if ((!nativeReflectApply(nativeMapHas, headers, [name]) && nativeReflectApply(nativeMapSize, headers, []) >= 100) || units > 65536) throw new RangeError(\"HTTP headers cannot exceed 100 fields or 64 KiB\");\n nativeReflectApply(nativeMapSet, headers, [name, item]);\n }]);\n return headers;\n}\n\nfunction responseHeadersOf(value) {\n requireHttpHost();\n const headers = new NativeMap();\n let units = 0;\n try {\n nativeReflectApply(nativeHeadersForEach, value, [(item, name) => {\n if (typeof name !== \"string\" || typeof item !== \"string\") throw new TypeError(\"HTTP response header names and values must be strings\");\n units += name.length + item.length;\n if ((!nativeReflectApply(nativeMapHas, headers, [name]) && nativeReflectApply(nativeMapSize, headers, []) >= 100) || units > 65536) throw new RangeError(\"HTTP response headers cannot exceed 100 fields or 64 KiB\");\n nativeReflectApply(nativeMapSet, headers, [name, item]);\n }]);\n } catch (error) {\n if (error instanceof RangeError) throw error;\n throw new TypeError(\"HTTP responses require native Headers\");\n }\n return headers;\n}\n\nasync function responseSnapshot(response) {\n let body = null;\n try {\n requireHttpHost();\n const ok = nativeReflectApply(nativeResponseOk, response, []);\n const status = nativeReflectApply(nativeResponseStatus, response, []);\n const statusText = __velarString(nativeReflectApply(nativeResponseStatusText, response, []), \"HTTP response status text\");\n const url = __velarString(nativeReflectApply(nativeResponseUrl, response, []), \"HTTP response URL\");\n const nativeHeaders = nativeReflectApply(nativeResponseHeaders, response, []);\n body = nativeReflectApply(nativeResponseBody, response, []);\n if (typeof ok !== \"boolean\" || !Number.isInteger(status) || status < 100 || status > 599\n || ok !== (status >= 200 && status <= 299)) {\n throw new TypeError(\"Fetch returned invalid HTTP response metadata\");\n }\n if (statusText.length > 65536) throw new RangeError(\"HTTP response status text cannot exceed 64 KiB\");\n if (url.length > 2 * 1024 * 1024) throw new RangeError(\"HTTP response URLs cannot exceed 2 MiB\");\n return {ok, status, statusText, url, headers: responseHeadersOf(nativeHeaders), body};\n } catch (error) {\n if (body !== null && typeof nativeStreamCancel === \"function\") {\n try { await nativeReflectApply(nativeStreamCancel, body, [error]); } catch {}\n }\n throw error;\n }\n}\n\nfunction optionsOf(value) {\n value = __velarOptions(value, \"HTTP options\", __velarOptionFields([\"headers\", \"body\", \"timeout\", \"maxBytes\", \"credentials\", \"cache\"]));\n const timeout = value.timeout ?? 120000;\n if (!Number.isSafeInteger(timeout) || timeout < 0 || timeout > 600000) throw new RangeError(\"HTTP timeout must be an integer from 0 through 600000 milliseconds\");\n const maxBytes = value.maxBytes ?? 16 * 1024 * 1024;\n if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 64 * 1024 * 1024) throw new RangeError(\"HTTP maxBytes must be an integer from 1 through 67108864\");\n const credentials = value.credentials == null ? undefined : __velarString(value.credentials, \"HTTP credentials\");\n if (credentials !== undefined && ![\"omit\", \"same-origin\", \"include\"].includes(credentials)) throw new TypeError(\"HTTP credentials must be omit, same-origin, or include\");\n const cache = value.cache == null ? undefined : __velarString(value.cache, \"HTTP cache mode\");\n if (cache !== undefined && ![\"default\", \"no-store\", \"reload\", \"no-cache\", \"force-cache\"].includes(cache)) throw new TypeError(\"HTTP cache mode must be default, no-store, reload, no-cache, or force-cache\");\n let headers = headersOf(value.headers);\n let body = value.body ?? null;\n const multipart = body && typeof body === \"object\" ? nativeReflectApply(nativeWeakMapGet, formBodies, [body]) : null;\n const nativeForm = typeof NativeFormData === \"function\" && body instanceof NativeFormData;\n const nativeBlob = typeof NativeBlob === \"function\" && body instanceof NativeBlob;\n const bytes = body != null && __velarHttpBytes.is(body);\n if (bytes) body = __velarHttpBytes.parse(body);\n else if (body != null && typeof body !== \"string\" && !multipart && !nativeForm && !nativeBlob) {\n if (typeof body !== \"object\") throw new TypeError(\"HTTP body must be text, JSON data, a Blob, or a VelarScript form body\");\n body = __velarJsonStringify(body);\n let hasContentType = false;\n nativeReflectApply(nativeMapForEach, headers, [(_item, name) => { if (name.toLowerCase() === \"content-type\") hasContentType = true; }]);\n if (!hasContentType) nativeReflectApply(nativeMapSet, headers, [\"content-type\", \"application/json\"]);\n headers = headersOf(headers);\n }\n if (typeof body === \"string\" && __velarUtf8ByteLength(body) > 16 * 1024 * 1024) throw new RangeError(\"HTTP body cannot exceed 16 MiB\");\n return __velarFreezeOptionsValue({ headers, body, timeout, maxBytes, credentials, cache });\n}\n\nfunction fieldName(value) {\n const name = __velarString(value, \"Form body field name\");\n if (!name) throw new TypeError(\"Form body field names cannot be empty\");\n if (name.length > 1024) throw new RangeError(\"Form body field names cannot exceed 1024 characters\");\n return name;\n}\n\nfunction nativeFile(value) {\n return __velarNativeFile(value, \"Form body files must come from velar/files pick()\");\n}\n\nexport function formBody() {\n requireHttpHost();\n const data = new NativeFormData();\n let fieldCount = 0;\n const reserve = (count = 1) => { if (fieldCount + count > 100000) throw new RangeError(\"Form bodies cannot exceed 100000 fields\"); fieldCount += count; };\n const fieldValue = (value) => { value = __velarString(value, \"Form body field value\"); if (__velarUtf8ByteLength(value) > 16 * 1024 * 1024) throw new RangeError(\"Form body field values cannot exceed 16 MiB\"); return value; };\n const body = {\n field(name, value) { name = fieldName(name); value = fieldValue(value); reserve(); nativeReflectApply(nativeFormAppend, data, [name, value]); return null; },\n file(name, value, fileName = \"\") {\n const file = nativeFile(value);\n fileName = __velarString(fileName, \"Form body file name\");\n if (fileName.length > 4096) throw new RangeError(\"Form body file names cannot exceed 4096 characters\");\n name = fieldName(name);\n reserve();\n if (fileName) nativeReflectApply(nativeFormAppend, data, [name, file, fileName]);\n else nativeReflectApply(nativeFormAppend, data, [name, file]);\n return null;\n },\n files(name, values) {\n name = fieldName(name);\n const input = __velarRequireList(values, \"Form body files\");\n const files = new __velarListNativeArray(input.length);\n for (let index = 0; index < input.length; index += 1) {\n __velarListReflectApply(__velarListDefineProperty, __velarListNativeObject, [files, index, {\n value: nativeFile(input[index]), enumerable: true, configurable: true, writable: true,\n }]);\n }\n reserve(files.length);\n for (let index = 0; index < files.length; index += 1) nativeReflectApply(nativeFormAppend, data, [name, files[index]]);\n return null;\n },\n remove(name) { name = fieldName(name); fieldCount -= nativeReflectApply(nativeFormGetAll, data, [name]).length; nativeReflectApply(nativeFormDelete, data, [name]); return null; },\n has(name) { return nativeReflectApply(nativeFormHas, data, [fieldName(name)]); },\n names() {\n const names = new __velarListNativeArray();\n const seen = new NativeMap();\n nativeReflectApply(nativeFormForEach, data, [(_value, name) => {\n if (nativeReflectApply(nativeMapHas, seen, [name])) return;\n const index = nativeReflectApply(nativeMapSize, seen, []);\n nativeReflectApply(nativeMapSet, seen, [name, true]);\n __velarListReflectApply(__velarListDefineProperty, __velarListNativeObject, [names, index, {\n value: name, enumerable: true, configurable: true, writable: true,\n }]);\n }]);\n return names;\n },\n };\n nativeReflectApply(nativeWeakMapSet, formBodies, [body, data]);\n return __velarFreezeOptionsValue(body);\n}\n\nexport class HttpResponseError extends Error {\n constructor(message, status, url, body = null) {\n message = __velarString(message, \"HTTP error message\");\n url = __velarString(url, \"HTTP error URL\");\n if (message.length > 65536) throw new RangeError(\"HTTP error messages cannot exceed 64 KiB\");\n if (url.length > 2 * 1024 * 1024) throw new RangeError(\"HTTP error URLs cannot exceed 2 MiB\");\n if (!Number.isInteger(status) || status < 100 || status > 599) throw new RangeError(\"HTTP error status must be an integer from 100 through 599\");\n super(message);\n this.name = \"HttpResponseError\";\n this.status = status;\n this.url = url;\n this.body = body;\n }\n}\n\nexport class HttpAbortError extends Error {\n constructor(reason) {\n if (reason !== \"cancelled\" && reason !== \"timeout\") throw new TypeError(\"HTTP abort reason must be cancelled or timeout\");\n super(reason === \"timeout\" ? \"HTTP request timed out\" : \"HTTP request cancelled\");\n this.name = \"HttpAbortError\";\n this.reason = reason;\n }\n}\n\n// D60 rule 149: a module-provided enum carries the same runtime face a declared\n// enum does -- charter section 6 reserves is, parse, and values on every enum,\n// and member access alone kept the gap invisible until a call threw.\nexport const HttpTransportPhase = __velarRegisterRuntimeType(__velarFreezeOptionsValue({\n request: \"request\",\n response: \"response\",\n is(value) { return value === \"request\" || value === \"response\"; },\n parse(value) {\n if (!HttpTransportPhase.is(value)) throw new TypeError(\"Value does not match HttpTransportPhase\");\n return value;\n },\n values() { return [\"request\", \"response\"]; },\n}));\nexport class HttpTransportError extends Error {\n constructor(message, phase) {\n message = __velarString(message, \"HTTP transport error message\");\n if (message.length === 0 || message.length > 65536) throw new RangeError(\"HTTP transport error messages must contain at most 64 KiB\");\n if (phase !== HttpTransportPhase.request && phase !== HttpTransportPhase.response) {\n throw new TypeError(\"HTTP transport phase must be request or response\");\n }\n super(message);\n this.name = \"HttpTransportError\";\n this.phase = phase;\n }\n}\n\nasync function readHttpTransportChunk(reader) {\n try { return await nativeReflectApply(nativeReaderRead, reader, []); }\n catch { throw new HttpTransportError(\"HTTP response transport failed\", HttpTransportPhase.response); }\n}\n\nclass HttpResponse {\n constructor(response, request) {\n this.request = request;\n this.maxBytes = request.options.maxBytes;\n this.bytesValue = null;\n this.bytesPending = null;\n this.streaming = false;\n this.status = response.status;\n this.statusText = response.statusText;\n this.url = response.url;\n this.headers = response.headers;\n this.body = response.body;\n this.declaredLength = nativeReflectApply(nativeMapGet, response.headers, [\"content-length\"]) ?? null;\n this.contentType = nativeReflectApply(nativeMapGet, response.headers, [\"content-type\"]) ?? \"\";\n if (response.body === null) request.finish();\n }\n async bytes() {\n if (this.bytesValue) return this.bytesValue;\n if (this.bytesPending) return this.bytesPending;\n const declared = __velarDeclaredLength(this.declaredLength);\n if (this.body !== null && declared !== null && declared > this.maxBytes) {\n if (this.body !== null && typeof nativeStreamCancel === \"function\") {\n try { await nativeReflectApply(nativeStreamCancel, this.body, [\"VelarScript HTTP response exceeded maxBytes\"]); } catch {}\n }\n this.request.finish();\n throw new RangeError(\"HTTP response exceeds maxBytes\");\n }\n this.bytesPending = (async () => {\n if (this.body === null) return new NativeUint8Array();\n let reader = null;\n try {\n if (typeof nativeStreamGetReader !== \"function\" || typeof nativeReaderRead !== \"function\" || typeof nativeReaderCancel !== \"function\"\n || typeof nativeTypedArrayTag !== \"function\" || typeof nativeTypedArrayByteLength !== \"function\" || typeof nativeUint8ArraySet !== \"function\") {\n throw new TypeError(\"The browser does not expose the required native response stream API\");\n }\n try { reader = nativeReflectApply(nativeStreamGetReader, this.body, []); }\n catch { throw new TypeError(\"Fetch returned an invalid HTTP response body\"); }\n const chunks = new __velarListNativeArray();\n let total = 0;\n while (true) {\n const next = await readHttpTransportChunk(reader);\n if (next.done) break;\n let kind;\n let length;\n try {\n kind = nativeReflectApply(nativeTypedArrayTag, next.value, []);\n length = nativeReflectApply(nativeTypedArrayByteLength, next.value, []);\n } catch { throw new TypeError(\"Fetch returned a non-byte response chunk\"); }\n if (kind !== \"Uint8Array\") throw new TypeError(\"Fetch returned a non-byte response chunk\");\n total += length;\n if (total > this.maxBytes) throw new RangeError(\"HTTP response exceeds maxBytes\");\n if (chunks.length >= 1000000) throw new RangeError(\"HTTP responses cannot exceed 1000000 chunks\");\n const chunk = new NativeUint8Array(length);\n nativeReflectApply(nativeUint8ArraySet, chunk, [next.value]);\n __velarListReflectApply(__velarListDefineProperty, __velarListNativeObject, [chunks, chunks.length, {\n value: chunk, enumerable: true, configurable: true, writable: true,\n }]);\n }\n const output = new NativeUint8Array(total);\n let offset = 0;\n for (let index = 0; index < chunks.length; index += 1) {\n const chunk = chunks[index];\n nativeReflectApply(nativeUint8ArraySet, output, [chunk, offset]);\n offset += nativeReflectApply(nativeTypedArrayByteLength, chunk, []);\n }\n return __velarHttpBytes.parse(output);\n } catch (error) {\n if (reader !== null) {\n try { await nativeReflectApply(nativeReaderCancel, reader, [error]); } catch {}\n } else if (typeof nativeStreamCancel === \"function\") {\n try { await nativeReflectApply(nativeStreamCancel, this.body, [error]); } catch {}\n }\n throw error;\n }\n })();\n try { this.bytesValue = await this.bytesPending; return this.bytesValue; }\n catch (error) { if (this.request.abortError) throw this.request.abortError; throw error; }\n finally { this.bytesPending = null; this.request.finish(); }\n }\n async json() { return __velarJsonParse(await this.text(), \"HTTP JSON text\"); }\n async text() { const decoder = new NativeTextDecoder(\"utf-8\", { fatal: true }); return nativeReflectApply(nativeTextDecode, decoder, [await this.bytes()]); }\n async streamText(consume) {\n if (typeof consume !== \"function\") throw new TypeError(\"HTTP streamText requires an async consumer\");\n if (this.bytesValue) {\n const decoder = new NativeTextDecoder(\"utf-8\", { fatal: true });\n const result = await consume(nativeReflectApply(nativeTextDecode, decoder, [this.bytesValue]));\n if (result !== null) throw new TypeError(\"HTTP stream consumer must resolve to null\");\n return null;\n }\n if (this.bytesPending || this.streaming) throw new Error(\"HTTP response body is already being consumed\");\n if (this.body === null) return null;\n const declared = __velarDeclaredLength(this.declaredLength);\n if (declared !== null && declared > this.maxBytes) {\n if (typeof nativeStreamCancel === \"function\") {\n try { await nativeReflectApply(nativeStreamCancel, this.body, [\"VelarScript HTTP response exceeded maxBytes\"]); } catch {}\n }\n this.request.finish();\n throw new RangeError(\"HTTP response exceeds maxBytes\");\n }\n if (typeof nativeStreamGetReader !== \"function\" || typeof nativeReaderRead !== \"function\" || typeof nativeReaderCancel !== \"function\"\n || typeof nativeTypedArrayTag !== \"function\" || typeof nativeTypedArrayByteLength !== \"function\") {\n this.request.finish();\n throw new TypeError(\"The browser does not expose the required native response stream API\");\n }\n this.streaming = true;\n let reader;\n try { reader = nativeReflectApply(nativeStreamGetReader, this.body, []); }\n catch { this.request.finish(); throw new TypeError(\"Fetch returned an invalid HTTP response body\"); }\n const decoder = new NativeTextDecoder(\"utf-8\", { fatal: true });\n let total = 0;\n let chunks = 0;\n try {\n while (true) {\n const next = await readHttpTransportChunk(reader);\n if (next.done) break;\n let kind;\n let length;\n try { kind = nativeReflectApply(nativeTypedArrayTag, next.value, []); length = nativeReflectApply(nativeTypedArrayByteLength, next.value, []); }\n catch { throw new TypeError(\"Fetch returned a non-byte response chunk\"); }\n if (kind !== \"Uint8Array\") throw new TypeError(\"Fetch returned a non-byte response chunk\");\n total += length;\n chunks += 1;\n if (total > this.maxBytes || chunks > 1000000) {\n try { await nativeReflectApply(nativeReaderCancel, reader, [\"VelarScript HTTP response exceeded its bound\"]); } catch {}\n throw new RangeError(total > this.maxBytes ? \"HTTP response exceeds maxBytes\" : \"HTTP responses cannot exceed 1000000 chunks\");\n }\n const text = nativeReflectApply(nativeTextDecode, decoder, [next.value, { stream: true }]);\n if (text) {\n const result = await consume(text);\n if (result !== null) throw new TypeError(\"HTTP stream consumer must resolve to null\");\n }\n if (this.request.abortError) throw this.request.abortError;\n }\n const tail = nativeReflectApply(nativeTextDecode, decoder, []);\n if (tail) {\n const result = await consume(tail);\n if (result !== null) throw new TypeError(\"HTTP stream consumer must resolve to null\");\n }\n if (this.request.abortError) throw this.request.abortError;\n return null;\n } catch (error) {\n if (this.request.abortError) throw this.request.abortError;\n try { await nativeReflectApply(nativeReaderCancel, reader, [error]); } catch {}\n throw error;\n } finally {\n this.request.finish();\n }\n }\n async blob() { return new NativeBlob([await this.bytes()], { type: this.contentType }); }\n async parse(Type) { Type = runtimeHttpType(Type); return __velarJsonParseTyped(Type, await this.text(), \"HTTP JSON text\"); }\n}\n\nclass Request {\n constructor(method, url, options) {\n this.method = methodOf(method);\n this.url = __velarString(url, \"HTTP URL\");\n if (this.url.length > 2 * 1024 * 1024) throw new RangeError(\"HTTP URLs cannot exceed 2 MiB\");\n this.options = optionsOf(options);\n if ((this.method === \"GET\" || this.method === \"HEAD\") && this.options.body != null) throw new TypeError(this.method + \" requests cannot have a body\");\n this.controller = null;\n this.pending = null;\n this.abortError = null;\n this.finished = false;\n this.timer = null;\n }\n async response() {\n if (this.pending) return this.pending;\n if (this.abortError) throw this.abortError;\n requireHttpHost();\n this.controller = new NativeAbortController();\n const timeoutMs = this.options.timeout;\n this.timer = timeoutMs ? nativeReflectApply(nativeSetTimeout, globalThis, [() => this.abort(\"timeout\"), timeoutMs]) : null;\n this.pending = this.perform(this.controller);\n return this.pending;\n }\n finish() {\n if (this.finished) return;\n this.finished = true;\n if (this.timer) { nativeReflectApply(nativeClearTimeout, globalThis, [this.timer]); this.timer = null; }\n }\n abort(reason) {\n if (this.finished || this.abortError) return;\n this.abortError = new HttpAbortError(reason);\n if (this.timer) { nativeReflectApply(nativeClearTimeout, globalThis, [this.timer]); this.timer = null; }\n if (this.controller) nativeReflectApply(nativeAbort, this.controller, [this.abortError]);\n }\n async perform(controller) {\n try {\n const headers = headerMap(this.options.headers);\n let body = this.options.body;\n const multipart = body != null && typeof body === \"object\" ? nativeReflectApply(nativeWeakMapGet, formBodies, [body]) : null;\n if (multipart instanceof NativeFormData) {\n if (nativeReflectApply(nativeHeadersHas, headers, [\"content-type\"])) throw new TypeError(\"Do not set content-type for a VelarScript form body; the browser owns its multipart boundary\");\n body = multipart;\n }\n const signal = nativeReflectApply(nativeAbortSignal, controller, []);\n let transportResponse;\n try {\n transportResponse = await nativeReflectApply(nativeFetch, globalThis, [this.url, {\n method: this.method,\n headers,\n body,\n credentials: this.options.credentials,\n cache: this.options.cache,\n signal,\n }]);\n } catch {\n if (this.abortError) throw this.abortError;\n throw new HttpTransportError(\"HTTP request transport failed\", HttpTransportPhase.request);\n }\n const response = await responseSnapshot(transportResponse);\n if (this.abortError) throw this.abortError;\n const wrapped = new HttpResponse(response, this);\n // D90 R20: the 2xx question is asked here and nowhere else. The\n // transport snapshot still carries ok; the response an author holds does\n // not, because by the time it is returned the answer is always yes.\n if (!response.ok) {\n const text = await wrapped.text();\n let parsed = text;\n try { parsed = text ? __velarJsonParse(text, \"HTTP error JSON text\") : null; } catch { parsed = text; }\n const errorUrl = wrapped.url || this.url;\n throw new HttpResponseError(\"HTTP \" + wrapped.status + \" for \" + errorUrl, wrapped.status, errorUrl, parsed);\n }\n return wrapped;\n } catch (error) {\n this.finish();\n if (this.abortError) throw this.abortError;\n throw error;\n }\n }\n async json() { return (await this.response()).json(); }\n async text() { return (await this.response()).text(); }\n async bytes() { return (await this.response()).bytes(); }\n async streamText(consume) { return (await this.response()).streamText(consume); }\n async blob() { return (await this.response()).blob(); }\n async parse(Type) { Type = runtimeHttpType(Type); return (await this.response()).parse(Type); }\n cancel() { this.abort(\"cancelled\"); return null; }\n}\n\nconst createRequest = (method) => (url, options = {}) => new Request(method, url, options);\nexport const http = __velarFreezeOptionsValue({\n request(method, url, options = {}) { return new Request(method, url, options); },\n get: createRequest(\"GET\"), post: createRequest(\"POST\"), put: createRequest(\"PUT\"), patch: createRequest(\"PATCH\"), delete: createRequest(\"DELETE\"), head: createRequest(\"HEAD\"),\n});\n";
|
|
78
78
|
export const WEB_STORAGE_MODULE = WEB_OWNED_CALLBACK_RUNTIME + "\n" + VELAR_STRICT_JSON_RUNTIME + "\n" + VELAR_UTF8_RUNTIME + "\n" + WEB_LIST_GUARD_RUNTIME + "\n" + VELAR_TYPE_REGISTRY_RUNTIME + "\n" + WEB_STORAGE_HOST_RUNTIME + "\n" + "const changeEvent = \"velar-storage-change\";\nconst storageMaxKeyCodeUnits = 4096;\nconst storageMaxListingCodeUnits = 16 * 1024 * 1024;\nconst storageMaxValueBytes = 16 * 1024 * 1024;\nconst storageNumberIsSafeInteger = Object.getOwnPropertyDescriptor(Number, \"isSafeInteger\")?.value;\nconst storageStringSlice = Object.getOwnPropertyDescriptor(String.prototype, \"slice\").value;\nconst storageListSort = Object.getOwnPropertyDescriptor(Array.prototype, \"sort\").value;\nconst storageMissingField = __velarBrowserMissingField;\nconst storageNativeUint8Array = typeof globalThis.Uint8Array === \"function\" ? globalThis.Uint8Array : null;\nconst storageTypedArrayPrototype = storageNativeUint8Array ? Object.getPrototypeOf(storageNativeUint8Array.prototype) : null;\nconst storageTypedArrayTag = storageTypedArrayPrototype ? Object.getOwnPropertyDescriptor(storageTypedArrayPrototype, Symbol.toStringTag)?.get : null;\nconst storageTypedArrayLength = storageTypedArrayPrototype ? Object.getOwnPropertyDescriptor(storageTypedArrayPrototype, \"length\")?.get : null;\nconst storageTypedArraySet = storageTypedArrayPrototype ? Object.getOwnPropertyDescriptor(storageTypedArrayPrototype, \"set\")?.value : null;\nfunction storageBytesKind(value) {\n if (typeof storageTypedArrayTag !== \"function\") return null;\n try { return __velarBrowserReflectApply(storageTypedArrayTag, value, []); } catch { return null; }\n}\nconst __velarStorageBytes = Object.freeze({\n is(value) { return storageBytesKind(value) === \"Uint8Array\"; },\n parse(value) {\n if (storageBytesKind(value) !== \"Uint8Array\" || typeof storageNativeUint8Array !== \"function\"\n || typeof storageTypedArrayLength !== \"function\" || typeof storageTypedArraySet !== \"function\") {\n throw new TypeError(\"Bytes requires Uint8Array\");\n }\n const output = new storageNativeUint8Array(__velarBrowserReflectApply(storageTypedArrayLength, value, []));\n __velarBrowserReflectApply(storageTypedArraySet, output, [value]);\n return output;\n },\n});\n\nexport class StorageQuotaError extends Error { constructor(message = \"Browser storage quota was exceeded\") { super(message); this.name = \"StorageQuotaError\"; } }\nexport class StorageTransactionError extends Error { constructor(message = \"Browser storage transaction failed\") { super(message); this.name = \"StorageTransactionError\"; } }\nexport class StorageUpgradeError extends Error { constructor(message = \"Browser storage upgrade failed\") { super(message); this.name = \"StorageUpgradeError\"; } }\nfunction storageFailure(error, phase = \"transaction\") {\n if (error instanceof StorageQuotaError || error instanceof StorageTransactionError || error instanceof StorageUpgradeError) return error;\n if (error && typeof error === \"object\" && error.name === \"QuotaExceededError\") return new StorageQuotaError(error.message || undefined);\n const message = error && typeof error === \"object\" && typeof error.message === \"string\" ? error.message : undefined;\n return phase === \"upgrade\" ? new StorageUpgradeError(message) : new StorageTransactionError(message);\n}\n\nfunction storageType(Type) { return __velarRequireRuntimeType(Type, \"Storage reads\"); }\nfunction storageText(value, name) { if (typeof value !== \"string\") throw new TypeError(name + \" must be a string\"); if (value.length > storageMaxKeyCodeUnits) throw new RangeError(name + \" cannot exceed 4096 characters\"); return value; }\nfunction storageSafeInteger(value) { return typeof storageNumberIsSafeInteger === \"function\" && __velarBrowserReflectApply(storageNumberIsSafeInteger, null, [value]); }\nfunction storageByteBudget(value) { if (!storageSafeInteger(value) || value <= 0 || value > storageMaxValueBytes) throw new RangeError(\"Storage maxBytes must be an integer from 1 through 16777216\"); return value; }\nfunction storageOwnDataField(value, name) {\n return __velarBrowserOwnDataField(value, name);\n}\nfunction storageHostEventField(event, name, nativeGetter, constructor) {\n return storageHostField(event, name, nativeGetter, constructor);\n}\nfunction storageChangeSnapshot(event) {\n const detail = storageHostEventField(event, \"detail\", storageCustomEventDetail, storageNativeCustomEvent);\n if (detail === storageMissingField || detail === null || typeof detail !== \"object\") return null;\n const prototype = Object.getPrototypeOf(detail);\n if (prototype !== Object.prototype && prototype !== null) return null;\n const areaName = storageOwnDataField(detail, \"areaName\");\n const key = storageOwnDataField(detail, \"key\");\n const newValue = storageOwnDataField(detail, \"newValue\");\n const oldValue = storageOwnDataField(detail, \"oldValue\");\n if (areaName === storageMissingField || key === storageMissingField || newValue === storageMissingField || oldValue === storageMissingField) return null;\n return { areaName, key, newValue, oldValue };\n}\nfunction storageEventSnapshot(event) {\n const storageArea = storageHostEventField(event, \"storageArea\", storageEventStorageArea, storageNativeStorageEvent);\n const key = storageHostEventField(event, \"key\", storageEventKey, storageNativeStorageEvent);\n const newValue = storageHostEventField(event, \"newValue\", storageEventNewValue, storageNativeStorageEvent);\n const oldValue = storageHostEventField(event, \"oldValue\", storageEventOldValue, storageNativeStorageEvent);\n if (storageArea === storageMissingField || key === storageMissingField || newValue === storageMissingField || oldValue === storageMissingField) return null;\n return { storageArea, key, newValue, oldValue };\n}\nfunction parsed(raw, Type, fallback, maxBytes) {\n Type = storageType(Type);\n if (raw == null) return fallback;\n if (typeof raw !== \"string\" || __velarUtf8ByteLength(raw) > maxBytes) return fallback;\n try { return __velarJsonParseTyped(Type, raw, \"Stored JSON text\"); } catch { return fallback; }\n}\n\nfunction createStore(storageArea, prefix = \"\", areaName = \"local\") {\n const area = () => {\n if (storageArea === storageMissingField || storageArea === null || (typeof storageArea !== \"object\" && typeof storageArea !== \"function\")) {\n throw new Error(\"velar/storage requires a browser storage environment\");\n }\n return storageArea;\n };\n const full = (key) => {\n const value = storageText(key, \"Storage key\");\n if (prefix.length > storageMaxKeyCodeUnits - value.length) throw new RangeError(\"Scoped storage keys cannot exceed 4096 characters\");\n return prefix + value;\n };\n const emit = (key, oldValue, newValue) => {\n if (typeof storageNativeCustomEvent !== \"function\") throw new TypeError(\"The browser CustomEvent API is unavailable\");\n const detail = Object.freeze({ areaName, key, oldValue, newValue });\n return __velarBrowserCallCaptured(storageGlobalDispatch, storageWindow, [new storageNativeCustomEvent(changeEvent, { detail })], \"dispatchEvent\");\n };\n const api = {\n get(key, Type, fallback = null, maxBytes = storageMaxValueBytes) {\n Type = storageType(Type);\n maxBytes = storageByteBudget(maxBytes);\n const name = full(key);\n return parsed(storageHostCall(area(), \"getItem\", storageGetItem, storageNativeStorage, [name]), Type, fallback, maxBytes);\n },\n set(key, value, maxBytes = storageMaxValueBytes) {\n const name = full(key);\n maxBytes = storageByteBudget(maxBytes);\n const next = __velarJsonStringify(value);\n if (__velarUtf8ByteLength(next) > maxBytes) throw new RangeError(\"Stored JSON exceeds maxBytes\");\n const target = area();\n const previous = storageHostCall(target, \"getItem\", storageGetItem, storageNativeStorage, [name]);\n storageHostCall(target, \"setItem\", storageSetItem, storageNativeStorage, [name, next]);\n emit(name, previous, next);\n return null;\n },\n has(key) { const name = full(key); return storageHostCall(area(), \"getItem\", storageGetItem, storageNativeStorage, [name]) != null; },\n keys() {\n const target = area();\n const count = storageHostField(target, \"length\", storageLength, storageNativeStorage);\n if (!storageSafeInteger(count) || count < 0 || count > 100000) throw new RangeError(\"Browser storage cannot exceed 100000 keys\");\n const output = [];\n let outputUnits = 0;\n for (let index = 0; index < count; index += 1) {\n const key = storageHostCall(target, \"key\", storageKey, storageNativeStorage, [index]);\n if (key === null) continue;\n if (typeof key !== \"string\") throw new TypeError(\"Browser storage returned a non-string key\");\n if (key.length < prefix.length || __velarBrowserCallCaptured(storageStringSlice, key, [0, prefix.length], \"String.slice\") !== prefix) continue;\n if (key.length > storageMaxKeyCodeUnits) throw new RangeError(\"Browser storage keys cannot exceed 4096 characters\");\n const visible = __velarBrowserCallCaptured(storageStringSlice, key, [prefix.length], \"String.slice\");\n outputUnits += visible.length;\n if (outputUnits > storageMaxListingCodeUnits) throw new RangeError(\"Browser storage key listings cannot exceed 16 MiB\");\n output.push(visible);\n }\n __velarBrowserCallCaptured(storageListSort, output, [], \"Array.sort\");\n return output;\n },\n remove(key) {\n const name = full(key);\n const target = area();\n const previous = storageHostCall(target, \"getItem\", storageGetItem, storageNativeStorage, [name]);\n storageHostCall(target, \"removeItem\", storageRemoveItem, storageNativeStorage, [name]);\n if (previous != null) emit(name, previous, null);\n return null;\n },\n clear() { for (const key of api.keys()) api.remove(key); return null; },\n scope(name) {\n const value = storageText(name, \"Storage scope\").trim();\n if (!value) throw new TypeError(\"Storage scope cannot be empty\");\n if (prefix.length > storageMaxKeyCodeUnits - value.length - 1) throw new RangeError(\"Storage scope paths cannot exceed 4096 characters\");\n return createStore(storageArea, prefix + value + \":\", areaName);\n },\n watch(key, Type, callback, maxBytes = storageMaxValueBytes) {\n if (typeof callback !== \"function\") throw new TypeError(\"Storage watch requires a callback\");\n Type = storageType(Type);\n maxBytes = storageByteBudget(maxBytes);\n const name = full(key);\n const changed = (event) => {\n const detail = storageChangeSnapshot(event);\n if (!detail || detail.areaName !== areaName || detail.key !== name) return;\n __velarInvokeOwnedCallback(callback, [parsed(detail.newValue, Type, null, maxBytes), parsed(detail.oldValue, Type, null, maxBytes)], \"storage\", \"watch\");\n };\n const stored = (event) => {\n const snapshot = storageEventSnapshot(event);\n if (!snapshot || snapshot.storageArea !== area() || snapshot.key !== name) return;\n __velarInvokeOwnedCallback(callback, [parsed(snapshot.newValue, Type, null, maxBytes), parsed(snapshot.oldValue, Type, null, maxBytes)], \"storage\", \"watch\");\n };\n const removeChanged = storageListenGlobal(changeEvent, changed);\n const removeStored = storageListenGlobal(\"storage\", stored);\n return () => { removeChanged(); removeStored(); return null; };\n },\n };\n return Object.freeze(api);\n}\n\nexport const storage = createStore(storageLocalArea);\nexport const session = createStore(storageSessionArea, \"\", \"session\");\n\nexport function database(name) {\n const databaseName = storageText(name, \"Database name\").trim();\n if (!databaseName) throw new TypeError(\"Database name cannot be empty\");\n if (databaseName.length > 256) throw new RangeError(\"Database names cannot exceed 256 characters\");\n if (storageIndexedDb === storageMissingField || storageIndexedDb === null) {\n throw new Error(\"velar/storage database requires IndexedDB\");\n }\n let opened = null;\n const requestResult = (request) => storageHostField(request, \"result\", storageIdbRequestResult, storageNativeIdbRequest);\n const requestError = (request) => storageHostField(request, \"error\", storageIdbRequestError, storageNativeIdbRequest);\n const closeConnection = (value) => storageHostCall(value, \"close\", storageIdbClose, storageNativeIdbDatabase);\n const objectOperation = (store, operation, arguments_) => {\n const methods = {\n get: storageIdbObjectGet,\n put: storageIdbObjectPut,\n getKey: storageIdbObjectGetKey,\n getAllKeys: storageIdbObjectGetAllKeys,\n delete: storageIdbObjectDelete,\n clear: storageIdbObjectClear,\n };\n return storageHostCall(store, operation, methods[operation], storageNativeIdbObjectStore, arguments_);\n };\n const connect = () => {\n if (opened) return opened;\n const pending = new Promise((resolve, reject) => {\n let request;\n const guarded = (callback) => (...arguments_) => { try { callback(...arguments_); } catch (error) { reject(error); } };\n try {\n request = storageHostCall(storageIndexedDb, \"open\", storageIdbOpen, storageNativeIdbFactory, [\"velar:\" + databaseName, 1]);\n storageListen(request, \"upgradeneeded\", guarded(() => {\n const result = requestResult(request);\n const names = storageHostField(result, \"objectStoreNames\", storageIdbObjectStoreNames, storageNativeIdbDatabase);\n const present = storageHostCall(names, \"contains\", storageDomStringListContains, storageNativeDomStringList, [\"values\"]);\n if (typeof present !== \"boolean\") throw new TypeError(\"IndexedDB objectStoreNames.contains must return bool\");\n if (!present) storageHostCall(result, \"createObjectStore\", storageIdbCreateObjectStore, storageNativeIdbDatabase, [\"values\"]);\n }), { once: true });\n storageListen(request, \"success\", guarded(() => {\n const result = requestResult(request);\n if (opened !== pending) { closeConnection(result); return; }\n storageListen(result, \"versionchange\", () => { closeConnection(result); if (opened === pending) opened = null; }, { once: true });\n storageListen(result, \"close\", () => { if (opened === pending) opened = null; }, { once: true });\n resolve(result);\n }), { once: true });\n storageListen(request, \"error\", guarded(() => reject(storageFailure(requestError(request), \"upgrade\"))), { once: true });\n storageListen(request, \"blocked\", () => reject(new StorageUpgradeError(\"VelarScript database upgrade is blocked by another open page\")), { once: true });\n } catch (error) { reject(storageFailure(error, \"upgrade\")); }\n });\n opened = pending;\n void pending.catch(() => { if (opened === pending) opened = null; });\n return pending;\n };\n const request = async (mode, operation) => {\n const connection = connect();\n const db = await connection;\n return new Promise((resolve, reject) => {\n let transaction;\n try { transaction = storageHostCall(db, \"transaction\", storageIdbTransaction, storageNativeIdbDatabase, [\"values\", mode]); }\n catch (error) {\n if (opened === connection) {\n opened = null;\n try { closeConnection(db); } catch {}\n }\n reject(storageFailure(error));\n return;\n }\n let value;\n let settled = false;\n const fail = (error) => { if (!settled) { settled = true; reject(error); } };\n const guarded = (callback) => (...arguments_) => { try { callback(...arguments_); } catch (error) { fail(error); } };\n try {\n const store = storageHostCall(transaction, \"objectStore\", storageIdbTransactionObjectStore, storageNativeIdbTransaction, [\"values\"]);\n const result = operation(store);\n if (result !== null) {\n storageListen(result, \"success\", guarded(() => { value = requestResult(result); }), { once: true });\n storageListen(result, \"error\", guarded(() => fail(storageFailure(requestError(result)))), { once: true });\n }\n storageListen(transaction, \"abort\", guarded(() => fail(storageFailure(storageHostField(transaction, \"error\", storageIdbTransactionError, storageNativeIdbTransaction)))), { once: true });\n storageListen(transaction, \"error\", guarded(() => fail(storageFailure(storageHostField(transaction, \"error\", storageIdbTransactionError, storageNativeIdbTransaction)))), { once: true });\n storageListen(transaction, \"complete\", guarded(() => { if (!settled) { settled = true; resolve(value); } }), { once: true });\n } catch (error) {\n try { storageHostCall(transaction, \"abort\", storageIdbTransactionAbort, storageNativeIdbTransaction); } catch {}\n fail(storageFailure(error));\n }\n });\n };\n const keyOf = (key) => storageText(key, \"Database key\");\n return Object.freeze({\n async get(key, Type, fallback = null, maxBytes = storageMaxValueBytes) { Type = storageType(Type); maxBytes = storageByteBudget(maxBytes); const name = keyOf(key); const encoded = await request(\"readonly\", (store) => objectOperation(store, \"get\", [name])); if (encoded === undefined || typeof encoded !== \"string\" || __velarUtf8ByteLength(encoded) > maxBytes) return fallback; try { return __velarJsonParseTyped(Type, encoded, \"Stored JSON text\"); } catch { return fallback; } },\n async set(key, value, maxBytes = storageMaxValueBytes) {\n const name = keyOf(key);\n maxBytes = storageByteBudget(maxBytes);\n const encoded = __velarJsonStringify(value);\n if (__velarUtf8ByteLength(encoded) > maxBytes) throw new RangeError(\"Stored JSON exceeds maxBytes\");\n await request(\"readwrite\", (store) => objectOperation(store, \"put\", [encoded, name]));\n return null;\n },\n async getBytes(key, fallback = null, maxBytes = storageMaxValueBytes) {\n const name = keyOf(key);\n maxBytes = storageByteBudget(maxBytes);\n const value = await request(\"readonly\", (store) => objectOperation(store, \"get\", [name]));\n if (value === undefined) return fallback === null ? null : __velarStorageBytes.parse(fallback);\n let bytes;\n try { bytes = __velarStorageBytes.parse(value); } catch { throw new StorageTransactionError(\"Stored value is not Bytes\"); }\n if (bytes.byteLength > maxBytes) throw new StorageTransactionError(\"Stored Bytes exceeds maxBytes\");\n return bytes;\n },\n async setBytes(key, value, maxBytes = storageMaxValueBytes) {\n const name = keyOf(key);\n maxBytes = storageByteBudget(maxBytes);\n const bytes = __velarStorageBytes.parse(value);\n if (bytes.byteLength > maxBytes) throw new RangeError(\"Stored Bytes exceeds maxBytes\");\n await request(\"readwrite\", (store) => objectOperation(store, \"put\", [bytes, name]));\n return null;\n },\n async batch(changes) {\n changes = __velarRequireList(changes, \"Database batch changes\");\n if (changes.length > 10000) throw new RangeError(\"Database batches cannot exceed 10000 changes\");\n const checked = [];\n let totalBytes = 0;\n for (let index = 0; index < changes.length; index += 1) {\n const change = changes[index];\n if (!change || typeof change !== \"object\" || Array.isArray(change)) throw new TypeError(\"Database batch changes must be records\");\n const keys = Object.keys(change);\n if (keys.length !== 2 || !keys.includes(\"key\") || !keys.includes(\"bytes\")) throw new TypeError(\"Database batch changes require exactly key and bytes\");\n const key = keyOf(change.key);\n const bytes = change.bytes === null ? null : __velarStorageBytes.parse(change.bytes);\n totalBytes += bytes?.byteLength ?? 0;\n if (totalBytes > 64 * 1024 * 1024) throw new RangeError(\"Database batch Bytes cannot exceed 64 MiB\");\n checked.push({key, bytes});\n }\n await request(\"readwrite\", (store) => {\n for (const change of checked) {\n objectOperation(store, change.bytes === null ? \"delete\" : \"put\", change.bytes === null ? [change.key] : [change.bytes, change.key]);\n }\n return null;\n });\n return null;\n },\n async has(key) { const name = keyOf(key); return (await request(\"readonly\", (store) => objectOperation(store, \"getKey\", [name]))) !== undefined; },\n async keys() {\n let keys = await request(\"readonly\", (store) => objectOperation(store, \"getAllKeys\", [undefined, 100001]));\n if (!Array.isArray(keys)) throw new TypeError(\"VelarScript database keys must be a List\");\n if (keys.length > 100000) throw new RangeError(\"VelarScript databases cannot expose more than 100000 keys at once\");\n keys = __velarRequireList(keys, \"Database keys\");\n for (const key of keys) if (typeof key !== \"string\") throw new TypeError(\"VelarScript database contains a non-string key\");\n __velarBrowserCallCaptured(storageListSort, keys, [], \"Array.sort\");\n return keys;\n },\n async remove(key) { const name = keyOf(key); await request(\"readwrite\", (store) => objectOperation(store, \"delete\", [name])); return null; },\n async clear() { await request(\"readwrite\", (store) => objectOperation(store, \"clear\", [])); return null; },\n });\n}\n";
|
|
@@ -92,5 +92,5 @@ export const LOOK_ARITHMETIC_RUNTIME = "function __velarLookDimension(value) {\n
|
|
|
92
92
|
* the look/class/style appliers. `webRuntime` splices the module's own
|
|
93
93
|
* keyword table into it; everything else here is the same for every program.
|
|
94
94
|
*/
|
|
95
|
-
export const WEB_RUNTIME_BODY = "function __velarReport(value, phase, scope = null, detail = \"\", unhandled = true) {\n return __velarRuntime.report(value, { phase, detail, component: scope ? scope.component : \"\", unhandled });\n}\n\nfunction __velarReportEvent(value, scope, detail) {\n if (__velarIsError(value) && __velarGraphWeakSetRemove(__velarRuntime.actionFailures, value)) return null;\n return __velarReport(value, \"event\", scope, detail);\n}\n\nconst __velarWebIterateKey = Symbol.for(\"velar.reactive.iterate.v1\");\nconst __velarWebNativeJson = globalThis.JSON;\nconst __velarWebJsonText = Object.getOwnPropertyDescriptor(__velarWebNativeJson, \"stringify\")?.value;\nconst __velarEventReflectApply = Object.getOwnPropertyDescriptor(Reflect, \"apply\")?.value;\nconst __velarEventConstructorDescriptor = Object.getOwnPropertyDescriptor(globalThis, \"Event\");\nconst __velarEventConstructor = __velarEventConstructorDescriptor && \"value\" in __velarEventConstructorDescriptor ? __velarEventConstructorDescriptor.value : null;\nconst __velarEventPrototype = typeof __velarEventConstructor === \"function\" ? Object.getOwnPropertyDescriptor(__velarEventConstructor, \"prototype\")?.value : null;\nconst __velarEventTargetGetter = __velarEventPrototype && Object.getOwnPropertyDescriptor(__velarEventPrototype, \"target\")?.get;\nconst __velarEventPreventDefault = __velarEventPrototype && Object.getOwnPropertyDescriptor(__velarEventPrototype, \"preventDefault\")?.value;\nconst __velarEventStopPropagation = __velarEventPrototype && Object.getOwnPropertyDescriptor(__velarEventPrototype, \"stopPropagation\")?.value;\nconst __velarEventMissingField = __velarGraphFreeze({});\nfunction __velarQuotedText(value) {\n return __velarGraphApply(__velarWebJsonText, __velarWebNativeJson, [value], \"JSON.stringify\");\n}\nfunction __velarAppendOwned(values, value) {\n values[values.length] = value;\n return value;\n}\nfunction __velarHasName(values, name) {\n for (let index = 0; index < values.length; index += 1) if (values[index] === name) return true;\n return false;\n}\nfunction __velarEventField(value, name, nativeGetter) {\n if (typeof nativeGetter === \"function\" && typeof __velarEventReflectApply === \"function\") {\n try { return __velarEventReflectApply(nativeGetter, value, []); } catch {}\n }\n if (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) return __velarEventMissingField;\n const descriptor = __velarGraphOwnDescriptor(value, name);\n return descriptor?.enumerable && \"value\" in descriptor ? descriptor.value : __velarEventMissingField;\n}\nfunction __velarEventCall(value, name, nativeMethod) {\n if (typeof nativeMethod === \"function\" && typeof __velarEventReflectApply === \"function\") {\n try { return __velarEventReflectApply(nativeMethod, value, []); } catch {}\n }\n const method = __velarEventField(value, name, null);\n if (typeof method !== \"function\" || typeof __velarEventReflectApply !== \"function\") throw new TypeError(\"DOM event does not expose native \" + name);\n return __velarEventReflectApply(method, value, []);\n}\n\n" + "function __velarTrack(subscribers) {\n __velarRuntime.trackSubscribers(subscribers);\n}\n\nfunction __velarToRaw(value) { return __velarRuntime.toRaw(value); }\nfunction __velarReactive(value, parent = null) { return __velarRuntime.reactive(value, parent); }\n\nfunction __velarWebListPop(value, requested = -1) {\n return __velarReactive(__velarListPop(value, requested));\n}\n\nfunction __velarUntracked(read) {\n const previous = __velarRuntime.activeObserver;\n __velarRuntime.activeObserver = null;\n try { return read(); } finally { __velarRuntime.activeObserver = previous; }\n}\n\nfunction __velarCleanupObserver(observer) {\n __velarRuntime.cleanupObserver(observer);\n}\n\n// P2b-9: a self-invalidating render used to report only that it happened. The\n// stack top was the graph's own trigger, so it named neither the collection\n// being written nor the scope reading it, and the distance between symptom and\n// cause was the whole debugging cost. Everything below is already known where\n// the budget trips: the observer carries its component and its watch subject,\n// and the graph has just recorded which path re-triggered it. Naming the write\n// is the difference between bisecting a render and reading one line.\n//\n// The advice is attached to the shape that earns it. A \"collection\" subject\n// means a collection was read for its size or contents and then written in the\n// same pass, and the two spellings that end it are the same two every time:\n// take the position from the loop instead of from the collection, or read the\n// value out before writing. The kind arrives beside the phrase, so nothing here\n// reads a sentence back apart to decide.\nfunction __velarSelfInvalidationMessage(mode, component, label, subject, kind) {\n let message = \"A reactive \" + mode + \" cannot invalidate itself more than 100 times\";\n if (component) message += \" (\" + component + \")\";\n else if (label) message += \" (watching \" + label + \")\";\n if (!subject) return message;\n message += \": it writes \" + subject + \" while reading it\";\n if (kind === \"collection\") {\n return message + \". A position taken from the collection being written -- 'items.get(built.size)' inside the loop that appends to 'built' -- reads it on every pass; take the position from a two-slot 'for value, index in ...' instead, or read what you need into a binding before the loop.\";\n }\n return message + \". Read it into a binding before the code that writes it, so the write cannot reach the read that tracked it.\";\n}\n\n// D90 R21: \"label\" names the observer in a report -- a watch carries its\n// subject as the author spelled it -- and \"sequence\" is its registration\n// number, which is the order the flush runs the watch tier in. The counter is\n// application-wide rather than per module, so two modules' watches order by the\n// order the two modules initialized.\nfunction __velarObserver(read, mode, scope, label = \"\") {\n // The first run of a DOM observer executes while its JSX position is being\n // constructed, and construction is transactional: the failure must reach\n // the surrounding owner (the mount transaction at the root, the containing\n // child position otherwise) so the promised fatal state or contained\n // placeholder appears instead of a silently empty region. Later runs are\n // updates; their failures are reported and the last valid DOM survives.\n let initial = mode === \"dom\";\n const observer = {\n mode,\n label,\n sequence: __velarNextObserverSequence(),\n component: scope !== null && scope !== undefined && typeof scope.component === \"string\" ? scope.component : \"\",\n stopped: false,\n running: false,\n selfInvalidations: 0,\n // P2b-9: the reactive path whose write landed while this observer was\n // reading. The graph fills it in only on a self-invalidating write, so the\n // runaway report can name what to go and look at.\n selfInvalidationSubject: \"\",\n selfInvalidationKind: \"\",\n dependencies: __velarGraphCreateSet(),\n run() {\n if (observer.stopped) return;\n observer.running = true;\n try { __velarRuntime.runTracked(observer, read); }\n catch (error) {\n if (initial) throw error;\n __velarReport(error, mode === \"watch\" ? \"watch\" : \"render\", scope);\n }\n finally {\n observer.running = false;\n initial = false;\n }\n },\n notify() {\n if (observer.stopped) return;\n if (observer.running) {\n observer.selfInvalidations += 1;\n if (observer.selfInvalidations > 100) {\n observer.stop();\n __velarReport(new RangeError(__velarSelfInvalidationMessage(\n mode === \"watch\" ? \"watch\" : \"render\",\n observer.component,\n observer.label,\n observer.selfInvalidationSubject,\n observer.selfInvalidationKind,\n )), mode === \"watch\" ? \"watch\" : \"render\", scope);\n return;\n }\n } else {\n observer.selfInvalidations = 0;\n }\n // The registry owns the one scheduler: the emitted prelude used to carry\n // its own copy of the queue insert and the flush drain, and the two\n // definitions of one concept is what let a watch be classified three\n // different ways. The capability observers in packages/web/src/runtime.ts\n // have always scheduled this way.\n __velarRuntime.schedule(observer);\n },\n stop() { observer.stopped = true; __velarCleanupObserver(observer); },\n };\n __velarAppendOwned(scope.cleanups, () => observer.stop());\n observer.run();\n return observer;\n}\n\n// D70 rule 180: a reactive source read during component setup and stored in a\n// plain binding is frozen. That is what const means, and a snapshot is a\n// legitimate thing to want -- so the report fires when the source *diverges*\n// from the snapshot, never when the snapshot is taken. A warning that fires on\n// correct code is a warning people learn to ignore; one that fires only after\n// the value on screen has actually gone stale cannot be wrong about that.\n//\n// The whole mechanism is installed only when the development host published its\n// hooks, so a production build pays nothing for it: no map, no stack capture,\n// and one already-false constant on the read path.\n// One module's copy of this runtime cannot own the state: a component in one\n// module reads a cell created in another, so the setup stack and the recorded\n// reads live on the shared hooks object every copy sees.\nconst __velarFrozenHooks = (() => {\n const hooks = globalThis.__velarDevelopmentHooks;\n if (!hooks || typeof hooks.frozenRead !== \"function\") return null;\n if (hooks.setupScopes === undefined) {\n hooks.setupScopes = [];\n hooks.reads = __velarGraphCreateWeakMap();\n hooks.derived = [];\n hooks.internalDepth = 0;\n }\n return hooks;\n})();\nconst __velarFrozenReadLimit = 32;\n\nfunction __velarSetupBegin(scope) {\n if (__velarFrozenHooks) __velarAppendOwned(__velarFrozenHooks.setupScopes, scope);\n return scope;\n}\n\nfunction __velarSetupEnd(value) {\n if (__velarFrozenHooks && __velarFrozenHooks.setupScopes.length > 0) __velarFrozenHooks.setupScopes.length -= 1;\n return value;\n}\n\n// The framework's own reads on the author's behalf -- checking a prop is\n// present, building the content a children slot holds, reading a handler\n// thunk. None of them freezes anything the author wrote: the\n// prop handle behind them stays live. Reporting them would be the false-positive\n// flood D70 rule 180 rejected, in its most literal form.\nfunction __velarInternalRead(read) {\n if (!__velarFrozenHooks) return __velarUntracked(read);\n __velarFrozenHooks.internalDepth += 1;\n try { return __velarUntracked(read); } finally { __velarFrozenHooks.internalDepth -= 1; }\n}\n\nfunction __velarRecordFrozenRead(cell, value) {\n if (!__velarFrozenHooks) return;\n if (__velarFrozenHooks.setupScopes.length === 0 || __velarFrozenHooks.internalDepth > 0) return;\n if (__velarRuntime.activeObserver !== null) return;\n // Only a value the reader can show is worth naming in the report; an object\n // read out of setup is followed through the deep graph, not frozen by this\n // read, so recording it would produce a report about the wrong thing.\n if (value !== null && typeof value === \"object\") return;\n const scope = __velarFrozenHooks.setupScopes[__velarFrozenHooks.setupScopes.length - 1];\n const existing = __velarGraphWeakMapRead(__velarFrozenHooks.reads, cell);\n if (existing) {\n if (existing.length >= __velarFrozenReadLimit) return;\n __velarAppendOwned(existing, { value, scope, site: new Error(\"velar frozen read\") });\n return;\n }\n __velarGraphWeakMapWrite(__velarFrozenHooks.reads, cell, [{ value, scope, site: new Error(\"velar frozen read\") }]);\n}\n\n// A derived value frozen during setup has no cell to hang a report on, and a\n// read that left no subscriber is a read the cache never tells anything about.\n// So the entries are kept in one dev-mode list and re-read after a state write\n// -- the only thing that can move a derived value -- which is the same\n// \"report on divergence\" rule the cells follow, reached the only way it can be.\nfunction __velarRecordFrozenDerived(access, value) {\n if (!__velarFrozenHooks) return;\n if (__velarFrozenHooks.setupScopes.length === 0 || __velarFrozenHooks.internalDepth > 0) return;\n if (__velarRuntime.activeObserver !== null) return;\n if (value !== null && typeof value === \"object\") return;\n if (__velarFrozenHooks.derived.length >= __velarFrozenReadLimit * 4) return;\n const scope = __velarFrozenHooks.setupScopes[__velarFrozenHooks.setupScopes.length - 1];\n __velarAppendOwned(__velarFrozenHooks.derived, { access, value, scope, site: new Error(\"velar frozen read\") });\n}\n\nfunction __velarReportFrozenDerived() {\n if (!__velarFrozenHooks || __velarFrozenHooks.derived.length === 0) return;\n const entries = __velarFrozenHooks.derived;\n const remaining = [];\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n let current = entry.value;\n let failed = false;\n try { current = __velarUntracked(entry.access); }\n catch { failed = true; }\n if (failed || __velarGraphSame(entry.value, current)) { remaining[remaining.length] = entry; continue; }\n __velarPublishFrozenRead(entry, current);\n }\n __velarFrozenHooks.derived = remaining;\n}\n\nfunction __velarReportFrozenReads(cell, next) {\n if (!__velarFrozenHooks) return;\n __velarReportFrozenDerived();\n const entries = __velarGraphWeakMapRead(__velarFrozenHooks.reads, cell);\n if (!entries) return;\n __velarGraphWeakMapRemove(__velarFrozenHooks.reads, cell);\n for (let index = 0; index < entries.length; index += 1) {\n if (__velarGraphSame(entries[index].value, next)) continue;\n __velarPublishFrozenRead(entries[index], next);\n }\n}\n\nfunction __velarPublishFrozenRead(entry, next) {\n const component = entry.scope && entry.scope.component ? entry.scope.component : \"a component\";\n __velarFrozenHooks.frozenRead({\n message: \"A reactive value read while \" + component + \" was being built was frozen at \"\n + __velarFrozenText(entry.value) + \", and the source has now changed to \" + __velarFrozenText(next)\n + \". Whatever was built from that read still shows the old value. If it is meant to follow, declare it with 'computed name = <expression>'; if the snapshot was intended, nothing here needs changing.\",\n stack: __velarDomString(entry.site && entry.site.stack ? entry.site.stack : \"\"),\n });\n}\n\nfunction __velarFrozenText(value) {\n return typeof value === \"string\" ? __velarQuotedText(value) : __velarDomString(value);\n}\n\n// \"name\" is the declared name an author \"state\" wrote, carried on the cell and\n// visible in the emitted source. The cells __velarResource and __velarAction\n// build for their own pending/error fields are created without one, because\n// they are the runtime's bookkeeping rather than state anyone declared.\n//\n// D90 R21: nothing read it any more. It existed for the two watch referees --\n// only a cell with a declared name could be a declared write target -- and they\n// went with the clause. It was left in place rather than removed with them,\n// because it is a fact about the cell rather than a mechanism, and it is what a\n// report naming the state a runaway wrote would have to read. D114 0.28.0 H-U1\n// is that report: __velarSelfInvalidationWrite below reads it.\nfunction __velarState(initial, name) {\n let value = __velarToRaw(initial);\n const subscribers = __velarGraphCreateSet();\n const cell = {\n velarStateName: name,\n // Named rather than shorthand so a captured stack shows a compiler frame\n // here: D70's report walks past its own frames to find the reading line,\n // and every JavaScript engine spells an anonymous getter differently.\n get: function __velarCellRead() {\n __velarTrack(subscribers);\n const current = __velarReactive(value, cell);\n __velarRecordFrozenRead(cell, current);\n return current;\n },\n set(next) {\n next = __velarToRaw(next);\n if (__velarGraphSame(value, next)) return next;\n const previous = value;\n value = next;\n __velarReportFrozenReads(cell, next);\n // Keep deep-change bubbling attached only to the value currently owned\n // by this cell. Otherwise every replaced object remains linked to the\n // state cell and continues to occupy the parent graph indefinitely.\n __velarRuntime.collectionUnlink(cell, previous);\n __velarReactive(value, cell);\n for (const observer of __velarGraphSetItems(subscribers)) {\n __velarSelfInvalidationWrite(observer, name);\n observer.notify();\n }\n return next;\n },\n };\n __velarReactive(value, cell);\n return cell;\n}\n\n// D114 0.28.0 H-U1: a state cell notifies its own subscriber set rather than\n// going through the graph's keyed notify, so the write path the runaway report\n// names was recorded for every deep write and for no write of a declared\n// state -- and a scalar self-write only ever reaches the 100-round cap through\n// a helper, which is why the gap read as \"a write through a plain def\". The\n// condition is the graph's own, verbatim: a write that lands while its own\n// reader is still running is the self-invalidating shape, and it is the only\n// one worth describing. A cell with no declared name is runtime bookkeeping --\n// __velarResource and __velarAction build theirs that way -- so it falls back\n// to the same phrase describeSubject uses for a place it cannot name.\nfunction __velarSelfInvalidationWrite(observer, name) {\n if (!observer.running) return;\n observer.selfInvalidationSubject = name ? \"state '\" + name + \"'\" : \"a tracked value\";\n observer.selfInvalidationKind = \"value\";\n}\n\n// D71 rule 182: a declared derived value reads bare, so it presents the same\n// .get() face a state cell does. The cache underneath is the runtime's own\n// memo; only the face it is read through differs.\nfunction __velarComputed(read) {\n const access = __velarRuntime.computed(read);\n if (!__velarFrozenHooks) return __velarGraphFreeze({ get: access });\n return __velarGraphFreeze({\n get: function __velarDerivedRead() {\n const value = access();\n __velarRecordFrozenDerived(access, value);\n return value;\n },\n });\n}\n\n" + "const __velarManagedAsyncNativePromise = globalThis.Promise;\nconst __velarManagedAsyncPromisePrototype = __velarGraphOwnDescriptor(__velarManagedAsyncNativePromise, \"prototype\")?.value;\nconst __velarManagedAsyncResolveOperation = __velarGraphOwnDescriptor(__velarManagedAsyncNativePromise, \"resolve\")?.value;\nconst __velarManagedAsyncRejectOperation = __velarGraphOwnDescriptor(__velarManagedAsyncNativePromise, \"reject\")?.value;\nconst __velarManagedAsyncThenOperation = __velarManagedAsyncPromisePrototype\n ? __velarGraphOwnDescriptor(__velarManagedAsyncPromisePrototype, \"then\")?.value\n : null;\nfunction __velarManagedAsyncResolve(value) {\n return __velarGraphApply(__velarManagedAsyncResolveOperation, __velarManagedAsyncNativePromise, [value], \"Promise.resolve\");\n}\nfunction __velarManagedAsyncReject(error) {\n return __velarGraphApply(__velarManagedAsyncRejectOperation, __velarManagedAsyncNativePromise, [error], \"Promise.reject\");\n}\nfunction __velarManagedAsyncThen(value, fulfilled, rejected) {\n return __velarGraphApply(__velarManagedAsyncThenOperation, value, [fulfilled, rejected], \"Promise.then\");\n}\nfunction __velarManagedAsyncCreate(executor) {\n if (typeof __velarManagedAsyncNativePromise !== \"function\") throw new TypeError(\"The JavaScript Promise API is unavailable\");\n return new __velarManagedAsyncNativePromise(executor);\n}\n\nfunction __velarResource(load, scope, name) {\n const value = __velarState(null);\n const loading = __velarState(true);\n const ready = __velarState(false);\n const error = __velarState(null);\n let generation = 0;\n let started = false;\n let disposed = false;\n\n const reload = () => {\n if (disposed) return __velarManagedAsyncResolve(null);\n started = true;\n const current = ++generation;\n loading.set(true);\n error.set(null);\n return __velarManagedAsyncThen(__velarManagedAsyncThen(__velarManagedAsyncResolve(), load),\n (next) => {\n if (disposed || current !== generation) return null;\n value.set(next);\n ready.set(true);\n loading.set(false);\n return null;\n },\n (failure) => {\n if (disposed || current !== generation) return null;\n const report = __velarRuntime.report(failure, { phase: \"resource\", detail: name, component: scope.component, unhandled: false });\n error.set(report.error);\n ready.set(true);\n loading.set(false);\n return null;\n },\n );\n };\n\n __velarAppendOwned(scope.mounts, () => started ? null : reload());\n __velarAppendOwned(scope.cleanups, () => { disposed = true; generation += 1; });\n return __velarGraphFreeze({\n get value() { return value.get(); },\n get loading() { return loading.get(); },\n get ready() { return ready.get(); },\n get error() { return error.get(); },\n reload,\n });\n}\n\nfunction __velarAction(execute, scope, name) {\n const pending = __velarState(false);\n const error = __velarState(null);\n let active = 0;\n let generation = 0;\n let disposed = false;\n\n const run = (...arguments_) => {\n // D114 W2: the one place an action call enters the runtime. An action\n // started from inside an observer run is asynchronous work that observer\n // started, so the reactive window carries into the flush its completion\n // schedules; started from anywhere else it records nothing.\n __velarNoteAsyncWork();\n if (disposed) return __velarManagedAsyncReject(__velarNormalizeError(\n \"Action '\" + name + \"' cannot run after its component is destroyed\",\n ));\n const current = ++generation;\n active += 1;\n pending.set(true);\n error.set(null);\n return __velarManagedAsyncThen(__velarManagedAsyncThen(__velarManagedAsyncResolve(), () => __velarGraphApply(execute, null, arguments_, \"action body\")),\n (value) => {\n active -= 1;\n if (!disposed) pending.set(active > 0);\n return value;\n },\n (failure) => {\n active -= 1;\n let actionError = __velarNormalizeError(failure);\n if (!disposed) {\n pending.set(active > 0);\n // Every action failure reports exactly once, through the action\n // phase, carrying the action's name as its detail -- including a\n // failure superseded by a newer call. Only the newest generation\n // owns the public error field. The actionFailures mark lets the\n // event and detached observers of the same rejection skip an\n // already-reported failure instead of reporting it a second time.\n const report = __velarRuntime.report(failure, { phase: \"action\", detail: name, component: scope.component, unhandled: false });\n actionError = report.error;\n __velarGraphWeakSetInsert(__velarRuntime.actionFailures, actionError);\n if (current === generation) error.set(report.error);\n }\n throw actionError;\n },\n );\n };\n\n __velarGraphDefine(run, \"pending\", { enumerable: true, get: () => pending.get() });\n __velarGraphDefine(run, \"error\", { enumerable: true, get: () => error.get() });\n __velarAppendOwned(scope.cleanups, () => { disposed = true; generation += 1; });\n return __velarGraphFreeze(run);\n}\n\n" + "function __velarScope(component = \"\") {\n return { cleanups: [], mounts: [], mounted: false, component };\n}\n\nconst __velarGlobalScope = __velarScope();\n\nfunction __velarMountScope(scope) {\n if (scope.mounted) return;\n scope.mounted = true;\n for (let index = 0; index < scope.mounts.length; index += 1) {\n try {\n const result = __velarUntracked(scope.mounts[index]);\n __velarObservePromise(result, (error) => __velarReport(error, \"mounted\", scope));\n } catch (error) { __velarReport(error, \"mounted\", scope); }\n }\n}\n\nfunction __velarDestroyScope(scope) {\n for (let index = scope.cleanups.length - 1; index >= 0; index -= 1) {\n // A reentrant destroy can empty the list underneath this walk; a missing\n // slot means the step already ran and must not run again.\n const cleanup = scope.cleanups[index];\n if (typeof cleanup !== \"function\") continue;\n try {\n const result = __velarUntracked(cleanup);\n __velarObservePromise(result, (error) => __velarReport(error, \"cleanup\", scope));\n } catch (error) { __velarReport(error, \"cleanup\", scope); }\n }\n scope.cleanups.length = 0;\n}\n\nfunction __velarCleanupStep(run, scope) {\n try {\n const result = __velarUntracked(run);\n __velarObservePromise(result, (error) => __velarReport(error, \"cleanup\", scope));\n } catch (error) { __velarReport(error, \"cleanup\", scope); }\n}\n\n// D90 R21: nothing here asks whether this watch writes. Execution order is\n// source order, so the only thing the flush needs of a watch is when it was\n// registered, and __velarObserver stamps that on it. The label is the subject\n// as the author spelled it, carried so a runaway flush can name the watches\n// that ran away.\nfunction __velarWatch(read, callback, scope, label = \"\") {\n let current;\n let currentVersion = 0;\n let initialized = false;\n let observer = null;\n observer = __velarObserver(() => {\n const next = read();\n __velarRuntime.trackDeep(next);\n const nextVersion = __velarRuntime.versionOf(next);\n if (initialized && (!__velarGraphSame(next, current) || nextVersion !== currentVersion)) {\n // The body is the author's effect, not part of the watched expression:\n // its own reactive reads must never become dependencies of what is being\n // watched, or one write re-evaluates the expression twice and an\n // unwatched value re-runs the watch.\n __velarUntracked(() => callback(next, current));\n }\n current = next;\n currentVersion = nextVersion;\n initialized = true;\n }, \"watch\", scope, label);\n}\n\nfunction __velarComponentHandle(value, componentName) {\n if (value === null || typeof value !== \"object\") throw new TypeError(\"Component \" + componentName + \" must expose an ordinary Handle record\");\n const prototype = __velarGraphPrototype(value);\n if (prototype !== __velarGraphPrototype({}) && prototype !== null) throw new TypeError(\"Component \" + componentName + \" must expose an ordinary Handle record\");\n const output = {};\n let active = true;\n const names = __velarGraphOwnNames(value);\n for (let index = 0; index < names.length; index += 1) {\n const name = names[index];\n const descriptor = __velarGraphOwnDescriptor(value, name);\n if (!descriptor || !descriptor.enumerable || !(\"value\" in descriptor)) throw new TypeError(\"Component \" + componentName + \" Handle fields must be enumerable data values\");\n const member = typeof descriptor.value === \"function\"\n ? (...arguments_) => {\n if (!active) throw new Error(\"Component \" + componentName + \" Handle is no longer active\");\n return __velarGraphApply(descriptor.value, null, arguments_, \"component Handle method\");\n }\n : descriptor.value;\n __velarGraphDefine(output, name, { enumerable: true, value: member });\n }\n return __velarGraphFreeze({\n value: __velarGraphFreeze(output),\n revoke() { active = false; },\n });\n}\n\n" + "function __velarComponent(node, scope, mounted, cleanup, handleState) {\n let destroyed = false;\n const refCleanups = [];\n const ownedNodes = node && __velarDomNodeType(node) === 11 ? __velarDomChildNodes(node) : [node];\n // An enclosing component forwards to a nested component's host only when that\n // component's root sits at its own root level. Marking the nodes here is what\n // lets the enclosing scan walk past a nested host buried inside one of its\n // own elements instead of counting it as a second host of its own.\n for (let index = 0; index < ownedNodes.length; index += 1) {\n if (ownedNodes[index] && __velarDomNodeType(ownedNodes[index]) === 1) {\n __velarGraphDefine(ownedNodes[index], \"__velarComponentNode\", { value: true, enumerable: true, configurable: true });\n }\n }\n if (mounted) __velarAppendOwned(scope.mounts, mounted);\n return {\n __velarComponent: true,\n node,\n __bindRef(setRef) {\n if (!handleState) throw new TypeError(\"This component does not expose a Handle\");\n const handle = handleState.value;\n let bound = true;\n setRef(handle, undefined);\n __velarAppendOwned(refCleanups, () => {\n if (!bound) return;\n bound = false;\n setRef(null, handle);\n });\n return null;\n },\n mount(target, before = null) {\n if (destroyed) throw new Error(\"Cannot mount a destroyed VelarScript component\");\n if (scope.mounted) throw new Error(\"Cannot mount a VelarScript component more than once\");\n const parent = typeof target === \"string\" ? __velarDomQuerySelector(target) : target;\n if (!parent) throw new Error(\"VelarScript mount target was not found\");\n __velarDomInsertBefore(parent, node, before);\n __velarMountScope(scope);\n return null;\n },\n __mount() { if (!destroyed) __velarMountScope(scope); },\n destroy(remove = true) {\n if (destroyed) return null;\n destroyed = true;\n for (let index = refCleanups.length - 1; index >= 0; index -= 1) refCleanups[index]();\n refCleanups.length = 0;\n if (handleState) handleState.revoke();\n if (cleanup) {\n try {\n const result = __velarUntracked(cleanup);\n __velarObservePromise(result, (error) => __velarReport(error, \"cleanup\", scope));\n } catch (error) { __velarReport(error, \"cleanup\", scope); }\n }\n __velarDestroyScope(scope);\n if (remove) for (let index = 0; index < ownedNodes.length; index += 1) __velarDomRemove(ownedNodes[index]);\n return null;\n },\n };\n}\n\nfunction __velarScopeComponentRoot(node, attribute) {\n if (!attribute || !node) return;\n if (__velarDomNodeType(node) === 1) {\n __velarDomSetAttribute(node, attribute, \"\");\n return;\n }\n if (__velarDomNodeType(node) === 11) {\n const children = __velarDomChildNodes(node);\n for (let index = 0; index < children.length; index += 1) {\n if (__velarDomNodeType(children[index]) === 1) __velarDomSetAttribute(children[index], attribute, \"\");\n }\n }\n}\n\nfunction __velarUseComponent(instance, scope, parentStyleScope = \"\") {\n __velarScopeComponentRoot(instance.node, parentStyleScope);\n __velarAppendOwned(scope.mounts, () => instance.__mount());\n __velarAppendOwned(scope.cleanups, () => instance.destroy(false));\n return instance.node;\n}\n\n// D114 P6 item 5 (LC-C2): the compiler-owned fatal state, as one element. The\n// root replaces a mount target with it; a dynamic region that threw while it\n// was first constructed renders it in place of the position it could not build.\n// Both are the same element with the same role and the same attribute, because\n// they are the same promise -- \"no blank page\" -- kept at two scales, and an\n// assistive technology has to find them the same way.\n//\n// D114 F7-web-b: in the namespace of the position it stands in. An HTML\n// '<section>' inside '<svg>' is not an SVG element and a browser lays out none\n// of it, so the marker a region left inside a chart was the blank the promise\n// was made against -- and the role went with it. The SVG spelling is the one\n// 'velar/routing' already renders for a lazy component that fails inside a\n// chart: a 'g' carrying the role and the attribute, with the sentence in a\n// 'text' child. Same wording, same two markers, one namespace apart.\nfunction __velarFatalNode(message, namespace) {\n if (namespace === \"svg\") {\n const host = __velarDomCreateElementNS(__velarSvgNamespace, \"g\");\n __velarDomSetAttribute(host, \"role\", \"alert\");\n __velarDomSetAttribute(host, \"data-velar-fatal\", \"\");\n const label = __velarDomCreateElementNS(__velarSvgNamespace, \"text\");\n __velarDomSetText(label, message);\n __velarDomAppend(host, label);\n return host;\n }\n const fallback = __velarDomCreateElement(\"section\");\n __velarDomSetAttribute(fallback, \"role\", \"alert\");\n __velarDomSetAttribute(fallback, \"data-velar-fatal\", \"\");\n __velarDomSetText(fallback, message);\n return fallback;\n}\n\nfunction __velarFatal(parent, error) {\n __velarDomReplaceChildren(parent, __velarFatalNode(\"The application could not start: \" + error.message));\n}\n\n// Whether any root has actually mounted, which is the whole question the\n// deferred module failure below has to answer: the no-blank-page promise is\n// about a page with nothing on it, and a page that already has an application\n// on it is not one the fatal state may replace.\nlet __velarMountedRoot = false;\n\n// A component element built while the module evaluates sits outside every\n// transaction the runtime owns, so a construction throw there used to escape\n// module evaluation and leave the page blank -- the one initial-render path the\n// promise did not cover. The failure is caught into this value instead, and the\n// module keeps evaluating so the '@main' region still runs: that is where the\n// error handlers are installed and where 'mount' is called, and reporting ahead\n// of both would report to nobody.\nfunction __velarModuleInstantiate(component, thunks, children, scope, namespace, setRef) {\n try {\n return __velarInstantiate(component, thunks, children, scope, namespace, setRef);\n } catch (error) {\n const failure = { error, surfaced: false };\n // The mount that takes this root surfaces the failure at its own target.\n // Nothing having taken it by the first microtask means nothing ever will,\n // and a root that was built to be mounted and never was is still a blank\n // page: it surfaces there instead, into the document body.\n __velarEnqueue(() => __velarSurfaceModuleFailure(failure, null));\n return { __velarModuleFailure: failure };\n }\n}\n\nfunction __velarSurfaceModuleFailure(failure, parent) {\n if (failure.surfaced) return null;\n failure.surfaced = true;\n // The phase is 'mount' because this is the same failure 'mount(<App />, ...)'\n // reports under that phase; the two spellings of one root differ in where the\n // element is written, not in what went wrong.\n const report = __velarReport(failure.error, \"mount\", null);\n try {\n const target = parent ?? (__velarMountedRoot ? null : __velarDomQuerySelector(\"body\"));\n if (target) __velarFatal(target, report.error);\n } catch {}\n return null;\n}\n\nfunction __velarMount(evaluate, fallbackTarget = null) {\n let values;\n try {\n values = evaluate();\n } catch (failure) {\n const report = __velarReport(failure, \"mount\", null);\n if (fallbackTarget !== null) {\n try {\n const fallback = __velarDomQuerySelector(fallbackTarget);\n if (fallback) __velarFatal(fallback, report.error);\n } catch {}\n }\n return null;\n }\n const value = values[0];\n const target = values[1];\n const parent = typeof target === \"string\" ? __velarDomQuerySelector(target) : target;\n // A root whose construction failed while the module evaluated is answered\n // here, ahead of the missing-target question: the construction failure is the\n // cause, and reporting the target instead would name a symptom. The target\n // still decides where the fatal state renders, and a missing one falls back\n // to the document body exactly as it does below.\n if (value && value.__velarModuleFailure) {\n __velarSurfaceModuleFailure(value.__velarModuleFailure, parent || null);\n return null;\n }\n if (!parent) {\n // A missing mount target must keep the no-blank-page promise in every\n // build: the failure is reported through velar/app and the fatal state\n // renders into the document body, since the requested target is exactly\n // what does not exist.\n const report = __velarReport(new Error(\"VelarScript mount target was not found\"), \"mount\", null);\n try {\n const body = __velarDomQuerySelector(\"body\");\n if (body) __velarFatal(body, report.error);\n } catch {}\n return null;\n }\n try {\n if (value && value.__velarComponent) {\n const result = value.mount(parent);\n if (__velarGraphIsList(globalThis.__velarHotDisposers)) __velarAppendOwned(globalThis.__velarHotDisposers, () => value.destroy());\n __velarMountedRoot = true;\n return result;\n }\n __velarAppend(parent, value);\n __velarMountScope(__velarGlobalScope);\n __velarMountedRoot = true;\n return null;\n } catch (failure) {\n const report = __velarReport(failure, \"mount\", null);\n __velarFatal(parent, report.error);\n return null;\n }\n}\n\n" + "const __velarSvgNamespace = \"http://www.w3.org/2000/svg\";\nconst __velarXlinkNamespace = \"http://www.w3.org/1999/xlink\";\nconst __velarXmlNamespace = \"http://www.w3.org/XML/1998/namespace\";\n\nfunction __velarCreateElement(tag, namespace) {\n return namespace === \"svg\" || tag === \"svg\"\n ? __velarDomCreateElementNS(__velarSvgNamespace, tag)\n : __velarDomCreateElement(tag);\n}\n\nfunction __velarListSnapshot(value, name) {\n value = __velarToRaw(value);\n __velarRuntime.collectionRead(value, __velarWebIterateKey, undefined);\n return __velarDomListSnapshot(value, name);\n}\n\nfunction __velarAppend(parent, value, state = null) {\n state ??= { active: __velarDomCreateSet(), depth: 0, values: 0, text: 0 };\n if (value == null || value === false || value === true) return;\n state.values += 1;\n if (state.values > 1000000) throw new RangeError(\"JSX cannot render more than 1000000 values\");\n if (typeof value === \"string\") {\n state.text += value.length;\n if (state.text > 16 * 1024 * 1024) throw new RangeError(\"JSX text cannot exceed 16 MiB\");\n __velarDomAppend(parent, __velarDomCreateTextNode(value));\n return;\n }\n if (typeof value === \"number\") {\n if (!__velarDomIsFinite(value)) throw new TypeError(\"JSX numbers must be finite\");\n __velarDomAppend(parent, __velarDomCreateTextNode(__velarDomString(value)));\n return;\n }\n if (__velarDomIsNode(value)) { __velarDomAppend(parent, value); return; }\n if (__velarDomIsArray(value)) {\n if (state.depth >= 128) throw new RangeError(\"JSX Lists cannot exceed 128 nested levels\");\n if (__velarDomSetContains(state.active, value)) throw new TypeError(\"JSX cannot render a cyclic List\");\n const values = __velarListSnapshot(value, \"JSX children\");\n __velarDomSetInsert(state.active, value);\n state.depth += 1;\n try {\n for (let index = 0; index < values.length; index += 1) __velarAppend(parent, values[index], state);\n } finally {\n state.depth -= 1;\n __velarDomSetRemove(state.active, value);\n }\n return;\n }\n throw new TypeError(\"JSX can render only text, finite numbers, bool, enums, WebNode values, and Lists of those values\");\n}\n\n// The rendering region currently being constructed. A 'children' slot is built\n// by the position that shows it and must be destroyed with it, so the slot is\n// owned by this scope rather than by the caller's component scope, which would\n// keep every hidden build's observers alive for the component's whole lifetime.\nlet __velarBuildScope = null;\n\nfunction __velarChildrenNode(build, scope) {\n const owner = __velarBuildScope === null ? scope : __velarBuildScope;\n return __velarInternalRead(() => build(owner));\n}\n\n// The scalar half of __velarAppend, lifted out so a region that can only ever\n// hold one text node can be that text node. The two branches are __velarAppend's\n// own, error text included: the checked type admits an unsound value only where\n// the program lied about it, and such a value must land exactly where it landed\n// before -- rendered if it is text or a finite number, refused with the same\n// message otherwise.\nfunction __velarTextValue(value) {\n if (typeof value === \"string\") {\n if (value.length > 16 * 1024 * 1024) throw new RangeError(\"JSX text cannot exceed 16 MiB\");\n return value;\n }\n if (typeof value === \"number\") {\n if (!__velarDomIsFinite(value)) throw new TypeError(\"JSX numbers must be finite\");\n return __velarDomString(value);\n }\n throw new TypeError(\"JSX can render only text, finite numbers, bool, enums, WebNode values, and Lists of those values\");\n}\n\n// F1: an interpolation whose checked type is 'string' or 'number' renders\n// exactly one text node -- never zero, never markup, never a list. So it needs\n// no comment pair to bracket content that can never grow or vanish, and no\n// child scope to own observers that can never exist: the text node is its own\n// anchor and its own content, created once and updated by assigning its data.\n// That is the same node identity a comment anchor gave, so a keyed row that\n// starts or ends on one still finds its bounds, and a focused sibling is never\n// detached by an update.\nfunction __velarText(parent, read, scope) {\n let node = null;\n __velarObserver(() => {\n // Read and validate before touching the document: a failed update must\n // leave the last valid text standing, exactly as a failed rebuild leaves\n // the last valid region standing.\n const value = __velarTextValue(read());\n if (node === null) __velarDomAppend(parent, node = __velarDomCreateTextNode(value));\n else __velarDomSetData(node, value);\n }, \"dom\", scope);\n}\n\nfunction __velarDynamic(parent, read, scope, rootState = null) {\n const start = __velarDomCreateComment(\"velar:start\");\n const end = __velarDomCreateComment(\"velar:end\");\n __velarDomAppend(parent, start, end);\n let nodes = [];\n let childScope = null;\n __velarAppendOwned(scope.mounts, () => { if (childScope) __velarMountScope(childScope); });\n __velarObserver(() => {\n const nextScope = __velarScope(scope.component);\n const fragment = __velarDomCreateFragment();\n let nextHost = null;\n const previousBuildScope = __velarBuildScope;\n __velarBuildScope = nextScope;\n try {\n __velarAppend(fragment, read(nextScope));\n if (rootState) nextHost = __velarRootHost(fragment, \"dynamic component\");\n }\n catch (error) { __velarDestroyScope(nextScope); throw error; }\n finally { __velarBuildScope = previousBuildScope; }\n const nextNodes = __velarDomChildNodes(fragment);\n if (childScope) __velarDestroyScope(childScope);\n for (let index = 0; index < nodes.length; index += 1) __velarDomRemove(nodes[index]);\n __velarDomBefore(end, fragment);\n childScope = nextScope;\n nodes = nextNodes;\n if (rootState) {\n rootState.host = nextHost;\n for (const listener of __velarGraphSetItems(rootState.listeners)) listener(nextHost);\n }\n if (scope.mounted) __velarMountScope(nextScope);\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n if (childScope) __velarDestroyScope(childScope);\n for (let index = 0; index < nodes.length; index += 1) __velarDomRemove(nodes[index]);\n nodes = [];\n if (rootState) {\n rootState.host = null;\n for (const listener of __velarGraphSetItems(rootState.listeners)) listener(null);\n }\n });\n}\n\nfunction __velarDynamicComponent(read, scope) {\n const fragment = __velarDomCreateFragment();\n const rootState = { host: null, listeners: __velarGraphCreateSet() };\n __velarGraphDefine(fragment, \"__velarDynamicRoot\", { value: rootState });\n __velarDynamic(fragment, read, scope, rootState);\n return fragment;\n}\n\nfunction __velarKeyed(parent, read, keyOf, render, scope) {\n const start = __velarDomCreateComment(\"velar:keyed-start\");\n const end = __velarDomCreateComment(\"velar:keyed-end\");\n __velarDomAppend(parent, start, end);\n let entries = __velarGraphCreateMap();\n __velarAppendOwned(scope.mounts, () => { for (const entry of __velarGraphMapItems(entries)) __velarMountScope(entry.scope); });\n __velarObserver(() => {\n const source = __velarToRaw(read() ?? []);\n const values = __velarListSnapshot(source, \"Keyed JSX\");\n const next = __velarGraphCreateMap();\n const created = [];\n try {\n for (let index = 0; index < values.length; index += 1) {\n const rawValue = __velarToRaw(values[index]);\n // The keyed source may be a fresh derived List on every render. A row\n // is observed directly by its child scope, so linking it to that\n // ephemeral container only retains dead Lists and slows later writes.\n const trackedValue = __velarReactive(rawValue);\n const key = __velarKey(keyOf(trackedValue));\n if (__velarGraphMapContains(next, key)) throw new Error(\"Duplicate JSX key '\" + (typeof key === \"string\" ? key : __velarDomString(key)) + \"'\");\n let entry = __velarGraphMapRead(entries, key);\n if (entry && !__velarGraphSame(entry.value, rawValue)) entry = undefined;\n if (!entry) {\n const childScope = __velarScope(scope.component);\n const fragment = __velarDomCreateFragment();\n const previousBuildScope = __velarBuildScope;\n __velarBuildScope = childScope;\n try { __velarAppend(fragment, render(trackedValue, childScope)); }\n catch (error) { __velarDestroyScope(childScope); throw error; }\n finally { __velarBuildScope = previousBuildScope; }\n // A row is held by its first and last top-level nodes, never by a\n // snapshot of the list between them: every dynamic construct brackets\n // itself with comments created once, so those two nodes are stable\n // while everything between them is replaced over time. Caching the\n // whole list put destroyed nodes back into the document on a later\n // reorder and stranded the live ones outside their own markers.\n const rowNodes = __velarDomChildNodes(fragment);\n entry = {\n value: rawValue,\n scope: childScope,\n first: rowNodes.length > 0 ? rowNodes[0] : null,\n last: rowNodes.length > 0 ? rowNodes[rowNodes.length - 1] : null,\n fragment,\n };\n created[created.length] = entry;\n }\n __velarGraphMapWrite(next, key, entry);\n }\n } catch (error) {\n for (let index = 0; index < created.length; index += 1) __velarDestroyScope(created[index].scope);\n throw error;\n }\n for (const key of __velarGraphMapKeyItems(entries)) {\n const entry = __velarGraphMapRead(entries, key);\n if (__velarGraphMapRead(next, key) === entry) continue;\n __velarDestroyScope(entry.scope);\n let node = entry.first;\n while (node !== null && node !== end) {\n const following = __velarDomNextSibling(node);\n __velarDomRemove(node);\n if (node === entry.last) break;\n node = following;\n }\n }\n // A row already standing in its final position must not be detached and\n // reattached: that moves focus off a live <input>, ends IME composition,\n // and resets transient subtree state. The cursor walks the surviving nodes\n // in order and only moves a node that is not already where it belongs.\n let cursor = __velarDomNextSibling(start);\n for (const entry of __velarGraphMapItems(next)) {\n if (entry.fragment) {\n __velarDomBefore(cursor === null ? end : cursor, entry.fragment);\n entry.fragment = null;\n if (scope.mounted) __velarMountScope(entry.scope);\n continue;\n }\n let node = entry.first;\n while (node !== null && node !== end) {\n const following = __velarDomNextSibling(node);\n if (node === cursor) cursor = __velarDomNextSibling(cursor);\n else __velarDomBefore(cursor === null ? end : cursor, node);\n if (node === entry.last) break;\n node = following;\n }\n }\n entries = next;\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n for (const entry of __velarGraphMapItems(entries)) __velarDestroyScope(entry.scope);\n __velarGraphMapEmpty(entries);\n });\n}\n\n" + "function __velarStaticAttr(element, name, value) {\n if (value === false || value == null) return;\n __velarSetAttribute(element, name, __velarAttributeValue(value, name));\n}\n\nfunction __velarAttr(element, name, read, scope) {\n __velarObserver(() => {\n const value = read();\n if (value == null || value === false) __velarRemoveAttribute(element, name);\n else __velarSetAttribute(element, name, __velarAttributeValue(value, name));\n }, \"dom\", scope);\n}\n\n// The attributes whose value the user agent navigates or fetches. For these the\n// scheme is part of what the value means, so it is checked; every other\n// attribute takes its text unchanged.\nconst __velarUrlAttributes = [\"href\", \"src\", \"action\", \"formaction\", \"poster\", \"data\", \"xlink:href\", \"ping\", \"cite\"];\nconst __velarUrlSchemes = [\"http\", \"https\", \"mailto\", \"tel\", \"blob\"];\n// 'data:' carries its own payload, so it is admitted only for media types the\n// user agent cannot execute. 'image/svg+xml' is deliberately absent: an SVG\n// document can carry script.\nconst __velarInertDataTypes = [\n \"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\", \"image/avif\", \"image/bmp\", \"image/x-icon\",\n \"video/mp4\", \"video/webm\", \"video/ogg\", \"audio/mpeg\", \"audio/ogg\", \"audio/wav\", \"audio/webm\",\n \"font/woff\", \"font/woff2\", \"text/plain\",\n];\n\n// 'javascript:' and 'vbscript:' are code, not locations. A value that arrived as\n// data must never become code because it reached an href, so an unknown scheme\n// is refused rather than passed through.\nfunction __velarUrlAttributeValue(value, name) {\n let scheme = \"\";\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n // The user agent strips ASCII whitespace and control characters before it\n // parses the scheme, so \"java\\tscript:\" reads as \"javascript:\" to it and\n // has to read that way here too.\n if (code <= 0x20 || code === 0x7f) continue;\n if (code === 58 && scheme.length > 0) {\n const lowered = scheme.toLowerCase();\n if (lowered === \"data\") {\n const payload = value.slice(index + 1).toLowerCase();\n for (let type = 0; type < __velarInertDataTypes.length; type += 1) {\n if (payload.startsWith(__velarInertDataTypes[type])) return value;\n }\n throw new TypeError(\"JSX attribute '\" + name + \"' rejected a 'data:' URL whose media type is not a known inert one\");\n }\n if (__velarHasName(__velarUrlSchemes, lowered)) return value;\n throw new TypeError(\"JSX attribute '\" + name + \"' rejected the '\" + lowered + \":' URL scheme\");\n }\n const letter = (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n if (letter || (scheme.length > 0 && ((code >= 48 && code <= 57) || code === 43 || code === 45 || code === 46))) {\n scheme += value[index];\n continue;\n }\n // Anything else this early means the value names no scheme: it is a\n // relative URL, which is always the application's own origin.\n return value;\n }\n return value;\n}\n\nfunction __velarAttributeValue(value, name) {\n if (value === true) return \"\";\n if (typeof value === \"number\") {\n if (!__velarDomIsFinite(value)) throw new TypeError(\"JSX attribute '\" + name + \"' requires a finite number\");\n return __velarDomString(value);\n }\n if (typeof value !== \"string\") throw new TypeError(\"JSX attribute '\" + name + \"' requires text, a finite number, bool, an enum, or null\");\n if (value.length > 1024 * 1024) throw new RangeError(\"JSX attribute '\" + name + \"' cannot exceed 1 MiB\");\n if (__velarHasName(__velarUrlAttributes, name)) return __velarUrlAttributeValue(value, name);\n return value;\n}\n\nfunction __velarKey(value) {\n if (typeof value === \"number\") {\n if (!__velarDomIsFinite(value)) throw new TypeError(\"A JSX key number must be finite\");\n return value;\n }\n if (typeof value !== \"string\") throw new TypeError(\"A JSX key must be a string, string-backed enum, or finite number\");\n if (value.length > 65536) throw new RangeError(\"A JSX key cannot exceed 65536 characters\");\n return value;\n}\n\nfunction __velarSetAttribute(element, name, value) {\n if (name.startsWith(\"xlink:\")) __velarDomSetAttributeNS(element, __velarXlinkNamespace, name, value);\n else if (name.startsWith(\"xml:\")) __velarDomSetAttributeNS(element, __velarXmlNamespace, name, value);\n else __velarDomSetAttribute(element, name, value);\n}\n\nfunction __velarRemoveAttribute(element, name) {\n if (name.startsWith(\"xlink:\")) __velarDomRemoveAttributeNS(element, __velarXlinkNamespace, name.slice(6));\n else if (name.startsWith(\"xml:\")) __velarDomRemoveAttributeNS(element, __velarXmlNamespace, name.slice(4));\n else __velarDomRemoveAttribute(element, name);\n}\n\n" + "function __velarClass(element, name, read, scope) {\n __velarClassBind(element, () => read() ? name : null, scope);\n}\n\n// The property a token carries. A token is '[target:]conditions:property' and\n// a CSS property name never contains ':', so the last segment is the property.\nfunction __velarLookProperty(token) {\n return token.slice(token.lastIndexOf(\":\") + 1);\n}\n\n// The surface a token writes on: its pseudo-element target, if it has one, plus\n// its property. Composition overrides a property on the surface that owns it —\n// '@before: content' and a bare 'content' are two surfaces, not one property\n// written under two conditions.\nfunction __velarLookSurface(token) {\n const first = token.indexOf(\":\");\n const last = token.lastIndexOf(\":\");\n return (first === last ? \"\" : token.slice(0, first + 1)) + token.slice(last + 1);\n}\n\n// Whether a token declares its property unconditionally: an unconditional\n// declaration spells its condition segment 'base', so the segment in front of\n// the property is what says a token stands on its own.\nfunction __velarLookUnconditional(token) {\n const last = token.lastIndexOf(\":\");\n return token.slice(token.lastIndexOf(\":\", last - 1) + 1, last) === \"base\";\n}\n\n// Composition is property-level across sources and token-level inside one look\n// block. A later unconditional declaration wins its property outright, so it\n// drops every condition the earlier sources wrote it under: the caller of a\n// component could otherwise not reach a padding the component set behind its\n// own private breakpoint, and 'the caller wins every property both of them set'\n// was true only under the identical condition (LOK-U10). A later conditional\n// declaration refines rather than replaces — it overwrites the identical token\n// and leaves the earlier unconditional value standing, because a caller that\n// writes only 'if @hover: color' never mentioned the resting colour and must\n// not delete it. Declarations written in one block are one source, so a block's\n// own 'if scheme.dark:' and 'if @hover:' still coexist and the cascade decides\n// between them.\nfunction __velarMergeRules(rules, groups, source, group) {\n const names = __velarGraphOwnNames(source);\n const owned = __velarGraphOwnNames(rules);\n for (let index = 0; index < names.length; index += 1) {\n const descriptor = __velarGraphOwnDescriptor(source, names[index]);\n if (!descriptor || !(\"value\" in descriptor)) continue;\n if (!__velarLookUnconditional(names[index])) continue;\n const surface = __velarLookSurface(names[index]);\n for (let other = 0; other < owned.length; other += 1) {\n const token = owned[other];\n if (groups[token] === group || __velarLookSurface(token) !== surface) continue;\n delete rules[token];\n delete groups[token];\n }\n }\n for (let index = 0; index < names.length; index += 1) {\n const descriptor = __velarGraphOwnDescriptor(source, names[index]);\n if (!descriptor || !(\"value\" in descriptor)) continue;\n if (descriptor.value == null) { delete rules[names[index]]; delete groups[names[index]]; continue; }\n rules[names[index]] = descriptor.value;\n groups[names[index]] = group;\n }\n}\n\nfunction __velarLook(parts) {\n const rules = __velarGraphCreateRecord();\n const groups = __velarGraphCreateRecord();\n // A built Look is one source. A bare rules record is a run of declarations\n // written in one look block, so consecutive ones share a source and a spread\n // between them opens the next.\n let group = 0;\n let run = 0;\n const add = (part) => {\n if (part == null || part === false) return;\n if (__velarGraphIsList(part)) { for (let index = 0; index < part.length; index += 1) add(part[index]); return; }\n if (part.__velarLook === true) {\n group += 1;\n run = 0;\n __velarMergeRules(rules, groups, part.rules, group);\n return;\n }\n if (part.rules && typeof part.rules === \"object\") {\n if (run === 0) { group += 1; run = group; }\n __velarMergeRules(rules, groups, part.rules, run);\n return;\n }\n throw new TypeError(\"look composition accepts only Look, Look?, or lists of Look values\");\n };\n add(parts);\n return __velarGraphFreeze({ __velarLook: true, rules: __velarGraphFreeze(rules) });\n}\n\nfunction __velarKeyframesValue(name) {\n if (typeof name !== \"string\" || !/^velar-kf-[0-9a-f]{8,32}$/.test(name)) throw new TypeError(\"Generated keyframes name is invalid\");\n return __velarGraphFreeze({ __velarKeyframes: true, name });\n}\n\nfunction __velarLookVariable(token) {\n return \"--velar-look-\" + token.replace(/[^A-Za-z0-9_-]+/g, \"-\");\n}\n\nfunction __velarLookValue(token, value) {\n if (token.endsWith(\":animation\")) return __velarAnimationLookValue(value);\n if (typeof value === \"number\") {\n if (!__velarDomIsFinite(value)) throw new TypeError(\"Look properties require finite numbers\");\n return __velarDomString(value);\n }\n if (typeof value !== \"string\") throw new TypeError(\"Look properties require text, finite numbers, typed visual values, or null\");\n if (value.length > 1024 * 1024) throw new RangeError(\"A Look property value cannot exceed 1 MiB\");\n if (token.endsWith(\":content\") && typeof value === \"string\" && value !== \"none\" && value !== \"normal\") return __velarCssString(value);\n // A closed keyword set is the property's whole string vocabulary, so a value\n // the compiler could not read — a prop, a record field, a call result — is\n // checked here instead. Without this a 'display' bound to \"grdi\" reached the\n // browser as a declaration it silently discards (LOK-U14).\n const keywords = __velarLookKeywords[__velarLookProperty(token)];\n if (keywords !== undefined && !__velarHasName(keywords, value.trim())) {\n let expected = \"\";\n for (let index = 0; index < keywords.length; index += 1) expected += (expected === \"\" ? \"\" : \", \") + keywords[index];\n throw new TypeError(\"Look property '\" + __velarLookProperty(token) + \"' does not accept '\" + value + \"'; use one of \" + expected);\n }\n return value;\n}\n\nfunction __velarAnimationLookValue(value) {\n const parts = [];\n const add = (item) => {\n if (__velarGraphIsList(item)) {\n for (let index = 0; index < item.length; index += 1) add(item[index]);\n return;\n }\n const marker = item && (typeof item === \"object\" || typeof item === \"function\")\n ? __velarGraphOwnDescriptor(item, \"__velarAnimation\") : null;\n const css = item && (typeof item === \"object\" || typeof item === \"function\")\n ? __velarGraphOwnDescriptor(item, \"css\") : null;\n if (!marker || !(\"value\" in marker) || marker.value !== true || !css || !(\"value\" in css) || typeof css.value !== \"string\") {\n throw new TypeError(\"Look animation requires Animation or a List of Animation values from animate()\");\n }\n __velarAppendOwned(parts, css.value);\n };\n add(value);\n if (parts.length === 0) throw new TypeError(\"A Look animation list cannot be empty\");\n let output = parts[0];\n for (let index = 1; index < parts.length; index += 1) output += \", \" + parts[index];\n return output;\n}\n\nconst __velarInlineStyleProperties = __velarGraphCreateSet([\"display\",\"position\",\"box-sizing\",\"isolation\",\"contain\",\"visibility\",\"z-index\",\"overflow\",\"overflow-x\",\"overflow-y\",\"resize\",\"clip\",\"clip-path\",\"object-fit\",\"object-position\",\"aspect-ratio\",\"grid-template-columns\",\"grid-template-rows\",\"grid-template-areas\",\"grid-auto-columns\",\"grid-auto-rows\",\"grid-auto-flow\",\"grid-column\",\"grid-column-start\",\"grid-column-end\",\"grid-row\",\"grid-row-start\",\"grid-row-end\",\"grid-area\",\"flex\",\"flex-direction\",\"flex-grow\",\"flex-shrink\",\"flex-basis\",\"flex-wrap\",\"order\",\"gap\",\"row-gap\",\"column-gap\",\"align-items\",\"justify-items\",\"justify-content\",\"align-content\",\"align-self\",\"justify-self\",\"place-items\",\"place-content\",\"place-self\",\"width\",\"height\",\"min-width\",\"max-width\",\"min-height\",\"max-height\",\"inline-size\",\"block-size\",\"min-inline-size\",\"max-inline-size\",\"min-block-size\",\"max-block-size\",\"inset\",\"top\",\"right\",\"bottom\",\"left\",\"inset-inline\",\"inset-block\",\"inset-inline-start\",\"inset-inline-end\",\"inset-block-start\",\"inset-block-end\",\"padding\",\"padding-top\",\"padding-right\",\"padding-bottom\",\"padding-left\",\"padding-inline\",\"padding-block\",\"padding-inline-start\",\"padding-inline-end\",\"padding-block-start\",\"padding-block-end\",\"margin\",\"margin-top\",\"margin-right\",\"margin-bottom\",\"margin-left\",\"margin-inline\",\"margin-block\",\"margin-inline-start\",\"margin-inline-end\",\"margin-block-start\",\"margin-block-end\",\"background\",\"background-color\",\"background-image\",\"background-position\",\"background-size\",\"background-repeat\",\"background-attachment\",\"background-clip\",\"background-origin\",\"background-blend-mode\",\"border\",\"border-width\",\"border-style\",\"border-color\",\"border-top\",\"border-right\",\"border-bottom\",\"border-left\",\"border-top-width\",\"border-right-width\",\"border-bottom-width\",\"border-left-width\",\"border-top-style\",\"border-right-style\",\"border-bottom-style\",\"border-left-style\",\"border-top-color\",\"border-right-color\",\"border-bottom-color\",\"border-left-color\",\"border-radius\",\"border-top-left-radius\",\"border-top-right-radius\",\"border-bottom-right-radius\",\"border-bottom-left-radius\",\"outline\",\"outline-width\",\"outline-style\",\"outline-color\",\"outline-offset\",\"box-shadow\",\"text-shadow\",\"opacity\",\"filter\",\"backdrop-filter\",\"content\",\"color\",\"font-family\",\"font-size\",\"font-weight\",\"font-style\",\"font-stretch\",\"font-variant\",\"font-kerning\",\"font-optical-sizing\",\"font-feature-settings\",\"font-variation-settings\",\"line-height\",\"vertical-align\",\"letter-spacing\",\"word-spacing\",\"text-align\",\"text-indent\",\"text-decoration\",\"text-decoration-color\",\"text-decoration-line\",\"text-decoration-style\",\"text-decoration-thickness\",\"text-underline-offset\",\"text-underline-position\",\"text-transform\",\"text-rendering\",\"white-space\",\"text-overflow\",\"text-wrap\",\"overflow-wrap\",\"word-break\",\"hyphens\",\"tab-size\",\"writing-mode\",\"text-orientation\",\"direction\",\"unicode-bidi\",\"list-style\",\"list-style-type\",\"list-style-position\",\"list-style-image\",\"fill\",\"stroke\",\"stroke-width\",\"stroke-linecap\",\"stroke-linejoin\",\"stroke-dasharray\",\"stroke-dashoffset\",\"translate\",\"scale\",\"rotate\",\"transform\",\"transform-origin\",\"transition\",\"transition-property\",\"transition-duration\",\"transition-delay\",\"transition-timing-function\",\"animation\",\"cursor\",\"pointer-events\",\"user-select\",\"touch-action\",\"appearance\",\"accent-color\",\"caret-color\",\"color-scheme\",\"scroll-behavior\",\"scroll-margin\",\"scroll-margin-top\",\"scroll-margin-right\",\"scroll-margin-bottom\",\"scroll-margin-left\",\"scroll-padding\",\"scroll-padding-top\",\"scroll-padding-right\",\"scroll-padding-bottom\",\"scroll-padding-left\",\"scroll-snap-align\",\"scroll-snap-stop\",\"scroll-snap-type\",\"overscroll-behavior\",\"overscroll-behavior-x\",\"overscroll-behavior-y\",\"scrollbar-color\",\"scrollbar-width\"]);\n\nfunction __velarStyleDeclarations(value) {\n if (!value || typeof value !== \"object\" || __velarGraphIsList(value)\n || (__velarGraphPrototype(value) !== __velarGraphNativeObject.prototype && __velarGraphPrototype(value) !== null)\n || __velarWebErrorOwnSymbols(value).length > 0) {\n throw new TypeError(\"style:* requires compiler-owned inline declarations\");\n }\n const names = __velarGraphOwnNames(value);\n if (names.length > 225) throw new RangeError(\"An inline Style has too many properties\");\n const output = {};\n for (let index = 0; index < names.length; index += 1) {\n const property = names[index];\n if (!__velarGraphSetContains(__velarInlineStyleProperties, property)) throw new TypeError(\"Unknown inline Style property '\" + property + \"'\");\n const descriptor = __velarGraphOwnDescriptor(value, property);\n if (!descriptor || !descriptor.enumerable || !(\"value\" in descriptor)) throw new TypeError(\"Inline Style declarations cannot use accessors\");\n __velarGraphDefine(output, property, { value: descriptor.value, enumerable: true, configurable: false, writable: false });\n }\n return __velarGraphFreeze(output);\n}\n\nfunction __velarInlineStyleState(element) {\n const current = __velarGraphOwnDescriptor(element, \"__velarInlineStyleState\");\n if (current) {\n if (!(\"value\" in current) || current.enumerable || current.configurable || current.writable\n || !current.value || typeof current.value !== \"object\") throw new TypeError(\"Inline Style ownership is invalid\");\n return current.value;\n }\n const state = __velarGraphFreeze({ base: __velarGraphCreateMap(), managed: __velarGraphCreateSet() });\n __velarGraphDefine(element, \"__velarInlineStyleState\", { value: state });\n return state;\n}\n\nfunction __velarAttachSource(registry, element, source) {\n let sources = __velarGraphWeakMapRead(registry, element);\n if (!sources) { sources = __velarGraphCreateSet(); __velarGraphWeakMapWrite(registry, element, sources); }\n __velarGraphSetInsert(sources, source);\n return sources;\n}\n\nfunction __velarDetachSource(registry, element, source) {\n const sources = __velarGraphWeakMapRead(registry, element);\n if (!sources) return;\n __velarGraphSetRemove(sources, source);\n if (__velarGraphSetCount(sources) === 0) __velarGraphWeakMapRemove(registry, element);\n}\n\nfunction __velarApplyStyles(element) {\n const sources = __velarGraphWeakMapRead(__velarRuntime.lookSources, element);\n const merged = __velarGraphCreateMap();\n if (sources) {\n for (const source of __velarGraphSetItems(sources)) {\n if (!source.styles) continue;\n const names = __velarGraphOwnNames(source.styles);\n for (let index = 0; index < names.length; index += 1) {\n __velarGraphMapWrite(merged, names[index], __velarGraphOwnDescriptor(source.styles, names[index]).value);\n }\n }\n }\n const state = __velarInlineStyleState(element);\n const next = __velarGraphCreateSet(__velarGraphMapKeyItems(merged));\n for (const property of __velarGraphSetItems(next)) {\n if (__velarGraphSetContains(state.managed, property)) continue;\n __velarGraphMapWrite(state.base, property, {\n value: __velarDomStyleValue(element, property),\n priority: __velarDomStylePriority(element, property),\n });\n }\n for (const property of __velarGraphSetItems(state.managed)) {\n if (__velarGraphSetContains(next, property)) continue;\n const base = __velarGraphMapRead(state.base, property);\n if (!base || (base.value === \"\" && base.priority === \"\")) __velarDomStyleClear(element, property);\n else __velarDomStyleWrite(element, property, base.value, base.priority);\n __velarGraphMapRemove(state.base, property);\n }\n for (const property of __velarGraphSetItems(next)) {\n const value = __velarGraphMapRead(merged, property);\n if (value == null) __velarDomStyleClear(element, property);\n else __velarDomStyleWrite(element, property, __velarLookValue(\"base:\" + property, value));\n }\n __velarGraphSetEmpty(state.managed);\n for (const property of __velarGraphSetItems(next)) __velarGraphSetInsert(state.managed, property);\n}\n\nfunction __velarStyleBind(element, read, scope) {\n const source = { rules: __velarGraphCreateRecord(), styles: {} };\n __velarAttachSource(__velarRuntime.lookSources, element, source);\n __velarObserver(() => {\n source.styles = __velarStyleDeclarations(read());\n __velarApplyStyles(element);\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n __velarDetachSource(__velarRuntime.lookSources, element, source);\n __velarApplyStyles(element);\n });\n}\n\nfunction __velarMoveStyleSource(source, previous, next) {\n if (previous) {\n __velarDetachSource(__velarRuntime.lookSources, previous, source);\n __velarApplyStyles(previous);\n }\n if (next) {\n __velarAttachSource(__velarRuntime.lookSources, next, source);\n __velarApplyStyles(next);\n }\n}\n\n// The dynamic-root marker sits on a fragment the emitter created, but the\n// fragment is still a host object: a planted prototype getter would otherwise\n// hand look/class/style application a forged host element.\nfunction __velarDynamicRootState(root) {\n if (root === null || root === undefined) return null;\n const descriptor = __velarGraphOwnDescriptor(root, \"__velarDynamicRoot\");\n return descriptor && \"value\" in descriptor && descriptor.value && typeof descriptor.value === \"object\"\n ? descriptor.value\n : null;\n}\n\nfunction __velarStyleBindRoot(root, read, scope) {\n const dynamic = __velarDynamicRootState(root);\n if (!dynamic) {\n __velarStyleBind(__velarRootHost(root, \"style\"), read, scope);\n return;\n }\n const source = { rules: __velarGraphCreateRecord(), styles: {} };\n let host = null;\n const move = (next) => {\n __velarMoveStyleSource(source, host, next);\n host = next;\n };\n __velarGraphSetInsert(dynamic.listeners, move);\n move(dynamic.host);\n __velarObserver(() => {\n source.styles = __velarStyleDeclarations(read());\n if (host) __velarApplyStyles(host);\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n __velarGraphSetRemove(dynamic.listeners, move);\n move(null);\n });\n}\n\n// Look and class ownership lives in one non-enumerable, non-configurable data\n// property per element, discovered through the captured descriptor ABI exactly\n// like inline style ownership. An ambient expando read would let a hostile\n// prototype hand the framework a forged token set.\nfunction __velarElementState(element, name, create) {\n const current = __velarGraphOwnDescriptor(element, name);\n if (current) {\n if (!(\"value\" in current) || current.enumerable || current.configurable || current.writable\n || !current.value || typeof current.value !== \"object\") throw new TypeError(\"VelarScript element ownership is invalid\");\n return current.value;\n }\n const state = create();\n __velarGraphDefine(element, name, { value: state });\n return state;\n}\n\nfunction __velarApplyLooks(element) {\n const sources = __velarGraphWeakMapRead(__velarRuntime.lookSources, element);\n const merged = __velarGraphCreateRecord();\n const groups = __velarGraphCreateRecord();\n if (sources) {\n // Each attached source is one Look, so a source that sets a property\n // unconditionally drops the property's other conditions from the sources\n // before it: the caller of a component composes after the component's own\n // host look and wins every property both of them set, whatever condition\n // either wrote it under. A source that writes the property only under a\n // condition refines that condition alone — the identical token is\n // overwritten and the earlier unconditional value stays, so the caller does\n // not delete a resting value it never mentioned.\n //\n // A null rule keeps its token: the token drives the generated selector and\n // only the custom property behind it disappears.\n let group = 0;\n for (const source of __velarGraphSetItems(sources)) {\n group += 1;\n const names = __velarGraphOwnNames(source.rules);\n const owned = __velarGraphOwnNames(merged);\n for (let index = 0; index < names.length; index += 1) {\n // A rule the assignment pass below refuses to read must not clear the\n // earlier sources either, or the property disappears with nothing put\n // in its place — the same 'a source deletes a value it never replaces'\n // shape the conditional guard above closes. '__velarMergeRules' spells\n // the test the same way.\n const descriptor = __velarGraphOwnDescriptor(source.rules, names[index]);\n if (!descriptor || !(\"value\" in descriptor)) continue;\n if (!__velarLookUnconditional(names[index])) continue;\n const surface = __velarLookSurface(names[index]);\n for (let other = 0; other < owned.length; other += 1) {\n if (groups[owned[other]] === group || __velarLookSurface(owned[other]) !== surface) continue;\n delete merged[owned[other]];\n delete groups[owned[other]];\n }\n }\n for (let index = 0; index < names.length; index += 1) {\n const descriptor = __velarGraphOwnDescriptor(source.rules, names[index]);\n if (!descriptor || !(\"value\" in descriptor)) continue;\n merged[names[index]] = descriptor.value;\n groups[names[index]] = group;\n }\n }\n }\n // The last value written per token, so a reactive change to one dynamic\n // property costs one DOM write instead of one per token plus a full attribute\n // rewrite (LOK-U15).\n const state = __velarElementState(element, \"__velarLookTokens\", () => __velarGraphFreeze({\n tokens: __velarGraphCreateSet(), written: { record: __velarGraphCreateRecord(), attribute: undefined },\n }));\n const written = state.written.record;\n const tokens = __velarGraphOwnNames(merged);\n const next = __velarGraphCreateSet(tokens);\n for (const token of __velarGraphSetItems(state.tokens)) {\n if (__velarGraphSetContains(next, token)) continue;\n __velarDomStyleClear(element, __velarLookVariable(token));\n delete written[token];\n }\n let attribute = \"\";\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index];\n const value = __velarGraphOwnDescriptor(merged, token)?.value;\n const text = value == null ? null : __velarLookValue(token, value);\n if (!(token in written) || written[token] !== text) {\n if (text === null) __velarDomStyleClear(element, __velarLookVariable(token));\n else __velarDomStyleWrite(element, __velarLookVariable(token), text);\n written[token] = text;\n }\n attribute = attribute === \"\" ? token : attribute + \" \" + token;\n }\n const desired = tokens.length === 0 ? null : attribute;\n if (state.written.attribute !== desired) {\n if (desired === null) __velarDomRemoveAttribute(element, \"data-velar-look\");\n else __velarDomSetAttribute(element, \"data-velar-look\", desired);\n state.written.attribute = desired;\n }\n __velarGraphSetEmpty(state.tokens);\n for (let index = 0; index < tokens.length; index += 1) __velarGraphSetInsert(state.tokens, tokens[index]);\n}\n\nfunction __velarLookBind(element, read, scope) {\n const source = { rules: __velarGraphCreateRecord() };\n __velarAttachSource(__velarRuntime.lookSources, element, source);\n __velarObserver(() => {\n source.rules = __velarLook([read()]).rules;\n __velarApplyLooks(element);\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n __velarDetachSource(__velarRuntime.lookSources, element, source);\n __velarApplyLooks(element);\n });\n}\n\nfunction __velarMoveLookSource(source, previous, next) {\n if (previous) {\n __velarDetachSource(__velarRuntime.lookSources, previous, source);\n __velarApplyLooks(previous);\n }\n if (next) {\n __velarAttachSource(__velarRuntime.lookSources, next, source);\n __velarApplyLooks(next);\n }\n}\n\nfunction __velarApplyExternalLook(element, value) {\n const source = { rules: __velarLook([value]).rules };\n __velarAttachSource(__velarRuntime.lookSources, element, source);\n __velarApplyLooks(element);\n return () => {\n __velarDetachSource(__velarRuntime.lookSources, element, source);\n __velarApplyLooks(element);\n };\n}\n\n__velarRuntime.installLook(__velarApplyExternalLook);\n\n// One resolution per root, shared by every capability bound to it: look, class\n// and style used to pay a fresh O(subtree) walk each.\n" + "const __velarRootHosts = __velarGraphCreateWeakMap();\n\nfunction __velarRootHostResolve(root) {\n const elements = [];\n const children = __velarDomChildNodes(root);\n for (let index = 0; index < children.length; index += 1) {\n if (__velarDomNodeType(children[index]) === 1) __velarAppendOwned(elements, children[index]);\n }\n const explicit = [];\n const forwarded = [];\n for (let index = 0; index < elements.length; index += 1) {\n const element = elements[index];\n // A nested component's own, perfectly legal host is that component's, not\n // this one's, at the root level exactly as below it. Every root-level node\n // of a nested component carries the marker and this component's own nodes\n // do not yet — construction marks them after a caller's look binds — so\n // the marker is what separates the two. Reading 'host' first counted a\n // nested component's marked root as a second host of the enclosing one and\n // collapsed the whole region, which is the buried-host defect standing at\n // the root level instead of below it. Such a node is not this component's\n // host but the host this component forwards to when it declares none of\n // its own, so it is collected apart rather than dropped.\n if (__velarDomOwnData(element, \"__velarComponentNode\") === true) {\n if (__velarDomOwnData(element, \"__velarHost\") === true) __velarAppendOwned(forwarded, element);\n continue;\n }\n if (__velarDomOwnData(element, \"__velarHost\") === true) { __velarAppendOwned(explicit, element); continue; }\n // A walk that refuses to enter a marked node stops at a nested component's\n // boundary whatever depth its host sits at; a flat 'querySelectorAll' scan\n // could only skip the marked node itself and still counted a host one level\n // below it.\n const pending = [element];\n for (let cursor = 0; cursor < pending.length; cursor += 1) {\n const nodes = __velarDomChildNodes(pending[cursor]);\n for (let child = 0; child < nodes.length; child += 1) {\n const node = nodes[child];\n if (__velarDomNodeType(node) !== 1) continue;\n if (__velarDomOwnData(node, \"__velarComponentNode\") === true) continue;\n if (__velarDomOwnData(node, \"__velarHost\") === true) __velarAppendOwned(explicit, node);\n __velarAppendOwned(pending, node);\n }\n }\n }\n if (explicit.length === 1) return explicit[0];\n if (explicit.length > 1) return \"A component can declare only one host element\";\n // Nothing of this component's own is marked, so a single nested component\n // root hands its host on. Two of them leave nothing to forward to, and the\n // component has to mark a native element of its own to settle it.\n if (forwarded.length === 1) return forwarded[0];\n if (forwarded.length > 1) return \"A component with multiple roots must mark exactly one native element with 'host'\";\n if (elements.length === 1) return elements[0];\n return \"A component with multiple roots must mark exactly one native element with 'host'\";\n}\n\nfunction __velarRootHost(root, capability) {\n if (root == null) throw new TypeError(\"A component with multiple roots must mark exactly one native element with 'host'\");\n if (__velarDomNodeType(root) === 1) return root;\n let resolved = __velarGraphWeakMapRead(__velarRootHosts, root);\n if (resolved === undefined) {\n resolved = __velarRootHostResolve(root);\n __velarGraphWeakMapWrite(__velarRootHosts, root, resolved);\n }\n if (typeof resolved === \"string\") throw new TypeError(resolved);\n return resolved;\n}\n\nfunction __velarLookBindRoot(root, read, scope) {\n const dynamic = __velarDynamicRootState(root);\n if (!dynamic) {\n __velarLookBind(__velarRootHost(root, \"look\"), read, scope);\n return;\n }\n const source = { rules: __velarGraphCreateRecord() };\n let host = null;\n const move = (next) => {\n __velarMoveLookSource(source, host, next);\n host = next;\n };\n __velarGraphSetInsert(dynamic.listeners, move);\n move(dynamic.host);\n __velarObserver(() => {\n source.rules = __velarLook([read()]).rules;\n if (host) __velarApplyLooks(host);\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n __velarGraphSetRemove(dynamic.listeners, move);\n move(null);\n });\n}\n\nfunction __velarClassBindRoot(root, read, scope) {\n const dynamic = __velarDynamicRootState(root);\n if (!dynamic) {\n __velarClassBind(__velarRootHost(root, \"class\"), read, scope);\n return;\n }\n const source = { names: [] };\n let host = null;\n const move = (next) => {\n __velarMoveClassSource(source, host, next);\n host = next;\n };\n __velarGraphSetInsert(dynamic.listeners, move);\n move(dynamic.host);\n __velarObserver(() => {\n source.names = __velarClassNames(read());\n if (host) __velarApplyClasses(host);\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n __velarGraphSetRemove(dynamic.listeners, move);\n move(null);\n });\n}\n\nfunction __velarClassNames(value, output = []) {\n if (value == null || value === false) return output;\n if (__velarGraphIsList(value)) {\n for (let index = 0; index < value.length; index += 1) __velarClassNames(value[index], output);\n return output;\n }\n if (typeof value !== \"string\") throw new TypeError(\"class accepts strings, string?, or lists of strings\");\n let name = \"\";\n for (let index = 0; index < value.length; index += 1) {\n const character = value[index];\n if (character === \" \" || character === \"\\t\" || character === \"\\n\" || character === \"\\r\" || character === \"\\f\" || character === \"\\v\") {\n if (name !== \"\") __velarAppendOwned(output, name);\n name = \"\";\n continue;\n }\n name += character;\n }\n if (name !== \"\") __velarAppendOwned(output, name);\n return output;\n}\n\nfunction __velarApplyClasses(element) {\n const sources = __velarGraphWeakMapRead(__velarRuntime.classSources, element);\n const next = __velarGraphCreateSet();\n if (sources) {\n for (const source of __velarGraphSetItems(sources)) {\n for (let index = 0; index < source.names.length; index += 1) __velarGraphSetInsert(next, source.names[index]);\n }\n }\n const state = __velarElementState(element, \"__velarClassState\", () => __velarGraphFreeze({\n base: __velarGraphCreateSet(__velarDomClassNames(element)),\n managed: __velarGraphCreateSet(),\n }));\n for (const name of __velarGraphSetItems(state.managed)) {\n if (!__velarGraphSetContains(next, name) && !__velarGraphSetContains(state.base, name)) __velarDomClassRemove(element, name);\n }\n for (const name of __velarGraphSetItems(next)) __velarDomClassInsert(element, name);\n __velarGraphSetEmpty(state.managed);\n for (const name of __velarGraphSetItems(next)) __velarGraphSetInsert(state.managed, name);\n}\n\nfunction __velarMoveClassSource(source, previous, next) {\n if (previous) {\n __velarDetachSource(__velarRuntime.classSources, previous, source);\n __velarApplyClasses(previous);\n }\n if (next) {\n __velarAttachSource(__velarRuntime.classSources, next, source);\n __velarApplyClasses(next);\n }\n}\n\nfunction __velarClassBind(element, read, scope) {\n const source = { names: [] };\n __velarAttachSource(__velarRuntime.classSources, element, source);\n __velarObserver(() => {\n source.names = __velarClassNames(read());\n __velarApplyClasses(element);\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n __velarDetachSource(__velarRuntime.classSources, element, source);\n __velarApplyClasses(element);\n });\n}\n\n" + "function __velarHtml(element, read, scope) {\n __velarObserver(() => {\n const value = read();\n if (value != null && typeof value !== \"string\") throw new TypeError(\"unsafe:html requires string or null\");\n if (value?.length > 16 * 1024 * 1024) throw new RangeError(\"unsafe:html cannot exceed 16 MiB\");\n __velarDomSetHtml(element, value ?? \"\");\n }, \"dom\", scope);\n}\n\nfunction __velarOn(element, event, read, scope, modifiers = []) {\n if (typeof __velarInternalRead(read) !== \"function\") throw new TypeError(\"Event '\" + event + \"' requires a function\");\n const capture = __velarHasName(modifiers, \"capture\");\n const once = __velarHasName(modifiers, \"once\");\n let removed = false;\n const remove = () => {\n if (removed) return;\n removed = true;\n __velarDomRemoveListener(element, event, listener, capture);\n };\n const listener = (value) => {\n try {\n if (__velarHasName(modifiers, \"self\")) {\n const target = __velarEventField(value, \"target\", __velarEventTargetGetter);\n if (target === __velarEventMissingField) throw new TypeError(\"DOM event does not expose a native target\");\n if (target !== element) return;\n }\n // 'once' is spent here rather than through the native option, so the\n // documented order -- self, then prevent, then stop, then the handler --\n // holds for it too. The native option removes the registration on the\n // first dispatch that merely reaches the element, which for 'self' is\n // exactly the dispatch the handler must not see: 'on:click.self.once'\n // could then never run at all.\n if (once) remove();\n if (__velarHasName(modifiers, \"prevent\")) __velarEventCall(value, \"preventDefault\", __velarEventPreventDefault);\n if (__velarHasName(modifiers, \"stop\")) __velarEventCall(value, \"stopPropagation\", __velarEventStopPropagation);\n // The handler expression is re-read per dispatch so handlers routed\n // through live props always see the current value.\n const handler = __velarInternalRead(read);\n if (typeof handler !== \"function\") throw new TypeError(\"Event '\" + event + \"' requires a function\");\n const result = __velarUntracked(() => handler(value));\n __velarObservePromise(result, (error) => __velarReportEvent(error, scope, event));\n } catch (error) { __velarReportEvent(error, scope, event); }\n };\n __velarDomAddListener(element, event, listener, { capture });\n __velarAppendOwned(scope.cleanups, remove);\n}\n\nfunction __velarBindValue(element, state, scope, numeric = false, parse = null) {\n __velarObserver(() => {\n const value = state.get();\n if (value == null) __velarDomSetFieldValue(element, \"\");\n else if (numeric) {\n if (typeof value !== \"number\" || !__velarDomIsFinite(value)) throw new TypeError(\"Numeric bind:value requires a finite number\");\n __velarDomSetFieldValue(element, __velarDomString(value));\n } else {\n if (typeof value !== \"string\") throw new TypeError(\"bind:value requires text\");\n __velarDomSetFieldValue(element, value);\n }\n }, \"dom\", scope);\n const update = () => state.set(numeric ? __velarDomFieldNumber(element) : parse ? parse(__velarDomFieldValue(element)) : __velarDomFieldValue(element));\n __velarDomAddListener(element, \"input\", update, false);\n __velarAppendOwned(scope.cleanups, () => __velarDomRemoveListener(element, \"input\", update, false));\n}\n\nfunction __velarBindGroupValues(state, own) {\n const value = __velarInternalRead(() => state.get());\n const values = __velarListSnapshot(value, \"bind:group state\");\n const output = new __velarDomNativeArray(values.length);\n let count = 0;\n for (let index = 0; index < values.length; index += 1) {\n const item = values[index];\n if (typeof item !== \"string\") throw new TypeError(\"bind:group on a checkbox requires List<string> state\");\n if (item !== own) { output[count] = item; count += 1; }\n }\n output.length = count;\n return output;\n}\n\nfunction __velarBindGroup(element, state, scope, multiple = false, parse = null) {\n __velarObserver(() => {\n const own = __velarDomFieldValue(element);\n const value = state.get();\n if (!multiple) {\n if (value != null && typeof value !== \"string\") throw new TypeError(\"bind:group requires text state\");\n __velarDomSetFieldChecked(element, value === own);\n return;\n }\n const values = __velarListSnapshot(value, \"bind:group state\");\n let present = false;\n for (let index = 0; index < values.length; index += 1) if (values[index] === own) present = true;\n __velarDomSetFieldChecked(element, present);\n }, \"dom\", scope);\n const update = () => {\n const own = __velarDomFieldValue(element);\n if (!multiple) {\n if (__velarDomFieldChecked(element)) state.set(parse ? parse(own) : own);\n return;\n }\n const remaining = __velarBindGroupValues(state, own);\n if (__velarDomFieldChecked(element)) remaining[remaining.length] = own;\n state.set(remaining);\n };\n __velarDomAddListener(element, \"change\", update, false);\n __velarAppendOwned(scope.cleanups, () => __velarDomRemoveListener(element, \"change\", update, false));\n}\n\nfunction __velarBindChecked(element, state, scope) {\n __velarObserver(() => {\n const value = state.get();\n if (typeof value !== \"boolean\") throw new TypeError(\"bind:checked requires bool\");\n __velarDomSetFieldChecked(element, value);\n }, \"dom\", scope);\n const update = () => state.set(__velarDomFieldChecked(element));\n __velarDomAddListener(element, \"change\", update, false);\n __velarAppendOwned(scope.cleanups, () => __velarDomRemoveListener(element, \"change\", update, false));\n}\n\n// Prop handles give a component body live reads over its props store. The\n// component function still runs exactly once per instance; only reads race\n// ahead, so state initializers can never re-run on a prop update.\n" + "function __velarPropProvided(props, name) {\n // A children slot is rendered content rather than a value thunk. Asking for\n // its value to decide whether the required slot exists would build the slot\n // once here and again at the JSX position that owns it. Its own property is\n // the presence proof; the first value read remains the one rendering read.\n if (name === \"children\") return __velarGraphOwnDescriptor(props, name) !== undefined;\n return __velarInternalRead(() => props[name]) !== undefined;\n}\n\nfunction __velarRequiredProp(props, name, component) {\n if (!__velarPropProvided(props, name)) throw new TypeError(\"Component \" + component + \" requires prop \" + name);\n return __velarGraphFreeze({\n get() {\n const value = props[name];\n if (value === undefined) throw new TypeError(\"Component \" + component + \" requires prop \" + name);\n return value;\n },\n });\n}\n\nfunction __velarProp(props, name, fallback) {\n const fallbackValue = __velarPropProvided(props, name) ? undefined : fallback();\n return __velarGraphFreeze({\n get() {\n const value = props[name];\n return value === undefined ? fallbackValue : value;\n },\n });\n}\n\nfunction __velarBindComponentRef(instance, setRef) {\n if (setRef === undefined) return instance;\n if (!instance || typeof instance.__bindRef !== \"function\") throw new TypeError(\"This component does not expose a Handle\");\n instance.__bindRef(setRef);\n return instance;\n}\n\n// Holds every prop's cache open for the length of one construction. The graph\n// records a dependency for whichever observer is running, so forcing the props\n// under this one keeps them clean while the component function runs: a read\n// during construction is served from the value the force produced, and a\n// tracked read still subscribes the observer that made it. Releasing the hold\n// hands each prop over to whatever actually observes it, which is the second\n// half of the rule -- recomputed on demand, cached while observed.\nfunction __velarConstructionHold() {\n return {\n mode: \"computed\",\n stopped: false,\n running: false,\n selfInvalidations: 0,\n dependencies: __velarGraphCreateSet(),\n spareDependencies: null,\n notify() {},\n run() {},\n };\n}\n\n// Instantiates a component with a live props store: each prop is a cached\n// derived value the props object exposes as a tracked getter, so a prop\n// expression that nothing reads costs nothing after construction. The component\n// call itself is untracked so construction can never subscribe an enclosing\n// dynamic region to prop reads.\nfunction __velarInstantiate(component, thunks, children, scope, namespace, setRef) {\n const props = {};\n // 'style:' on a component host is the caller decorating the instance's root,\n // the way it decorates a native element. The slot the compiler inserts for it\n // is not a field the component declares, so it is bound here rather than\n // handed inward -- a component the runtime implements validates its props\n // against the fields it does declare and would refuse an unknown one.\n const styleRead = thunks.__velarStyle;\n const propNames = __velarGraphOwnNames(thunks);\n const accesses = [];\n for (let index = 0; index < propNames.length; index += 1) {\n const name = propNames[index];\n if (name === \"__velarStyle\") continue;\n // A prop is a derived value, not an eagerly pushed one: an unconditional\n // observer per prop re-ran every prop expression on every dependency\n // change, including the expensive ones behind props the component never\n // reads. The cache is the same one a declared derived value uses.\n const access = __velarComputed(thunks[name]);\n accesses[accesses.length] = access;\n __velarGraphDefine(props, name, { enumerable: true, get: () => access.get() });\n }\n // 'children' follows Vel's ordinary rules: it is rendered content owned by\n // the position that shows it, rebuilt whenever that position renders again.\n // As a one-shot fragment value it could be shown exactly once, and the first\n // time a conditional position hid it the content was destroyed for good.\n if (children !== undefined) __velarGraphDefine(props, \"children\", { enumerable: true, get: () => __velarChildrenNode(children, scope) });\n const instance = __velarUntracked(() => {\n if (accesses.length === 0) return component(props, namespace);\n // Component JSX evaluates the way the charter says a JavaScript object\n // literal does: every prop expression runs once, in the order the caller\n // wrote it, and only then does the component function run. 'children' is\n // not one of them -- it is rendered content owned by the position that\n // shows it, so a position that never shows it never builds it.\n const hold = __velarConstructionHold();\n try {\n __velarRuntime.runTracked(hold, () => {\n for (let index = 0; index < accesses.length; index += 1) accesses[index].get();\n });\n return component(props, namespace);\n } finally { __velarCleanupObserver(hold); }\n });\n if (styleRead !== undefined) __velarStyleBindRoot(instance.node, styleRead, scope);\n return __velarBindComponentRef(instance, setRef);\n}\n\n// A component element in child position: one stable instance whose prop\n// observers live in a dedicated scope, destroyed only when the position\n// itself unmounts. Construction failures stay contained to the position.\nfunction __velarChild(component, thunks, children, scope, namespace, setRef) {\n const childScope = __velarScope(scope.component);\n let constructed = false;\n __velarAppendOwned(scope.mounts, () => { if (constructed) __velarMountScope(childScope); });\n __velarAppendOwned(scope.cleanups, () => { if (constructed) __velarDestroyScope(childScope); });\n try {\n const node = __velarUseComponent(__velarInstantiate(component, thunks, children, childScope, namespace, setRef), childScope);\n constructed = true;\n return node;\n } catch (error) {\n __velarDestroyScope(childScope);\n // D114 P6 item 5 (LC-C2): the position that could not be built leaves the\n // compiler-owned fatal state, scoped to itself. It used to leave an HTML\n // comment -- invisible to the reader and to assistive technology alike --\n // so \"the initial render never leaves a blank page\" was true of the root\n // and false one node in. The isolation is unchanged: siblings mount and\n // keep running, and the failure is still reported in the `render` phase.\n const report = __velarReport(error, \"render\", scope);\n // The namespace this position renders into, so the marker is an element the\n // surrounding document can actually lay out (F7-web-b).\n return __velarFatalNode(\"This part of the page could not start: \" + report.error.message, namespace);\n }\n}\n\n// tick() promises the settled flush, so it drains the reactive queues instead\n// of hopping one microtask and hoping. Each round runs the pending flush and\n// yields, so work an observer queued asynchronously is picked up too; the round\n// count is bounded for the same reason the flush budget is, and the flush's own\n// budget is what ends a runaway cycle.\n" + "function __velarSettledStep() {\n return __velarManagedAsyncCreate((resolve) => __velarEnqueue(resolve));\n}\n\nfunction __velarSettled(rounds = 10000) {\n return __velarManagedAsyncThen(__velarSettledStep(), () => {\n if (__velarRuntime.flushPending) __velarFlush();\n if (rounds > 1 && (__velarGraphSetCount(__velarRuntime.domQueue)\n || __velarGraphSetCount(__velarRuntime.watchQueue) || __velarRuntime.flushPending)) {\n return __velarSettled(rounds - 1);\n }\n return null;\n });\n}\n\n// The failure the flush parked for its claimants, read rather than taken, and\n// this caller's wait ended.\n//\n// D114 F9-web (WB-C1): the park was drained by whoever looked first, so a\n// second `tick()` awaiting the same broken flush found nothing and resolved --\n// it stepped over the broken update the charter says awaiting `tick()` cannot\n// step over. Every `tick()` pending at that flush is a claimant and rejects\n// with the same failure, so the park is released only when the last of them has\n// left. That is also what makes a `tick()` awaited *after* the flush resolve:\n// by then nobody is waiting, so nothing was parked and nothing is left.\nfunction __velarClaimUnhandledFailure() {\n let claimed = null;\n for (const failure of __velarGraphSetItems(__velarRuntime.unhandledFailures)) { claimed = failure; break; }\n __velarLeaveTickWait();\n if (!__velarTickWaiting()) __velarGraphSetEmpty(__velarRuntime.unhandledFailures);\n return claimed;\n}\n\n// tick() is where an awaiting caller meets the reactive queue, which makes it\n// the owned place for a failure no handler claimed to surface: the test that\n// awaited the flush fails with the real error, and the process -- the test\n// runner, or the page -- continues.\n//\n// D114 P6 item 4 (LC-C1): the wait is counted, because the flush has to know\n// whether anyone is there. While this promise is pending the escalation path\n// parks an unowned failure instead of handing it to the host, in every host;\n// with nobody waiting it goes to the host error event (browser) or the report\n// channel (elsewhere) exactly as before.\nfunction __velarTick() {\n __velarEnterTickWait();\n return __velarManagedAsyncThen(__velarSettled(), () => {\n const failure = __velarClaimUnhandledFailure();\n if (failure !== null) throw failure;\n return null;\n }, (error) => {\n __velarClaimUnhandledFailure();\n throw error;\n });\n}";
|
|
95
|
+
export const WEB_RUNTIME_BODY = "function __velarReport(value, phase, scope = null, detail = \"\", unhandled = true) {\n return __velarRuntime.report(value, { phase, detail, component: scope ? scope.component : \"\", unhandled });\n}\n\nfunction __velarReportEvent(value, scope, detail) {\n if (__velarIsError(value) && __velarGraphWeakSetRemove(__velarRuntime.actionFailures, value)) return null;\n return __velarReport(value, \"event\", scope, detail);\n}\n\nconst __velarWebIterateKey = Symbol.for(\"velar.reactive.iterate.v1\");\nconst __velarWebNativeJson = globalThis.JSON;\nconst __velarWebJsonText = Object.getOwnPropertyDescriptor(__velarWebNativeJson, \"stringify\")?.value;\nconst __velarEventReflectApply = Object.getOwnPropertyDescriptor(Reflect, \"apply\")?.value;\nconst __velarEventConstructorDescriptor = Object.getOwnPropertyDescriptor(globalThis, \"Event\");\nconst __velarEventConstructor = __velarEventConstructorDescriptor && \"value\" in __velarEventConstructorDescriptor ? __velarEventConstructorDescriptor.value : null;\nconst __velarEventPrototype = typeof __velarEventConstructor === \"function\" ? Object.getOwnPropertyDescriptor(__velarEventConstructor, \"prototype\")?.value : null;\nconst __velarEventTargetGetter = __velarEventPrototype && Object.getOwnPropertyDescriptor(__velarEventPrototype, \"target\")?.get;\nconst __velarEventPreventDefault = __velarEventPrototype && Object.getOwnPropertyDescriptor(__velarEventPrototype, \"preventDefault\")?.value;\nconst __velarEventStopPropagation = __velarEventPrototype && Object.getOwnPropertyDescriptor(__velarEventPrototype, \"stopPropagation\")?.value;\nconst __velarEventMissingField = __velarGraphFreeze({});\nfunction __velarQuotedText(value) {\n return __velarGraphApply(__velarWebJsonText, __velarWebNativeJson, [value], \"JSON.stringify\");\n}\nfunction __velarAppendOwned(values, value) {\n values[values.length] = value;\n return value;\n}\nfunction __velarHasName(values, name) {\n for (let index = 0; index < values.length; index += 1) if (values[index] === name) return true;\n return false;\n}\nfunction __velarEventField(value, name, nativeGetter) {\n if (typeof nativeGetter === \"function\" && typeof __velarEventReflectApply === \"function\") {\n try { return __velarEventReflectApply(nativeGetter, value, []); } catch {}\n }\n if (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) return __velarEventMissingField;\n const descriptor = __velarGraphOwnDescriptor(value, name);\n return descriptor?.enumerable && \"value\" in descriptor ? descriptor.value : __velarEventMissingField;\n}\nfunction __velarEventCall(value, name, nativeMethod) {\n if (typeof nativeMethod === \"function\" && typeof __velarEventReflectApply === \"function\") {\n try { return __velarEventReflectApply(nativeMethod, value, []); } catch {}\n }\n const method = __velarEventField(value, name, null);\n if (typeof method !== \"function\" || typeof __velarEventReflectApply !== \"function\") throw new TypeError(\"DOM event does not expose native \" + name);\n return __velarEventReflectApply(method, value, []);\n}\n\n" + "function __velarTrack(subscribers) {\n __velarRuntime.trackSubscribers(subscribers);\n}\n\nfunction __velarToRaw(value) { return __velarRuntime.toRaw(value); }\nfunction __velarReactive(value, parent = null) { return __velarRuntime.reactive(value, parent); }\n\nfunction __velarWebListPop(value, requested = -1) {\n return __velarReactive(__velarListPop(value, requested));\n}\n\nfunction __velarUntracked(read) {\n const previous = __velarRuntime.activeObserver;\n __velarRuntime.activeObserver = null;\n try { return read(); } finally { __velarRuntime.activeObserver = previous; }\n}\n\nfunction __velarCleanupObserver(observer) {\n __velarRuntime.cleanupObserver(observer);\n}\n\n// P2b-9: a self-invalidating render used to report only that it happened. The\n// stack top was the graph's own trigger, so it named neither the collection\n// being written nor the scope reading it, and the distance between symptom and\n// cause was the whole debugging cost. Everything below is already known where\n// the budget trips: the observer carries its component and its watch subject,\n// and the graph has just recorded which path re-triggered it. Naming the write\n// is the difference between bisecting a render and reading one line.\n//\n// The advice is attached to the shape that earns it. A \"collection\" subject\n// means a collection was read for its size or contents and then written in the\n// same pass, and the two spellings that end it are the same two every time:\n// take the position from the loop instead of from the collection, or read the\n// value out before writing. The kind arrives beside the phrase, so nothing here\n// reads a sentence back apart to decide.\nfunction __velarSelfInvalidationMessage(mode, component, label, subject, kind) {\n let message = \"A reactive \" + mode + \" cannot invalidate itself more than 100 times\";\n if (component) message += \" (\" + component + \")\";\n else if (label) message += \" (watching \" + label + \")\";\n if (!subject) return message;\n message += \": it writes \" + subject + \" while reading it\";\n if (kind === \"collection\") {\n return message + \". A position taken from the collection being written -- 'items.get(built.size)' inside the loop that appends to 'built' -- reads it on every pass; take the position from a two-slot 'for value, index in ...' instead, or read what you need into a binding before the loop.\";\n }\n return message + \". Read it into a binding before the code that writes it, so the write cannot reach the read that tracked it.\";\n}\n\n// D90 R21: \"label\" names the observer in a report -- a watch carries its\n// subject as the author spelled it -- and \"sequence\" is its registration\n// number, which is the order the flush runs the watch tier in. The counter is\n// application-wide rather than per module, so two modules' watches order by the\n// order the two modules initialized.\nfunction __velarObserver(read, mode, scope, label = \"\") {\n // The first run of a DOM observer executes while its JSX position is being\n // constructed, and construction is transactional: the failure must reach\n // the surrounding owner (the mount transaction at the root, the containing\n // child position otherwise) so the promised fatal state or contained\n // placeholder appears instead of a silently empty region. Later runs are\n // updates; their failures are reported and the last valid DOM survives.\n let initial = mode === \"dom\";\n const observer = {\n mode,\n label,\n sequence: __velarNextObserverSequence(),\n component: scope !== null && scope !== undefined && typeof scope.component === \"string\" ? scope.component : \"\",\n stopped: false,\n running: false,\n selfInvalidations: 0,\n // P2b-9: the reactive path whose write landed while this observer was\n // reading. The graph fills it in only on a self-invalidating write, so the\n // runaway report can name what to go and look at.\n selfInvalidationSubject: \"\",\n selfInvalidationKind: \"\",\n dependencies: __velarGraphCreateSet(),\n run() {\n if (observer.stopped) return;\n observer.running = true;\n try { __velarRuntime.runTracked(observer, read); }\n catch (error) {\n if (initial) throw error;\n __velarReport(error, mode === \"watch\" ? \"watch\" : \"render\", scope);\n }\n finally {\n observer.running = false;\n initial = false;\n }\n },\n notify() {\n if (observer.stopped) return;\n if (observer.running) {\n observer.selfInvalidations += 1;\n if (observer.selfInvalidations > 100) {\n observer.stop();\n __velarReport(new RangeError(__velarSelfInvalidationMessage(\n mode === \"watch\" ? \"watch\" : \"render\",\n observer.component,\n observer.label,\n observer.selfInvalidationSubject,\n observer.selfInvalidationKind,\n )), mode === \"watch\" ? \"watch\" : \"render\", scope);\n return;\n }\n } else {\n observer.selfInvalidations = 0;\n }\n // The registry owns the one scheduler: the emitted prelude used to carry\n // its own copy of the queue insert and the flush drain, and the two\n // definitions of one concept is what let a watch be classified three\n // different ways. The capability observers in packages/web/src/runtime.ts\n // have always scheduled this way.\n __velarRuntime.schedule(observer);\n },\n stop() { observer.stopped = true; __velarCleanupObserver(observer); },\n };\n __velarAppendOwned(scope.cleanups, () => observer.stop());\n observer.run();\n return observer;\n}\n\n// D70 rule 180: a reactive source read during component setup and stored in a\n// plain binding is frozen. That is what const means, and a snapshot is a\n// legitimate thing to want -- so the report fires when the source *diverges*\n// from the snapshot, never when the snapshot is taken. A warning that fires on\n// correct code is a warning people learn to ignore; one that fires only after\n// the value on screen has actually gone stale cannot be wrong about that.\n//\n// The whole mechanism is installed only when the development host published its\n// hooks, so a production build pays nothing for it: no map, no stack capture,\n// and one already-false constant on the read path.\n// One module's copy of this runtime cannot own the state: a component in one\n// module reads a cell created in another, so the setup stack and the recorded\n// reads live on the shared hooks object every copy sees.\nconst __velarFrozenHooks = (() => {\n const hooks = globalThis.__velarDevelopmentHooks;\n if (!hooks || typeof hooks.frozenRead !== \"function\") return null;\n if (hooks.setupScopes === undefined) {\n hooks.setupScopes = [];\n hooks.reads = __velarGraphCreateWeakMap();\n hooks.derived = [];\n hooks.internalDepth = 0;\n }\n return hooks;\n})();\nconst __velarFrozenReadLimit = 32;\n\nfunction __velarSetupBegin(scope) {\n if (__velarFrozenHooks) __velarAppendOwned(__velarFrozenHooks.setupScopes, scope);\n return scope;\n}\n\nfunction __velarSetupEnd(value) {\n if (__velarFrozenHooks && __velarFrozenHooks.setupScopes.length > 0) __velarFrozenHooks.setupScopes.length -= 1;\n return value;\n}\n\n// The framework's own reads on the author's behalf -- checking a prop is\n// present, building the content a children slot holds, reading a handler\n// thunk. None of them freezes anything the author wrote: the\n// prop handle behind them stays live. Reporting them would be the false-positive\n// flood D70 rule 180 rejected, in its most literal form.\nfunction __velarInternalRead(read) {\n if (!__velarFrozenHooks) return __velarUntracked(read);\n __velarFrozenHooks.internalDepth += 1;\n try { return __velarUntracked(read); } finally { __velarFrozenHooks.internalDepth -= 1; }\n}\n\nfunction __velarRecordFrozenRead(cell, value) {\n if (!__velarFrozenHooks) return;\n if (__velarFrozenHooks.setupScopes.length === 0 || __velarFrozenHooks.internalDepth > 0) return;\n if (__velarRuntime.activeObserver !== null) return;\n // Only a value the reader can show is worth naming in the report; an object\n // read out of setup is followed through the deep graph, not frozen by this\n // read, so recording it would produce a report about the wrong thing.\n if (value !== null && typeof value === \"object\") return;\n const scope = __velarFrozenHooks.setupScopes[__velarFrozenHooks.setupScopes.length - 1];\n const existing = __velarGraphWeakMapRead(__velarFrozenHooks.reads, cell);\n if (existing) {\n if (existing.length >= __velarFrozenReadLimit) return;\n __velarAppendOwned(existing, { value, scope, site: new Error(\"velar frozen read\") });\n return;\n }\n __velarGraphWeakMapWrite(__velarFrozenHooks.reads, cell, [{ value, scope, site: new Error(\"velar frozen read\") }]);\n}\n\n// A derived value frozen during setup has no cell to hang a report on, and a\n// read that left no subscriber is a read the cache never tells anything about.\n// So the entries are kept in one dev-mode list and re-read after a state write\n// -- the only thing that can move a derived value -- which is the same\n// \"report on divergence\" rule the cells follow, reached the only way it can be.\nfunction __velarRecordFrozenDerived(access, value) {\n if (!__velarFrozenHooks) return;\n if (__velarFrozenHooks.setupScopes.length === 0 || __velarFrozenHooks.internalDepth > 0) return;\n if (__velarRuntime.activeObserver !== null) return;\n if (value !== null && typeof value === \"object\") return;\n if (__velarFrozenHooks.derived.length >= __velarFrozenReadLimit * 4) return;\n const scope = __velarFrozenHooks.setupScopes[__velarFrozenHooks.setupScopes.length - 1];\n __velarAppendOwned(__velarFrozenHooks.derived, { access, value, scope, site: new Error(\"velar frozen read\") });\n}\n\nfunction __velarReportFrozenDerived() {\n if (!__velarFrozenHooks || __velarFrozenHooks.derived.length === 0) return;\n const entries = __velarFrozenHooks.derived;\n const remaining = [];\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n let current = entry.value;\n let failed = false;\n try { current = __velarUntracked(entry.access); }\n catch { failed = true; }\n if (failed || __velarGraphSame(entry.value, current)) { remaining[remaining.length] = entry; continue; }\n __velarPublishFrozenRead(entry, current);\n }\n __velarFrozenHooks.derived = remaining;\n}\n\nfunction __velarReportFrozenReads(cell, next) {\n if (!__velarFrozenHooks) return;\n __velarReportFrozenDerived();\n const entries = __velarGraphWeakMapRead(__velarFrozenHooks.reads, cell);\n if (!entries) return;\n __velarGraphWeakMapRemove(__velarFrozenHooks.reads, cell);\n for (let index = 0; index < entries.length; index += 1) {\n if (__velarGraphSame(entries[index].value, next)) continue;\n __velarPublishFrozenRead(entries[index], next);\n }\n}\n\nfunction __velarPublishFrozenRead(entry, next) {\n const component = entry.scope && entry.scope.component ? entry.scope.component : \"a component\";\n __velarFrozenHooks.frozenRead({\n message: \"A reactive value read while \" + component + \" was being built was frozen at \"\n + __velarFrozenText(entry.value) + \", and the source has now changed to \" + __velarFrozenText(next)\n + \". Whatever was built from that read still shows the old value. If it is meant to follow, declare it with 'computed name = <expression>'; if the snapshot was intended, nothing here needs changing.\",\n stack: __velarDomString(entry.site && entry.site.stack ? entry.site.stack : \"\"),\n });\n}\n\nfunction __velarFrozenText(value) {\n return typeof value === \"string\" ? __velarQuotedText(value) : __velarDomString(value);\n}\n\n// \"name\" is the declared name an author \"state\" wrote, carried on the cell and\n// visible in the emitted source. The cells __velarResource and __velarAction\n// build for their own pending/error fields are created without one, because\n// they are the runtime's bookkeeping rather than state anyone declared.\n//\n// D90 R21: nothing read it any more. It existed for the two watch referees --\n// only a cell with a declared name could be a declared write target -- and they\n// went with the clause. It was left in place rather than removed with them,\n// because it is a fact about the cell rather than a mechanism, and it is what a\n// report naming the state a runaway wrote would have to read. D114 0.28.0 H-U1\n// is that report: __velarSelfInvalidationWrite below reads it.\nfunction __velarState(initial, name) {\n let value = __velarToRaw(initial);\n const subscribers = __velarGraphCreateSet();\n const cell = {\n velarStateName: name,\n // Named rather than shorthand so a captured stack shows a compiler frame\n // here: D70's report walks past its own frames to find the reading line,\n // and every JavaScript engine spells an anonymous getter differently.\n get: function __velarCellRead() {\n __velarTrack(subscribers);\n const current = __velarReactive(value, cell);\n __velarRecordFrozenRead(cell, current);\n return current;\n },\n set(next) {\n next = __velarToRaw(next);\n if (__velarGraphSame(value, next)) return next;\n const previous = value;\n value = next;\n __velarReportFrozenReads(cell, next);\n // Keep deep-change bubbling attached only to the value currently owned\n // by this cell. Otherwise every replaced object remains linked to the\n // state cell and continues to occupy the parent graph indefinitely.\n __velarRuntime.collectionUnlink(cell, previous);\n __velarReactive(value, cell);\n for (const observer of __velarGraphSetItems(subscribers)) {\n __velarSelfInvalidationWrite(observer, name);\n observer.notify();\n }\n return next;\n },\n };\n __velarReactive(value, cell);\n return cell;\n}\n\n// D114 0.28.0 H-U1: a state cell notifies its own subscriber set rather than\n// going through the graph's keyed notify, so the write path the runaway report\n// names was recorded for every deep write and for no write of a declared\n// state -- and a scalar self-write only ever reaches the 100-round cap through\n// a helper, which is why the gap read as \"a write through a plain def\". The\n// condition is the graph's own, verbatim: a write that lands while its own\n// reader is still running is the self-invalidating shape, and it is the only\n// one worth describing. A cell with no declared name is runtime bookkeeping --\n// __velarResource and __velarAction build theirs that way -- so it falls back\n// to the same phrase describeSubject uses for a place it cannot name.\nfunction __velarSelfInvalidationWrite(observer, name) {\n if (!observer.running) return;\n observer.selfInvalidationSubject = name ? \"state '\" + name + \"'\" : \"a tracked value\";\n observer.selfInvalidationKind = \"value\";\n}\n\n// D71 rule 182: a declared derived value reads bare, so it presents the same\n// .get() face a state cell does. The cache underneath is the runtime's own\n// memo; only the face it is read through differs.\nfunction __velarComputed(read) {\n const access = __velarRuntime.computed(read);\n if (!__velarFrozenHooks) return __velarGraphFreeze({ get: access });\n return __velarGraphFreeze({\n get: function __velarDerivedRead() {\n const value = access();\n __velarRecordFrozenDerived(access, value);\n return value;\n },\n });\n}\n\n" + "const __velarManagedAsyncNativePromise = globalThis.Promise;\nconst __velarManagedAsyncPromisePrototype = __velarGraphOwnDescriptor(__velarManagedAsyncNativePromise, \"prototype\")?.value;\nconst __velarManagedAsyncResolveOperation = __velarGraphOwnDescriptor(__velarManagedAsyncNativePromise, \"resolve\")?.value;\nconst __velarManagedAsyncRejectOperation = __velarGraphOwnDescriptor(__velarManagedAsyncNativePromise, \"reject\")?.value;\nconst __velarManagedAsyncThenOperation = __velarManagedAsyncPromisePrototype\n ? __velarGraphOwnDescriptor(__velarManagedAsyncPromisePrototype, \"then\")?.value\n : null;\nfunction __velarManagedAsyncResolve(value) {\n return __velarGraphApply(__velarManagedAsyncResolveOperation, __velarManagedAsyncNativePromise, [value], \"Promise.resolve\");\n}\nfunction __velarManagedAsyncReject(error) {\n return __velarGraphApply(__velarManagedAsyncRejectOperation, __velarManagedAsyncNativePromise, [error], \"Promise.reject\");\n}\nfunction __velarManagedAsyncThen(value, fulfilled, rejected) {\n return __velarGraphApply(__velarManagedAsyncThenOperation, value, [fulfilled, rejected], \"Promise.then\");\n}\nfunction __velarManagedAsyncCreate(executor) {\n if (typeof __velarManagedAsyncNativePromise !== \"function\") throw new TypeError(\"The JavaScript Promise API is unavailable\");\n return new __velarManagedAsyncNativePromise(executor);\n}\n\nfunction __velarResource(load, scope, name) {\n const value = __velarState(null);\n const loading = __velarState(true);\n const ready = __velarState(false);\n const error = __velarState(null);\n let generation = 0;\n let started = false;\n let disposed = false;\n\n const reload = () => {\n if (disposed) return __velarManagedAsyncResolve(null);\n started = true;\n const current = ++generation;\n loading.set(true);\n error.set(null);\n return __velarManagedAsyncThen(__velarManagedAsyncThen(__velarManagedAsyncResolve(), load),\n (next) => {\n if (disposed || current !== generation) return null;\n value.set(next);\n ready.set(true);\n loading.set(false);\n return null;\n },\n (failure) => {\n if (disposed || current !== generation) return null;\n const report = __velarRuntime.report(failure, { phase: \"resource\", detail: name, component: scope.component, unhandled: false });\n error.set(report.error);\n ready.set(true);\n loading.set(false);\n return null;\n },\n );\n };\n\n __velarAppendOwned(scope.mounts, () => started ? null : reload());\n __velarAppendOwned(scope.cleanups, () => { disposed = true; generation += 1; });\n return __velarGraphFreeze({\n get value() { return value.get(); },\n get loading() { return loading.get(); },\n get ready() { return ready.get(); },\n get error() { return error.get(); },\n reload,\n });\n}\n\nfunction __velarAction(execute, scope, name) {\n const pending = __velarState(false);\n const error = __velarState(null);\n let active = 0;\n let generation = 0;\n let disposed = false;\n\n const run = (...arguments_) => {\n // D114 W2: the one place an action call enters the runtime. An action\n // started from inside an observer run is asynchronous work that observer\n // started, so the reactive window carries into the flush its completion\n // schedules; started from anywhere else it records nothing.\n __velarNoteAsyncWork();\n if (disposed) return __velarManagedAsyncReject(__velarNormalizeError(\n \"Action '\" + name + \"' cannot run after its component is destroyed\",\n ));\n const current = ++generation;\n active += 1;\n pending.set(true);\n error.set(null);\n return __velarManagedAsyncThen(__velarManagedAsyncThen(__velarManagedAsyncResolve(), () => __velarGraphApply(execute, null, arguments_, \"action body\")),\n (value) => {\n active -= 1;\n if (!disposed) pending.set(active > 0);\n return value;\n },\n (failure) => {\n active -= 1;\n let actionError = __velarNormalizeError(failure);\n if (!disposed) {\n pending.set(active > 0);\n // Every action failure reports exactly once, through the action\n // phase, carrying the action's name as its detail -- including a\n // failure superseded by a newer call. Only the newest generation\n // owns the public error field. The actionFailures mark lets the\n // event and detached observers of the same rejection skip an\n // already-reported failure instead of reporting it a second time.\n const report = __velarRuntime.report(failure, { phase: \"action\", detail: name, component: scope.component, unhandled: false });\n actionError = report.error;\n __velarGraphWeakSetInsert(__velarRuntime.actionFailures, actionError);\n if (current === generation) error.set(report.error);\n }\n throw actionError;\n },\n );\n };\n\n __velarGraphDefine(run, \"pending\", { enumerable: true, get: () => pending.get() });\n __velarGraphDefine(run, \"error\", { enumerable: true, get: () => error.get() });\n __velarAppendOwned(scope.cleanups, () => { disposed = true; generation += 1; });\n return __velarGraphFreeze(run);\n}\n\n" + "function __velarScope(component = \"\") {\n return { cleanups: [], mounts: [], mounted: false, component };\n}\n\nconst __velarGlobalScope = __velarScope();\n\nfunction __velarMountScope(scope) {\n if (scope.mounted) return;\n scope.mounted = true;\n for (let index = 0; index < scope.mounts.length; index += 1) {\n try {\n const result = __velarUntracked(scope.mounts[index]);\n __velarObservePromise(result, (error) => __velarReport(error, \"mounted\", scope));\n } catch (error) { __velarReport(error, \"mounted\", scope); }\n }\n}\n\nfunction __velarDestroyScope(scope) {\n for (let index = scope.cleanups.length - 1; index >= 0; index -= 1) {\n // A reentrant destroy can empty the list underneath this walk; a missing\n // slot means the step already ran and must not run again.\n const cleanup = scope.cleanups[index];\n if (typeof cleanup !== \"function\") continue;\n try {\n const result = __velarUntracked(cleanup);\n __velarObservePromise(result, (error) => __velarReport(error, \"cleanup\", scope));\n } catch (error) { __velarReport(error, \"cleanup\", scope); }\n }\n scope.cleanups.length = 0;\n}\n\nfunction __velarCleanupStep(run, scope) {\n try {\n const result = __velarUntracked(run);\n __velarObservePromise(result, (error) => __velarReport(error, \"cleanup\", scope));\n } catch (error) { __velarReport(error, \"cleanup\", scope); }\n}\n\n// D90 R21: nothing here asks whether this watch writes. Execution order is\n// source order, so the only thing the flush needs of a watch is when it was\n// registered, and __velarObserver stamps that on it. The label is the subject\n// as the author spelled it, carried so a runaway flush can name the watches\n// that ran away.\nfunction __velarWatch(read, callback, scope, label = \"\") {\n let current;\n let currentVersion = 0;\n let initialized = false;\n let observer = null;\n observer = __velarObserver(() => {\n const next = read();\n __velarRuntime.trackDeep(next);\n const nextVersion = __velarRuntime.versionOf(next);\n if (initialized && (!__velarGraphSame(next, current) || nextVersion !== currentVersion)) {\n // The body is the author's effect, not part of the watched expression:\n // its own reactive reads must never become dependencies of what is being\n // watched, or one write re-evaluates the expression twice and an\n // unwatched value re-runs the watch.\n __velarUntracked(() => callback(next, current));\n }\n current = next;\n currentVersion = nextVersion;\n initialized = true;\n }, \"watch\", scope, label);\n}\n\nfunction __velarComponentHandle(value, componentName) {\n if (value === null || typeof value !== \"object\") throw new TypeError(\"Component \" + componentName + \" must expose an ordinary Handle record\");\n const prototype = __velarGraphPrototype(value);\n if (prototype !== __velarGraphPrototype({}) && prototype !== null) throw new TypeError(\"Component \" + componentName + \" must expose an ordinary Handle record\");\n const output = {};\n let active = true;\n const names = __velarGraphOwnNames(value);\n for (let index = 0; index < names.length; index += 1) {\n const name = names[index];\n const descriptor = __velarGraphOwnDescriptor(value, name);\n if (!descriptor || !descriptor.enumerable || !(\"value\" in descriptor)) throw new TypeError(\"Component \" + componentName + \" Handle fields must be enumerable data values\");\n const member = typeof descriptor.value === \"function\"\n ? (...arguments_) => {\n if (!active) throw new Error(\"Component \" + componentName + \" Handle is no longer active\");\n return __velarGraphApply(descriptor.value, null, arguments_, \"component Handle method\");\n }\n : descriptor.value;\n __velarGraphDefine(output, name, { enumerable: true, value: member });\n }\n return __velarGraphFreeze({\n value: __velarGraphFreeze(output),\n revoke() { active = false; },\n });\n}\n\n" + "function __velarComponent(node, scope, mounted, cleanup, handleState) {\n let destroyed = false;\n const refCleanups = [];\n const ownedNodes = node && __velarDomNodeType(node) === 11 ? __velarDomChildNodes(node) : [node];\n // An enclosing component forwards to a nested component's host only when that\n // component's root sits at its own root level. Marking the nodes here is what\n // lets the enclosing scan walk past a nested host buried inside one of its\n // own elements instead of counting it as a second host of its own.\n for (let index = 0; index < ownedNodes.length; index += 1) {\n if (ownedNodes[index] && __velarDomNodeType(ownedNodes[index]) === 1) {\n __velarGraphDefine(ownedNodes[index], \"__velarComponentNode\", { value: true, enumerable: true, configurable: true });\n }\n }\n if (mounted) __velarAppendOwned(scope.mounts, mounted);\n return {\n __velarComponent: true,\n node,\n __bindRef(setRef) {\n if (!handleState) throw new TypeError(\"This component does not expose a Handle\");\n const handle = handleState.value;\n let bound = true;\n setRef(handle, undefined);\n __velarAppendOwned(refCleanups, () => {\n if (!bound) return;\n bound = false;\n setRef(null, handle);\n });\n return null;\n },\n mount(target, before = null) {\n if (destroyed) throw new Error(\"Cannot mount a destroyed VelarScript component\");\n if (scope.mounted) throw new Error(\"Cannot mount a VelarScript component more than once\");\n const parent = typeof target === \"string\" ? __velarDomQuerySelector(target) : target;\n if (!parent) throw new Error(\"VelarScript mount target was not found\");\n __velarDomInsertBefore(parent, node, before);\n __velarMountScope(scope);\n return null;\n },\n __mount() { if (!destroyed) __velarMountScope(scope); },\n destroy(remove = true) {\n if (destroyed) return null;\n destroyed = true;\n for (let index = refCleanups.length - 1; index >= 0; index -= 1) refCleanups[index]();\n refCleanups.length = 0;\n if (handleState) handleState.revoke();\n if (cleanup) {\n try {\n const result = __velarUntracked(cleanup);\n __velarObservePromise(result, (error) => __velarReport(error, \"cleanup\", scope));\n } catch (error) { __velarReport(error, \"cleanup\", scope); }\n }\n __velarDestroyScope(scope);\n if (remove) for (let index = 0; index < ownedNodes.length; index += 1) __velarDomRemove(ownedNodes[index]);\n return null;\n },\n };\n}\n\nfunction __velarScopeComponentRoot(node, attribute) {\n if (!attribute || !node) return;\n if (__velarDomNodeType(node) === 1) {\n __velarDomSetAttribute(node, attribute, \"\");\n return;\n }\n if (__velarDomNodeType(node) === 11) {\n const children = __velarDomChildNodes(node);\n for (let index = 0; index < children.length; index += 1) {\n if (__velarDomNodeType(children[index]) === 1) __velarDomSetAttribute(children[index], attribute, \"\");\n }\n }\n}\n\nfunction __velarUseComponent(instance, scope, parentStyleScope = \"\") {\n __velarScopeComponentRoot(instance.node, parentStyleScope);\n __velarAppendOwned(scope.mounts, () => instance.__mount());\n __velarAppendOwned(scope.cleanups, () => instance.destroy(false));\n return instance.node;\n}\n\n// D114 P6 item 5 (LC-C2): the compiler-owned fatal state, as one element. The\n// root replaces a mount target with it; a dynamic region that threw while it\n// was first constructed renders it in place of the position it could not build.\n// Both are the same element with the same role and the same attribute, because\n// they are the same promise -- \"no blank page\" -- kept at two scales, and an\n// assistive technology has to find them the same way.\n//\n// D114 F7-web-b: in the namespace of the position it stands in. An HTML\n// '<section>' inside '<svg>' is not an SVG element and a browser lays out none\n// of it, so the marker a region left inside a chart was the blank the promise\n// was made against -- and the role went with it. The SVG spelling is the one\n// 'velar/routing' already renders for a lazy component that fails inside a\n// chart: a 'g' carrying the role and the attribute, with the sentence in a\n// 'text' child. Same wording, same two markers, one namespace apart.\nfunction __velarFatalNode(message, namespace) {\n if (namespace === \"svg\") {\n const host = __velarDomCreateElementNS(__velarSvgNamespace, \"g\");\n __velarDomSetAttribute(host, \"role\", \"alert\");\n __velarDomSetAttribute(host, \"data-velar-fatal\", \"\");\n const label = __velarDomCreateElementNS(__velarSvgNamespace, \"text\");\n __velarDomSetText(label, message);\n __velarDomAppend(host, label);\n return host;\n }\n const fallback = __velarDomCreateElement(\"section\");\n __velarDomSetAttribute(fallback, \"role\", \"alert\");\n __velarDomSetAttribute(fallback, \"data-velar-fatal\", \"\");\n __velarDomSetText(fallback, message);\n return fallback;\n}\n\n// D114 WB-U1: and the root takes the namespace too. A region gets it from the\n// lowering, which knows the position it is building; a root's target is named at\n// runtime -- a selector the program wrote, or the document body a module failure\n// falls back to -- so the target itself is what answers. Without it the root\n// fatal was always the HTML spelling, and an application mounted into a chart\n// left its one \"the application could not start\" element where a browser lays\n// out nothing: the blank page the promise is about, at the larger of the two\n// scales the promise covers.\nfunction __velarFatal(parent, error) {\n const namespace = __velarDomNamespace(parent) === __velarSvgNamespace ? \"svg\" : undefined;\n __velarDomReplaceChildren(parent, __velarFatalNode(\"The application could not start: \" + error.message, namespace));\n}\n\n// Whether any root has actually mounted, which is the whole question the\n// deferred module failure below has to answer: the no-blank-page promise is\n// about a page with nothing on it, and a page that already has an application\n// on it is not one the fatal state may replace.\nlet __velarMountedRoot = false;\n\n// A component element built while the module evaluates sits outside every\n// transaction the runtime owns, so a construction throw there used to escape\n// module evaluation and leave the page blank -- the one initial-render path the\n// promise did not cover. The failure is caught into this value instead, and the\n// module keeps evaluating so the '@main' region still runs: that is where the\n// error handlers are installed and where 'mount' is called, and reporting ahead\n// of both would report to nobody.\nfunction __velarModuleInstantiate(component, thunks, children, scope, namespace, setRef) {\n try {\n return __velarInstantiate(component, thunks, children, scope, namespace, setRef);\n } catch (error) {\n const failure = { error, surfaced: false };\n // The mount that takes this root surfaces the failure at its own target.\n // Nothing having taken it by the first microtask means nothing ever will,\n // and a root that was built to be mounted and never was is still a blank\n // page: it surfaces there instead, into the document body.\n __velarEnqueue(() => __velarSurfaceModuleFailure(failure, null));\n return { __velarModuleFailure: failure };\n }\n}\n\nfunction __velarSurfaceModuleFailure(failure, parent) {\n if (failure.surfaced) return null;\n failure.surfaced = true;\n // The phase is 'mount' because this is the same failure 'mount(<App />, ...)'\n // reports under that phase; the two spellings of one root differ in where the\n // element is written, not in what went wrong.\n const report = __velarReport(failure.error, \"mount\", null);\n try {\n const target = parent ?? (__velarMountedRoot ? null : __velarDomQuerySelector(\"body\"));\n if (target) __velarFatal(target, report.error);\n } catch {}\n return null;\n}\n\nfunction __velarMount(evaluate, fallbackTarget = null) {\n let values;\n try {\n values = evaluate();\n } catch (failure) {\n const report = __velarReport(failure, \"mount\", null);\n if (fallbackTarget !== null) {\n try {\n const fallback = __velarDomQuerySelector(fallbackTarget);\n if (fallback) __velarFatal(fallback, report.error);\n } catch {}\n }\n return null;\n }\n const value = values[0];\n const target = values[1];\n const parent = typeof target === \"string\" ? __velarDomQuerySelector(target) : target;\n // A root whose construction failed while the module evaluated is answered\n // here, ahead of the missing-target question: the construction failure is the\n // cause, and reporting the target instead would name a symptom. The target\n // still decides where the fatal state renders, and a missing one falls back\n // to the document body exactly as it does below.\n if (value && value.__velarModuleFailure) {\n __velarSurfaceModuleFailure(value.__velarModuleFailure, parent || null);\n return null;\n }\n if (!parent) {\n // A missing mount target must keep the no-blank-page promise in every\n // build: the failure is reported through velar/app and the fatal state\n // renders into the document body, since the requested target is exactly\n // what does not exist.\n const report = __velarReport(new Error(\"VelarScript mount target was not found\"), \"mount\", null);\n try {\n const body = __velarDomQuerySelector(\"body\");\n if (body) __velarFatal(body, report.error);\n } catch {}\n return null;\n }\n try {\n if (value && value.__velarComponent) {\n const result = value.mount(parent);\n if (__velarGraphIsList(globalThis.__velarHotDisposers)) __velarAppendOwned(globalThis.__velarHotDisposers, () => value.destroy());\n __velarMountedRoot = true;\n return result;\n }\n __velarAppend(parent, value);\n __velarMountScope(__velarGlobalScope);\n __velarMountedRoot = true;\n return null;\n } catch (failure) {\n const report = __velarReport(failure, \"mount\", null);\n __velarFatal(parent, report.error);\n return null;\n }\n}\n\n" + "const __velarSvgNamespace = \"http://www.w3.org/2000/svg\";\nconst __velarXlinkNamespace = \"http://www.w3.org/1999/xlink\";\nconst __velarXmlNamespace = \"http://www.w3.org/XML/1998/namespace\";\n\nfunction __velarCreateElement(tag, namespace) {\n return namespace === \"svg\" || tag === \"svg\"\n ? __velarDomCreateElementNS(__velarSvgNamespace, tag)\n : __velarDomCreateElement(tag);\n}\n\nfunction __velarListSnapshot(value, name) {\n value = __velarToRaw(value);\n __velarRuntime.collectionRead(value, __velarWebIterateKey, undefined);\n return __velarDomListSnapshot(value, name);\n}\n\nfunction __velarAppend(parent, value, state = null) {\n state ??= { active: __velarDomCreateSet(), depth: 0, values: 0, text: 0 };\n if (value == null || value === false || value === true) return;\n state.values += 1;\n if (state.values > 1000000) throw new RangeError(\"JSX cannot render more than 1000000 values\");\n if (typeof value === \"string\") {\n state.text += value.length;\n if (state.text > 16 * 1024 * 1024) throw new RangeError(\"JSX text cannot exceed 16 MiB\");\n __velarDomAppend(parent, __velarDomCreateTextNode(value));\n return;\n }\n if (typeof value === \"number\") {\n if (!__velarDomIsFinite(value)) throw new TypeError(\"JSX numbers must be finite\");\n __velarDomAppend(parent, __velarDomCreateTextNode(__velarDomString(value)));\n return;\n }\n if (__velarDomIsNode(value)) { __velarDomAppend(parent, value); return; }\n if (__velarDomIsArray(value)) {\n if (state.depth >= 128) throw new RangeError(\"JSX Lists cannot exceed 128 nested levels\");\n if (__velarDomSetContains(state.active, value)) throw new TypeError(\"JSX cannot render a cyclic List\");\n const values = __velarListSnapshot(value, \"JSX children\");\n __velarDomSetInsert(state.active, value);\n state.depth += 1;\n try {\n for (let index = 0; index < values.length; index += 1) __velarAppend(parent, values[index], state);\n } finally {\n state.depth -= 1;\n __velarDomSetRemove(state.active, value);\n }\n return;\n }\n throw new TypeError(\"JSX can render only text, finite numbers, bool, enums, WebNode values, and Lists of those values\");\n}\n\n// The rendering region currently being constructed. A 'children' slot is built\n// by the position that shows it and must be destroyed with it, so the slot is\n// owned by this scope rather than by the caller's component scope, which would\n// keep every hidden build's observers alive for the component's whole lifetime.\nlet __velarBuildScope = null;\n\nfunction __velarChildrenNode(build, scope) {\n const owner = __velarBuildScope === null ? scope : __velarBuildScope;\n return __velarInternalRead(() => build(owner));\n}\n\n// The scalar half of __velarAppend, lifted out so a region that can only ever\n// hold one text node can be that text node. The two branches are __velarAppend's\n// own, error text included: the checked type admits an unsound value only where\n// the program lied about it, and such a value must land exactly where it landed\n// before -- rendered if it is text or a finite number, refused with the same\n// message otherwise.\nfunction __velarTextValue(value) {\n if (typeof value === \"string\") {\n if (value.length > 16 * 1024 * 1024) throw new RangeError(\"JSX text cannot exceed 16 MiB\");\n return value;\n }\n if (typeof value === \"number\") {\n if (!__velarDomIsFinite(value)) throw new TypeError(\"JSX numbers must be finite\");\n return __velarDomString(value);\n }\n throw new TypeError(\"JSX can render only text, finite numbers, bool, enums, WebNode values, and Lists of those values\");\n}\n\n// F1: an interpolation whose checked type is 'string' or 'number' renders\n// exactly one text node -- never zero, never markup, never a list. So it needs\n// no comment pair to bracket content that can never grow or vanish, and no\n// child scope to own observers that can never exist: the text node is its own\n// anchor and its own content, created once and updated by assigning its data.\n// That is the same node identity a comment anchor gave, so a keyed row that\n// starts or ends on one still finds its bounds, and a focused sibling is never\n// detached by an update.\nfunction __velarText(parent, read, scope) {\n let node = null;\n __velarObserver(() => {\n // Read and validate before touching the document: a failed update must\n // leave the last valid text standing, exactly as a failed rebuild leaves\n // the last valid region standing.\n const value = __velarTextValue(read());\n if (node === null) __velarDomAppend(parent, node = __velarDomCreateTextNode(value));\n else __velarDomSetData(node, value);\n }, \"dom\", scope);\n}\n\nfunction __velarDynamic(parent, read, scope, rootState = null) {\n const start = __velarDomCreateComment(\"velar:start\");\n const end = __velarDomCreateComment(\"velar:end\");\n __velarDomAppend(parent, start, end);\n let nodes = [];\n let childScope = null;\n __velarAppendOwned(scope.mounts, () => { if (childScope) __velarMountScope(childScope); });\n __velarObserver(() => {\n const nextScope = __velarScope(scope.component);\n const fragment = __velarDomCreateFragment();\n let nextHost = null;\n const previousBuildScope = __velarBuildScope;\n __velarBuildScope = nextScope;\n try {\n __velarAppend(fragment, read(nextScope));\n if (rootState) nextHost = __velarRootHost(fragment, \"dynamic component\");\n }\n catch (error) { __velarDestroyScope(nextScope); throw error; }\n finally { __velarBuildScope = previousBuildScope; }\n const nextNodes = __velarDomChildNodes(fragment);\n if (childScope) __velarDestroyScope(childScope);\n for (let index = 0; index < nodes.length; index += 1) __velarDomRemove(nodes[index]);\n __velarDomBefore(end, fragment);\n childScope = nextScope;\n nodes = nextNodes;\n if (rootState) {\n rootState.host = nextHost;\n for (const listener of __velarGraphSetItems(rootState.listeners)) listener(nextHost);\n }\n if (scope.mounted) __velarMountScope(nextScope);\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n if (childScope) __velarDestroyScope(childScope);\n for (let index = 0; index < nodes.length; index += 1) __velarDomRemove(nodes[index]);\n nodes = [];\n if (rootState) {\n rootState.host = null;\n for (const listener of __velarGraphSetItems(rootState.listeners)) listener(null);\n }\n });\n}\n\nfunction __velarDynamicComponent(read, scope) {\n const fragment = __velarDomCreateFragment();\n const rootState = { host: null, listeners: __velarGraphCreateSet() };\n __velarGraphDefine(fragment, \"__velarDynamicRoot\", { value: rootState });\n __velarDynamic(fragment, read, scope, rootState);\n return fragment;\n}\n\nfunction __velarKeyed(parent, read, keyOf, render, scope) {\n const start = __velarDomCreateComment(\"velar:keyed-start\");\n const end = __velarDomCreateComment(\"velar:keyed-end\");\n __velarDomAppend(parent, start, end);\n let entries = __velarGraphCreateMap();\n __velarAppendOwned(scope.mounts, () => { for (const entry of __velarGraphMapItems(entries)) __velarMountScope(entry.scope); });\n __velarObserver(() => {\n const source = __velarToRaw(read() ?? []);\n const values = __velarListSnapshot(source, \"Keyed JSX\");\n const next = __velarGraphCreateMap();\n const created = [];\n try {\n for (let index = 0; index < values.length; index += 1) {\n const rawValue = __velarToRaw(values[index]);\n // The keyed source may be a fresh derived List on every render. A row\n // is observed directly by its child scope, so linking it to that\n // ephemeral container only retains dead Lists and slows later writes.\n const trackedValue = __velarReactive(rawValue);\n const key = __velarKey(keyOf(trackedValue));\n if (__velarGraphMapContains(next, key)) throw new Error(\"Duplicate JSX key '\" + (typeof key === \"string\" ? key : __velarDomString(key)) + \"'\");\n let entry = __velarGraphMapRead(entries, key);\n if (entry && !__velarGraphSame(entry.value, rawValue)) entry = undefined;\n if (!entry) {\n const childScope = __velarScope(scope.component);\n const fragment = __velarDomCreateFragment();\n const previousBuildScope = __velarBuildScope;\n __velarBuildScope = childScope;\n try { __velarAppend(fragment, render(trackedValue, childScope)); }\n catch (error) { __velarDestroyScope(childScope); throw error; }\n finally { __velarBuildScope = previousBuildScope; }\n // A row is held by its first and last top-level nodes, never by a\n // snapshot of the list between them: every dynamic construct brackets\n // itself with comments created once, so those two nodes are stable\n // while everything between them is replaced over time. Caching the\n // whole list put destroyed nodes back into the document on a later\n // reorder and stranded the live ones outside their own markers.\n const rowNodes = __velarDomChildNodes(fragment);\n entry = {\n value: rawValue,\n scope: childScope,\n first: rowNodes.length > 0 ? rowNodes[0] : null,\n last: rowNodes.length > 0 ? rowNodes[rowNodes.length - 1] : null,\n fragment,\n };\n created[created.length] = entry;\n }\n __velarGraphMapWrite(next, key, entry);\n }\n } catch (error) {\n for (let index = 0; index < created.length; index += 1) __velarDestroyScope(created[index].scope);\n throw error;\n }\n for (const key of __velarGraphMapKeyItems(entries)) {\n const entry = __velarGraphMapRead(entries, key);\n if (__velarGraphMapRead(next, key) === entry) continue;\n __velarDestroyScope(entry.scope);\n let node = entry.first;\n while (node !== null && node !== end) {\n const following = __velarDomNextSibling(node);\n __velarDomRemove(node);\n if (node === entry.last) break;\n node = following;\n }\n }\n // A row already standing in its final position must not be detached and\n // reattached: that moves focus off a live <input>, ends IME composition,\n // and resets transient subtree state. The cursor walks the surviving nodes\n // in order and only moves a node that is not already where it belongs.\n let cursor = __velarDomNextSibling(start);\n for (const entry of __velarGraphMapItems(next)) {\n if (entry.fragment) {\n __velarDomBefore(cursor === null ? end : cursor, entry.fragment);\n entry.fragment = null;\n if (scope.mounted) __velarMountScope(entry.scope);\n continue;\n }\n let node = entry.first;\n while (node !== null && node !== end) {\n const following = __velarDomNextSibling(node);\n if (node === cursor) cursor = __velarDomNextSibling(cursor);\n else __velarDomBefore(cursor === null ? end : cursor, node);\n if (node === entry.last) break;\n node = following;\n }\n }\n entries = next;\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n for (const entry of __velarGraphMapItems(entries)) __velarDestroyScope(entry.scope);\n __velarGraphMapEmpty(entries);\n });\n}\n\n" + "function __velarStaticAttr(element, name, value) {\n if (value === false || value == null) return;\n __velarSetAttribute(element, name, __velarAttributeValue(value, name));\n}\n\nfunction __velarAttr(element, name, read, scope) {\n __velarObserver(() => {\n const value = read();\n if (value == null || value === false) __velarRemoveAttribute(element, name);\n else __velarSetAttribute(element, name, __velarAttributeValue(value, name));\n }, \"dom\", scope);\n}\n\n// The attributes whose value the user agent navigates or fetches. For these the\n// scheme is part of what the value means, so it is checked; every other\n// attribute takes its text unchanged.\nconst __velarUrlAttributes = [\"href\", \"src\", \"action\", \"formaction\", \"poster\", \"data\", \"xlink:href\", \"ping\", \"cite\"];\nconst __velarUrlSchemes = [\"http\", \"https\", \"mailto\", \"tel\", \"blob\"];\n// 'data:' carries its own payload, so it is admitted only for media types the\n// user agent cannot execute. 'image/svg+xml' is deliberately absent: an SVG\n// document can carry script.\nconst __velarInertDataTypes = [\n \"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\", \"image/avif\", \"image/bmp\", \"image/x-icon\",\n \"video/mp4\", \"video/webm\", \"video/ogg\", \"audio/mpeg\", \"audio/ogg\", \"audio/wav\", \"audio/webm\",\n \"font/woff\", \"font/woff2\", \"text/plain\",\n];\n\n// 'javascript:' and 'vbscript:' are code, not locations. A value that arrived as\n// data must never become code because it reached an href, so an unknown scheme\n// is refused rather than passed through.\nfunction __velarUrlAttributeValue(value, name) {\n let scheme = \"\";\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n // The user agent strips ASCII whitespace and control characters before it\n // parses the scheme, so \"java\\tscript:\" reads as \"javascript:\" to it and\n // has to read that way here too.\n if (code <= 0x20 || code === 0x7f) continue;\n if (code === 58 && scheme.length > 0) {\n const lowered = scheme.toLowerCase();\n if (lowered === \"data\") {\n const payload = value.slice(index + 1).toLowerCase();\n for (let type = 0; type < __velarInertDataTypes.length; type += 1) {\n if (payload.startsWith(__velarInertDataTypes[type])) return value;\n }\n throw new TypeError(\"JSX attribute '\" + name + \"' rejected a 'data:' URL whose media type is not a known inert one\");\n }\n if (__velarHasName(__velarUrlSchemes, lowered)) return value;\n throw new TypeError(\"JSX attribute '\" + name + \"' rejected the '\" + lowered + \":' URL scheme\");\n }\n const letter = (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n if (letter || (scheme.length > 0 && ((code >= 48 && code <= 57) || code === 43 || code === 45 || code === 46))) {\n scheme += value[index];\n continue;\n }\n // Anything else this early means the value names no scheme: it is a\n // relative URL, which is always the application's own origin.\n return value;\n }\n return value;\n}\n\nfunction __velarAttributeValue(value, name) {\n if (value === true) return \"\";\n if (typeof value === \"number\") {\n if (!__velarDomIsFinite(value)) throw new TypeError(\"JSX attribute '\" + name + \"' requires a finite number\");\n return __velarDomString(value);\n }\n if (typeof value !== \"string\") throw new TypeError(\"JSX attribute '\" + name + \"' requires text, a finite number, bool, an enum, or null\");\n if (value.length > 1024 * 1024) throw new RangeError(\"JSX attribute '\" + name + \"' cannot exceed 1 MiB\");\n if (__velarHasName(__velarUrlAttributes, name)) return __velarUrlAttributeValue(value, name);\n return value;\n}\n\nfunction __velarKey(value) {\n if (typeof value === \"number\") {\n if (!__velarDomIsFinite(value)) throw new TypeError(\"A JSX key number must be finite\");\n return value;\n }\n if (typeof value !== \"string\") throw new TypeError(\"A JSX key must be a string, string-backed enum, or finite number\");\n if (value.length > 65536) throw new RangeError(\"A JSX key cannot exceed 65536 characters\");\n return value;\n}\n\nfunction __velarSetAttribute(element, name, value) {\n if (name.startsWith(\"xlink:\")) __velarDomSetAttributeNS(element, __velarXlinkNamespace, name, value);\n else if (name.startsWith(\"xml:\")) __velarDomSetAttributeNS(element, __velarXmlNamespace, name, value);\n else __velarDomSetAttribute(element, name, value);\n}\n\nfunction __velarRemoveAttribute(element, name) {\n if (name.startsWith(\"xlink:\")) __velarDomRemoveAttributeNS(element, __velarXlinkNamespace, name.slice(6));\n else if (name.startsWith(\"xml:\")) __velarDomRemoveAttributeNS(element, __velarXmlNamespace, name.slice(4));\n else __velarDomRemoveAttribute(element, name);\n}\n\n" + "function __velarClass(element, name, read, scope) {\n __velarClassBind(element, () => read() ? name : null, scope);\n}\n\n// The property a token carries. A token is '[target:]conditions:property' and\n// a CSS property name never contains ':', so the last segment is the property.\nfunction __velarLookProperty(token) {\n return token.slice(token.lastIndexOf(\":\") + 1);\n}\n\n// The surface a token writes on: its pseudo-element target, if it has one, plus\n// its property. Composition overrides a property on the surface that owns it —\n// '@before: content' and a bare 'content' are two surfaces, not one property\n// written under two conditions.\nfunction __velarLookSurface(token) {\n const first = token.indexOf(\":\");\n const last = token.lastIndexOf(\":\");\n return (first === last ? \"\" : token.slice(0, first + 1)) + token.slice(last + 1);\n}\n\n// Whether a token declares its property unconditionally: an unconditional\n// declaration spells its condition segment 'base', so the segment in front of\n// the property is what says a token stands on its own.\nfunction __velarLookUnconditional(token) {\n const last = token.lastIndexOf(\":\");\n return token.slice(token.lastIndexOf(\":\", last - 1) + 1, last) === \"base\";\n}\n\n// Composition is property-level across sources and token-level inside one look\n// block. A later unconditional declaration wins its property outright, so it\n// drops every condition the earlier sources wrote it under: the caller of a\n// component could otherwise not reach a padding the component set behind its\n// own private breakpoint, and 'the caller wins every property both of them set'\n// was true only under the identical condition (LOK-U10). A later conditional\n// declaration refines rather than replaces — it overwrites the identical token\n// and leaves the earlier unconditional value standing, because a caller that\n// writes only 'if @hover: color' never mentioned the resting colour and must\n// not delete it. Declarations written in one block are one source, so a block's\n// own 'if scheme.dark:' and 'if @hover:' still coexist and the cascade decides\n// between them.\nfunction __velarMergeRules(rules, groups, source, group) {\n const names = __velarGraphOwnNames(source);\n const owned = __velarGraphOwnNames(rules);\n for (let index = 0; index < names.length; index += 1) {\n const descriptor = __velarGraphOwnDescriptor(source, names[index]);\n if (!descriptor || !(\"value\" in descriptor)) continue;\n if (!__velarLookUnconditional(names[index])) continue;\n const surface = __velarLookSurface(names[index]);\n for (let other = 0; other < owned.length; other += 1) {\n const token = owned[other];\n if (groups[token] === group || __velarLookSurface(token) !== surface) continue;\n delete rules[token];\n delete groups[token];\n }\n }\n for (let index = 0; index < names.length; index += 1) {\n const descriptor = __velarGraphOwnDescriptor(source, names[index]);\n if (!descriptor || !(\"value\" in descriptor)) continue;\n if (descriptor.value == null) { delete rules[names[index]]; delete groups[names[index]]; continue; }\n rules[names[index]] = descriptor.value;\n groups[names[index]] = group;\n }\n}\n\nfunction __velarLook(parts) {\n const rules = __velarGraphCreateRecord();\n const groups = __velarGraphCreateRecord();\n // A built Look is one source. A bare rules record is a run of declarations\n // written in one look block, so consecutive ones share a source and a spread\n // between them opens the next.\n let group = 0;\n let run = 0;\n const add = (part) => {\n if (part == null || part === false) return;\n if (__velarGraphIsList(part)) { for (let index = 0; index < part.length; index += 1) add(part[index]); return; }\n if (part.__velarLook === true) {\n group += 1;\n run = 0;\n __velarMergeRules(rules, groups, part.rules, group);\n return;\n }\n if (part.rules && typeof part.rules === \"object\") {\n if (run === 0) { group += 1; run = group; }\n __velarMergeRules(rules, groups, part.rules, run);\n return;\n }\n throw new TypeError(\"look composition accepts only Look, Look?, or lists of Look values\");\n };\n add(parts);\n return __velarGraphFreeze({ __velarLook: true, rules: __velarGraphFreeze(rules) });\n}\n\nfunction __velarKeyframesValue(name) {\n if (typeof name !== \"string\" || !/^velar-kf-[0-9a-f]{8,32}$/.test(name)) throw new TypeError(\"Generated keyframes name is invalid\");\n return __velarGraphFreeze({ __velarKeyframes: true, name });\n}\n\nfunction __velarLookVariable(token) {\n return \"--velar-look-\" + token.replace(/[^A-Za-z0-9_-]+/g, \"-\");\n}\n\nfunction __velarLookValue(token, value) {\n if (token.endsWith(\":animation\")) return __velarAnimationLookValue(value);\n if (typeof value === \"number\") {\n if (!__velarDomIsFinite(value)) throw new TypeError(\"Look properties require finite numbers\");\n return __velarDomString(value);\n }\n if (typeof value !== \"string\") throw new TypeError(\"Look properties require text, finite numbers, typed visual values, or null\");\n if (value.length > 1024 * 1024) throw new RangeError(\"A Look property value cannot exceed 1 MiB\");\n if (token.endsWith(\":content\") && typeof value === \"string\" && value !== \"none\" && value !== \"normal\") return __velarCssString(value);\n // A closed keyword set is the property's whole string vocabulary, so a value\n // the compiler could not read — a prop, a record field, a call result — is\n // checked here instead. Without this a 'display' bound to \"grdi\" reached the\n // browser as a declaration it silently discards (LOK-U14).\n const keywords = __velarLookKeywords[__velarLookProperty(token)];\n if (keywords !== undefined && !__velarHasName(keywords, value.trim())) {\n let expected = \"\";\n for (let index = 0; index < keywords.length; index += 1) expected += (expected === \"\" ? \"\" : \", \") + keywords[index];\n throw new TypeError(\"Look property '\" + __velarLookProperty(token) + \"' does not accept '\" + value + \"'; use one of \" + expected);\n }\n return value;\n}\n\nfunction __velarAnimationLookValue(value) {\n const parts = [];\n const add = (item) => {\n if (__velarGraphIsList(item)) {\n for (let index = 0; index < item.length; index += 1) add(item[index]);\n return;\n }\n const marker = item && (typeof item === \"object\" || typeof item === \"function\")\n ? __velarGraphOwnDescriptor(item, \"__velarAnimation\") : null;\n const css = item && (typeof item === \"object\" || typeof item === \"function\")\n ? __velarGraphOwnDescriptor(item, \"css\") : null;\n if (!marker || !(\"value\" in marker) || marker.value !== true || !css || !(\"value\" in css) || typeof css.value !== \"string\") {\n throw new TypeError(\"Look animation requires Animation or a List of Animation values from animate()\");\n }\n __velarAppendOwned(parts, css.value);\n };\n add(value);\n if (parts.length === 0) throw new TypeError(\"A Look animation list cannot be empty\");\n let output = parts[0];\n for (let index = 1; index < parts.length; index += 1) output += \", \" + parts[index];\n return output;\n}\n\nconst __velarInlineStyleProperties = __velarGraphCreateSet([\"display\",\"position\",\"box-sizing\",\"isolation\",\"contain\",\"visibility\",\"z-index\",\"overflow\",\"overflow-x\",\"overflow-y\",\"resize\",\"clip\",\"clip-path\",\"object-fit\",\"object-position\",\"aspect-ratio\",\"grid-template-columns\",\"grid-template-rows\",\"grid-template-areas\",\"grid-auto-columns\",\"grid-auto-rows\",\"grid-auto-flow\",\"grid-column\",\"grid-column-start\",\"grid-column-end\",\"grid-row\",\"grid-row-start\",\"grid-row-end\",\"grid-area\",\"flex\",\"flex-direction\",\"flex-grow\",\"flex-shrink\",\"flex-basis\",\"flex-wrap\",\"order\",\"gap\",\"row-gap\",\"column-gap\",\"align-items\",\"justify-items\",\"justify-content\",\"align-content\",\"align-self\",\"justify-self\",\"place-items\",\"place-content\",\"place-self\",\"width\",\"height\",\"min-width\",\"max-width\",\"min-height\",\"max-height\",\"inline-size\",\"block-size\",\"min-inline-size\",\"max-inline-size\",\"min-block-size\",\"max-block-size\",\"inset\",\"top\",\"right\",\"bottom\",\"left\",\"inset-inline\",\"inset-block\",\"inset-inline-start\",\"inset-inline-end\",\"inset-block-start\",\"inset-block-end\",\"padding\",\"padding-top\",\"padding-right\",\"padding-bottom\",\"padding-left\",\"padding-inline\",\"padding-block\",\"padding-inline-start\",\"padding-inline-end\",\"padding-block-start\",\"padding-block-end\",\"margin\",\"margin-top\",\"margin-right\",\"margin-bottom\",\"margin-left\",\"margin-inline\",\"margin-block\",\"margin-inline-start\",\"margin-inline-end\",\"margin-block-start\",\"margin-block-end\",\"background\",\"background-color\",\"background-image\",\"background-position\",\"background-size\",\"background-repeat\",\"background-attachment\",\"background-clip\",\"background-origin\",\"background-blend-mode\",\"border\",\"border-width\",\"border-style\",\"border-color\",\"border-top\",\"border-right\",\"border-bottom\",\"border-left\",\"border-top-width\",\"border-right-width\",\"border-bottom-width\",\"border-left-width\",\"border-top-style\",\"border-right-style\",\"border-bottom-style\",\"border-left-style\",\"border-top-color\",\"border-right-color\",\"border-bottom-color\",\"border-left-color\",\"border-radius\",\"border-top-left-radius\",\"border-top-right-radius\",\"border-bottom-right-radius\",\"border-bottom-left-radius\",\"outline\",\"outline-width\",\"outline-style\",\"outline-color\",\"outline-offset\",\"box-shadow\",\"text-shadow\",\"opacity\",\"filter\",\"backdrop-filter\",\"content\",\"color\",\"font-family\",\"font-size\",\"font-weight\",\"font-style\",\"font-stretch\",\"font-variant\",\"font-kerning\",\"font-optical-sizing\",\"font-feature-settings\",\"font-variation-settings\",\"line-height\",\"vertical-align\",\"letter-spacing\",\"word-spacing\",\"text-align\",\"text-indent\",\"text-decoration\",\"text-decoration-color\",\"text-decoration-line\",\"text-decoration-style\",\"text-decoration-thickness\",\"text-underline-offset\",\"text-underline-position\",\"text-transform\",\"text-rendering\",\"white-space\",\"text-overflow\",\"text-wrap\",\"overflow-wrap\",\"word-break\",\"hyphens\",\"tab-size\",\"writing-mode\",\"text-orientation\",\"direction\",\"unicode-bidi\",\"list-style\",\"list-style-type\",\"list-style-position\",\"list-style-image\",\"fill\",\"stroke\",\"stroke-width\",\"stroke-linecap\",\"stroke-linejoin\",\"stroke-dasharray\",\"stroke-dashoffset\",\"translate\",\"scale\",\"rotate\",\"transform\",\"transform-origin\",\"transition\",\"transition-property\",\"transition-duration\",\"transition-delay\",\"transition-timing-function\",\"animation\",\"cursor\",\"pointer-events\",\"user-select\",\"touch-action\",\"appearance\",\"accent-color\",\"caret-color\",\"color-scheme\",\"scroll-behavior\",\"scroll-margin\",\"scroll-margin-top\",\"scroll-margin-right\",\"scroll-margin-bottom\",\"scroll-margin-left\",\"scroll-padding\",\"scroll-padding-top\",\"scroll-padding-right\",\"scroll-padding-bottom\",\"scroll-padding-left\",\"scroll-snap-align\",\"scroll-snap-stop\",\"scroll-snap-type\",\"overscroll-behavior\",\"overscroll-behavior-x\",\"overscroll-behavior-y\",\"scrollbar-color\",\"scrollbar-width\"]);\n\nfunction __velarStyleDeclarations(value) {\n if (!value || typeof value !== \"object\" || __velarGraphIsList(value)\n || (__velarGraphPrototype(value) !== __velarGraphNativeObject.prototype && __velarGraphPrototype(value) !== null)\n || __velarWebErrorOwnSymbols(value).length > 0) {\n throw new TypeError(\"style:* requires compiler-owned inline declarations\");\n }\n const names = __velarGraphOwnNames(value);\n if (names.length > 225) throw new RangeError(\"An inline Style has too many properties\");\n const output = {};\n for (let index = 0; index < names.length; index += 1) {\n const property = names[index];\n if (!__velarGraphSetContains(__velarInlineStyleProperties, property)) throw new TypeError(\"Unknown inline Style property '\" + property + \"'\");\n const descriptor = __velarGraphOwnDescriptor(value, property);\n if (!descriptor || !descriptor.enumerable || !(\"value\" in descriptor)) throw new TypeError(\"Inline Style declarations cannot use accessors\");\n __velarGraphDefine(output, property, { value: descriptor.value, enumerable: true, configurable: false, writable: false });\n }\n return __velarGraphFreeze(output);\n}\n\nfunction __velarInlineStyleState(element) {\n const current = __velarGraphOwnDescriptor(element, \"__velarInlineStyleState\");\n if (current) {\n if (!(\"value\" in current) || current.enumerable || current.configurable || current.writable\n || !current.value || typeof current.value !== \"object\") throw new TypeError(\"Inline Style ownership is invalid\");\n return current.value;\n }\n const state = __velarGraphFreeze({ base: __velarGraphCreateMap(), managed: __velarGraphCreateSet() });\n __velarGraphDefine(element, \"__velarInlineStyleState\", { value: state });\n return state;\n}\n\nfunction __velarAttachSource(registry, element, source) {\n let sources = __velarGraphWeakMapRead(registry, element);\n if (!sources) { sources = __velarGraphCreateSet(); __velarGraphWeakMapWrite(registry, element, sources); }\n __velarGraphSetInsert(sources, source);\n return sources;\n}\n\nfunction __velarDetachSource(registry, element, source) {\n const sources = __velarGraphWeakMapRead(registry, element);\n if (!sources) return;\n __velarGraphSetRemove(sources, source);\n if (__velarGraphSetCount(sources) === 0) __velarGraphWeakMapRemove(registry, element);\n}\n\nfunction __velarApplyStyles(element) {\n const sources = __velarGraphWeakMapRead(__velarRuntime.lookSources, element);\n const merged = __velarGraphCreateMap();\n if (sources) {\n for (const source of __velarGraphSetItems(sources)) {\n if (!source.styles) continue;\n const names = __velarGraphOwnNames(source.styles);\n for (let index = 0; index < names.length; index += 1) {\n __velarGraphMapWrite(merged, names[index], __velarGraphOwnDescriptor(source.styles, names[index]).value);\n }\n }\n }\n const state = __velarInlineStyleState(element);\n const next = __velarGraphCreateSet(__velarGraphMapKeyItems(merged));\n for (const property of __velarGraphSetItems(next)) {\n if (__velarGraphSetContains(state.managed, property)) continue;\n __velarGraphMapWrite(state.base, property, {\n value: __velarDomStyleValue(element, property),\n priority: __velarDomStylePriority(element, property),\n });\n }\n for (const property of __velarGraphSetItems(state.managed)) {\n if (__velarGraphSetContains(next, property)) continue;\n const base = __velarGraphMapRead(state.base, property);\n if (!base || (base.value === \"\" && base.priority === \"\")) __velarDomStyleClear(element, property);\n else __velarDomStyleWrite(element, property, base.value, base.priority);\n __velarGraphMapRemove(state.base, property);\n }\n for (const property of __velarGraphSetItems(next)) {\n const value = __velarGraphMapRead(merged, property);\n if (value == null) __velarDomStyleClear(element, property);\n else __velarDomStyleWrite(element, property, __velarLookValue(\"base:\" + property, value));\n }\n __velarGraphSetEmpty(state.managed);\n for (const property of __velarGraphSetItems(next)) __velarGraphSetInsert(state.managed, property);\n}\n\nfunction __velarStyleBind(element, read, scope) {\n const source = { rules: __velarGraphCreateRecord(), styles: {} };\n __velarAttachSource(__velarRuntime.lookSources, element, source);\n __velarObserver(() => {\n source.styles = __velarStyleDeclarations(read());\n __velarApplyStyles(element);\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n __velarDetachSource(__velarRuntime.lookSources, element, source);\n __velarApplyStyles(element);\n });\n}\n\nfunction __velarMoveStyleSource(source, previous, next) {\n if (previous) {\n __velarDetachSource(__velarRuntime.lookSources, previous, source);\n __velarApplyStyles(previous);\n }\n if (next) {\n __velarAttachSource(__velarRuntime.lookSources, next, source);\n __velarApplyStyles(next);\n }\n}\n\n// The dynamic-root marker sits on a fragment the emitter created, but the\n// fragment is still a host object: a planted prototype getter would otherwise\n// hand look/class/style application a forged host element.\nfunction __velarDynamicRootState(root) {\n if (root === null || root === undefined) return null;\n const descriptor = __velarGraphOwnDescriptor(root, \"__velarDynamicRoot\");\n return descriptor && \"value\" in descriptor && descriptor.value && typeof descriptor.value === \"object\"\n ? descriptor.value\n : null;\n}\n\nfunction __velarStyleBindRoot(root, read, scope) {\n const dynamic = __velarDynamicRootState(root);\n if (!dynamic) {\n __velarStyleBind(__velarRootHost(root, \"style\"), read, scope);\n return;\n }\n const source = { rules: __velarGraphCreateRecord(), styles: {} };\n let host = null;\n const move = (next) => {\n __velarMoveStyleSource(source, host, next);\n host = next;\n };\n __velarGraphSetInsert(dynamic.listeners, move);\n move(dynamic.host);\n __velarObserver(() => {\n source.styles = __velarStyleDeclarations(read());\n if (host) __velarApplyStyles(host);\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n __velarGraphSetRemove(dynamic.listeners, move);\n move(null);\n });\n}\n\n// Look and class ownership lives in one non-enumerable, non-configurable data\n// property per element, discovered through the captured descriptor ABI exactly\n// like inline style ownership. An ambient expando read would let a hostile\n// prototype hand the framework a forged token set.\nfunction __velarElementState(element, name, create) {\n const current = __velarGraphOwnDescriptor(element, name);\n if (current) {\n if (!(\"value\" in current) || current.enumerable || current.configurable || current.writable\n || !current.value || typeof current.value !== \"object\") throw new TypeError(\"VelarScript element ownership is invalid\");\n return current.value;\n }\n const state = create();\n __velarGraphDefine(element, name, { value: state });\n return state;\n}\n\nfunction __velarApplyLooks(element) {\n const sources = __velarGraphWeakMapRead(__velarRuntime.lookSources, element);\n const merged = __velarGraphCreateRecord();\n const groups = __velarGraphCreateRecord();\n if (sources) {\n // Each attached source is one Look, so a source that sets a property\n // unconditionally drops the property's other conditions from the sources\n // before it: the caller of a component composes after the component's own\n // host look and wins every property both of them set, whatever condition\n // either wrote it under. A source that writes the property only under a\n // condition refines that condition alone — the identical token is\n // overwritten and the earlier unconditional value stays, so the caller does\n // not delete a resting value it never mentioned.\n //\n // A null rule keeps its token: the token drives the generated selector and\n // only the custom property behind it disappears.\n let group = 0;\n for (const source of __velarGraphSetItems(sources)) {\n group += 1;\n const names = __velarGraphOwnNames(source.rules);\n const owned = __velarGraphOwnNames(merged);\n for (let index = 0; index < names.length; index += 1) {\n // A rule the assignment pass below refuses to read must not clear the\n // earlier sources either, or the property disappears with nothing put\n // in its place — the same 'a source deletes a value it never replaces'\n // shape the conditional guard above closes. '__velarMergeRules' spells\n // the test the same way.\n const descriptor = __velarGraphOwnDescriptor(source.rules, names[index]);\n if (!descriptor || !(\"value\" in descriptor)) continue;\n if (!__velarLookUnconditional(names[index])) continue;\n const surface = __velarLookSurface(names[index]);\n for (let other = 0; other < owned.length; other += 1) {\n if (groups[owned[other]] === group || __velarLookSurface(owned[other]) !== surface) continue;\n delete merged[owned[other]];\n delete groups[owned[other]];\n }\n }\n for (let index = 0; index < names.length; index += 1) {\n const descriptor = __velarGraphOwnDescriptor(source.rules, names[index]);\n if (!descriptor || !(\"value\" in descriptor)) continue;\n merged[names[index]] = descriptor.value;\n groups[names[index]] = group;\n }\n }\n }\n // The last value written per token, so a reactive change to one dynamic\n // property costs one DOM write instead of one per token plus a full attribute\n // rewrite (LOK-U15).\n const state = __velarElementState(element, \"__velarLookTokens\", () => __velarGraphFreeze({\n tokens: __velarGraphCreateSet(), written: { record: __velarGraphCreateRecord(), attribute: undefined },\n }));\n const written = state.written.record;\n const tokens = __velarGraphOwnNames(merged);\n const next = __velarGraphCreateSet(tokens);\n for (const token of __velarGraphSetItems(state.tokens)) {\n if (__velarGraphSetContains(next, token)) continue;\n __velarDomStyleClear(element, __velarLookVariable(token));\n delete written[token];\n }\n let attribute = \"\";\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index];\n const value = __velarGraphOwnDescriptor(merged, token)?.value;\n const text = value == null ? null : __velarLookValue(token, value);\n if (!(token in written) || written[token] !== text) {\n if (text === null) __velarDomStyleClear(element, __velarLookVariable(token));\n else __velarDomStyleWrite(element, __velarLookVariable(token), text);\n written[token] = text;\n }\n attribute = attribute === \"\" ? token : attribute + \" \" + token;\n }\n const desired = tokens.length === 0 ? null : attribute;\n if (state.written.attribute !== desired) {\n if (desired === null) __velarDomRemoveAttribute(element, \"data-velar-look\");\n else __velarDomSetAttribute(element, \"data-velar-look\", desired);\n state.written.attribute = desired;\n }\n __velarGraphSetEmpty(state.tokens);\n for (let index = 0; index < tokens.length; index += 1) __velarGraphSetInsert(state.tokens, tokens[index]);\n}\n\nfunction __velarLookBind(element, read, scope) {\n const source = { rules: __velarGraphCreateRecord() };\n __velarAttachSource(__velarRuntime.lookSources, element, source);\n __velarObserver(() => {\n source.rules = __velarLook([read()]).rules;\n __velarApplyLooks(element);\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n __velarDetachSource(__velarRuntime.lookSources, element, source);\n __velarApplyLooks(element);\n });\n}\n\nfunction __velarMoveLookSource(source, previous, next) {\n if (previous) {\n __velarDetachSource(__velarRuntime.lookSources, previous, source);\n __velarApplyLooks(previous);\n }\n if (next) {\n __velarAttachSource(__velarRuntime.lookSources, next, source);\n __velarApplyLooks(next);\n }\n}\n\nfunction __velarApplyExternalLook(element, value) {\n const source = { rules: __velarLook([value]).rules };\n __velarAttachSource(__velarRuntime.lookSources, element, source);\n __velarApplyLooks(element);\n return () => {\n __velarDetachSource(__velarRuntime.lookSources, element, source);\n __velarApplyLooks(element);\n };\n}\n\n__velarRuntime.installLook(__velarApplyExternalLook);\n\n// One resolution per root, shared by every capability bound to it: look, class\n// and style used to pay a fresh O(subtree) walk each.\n" + "const __velarRootHosts = __velarGraphCreateWeakMap();\n\nfunction __velarRootHostResolve(root) {\n const elements = [];\n const children = __velarDomChildNodes(root);\n for (let index = 0; index < children.length; index += 1) {\n if (__velarDomNodeType(children[index]) === 1) __velarAppendOwned(elements, children[index]);\n }\n const explicit = [];\n const forwarded = [];\n for (let index = 0; index < elements.length; index += 1) {\n const element = elements[index];\n // A nested component's own, perfectly legal host is that component's, not\n // this one's, at the root level exactly as below it. Every root-level node\n // of a nested component carries the marker and this component's own nodes\n // do not yet — construction marks them after a caller's look binds — so\n // the marker is what separates the two. Reading 'host' first counted a\n // nested component's marked root as a second host of the enclosing one and\n // collapsed the whole region, which is the buried-host defect standing at\n // the root level instead of below it. Such a node is not this component's\n // host but the host this component forwards to when it declares none of\n // its own, so it is collected apart rather than dropped.\n if (__velarDomOwnData(element, \"__velarComponentNode\") === true) {\n if (__velarDomOwnData(element, \"__velarHost\") === true) __velarAppendOwned(forwarded, element);\n continue;\n }\n if (__velarDomOwnData(element, \"__velarHost\") === true) { __velarAppendOwned(explicit, element); continue; }\n // A walk that refuses to enter a marked node stops at a nested component's\n // boundary whatever depth its host sits at; a flat 'querySelectorAll' scan\n // could only skip the marked node itself and still counted a host one level\n // below it.\n const pending = [element];\n for (let cursor = 0; cursor < pending.length; cursor += 1) {\n const nodes = __velarDomChildNodes(pending[cursor]);\n for (let child = 0; child < nodes.length; child += 1) {\n const node = nodes[child];\n if (__velarDomNodeType(node) !== 1) continue;\n if (__velarDomOwnData(node, \"__velarComponentNode\") === true) continue;\n if (__velarDomOwnData(node, \"__velarHost\") === true) __velarAppendOwned(explicit, node);\n __velarAppendOwned(pending, node);\n }\n }\n }\n if (explicit.length === 1) return explicit[0];\n if (explicit.length > 1) return \"A component can declare only one host element\";\n // Nothing of this component's own is marked, so a single nested component\n // root hands its host on. Two of them leave nothing to forward to, and the\n // component has to mark a native element of its own to settle it.\n if (forwarded.length === 1) return forwarded[0];\n if (forwarded.length > 1) return \"A component with multiple roots must mark exactly one native element with 'host'\";\n if (elements.length === 1) return elements[0];\n return \"A component with multiple roots must mark exactly one native element with 'host'\";\n}\n\nfunction __velarRootHost(root, capability) {\n if (root == null) throw new TypeError(\"A component with multiple roots must mark exactly one native element with 'host'\");\n if (__velarDomNodeType(root) === 1) return root;\n let resolved = __velarGraphWeakMapRead(__velarRootHosts, root);\n if (resolved === undefined) {\n resolved = __velarRootHostResolve(root);\n __velarGraphWeakMapWrite(__velarRootHosts, root, resolved);\n }\n if (typeof resolved === \"string\") throw new TypeError(resolved);\n return resolved;\n}\n\nfunction __velarLookBindRoot(root, read, scope) {\n const dynamic = __velarDynamicRootState(root);\n if (!dynamic) {\n __velarLookBind(__velarRootHost(root, \"look\"), read, scope);\n return;\n }\n const source = { rules: __velarGraphCreateRecord() };\n let host = null;\n const move = (next) => {\n __velarMoveLookSource(source, host, next);\n host = next;\n };\n __velarGraphSetInsert(dynamic.listeners, move);\n move(dynamic.host);\n __velarObserver(() => {\n source.rules = __velarLook([read()]).rules;\n if (host) __velarApplyLooks(host);\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n __velarGraphSetRemove(dynamic.listeners, move);\n move(null);\n });\n}\n\nfunction __velarClassBindRoot(root, read, scope) {\n const dynamic = __velarDynamicRootState(root);\n if (!dynamic) {\n __velarClassBind(__velarRootHost(root, \"class\"), read, scope);\n return;\n }\n const source = { names: [] };\n let host = null;\n const move = (next) => {\n __velarMoveClassSource(source, host, next);\n host = next;\n };\n __velarGraphSetInsert(dynamic.listeners, move);\n move(dynamic.host);\n __velarObserver(() => {\n source.names = __velarClassNames(read());\n if (host) __velarApplyClasses(host);\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n __velarGraphSetRemove(dynamic.listeners, move);\n move(null);\n });\n}\n\nfunction __velarClassNames(value, output = []) {\n if (value == null || value === false) return output;\n if (__velarGraphIsList(value)) {\n for (let index = 0; index < value.length; index += 1) __velarClassNames(value[index], output);\n return output;\n }\n if (typeof value !== \"string\") throw new TypeError(\"class accepts strings, string?, or lists of strings\");\n let name = \"\";\n for (let index = 0; index < value.length; index += 1) {\n const character = value[index];\n if (character === \" \" || character === \"\\t\" || character === \"\\n\" || character === \"\\r\" || character === \"\\f\" || character === \"\\v\") {\n if (name !== \"\") __velarAppendOwned(output, name);\n name = \"\";\n continue;\n }\n name += character;\n }\n if (name !== \"\") __velarAppendOwned(output, name);\n return output;\n}\n\nfunction __velarApplyClasses(element) {\n const sources = __velarGraphWeakMapRead(__velarRuntime.classSources, element);\n const next = __velarGraphCreateSet();\n if (sources) {\n for (const source of __velarGraphSetItems(sources)) {\n for (let index = 0; index < source.names.length; index += 1) __velarGraphSetInsert(next, source.names[index]);\n }\n }\n const state = __velarElementState(element, \"__velarClassState\", () => __velarGraphFreeze({\n base: __velarGraphCreateSet(__velarDomClassNames(element)),\n managed: __velarGraphCreateSet(),\n }));\n for (const name of __velarGraphSetItems(state.managed)) {\n if (!__velarGraphSetContains(next, name) && !__velarGraphSetContains(state.base, name)) __velarDomClassRemove(element, name);\n }\n for (const name of __velarGraphSetItems(next)) __velarDomClassInsert(element, name);\n __velarGraphSetEmpty(state.managed);\n for (const name of __velarGraphSetItems(next)) __velarGraphSetInsert(state.managed, name);\n}\n\nfunction __velarMoveClassSource(source, previous, next) {\n if (previous) {\n __velarDetachSource(__velarRuntime.classSources, previous, source);\n __velarApplyClasses(previous);\n }\n if (next) {\n __velarAttachSource(__velarRuntime.classSources, next, source);\n __velarApplyClasses(next);\n }\n}\n\nfunction __velarClassBind(element, read, scope) {\n const source = { names: [] };\n __velarAttachSource(__velarRuntime.classSources, element, source);\n __velarObserver(() => {\n source.names = __velarClassNames(read());\n __velarApplyClasses(element);\n }, \"dom\", scope);\n __velarAppendOwned(scope.cleanups, () => {\n __velarDetachSource(__velarRuntime.classSources, element, source);\n __velarApplyClasses(element);\n });\n}\n\n" + "function __velarHtml(element, read, scope) {\n __velarObserver(() => {\n const value = read();\n if (value != null && typeof value !== \"string\") throw new TypeError(\"unsafe:html requires string or null\");\n if (value?.length > 16 * 1024 * 1024) throw new RangeError(\"unsafe:html cannot exceed 16 MiB\");\n __velarDomSetHtml(element, value ?? \"\");\n }, \"dom\", scope);\n}\n\nfunction __velarOn(element, event, read, scope, modifiers = []) {\n if (typeof __velarInternalRead(read) !== \"function\") throw new TypeError(\"Event '\" + event + \"' requires a function\");\n const capture = __velarHasName(modifiers, \"capture\");\n const once = __velarHasName(modifiers, \"once\");\n let removed = false;\n const remove = () => {\n if (removed) return;\n removed = true;\n __velarDomRemoveListener(element, event, listener, capture);\n };\n const listener = (value) => {\n try {\n if (__velarHasName(modifiers, \"self\")) {\n const target = __velarEventField(value, \"target\", __velarEventTargetGetter);\n if (target === __velarEventMissingField) throw new TypeError(\"DOM event does not expose a native target\");\n if (target !== element) return;\n }\n // 'once' is spent here rather than through the native option, so the\n // documented order -- self, then prevent, then stop, then the handler --\n // holds for it too. The native option removes the registration on the\n // first dispatch that merely reaches the element, which for 'self' is\n // exactly the dispatch the handler must not see: 'on:click.self.once'\n // could then never run at all.\n if (once) remove();\n if (__velarHasName(modifiers, \"prevent\")) __velarEventCall(value, \"preventDefault\", __velarEventPreventDefault);\n if (__velarHasName(modifiers, \"stop\")) __velarEventCall(value, \"stopPropagation\", __velarEventStopPropagation);\n // The handler expression is re-read per dispatch so handlers routed\n // through live props always see the current value.\n const handler = __velarInternalRead(read);\n if (typeof handler !== \"function\") throw new TypeError(\"Event '\" + event + \"' requires a function\");\n const result = __velarUntracked(() => handler(value));\n __velarObservePromise(result, (error) => __velarReportEvent(error, scope, event));\n } catch (error) { __velarReportEvent(error, scope, event); }\n };\n __velarDomAddListener(element, event, listener, { capture });\n __velarAppendOwned(scope.cleanups, remove);\n}\n\nfunction __velarBindValue(element, state, scope, numeric = false, parse = null) {\n __velarObserver(() => {\n const value = state.get();\n if (value == null) __velarDomSetFieldValue(element, \"\");\n else if (numeric) {\n if (typeof value !== \"number\" || !__velarDomIsFinite(value)) throw new TypeError(\"Numeric bind:value requires a finite number\");\n __velarDomSetFieldValue(element, __velarDomString(value));\n } else {\n if (typeof value !== \"string\") throw new TypeError(\"bind:value requires text\");\n __velarDomSetFieldValue(element, value);\n }\n }, \"dom\", scope);\n const update = () => state.set(numeric ? __velarDomFieldNumber(element) : parse ? parse(__velarDomFieldValue(element)) : __velarDomFieldValue(element));\n __velarDomAddListener(element, \"input\", update, false);\n __velarAppendOwned(scope.cleanups, () => __velarDomRemoveListener(element, \"input\", update, false));\n}\n\nfunction __velarBindGroupValues(state, own) {\n const value = __velarInternalRead(() => state.get());\n const values = __velarListSnapshot(value, \"bind:group state\");\n const output = new __velarDomNativeArray(values.length);\n let count = 0;\n for (let index = 0; index < values.length; index += 1) {\n const item = values[index];\n if (typeof item !== \"string\") throw new TypeError(\"bind:group on a checkbox requires List<string> state\");\n if (item !== own) { output[count] = item; count += 1; }\n }\n output.length = count;\n return output;\n}\n\nfunction __velarBindGroup(element, state, scope, multiple = false, parse = null) {\n __velarObserver(() => {\n const own = __velarDomFieldValue(element);\n const value = state.get();\n if (!multiple) {\n if (value != null && typeof value !== \"string\") throw new TypeError(\"bind:group requires text state\");\n __velarDomSetFieldChecked(element, value === own);\n return;\n }\n const values = __velarListSnapshot(value, \"bind:group state\");\n let present = false;\n for (let index = 0; index < values.length; index += 1) if (values[index] === own) present = true;\n __velarDomSetFieldChecked(element, present);\n }, \"dom\", scope);\n const update = () => {\n const own = __velarDomFieldValue(element);\n if (!multiple) {\n if (__velarDomFieldChecked(element)) state.set(parse ? parse(own) : own);\n return;\n }\n const remaining = __velarBindGroupValues(state, own);\n if (__velarDomFieldChecked(element)) remaining[remaining.length] = own;\n state.set(remaining);\n };\n __velarDomAddListener(element, \"change\", update, false);\n __velarAppendOwned(scope.cleanups, () => __velarDomRemoveListener(element, \"change\", update, false));\n}\n\nfunction __velarBindChecked(element, state, scope) {\n __velarObserver(() => {\n const value = state.get();\n if (typeof value !== \"boolean\") throw new TypeError(\"bind:checked requires bool\");\n __velarDomSetFieldChecked(element, value);\n }, \"dom\", scope);\n const update = () => state.set(__velarDomFieldChecked(element));\n __velarDomAddListener(element, \"change\", update, false);\n __velarAppendOwned(scope.cleanups, () => __velarDomRemoveListener(element, \"change\", update, false));\n}\n\n// Prop handles give a component body live reads over its props store. The\n// component function still runs exactly once per instance; only reads race\n// ahead, so state initializers can never re-run on a prop update.\n" + "function __velarPropProvided(props, name) {\n // A children slot is rendered content rather than a value thunk. Asking for\n // its value to decide whether the required slot exists would build the slot\n // once here and again at the JSX position that owns it. Its own property is\n // the presence proof; the first value read remains the one rendering read.\n if (name === \"children\") return __velarGraphOwnDescriptor(props, name) !== undefined;\n return __velarInternalRead(() => props[name]) !== undefined;\n}\n\nfunction __velarRequiredProp(props, name, component) {\n if (!__velarPropProvided(props, name)) throw new TypeError(\"Component \" + component + \" requires prop \" + name);\n return __velarGraphFreeze({\n get() {\n const value = props[name];\n if (value === undefined) throw new TypeError(\"Component \" + component + \" requires prop \" + name);\n return value;\n },\n });\n}\n\nfunction __velarProp(props, name, fallback) {\n const fallbackValue = __velarPropProvided(props, name) ? undefined : fallback();\n return __velarGraphFreeze({\n get() {\n const value = props[name];\n return value === undefined ? fallbackValue : value;\n },\n });\n}\n\nfunction __velarBindComponentRef(instance, setRef) {\n if (setRef === undefined) return instance;\n if (!instance || typeof instance.__bindRef !== \"function\") throw new TypeError(\"This component does not expose a Handle\");\n instance.__bindRef(setRef);\n return instance;\n}\n\n// Holds every prop's cache open for the length of one construction. The graph\n// records a dependency for whichever observer is running, so forcing the props\n// under this one keeps them clean while the component function runs: a read\n// during construction is served from the value the force produced, and a\n// tracked read still subscribes the observer that made it. Releasing the hold\n// hands each prop over to whatever actually observes it, which is the second\n// half of the rule -- recomputed on demand, cached while observed.\nfunction __velarConstructionHold() {\n return {\n mode: \"computed\",\n stopped: false,\n running: false,\n selfInvalidations: 0,\n dependencies: __velarGraphCreateSet(),\n spareDependencies: null,\n notify() {},\n run() {},\n };\n}\n\n// Instantiates a component with a live props store: each prop is a cached\n// derived value the props object exposes as a tracked getter, so a prop\n// expression that nothing reads costs nothing after construction. The component\n// call itself is untracked so construction can never subscribe an enclosing\n// dynamic region to prop reads.\nfunction __velarInstantiate(component, thunks, children, scope, namespace, setRef) {\n const props = {};\n // 'style:' on a component host is the caller decorating the instance's root,\n // the way it decorates a native element. The slot the compiler inserts for it\n // is not a field the component declares, so it is bound here rather than\n // handed inward -- a component the runtime implements validates its props\n // against the fields it does declare and would refuse an unknown one.\n const styleRead = thunks.__velarStyle;\n const propNames = __velarGraphOwnNames(thunks);\n const accesses = [];\n for (let index = 0; index < propNames.length; index += 1) {\n const name = propNames[index];\n if (name === \"__velarStyle\") continue;\n // A prop is a derived value, not an eagerly pushed one: an unconditional\n // observer per prop re-ran every prop expression on every dependency\n // change, including the expensive ones behind props the component never\n // reads. The cache is the same one a declared derived value uses.\n const access = __velarComputed(thunks[name]);\n accesses[accesses.length] = access;\n __velarGraphDefine(props, name, { enumerable: true, get: () => access.get() });\n }\n // 'children' follows Vel's ordinary rules: it is rendered content owned by\n // the position that shows it, rebuilt whenever that position renders again.\n // As a one-shot fragment value it could be shown exactly once, and the first\n // time a conditional position hid it the content was destroyed for good.\n if (children !== undefined) __velarGraphDefine(props, \"children\", { enumerable: true, get: () => __velarChildrenNode(children, scope) });\n const instance = __velarUntracked(() => {\n if (accesses.length === 0) return component(props, namespace);\n // Component JSX evaluates the way the charter says a JavaScript object\n // literal does: every prop expression runs once, in the order the caller\n // wrote it, and only then does the component function run. 'children' is\n // not one of them -- it is rendered content owned by the position that\n // shows it, so a position that never shows it never builds it.\n const hold = __velarConstructionHold();\n try {\n __velarRuntime.runTracked(hold, () => {\n for (let index = 0; index < accesses.length; index += 1) accesses[index].get();\n });\n return component(props, namespace);\n } finally { __velarCleanupObserver(hold); }\n });\n if (styleRead !== undefined) __velarStyleBindRoot(instance.node, styleRead, scope);\n return __velarBindComponentRef(instance, setRef);\n}\n\n// A component element in child position: one stable instance whose prop\n// observers live in a dedicated scope, destroyed only when the position\n// itself unmounts. Construction failures stay contained to the position.\nfunction __velarChild(component, thunks, children, scope, namespace, setRef) {\n const childScope = __velarScope(scope.component);\n let constructed = false;\n __velarAppendOwned(scope.mounts, () => { if (constructed) __velarMountScope(childScope); });\n __velarAppendOwned(scope.cleanups, () => { if (constructed) __velarDestroyScope(childScope); });\n try {\n const node = __velarUseComponent(__velarInstantiate(component, thunks, children, childScope, namespace, setRef), childScope);\n constructed = true;\n return node;\n } catch (error) {\n __velarDestroyScope(childScope);\n // D114 P6 item 5 (LC-C2): the position that could not be built leaves the\n // compiler-owned fatal state, scoped to itself. It used to leave an HTML\n // comment -- invisible to the reader and to assistive technology alike --\n // so \"the initial render never leaves a blank page\" was true of the root\n // and false one node in. The isolation is unchanged: siblings mount and\n // keep running, and the failure is still reported in the `render` phase.\n const report = __velarReport(error, \"render\", scope);\n // The namespace this position renders into, so the marker is an element the\n // surrounding document can actually lay out (F7-web-b).\n return __velarFatalNode(\"This part of the page could not start: \" + report.error.message, namespace);\n }\n}\n\n// tick() promises the settled flush, so it drains the reactive queues instead\n// of hopping one microtask and hoping. Each round runs the pending flush and\n// yields, so work an observer queued asynchronously is picked up too; the round\n// count is bounded for the same reason the flush budget is, and the flush's own\n// budget is what ends a runaway cycle.\n" + "function __velarSettledStep() {\n return __velarManagedAsyncCreate((resolve) => __velarEnqueue(resolve));\n}\n\nfunction __velarSettled(rounds = 10000) {\n return __velarManagedAsyncThen(__velarSettledStep(), () => {\n if (__velarRuntime.flushPending) __velarFlush();\n if (rounds > 1 && (__velarGraphSetCount(__velarRuntime.domQueue)\n || __velarGraphSetCount(__velarRuntime.watchQueue) || __velarRuntime.flushPending)) {\n return __velarSettled(rounds - 1);\n }\n return null;\n });\n}\n\n// The failure the flush parked for its claimants, read rather than taken, and\n// this caller's wait ended.\n//\n// D114 F9-web (WB-C1): the park was drained by whoever looked first, so a\n// second `tick()` awaiting the same broken flush found nothing and resolved --\n// it stepped over the broken update the charter says awaiting `tick()` cannot\n// step over. Every `tick()` pending at that flush is a claimant and rejects\n// with the same failure, so the park is released only when the last of them has\n// left. That is also what makes a `tick()` awaited *after* the flush resolve:\n// by then nobody is waiting, so nothing was parked and nothing is left.\nfunction __velarClaimUnhandledFailure() {\n let claimed = null;\n for (const failure of __velarGraphSetItems(__velarRuntime.unhandledFailures)) { claimed = failure; break; }\n __velarLeaveTickWait();\n if (!__velarTickWaiting()) __velarGraphSetEmpty(__velarRuntime.unhandledFailures);\n return claimed;\n}\n\n// tick() is where an awaiting caller meets the reactive queue, which makes it\n// the owned place for a failure no handler claimed to surface: the test that\n// awaited the flush fails with the real error, and the process -- the test\n// runner, or the page -- continues.\n//\n// D114 P6 item 4 (LC-C1): the wait is counted, because the flush has to know\n// whether anyone is there. While this promise is pending the escalation path\n// parks an unowned failure instead of handing it to the host, in every host;\n// with nobody waiting it goes to the host error event (browser) or the report\n// channel (elsewhere) exactly as before.\nfunction __velarTick() {\n __velarEnterTickWait();\n return __velarManagedAsyncThen(__velarSettled(), () => {\n const failure = __velarClaimUnhandledFailure();\n if (failure !== null) throw failure;\n return null;\n }, (error) => {\n __velarClaimUnhandledFailure();\n throw error;\n });\n}";
|
|
96
96
|
//# sourceMappingURL=runtime-sources.generated.js.map
|