@agent-native/core-corpus 0.231.0 → 0.232.0-nightly-20261118152333

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (19) hide show
  1. package/corpus/README.md +1 -1
  2. package/corpus/templates/analytics/.deploy-tmp/agent-native-provided-plugins.mjs +10 -0
  3. package/corpus/templates/assets/.deploy-tmp/agent-native-provided-plugins.mjs +10 -0
  4. package/corpus/templates/brain/.deploy-tmp/agent-native-provided-plugins.mjs +10 -0
  5. package/corpus/templates/calendar/.deploy-tmp/agent-native-provided-plugins.mjs +10 -0
  6. package/corpus/templates/chat/.deploy-tmp/agent-native-provided-plugins.mjs +10 -0
  7. package/corpus/templates/clips/.deploy-tmp/agent-native-provided-plugins.mjs +10 -0
  8. package/corpus/templates/content/.deploy-tmp/agent-native-provided-plugins.mjs +10 -0
  9. package/corpus/templates/content/changelog/2026-11-18-content-opens-reliably-in-browsers-missing-newer-javascript-.md +6 -0
  10. package/corpus/templates/crm/.deploy-tmp/agent-native-provided-plugins.mjs +10 -0
  11. package/corpus/templates/design/.deploy-tmp/agent-native-provided-plugins.mjs +10 -0
  12. package/corpus/templates/design/.generated/bridge/native-builtin-metadata.generated.ts +326 -0
  13. package/corpus/templates/design/.generated/bridge/native-worker-source.generated.ts +6 -0
  14. package/corpus/templates/dispatch/.deploy-tmp/agent-native-provided-plugins.mjs +10 -0
  15. package/corpus/templates/forms/.deploy-tmp/agent-native-provided-plugins.mjs +10 -0
  16. package/corpus/templates/mail/.deploy-tmp/agent-native-provided-plugins.mjs +10 -0
  17. package/corpus/templates/plan/.deploy-tmp/agent-native-provided-plugins.mjs +10 -0
  18. package/corpus/templates/slides/.deploy-tmp/agent-native-provided-plugins.mjs +10 -0
  19. package/package.json +1 -1
@@ -0,0 +1,6 @@
1
+ // AUTO-GENERATED by bridge/codegen.ts — do not edit manually.
2
+ // Run: pnpm exec tsx app/components/design/bridge/codegen.ts
3
+
4
+ /** Self-contained native GPU worker script. Keep this generation before bridge compilation. */
5
+ export const nativeWorkerSource: string =
6
+ '"use strict";\n(() => {\n var __defProp = Object.defineProperty;\n var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\n var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);\n\n // shared/native-effect-transform.ts\n function planNativeEffectTransform(transform, geometry) {\n const { width, height, pixelRatio, target } = geometry;\n const translate = transform?.translate ?? [0, 0];\n const scale = transform?.scale ?? [1, 1];\n const angle = transform?.rotate ?? 0;\n const origin = transform?.origin ?? [0.5, 0.5];\n if (![width, height, pixelRatio, target.width, target.height].every(\n (value) => Number.isFinite(value) && value > 0\n ) || ![target.x, target.y, angle, ...translate, ...scale, ...origin].every(\n Number.isFinite\n ) || scale.some((value) => value <= 0 || value > 100) || origin.some((value) => value < 0 || value > 1) || translate.some((value) => Math.abs(value) > 1e5) || Math.abs(angle) > 100 * Math.PI)\n return {\n ok: false,\n code: "effect-transform-invalid",\n detail: "Effect transform or target geometry is outside its bounds."\n };\n const ox = target.x + origin[0] * target.width;\n const oy = target.y + origin[1] * target.height;\n const tx = translate[0] * pixelRatio;\n const ty = translate[1] * pixelRatio;\n const cosine = Math.cos(angle);\n const sine = Math.sin(angle);\n const a = cosine / scale[0];\n const b = sine / scale[0];\n const d = -sine / scale[1];\n const e = cosine / scale[1];\n const rows = [\n [a, b * height / width, (ox - a * (ox + tx) - b * (oy + ty)) / width, 0],\n [d * width / height, e, (oy - d * (ox + tx) - e * (oy + ty)) / height, 0]\n ];\n if (rows.some(\n (row) => row.some((value) => !Number.isFinite(Math.fround(value)))\n ))\n return {\n ok: false,\n code: "effect-transform-invalid",\n detail: "Effect transform cannot be represented by GPU float uniforms."\n };\n return { ok: true, rows };\n }\n\n // shared/native-export-region.ts\n function planNativeExportRegion({\n viewport,\n cropRect,\n pixelRatio\n }) {\n if (![viewport.width, viewport.height].every(\n (value) => Number.isSafeInteger(value) && value > 0 && value <= 32768\n ))\n return { ok: false, code: "viewport-invalid" };\n const region = cropRect ?? { x: 0, y: 0, ...viewport };\n if (![region.x, region.y, region.width, region.height].every(Number.isFinite) || region.width <= 0 || region.height <= 0)\n return { ok: false, code: "region-invalid" };\n const width = Math.ceil(region.width * pixelRatio);\n const height = Math.ceil(region.height * pixelRatio);\n if (!Number.isFinite(pixelRatio) || pixelRatio <= 0 || pixelRatio > 4 || !Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 || width > 4096 || height > 4096 || width * height > 8388608)\n return { ok: false, code: "size-unsupported" };\n return { ok: true, region: { ...region }, width, height };\n }\n\n // ../../node_modules/.pnpm/parse5@8.0.1/node_modules/parse5/dist/common/unicode.js\n var CODE_POINTS;\n (function(CODE_POINTS2) {\n CODE_POINTS2[CODE_POINTS2["EOF"] = -1] = "EOF";\n CODE_POINTS2[CODE_POINTS2["NULL"] = 0] = "NULL";\n CODE_POINTS2[CODE_POINTS2["TABULATION"] = 9] = "TABULATION";\n CODE_POINTS2[CODE_POINTS2["CARRIAGE_RETURN"] = 13] = "CARRIAGE_RETURN";\n CODE_POINTS2[CODE_POINTS2["LINE_FEED"] = 10] = "LINE_FEED";\n CODE_POINTS2[CODE_POINTS2["FORM_FEED"] = 12] = "FORM_FEED";\n CODE_POINTS2[CODE_POINTS2["SPACE"] = 32] = "SPACE";\n CODE_POINTS2[CODE_POINTS2["EXCLAMATION_MARK"] = 33] = "EXCLAMATION_MARK";\n CODE_POINTS2[CODE_POINTS2["QUOTATION_MARK"] = 34] = "QUOTATION_MARK";\n CODE_POINTS2[CODE_POINTS2["AMPERSAND"] = 38] = "AMPERSAND";\n CODE_POINTS2[CODE_POINTS2["APOSTROPHE"] = 39] = "APOSTROPHE";\n CODE_POINTS2[CODE_POINTS2["HYPHEN_MINUS"] = 45] = "HYPHEN_MINUS";\n CODE_POINTS2[CODE_POINTS2["SOLIDUS"] = 47] = "SOLIDUS";\n CODE_POINTS2[CODE_POINTS2["DIGIT_0"] = 48] = "DIGIT_0";\n CODE_POINTS2[CODE_POINTS2["DIGIT_9"] = 57] = "DIGIT_9";\n CODE_POINTS2[CODE_POINTS2["SEMICOLON"] = 59] = "SEMICOLON";\n CODE_POINTS2[CODE_POINTS2["LESS_THAN_SIGN"] = 60] = "LESS_THAN_SIGN";\n CODE_POINTS2[CODE_POINTS2["EQUALS_SIGN"] = 61] = "EQUALS_SIGN";\n CODE_POINTS2[CODE_POINTS2["GREATER_THAN_SIGN"] = 62] = "GREATER_THAN_SIGN";\n CODE_POINTS2[CODE_POINTS2["QUESTION_MARK"] = 63] = "QUESTION_MARK";\n CODE_POINTS2[CODE_POINTS2["LATIN_CAPITAL_A"] = 65] = "LATIN_CAPITAL_A";\n CODE_POINTS2[CODE_POINTS2["LATIN_CAPITAL_Z"] = 90] = "LATIN_CAPITAL_Z";\n CODE_POINTS2[CODE_POINTS2["RIGHT_SQUARE_BRACKET"] = 93] = "RIGHT_SQUARE_BRACKET";\n CODE_POINTS2[CODE_POINTS2["GRAVE_ACCENT"] = 96] = "GRAVE_ACCENT";\n CODE_POINTS2[CODE_POINTS2["LATIN_SMALL_A"] = 97] = "LATIN_SMALL_A";\n CODE_POINTS2[CODE_POINTS2["LATIN_SMALL_Z"] = 122] = "LATIN_SMALL_Z";\n })(CODE_POINTS || (CODE_POINTS = {}));\n\n // ../../node_modules/.pnpm/parse5@8.0.1/node_modules/parse5/dist/common/error-codes.js\n var ERR;\n (function(ERR2) {\n ERR2["controlCharacterInInputStream"] = "control-character-in-input-stream";\n ERR2["noncharacterInInputStream"] = "noncharacter-in-input-stream";\n ERR2["surrogateInInputStream"] = "surrogate-in-input-stream";\n ERR2["nonVoidHtmlElementStartTagWithTrailingSolidus"] = "non-void-html-element-start-tag-with-trailing-solidus";\n ERR2["endTagWithAttributes"] = "end-tag-with-attributes";\n ERR2["endTagWithTrailingSolidus"] = "end-tag-with-trailing-solidus";\n ERR2["unexpectedSolidusInTag"] = "unexpected-solidus-in-tag";\n ERR2["unexpectedNullCharacter"] = "unexpected-null-character";\n ERR2["unexpectedQuestionMarkInsteadOfTagName"] = "unexpected-question-mark-instead-of-tag-name";\n ERR2["invalidFirstCharacterOfTagName"] = "invalid-first-character-of-tag-name";\n ERR2["unexpectedEqualsSignBeforeAttributeName"] = "unexpected-equals-sign-before-attribute-name";\n ERR2["missingEndTagName"] = "missing-end-tag-name";\n ERR2["unexpectedCharacterInAttributeName"] = "unexpected-character-in-attribute-name";\n ERR2["unknownNamedCharacterReference"] = "unknown-named-character-reference";\n ERR2["missingSemicolonAfterCharacterReference"] = "missing-semicolon-after-character-reference";\n ERR2["unexpectedCharacterAfterDoctypeSystemIdentifier"] = "unexpected-character-after-doctype-system-identifier";\n ERR2["unexpectedCharacterInUnquotedAttributeValue"] = "unexpected-character-in-unquoted-attribute-value";\n ERR2["eofBeforeTagName"] = "eof-before-tag-name";\n ERR2["eofInTag"] = "eof-in-tag";\n ERR2["missingAttributeValue"] = "missing-attribute-value";\n ERR2["missingWhitespaceBetweenAttributes"] = "missing-whitespace-between-attributes";\n ERR2["missingWhitespaceAfterDoctypePublicKeyword"] = "missing-whitespace-after-doctype-public-keyword";\n ERR2["missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers"] = "missing-whitespace-between-doctype-public-and-system-identifiers";\n ERR2["missingWhitespaceAfterDoctypeSystemKeyword"] = "missing-whitespace-after-doctype-system-keyword";\n ERR2["missingQuoteBeforeDoctypePublicIdentifier"] = "missing-quote-before-doctype-public-identifier";\n ERR2["missingQuoteBeforeDoctypeSystemIdentifier"] = "missing-quote-before-doctype-system-identifier";\n ERR2["missingDoctypePublicIdentifier"] = "missing-doctype-public-identifier";\n ERR2["missingDoctypeSystemIdentifier"] = "missing-doctype-system-identifier";\n ERR2["abruptDoctypePublicIdentifier"] = "abrupt-doctype-public-identifier";\n ERR2["abruptDoctypeSystemIdentifier"] = "abrupt-doctype-system-identifier";\n ERR2["cdataInHtmlContent"] = "cdata-in-html-content";\n ERR2["incorrectlyOpenedComment"] = "incorrectly-opened-comment";\n ERR2["eofInScriptHtmlCommentLikeText"] = "eof-in-script-html-comment-like-text";\n ERR2["eofInDoctype"] = "eof-in-doctype";\n ERR2["nestedComment"] = "nested-comment";\n ERR2["abruptClosingOfEmptyComment"] = "abrupt-closing-of-empty-comment";\n ERR2["eofInComment"] = "eof-in-comment";\n ERR2["incorrectlyClosedComment"] = "incorrectly-closed-comment";\n ERR2["eofInCdata"] = "eof-in-cdata";\n ERR2["absenceOfDigitsInNumericCharacterReference"] = "absence-of-digits-in-numeric-character-reference";\n ERR2["nullCharacterReference"] = "null-character-reference";\n ERR2["surrogateCharacterReference"] = "surrogate-character-reference";\n ERR2["characterReferenceOutsideUnicodeRange"] = "character-reference-outside-unicode-range";\n ERR2["controlCharacterReference"] = "control-character-reference";\n ERR2["noncharacterCharacterReference"] = "noncharacter-character-reference";\n ERR2["missingWhitespaceBeforeDoctypeName"] = "missing-whitespace-before-doctype-name";\n ERR2["missingDoctypeName"] = "missing-doctype-name";\n ERR2["invalidCharacterSequenceAfterDoctypeName"] = "invalid-character-sequence-after-doctype-name";\n ERR2["duplicateAttribute"] = "duplicate-attribute";\n ERR2["nonConformingDoctype"] = "non-conforming-doctype";\n ERR2["missingDoctype"] = "missing-doctype";\n ERR2["misplacedDoctype"] = "misplaced-doctype";\n ERR2["endTagWithoutMatchingOpenElement"] = "end-tag-without-matching-open-element";\n ERR2["closingOfElementWithOpenChildElements"] = "closing-of-element-with-open-child-elements";\n ERR2["disallowedContentInNoscriptInHead"] = "disallowed-content-in-noscript-in-head";\n ERR2["openElementsLeftAfterEof"] = "open-elements-left-after-eof";\n ERR2["abandonedHeadElementChild"] = "abandoned-head-element-child";\n ERR2["misplacedStartTagForHeadElement"] = "misplaced-start-tag-for-head-element";\n ERR2["nestedNoscriptInHead"] = "nested-noscript-in-head";\n ERR2["eofInElementThatCanContainOnlyText"] = "eof-in-element-that-can-contain-only-text";\n })(ERR || (ERR = {}));\n\n // ../../node_modules/.pnpm/parse5@8.0.1/node_modules/parse5/dist/tokenizer/preprocessor.js\n var DEFAULT_BUFFER_WATERLINE = 1 << 16;\n\n // ../../node_modules/.pnpm/parse5@8.0.1/node_modules/parse5/dist/common/token.js\n var TokenType;\n (function(TokenType2) {\n TokenType2[TokenType2["CHARACTER"] = 0] = "CHARACTER";\n TokenType2[TokenType2["NULL_CHARACTER"] = 1] = "NULL_CHARACTER";\n TokenType2[TokenType2["WHITESPACE_CHARACTER"] = 2] = "WHITESPACE_CHARACTER";\n TokenType2[TokenType2["START_TAG"] = 3] = "START_TAG";\n TokenType2[TokenType2["END_TAG"] = 4] = "END_TAG";\n TokenType2[TokenType2["COMMENT"] = 5] = "COMMENT";\n TokenType2[TokenType2["DOCTYPE"] = 6] = "DOCTYPE";\n TokenType2[TokenType2["EOF"] = 7] = "EOF";\n TokenType2[TokenType2["HIBERNATION"] = 8] = "HIBERNATION";\n })(TokenType || (TokenType = {}));\n\n // ../../node_modules/.pnpm/parse5@8.0.1/node_modules/parse5/dist/common/html.js\n var NS;\n (function(NS2) {\n NS2["HTML"] = "http://www.w3.org/1999/xhtml";\n NS2["MATHML"] = "http://www.w3.org/1998/Math/MathML";\n NS2["SVG"] = "http://www.w3.org/2000/svg";\n NS2["XLINK"] = "http://www.w3.org/1999/xlink";\n NS2["XML"] = "http://www.w3.org/XML/1998/namespace";\n NS2["XMLNS"] = "http://www.w3.org/2000/xmlns/";\n })(NS || (NS = {}));\n var ATTRS;\n (function(ATTRS2) {\n ATTRS2["TYPE"] = "type";\n ATTRS2["ACTION"] = "action";\n ATTRS2["ENCODING"] = "encoding";\n ATTRS2["PROMPT"] = "prompt";\n ATTRS2["NAME"] = "name";\n ATTRS2["COLOR"] = "color";\n ATTRS2["FACE"] = "face";\n ATTRS2["SIZE"] = "size";\n })(ATTRS || (ATTRS = {}));\n var DOCUMENT_MODE;\n (function(DOCUMENT_MODE2) {\n DOCUMENT_MODE2["NO_QUIRKS"] = "no-quirks";\n DOCUMENT_MODE2["QUIRKS"] = "quirks";\n DOCUMENT_MODE2["LIMITED_QUIRKS"] = "limited-quirks";\n })(DOCUMENT_MODE || (DOCUMENT_MODE = {}));\n var TAG_NAMES;\n (function(TAG_NAMES2) {\n TAG_NAMES2["A"] = "a";\n TAG_NAMES2["ADDRESS"] = "address";\n TAG_NAMES2["ANNOTATION_XML"] = "annotation-xml";\n TAG_NAMES2["APPLET"] = "applet";\n TAG_NAMES2["AREA"] = "area";\n TAG_NAMES2["ARTICLE"] = "article";\n TAG_NAMES2["ASIDE"] = "aside";\n TAG_NAMES2["B"] = "b";\n TAG_NAMES2["BASE"] = "base";\n TAG_NAMES2["BASEFONT"] = "basefont";\n TAG_NAMES2["BGSOUND"] = "bgsound";\n TAG_NAMES2["BIG"] = "big";\n TAG_NAMES2["BLOCKQUOTE"] = "blockquote";\n TAG_NAMES2["BODY"] = "body";\n TAG_NAMES2["BR"] = "br";\n TAG_NAMES2["BUTTON"] = "button";\n TAG_NAMES2["CAPTION"] = "caption";\n TAG_NAMES2["CENTER"] = "center";\n TAG_NAMES2["CODE"] = "code";\n TAG_NAMES2["COL"] = "col";\n TAG_NAMES2["COLGROUP"] = "colgroup";\n TAG_NAMES2["DD"] = "dd";\n TAG_NAMES2["DESC"] = "desc";\n TAG_NAMES2["DETAILS"] = "details";\n TAG_NAMES2["DIALOG"] = "dialog";\n TAG_NAMES2["DIR"] = "dir";\n TAG_NAMES2["DIV"] = "div";\n TAG_NAMES2["DL"] = "dl";\n TAG_NAMES2["DT"] = "dt";\n TAG_NAMES2["EM"] = "em";\n TAG_NAMES2["EMBED"] = "embed";\n TAG_NAMES2["FIELDSET"] = "fieldset";\n TAG_NAMES2["FIGCAPTION"] = "figcaption";\n TAG_NAMES2["FIGURE"] = "figure";\n TAG_NAMES2["FONT"] = "font";\n TAG_NAMES2["FOOTER"] = "footer";\n TAG_NAMES2["FOREIGN_OBJECT"] = "foreignObject";\n TAG_NAMES2["FORM"] = "form";\n TAG_NAMES2["FRAME"] = "frame";\n TAG_NAMES2["FRAMESET"] = "frameset";\n TAG_NAMES2["H1"] = "h1";\n TAG_NAMES2["H2"] = "h2";\n TAG_NAMES2["H3"] = "h3";\n TAG_NAMES2["H4"] = "h4";\n TAG_NAMES2["H5"] = "h5";\n TAG_NAMES2["H6"] = "h6";\n TAG_NAMES2["HEAD"] = "head";\n TAG_NAMES2["HEADER"] = "header";\n TAG_NAMES2["HGROUP"] = "hgroup";\n TAG_NAMES2["HR"] = "hr";\n TAG_NAMES2["HTML"] = "html";\n TAG_NAMES2["I"] = "i";\n TAG_NAMES2["IMG"] = "img";\n TAG_NAMES2["IMAGE"] = "image";\n TAG_NAMES2["INPUT"] = "input";\n TAG_NAMES2["IFRAME"] = "iframe";\n TAG_NAMES2["KEYGEN"] = "keygen";\n TAG_NAMES2["LABEL"] = "label";\n TAG_NAMES2["LI"] = "li";\n TAG_NAMES2["LINK"] = "link";\n TAG_NAMES2["LISTING"] = "listing";\n TAG_NAMES2["MAIN"] = "main";\n TAG_NAMES2["MALIGNMARK"] = "malignmark";\n TAG_NAMES2["MARQUEE"] = "marquee";\n TAG_NAMES2["MATH"] = "math";\n TAG_NAMES2["MENU"] = "menu";\n TAG_NAMES2["META"] = "meta";\n TAG_NAMES2["MGLYPH"] = "mglyph";\n TAG_NAMES2["MI"] = "mi";\n TAG_NAMES2["MO"] = "mo";\n TAG_NAMES2["MN"] = "mn";\n TAG_NAMES2["MS"] = "ms";\n TAG_NAMES2["MTEXT"] = "mtext";\n TAG_NAMES2["NAV"] = "nav";\n TAG_NAMES2["NOBR"] = "nobr";\n TAG_NAMES2["NOFRAMES"] = "noframes";\n TAG_NAMES2["NOEMBED"] = "noembed";\n TAG_NAMES2["NOSCRIPT"] = "noscript";\n TAG_NAMES2["OBJECT"] = "object";\n TAG_NAMES2["OL"] = "ol";\n TAG_NAMES2["OPTGROUP"] = "optgroup";\n TAG_NAMES2["OPTION"] = "option";\n TAG_NAMES2["P"] = "p";\n TAG_NAMES2["PARAM"] = "param";\n TAG_NAMES2["PLAINTEXT"] = "plaintext";\n TAG_NAMES2["PRE"] = "pre";\n TAG_NAMES2["RB"] = "rb";\n TAG_NAMES2["RP"] = "rp";\n TAG_NAMES2["RT"] = "rt";\n TAG_NAMES2["RTC"] = "rtc";\n TAG_NAMES2["RUBY"] = "ruby";\n TAG_NAMES2["S"] = "s";\n TAG_NAMES2["SCRIPT"] = "script";\n TAG_NAMES2["SEARCH"] = "search";\n TAG_NAMES2["SECTION"] = "section";\n TAG_NAMES2["SELECT"] = "select";\n TAG_NAMES2["SOURCE"] = "source";\n TAG_NAMES2["SMALL"] = "small";\n TAG_NAMES2["SPAN"] = "span";\n TAG_NAMES2["STRIKE"] = "strike";\n TAG_NAMES2["STRONG"] = "strong";\n TAG_NAMES2["STYLE"] = "style";\n TAG_NAMES2["SUB"] = "sub";\n TAG_NAMES2["SUMMARY"] = "summary";\n TAG_NAMES2["SUP"] = "sup";\n TAG_NAMES2["TABLE"] = "table";\n TAG_NAMES2["TBODY"] = "tbody";\n TAG_NAMES2["TEMPLATE"] = "template";\n TAG_NAMES2["TEXTAREA"] = "textarea";\n TAG_NAMES2["TFOOT"] = "tfoot";\n TAG_NAMES2["TD"] = "td";\n TAG_NAMES2["TH"] = "th";\n TAG_NAMES2["THEAD"] = "thead";\n TAG_NAMES2["TITLE"] = "title";\n TAG_NAMES2["TR"] = "tr";\n TAG_NAMES2["TRACK"] = "track";\n TAG_NAMES2["TT"] = "tt";\n TAG_NAMES2["U"] = "u";\n TAG_NAMES2["UL"] = "ul";\n TAG_NAMES2["SVG"] = "svg";\n TAG_NAMES2["VAR"] = "var";\n TAG_NAMES2["WBR"] = "wbr";\n TAG_NAMES2["XMP"] = "xmp";\n })(TAG_NAMES || (TAG_NAMES = {}));\n var TAG_ID;\n (function(TAG_ID2) {\n TAG_ID2[TAG_ID2["UNKNOWN"] = 0] = "UNKNOWN";\n TAG_ID2[TAG_ID2["A"] = 1] = "A";\n TAG_ID2[TAG_ID2["ADDRESS"] = 2] = "ADDRESS";\n TAG_ID2[TAG_ID2["ANNOTATION_XML"] = 3] = "ANNOTATION_XML";\n TAG_ID2[TAG_ID2["APPLET"] = 4] = "APPLET";\n TAG_ID2[TAG_ID2["AREA"] = 5] = "AREA";\n TAG_ID2[TAG_ID2["ARTICLE"] = 6] = "ARTICLE";\n TAG_ID2[TAG_ID2["ASIDE"] = 7] = "ASIDE";\n TAG_ID2[TAG_ID2["B"] = 8] = "B";\n TAG_ID2[TAG_ID2["BASE"] = 9] = "BASE";\n TAG_ID2[TAG_ID2["BASEFONT"] = 10] = "BASEFONT";\n TAG_ID2[TAG_ID2["BGSOUND"] = 11] = "BGSOUND";\n TAG_ID2[TAG_ID2["BIG"] = 12] = "BIG";\n TAG_ID2[TAG_ID2["BLOCKQUOTE"] = 13] = "BLOCKQUOTE";\n TAG_ID2[TAG_ID2["BODY"] = 14] = "BODY";\n TAG_ID2[TAG_ID2["BR"] = 15] = "BR";\n TAG_ID2[TAG_ID2["BUTTON"] = 16] = "BUTTON";\n TAG_ID2[TAG_ID2["CAPTION"] = 17] = "CAPTION";\n TAG_ID2[TAG_ID2["CENTER"] = 18] = "CENTER";\n TAG_ID2[TAG_ID2["CODE"] = 19] = "CODE";\n TAG_ID2[TAG_ID2["COL"] = 20] = "COL";\n TAG_ID2[TAG_ID2["COLGROUP"] = 21] = "COLGROUP";\n TAG_ID2[TAG_ID2["DD"] = 22] = "DD";\n TAG_ID2[TAG_ID2["DESC"] = 23] = "DESC";\n TAG_ID2[TAG_ID2["DETAILS"] = 24] = "DETAILS";\n TAG_ID2[TAG_ID2["DIALOG"] = 25] = "DIALOG";\n TAG_ID2[TAG_ID2["DIR"] = 26] = "DIR";\n TAG_ID2[TAG_ID2["DIV"] = 27] = "DIV";\n TAG_ID2[TAG_ID2["DL"] = 28] = "DL";\n TAG_ID2[TAG_ID2["DT"] = 29] = "DT";\n TAG_ID2[TAG_ID2["EM"] = 30] = "EM";\n TAG_ID2[TAG_ID2["EMBED"] = 31] = "EMBED";\n TAG_ID2[TAG_ID2["FIELDSET"] = 32] = "FIELDSET";\n TAG_ID2[TAG_ID2["FIGCAPTION"] = 33] = "FIGCAPTION";\n TAG_ID2[TAG_ID2["FIGURE"] = 34] = "FIGURE";\n TAG_ID2[TAG_ID2["FONT"] = 35] = "FONT";\n TAG_ID2[TAG_ID2["FOOTER"] = 36] = "FOOTER";\n TAG_ID2[TAG_ID2["FOREIGN_OBJECT"] = 37] = "FOREIGN_OBJECT";\n TAG_ID2[TAG_ID2["FORM"] = 38] = "FORM";\n TAG_ID2[TAG_ID2["FRAME"] = 39] = "FRAME";\n TAG_ID2[TAG_ID2["FRAMESET"] = 40] = "FRAMESET";\n TAG_ID2[TAG_ID2["H1"] = 41] = "H1";\n TAG_ID2[TAG_ID2["H2"] = 42] = "H2";\n TAG_ID2[TAG_ID2["H3"] = 43] = "H3";\n TAG_ID2[TAG_ID2["H4"] = 44] = "H4";\n TAG_ID2[TAG_ID2["H5"] = 45] = "H5";\n TAG_ID2[TAG_ID2["H6"] = 46] = "H6";\n TAG_ID2[TAG_ID2["HEAD"] = 47] = "HEAD";\n TAG_ID2[TAG_ID2["HEADER"] = 48] = "HEADER";\n TAG_ID2[TAG_ID2["HGROUP"] = 49] = "HGROUP";\n TAG_ID2[TAG_ID2["HR"] = 50] = "HR";\n TAG_ID2[TAG_ID2["HTML"] = 51] = "HTML";\n TAG_ID2[TAG_ID2["I"] = 52] = "I";\n TAG_ID2[TAG_ID2["IMG"] = 53] = "IMG";\n TAG_ID2[TAG_ID2["IMAGE"] = 54] = "IMAGE";\n TAG_ID2[TAG_ID2["INPUT"] = 55] = "INPUT";\n TAG_ID2[TAG_ID2["IFRAME"] = 56] = "IFRAME";\n TAG_ID2[TAG_ID2["KEYGEN"] = 57] = "KEYGEN";\n TAG_ID2[TAG_ID2["LABEL"] = 58] = "LABEL";\n TAG_ID2[TAG_ID2["LI"] = 59] = "LI";\n TAG_ID2[TAG_ID2["LINK"] = 60] = "LINK";\n TAG_ID2[TAG_ID2["LISTING"] = 61] = "LISTING";\n TAG_ID2[TAG_ID2["MAIN"] = 62] = "MAIN";\n TAG_ID2[TAG_ID2["MALIGNMARK"] = 63] = "MALIGNMARK";\n TAG_ID2[TAG_ID2["MARQUEE"] = 64] = "MARQUEE";\n TAG_ID2[TAG_ID2["MATH"] = 65] = "MATH";\n TAG_ID2[TAG_ID2["MENU"] = 66] = "MENU";\n TAG_ID2[TAG_ID2["META"] = 67] = "META";\n TAG_ID2[TAG_ID2["MGLYPH"] = 68] = "MGLYPH";\n TAG_ID2[TAG_ID2["MI"] = 69] = "MI";\n TAG_ID2[TAG_ID2["MO"] = 70] = "MO";\n TAG_ID2[TAG_ID2["MN"] = 71] = "MN";\n TAG_ID2[TAG_ID2["MS"] = 72] = "MS";\n TAG_ID2[TAG_ID2["MTEXT"] = 73] = "MTEXT";\n TAG_ID2[TAG_ID2["NAV"] = 74] = "NAV";\n TAG_ID2[TAG_ID2["NOBR"] = 75] = "NOBR";\n TAG_ID2[TAG_ID2["NOFRAMES"] = 76] = "NOFRAMES";\n TAG_ID2[TAG_ID2["NOEMBED"] = 77] = "NOEMBED";\n TAG_ID2[TAG_ID2["NOSCRIPT"] = 78] = "NOSCRIPT";\n TAG_ID2[TAG_ID2["OBJECT"] = 79] = "OBJECT";\n TAG_ID2[TAG_ID2["OL"] = 80] = "OL";\n TAG_ID2[TAG_ID2["OPTGROUP"] = 81] = "OPTGROUP";\n TAG_ID2[TAG_ID2["OPTION"] = 82] = "OPTION";\n TAG_ID2[TAG_ID2["P"] = 83] = "P";\n TAG_ID2[TAG_ID2["PARAM"] = 84] = "PARAM";\n TAG_ID2[TAG_ID2["PLAINTEXT"] = 85] = "PLAINTEXT";\n TAG_ID2[TAG_ID2["PRE"] = 86] = "PRE";\n TAG_ID2[TAG_ID2["RB"] = 87] = "RB";\n TAG_ID2[TAG_ID2["RP"] = 88] = "RP";\n TAG_ID2[TAG_ID2["RT"] = 89] = "RT";\n TAG_ID2[TAG_ID2["RTC"] = 90] = "RTC";\n TAG_ID2[TAG_ID2["RUBY"] = 91] = "RUBY";\n TAG_ID2[TAG_ID2["S"] = 92] = "S";\n TAG_ID2[TAG_ID2["SCRIPT"] = 93] = "SCRIPT";\n TAG_ID2[TAG_ID2["SEARCH"] = 94] = "SEARCH";\n TAG_ID2[TAG_ID2["SECTION"] = 95] = "SECTION";\n TAG_ID2[TAG_ID2["SELECT"] = 96] = "SELECT";\n TAG_ID2[TAG_ID2["SOURCE"] = 97] = "SOURCE";\n TAG_ID2[TAG_ID2["SMALL"] = 98] = "SMALL";\n TAG_ID2[TAG_ID2["SPAN"] = 99] = "SPAN";\n TAG_ID2[TAG_ID2["STRIKE"] = 100] = "STRIKE";\n TAG_ID2[TAG_ID2["STRONG"] = 101] = "STRONG";\n TAG_ID2[TAG_ID2["STYLE"] = 102] = "STYLE";\n TAG_ID2[TAG_ID2["SUB"] = 103] = "SUB";\n TAG_ID2[TAG_ID2["SUMMARY"] = 104] = "SUMMARY";\n TAG_ID2[TAG_ID2["SUP"] = 105] = "SUP";\n TAG_ID2[TAG_ID2["TABLE"] = 106] = "TABLE";\n TAG_ID2[TAG_ID2["TBODY"] = 107] = "TBODY";\n TAG_ID2[TAG_ID2["TEMPLATE"] = 108] = "TEMPLATE";\n TAG_ID2[TAG_ID2["TEXTAREA"] = 109] = "TEXTAREA";\n TAG_ID2[TAG_ID2["TFOOT"] = 110] = "TFOOT";\n TAG_ID2[TAG_ID2["TD"] = 111] = "TD";\n TAG_ID2[TAG_ID2["TH"] = 112] = "TH";\n TAG_ID2[TAG_ID2["THEAD"] = 113] = "THEAD";\n TAG_ID2[TAG_ID2["TITLE"] = 114] = "TITLE";\n TAG_ID2[TAG_ID2["TR"] = 115] = "TR";\n TAG_ID2[TAG_ID2["TRACK"] = 116] = "TRACK";\n TAG_ID2[TAG_ID2["TT"] = 117] = "TT";\n TAG_ID2[TAG_ID2["U"] = 118] = "U";\n TAG_ID2[TAG_ID2["UL"] = 119] = "UL";\n TAG_ID2[TAG_ID2["SVG"] = 120] = "SVG";\n TAG_ID2[TAG_ID2["VAR"] = 121] = "VAR";\n TAG_ID2[TAG_ID2["WBR"] = 122] = "WBR";\n TAG_ID2[TAG_ID2["XMP"] = 123] = "XMP";\n })(TAG_ID || (TAG_ID = {}));\n var TAG_NAME_TO_ID = /* @__PURE__ */ new Map([\n [TAG_NAMES.A, TAG_ID.A],\n [TAG_NAMES.ADDRESS, TAG_ID.ADDRESS],\n [TAG_NAMES.ANNOTATION_XML, TAG_ID.ANNOTATION_XML],\n [TAG_NAMES.APPLET, TAG_ID.APPLET],\n [TAG_NAMES.AREA, TAG_ID.AREA],\n [TAG_NAMES.ARTICLE, TAG_ID.ARTICLE],\n [TAG_NAMES.ASIDE, TAG_ID.ASIDE],\n [TAG_NAMES.B, TAG_ID.B],\n [TAG_NAMES.BASE, TAG_ID.BASE],\n [TAG_NAMES.BASEFONT, TAG_ID.BASEFONT],\n [TAG_NAMES.BGSOUND, TAG_ID.BGSOUND],\n [TAG_NAMES.BIG, TAG_ID.BIG],\n [TAG_NAMES.BLOCKQUOTE, TAG_ID.BLOCKQUOTE],\n [TAG_NAMES.BODY, TAG_ID.BODY],\n [TAG_NAMES.BR, TAG_ID.BR],\n [TAG_NAMES.BUTTON, TAG_ID.BUTTON],\n [TAG_NAMES.CAPTION, TAG_ID.CAPTION],\n [TAG_NAMES.CENTER, TAG_ID.CENTER],\n [TAG_NAMES.CODE, TAG_ID.CODE],\n [TAG_NAMES.COL, TAG_ID.COL],\n [TAG_NAMES.COLGROUP, TAG_ID.COLGROUP],\n [TAG_NAMES.DD, TAG_ID.DD],\n [TAG_NAMES.DESC, TAG_ID.DESC],\n [TAG_NAMES.DETAILS, TAG_ID.DETAILS],\n [TAG_NAMES.DIALOG, TAG_ID.DIALOG],\n [TAG_NAMES.DIR, TAG_ID.DIR],\n [TAG_NAMES.DIV, TAG_ID.DIV],\n [TAG_NAMES.DL, TAG_ID.DL],\n [TAG_NAMES.DT, TAG_ID.DT],\n [TAG_NAMES.EM, TAG_ID.EM],\n [TAG_NAMES.EMBED, TAG_ID.EMBED],\n [TAG_NAMES.FIELDSET, TAG_ID.FIELDSET],\n [TAG_NAMES.FIGCAPTION, TAG_ID.FIGCAPTION],\n [TAG_NAMES.FIGURE, TAG_ID.FIGURE],\n [TAG_NAMES.FONT, TAG_ID.FONT],\n [TAG_NAMES.FOOTER, TAG_ID.FOOTER],\n [TAG_NAMES.FOREIGN_OBJECT, TAG_ID.FOREIGN_OBJECT],\n [TAG_NAMES.FORM, TAG_ID.FORM],\n [TAG_NAMES.FRAME, TAG_ID.FRAME],\n [TAG_NAMES.FRAMESET, TAG_ID.FRAMESET],\n [TAG_NAMES.H1, TAG_ID.H1],\n [TAG_NAMES.H2, TAG_ID.H2],\n [TAG_NAMES.H3, TAG_ID.H3],\n [TAG_NAMES.H4, TAG_ID.H4],\n [TAG_NAMES.H5, TAG_ID.H5],\n [TAG_NAMES.H6, TAG_ID.H6],\n [TAG_NAMES.HEAD, TAG_ID.HEAD],\n [TAG_NAMES.HEADER, TAG_ID.HEADER],\n [TAG_NAMES.HGROUP, TAG_ID.HGROUP],\n [TAG_NAMES.HR, TAG_ID.HR],\n [TAG_NAMES.HTML, TAG_ID.HTML],\n [TAG_NAMES.I, TAG_ID.I],\n [TAG_NAMES.IMG, TAG_ID.IMG],\n [TAG_NAMES.IMAGE, TAG_ID.IMAGE],\n [TAG_NAMES.INPUT, TAG_ID.INPUT],\n [TAG_NAMES.IFRAME, TAG_ID.IFRAME],\n [TAG_NAMES.KEYGEN, TAG_ID.KEYGEN],\n [TAG_NAMES.LABEL, TAG_ID.LABEL],\n [TAG_NAMES.LI, TAG_ID.LI],\n [TAG_NAMES.LINK, TAG_ID.LINK],\n [TAG_NAMES.LISTING, TAG_ID.LISTING],\n [TAG_NAMES.MAIN, TAG_ID.MAIN],\n [TAG_NAMES.MALIGNMARK, TAG_ID.MALIGNMARK],\n [TAG_NAMES.MARQUEE, TAG_ID.MARQUEE],\n [TAG_NAMES.MATH, TAG_ID.MATH],\n [TAG_NAMES.MENU, TAG_ID.MENU],\n [TAG_NAMES.META, TAG_ID.META],\n [TAG_NAMES.MGLYPH, TAG_ID.MGLYPH],\n [TAG_NAMES.MI, TAG_ID.MI],\n [TAG_NAMES.MO, TAG_ID.MO],\n [TAG_NAMES.MN, TAG_ID.MN],\n [TAG_NAMES.MS, TAG_ID.MS],\n [TAG_NAMES.MTEXT, TAG_ID.MTEXT],\n [TAG_NAMES.NAV, TAG_ID.NAV],\n [TAG_NAMES.NOBR, TAG_ID.NOBR],\n [TAG_NAMES.NOFRAMES, TAG_ID.NOFRAMES],\n [TAG_NAMES.NOEMBED, TAG_ID.NOEMBED],\n [TAG_NAMES.NOSCRIPT, TAG_ID.NOSCRIPT],\n [TAG_NAMES.OBJECT, TAG_ID.OBJECT],\n [TAG_NAMES.OL, TAG_ID.OL],\n [TAG_NAMES.OPTGROUP, TAG_ID.OPTGROUP],\n [TAG_NAMES.OPTION, TAG_ID.OPTION],\n [TAG_NAMES.P, TAG_ID.P],\n [TAG_NAMES.PARAM, TAG_ID.PARAM],\n [TAG_NAMES.PLAINTEXT, TAG_ID.PLAINTEXT],\n [TAG_NAMES.PRE, TAG_ID.PRE],\n [TAG_NAMES.RB, TAG_ID.RB],\n [TAG_NAMES.RP, TAG_ID.RP],\n [TAG_NAMES.RT, TAG_ID.RT],\n [TAG_NAMES.RTC, TAG_ID.RTC],\n [TAG_NAMES.RUBY, TAG_ID.RUBY],\n [TAG_NAMES.S, TAG_ID.S],\n [TAG_NAMES.SCRIPT, TAG_ID.SCRIPT],\n [TAG_NAMES.SEARCH, TAG_ID.SEARCH],\n [TAG_NAMES.SECTION, TAG_ID.SECTION],\n [TAG_NAMES.SELECT, TAG_ID.SELECT],\n [TAG_NAMES.SOURCE, TAG_ID.SOURCE],\n [TAG_NAMES.SMALL, TAG_ID.SMALL],\n [TAG_NAMES.SPAN, TAG_ID.SPAN],\n [TAG_NAMES.STRIKE, TAG_ID.STRIKE],\n [TAG_NAMES.STRONG, TAG_ID.STRONG],\n [TAG_NAMES.STYLE, TAG_ID.STYLE],\n [TAG_NAMES.SUB, TAG_ID.SUB],\n [TAG_NAMES.SUMMARY, TAG_ID.SUMMARY],\n [TAG_NAMES.SUP, TAG_ID.SUP],\n [TAG_NAMES.TABLE, TAG_ID.TABLE],\n [TAG_NAMES.TBODY, TAG_ID.TBODY],\n [TAG_NAMES.TEMPLATE, TAG_ID.TEMPLATE],\n [TAG_NAMES.TEXTAREA, TAG_ID.TEXTAREA],\n [TAG_NAMES.TFOOT, TAG_ID.TFOOT],\n [TAG_NAMES.TD, TAG_ID.TD],\n [TAG_NAMES.TH, TAG_ID.TH],\n [TAG_NAMES.THEAD, TAG_ID.THEAD],\n [TAG_NAMES.TITLE, TAG_ID.TITLE],\n [TAG_NAMES.TR, TAG_ID.TR],\n [TAG_NAMES.TRACK, TAG_ID.TRACK],\n [TAG_NAMES.TT, TAG_ID.TT],\n [TAG_NAMES.U, TAG_ID.U],\n [TAG_NAMES.UL, TAG_ID.UL],\n [TAG_NAMES.SVG, TAG_ID.SVG],\n [TAG_NAMES.VAR, TAG_ID.VAR],\n [TAG_NAMES.WBR, TAG_ID.WBR],\n [TAG_NAMES.XMP, TAG_ID.XMP]\n ]);\n var $ = TAG_ID;\n var SPECIAL_ELEMENTS = {\n [NS.HTML]: /* @__PURE__ */ new Set([\n $.ADDRESS,\n $.APPLET,\n $.AREA,\n $.ARTICLE,\n $.ASIDE,\n $.BASE,\n $.BASEFONT,\n $.BGSOUND,\n $.BLOCKQUOTE,\n $.BODY,\n $.BR,\n $.BUTTON,\n $.CAPTION,\n $.CENTER,\n $.COL,\n $.COLGROUP,\n $.DD,\n $.DETAILS,\n $.DIR,\n $.DIV,\n $.DL,\n $.DT,\n $.EMBED,\n $.FIELDSET,\n $.FIGCAPTION,\n $.FIGURE,\n $.FOOTER,\n $.FORM,\n $.FRAME,\n $.FRAMESET,\n $.H1,\n $.H2,\n $.H3,\n $.H4,\n $.H5,\n $.H6,\n $.HEAD,\n $.HEADER,\n $.HGROUP,\n $.HR,\n $.HTML,\n $.IFRAME,\n $.IMG,\n $.INPUT,\n $.LI,\n $.LINK,\n $.LISTING,\n $.MAIN,\n $.MARQUEE,\n $.MENU,\n $.META,\n $.NAV,\n $.NOEMBED,\n $.NOFRAMES,\n $.NOSCRIPT,\n $.OBJECT,\n $.OL,\n $.P,\n $.PARAM,\n $.PLAINTEXT,\n $.PRE,\n $.SCRIPT,\n $.SECTION,\n $.SELECT,\n $.SOURCE,\n $.STYLE,\n $.SUMMARY,\n $.TABLE,\n $.TBODY,\n $.TD,\n $.TEMPLATE,\n $.TEXTAREA,\n $.TFOOT,\n $.TH,\n $.THEAD,\n $.TITLE,\n $.TR,\n $.TRACK,\n $.UL,\n $.WBR,\n $.XMP\n ]),\n [NS.MATHML]: /* @__PURE__ */ new Set([$.MI, $.MO, $.MN, $.MS, $.MTEXT, $.ANNOTATION_XML]),\n [NS.SVG]: /* @__PURE__ */ new Set([$.TITLE, $.FOREIGN_OBJECT, $.DESC]),\n [NS.XLINK]: /* @__PURE__ */ new Set(),\n [NS.XML]: /* @__PURE__ */ new Set(),\n [NS.XMLNS]: /* @__PURE__ */ new Set()\n };\n var NUMBERED_HEADERS = /* @__PURE__ */ new Set([$.H1, $.H2, $.H3, $.H4, $.H5, $.H6]);\n var UNESCAPED_TEXT = /* @__PURE__ */ new Set([\n TAG_NAMES.STYLE,\n TAG_NAMES.SCRIPT,\n TAG_NAMES.XMP,\n TAG_NAMES.IFRAME,\n TAG_NAMES.NOEMBED,\n TAG_NAMES.NOFRAMES,\n TAG_NAMES.PLAINTEXT\n ]);\n\n // ../../node_modules/.pnpm/parse5@8.0.1/node_modules/parse5/dist/tokenizer/index.js\n var State;\n (function(State2) {\n State2[State2["DATA"] = 0] = "DATA";\n State2[State2["RCDATA"] = 1] = "RCDATA";\n State2[State2["RAWTEXT"] = 2] = "RAWTEXT";\n State2[State2["SCRIPT_DATA"] = 3] = "SCRIPT_DATA";\n State2[State2["PLAINTEXT"] = 4] = "PLAINTEXT";\n State2[State2["TAG_OPEN"] = 5] = "TAG_OPEN";\n State2[State2["END_TAG_OPEN"] = 6] = "END_TAG_OPEN";\n State2[State2["TAG_NAME"] = 7] = "TAG_NAME";\n State2[State2["RCDATA_LESS_THAN_SIGN"] = 8] = "RCDATA_LESS_THAN_SIGN";\n State2[State2["RCDATA_END_TAG_OPEN"] = 9] = "RCDATA_END_TAG_OPEN";\n State2[State2["RCDATA_END_TAG_NAME"] = 10] = "RCDATA_END_TAG_NAME";\n State2[State2["RAWTEXT_LESS_THAN_SIGN"] = 11] = "RAWTEXT_LESS_THAN_SIGN";\n State2[State2["RAWTEXT_END_TAG_OPEN"] = 12] = "RAWTEXT_END_TAG_OPEN";\n State2[State2["RAWTEXT_END_TAG_NAME"] = 13] = "RAWTEXT_END_TAG_NAME";\n State2[State2["SCRIPT_DATA_LESS_THAN_SIGN"] = 14] = "SCRIPT_DATA_LESS_THAN_SIGN";\n State2[State2["SCRIPT_DATA_END_TAG_OPEN"] = 15] = "SCRIPT_DATA_END_TAG_OPEN";\n State2[State2["SCRIPT_DATA_END_TAG_NAME"] = 16] = "SCRIPT_DATA_END_TAG_NAME";\n State2[State2["SCRIPT_DATA_ESCAPE_START"] = 17] = "SCRIPT_DATA_ESCAPE_START";\n State2[State2["SCRIPT_DATA_ESCAPE_START_DASH"] = 18] = "SCRIPT_DATA_ESCAPE_START_DASH";\n State2[State2["SCRIPT_DATA_ESCAPED"] = 19] = "SCRIPT_DATA_ESCAPED";\n State2[State2["SCRIPT_DATA_ESCAPED_DASH"] = 20] = "SCRIPT_DATA_ESCAPED_DASH";\n State2[State2["SCRIPT_DATA_ESCAPED_DASH_DASH"] = 21] = "SCRIPT_DATA_ESCAPED_DASH_DASH";\n State2[State2["SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN"] = 22] = "SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN";\n State2[State2["SCRIPT_DATA_ESCAPED_END_TAG_OPEN"] = 23] = "SCRIPT_DATA_ESCAPED_END_TAG_OPEN";\n State2[State2["SCRIPT_DATA_ESCAPED_END_TAG_NAME"] = 24] = "SCRIPT_DATA_ESCAPED_END_TAG_NAME";\n State2[State2["SCRIPT_DATA_DOUBLE_ESCAPE_START"] = 25] = "SCRIPT_DATA_DOUBLE_ESCAPE_START";\n State2[State2["SCRIPT_DATA_DOUBLE_ESCAPED"] = 26] = "SCRIPT_DATA_DOUBLE_ESCAPED";\n State2[State2["SCRIPT_DATA_DOUBLE_ESCAPED_DASH"] = 27] = "SCRIPT_DATA_DOUBLE_ESCAPED_DASH";\n State2[State2["SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH"] = 28] = "SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH";\n State2[State2["SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN"] = 29] = "SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN";\n State2[State2["SCRIPT_DATA_DOUBLE_ESCAPE_END"] = 30] = "SCRIPT_DATA_DOUBLE_ESCAPE_END";\n State2[State2["BEFORE_ATTRIBUTE_NAME"] = 31] = "BEFORE_ATTRIBUTE_NAME";\n State2[State2["ATTRIBUTE_NAME"] = 32] = "ATTRIBUTE_NAME";\n State2[State2["AFTER_ATTRIBUTE_NAME"] = 33] = "AFTER_ATTRIBUTE_NAME";\n State2[State2["BEFORE_ATTRIBUTE_VALUE"] = 34] = "BEFORE_ATTRIBUTE_VALUE";\n State2[State2["ATTRIBUTE_VALUE_DOUBLE_QUOTED"] = 35] = "ATTRIBUTE_VALUE_DOUBLE_QUOTED";\n State2[State2["ATTRIBUTE_VALUE_SINGLE_QUOTED"] = 36] = "ATTRIBUTE_VALUE_SINGLE_QUOTED";\n State2[State2["ATTRIBUTE_VALUE_UNQUOTED"] = 37] = "ATTRIBUTE_VALUE_UNQUOTED";\n State2[State2["AFTER_ATTRIBUTE_VALUE_QUOTED"] = 38] = "AFTER_ATTRIBUTE_VALUE_QUOTED";\n State2[State2["SELF_CLOSING_START_TAG"] = 39] = "SELF_CLOSING_START_TAG";\n State2[State2["BOGUS_COMMENT"] = 40] = "BOGUS_COMMENT";\n State2[State2["MARKUP_DECLARATION_OPEN"] = 41] = "MARKUP_DECLARATION_OPEN";\n State2[State2["COMMENT_START"] = 42] = "COMMENT_START";\n State2[State2["COMMENT_START_DASH"] = 43] = "COMMENT_START_DASH";\n State2[State2["COMMENT"] = 44] = "COMMENT";\n State2[State2["COMMENT_LESS_THAN_SIGN"] = 45] = "COMMENT_LESS_THAN_SIGN";\n State2[State2["COMMENT_LESS_THAN_SIGN_BANG"] = 46] = "COMMENT_LESS_THAN_SIGN_BANG";\n State2[State2["COMMENT_LESS_THAN_SIGN_BANG_DASH"] = 47] = "COMMENT_LESS_THAN_SIGN_BANG_DASH";\n State2[State2["COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH"] = 48] = "COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH";\n State2[State2["COMMENT_END_DASH"] = 49] = "COMMENT_END_DASH";\n State2[State2["COMMENT_END"] = 50] = "COMMENT_END";\n State2[State2["COMMENT_END_BANG"] = 51] = "COMMENT_END_BANG";\n State2[State2["DOCTYPE"] = 52] = "DOCTYPE";\n State2[State2["BEFORE_DOCTYPE_NAME"] = 53] = "BEFORE_DOCTYPE_NAME";\n State2[State2["DOCTYPE_NAME"] = 54] = "DOCTYPE_NAME";\n State2[State2["AFTER_DOCTYPE_NAME"] = 55] = "AFTER_DOCTYPE_NAME";\n State2[State2["AFTER_DOCTYPE_PUBLIC_KEYWORD"] = 56] = "AFTER_DOCTYPE_PUBLIC_KEYWORD";\n State2[State2["BEFORE_DOCTYPE_PUBLIC_IDENTIFIER"] = 57] = "BEFORE_DOCTYPE_PUBLIC_IDENTIFIER";\n State2[State2["DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED"] = 58] = "DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED";\n State2[State2["DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED"] = 59] = "DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED";\n State2[State2["AFTER_DOCTYPE_PUBLIC_IDENTIFIER"] = 60] = "AFTER_DOCTYPE_PUBLIC_IDENTIFIER";\n State2[State2["BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS"] = 61] = "BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS";\n State2[State2["AFTER_DOCTYPE_SYSTEM_KEYWORD"] = 62] = "AFTER_DOCTYPE_SYSTEM_KEYWORD";\n State2[State2["BEFORE_DOCTYPE_SYSTEM_IDENTIFIER"] = 63] = "BEFORE_DOCTYPE_SYSTEM_IDENTIFIER";\n State2[State2["DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED"] = 64] = "DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED";\n State2[State2["DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED"] = 65] = "DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED";\n State2[State2["AFTER_DOCTYPE_SYSTEM_IDENTIFIER"] = 66] = "AFTER_DOCTYPE_SYSTEM_IDENTIFIER";\n State2[State2["BOGUS_DOCTYPE"] = 67] = "BOGUS_DOCTYPE";\n State2[State2["CDATA_SECTION"] = 68] = "CDATA_SECTION";\n State2[State2["CDATA_SECTION_BRACKET"] = 69] = "CDATA_SECTION_BRACKET";\n State2[State2["CDATA_SECTION_END"] = 70] = "CDATA_SECTION_END";\n State2[State2["CHARACTER_REFERENCE"] = 71] = "CHARACTER_REFERENCE";\n State2[State2["AMBIGUOUS_AMPERSAND"] = 72] = "AMBIGUOUS_AMPERSAND";\n })(State || (State = {}));\n var TokenizerMode = {\n DATA: State.DATA,\n RCDATA: State.RCDATA,\n RAWTEXT: State.RAWTEXT,\n SCRIPT_DATA: State.SCRIPT_DATA,\n PLAINTEXT: State.PLAINTEXT,\n CDATA_SECTION: State.CDATA_SECTION\n };\n\n // ../../node_modules/.pnpm/parse5@8.0.1/node_modules/parse5/dist/parser/open-element-stack.js\n var IMPLICIT_END_TAG_REQUIRED = /* @__PURE__ */ new Set([TAG_ID.DD, TAG_ID.DT, TAG_ID.LI, TAG_ID.OPTGROUP, TAG_ID.OPTION, TAG_ID.P, TAG_ID.RB, TAG_ID.RP, TAG_ID.RT, TAG_ID.RTC]);\n var IMPLICIT_END_TAG_REQUIRED_THOROUGHLY = /* @__PURE__ */ new Set([\n ...IMPLICIT_END_TAG_REQUIRED,\n TAG_ID.CAPTION,\n TAG_ID.COLGROUP,\n TAG_ID.TBODY,\n TAG_ID.TD,\n TAG_ID.TFOOT,\n TAG_ID.TH,\n TAG_ID.THEAD,\n TAG_ID.TR\n ]);\n var SCOPING_ELEMENTS_HTML = /* @__PURE__ */ new Set([\n TAG_ID.APPLET,\n TAG_ID.CAPTION,\n TAG_ID.HTML,\n TAG_ID.MARQUEE,\n TAG_ID.OBJECT,\n TAG_ID.TABLE,\n TAG_ID.TD,\n TAG_ID.TEMPLATE,\n TAG_ID.TH\n ]);\n var SCOPING_ELEMENTS_HTML_LIST = /* @__PURE__ */ new Set([...SCOPING_ELEMENTS_HTML, TAG_ID.OL, TAG_ID.UL]);\n var SCOPING_ELEMENTS_HTML_BUTTON = /* @__PURE__ */ new Set([...SCOPING_ELEMENTS_HTML, TAG_ID.BUTTON]);\n var SCOPING_ELEMENTS_MATHML = /* @__PURE__ */ new Set([TAG_ID.ANNOTATION_XML, TAG_ID.MI, TAG_ID.MN, TAG_ID.MO, TAG_ID.MS, TAG_ID.MTEXT]);\n var SCOPING_ELEMENTS_SVG = /* @__PURE__ */ new Set([TAG_ID.DESC, TAG_ID.FOREIGN_OBJECT, TAG_ID.TITLE]);\n var TABLE_ROW_CONTEXT = /* @__PURE__ */ new Set([TAG_ID.TR, TAG_ID.TEMPLATE, TAG_ID.HTML]);\n var TABLE_BODY_CONTEXT = /* @__PURE__ */ new Set([TAG_ID.TBODY, TAG_ID.TFOOT, TAG_ID.THEAD, TAG_ID.TEMPLATE, TAG_ID.HTML]);\n var TABLE_CONTEXT = /* @__PURE__ */ new Set([TAG_ID.TABLE, TAG_ID.TEMPLATE, TAG_ID.HTML]);\n var TABLE_CELLS = /* @__PURE__ */ new Set([TAG_ID.TD, TAG_ID.TH]);\n\n // ../../node_modules/.pnpm/parse5@8.0.1/node_modules/parse5/dist/parser/formatting-element-list.js\n var EntryType;\n (function(EntryType2) {\n EntryType2[EntryType2["Marker"] = 0] = "Marker";\n EntryType2[EntryType2["Element"] = 1] = "Element";\n })(EntryType || (EntryType = {}));\n var MARKER = { type: EntryType.Marker };\n\n // ../../node_modules/.pnpm/parse5@8.0.1/node_modules/parse5/dist/common/doctype.js\n var QUIRKS_MODE_PUBLIC_ID_PREFIXES = [\n "+//silmaril//dtd html pro v0r11 19970101//",\n "-//as//dtd html 3.0 aswedit + extensions//",\n "-//advasoft ltd//dtd html 3.0 aswedit + extensions//",\n "-//ietf//dtd html 2.0 level 1//",\n "-//ietf//dtd html 2.0 level 2//",\n "-//ietf//dtd html 2.0 strict level 1//",\n "-//ietf//dtd html 2.0 strict level 2//",\n "-//ietf//dtd html 2.0 strict//",\n "-//ietf//dtd html 2.0//",\n "-//ietf//dtd html 2.1e//",\n "-//ietf//dtd html 3.0//",\n "-//ietf//dtd html 3.2 final//",\n "-//ietf//dtd html 3.2//",\n "-//ietf//dtd html 3//",\n "-//ietf//dtd html level 0//",\n "-//ietf//dtd html level 1//",\n "-//ietf//dtd html level 2//",\n "-//ietf//dtd html level 3//",\n "-//ietf//dtd html strict level 0//",\n "-//ietf//dtd html strict level 1//",\n "-//ietf//dtd html strict level 2//",\n "-//ietf//dtd html strict level 3//",\n "-//ietf//dtd html strict//",\n "-//ietf//dtd html//",\n "-//metrius//dtd metrius presentational//",\n "-//microsoft//dtd internet explorer 2.0 html strict//",\n "-//microsoft//dtd internet explorer 2.0 html//",\n "-//microsoft//dtd internet explorer 2.0 tables//",\n "-//microsoft//dtd internet explorer 3.0 html strict//",\n "-//microsoft//dtd internet explorer 3.0 html//",\n "-//microsoft//dtd internet explorer 3.0 tables//",\n "-//netscape comm. corp.//dtd html//",\n "-//netscape comm. corp.//dtd strict html//",\n "-//o\'reilly and associates//dtd html 2.0//",\n "-//o\'reilly and associates//dtd html extended 1.0//",\n "-//o\'reilly and associates//dtd html extended relaxed 1.0//",\n "-//sq//dtd html 2.0 hotmetal + extensions//",\n "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//",\n "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//",\n "-//spyglass//dtd html 2.0 extended//",\n "-//sun microsystems corp.//dtd hotjava html//",\n "-//sun microsystems corp.//dtd hotjava strict html//",\n "-//w3c//dtd html 3 1995-03-24//",\n "-//w3c//dtd html 3.2 draft//",\n "-//w3c//dtd html 3.2 final//",\n "-//w3c//dtd html 3.2//",\n "-//w3c//dtd html 3.2s draft//",\n "-//w3c//dtd html 4.0 frameset//",\n "-//w3c//dtd html 4.0 transitional//",\n "-//w3c//dtd html experimental 19960712//",\n "-//w3c//dtd html experimental 970421//",\n "-//w3c//dtd w3 html//",\n "-//w3o//dtd w3 html 3.0//",\n "-//webtechs//dtd mozilla html 2.0//",\n "-//webtechs//dtd mozilla html//"\n ];\n var QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = [\n ...QUIRKS_MODE_PUBLIC_ID_PREFIXES,\n "-//w3c//dtd html 4.01 frameset//",\n "-//w3c//dtd html 4.01 transitional//"\n ];\n var LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = ["-//w3c//dtd xhtml 1.0 frameset//", "-//w3c//dtd xhtml 1.0 transitional//"];\n var LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = [\n ...LIMITED_QUIRKS_PUBLIC_ID_PREFIXES,\n "-//w3c//dtd html 4.01 frameset//",\n "-//w3c//dtd html 4.01 transitional//"\n ];\n\n // ../../node_modules/.pnpm/parse5@8.0.1/node_modules/parse5/dist/common/foreign-content.js\n var SVG_ATTRS_ADJUSTMENT_MAP = new Map([\n "attributeName",\n "attributeType",\n "baseFrequency",\n "baseProfile",\n "calcMode",\n "clipPathUnits",\n "diffuseConstant",\n "edgeMode",\n "filterUnits",\n "glyphRef",\n "gradientTransform",\n "gradientUnits",\n "kernelMatrix",\n "kernelUnitLength",\n "keyPoints",\n "keySplines",\n "keyTimes",\n "lengthAdjust",\n "limitingConeAngle",\n "markerHeight",\n "markerUnits",\n "markerWidth",\n "maskContentUnits",\n "maskUnits",\n "numOctaves",\n "pathLength",\n "patternContentUnits",\n "patternTransform",\n "patternUnits",\n "pointsAtX",\n "pointsAtY",\n "pointsAtZ",\n "preserveAlpha",\n "preserveAspectRatio",\n "primitiveUnits",\n "refX",\n "refY",\n "repeatCount",\n "repeatDur",\n "requiredExtensions",\n "requiredFeatures",\n "specularConstant",\n "specularExponent",\n "spreadMethod",\n "startOffset",\n "stdDeviation",\n "stitchTiles",\n "surfaceScale",\n "systemLanguage",\n "tableValues",\n "targetX",\n "targetY",\n "textLength",\n "viewBox",\n "viewTarget",\n "xChannelSelector",\n "yChannelSelector",\n "zoomAndPan"\n ].map((attr) => [attr.toLowerCase(), attr]));\n var XML_ATTRS_ADJUSTMENT_MAP = /* @__PURE__ */ new Map([\n ["xlink:actuate", { prefix: "xlink", name: "actuate", namespace: NS.XLINK }],\n ["xlink:arcrole", { prefix: "xlink", name: "arcrole", namespace: NS.XLINK }],\n ["xlink:href", { prefix: "xlink", name: "href", namespace: NS.XLINK }],\n ["xlink:role", { prefix: "xlink", name: "role", namespace: NS.XLINK }],\n ["xlink:show", { prefix: "xlink", name: "show", namespace: NS.XLINK }],\n ["xlink:title", { prefix: "xlink", name: "title", namespace: NS.XLINK }],\n ["xlink:type", { prefix: "xlink", name: "type", namespace: NS.XLINK }],\n ["xml:lang", { prefix: "xml", name: "lang", namespace: NS.XML }],\n ["xml:space", { prefix: "xml", name: "space", namespace: NS.XML }],\n ["xmlns", { prefix: "", name: "xmlns", namespace: NS.XMLNS }],\n ["xmlns:xlink", { prefix: "xmlns", name: "xlink", namespace: NS.XMLNS }]\n ]);\n var SVG_TAG_NAMES_ADJUSTMENT_MAP = new Map([\n "altGlyph",\n "altGlyphDef",\n "altGlyphItem",\n "animateColor",\n "animateMotion",\n "animateTransform",\n "clipPath",\n "feBlend",\n "feColorMatrix",\n "feComponentTransfer",\n "feComposite",\n "feConvolveMatrix",\n "feDiffuseLighting",\n "feDisplacementMap",\n "feDistantLight",\n "feFlood",\n "feFuncA",\n "feFuncB",\n "feFuncG",\n "feFuncR",\n "feGaussianBlur",\n "feImage",\n "feMerge",\n "feMergeNode",\n "feMorphology",\n "feOffset",\n "fePointLight",\n "feSpecularLighting",\n "feSpotLight",\n "feTile",\n "feTurbulence",\n "foreignObject",\n "glyphRef",\n "linearGradient",\n "radialGradient",\n "textPath"\n ].map((tn) => [tn.toLowerCase(), tn]));\n var EXITS_FOREIGN_CONTENT = /* @__PURE__ */ new Set([\n TAG_ID.B,\n TAG_ID.BIG,\n TAG_ID.BLOCKQUOTE,\n TAG_ID.BODY,\n TAG_ID.BR,\n TAG_ID.CENTER,\n TAG_ID.CODE,\n TAG_ID.DD,\n TAG_ID.DIV,\n TAG_ID.DL,\n TAG_ID.DT,\n TAG_ID.EM,\n TAG_ID.EMBED,\n TAG_ID.H1,\n TAG_ID.H2,\n TAG_ID.H3,\n TAG_ID.H4,\n TAG_ID.H5,\n TAG_ID.H6,\n TAG_ID.HEAD,\n TAG_ID.HR,\n TAG_ID.I,\n TAG_ID.IMG,\n TAG_ID.LI,\n TAG_ID.LISTING,\n TAG_ID.MENU,\n TAG_ID.META,\n TAG_ID.NOBR,\n TAG_ID.OL,\n TAG_ID.P,\n TAG_ID.PRE,\n TAG_ID.RUBY,\n TAG_ID.S,\n TAG_ID.SMALL,\n TAG_ID.SPAN,\n TAG_ID.STRONG,\n TAG_ID.STRIKE,\n TAG_ID.SUB,\n TAG_ID.SUP,\n TAG_ID.TABLE,\n TAG_ID.TT,\n TAG_ID.U,\n TAG_ID.UL,\n TAG_ID.VAR\n ]);\n\n // ../../node_modules/.pnpm/parse5@8.0.1/node_modules/parse5/dist/parser/index.js\n var InsertionMode;\n (function(InsertionMode2) {\n InsertionMode2[InsertionMode2["INITIAL"] = 0] = "INITIAL";\n InsertionMode2[InsertionMode2["BEFORE_HTML"] = 1] = "BEFORE_HTML";\n InsertionMode2[InsertionMode2["BEFORE_HEAD"] = 2] = "BEFORE_HEAD";\n InsertionMode2[InsertionMode2["IN_HEAD"] = 3] = "IN_HEAD";\n InsertionMode2[InsertionMode2["IN_HEAD_NO_SCRIPT"] = 4] = "IN_HEAD_NO_SCRIPT";\n InsertionMode2[InsertionMode2["AFTER_HEAD"] = 5] = "AFTER_HEAD";\n InsertionMode2[InsertionMode2["IN_BODY"] = 6] = "IN_BODY";\n InsertionMode2[InsertionMode2["TEXT"] = 7] = "TEXT";\n InsertionMode2[InsertionMode2["IN_TABLE"] = 8] = "IN_TABLE";\n InsertionMode2[InsertionMode2["IN_TABLE_TEXT"] = 9] = "IN_TABLE_TEXT";\n InsertionMode2[InsertionMode2["IN_CAPTION"] = 10] = "IN_CAPTION";\n InsertionMode2[InsertionMode2["IN_COLUMN_GROUP"] = 11] = "IN_COLUMN_GROUP";\n InsertionMode2[InsertionMode2["IN_TABLE_BODY"] = 12] = "IN_TABLE_BODY";\n InsertionMode2[InsertionMode2["IN_ROW"] = 13] = "IN_ROW";\n InsertionMode2[InsertionMode2["IN_CELL"] = 14] = "IN_CELL";\n InsertionMode2[InsertionMode2["IN_SELECT"] = 15] = "IN_SELECT";\n InsertionMode2[InsertionMode2["IN_SELECT_IN_TABLE"] = 16] = "IN_SELECT_IN_TABLE";\n InsertionMode2[InsertionMode2["IN_TEMPLATE"] = 17] = "IN_TEMPLATE";\n InsertionMode2[InsertionMode2["AFTER_BODY"] = 18] = "AFTER_BODY";\n InsertionMode2[InsertionMode2["IN_FRAMESET"] = 19] = "IN_FRAMESET";\n InsertionMode2[InsertionMode2["AFTER_FRAMESET"] = 20] = "AFTER_FRAMESET";\n InsertionMode2[InsertionMode2["AFTER_AFTER_BODY"] = 21] = "AFTER_AFTER_BODY";\n InsertionMode2[InsertionMode2["AFTER_AFTER_FRAMESET"] = 22] = "AFTER_AFTER_FRAMESET";\n })(InsertionMode || (InsertionMode = {}));\n var TABLE_STRUCTURE_TAGS = /* @__PURE__ */ new Set([TAG_ID.TABLE, TAG_ID.TBODY, TAG_ID.TFOOT, TAG_ID.THEAD, TAG_ID.TR]);\n var TABLE_VOID_ELEMENTS = /* @__PURE__ */ new Set([TAG_ID.CAPTION, TAG_ID.COL, TAG_ID.COLGROUP, TAG_ID.TBODY, TAG_ID.TD, TAG_ID.TFOOT, TAG_ID.TH, TAG_ID.THEAD, TAG_ID.TR]);\n\n // ../../node_modules/.pnpm/parse5@8.0.1/node_modules/parse5/dist/serializer/index.js\n var VOID_ELEMENTS = /* @__PURE__ */ new Set([\n TAG_NAMES.AREA,\n TAG_NAMES.BASE,\n TAG_NAMES.BASEFONT,\n TAG_NAMES.BGSOUND,\n TAG_NAMES.BR,\n TAG_NAMES.COL,\n TAG_NAMES.EMBED,\n TAG_NAMES.FRAME,\n TAG_NAMES.HR,\n TAG_NAMES.IMG,\n TAG_NAMES.INPUT,\n TAG_NAMES.KEYGEN,\n TAG_NAMES.LINK,\n TAG_NAMES.META,\n TAG_NAMES.PARAM,\n TAG_NAMES.SOURCE,\n TAG_NAMES.TRACK,\n TAG_NAMES.WBR\n ]);\n\n // shared/native-linear-resource-graph.ts\n var RESOURCE_NAME = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;\n var TEXTURE_FORMATS = /* @__PURE__ */ new Set(["rgba8unorm", "rgba16float"]);\n function isLinearResourceDispatch(value) {\n if (!value || typeof value !== "object") return false;\n const dispatch = value;\n const size = dispatch.workgroupSize;\n if (Object.keys(dispatch).length !== 2 || !Array.isArray(size) || size.length !== 3 || size.some((value2) => !Number.isSafeInteger(value2) || value2 < 1) || size[2] !== 1 || size[0] * size[1] > 256)\n return false;\n return dispatch.elements === "output-texture" && size[0] <= 256 && size[1] <= 256 || dispatch.elements === "output-buffer" && size[1] === 1 && size[0] <= 256;\n }\n function withoutWgslCommentsAndStrings(source) {\n let output = "";\n let blockDepth = 0;\n let line = false;\n let quote = null;\n for (let index = 0; index < source.length; index += 1) {\n const character = source[index];\n const next = source[index + 1];\n if (line) {\n if (character === "\\n") {\n line = false;\n output += "\\n";\n } else output += " ";\n continue;\n }\n if (blockDepth) {\n if (character === "/" && next === "*") {\n blockDepth += 1;\n output += " ";\n index += 1;\n } else if (character === "*" && next === "/") {\n blockDepth -= 1;\n output += " ";\n index += 1;\n } else output += character === "\\n" ? "\\n" : " ";\n continue;\n }\n if (quote) {\n if (character === "\\\\") {\n output += " ";\n index += 1;\n } else if (character === quote) {\n quote = null;\n output += " ";\n } else output += character === "\\n" ? "\\n" : " ";\n continue;\n }\n if (character === "/" && next === "/") {\n line = true;\n output += " ";\n index += 1;\n } else if (character === "/" && next === "*") {\n blockDepth = 1;\n output += " ";\n index += 1;\n } else if (character === \'"\' || character === "\'") {\n quote = character;\n output += " ";\n } else output += character;\n }\n return blockDepth || quote ? null : output;\n }\n function linearResourceWorkgroupSize(wgsl) {\n const source = withoutWgslCommentsAndStrings(wgsl);\n if (!source) return null;\n const entry = /@compute\\s+@workgroup_size\\s*\\(\\s*(\\d+)u?\\s*,\\s*(\\d+)u?\\s*,\\s*(\\d+)u?\\s*\\)\\s*fn\\s+cs\\s*\\(/g;\n const matches = [...source.matchAll(entry)];\n if (matches.length !== 1 || [...source.matchAll(/\\bfn\\s+cs\\s*\\(/g)].length !== 1 || [...source.matchAll(/@compute\\b/g)].length !== 1)\n return null;\n const values = matches[0].slice(1, 4).map(Number);\n return values.every(Number.isSafeInteger) ? values : null;\n }\n function validateLinearResourceGraph(spec, passes, resources, output) {\n const errors = [];\n if (!spec || spec.abi !== "linear-resource-v1" || Object.keys(spec).length !== 1 || !output || !RESOURCE_NAME.test(output))\n return ["linear resource graph needs an explicit final texture output"];\n const producers = new Map(passes.map((pass) => [pass.output, pass]));\n const final = resources.get(output);\n if (final?.kind !== "texture-2d" || final.external === true || !final.usage?.includes("sampled") || !producers.has(output))\n errors.push(\n "linear resource graph final output must be a produced sampled texture"\n );\n for (const resource of resources.values()) {\n if (resource.usage?.some(\n (usage) => usage === "copy-src" || usage === "copy-dst"\n ))\n errors.push(\n `linear resource ${resource.name} declares unsupported copy usage`\n );\n if (resource.persistent || resource.preprocess || resource.mipmap || resource.size === "source")\n errors.push(\n `linear resource ${resource.name} has an unsupported lifetime or preprocessing mode`\n );\n if (resource.external) {\n if (resource.kind !== "texture-2d" || resource.usage?.length !== 1 || resource.usage[0] !== "sampled")\n errors.push(\n `linear external resource ${resource.name} must be a sampled texture`\n );\n continue;\n }\n if (resource.kind === "buffer") {\n if (resource.size !== "fixed" || !Number.isSafeInteger(resource.byteLength) || !resource.byteLength || resource.byteLength % 16 !== 0 || resource.byteLength > 16777216 || resource.format !== void 0 || resource.usage?.length !== 1 || resource.usage[0] !== "storage")\n errors.push(\n `linear buffer ${resource.name} needs bounded 16-byte storage cells`\n );\n } else if (!TEXTURE_FORMATS.has(resource.format ?? "") || resource.size !== "viewport" && resource.size !== "fixed" || !resource.usage?.includes("sampled"))\n errors.push(\n `linear texture ${resource.name} needs a supported sampled format and size`\n );\n }\n for (const pass of passes) {\n const resource = resources.get(pass.output);\n if (pass.additionalOutputs !== void 0 || pass.previousFrameReads !== void 0 || pass.persistent !== void 0 || pass.draw !== void 0 || pass.original !== void 0)\n errors.push(\n `linear pass ${pass.id} uses an unsupported temporal or extra-output mode`\n );\n if (pass.kind === "compute") {\n const dispatch = pass.dispatch;\n if (!isLinearResourceDispatch(dispatch) || dispatch.elements === "output-texture" !== (resource?.kind === "texture-2d") || !resource?.usage?.includes("storage")) {\n errors.push(\n `linear compute pass ${pass.id} needs a matching storage output and dispatch`\n );\n continue;\n }\n const declared = linearResourceWorkgroupSize(pass.wgsl);\n if (!declared || declared.some(\n (dimension, index) => dimension !== dispatch.workgroupSize[index]\n ))\n errors.push(\n `linear compute pass ${pass.id} has mismatched WGSL workgroup metadata`\n );\n } else if (pass.kind !== "render" || pass.dispatch !== void 0 || resource?.kind !== "texture-2d" || !resource.usage?.includes("render"))\n errors.push(\n `linear render pass ${pass.id} needs a render texture output`\n );\n for (const read of pass.reads) {\n const input = resources.get(read);\n if (!input || input.kind === "texture-2d" && !input.usage?.includes("sampled") || input.kind === "buffer" && !input.usage?.includes("storage"))\n errors.push(`linear pass ${pass.id} has an unsupported read ${read}`);\n }\n }\n return errors;\n }\n\n // shared/native-stateful-resource-graph.ts\n var RESOURCE_NAME2 = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;\n var MAX_STATE_BYTES = 16 * 1024 * 1024;\n var MAX_GRAPH_BYTES = 64 * 1024 * 1024;\n function record(value) {\n return value !== null && typeof value === "object" && !Array.isArray(value);\n }\n function isStatefulResourceDraw(value) {\n if (!record(value) || Object.keys(value).length !== 2) return false;\n const instances = value.instances;\n return value.vertices === 6 && record(instances) && Object.keys(instances).length === 2 && typeof instances.property === "string" && RESOURCE_NAME2.test(instances.property) && Number.isSafeInteger(instances.max) && instances.max >= 1 && instances.max <= 4096;\n }\n function validateStatefulResourceGraph(value, passes, resources, output, properties) {\n if (!record(value)) return ["stateful resource graph is malformed"];\n const timing = value.timing;\n const stateResources = value.stateResources;\n const resetProperties = value.resetProperties;\n if (value.abi !== "stateful-resource-v1" && value.abi !== "stateful-resource-v2" && value.abi !== "stateful-resource-v3" || Object.keys(value).some(\n (key) => ![\n "abi",\n "timing",\n "stateResources",\n "sourceHistory",\n "resetProperties"\n ].includes(key)\n ) || !record(timing) || Object.keys(timing).length !== 3 || !Number.isFinite(timing.fixedDt) || timing.fixedDt < 1 / 240 || timing.fixedDt > 1 / 15 || !Number.isSafeInteger(timing.maxStepsPerCall) || timing.maxStepsPerCall < 1 || timing.maxStepsPerCall > 512 || !Number.isSafeInteger(timing.maxStepIndex) || timing.maxStepIndex < 0 || timing.maxStepIndex > 36e3 || !Array.isArray(stateResources) || stateResources.length < 1 || stateResources.length > 8 || !stateResources.every(\n (name) => typeof name === "string" && RESOURCE_NAME2.test(name)\n ) || new Set(stateResources).size !== stateResources.length || value.sourceHistory !== void 0 && value.sourceHistory !== "sequential-captures" || resetProperties !== void 0 && (!Array.isArray(resetProperties) || resetProperties.length > 16 || !resetProperties.every(\n (name) => typeof name === "string" && RESOURCE_NAME2.test(name)\n ) || new Set(resetProperties).size !== resetProperties.length || resetProperties.some((name) => !properties?.[name])))\n return ["stateful resource graph is malformed or unbounded"];\n const errors = [];\n const external = [...resources.values()].filter(\n (resource) => resource.external\n );\n if (value.abi === "stateful-resource-v1") {\n if (external.length !== 1 || external[0]?.name !== "source")\n errors.push("stateful graph needs exactly one external source texture");\n } else if (value.abi === "stateful-resource-v3") {\n if (external.length > 4)\n errors.push("stateful v3 graph has too many external textures");\n if (external.length === 0 && value.sourceHistory !== void 0)\n errors.push("source-free stateful graph cannot capture source history");\n } else if (external.length < 2 || external.length > 4 || !external.some((resource) => resource.name === "source")) {\n errors.push(\n "stateful v2 graph needs source and one to three named external textures"\n );\n }\n if ((value.abi === "stateful-resource-v2" || value.abi === "stateful-resource-v3") && external.some(\n (resource) => !passes.some((pass) => pass.reads.includes(resource.name))\n ))\n errors.push(\n value.abi === "stateful-resource-v2" ? "stateful v2 graph has an unread external texture" : "stateful v3 graph has an unread external texture"\n );\n const state = new Set(stateResources);\n const producerIndex = /* @__PURE__ */ new Map();\n for (const [index, pass] of passes.entries()) {\n producerIndex.set(pass.output, index);\n }\n if (!output || passes[passes.length - 1]?.output !== output || passes[passes.length - 1]?.kind !== "render" || resources.get(output)?.kind !== "texture-2d" || !resources.get(output)?.usage?.includes("sampled"))\n errors.push("stateful graph needs a final produced sampled render texture");\n let retainedBytes = 0;\n let graphBytes = 0;\n for (const resource of resources.values()) {\n if (resource.external) {\n if (resource.kind !== "texture-2d" || resource.usage?.length !== 1 || resource.usage[0] !== "sampled" || resource.persistent)\n errors.push(\n `stateful external resource ${resource.name} must be sampled`\n );\n continue;\n }\n if (resource.preprocess || resource.mipmap || resource.size === "source" || resource.usage?.some(\n (usage) => usage === "copy-src" || usage === "copy-dst"\n ))\n errors.push(`stateful resource ${resource.name} uses unsupported setup`);\n if (Boolean(resource.persistent) !== state.has(resource.name))\n errors.push(`stateful resource ${resource.name} has ambiguous lifetime`);\n let bytes = 0;\n if (resource.kind === "buffer") {\n if (resource.size !== "fixed" || !Number.isSafeInteger(resource.byteLength) || !resource.byteLength || resource.byteLength % 16 !== 0 || resource.byteLength > MAX_STATE_BYTES || resource.format !== void 0 || resource.usage?.length !== 1 || resource.usage[0] !== "storage")\n errors.push(`stateful buffer ${resource.name} must be bounded storage`);\n bytes = resource.byteLength ?? 0;\n } else {\n if (resource.format !== "rgba16float" && resource.format !== "rgba8unorm" || resource.size !== "fixed" && resource.size !== "viewport" || !resource.usage?.includes("sampled") || !resource.usage.some(\n (usage) => usage === "storage" || usage === "render"\n ))\n errors.push(`stateful texture ${resource.name} has invalid usage`);\n if (resource.size === "fixed") {\n const pixels = (resource.width ?? 0) * (resource.height ?? 0);\n if (!Number.isSafeInteger(resource.width) || !Number.isSafeInteger(resource.height) || !resource.width || !resource.height || resource.width > 2048 || resource.height > 2048 || pixels > 2097152)\n errors.push(`stateful texture ${resource.name} exceeds fixed bounds`);\n bytes = pixels * (resource.format === "rgba16float" ? 8 : 4);\n }\n if (state.has(resource.name) && (resource.size !== "fixed" || resource.format !== "rgba16float"))\n errors.push(\n `stateful texture ${resource.name} needs fixed rgba16float state`\n );\n }\n if (state.has(resource.name)) retainedBytes += bytes;\n graphBytes += bytes * (state.has(resource.name) ? 3 : 1);\n }\n if (retainedBytes > MAX_STATE_BYTES || graphBytes > MAX_GRAPH_BYTES)\n errors.push("stateful graph exceeds fixed GPU resource budget");\n for (const name of state) {\n if (!resources.has(name) || !producerIndex.has(name))\n errors.push(`stateful resource ${name} needs one declared producer`);\n if (!passes.some((pass) => pass.previousFrameReads?.includes(name)))\n errors.push(`stateful resource ${name} needs a previous-frame read`);\n }\n for (const [index, pass] of passes.entries()) {\n const written = resources.get(pass.output);\n if (pass.original !== void 0 || pass.additionalOutputs !== void 0 || pass.persistent !== void 0 || pass.reads.length + (pass.previousFrameReads?.length ?? 0) > 16)\n errors.push(\n `stateful pass ${pass.id} uses unsupported outputs or bindings`\n );\n for (const name of pass.reads) {\n const input = resources.get(name);\n const producer = producerIndex.get(name);\n if (!input || producer !== void 0 && producer >= index)\n errors.push(\n `stateful pass ${pass.id} has a missing or forward read ${name}`\n );\n }\n for (const name of pass.previousFrameReads ?? []) {\n if (!state.has(name))\n errors.push(`stateful pass ${pass.id} has undeclared history ${name}`);\n }\n if (pass.kind === "compute") {\n const dispatch = pass.dispatch;\n if (!isLinearResourceDispatch(dispatch) || dispatch.elements === "output-texture" !== (written?.kind === "texture-2d") || !written?.usage?.includes("storage")) {\n errors.push(`stateful compute pass ${pass.id} needs storage dispatch`);\n } else {\n const declared = linearResourceWorkgroupSize(pass.wgsl);\n if (!declared || declared.some(\n (dimension, axis2) => dimension !== dispatch.workgroupSize[axis2]\n ))\n errors.push(\n `stateful compute pass ${pass.id} has mismatched workgroup`\n );\n }\n if (pass.draw !== void 0)\n errors.push(`stateful compute pass ${pass.id} cannot draw`);\n } else if (pass.dispatch !== void 0 || written?.kind !== "texture-2d" || !written.usage?.includes("render")) {\n errors.push(\n `stateful render pass ${pass.id} needs render texture output`\n );\n }\n if (pass.draw !== void 0) {\n if (!isStatefulResourceDraw(pass.draw)) {\n errors.push(`stateful pass ${pass.id} has unbounded instanced draw`);\n } else {\n const count = properties?.[pass.draw.instances.property];\n if (count?.type !== "int" || !Number.isSafeInteger(count.default) || count.default < 1 || count.default > pass.draw.instances.max || !Number.isSafeInteger(count.min) || count.min < 1 || !Number.isSafeInteger(count.max) || count.max > pass.draw.instances.max || !pass.reads.some((name) => resources.get(name)?.kind === "buffer"))\n errors.push(\n `stateful pass ${pass.id} needs bounded buffer-backed draw`\n );\n }\n }\n }\n return errors;\n }\n\n // shared/native-stateless-compute.ts\n function isStatelessComputeDispatch(value) {\n if (!value || typeof value !== "object") return false;\n const dispatch = value;\n const size = dispatch.workgroupSize;\n if (!Array.isArray(size) || size.length !== 3 || size[2] !== 1 || size.some((n) => !Number.isSafeInteger(n) || n < 1 || n > 256) || size[0] * size[1] > 256)\n return false;\n if (dispatch.elements === "source-grid")\n return Object.keys(dispatch).length === 2;\n return dispatch.elements === "source-row-blocks" && Object.keys(dispatch).length === 3 && size[0] === 64 && size[1] === 1 && typeof dispatch.blockProperty === "string" && /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(dispatch.blockProperty);\n }\n function validateStatelessComputeGraph(spec, passes, resources, output) {\n const invalid = [\n "stateless compute needs a bounded source/buffer/resolve ABI"\n ];\n if (!spec || typeof spec !== "object" || spec.abi !== "source-buffer-v1" || Object.keys(spec).some(\n (key) => !["abi", "bufferResource", "sharedBytes", "subpixelBlocks"].includes(\n key\n )\n ) || !Number.isSafeInteger(spec.sharedBytes) || spec.sharedBytes < 0 || spec.sharedBytes > 16384 || typeof spec.bufferResource !== "string" || spec.subpixelBlocks !== void 0 && spec.subpixelBlocks !== "source-identity")\n return invalid;\n const [compute, resolve] = passes;\n const source = resources.get("source");\n const buffer = resources.get(spec.bufferResource);\n const color2 = output ? resources.get(output) : void 0;\n if (resources.size !== 3 || passes.length !== 2 || source?.kind !== "texture-2d" || source.external !== true || source.size !== "viewport" || source.persistent === true || source.preprocess !== void 0 || source.mipmap !== void 0 || source.sampleEncoding !== void 0 || source.usage?.length !== 1 || !source.usage.includes("sampled") || buffer?.kind !== "buffer" || buffer.size !== "source" || buffer.byteLength !== void 0 || ![1, 4, 8, 16].includes(buffer.sourceBytesPerPixel) || buffer.external === true || buffer.persistent === true || buffer.format !== void 0 || buffer.usage?.length !== 2 || !buffer.usage.includes("storage") || !buffer.usage.includes("copy-dst") || color2?.kind !== "texture-2d" || color2.size !== "viewport" || color2.format !== "rgba16float" || color2.external === true || color2.persistent === true || !color2.usage?.includes("render") || !color2.usage.includes("sampled") || compute?.kind !== "compute" || compute.reads.length !== 1 || compute.reads[0] !== "source" || compute.output !== spec.bufferResource || !isStatelessComputeDispatch(compute.dispatch) || resolve?.kind !== "render" || resolve.reads.length !== 2 || resolve.reads[0] !== "source" || resolve.reads[1] !== spec.bufferResource || resolve.output !== output || passes.some(\n (pass) => pass.previousFrameReads !== void 0 || pass.additionalOutputs !== void 0 || pass.persistent === true || pass.draw !== void 0 || pass.original !== void 0\n ) || resolve.dispatch !== void 0)\n return invalid;\n if (spec.subpixelBlocks !== void 0 && compute.dispatch.elements !== "source-row-blocks")\n return invalid;\n const dispatch = compute.dispatch;\n const match = /@compute\\s+@workgroup_size\\(\\s*(\\d+)u?\\s*(?:,\\s*(\\d+)u?\\s*)?(?:,\\s*(\\d+)u?\\s*)?\\)\\s*fn\\s+cs\\s*\\(/.exec(\n compute.wgsl\n );\n if (!match || [\n Number(match[1]),\n match[2] === void 0 ? 1 : Number(match[2]),\n match[3] === void 0 ? 1 : Number(match[3])\n ].some((n, i) => n !== dispatch.workgroupSize[i]))\n return invalid;\n return [];\n }\n\n // shared/effect-graph.ts\n function isEffectMeshSpec(value) {\n if (!value || typeof value !== "object" || Array.isArray(value)) return false;\n const mesh = value;\n return Object.keys(mesh).length === 2 && Number.isSafeInteger(mesh.columns) && Number.isSafeInteger(mesh.rows) && mesh.columns >= 16 && mesh.columns <= 256 && mesh.rows >= 16 && mesh.rows <= 256 && mesh.columns * mesh.rows <= 32768;\n }\n function isEffectMeshPassCompatible(pass, specializedGraph) {\n return isEffectMeshSpec(pass.mesh) && pass.kind === "render" && pass.draw === void 0 && pass.dispatch === void 0 && pass.persistent === void 0 && pass.previousFrameReads === void 0 && pass.additionalOutputs === void 0 && pass.original === void 0 && !specializedGraph;\n }\n var FEEDBACK_UNIFORM_SLOTS = [\n "intensity",\n "blockSize",\n "drift",\n "churn",\n "blend",\n "seed"\n ];\n function feedbackUniformProperties(feedback) {\n return Object.fromEntries(\n FEEDBACK_UNIFORM_SLOTS.map((slot) => [\n slot,\n feedback.uniformProperties?.[slot] ?? slot\n ])\n );\n }\n var EXTERNAL_RESOURCES = /* @__PURE__ */ new Set(["source", "mask", "backdrop"]);\n var RESOURCE_NAME3 = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;\n function validateFeedbackGraph(feedback, passes, resources, output) {\n if (feedback?.abi !== "texture-feedback-v1" || feedback.sourceHistory !== void 0 && feedback.sourceHistory !== "sequential-captures" || feedback.pointer !== void 0 && feedback.pointer !== "interaction-v1" || feedback.resolveDraw !== void 0 && (feedback.resolveDraw === null || typeof feedback.resolveDraw !== "object" || Array.isArray(feedback.resolveDraw) || Object.keys(feedback.resolveDraw).length !== 2 || feedback.resolveDraw.vertices !== 6 || !Number.isSafeInteger(feedback.resolveDraw.instances) || feedback.resolveDraw.instances < 1 || feedback.resolveDraw.instances > 256) || !feedback.grid || !Number.isSafeInteger(feedback.grid.width) || !Number.isSafeInteger(feedback.grid.height) || feedback.grid.width < 1 || feedback.grid.height < 1 || feedback.grid.width > 2048 || feedback.grid.height > 2048 || feedback.grid.width * feedback.grid.height > 2097152 || feedback.grid.format !== "rgba16float" || !Array.isArray(feedback.grid.workgroup) || feedback.grid.workgroup.length !== 2 || feedback.grid.workgroup[0] !== 8 || feedback.grid.workgroup[1] !== 8 || !feedback.timing || !Number.isFinite(feedback.timing.fixedDt) || feedback.timing.fixedDt < 1 / 240 || feedback.timing.fixedDt > 1 / 15 || !Number.isSafeInteger(feedback.timing.maxStepsPerCall) || feedback.timing.maxStepsPerCall < 1 || feedback.timing.maxStepsPerCall > 512 || !Number.isSafeInteger(feedback.timing.maxStepIndex) || feedback.timing.maxStepIndex < 0 || feedback.timing.maxStepIndex > 36e3 || typeof feedback.stateResource !== "string" || !RESOURCE_NAME3.test(feedback.stateResource) || typeof feedback.displayResource !== "string" || !RESOURCE_NAME3.test(feedback.displayResource) || feedback.stateResource === feedback.displayResource || feedback.uniformProperties !== void 0 && (typeof feedback.uniformProperties !== "object" || feedback.uniformProperties === null || Array.isArray(feedback.uniformProperties) || Object.keys(feedback.uniformProperties).some(\n (slot) => !FEEDBACK_UNIFORM_SLOTS.includes(slot) || !RESOURCE_NAME3.test(\n feedback.uniformProperties?.[slot] ?? ""\n )\n ) || new Set(Object.values(feedbackUniformProperties(feedback))).size !== FEEDBACK_UNIFORM_SLOTS.length) || feedback.resetProperties !== void 0 && (!Array.isArray(feedback.resetProperties) || feedback.resetProperties.length > 16 || new Set(feedback.resetProperties).size !== feedback.resetProperties.length || feedback.resetProperties.some(\n (property) => typeof property !== "string" || !RESOURCE_NAME3.test(property)\n )))\n return ["feedback specification is malformed or unbounded"];\n const errors = [];\n const [compute, resolve] = passes;\n const state = resources.get(feedback.stateResource);\n const display = resources.get(feedback.displayResource);\n const presented = output ? resources.get(output) : void 0;\n const fixedTexture = (resource) => resource?.kind === "texture-2d" && resource.external !== true && resource.size === "fixed" && resource.width === feedback.grid.width && resource.height === feedback.grid.height && resource.format === "rgba16float" && resource.usage?.includes("sampled") === true && resource.usage.includes("storage");\n if (passes.length !== 2 || compute?.kind !== "compute" || compute.reads.length !== 1 || compute.reads[0] !== "source" || compute.output !== feedback.stateResource || compute.additionalOutputs?.length !== 1 || compute.additionalOutputs[0] !== feedback.displayResource || compute.previousFrameReads?.length !== 1 || compute.previousFrameReads[0] !== feedback.stateResource || compute.dispatch?.elements !== "fixed-grid" || !Array.isArray(compute.dispatch.workgroupSize) || compute.dispatch.workgroupSize[0] !== 8 || compute.dispatch.workgroupSize[1] !== 8 || resolve?.kind !== "render" || resolve.reads.length !== 2 || resolve.reads[0] !== "source" || resolve.reads[1] !== feedback.displayResource || resolve.additionalOutputs !== void 0 || resolve.previousFrameReads !== void 0 || resolve.dispatch !== void 0 || resolve.draw !== void 0 || output !== resolve.output)\n errors.push(\n "feedback needs one state/display compute and one source/display resolve pass"\n );\n if (!fixedTexture(state) || state?.persistent !== true || !fixedTexture(display) || display?.persistent === true || presented?.kind !== "texture-2d" || presented.external === true || presented.size !== "viewport" || presented.format !== "rgba16float" || !presented.usage?.includes("render") || !presented.usage.includes("sampled"))\n errors.push(\n "feedback needs bounded float state, display, and resolve resources"\n );\n return errors;\n }\n function planEffectPasses(passes, declaredResources, finalOutput, feedback, statelessCompute, resourceGraph, properties) {\n const errors = [];\n if (!Array.isArray(passes) || passes.length < 1 || passes.length > 16) {\n return {\n passes: [],\n resources: [],\n errors: ["effect graph needs 1\\u201316 passes"]\n };\n }\n for (const [index, pass] of passes.entries()) {\n if (!pass || typeof pass !== "object" || typeof pass.id !== "string" || typeof pass.output !== "string" || typeof pass.wgsl !== "string" || !Array.isArray(pass.reads) || pass.additionalOutputs !== void 0 && (!Array.isArray(pass.additionalOutputs) || pass.additionalOutputs.length !== 1 || !pass.additionalOutputs.every(\n (output) => typeof output === "string"\n )) || pass.reads.length > 16 || !pass.reads.every((read) => typeof read === "string") || new Set(pass.reads).size !== pass.reads.length || pass.previousFrameReads !== void 0 && (!Array.isArray(pass.previousFrameReads) || pass.previousFrameReads.length > 16 || !pass.previousFrameReads.every(\n (read) => typeof read === "string"\n ) || new Set(pass.previousFrameReads).size !== pass.previousFrameReads.length) || pass.dispatch !== void 0 && (pass.kind !== "compute" || !(pass.dispatch.workgroupSize === 256 && pass.dispatch.elements === "simulation-count" || Array.isArray(pass.dispatch.workgroupSize) && pass.dispatch.workgroupSize.length === 2 && pass.dispatch.workgroupSize[0] === 8 && pass.dispatch.workgroupSize[1] === 8 && pass.dispatch.elements === "fixed-grid" || isStatelessComputeDispatch(pass.dispatch) || isLinearResourceDispatch(pass.dispatch)) || !isStatelessComputeDispatch(pass.dispatch) && !isLinearResourceDispatch(pass.dispatch) && Object.keys(pass.dispatch).length !== 2) || pass.draw !== void 0 && (pass.kind !== "render" || pass.draw.vertices !== 6 || pass.draw.instances !== "simulation-count" && !((resourceGraph?.abi === "stateful-resource-v1" || resourceGraph?.abi === "stateful-resource-v2" || resourceGraph?.abi === "stateful-resource-v3") && isStatefulResourceDraw(pass.draw)) || Object.keys(pass.draw).length !== 2) || pass.mesh !== void 0 && !isEffectMeshPassCompatible(\n pass,\n feedback !== void 0 || statelessCompute !== void 0 || resourceGraph !== void 0\n )) {\n errors.push(`pass[${index}] is malformed`);\n }\n }\n if (errors.length) return { passes: [], resources: [], errors };\n if (passes.some((pass) => pass.original !== void 0)) {\n return {\n passes: [],\n resources: [],\n errors: ["retired original-pass execution is unsupported"]\n };\n }\n if (declaredResources?.some((resource) => resource.preprocess !== void 0)) {\n return {\n passes: [],\n resources: [],\n errors: ["retired source preprocessing is unsupported"]\n };\n }\n const declarations = /* @__PURE__ */ new Map();\n if (declaredResources) {\n if (!Array.isArray(declaredResources) || declaredResources.length > 48) {\n return {\n passes: [],\n resources: [],\n errors: ["effect graph declares too many resources"]\n };\n }\n for (const [index, resource] of declaredResources.entries()) {\n if (!resource || typeof resource !== "object" || typeof resource.name !== "string" || !RESOURCE_NAME3.test(resource.name) || resource.kind !== "texture-2d" && resource.kind !== "buffer" || resource.format !== void 0 && (typeof resource.format !== "string" || !/^[a-z0-9-]{1,64}$/.test(resource.format)) || resource.size !== void 0 && resource.size !== "viewport" && resource.size !== "fixed" && resource.size !== "source" || resource.kind === "buffer" && ((resource.size === "source" ? resource.byteLength !== void 0 || ![1, 4, 8, 16].includes(resource.sourceBytesPerPixel) : !Number.isSafeInteger(resource.byteLength) || resource.byteLength < 1 || resource.byteLength > 16777216 || resource.sourceBytesPerPixel !== void 0) || resource.width !== void 0 || resource.height !== void 0) || resource.kind === "texture-2d" && (resource.byteLength !== void 0 || resource.sourceBytesPerPixel !== void 0 || resource.size === "source" || resource.size === "fixed" && (!Number.isSafeInteger(resource.width) || !Number.isSafeInteger(resource.height) || resource.width < 1 || resource.height < 1 || resource.width > 8192 || resource.height > 8192) || resource.size !== "fixed" && (resource.width !== void 0 || resource.height !== void 0)) || resource.persistent !== void 0 && typeof resource.persistent !== "boolean" || resource.external !== void 0 && typeof resource.external !== "boolean" || resource.sampleEncoding !== void 0 && (resource.sampleEncoding !== "srgb-color" && resource.sampleEncoding !== "srgb-color-premultiplied" && resource.sampleEncoding !== "linear-data" && resource.sampleEncoding !== "srgb-encoded-straight" || resource.sampleEncoding === "srgb-encoded-straight" && resource.name !== "source" && resource.name !== "image" || resource.kind !== "texture-2d" || resource.external !== true || resource.usage !== void 0 && (!Array.isArray(resource.usage) || !resource.usage.includes("sampled"))) || resource.preprocess !== void 0 && (resource.preprocess !== "paper-liquid-mask" && resource.preprocess !== "paper-gem-smoke-mask-32" || resource.kind !== "texture-2d" || resource.external !== true || resource.sampleEncoding !== "linear-data" || resource.mipmap !== "generated") || resource.mipmap !== void 0 && (resource.mipmap !== "generated" || resource.kind !== "texture-2d" || resource.external !== true || resource.usage !== void 0 && !resource.usage.includes("sampled")) || resource.usage !== void 0 && (!Array.isArray(resource.usage) || new Set(resource.usage).size !== resource.usage.length || !resource.usage.every(\n (usage) => typeof usage === "string" && [\n "sampled",\n "render",\n "storage",\n "copy-src",\n "copy-dst"\n ].includes(usage)\n ))) {\n errors.push(`resource[${index}] is malformed`);\n continue;\n }\n if (declarations.has(resource.name))\n errors.push(`resource "${resource.name}" is duplicated`);\n if (EXTERNAL_RESOURCES.has(resource.name) && !resource.external) {\n errors.push(`resource "${resource.name}" has invalid external binding`);\n }\n declarations.set(resource.name, resource);\n }\n }\n if (errors.length) return { passes: [], resources: [], errors };\n const producers = /* @__PURE__ */ new Map();\n const ids = /* @__PURE__ */ new Set();\n for (const pass of passes) {\n if (!RESOURCE_NAME3.test(pass.id) || ids.has(pass.id)) {\n errors.push(`pass id "${pass.id}" is invalid or duplicated`);\n }\n ids.add(pass.id);\n for (const output of [pass.output, ...pass.additionalOutputs ?? []]) {\n if (!RESOURCE_NAME3.test(output) || EXTERNAL_RESOURCES.has(output) || declarations.get(output)?.external)\n errors.push(`pass "${pass.id}" has invalid output "${output}"`);\n if (producers.has(output))\n errors.push(`resource "${output}" has multiple producers`);\n producers.set(output, pass);\n }\n if (declaredResources) {\n for (const output of [pass.output, ...pass.additionalOutputs ?? []]) {\n const resource = declarations.get(output);\n if (!resource)\n errors.push(`pass "${pass.id}" output "${output}" is undeclared`);\n else if (pass.kind === "render" && resource.kind !== "texture-2d")\n errors.push(\n `render pass "${pass.id}" must output a texture-2d resource`\n );\n if (resource && pass.persistent !== void 0 && resource.persistent !== void 0 && pass.persistent !== resource.persistent && output === pass.output)\n errors.push(\n `pass "${pass.id}" persistence disagrees with resource "${output}"`\n );\n if (resource?.usage && !resource.usage.includes(\n pass.kind === "render" ? "render" : "storage"\n ))\n errors.push(\n `pass "${pass.id}" output "${output}" lacks ${pass.kind === "render" ? "render" : "storage"} usage`\n );\n }\n }\n if ([...pass.reads].some(\n (read) => [pass.output, ...pass.additionalOutputs ?? []].includes(read)\n )) {\n errors.push(\n `pass "${pass.id}" reads and writes "${pass.output}" in one frame`\n );\n }\n if (pass.kind !== "render" && pass.kind !== "compute") {\n errors.push(`pass "${pass.id}" has invalid kind`);\n }\n }\n if (!feedback && passes.some((pass) => pass.additionalOutputs?.length))\n errors.push("additional outputs require a feedback definition");\n if (!feedback && passes.some((pass) => pass.dispatch?.elements === "fixed-grid"))\n errors.push("fixed-grid dispatch requires a feedback definition");\n if (feedback)\n errors.push(\n ...validateFeedbackGraph(feedback, passes, declarations, finalOutput)\n );\n if (statelessCompute)\n errors.push(\n ...validateStatelessComputeGraph(\n statelessCompute,\n passes,\n declarations,\n finalOutput\n )\n );\n else if (passes.some((pass) => isStatelessComputeDispatch(pass.dispatch)) || [...declarations.values()].some((resource) => resource.size === "source"))\n errors.push("stateless-compute-definition-invalid");\n if (resourceGraph)\n errors.push(\n ...resourceGraph.abi === "stateful-resource-v1" || resourceGraph.abi === "stateful-resource-v2" || resourceGraph.abi === "stateful-resource-v3" ? validateStatefulResourceGraph(\n resourceGraph,\n passes,\n declarations,\n finalOutput,\n properties\n ) : validateLinearResourceGraph(\n resourceGraph,\n passes,\n declarations,\n finalOutput\n )\n );\n else if (passes.some((pass) => isLinearResourceDispatch(pass.dispatch)))\n errors.push("linear-resource-definition-invalid");\n const edges = /* @__PURE__ */ new Map();\n const indegree = /* @__PURE__ */ new Map();\n for (const pass of passes) {\n edges.set(pass.id, /* @__PURE__ */ new Set());\n indegree.set(pass.id, 0);\n }\n for (const pass of passes) {\n for (const resource of pass.reads) {\n if (!RESOURCE_NAME3.test(resource))\n errors.push(`invalid resource "${resource}"`);\n const producer = producers.get(resource);\n if (declaredResources && !declarations.has(resource)) {\n errors.push(\n `pass "${pass.id}" reads undeclared resource "${resource}"`\n );\n }\n const declaration = declarations.get(resource);\n if (declaration?.usage && !declaration.usage.includes(\n declaration.kind === "texture-2d" ? "sampled" : "storage"\n ))\n errors.push(\n `pass "${pass.id}" read "${resource}" lacks ${declaration.kind === "texture-2d" ? "sampled" : "storage"} usage`\n );\n if (!producer && !declaration?.external && !EXTERNAL_RESOURCES.has(resource)) {\n errors.push(`pass "${pass.id}" reads unknown resource "${resource}"`);\n }\n if (producer && producer.id !== pass.id && !edges.get(producer.id)?.has(pass.id)) {\n edges.get(producer.id)?.add(pass.id);\n indegree.set(pass.id, (indegree.get(pass.id) ?? 0) + 1);\n }\n }\n for (const resource of pass.previousFrameReads ?? []) {\n if (!RESOURCE_NAME3.test(resource))\n errors.push(`invalid resource "${resource}"`);\n const producer = producers.get(resource);\n const declaration = declarations.get(resource);\n if (!producer || !(declaration?.persistent ?? producer.persistent)) {\n errors.push(\n `pass "${pass.id}" previous-frame read "${resource}" requires a persistent producer`\n );\n }\n if (declaration?.usage && !declaration.usage.includes(\n declaration.kind === "texture-2d" ? "sampled" : "storage"\n ))\n errors.push(\n `pass "${pass.id}" previous-frame read "${resource}" lacks ${declaration.kind === "texture-2d" ? "sampled" : "storage"} usage`\n );\n }\n }\n const ready = passes.filter((pass) => indegree.get(pass.id) === 0);\n const ordered = [];\n while (ready.length) {\n const next = ready.shift();\n ordered.push(next);\n for (const dependent of edges.get(next.id) ?? []) {\n const remaining = (indegree.get(dependent) ?? 0) - 1;\n indegree.set(dependent, remaining);\n if (remaining === 0) {\n const pass = passes.find((candidate) => candidate.id === dependent);\n if (pass) ready.push(pass);\n }\n }\n }\n if (ordered.length !== passes.length)\n errors.push("same-frame pass graph contains a cycle");\n if (finalOutput !== void 0) {\n if (!RESOURCE_NAME3.test(finalOutput) || !producers.has(finalOutput)) {\n errors.push(`final output "${finalOutput}" has no producing pass`);\n } else if (declaredResources && declarations.get(finalOutput)?.kind !== "texture-2d") {\n errors.push(`final output "${finalOutput}" must be texture-2d`);\n }\n }\n const presentedOutput = finalOutput ?? ordered[ordered.length - 1]?.output;\n const presentedDeclaration = presentedOutput ? declarations.get(presentedOutput) : void 0;\n if (presentedOutput && presentedDeclaration?.usage && !presentedDeclaration.usage.includes("sampled"))\n errors.push(\n `final output "${presentedOutput}" lacks sampled usage for presentation`\n );\n const indexes = new Map(ordered.map((pass, index) => [pass.id, index]));\n const resources = /* @__PURE__ */ new Map();\n const externalResources = /* @__PURE__ */ new Set([\n ...EXTERNAL_RESOURCES,\n ...[...declarations.values()].filter((resource) => resource.external).map((resource) => resource.name)\n ]);\n for (const external of externalResources) {\n resources.set(external, {\n name: external,\n producer: null,\n firstUse: 0,\n lastUse: -1,\n persistent: false,\n external: true,\n kind: declarations.get(external)?.kind,\n format: declarations.get(external)?.format,\n size: declarations.get(external)?.size\n });\n }\n for (const pass of ordered) {\n const index = indexes.get(pass.id);\n for (const output of [pass.output, ...pass.additionalOutputs ?? []])\n resources.set(output, {\n name: output,\n producer: pass.id,\n firstUse: index,\n lastUse: index,\n persistent: declarations.get(output)?.persistent ?? !!pass.persistent,\n external: false,\n kind: declarations.get(output)?.kind,\n format: declarations.get(output)?.format,\n size: declarations.get(output)?.size ?? "viewport"\n });\n }\n for (const pass of ordered) {\n const index = indexes.get(pass.id);\n for (const name of [...pass.reads, ...pass.previousFrameReads ?? []]) {\n const resource = resources.get(name);\n if (resource) resource.lastUse = Math.max(resource.lastUse, index);\n }\n }\n if (presentedOutput) {\n const presented = resources.get(presentedOutput);\n if (presented)\n presented.lastUse = Math.max(presented.lastUse, ordered.length);\n }\n return {\n passes: errors.length ? [] : ordered,\n resources: [...resources.values()].filter(\n (resource) => resource.lastUse >= 0 || !resource.external\n ),\n errors\n };\n }\n function planEffectGraph(definition) {\n return planEffectPasses(\n definition.passes,\n definition.resources,\n definition.output,\n definition.feedback,\n definition.statelessCompute,\n definition.resourceGraph,\n definition.properties\n );\n }\n\n // shared/native-effect-paint.ts\n var MAX_EFFECT_PAINT_STOPS = 8;\n var NativeEffectPaintValueError = class extends TypeError {\n constructor() {\n super("Native paint has an invalid value or capacity.");\n __publicField(this, "code", "effect-paint-value-invalid");\n this.name = "NativeEffectPaintValueError";\n }\n };\n var INTERPOLATIONS = [\n "",\n "in srgb",\n "in srgb-linear",\n "in oklab",\n "in display-p3"\n ];\n function object(value) {\n return !!value && typeof value === "object" && !Array.isArray(value);\n }\n function keys(value, allowed) {\n return Object.keys(value).every((key) => allowed.includes(key));\n }\n function unit(value) {\n return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;\n }\n function color(value) {\n return object(value) && keys(value, ["space", "components", "alpha"]) && (value.space === "srgb" || value.space === "display-p3") && Array.isArray(value.components) && value.components.length === 3 && Array.from(value.components).every(unit) && unit(value.alpha);\n }\n function isEffectPaint(value, maxCount = MAX_EFFECT_PAINT_STOPS, allowedKinds) {\n if (!Number.isInteger(maxCount) || maxCount < 1 || maxCount > MAX_EFFECT_PAINT_STOPS || !object(value))\n return false;\n if (allowedKinds !== void 0 && (!Array.isArray(allowedKinds) || !allowedKinds.includes(value.kind)))\n return false;\n if (value.kind === "solid")\n return keys(value, ["kind", "color"]) && color(value.color);\n return ["linear", "radial", "angular", "diamond"].includes(String(value.kind)) && keys(value, ["kind", "angle", "stops", "opacity", "interpolation"]) && typeof value.angle === "number" && Number.isFinite(value.angle) && Math.abs(value.angle) <= 1e6 && (value.opacity === void 0 || unit(value.opacity)) && (value.interpolation === void 0 || INTERPOLATIONS.includes(\n value.interpolation\n )) && Array.isArray(value.stops) && value.stops.length >= 2 && value.stops.length <= maxCount && Array.from(value.stops).every(\n (stop) => object(stop) && keys(stop, ["position", "color"]) && unit(stop.position) && color(stop.color)\n );\n }\n function effectPaintInterpolation(paint) {\n if (paint.interpolation) return paint.interpolation;\n return paint.stops.every((stop) => stop.color.space === "srgb") ? "in srgb" : "in oklab";\n }\n function packEffectPaint(paint, maxCount, linearColor) {\n if (!isEffectPaint(paint, maxCount)) throw new NativeEffectPaintValueError();\n const packed = new Float32Array((1 + 2 * maxCount) * 4);\n const kinds = ["solid", "linear", "radial", "angular", "diamond"];\n const interpolation = paint.kind === "solid" ? 0 : ["in srgb", "in srgb-linear", "in oklab", "in display-p3"].indexOf(\n effectPaintInterpolation(paint)\n );\n const stops = paint.kind === "solid" ? [{ position: 0, color: paint.color }] : [...paint.stops].sort((a, b) => a.position - b.position);\n packed.set([\n kinds.indexOf(paint.kind) + 8 * interpolation,\n stops.length,\n paint.kind === "solid" ? 0 : paint.angle % 360 * Math.PI / 180,\n paint.kind === "solid" ? 1 : paint.opacity ?? 1\n ]);\n for (const [index, stop] of stops.entries()) {\n packed.set(\n [...linearColor(stop.color), stop.color.alpha],\n (1 + index * 2) * 4\n );\n packed[(2 + index * 2) * 4] = stop.position;\n }\n return packed;\n }\n\n // shared/native-effect-parameter-constraints.ts\n var PROPERTY_NAME_RE = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;\n var MAX_CONSTRAINTS = 8;\n var NativeEffectParameterConstraintError = class extends Error {\n constructor(issues) {\n super(`Native parameter constraints rejected: ${issues.join("; ")}`);\n __publicField(this, "issues", issues);\n __publicField(this, "code", "parameter-constraint");\n this.name = "NativeEffectParameterConstraintError";\n }\n };\n function constraintPropertyKeys(constraint) {\n if (constraint.kind === "ordered-floats")\n return [constraint.lesser, constraint.greater];\n if (constraint.kind === "float-sum") return constraint.properties;\n return constraint.corners;\n }\n function object2(value) {\n return value !== null && typeof value === "object" && !Array.isArray(value);\n }\n function finite(value) {\n return typeof value === "number" && Number.isFinite(value);\n }\n function own(value, key) {\n return Object.prototype.hasOwnProperty.call(value, key);\n }\n function exactKeys(value, keys2) {\n return Object.keys(value).length === keys2.length && keys2.every((key) => own(value, key));\n }\n function boundedProperty(properties, key, type) {\n if (typeof key !== "string" || !PROPERTY_NAME_RE.test(key) || !own(properties, key))\n return false;\n const property = properties[key];\n if (!object2(property) || property.type !== type) return false;\n const { min, max } = property;\n if (!finite(min) || !finite(max) || min >= max || Math.abs(min) > 1e6 || Math.abs(max) > 1e6)\n return false;\n if (type === "vec2" && (min !== 0 || max !== 1)) return false;\n return true;\n }\n function point(value) {\n return Array.isArray(value) && value.length === 2 && value.every(\n (coordinate) => finite(coordinate) && coordinate >= 0 && coordinate <= 1\n );\n }\n function cross(a, b, c) {\n return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]);\n }\n function evaluateParameterConstraint(constraint, values) {\n if (constraint.kind === "float-sum") {\n const terms = constraint.properties.map((key) => values[key]);\n if (!terms.every(finite)) return "sum-limit";\n return terms.reduce((sum, value) => sum + value, 0) <= constraint.maxSum ? null : "sum-limit";\n }\n if (constraint.kind === "ordered-floats") {\n const lesser = values[constraint.lesser];\n const greater = values[constraint.greater];\n if (!finite(lesser) || !finite(greater)) return "ordered-gap";\n return greater - lesser >= constraint.minGap ? null : "ordered-gap";\n }\n const corners = constraint.corners.map((key) => values[key]);\n if (!corners.every(point)) return "quad-degenerate";\n const vertices = corners;\n const turns = vertices.map(\n (_, index) => cross(\n vertices[index],\n vertices[(index + 1) % 4],\n vertices[(index + 2) % 4]\n )\n );\n if (turns.some((turn) => Math.abs(turn) < constraint.minCross))\n return "quad-degenerate";\n if (!turns.every((turn) => Math.sign(turn) === Math.sign(turns[0])))\n return "quad-nonconvex";\n const doubleArea = vertices.reduce((sum, vertex, index) => {\n const next = vertices[(index + 1) % 4];\n return sum + vertex[0] * next[1] - next[0] * vertex[1];\n }, 0);\n return Math.abs(doubleArea) / 2 >= constraint.minArea ? null : "quad-degenerate";\n }\n function validateParameterConstraintDefinitions(raw, properties) {\n if (raw === void 0) return [];\n if (!Array.isArray(raw) || raw.length < 1 || raw.length > MAX_CONSTRAINTS)\n return [`parameterConstraints needs 1\\u2013${MAX_CONSTRAINTS} entries`];\n if (!object2(properties))\n return ["parameterConstraints needs declared properties"];\n const errors = [];\n const seen = /* @__PURE__ */ new Set();\n for (const [index, candidate] of raw.entries()) {\n const prefix = `parameterConstraints[${index}]`;\n if (!object2(candidate)) {\n errors.push(`${prefix} is malformed`);\n continue;\n }\n let constraint;\n if (candidate.kind === "float-sum") {\n if (!exactKeys(candidate, ["kind", "properties", "maxSum"]) || !Array.isArray(candidate.properties) || candidate.properties.length < 2 || candidate.properties.length > 8 || new Set(candidate.properties).size !== candidate.properties.length || !candidate.properties.every(\n (key) => boundedProperty(properties, key, "float")\n ) || !finite(candidate.maxSum) || candidate.maxSum <= 0 || candidate.maxSum > 1e6) {\n errors.push(\n `${prefix} needs two to eight distinct bounded float properties and a positive finite sum limit`\n );\n continue;\n }\n constraint = candidate;\n } else if (candidate.kind === "ordered-floats") {\n if (!exactKeys(candidate, ["kind", "lesser", "greater", "minGap"]) || !boundedProperty(properties, candidate.lesser, "float") || !boundedProperty(properties, candidate.greater, "float") || candidate.lesser === candidate.greater || !finite(candidate.minGap) || candidate.minGap <= 0 || candidate.minGap > 1e3) {\n errors.push(\n `${prefix} needs two distinct bounded float properties and a positive finite gap`\n );\n continue;\n }\n constraint = candidate;\n } else if (candidate.kind === "convex-quad") {\n if (!exactKeys(candidate, ["kind", "corners", "minArea", "minCross"]) || !Array.isArray(candidate.corners) || candidate.corners.length !== 4 || new Set(candidate.corners).size !== 4 || !candidate.corners.every(\n (key) => boundedProperty(properties, key, "vec2")\n ) || !finite(candidate.minArea) || candidate.minArea <= 0 || candidate.minArea > 1 || !finite(candidate.minCross) || candidate.minCross <= 0 || candidate.minCross > 1) {\n errors.push(\n `${prefix} needs four distinct normalized vec2 properties and bounded positive area/cross limits`\n );\n continue;\n }\n constraint = candidate;\n } else {\n errors.push(`${prefix} kind is invalid`);\n continue;\n }\n const fingerprint = JSON.stringify(constraint);\n if (seen.has(fingerprint))\n errors.push(`${prefix} duplicates another constraint`);\n seen.add(fingerprint);\n const defaults = Object.fromEntries(\n constraintPropertyKeys(constraint).map((key) => [\n key,\n properties[key].default\n ])\n );\n const issue = evaluateParameterConstraint(constraint, defaults);\n if (issue) errors.push(`${prefix} defaults violate ${issue}`);\n }\n return errors;\n }\n function validateResolvedParameterConstraints(constraints, properties, params) {\n if (!constraints) return [];\n const values = {};\n for (const constraint of constraints) {\n const keys2 = constraintPropertyKeys(constraint);\n for (const key of keys2) {\n const property = properties[key];\n const fallback = property?.defaultFrom;\n values[key] = own(params, key) ? params[key] : typeof fallback === "string" && properties[fallback] ? own(params, fallback) ? params[fallback] : properties[fallback].default : property?.default;\n }\n }\n return constraints.flatMap((constraint, index) => {\n const issue = evaluateParameterConstraint(constraint, values);\n return issue ? [`parameterConstraints[${index}] violates ${issue}`] : [];\n });\n }\n\n // shared/native-effect-position.ts\n var MAX_NATIVE_POSITION_MAGNITUDE = 1e6;\n var UV = 0;\n var PX = 1;\n var PERCENT = 2;\n function bounded(value) {\n return typeof value === "number" && Number.isFinite(value) && Math.abs(value) <= MAX_NATIVE_POSITION_MAGNITUDE;\n }\n function axis(value, direction) {\n if (bounded(value)) return [value, UV];\n if (typeof value === "string") {\n const keyword = value.trim().toLowerCase();\n if (keyword === "center") return [0.5, UV];\n if (direction === "x") {\n if (keyword === "left") return [0, UV];\n if (keyword === "right") return [1, UV];\n } else {\n if (keyword === "top") return [0, UV];\n if (keyword === "bottom") return [1, UV];\n }\n return null;\n }\n if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== 2 || !("value" in value) || !("unit" in value) || !bounded(value.value))\n return null;\n if (value.unit === "uv") return [value.value, UV];\n if (value.unit === "px") return [value.value, PX];\n if (value.unit === "percent") return [value.value, PERCENT];\n return null;\n }\n function keywordPosition(value) {\n const parts = value.trim().toLowerCase().split(/\\s+/);\n if (parts.length < 1 || parts.length > 2 || parts.some(\n (part) => part !== "left" && part !== "center" && part !== "right" && part !== "top" && part !== "bottom"\n ) || parts.filter((part) => part === "left" || part === "right").length > 1 || parts.filter((part) => part === "top" || part === "bottom").length > 1)\n return null;\n const x = parts.includes("left") ? 0 : parts.includes("right") ? 1 : 0.5;\n const y = parts.includes("top") ? 0 : parts.includes("bottom") ? 1 : 0.5;\n return [x, y, UV, UV];\n }\n function parseNativePosition(value) {\n if (typeof value === "string") return keywordPosition(value);\n if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== 2 || !("x" in value) || !("y" in value))\n return null;\n const x = axis(value.x, "x");\n const y = axis(value.y, "y");\n return x && y ? [x[0], y[0], x[1], y[1]] : null;\n }\n function isNativePositionValue(value) {\n return parseNativePosition(value) !== null;\n }\n function packNativePosition(value) {\n const packed = parseNativePosition(value);\n if (!packed) throw new TypeError("native position is invalid");\n return packed;\n }\n\n // shared/native-parameter-animation.ts\n var EASINGS = /* @__PURE__ */ new Set([\n "linear",\n "ease-in",\n "ease-out",\n "ease-in-out",\n "step"\n ]);\n function nativeParameterCanAnimate(definition, name) {\n const property = definition.properties[name];\n if (!property || property.rebuild) return false;\n if (definition.feedback && (definition.feedback.uniformProperties?.seed ?? "seed") === name || definition.feedback?.resetProperties?.includes(name) || definition.resourceGraph && "resetProperties" in definition.resourceGraph && definition.resourceGraph.resetProperties?.includes(name))\n return false;\n if (Object.values(definition.inputs ?? {}).some(\n (input) => input.enabledWhen?.property === name\n ))\n return false;\n if (definition.interaction?.positionProperty === name || definition.interaction?.activeProperty === name)\n return false;\n if (property.type === "texture" || property.type === "position" || property.type === "color-array" || property.type === "color-ramp" || property.type === "record-array" || property.type === "paint")\n return false;\n return definition.simulation?.count.property !== name;\n }\n function validateNativeParameterAnimation(definition, animation, validateValue2) {\n if (animation === void 0) return [];\n const errors = [];\n if (!animation || typeof animation !== "object" || Array.isArray(animation))\n return ["animation must be an object"];\n const value = animation;\n if (Object.keys(value).some(\n (key) => key !== "duration" && key !== "loop" && key !== "tracks"\n ))\n errors.push("animation has unknown fields");\n if (typeof value.duration !== "number" || !Number.isFinite(value.duration) || value.duration <= 0 || value.duration > 60)\n errors.push("animation duration must be within (0, 60] seconds");\n if (typeof value.loop !== "boolean")\n errors.push("animation loop must be boolean");\n const tracks = value.tracks;\n if (!tracks || typeof tracks !== "object" || Array.isArray(tracks)) {\n errors.push("animation tracks must be an object");\n return errors;\n }\n const entries = Object.entries(tracks);\n if (entries.length < 1 || entries.length > 16)\n errors.push("animation needs 1\\u201316 tracks");\n for (const [name, candidate] of entries) {\n const prefix = `animation track ${name}`;\n if (!nativeParameterCanAnimate(definition, name)) {\n errors.push(`${prefix} is not animatable`);\n continue;\n }\n if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) {\n errors.push(`${prefix} must be an object`);\n continue;\n }\n const track = candidate;\n if (Object.keys(track).some((key) => key !== "keys"))\n errors.push(`${prefix} has unknown fields`);\n if (!Array.isArray(track.keys) || track.keys.length < 2 || track.keys.length > 32) {\n errors.push(`${prefix} needs 2\\u201332 keys`);\n continue;\n }\n const property = definition.properties[name];\n let previousTime = -1;\n let colorSpace;\n for (const [index, item] of track.keys.entries()) {\n const keyPrefix = `${prefix} key ${index}`;\n if (!item || typeof item !== "object" || Array.isArray(item)) {\n errors.push(`${keyPrefix} must be an object`);\n continue;\n }\n const key = item;\n if (Object.keys(key).some(\n (field) => !["time", "value", "easing"].includes(field)\n ))\n errors.push(`${keyPrefix} has unknown fields`);\n if (typeof key.time !== "number" || !Number.isFinite(key.time) || key.time < 0 || key.time > (typeof value.duration === "number" ? value.duration : 0) || key.time <= previousTime)\n errors.push(`${keyPrefix} time must increase within duration`);\n else previousTime = key.time;\n validateValue2(property, key.value, name, errors);\n if (key.easing !== void 0 && !EASINGS.has(key.easing))\n errors.push(`${keyPrefix} has invalid easing`);\n if ((property.type === "bool" || property.type === "enum") && key.easing !== void 0 && key.easing !== "step")\n errors.push(`${keyPrefix} must use step easing`);\n if (property.type === "color" && key.value && typeof key.value === "object") {\n const space = key.value.space;\n if (colorSpace && colorSpace !== space)\n errors.push(`${prefix} color keys must share a color space`);\n if (space !== property.default.space)\n errors.push(`${prefix} color keys must use the declared color space`);\n colorSpace = space;\n }\n }\n if (track.keys[0]?.time !== 0)\n errors.push(`${prefix} must start at time 0`);\n if (track.keys[track.keys.length - 1]?.time !== value.duration)\n errors.push(`${prefix} must end at duration`);\n }\n return errors;\n }\n function eased(progress, easing) {\n switch (easing) {\n case "ease-in":\n return progress * progress;\n case "ease-out":\n return 1 - (1 - progress) * (1 - progress);\n case "ease-in-out":\n return progress < 0.5 ? 2 * progress * progress : 1 - 2 * (1 - progress) * (1 - progress);\n case "step":\n return 0;\n default:\n return progress;\n }\n }\n function interpolate(property, a, b, progress) {\n if (property.type === "bool" || property.type === "enum") return a;\n if (property.type === "float" || property.type === "int") {\n const value = a + (b - a) * progress;\n return property.type === "int" ? Math.round(value) : value;\n }\n if (property.type === "vec2") {\n const from = a;\n const to = b;\n return [\n from[0] + (to[0] - from[0]) * progress,\n from[1] + (to[1] - from[1]) * progress\n ];\n }\n if (property.type === "color") {\n const from = a;\n const to = b;\n return {\n space: from.space,\n components: [0, 1, 2].map(\n (index) => from.components[index] + (to.components[index] - from.components[index]) * progress\n ),\n alpha: from.alpha + (to.alpha - from.alpha) * progress\n };\n }\n throw new Error(`Unsupported animated property type ${property.type}`);\n }\n function resolveNativeParameterAnimation(definition, params, animation, localTime2) {\n if (!animation) return params;\n if (!Number.isFinite(localTime2) || localTime2 < 0)\n throw new Error("Animation local time must be finite and nonnegative");\n const time = animation.loop ? localTime2 % animation.duration : Math.min(localTime2, animation.duration);\n const resolved = { ...params };\n for (const [name, track] of Object.entries(animation.tracks)) {\n const property = definition.properties[name];\n if (!nativeParameterCanAnimate(definition, name) || !property)\n throw new Error(`Animation track ${name} is not animatable`);\n const keys2 = track.keys;\n if (time <= keys2[0].time) {\n resolved[name] = keys2[0].value;\n continue;\n }\n const last = keys2[keys2.length - 1];\n if (time >= last.time) {\n resolved[name] = last.value;\n continue;\n }\n for (let index = 0; index < keys2.length - 1; index++) {\n const from = keys2[index];\n const to = keys2[index + 1];\n if (time >= to.time) continue;\n const progress = (time - from.time) / (to.time - from.time);\n resolved[name] = interpolate(\n property,\n from.value,\n to.value,\n eased(progress, from.easing ?? "linear")\n );\n break;\n }\n }\n return resolved;\n }\n\n // shared/native-source-sizing.ts\n function record2(value) {\n return value !== null && typeof value === "object" && !Array.isArray(value);\n }\n function exactKeys2(value, keys2) {\n return Object.keys(value).length === keys2.length && keys2.every((key) => Object.prototype.hasOwnProperty.call(value, key));\n }\n function bounded2(value, min, max) {\n return typeof value === "number" && Number.isFinite(value) && value >= min && value <= max;\n }\n function pair(value, min, max) {\n return Array.isArray(value) && value.length === 2 && value.every((part) => bounded2(part, min, max));\n }\n function isNativeSourceSizing(value) {\n if (!record2(value) || !exactKeys2(value, [\n "inputSpace",\n "aspectRatio",\n "fit",\n "worldSize",\n "origin",\n "offset",\n "scale",\n "rotationDegrees",\n "sampling"\n ]))\n return false;\n if (!record2(value.sampling) || !exactKeys2(value.sampling, ["min", "mag", "mipmap"]))\n return false;\n return (value.inputSpace === "intrinsic-image" || value.inputSpace === "rendered-surface") && bounded2(value.aspectRatio, 1 / 64, 64) && (value.fit === "none" || value.fit === "contain" || value.fit === "cover") && pair(value.worldSize, 0, 16384) && pair(value.origin, 0, 1) && pair(value.offset, -1, 1) && bounded2(value.scale, 0.1, 4) && bounded2(value.rotationDegrees, 0, 360) && (value.sampling.min === "nearest" || value.sampling.min === "linear") && (value.sampling.mag === "nearest" || value.sampling.mag === "linear") && (value.sampling.mipmap === "none" || value.sampling.mipmap === "nearest" || value.sampling.mipmap === "linear");\n }\n\n // shared/native-uniform-timing.ts\n var NativeUniformTimingError = class extends RangeError {\n constructor(field) {\n super(`native-uniform-timing-invalid:${field}`);\n __publicField(this, "field", field);\n __publicField(this, "code", "native-uniform-timing-invalid");\n this.name = "NativeUniformTimingError";\n }\n };\n function isFiniteNativeUniformTiming(value) {\n return typeof value === "number" && Number.isFinite(Math.fround(value));\n }\n function assertNativeUniformTiming(value, field) {\n if (!isFiniteNativeUniformTiming(value))\n throw new NativeUniformTimingError(field);\n }\n function packNativeUniformClock(input) {\n const deltaTime = input.deltaTime === void 0 ? 0 : input.deltaTime;\n assertNativeUniformTiming(input.time, "time");\n assertNativeUniformTiming(deltaTime, "delta-time");\n return new Float32Array([\n input.time,\n input.seed,\n input.pixelRatio,\n deltaTime\n ]);\n }\n\n // shared/native-effects.ts\n var NATIVE_EFFECT_SCHEMA_VERSION = 2;\n var MAX_EFFECT_MANIFEST_BYTES = 2e6;\n var MAX_PROPERTY_SLOTS = 32;\n var MAX_COLOR_ARRAY = 10;\n var MAX_COLOR_RAMP = 8;\n var ID_RE = /^[A-Za-z0-9_.:-]{1,128}$/;\n var PROPERTY_RE = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;\n function definitionKey(id, version) {\n return `${id}\\0${version}`;\n }\n function resolvedEffectPropertyValue(definition, params, name) {\n const property = definition.properties[name];\n if (!property) throw new TypeError(`Unknown effect property ${name}`);\n if (Object.prototype.hasOwnProperty.call(params, name)) return params[name];\n if (property.type === "float" && property.defaultFrom) {\n const source = definition.properties[property.defaultFrom];\n if (!source || source.type !== "float")\n throw new TypeError(\n `Invalid effect property default source ${property.defaultFrom}`\n );\n return Object.prototype.hasOwnProperty.call(params, property.defaultFrom) ? params[property.defaultFrom] : source.default;\n }\n return property.default;\n }\n function effectInputEnabled(port, definition, params) {\n const condition = port.enabledWhen;\n if (!condition) return true;\n return (params[condition.property] ?? definition.properties[condition.property]?.default) === condition.equals;\n }\n function record3(value) {\n return !!value && typeof value === "object" && !Array.isArray(value);\n }\n function finite2(value) {\n return typeof value === "number" && Number.isFinite(value);\n }\n function finiteUnit(value) {\n return finite2(value) && value >= 0 && value <= 1;\n }\n function validImportedUpstream(value) {\n return record3(value) && ["repository", "commit", "file", "license"].every(\n (key) => typeof value[key] === "string" && !!value[key]\n );\n }\n function validColor(value) {\n return record3(value) && (value.space === "srgb" || value.space === "display-p3") && Array.isArray(value.components) && value.components.length === 3 && Array.from(value.components).every(finiteUnit) && finiteUnit(value.alpha);\n }\n function validColorStop(value) {\n return record3(value) && finiteUnit(value.position) && validColor(value.color);\n }\n var NativeEffectPropertyValueError = class extends TypeError {\n constructor(errors) {\n super(errors.join("; "));\n __publicField(this, "errors", errors);\n __publicField(this, "code", "effect-property-values-invalid");\n this.name = "NativeEffectPropertyValueError";\n }\n };\n function checkEffectAssetUrl(value) {\n if (typeof value !== "string") return { ok: false, reason: "invalid-type" };\n if (!value.startsWith("/") || value.startsWith("//"))\n return { ok: false, reason: "non-local" };\n if (value.length > 2048 || /[\\\\\\s<>"\'\\u0000-\\u001f]/.test(value))\n return { ok: false, reason: "unsafe-path" };\n try {\n const decoded = decodeURIComponent(value.split(/[?#]/, 1)[0]);\n if (!decoded.startsWith("/") || decoded.startsWith("//") || decoded.includes("%") || decoded.split("/").includes("..") || /[\\\\\\u0000-\\u001f]/.test(decoded))\n return { ok: false, reason: "unsafe-path" };\n return { ok: true, url: value };\n } catch {\n return { ok: false, reason: "malformed-encoding" };\n }\n }\n function validateTransform(value, prefix, errors) {\n if (value === void 0) return;\n if (!record3(value)) {\n errors.push(`${prefix}.transform must be an object`);\n return;\n }\n if (value.translate !== void 0 && (!Array.isArray(value.translate) || value.translate.length !== 2 || !value.translate.every(\n (part) => finite2(part) && Math.abs(part) <= 1e5\n )))\n errors.push(\n `${prefix}.transform.translate needs two bounded pixel offsets`\n );\n if (value.scale !== void 0 && (!Array.isArray(value.scale) || value.scale.length !== 2 || !value.scale.every((part) => finite2(part) && part > 0 && part <= 100)))\n errors.push(`${prefix}.transform.scale needs two positive bounded factors`);\n if (value.rotate !== void 0 && (!finite2(value.rotate) || Math.abs(value.rotate) > 100 * Math.PI))\n errors.push(`${prefix}.transform.rotate needs bounded radians`);\n if (value.origin !== void 0 && (!Array.isArray(value.origin) || value.origin.length !== 2 || !value.origin.every(finiteUnit)))\n errors.push(`${prefix}.transform.origin needs normalized coordinates`);\n for (const key of Object.keys(value))\n if (!["translate", "scale", "rotate", "origin"].includes(key))\n errors.push(`${prefix}.transform has unknown field "${key}"`);\n }\n function validateSourceSizing(value, definition, prefix, errors) {\n if (value === void 0) {\n if (definition?.sourceSizing?.intrinsicEncoding === "srgb-encoded-straight")\n errors.push(`${prefix}.sourceSizing needs an intrinsic-image source`);\n return;\n }\n if (definition?.sourceSizing?.uv !== "paper-image") {\n errors.push(\n `${prefix}.sourceSizing needs a processor definition with the saved image-UV contract`\n );\n return;\n }\n if (!isNativeSourceSizing(value))\n errors.push(`${prefix}.sourceSizing is invalid`);\n else if (value.inputSpace === "intrinsic-image" && definition.sourceSizing?.intrinsicEncoding !== "srgb-encoded-straight")\n errors.push(\n `${prefix}.sourceSizing needs an encoded-straight intrinsic source ABI`\n );\n else if (value.inputSpace === "rendered-surface" && definition.sourceSizing?.intrinsicEncoding === "srgb-encoded-straight")\n errors.push(`${prefix}.sourceSizing needs an intrinsic-image source`);\n }\n function validateBindings(value, definition, prefix, errors) {\n if (value === void 0) return;\n if (!record3(value) || Object.keys(value).length > 16) {\n errors.push(`${prefix}.bindings must contain at most 16 named inputs`);\n return;\n }\n for (const [name, binding] of Object.entries(value)) {\n const port = definition?.inputs && Object.prototype.hasOwnProperty.call(definition.inputs, name) ? definition.inputs[name] : void 0;\n if (!port || !["texture-2d", "mask"].includes(port.kind)) {\n errors.push(\n `${prefix}.bindings.${name} needs a texture or mask input port`\n );\n continue;\n }\n if (!record3(binding)) {\n errors.push(`${prefix}.bindings.${name} is invalid`);\n continue;\n }\n const fields = binding.kind === "builtin" ? ["kind", "source"] : binding.kind === "authored-node" ? ["kind", "nodeId", "capture"] : binding.kind === "camera" ? ["kind"] : binding.kind === "asset" ? ["kind", "url"] : ["kind"];\n if (Object.keys(binding).some((field) => !fields.includes(field)))\n errors.push(`${prefix}.bindings.${name} has unknown fields`);\n const optionalNoise = definition?.optionalImage && definition.passes[0]?.reads[1] === "noise" && name === "noise";\n if ((name === definition?.optionalImage?.port || optionalNoise) && binding.kind !== "asset")\n errors.push(\n `${prefix}.bindings.${name} needs an asset for optional image sampling`\n );\n if (binding.kind === "builtin") {\n if (![\n "source",\n "mask",\n "backdrop",\n "receiver-geometry",\n "receiver-interior"\n ].includes(String(binding.source)) || port.kind === "mask" && binding.source !== "mask" || port.kind === "texture-2d" && binding.source === "mask")\n errors.push(\n `${prefix}.bindings.${name} builtin source is incompatible`\n );\n } else if (binding.kind === "authored-node") {\n if (typeof binding.nodeId !== "string" || !ID_RE.test(binding.nodeId) || !["content", "appearance"].includes(String(binding.capture)))\n errors.push(`${prefix}.bindings.${name} authored node is invalid`);\n } else if (binding.kind === "asset") {\n const asset = checkEffectAssetUrl(binding.url);\n if (!asset.ok)\n errors.push(\n `${prefix}.bindings.${name} asset needs a same-origin root path (${asset.reason})`\n );\n } else if (binding.kind === "camera") {\n if (port.kind !== "texture-2d")\n errors.push(`${prefix}.bindings.${name} camera needs a texture input`);\n } else {\n errors.push(`${prefix}.bindings.${name} kind is invalid`);\n }\n }\n }\n function validateTextureBindingConflicts(params, bindings, definition, prefix, errors) {\n if (!record3(params) || !record3(bindings) || !definition) return;\n for (const [name, property] of Object.entries(definition.properties)) {\n if (property.type !== "texture") continue;\n const value = Object.prototype.hasOwnProperty.call(params, name) ? params[name] : property.default;\n if (value !== null && Object.prototype.hasOwnProperty.call(bindings, property.input))\n errors.push(\n `${prefix} texture property "${name}" conflicts with input binding "${property.input}"`\n );\n }\n }\n function validateValue(prop, value, name, errors) {\n switch (prop.type) {\n case "float":\n case "int":\n if (!finite2(value) || prop.type === "int" && !Number.isInteger(value) || prop.min !== void 0 && value < prop.min || prop.max !== void 0 && value > prop.max) {\n errors.push(\n `property "${name}" needs a finite ${prop.type} within bounds`\n );\n }\n break;\n case "bool":\n if (typeof value !== "boolean")\n errors.push(`property "${name}" needs a boolean`);\n break;\n case "enum":\n if (typeof value !== "string" || !prop.options.includes(value)) {\n errors.push(`property "${name}" needs one of its options`);\n }\n break;\n case "color":\n if (!validColor(value))\n errors.push(`property "${name}" needs a normalized color`);\n break;\n case "vec2":\n if (!Array.isArray(value) || value.length !== 2 || !value.every(finite2) || prop.min !== void 0 && value.some((part) => part < prop.min) || prop.max !== void 0 && value.some((part) => part > prop.max)) {\n errors.push(\n `property "${name}" needs two finite numbers within bounds`\n );\n }\n break;\n case "position":\n if (!isNativePositionValue(value))\n errors.push(`property "${name}" needs a bounded 2D position`);\n break;\n case "color-array":\n if (!Array.isArray(value) || value.length > prop.maxCount || !value.every(validColor)) {\n errors.push(\n `property "${name}" needs at most ${prop.maxCount} normalized colors`\n );\n }\n break;\n case "color-ramp":\n if (!Array.isArray(value) || value.length > prop.maxCount || !Array.from(value).every(validColorStop))\n errors.push(\n `property "${name}" needs at most ${prop.maxCount} normalized color stops with positions within 0\\u20131`\n );\n break;\n case "record-array": {\n const names = record3(prop.fields) ? Object.keys(prop.fields) : [];\n if (!Array.isArray(value) || !Number.isSafeInteger(prop.maxCount) || prop.maxCount < 1 || prop.maxCount > 4 || value.length < (prop.minCount ?? 0) || value.length > prop.maxCount || names.length < 1 || names.length > 16) {\n errors.push(`property "${name}" needs a bounded record array`);\n break;\n }\n try {\n planNativeRecordLayout(prop.fields);\n } catch (error) {\n if (!(error instanceof NativeEffectPropertyLayoutError)) throw error;\n errors.push(`property "${name}" ${error.message}`);\n break;\n }\n for (const [index, row] of value.entries()) {\n if (!record3(row) || Object.keys(row).length !== names.length || !names.every(\n (fieldName) => Object.prototype.hasOwnProperty.call(row, fieldName)\n )) {\n errors.push(`property "${name}" record ${index} has invalid fields`);\n continue;\n }\n for (const fieldName of names)\n validateValue(\n prop.fields[fieldName],\n row[fieldName],\n `${name}[${index}].${fieldName}`,\n errors\n );\n if (prop.parameterConstraints && validateParameterConstraintDefinitions(\n prop.parameterConstraints,\n prop.fields\n ).length === 0)\n errors.push(\n ...validateResolvedParameterConstraints(\n prop.parameterConstraints,\n prop.fields,\n row\n ).map(\n (issue) => `property "${name}" record ${index} (${names.join(", ")}) ${issue}`\n )\n );\n }\n break;\n }\n case "paint":\n if (!isEffectPaint(value, prop.maxCount, prop.allowedKinds))\n errors.push(\n `property "${name}" needs an allowed paint with 2\\u2013${prop.maxCount} normalized gradient stops`\n );\n break;\n case "texture":\n if (value !== null) {\n if (!record3(value) || value.kind !== "asset") {\n errors.push(\n `property "${name}" needs a same-origin texture asset or null`\n );\n } else {\n const asset = checkEffectAssetUrl(value.url);\n if (!asset.ok)\n errors.push(\n `property "${name}" needs a same-origin texture asset or null (${asset.reason})`\n );\n }\n }\n break;\n }\n }\n function propertySlots(prop) {\n if (prop.type === "texture") return 0;\n if (prop.type === "record-array")\n return 1 + prop.maxCount * planNativeRecordLayout(prop.fields).stride / 4;\n if (prop.type === "color-array") return 1 + prop.maxCount;\n if (prop.type === "color-ramp" || prop.type === "paint")\n return 1 + 2 * prop.maxCount;\n return 1;\n }\n var NativeEffectPropertyLayoutError = class extends TypeError {\n constructor(code, message) {\n super(message);\n __publicField(this, "code", code);\n this.name = "NativeEffectPropertyLayoutError";\n }\n };\n function nativeEffectUniformFloats(definition) {\n if (definition.uniformFloats === void 0) return 128;\n if (definition.uniformFloats === 256) return 256;\n throw new NativeEffectPropertyLayoutError(\n "invalid-mode",\n "uniformFloats must be 256 when present"\n );\n }\n function planNativeRecordLayout(fields) {\n if (!record3(fields) || Object.keys(fields).length < 1 || Object.keys(fields).length > 16)\n throw new NativeEffectPropertyLayoutError(\n "invalid-property",\n "record fields need 1\\u201316 named entries"\n );\n const offsets = /* @__PURE__ */ Object.create(null);\n let next = 0;\n for (const [name, field] of Object.entries(fields)) {\n if (!PROPERTY_RE.test(name) || !record3(field) || typeof field.type !== "string" || !["float", "int", "bool", "vec2", "color"].includes(field.type))\n throw new NativeEffectPropertyLayoutError(\n "invalid-property",\n `record field "${name}" has invalid uniform type`\n );\n const alignment = field.type === "vec2" ? 2 : field.type === "color" ? 4 : 1;\n const width = field.type === "vec2" ? 2 : field.type === "color" ? 4 : 1;\n next = Math.ceil(next / alignment) * alignment;\n offsets[name] = next;\n next += width;\n }\n return { offsets, floatCount: next, stride: Math.ceil(next / 4) * 4 };\n }\n function planNativePropertyLayout(definition) {\n const mode = definition.uniformPacking;\n if (mode !== void 0 && mode !== "compact")\n throw new NativeEffectPropertyLayoutError(\n "invalid-mode",\n "uniformPacking must be compact when present"\n );\n const capacity = nativeEffectUniformFloats(definition);\n if (capacity === 256 && mode !== "compact")\n throw new NativeEffectPropertyLayoutError(\n "invalid-mode",\n "uniformFloats 256 needs compact uniformPacking"\n );\n if (!record3(definition.properties))\n throw new NativeEffectPropertyLayoutError(\n "invalid-property",\n "properties must be an object"\n );\n const offsets = /* @__PURE__ */ Object.create(null);\n let next = 0;\n for (const [name, prop] of Object.entries(definition.properties)) {\n if (!record3(prop) || !PROPERTY_RE.test(name) || ![\n "float",\n "int",\n "bool",\n "enum",\n "vec2",\n "color",\n "position",\n "color-array",\n "color-ramp",\n "paint",\n "texture",\n "record-array"\n ].includes(prop.type))\n throw new NativeEffectPropertyLayoutError(\n "invalid-property",\n `property "${name}" has invalid uniform type`\n );\n const property = prop;\n if (property.type === "texture") continue;\n if (property.type === "record-array") {\n if (mode !== "compact" || !Number.isSafeInteger(property.maxCount) || property.maxCount < 1 || property.maxCount > 4)\n throw new NativeEffectPropertyLayoutError(\n "invalid-property",\n `property "${name}" needs compact packing and 1\\u20134 records`\n );\n const row = planNativeRecordLayout(property.fields);\n const offset2 = Math.ceil(next / 4) * 4;\n offsets[name] = offset2;\n next = offset2 + 4 + property.maxCount * row.stride;\n continue;\n }\n if (property.type === "color-array" || property.type === "color-ramp" || property.type === "paint") {\n const maximum = property.type === "paint" ? MAX_EFFECT_PAINT_STOPS : property.type === "color-ramp" ? MAX_COLOR_RAMP : MAX_COLOR_ARRAY;\n if (!Number.isSafeInteger(property.maxCount) || property.maxCount < 1 || property.maxCount > maximum)\n throw new NativeEffectPropertyLayoutError(\n "invalid-property",\n `property "${name}" has invalid uniform count`\n );\n }\n let alignment = 4;\n let width = propertySlots(property) * 4;\n if (mode === "compact") {\n if (["float", "int", "bool", "enum"].includes(property.type)) {\n alignment = 1;\n width = 1;\n } else if (property.type === "vec2") {\n alignment = 2;\n width = 2;\n }\n }\n if (!Number.isSafeInteger(width) || width < 1 || width > capacity)\n throw new NativeEffectPropertyLayoutError(\n "invalid-property",\n `property "${name}" has invalid uniform width`\n );\n const offset = Math.ceil(next / alignment) * alignment;\n offsets[name] = offset;\n next = offset + width;\n }\n if (next > capacity)\n throw new NativeEffectPropertyLayoutError(\n "overflow",\n mode === "compact" ? `properties need ${next} float uniforms; max is ${capacity}` : `properties need ${next / 4} vec4 slots; max is ${MAX_PROPERTY_SLOTS}`\n );\n return { offsets, floatCount: next };\n }\n function validatePorts(value, prefix, resources, errors, isInput, optionalImagePort, properties) {\n if (value === void 0) return;\n if (!record3(value) || Object.keys(value).length > 32) {\n errors.push(`${prefix} must contain at most 32 named ports`);\n return;\n }\n const resourceNames = Array.isArray(resources) ? new Set(\n resources.map(\n (resource) => record3(resource) ? resource.name : void 0\n )\n ) : null;\n for (const [name, unknownPort] of Object.entries(value)) {\n if (!PROPERTY_RE.test(name) || !record3(unknownPort) || ![\n "float",\n "int",\n "bool",\n "vec2",\n "color",\n "texture-2d",\n "mask",\n "buffer",\n "signal"\n ].includes(String(unknownPort.kind)) || unknownPort.optional !== void 0 && typeof unknownPort.optional !== "boolean") {\n errors.push(`${prefix}.${name} is invalid`);\n continue;\n }\n const needsResource = ["texture-2d", "mask", "buffer"].includes(\n String(unknownPort.kind)\n );\n if (needsResource && (typeof unknownPort.resource !== "string" || !resourceNames?.has(unknownPort.resource))) {\n errors.push(`${prefix}.${name} needs a declared resource`);\n }\n if (!needsResource && unknownPort.resource !== void 0) {\n errors.push(`${prefix}.${name} cannot bind a texture/buffer resource`);\n }\n const resource = Array.isArray(resources) ? resources.find(\n (candidate) => record3(candidate) && candidate.name === unknownPort.resource\n ) : void 0;\n if (resource && (unknownPort.kind === "buffer" && resource.kind !== "buffer" || ["texture-2d", "mask"].includes(String(unknownPort.kind)) && resource.kind !== "texture-2d")) {\n errors.push(`${prefix}.${name} resource kind does not match port kind`);\n }\n if (unknownPort.enabledWhen !== void 0) {\n const condition = unknownPort.enabledWhen;\n const dependency = record3(condition) && record3(properties) ? properties[condition.property] : void 0;\n if (!isInput || !["texture-2d", "mask"].includes(String(unknownPort.kind)) || unknownPort.optional === true || unknownPort.fallback !== "transparent-data" || !record3(condition) || Object.keys(condition).length !== 2 || typeof condition.property !== "string" || !record3(dependency) || !["bool", "enum", "int", "float"].includes(String(dependency.type)) || dependency.type === "bool" && typeof condition.equals !== "boolean" || dependency.type === "enum" && (!Array.isArray(dependency.options) || !dependency.options.includes(condition.equals)) || ["int", "float"].includes(String(dependency.type)) && (!finite2(condition.equals) || dependency.type === "int" && !Number.isInteger(condition.equals)))\n errors.push(`${prefix}.${name} has an invalid enabledWhen condition`);\n }\n if (unknownPort.fallback !== void 0 && (!isInput || unknownPort.fallback !== "transparent-data" || unknownPort.optional !== true && unknownPort.enabledWhen === void 0 || !["texture-2d", "mask"].includes(String(unknownPort.kind)) || !(unknownPort.enabledWhen !== void 0 || resource?.preprocess === "paper-liquid-mask" || name === optionalImagePort && resource?.name === "image" && (resource.sampleEncoding === "srgb-encoded-straight" || resource.sampleEncoding === "linear-data"))))\n errors.push(`${prefix}.${name} has an unsupported input fallback`);\n }\n }\n function validateConditionalInputs(params, bindings, definition, prefix, errors) {\n if (!definition || !record3(params)) return;\n for (const [name, port] of Object.entries(definition.inputs ?? {})) {\n if (!port.enabledWhen || !effectInputEnabled(\n port,\n definition,\n params\n ))\n continue;\n const hasBinding = record3(bindings) && Object.prototype.hasOwnProperty.call(bindings, name);\n const hasTextureProperty = Object.entries(definition.properties).some(\n ([propertyName, property]) => property.type === "texture" && property.input === name && (Object.prototype.hasOwnProperty.call(params, propertyName) ? params[propertyName] !== null : property.default !== null)\n );\n if (!hasBinding && !hasTextureProperty)\n errors.push(\n `${prefix}.input-conditional-binding-required: ${name} needs a source in ${String(port.enabledWhen.equals)} mode`\n );\n }\n }\n function validateProperties(properties, prefix, errors, uniformPacking, uniformFloats) {\n if (!record3(properties)) {\n errors.push(`${prefix}.properties must be an object`);\n return;\n }\n const initialErrorCount = errors.length;\n if (Object.keys(properties).length > 64)\n errors.push(`${prefix}.properties must contain at most 64 entries`);\n for (const [name, unknownProp] of Object.entries(properties)) {\n if (!PROPERTY_RE.test(name))\n errors.push(`${prefix} property name "${name}" is invalid`);\n if (!record3(unknownProp)) {\n errors.push(`${prefix} property "${name}" must be an object`);\n continue;\n }\n const prop = unknownProp;\n if (![\n "float",\n "int",\n "bool",\n "enum",\n "color",\n "vec2",\n "position",\n "color-array",\n "color-ramp",\n "paint",\n "texture",\n "record-array"\n ].includes(prop.type)) {\n errors.push(`${prefix} property "${name}" has unsupported type`);\n continue;\n }\n if (typeof prop.label !== "string" || !prop.label.trim() || prop.label.length > 80) {\n errors.push(`${prefix} property "${name}" needs a label \\u2264 80 characters`);\n }\n if ("min" in prop && prop.min !== void 0 && !finite2(prop.min))\n errors.push(`${prefix} property "${name}" min must be finite`);\n if ("max" in prop && prop.max !== void 0 && !finite2(prop.max))\n errors.push(`${prefix} property "${name}" max must be finite`);\n if ("min" in prop && "max" in prop && prop.min !== void 0 && prop.max !== void 0 && prop.min > prop.max) {\n errors.push(`${prefix} property "${name}" min exceeds max`);\n }\n if ("step" in prop && prop.step !== void 0 && (!finite2(prop.step) || prop.step <= 0)) {\n errors.push(`${prefix} property "${name}" step must be positive`);\n }\n if ("displayScale" in prop && prop.displayScale !== void 0 && (!finite2(prop.displayScale) || prop.displayScale <= 0 || prop.displayScale > 1e6)) {\n errors.push(\n `${prefix} property "${name}" displayScale must be positive and finite`\n );\n }\n if ("defaultFrom" in prop && prop.defaultFrom !== void 0) {\n const source = typeof prop.defaultFrom === "string" ? properties[prop.defaultFrom] : void 0;\n if (prop.type !== "float" || typeof prop.defaultFrom !== "string" || !record3(source) || source.type !== "float" || source.defaultFrom !== void 0 || !finite2(source.default) || finite2(prop.min) && (!finite2(source.min) || source.min < prop.min) || finite2(prop.max) && (!finite2(source.max) || source.max > prop.max))\n errors.push(\n `${prefix} property "${name}" has an invalid default source`\n );\n }\n if (prop.type === "enum" && (!Array.isArray(prop.options) || !prop.options.length || prop.options.length > 32 || !prop.options.every(\n (option) => typeof option === "string" && !!option && option.length <= 80\n ) || new Set(prop.options).size !== prop.options.length)) {\n errors.push(`${prefix} property "${name}" needs distinct enum options`);\n }\n if (prop.type === "paint" && Object.keys(prop).some(\n (key) => ![\n "type",\n "label",\n "default",\n "maxCount",\n "allowedKinds",\n "group",\n "rebuild",\n "visibleWhen",\n "advanced"\n ].includes(key)\n ))\n errors.push(`${prefix} property "${name}" paint has unknown fields`);\n if (prop.type === "paint" && prop.allowedKinds !== void 0 && (!Array.isArray(prop.allowedKinds) || prop.allowedKinds.length < 1 || prop.allowedKinds.length > 5 || !Array.from(prop.allowedKinds).every(\n (kind) => ["solid", "linear", "radial", "angular", "diamond"].includes(kind)\n ) || new Set(prop.allowedKinds).size !== prop.allowedKinds.length))\n errors.push(\n `${prefix} property "${name}" needs distinct allowed paint kinds`\n );\n if (prop.type === "color-array" || prop.type === "color-ramp" || prop.type === "paint") {\n const maximum = prop.type === "paint" ? MAX_EFFECT_PAINT_STOPS : prop.type === "color-ramp" ? MAX_COLOR_RAMP : MAX_COLOR_ARRAY;\n if (!Number.isInteger(prop.maxCount) || prop.maxCount < 1 || prop.maxCount > maximum) {\n errors.push(\n `${prefix} property "${name}" maxCount must be 1\\u2013${maximum}`\n );\n continue;\n }\n }\n if (prop.type === "record-array") {\n if (Object.keys(prop).some(\n (key) => ![\n "type",\n "label",\n "itemLabel",\n "default",\n "minCount",\n "maxCount",\n "fields",\n "parameterConstraints",\n "group",\n "rebuild",\n "visibleWhen",\n "advanced"\n ].includes(key)\n ))\n errors.push(`${prefix} property "${name}" has unknown fields`);\n if (uniformPacking !== "compact" || !Number.isSafeInteger(prop.maxCount) || prop.maxCount < 1 || prop.maxCount > 4 || prop.minCount !== void 0 && (!Number.isSafeInteger(prop.minCount) || prop.minCount < 0 || prop.minCount > prop.maxCount) || prop.itemLabel !== void 0 && (typeof prop.itemLabel !== "string" || !prop.itemLabel.trim() || prop.itemLabel.length > 80))\n errors.push(`${prefix} property "${name}" has invalid record bounds`);\n if (!record3(prop.fields)) {\n errors.push(`${prefix} property "${name}" needs record fields`);\n } else {\n try {\n planNativeRecordLayout(prop.fields);\n } catch (error) {\n if (!(error instanceof NativeEffectPropertyLayoutError)) throw error;\n errors.push(`${prefix} property "${name}" ${error.message}`);\n }\n for (const [fieldName, field] of Object.entries(prop.fields)) {\n if (!record3(field)) continue;\n const allowed = field.type === "bool" || field.type === "color" ? ["type", "label", "default"] : [\n "type",\n "label",\n "default",\n "min",\n "max",\n "step",\n "displayScale",\n "unit"\n ];\n if (Object.keys(field).some((key) => !allowed.includes(key)))\n errors.push(\n `${prefix} property "${name}" field "${fieldName}" has unknown fields`\n );\n if (typeof field.label !== "string" || !field.label.trim() || field.label.length > 80)\n errors.push(\n `${prefix} property "${name}" field "${fieldName}" needs a label`\n );\n if (field.type === "float" || field.type === "int" || field.type === "vec2") {\n if (field.min !== void 0 && !finite2(field.min))\n errors.push(\n `${prefix} property "${name}" field "${fieldName}" min is invalid`\n );\n if (field.max !== void 0 && !finite2(field.max))\n errors.push(\n `${prefix} property "${name}" field "${fieldName}" max is invalid`\n );\n if (field.min !== void 0 && field.max !== void 0 && field.min > field.max)\n errors.push(\n `${prefix} property "${name}" field "${fieldName}" bounds are reversed`\n );\n if (field.step !== void 0 && (!finite2(field.step) || field.step <= 0))\n errors.push(\n `${prefix} property "${name}" field "${fieldName}" step is invalid`\n );\n if (field.displayScale !== void 0 && (!finite2(field.displayScale) || field.displayScale <= 0 || field.displayScale > 1e6))\n errors.push(\n `${prefix} property "${name}" field "${fieldName}" displayScale is invalid`\n );\n if (field.unit !== void 0 && (typeof field.unit !== "string" || field.unit.length > 32))\n errors.push(\n `${prefix} property "${name}" field "${fieldName}" unit is invalid`\n );\n }\n if (typeof field.type === "string" && ["float", "int", "bool", "vec2", "color"].includes(field.type))\n validateValue(\n field,\n field.default,\n `${name}.${fieldName}`,\n errors\n );\n }\n errors.push(\n ...validateParameterConstraintDefinitions(\n prop.parameterConstraints,\n prop.fields\n ).map((issue) => `${prefix} property "${name}" ${issue}`)\n );\n }\n }\n if (prop.type === "position" && prop.basis !== "source" && prop.basis !== "viewport")\n errors.push(`${prefix} property "${name}" needs a position basis`);\n if (prop.rebuild !== void 0 && typeof prop.rebuild !== "boolean")\n errors.push(`${prefix} property "${name}" rebuild must be boolean`);\n if (prop.advanced !== void 0 && typeof prop.advanced !== "boolean")\n errors.push(`${prefix} property "${name}" advanced must be boolean`);\n if (prop.group !== void 0 && (typeof prop.group !== "string" || prop.group.length > 80))\n errors.push(`${prefix} property "${name}" group is invalid`);\n if ("unit" in prop && prop.unit !== void 0 && (typeof prop.unit !== "string" || prop.unit.length > 32))\n errors.push(`${prefix} property "${name}" unit is invalid`);\n if (prop.type === "texture" && (typeof prop.input !== "string" || !PROPERTY_RE.test(prop.input)))\n errors.push(`${prefix} property "${name}" needs a named texture input`);\n if (prop.type !== "enum" || Array.isArray(prop.options))\n validateValue(prop, prop.default, name, errors);\n }\n for (const [name, candidate] of Object.entries(properties)) {\n if (!record3(candidate) || candidate.visibleWhen === void 0) continue;\n const condition = candidate.visibleWhen;\n if (!record3(condition) || typeof condition.property !== "string" || condition.property === name || !Object.prototype.hasOwnProperty.call(properties, condition.property)) {\n errors.push(\n `${prefix} property "${name}" has an invalid visibility condition`\n );\n continue;\n }\n const dependency = properties[condition.property];\n if (!record3(dependency) || !["bool", "enum", "int", "float"].includes(String(dependency.type)) || !["boolean", "string", "number"].includes(typeof condition.equals) || dependency.type === "bool" && typeof condition.equals !== "boolean" || dependency.type === "enum" && (!Array.isArray(dependency.options) || !dependency.options.includes(condition.equals)) || ["int", "float"].includes(String(dependency.type)) && (!finite2(condition.equals) || dependency.type === "int" && !Number.isInteger(condition.equals)))\n errors.push(\n `${prefix} property "${name}" visibility condition mismatches its dependency`\n );\n }\n for (const name of Object.keys(properties)) {\n const seen = /* @__PURE__ */ new Set();\n let current = name;\n while (true) {\n const property = properties[current];\n if (!record3(property) || !record3(property.visibleWhen)) break;\n const next = property.visibleWhen.property;\n if (typeof next !== "string" || !Object.prototype.hasOwnProperty.call(properties, next))\n break;\n if (seen.has(next) || next === name) {\n errors.push(`${prefix} property "${name}" has a visibility cycle`);\n break;\n }\n seen.add(next);\n current = next;\n }\n }\n if (errors.length === initialErrorCount) {\n try {\n planNativePropertyLayout({\n properties,\n uniformPacking,\n uniformFloats\n });\n } catch (error) {\n if (!(error instanceof NativeEffectPropertyLayoutError)) throw error;\n errors.push(`${prefix} ${error.message}`);\n }\n }\n }\n function validateDefinition(value, index, errors) {\n const prefix = `definition[${index}]`;\n if (!record3(value)) {\n errors.push(`${prefix} must be an object`);\n return false;\n }\n if (typeof value.id !== "string" || !ID_RE.test(value.id))\n errors.push(`${prefix}.id is invalid`);\n if (typeof value.name !== "string" || !value.name.trim() || value.name.length > 80)\n errors.push(`${prefix}.name is invalid`);\n if (!Number.isSafeInteger(value.version) || value.version < 1) {\n errors.push(`${prefix}.version must be a positive integer`);\n }\n if (!["generator", "processor", "simulation"].includes(String(value.kind)))\n errors.push(`${prefix}.kind is invalid`);\n if (value.uniformPacking !== void 0 && value.uniformPacking !== "compact")\n errors.push(`${prefix}.uniformPacking must be compact when present`);\n if (value.uniformFloats !== void 0 && value.uniformFloats !== 256)\n errors.push(`${prefix}.uniformFloats must be 256 when present`);\n if (value.uniformFloats === 256 && value.uniformPacking !== "compact")\n errors.push(`${prefix}.uniformFloats needs compact uniformPacking`);\n if (value.sourceSizing !== void 0 && (value.kind !== "processor" || !record3(value.sourceSizing) || Object.keys(value.sourceSizing).some(\n (key) => key !== "uv" && key !== "intrinsicEncoding" && key !== "defaultSampling"\n ) || value.sourceSizing.uv !== "paper-image" || value.sourceSizing.intrinsicEncoding !== void 0 && value.sourceSizing.intrinsicEncoding !== "srgb-encoded-straight" || value.sourceSizing.defaultSampling !== void 0 && (!record3(value.sourceSizing.defaultSampling) || Object.keys(value.sourceSizing.defaultSampling).length !== 3 || value.sourceSizing.defaultSampling.min !== "linear" || value.sourceSizing.defaultSampling.mag !== "linear" || value.sourceSizing.defaultSampling.mipmap !== "linear" || value.sourceSizing.intrinsicEncoding !== "srgb-encoded-straight") || !Array.isArray(value.passes) || value.passes.length !== 1 || value.passes[0]?.kind !== "render" || !value.passes[0]?.reads?.includes("source")))\n errors.push(\n `${prefix}.sourceSizing ABI needs one source-reading processor render pass`\n );\n if (record3(value.sourceSizing) && value.sourceSizing.intrinsicEncoding === "srgb-encoded-straight") {\n const source = Array.isArray(value.resources) ? value.resources.find(\n (resource) => record3(resource) && resource.name === "source"\n ) : void 0;\n if (!record3(source) || source.kind !== "texture-2d" || source.external !== true || source.sampleEncoding !== "srgb-encoded-straight")\n errors.push(\n `${prefix}.sourceSizing intrinsic source needs an encoded-straight external texture`\n );\n }\n if (value.optionalImage !== void 0) {\n if (value.sourceSizing !== void 0)\n errors.push(`${prefix}.optionalImage cannot share sourceSizing UV rows`);\n if (["imageMeta", "imagePresent", "intrinsicAspect"].some(\n (key) => Object.prototype.hasOwnProperty.call(value, key)\n ))\n errors.push(`${prefix}.optionalImage metadata is runtime-resolved`);\n const contract = value.optionalImage;\n const imageInput = record3(value.inputs) ? value.inputs.image : void 0;\n const imageResource = Array.isArray(value.resources) ? value.resources.find(\n (resource) => record3(resource) && resource.name === "image"\n ) : void 0;\n const noiseInput = record3(value.inputs) ? value.inputs.noise : void 0;\n const noiseResource = Array.isArray(value.resources) ? value.resources.find(\n (resource) => record3(resource) && resource.name === "noise"\n ) : void 0;\n const imageProperties = record3(value.properties) ? Object.values(value.properties).filter(\n (property) => record3(property) && property.type === "texture" && property.input === "image"\n ) : [];\n const imageSizingProperties = record3(value.properties) ? value.properties : {};\n const fitProperty = imageSizingProperties.fit;\n const fitOptions = record3(fitProperty) && Array.isArray(fitProperty.options) ? fitProperty.options : null;\n const sizedFloat = (name, min, max) => {\n const property = imageSizingProperties[name];\n return record3(property) && property.type === "float" && finite2(property.default) && property.default >= min && property.default <= max && finite2(property.min) && property.min >= min && finite2(property.max) && property.max <= max;\n };\n const imageSizingValid = record3(fitProperty) && fitProperty.type === "enum" && fitOptions?.length === 3 && ["none", "contain", "cover"].every(\n (option) => fitOptions.includes(option)\n ) && sizedFloat("scale", 0.01, 8) && sizedFloat("rotation", 0, 360) && sizedFloat("originX", 0, 1) && sizedFloat("originY", 0, 1) && sizedFloat("offsetX", -1, 1) && sizedFloat("offsetY", -1, 1);\n const readsImage = Array.isArray(value.passes) && value.passes.length === 1 && value.passes[0]?.kind === "render" && Array.isArray(value.passes[0]?.reads) && value.passes[0].reads[0] === "image" && value.passes[0].reads.length <= 2;\n const secondRead = Array.isArray(value.passes) && Array.isArray(value.passes[0]?.reads) ? value.passes[0].reads[1] : void 0;\n const noiseValid = secondRead === void 0 || secondRead === "noise" && record3(noiseInput) && noiseInput.kind === "texture-2d" && noiseInput.resource === "noise" && noiseInput.fallback === void 0 && record3(noiseResource) && noiseResource.kind === "texture-2d" && noiseResource.external === true && noiseResource.sampleEncoding === "linear-data" && noiseResource.preprocess === void 0 && noiseResource.mipmap === void 0;\n if (!record3(contract) || Object.keys(contract).length !== 2 || contract.port !== "image" || contract.abi !== "paper-optional-image-v1" || value.kind !== "generator" || !record3(imageInput) || imageInput.kind !== "texture-2d" || imageInput.resource !== "image" || imageInput.optional !== true || imageInput.fallback !== "transparent-data" || !record3(imageResource) || imageResource.kind !== "texture-2d" || imageResource.external !== true || !((imageResource.sampleEncoding === "srgb-encoded-straight" || imageResource.sampleEncoding === "linear-data") && (imageResource.preprocess === void 0 || imageResource.sampleEncoding === "linear-data" && imageResource.preprocess === "paper-gem-smoke-mask-32" && imageResource.mipmap === "generated")) || imageProperties.length !== 1 || !record3(imageProperties[0]) || imageProperties[0].default !== null || !imageSizingValid || !readsImage || !noiseValid)\n errors.push(\n `${prefix}.optionalImage needs one optional image asset input and one image-reading render pass`\n );\n }\n if (value.optionalImage === void 0 && Array.isArray(value.resources) && value.resources.some(\n (resource) => record3(resource) && resource.name === "image" && (resource.sampleEncoding === "srgb-encoded-straight" || resource.sampleEncoding === "linear-data")\n ))\n errors.push(`${prefix}.image resource needs the optional-image ABI`);\n if (!Array.isArray(value.placements) || !value.placements.length || !value.placements.every(\n (placement) => ["fill", "layer", "backdrop"].includes(placement)\n ) || new Set(value.placements).size !== value.placements.length)\n errors.push(`${prefix}.placements are invalid`);\n if (value.extent !== void 0) {\n const extent = value.extent;\n if (!record3(extent) || Object.keys(extent).some((key) => key !== "source" && key !== "output") || !Object.keys(extent).length) {\n errors.push(`${prefix}.extent is invalid`);\n } else {\n for (const [kind, insets] of Object.entries(extent)) {\n if (!record3(insets) || Object.keys(insets).length !== 4 || ["top", "right", "bottom", "left"].some(\n (side) => !Object.prototype.hasOwnProperty.call(insets, side) || typeof insets[side] !== "number" || !Number.isFinite(insets[side]) || insets[side] < 0 || insets[side] > 128\n ))\n errors.push(\n `${prefix}.extent.${kind} needs four bounded CSS-pixel sides`\n );\n }\n }\n }\n if (value.statelessCompute !== void 0) {\n if (!record3(value.statelessCompute) || value.statelessCompute.abi !== "source-buffer-v1" || value.kind !== "processor" || value.simulation !== void 0 || value.feedback !== void 0 || value.extent !== void 0 || value.sourceSizing !== void 0 || value.optionalImage !== void 0)\n errors.push(\n `${prefix}.statelessCompute: stateless-compute-definition-invalid`\n );\n if (record3(value.statelessCompute) && Array.isArray(value.passes) && record3(value.properties)) {\n const dispatch = value.passes[0]?.dispatch;\n if (isStatelessComputeDispatch(dispatch) && dispatch.elements === "source-row-blocks") {\n const property = value.properties[dispatch.blockProperty];\n if (!record3(property) || property.type !== "int" || typeof property.min !== "number" || property.min < 1 || typeof property.max !== "number" || property.max > 16)\n errors.push(\n `${prefix}.statelessCompute: stateless-compute-definition-invalid`\n );\n }\n }\n }\n if (value.resourceGraph !== void 0 && (!record3(value.resourceGraph) || value.resourceGraph.abi !== "stateful-resource-v1" && value.resourceGraph.abi !== "stateful-resource-v2" && value.resourceGraph.abi !== "stateful-resource-v3" && (value.resourceGraph.abi !== "linear-resource-v1" || Object.keys(value.resourceGraph).length !== 1) || value.kind === "simulation" || value.feedback !== void 0 || value.statelessCompute !== void 0 || value.simulation !== void 0 || value.optionalImage !== void 0 || value.sourceSizing !== void 0))\n errors.push(`${prefix}.resourceGraph: linear-resource-definition-invalid`);\n if (value.simulation !== void 0) {\n const simulation = value.simulation;\n const count = record3(simulation) ? simulation.count : void 0;\n const tiers = record3(count) ? count.tiers : void 0;\n const boundedCount = record3(count) && (Object.prototype.hasOwnProperty.call(count, "min") || Object.prototype.hasOwnProperty.call(count, "max"));\n const idlePointer = record3(simulation) ? simulation.idlePointer : void 0;\n const stateResource = record3(simulation) && Array.isArray(value.resources) ? value.resources?.find(\n (resource) => record3(resource) && resource.name === simulation.stateResource\n ) : void 0;\n const countProperty = record3(simulation) && record3(count) && record3(value.properties) ? value.properties[String(count.property)] : void 0;\n if (value.kind !== "simulation" || !record3(simulation) || Object.keys(simulation).some(\n (key) => ![\n "fixedDt",\n "stateResource",\n "bytesPerParticle",\n "count",\n "maxInteractiveSteps",\n "maxDeterministicSteps",\n "idlePointer"\n ].includes(key)\n ) || simulation.fixedDt !== 1 / 120 || simulation.bytesPerParticle !== 32 || simulation.maxInteractiveSteps !== 8 || simulation.maxDeterministicSteps !== 512 || !record3(count) || (boundedCount ? Object.keys(count).some(\n (key) => key !== "property" && key !== "min" && key !== "max"\n ) || !Number.isSafeInteger(count.min) || !Number.isSafeInteger(count.max) || count.min < 1 || count.max > 5e4 || count.min > count.max || !record3(countProperty) || countProperty.type !== "int" || countProperty.min !== count.min || countProperty.max !== count.max || countProperty.step !== 1 || !Number.isSafeInteger(countProperty.default) || countProperty.default < count.min || countProperty.default > count.max : Object.keys(count).some(\n (key) => key !== "property" && key !== "tiers"\n ) || !record3(tiers) || Object.keys(tiers).length !== 3 || tiers.low !== 1e4 || tiers.medium !== 25e3 || tiers.high !== 5e4 || !record3(countProperty) || countProperty.type !== "enum" || !Array.isArray(countProperty.options) || !["low", "medium", "high"].every(\n (tier) => countProperty.options.includes(tier)\n )) || !record3(idlePointer) || Object.keys(idlePointer).length !== 2 || ![idlePointer.x, idlePointer.y].every(\n (coordinate) => typeof coordinate === "number" && Number.isFinite(coordinate) && coordinate >= 0 && coordinate <= 1\n ) || stateResource?.kind !== "buffer" || !stateResource.persistent || !stateResource.usage?.includes("storage") || !stateResource.byteLength || stateResource.byteLength < (boundedCount ? count.max : 5e4) * 32 || stateResource.byteLength > 16777216)\n errors.push(`${prefix}.simulation is invalid or unbounded`);\n } else if (value.kind === "simulation") {\n errors.push(`${prefix}.simulation is required`);\n }\n if (value.feedback !== void 0) {\n const feedback = value.feedback;\n const grid = record3(feedback) ? feedback.grid : void 0;\n const timing = record3(feedback) ? feedback.timing : void 0;\n const properties = record3(value.properties) ? value.properties : {};\n const boundedFloat = (name, min, max) => {\n const property = properties[name];\n return record3(property) && property.type === "float" && property.min === min && property.max === max && finite2(property.default) && property.default >= min && property.default <= max;\n };\n const uniformProperties = record3(feedback) && record3(feedback.uniformProperties) ? feedback.uniformProperties : void 0;\n const aliasesValid = uniformProperties === void 0 || Object.keys(uniformProperties).every(\n (slot) => FEEDBACK_UNIFORM_SLOTS.includes(\n slot\n ) && typeof uniformProperties[slot] === "string" && PROPERTY_RE.test(uniformProperties[slot])\n ) && new Set(\n FEEDBACK_UNIFORM_SLOTS.map((slot) => uniformProperties[slot] ?? slot)\n ).size === FEEDBACK_UNIFORM_SLOTS.length;\n const resolvedProperties = aliasesValid && record3(feedback) ? feedbackUniformProperties(feedback) : void 0;\n const resetProperties = record3(feedback) && feedback.resetProperties !== void 0 ? feedback.resetProperties : void 0;\n const resetPropertiesValid = resetProperties === void 0 || Array.isArray(resetProperties) && resetProperties.length <= 16 && new Set(resetProperties).size === resetProperties.length && resetProperties.every((name) => {\n if (typeof name !== "string" || !PROPERTY_RE.test(name) || !record3(value.properties) || !Object.prototype.hasOwnProperty.call(value.properties, name))\n return false;\n const property = value.properties[name];\n return record3(property) && ["float", "int"].includes(String(property.type)) && finite2(property.default);\n });\n const feedbackKeysValid = !record3(feedback) || Object.keys(feedback).every(\n (key) => [\n "abi",\n "grid",\n "timing",\n "stateResource",\n "displayResource",\n "uniformProperties",\n "resetProperties",\n "sourceHistory",\n "resolveDraw",\n "pointer"\n ].includes(key)\n ) && ["abi", "grid", "timing", "stateResource", "displayResource"].every(\n (key) => Object.prototype.hasOwnProperty.call(feedback, key)\n );\n if (value.kind !== "processor" || !Array.isArray(value.placements) || !value.placements.every(\n (placement) => ["layer", "backdrop"].includes(String(placement))\n ) || value.simulation !== void 0 || value.optionalImage !== void 0 || value.sourceSizing !== void 0 || !record3(feedback) || !feedbackKeysValid || Object.keys(feedback).length !== (uniformProperties === void 0 ? 5 : 6) + (resetProperties === void 0 ? 0 : 1) + (feedback.sourceHistory === void 0 ? 0 : 1) + (feedback.resolveDraw === void 0 ? 0 : 1) + (feedback.pointer === void 0 ? 0 : 1) || !resetPropertiesValid || !aliasesValid || feedback.abi !== "texture-feedback-v1" || feedback.sourceHistory !== void 0 && feedback.sourceHistory !== "sequential-captures" || feedback.pointer !== void 0 && feedback.pointer !== "interaction-v1" || feedback.pointer !== void 0 && value.interaction === void 0 || feedback.resolveDraw !== void 0 && (!record3(feedback.resolveDraw) || Object.keys(feedback.resolveDraw).length !== 2 || feedback.resolveDraw.vertices !== 6 || !Number.isSafeInteger(feedback.resolveDraw.instances) || feedback.resolveDraw.instances < 1 || feedback.resolveDraw.instances > 256) || !record3(grid) || Object.keys(grid).length !== 4 || !Number.isSafeInteger(grid.width) || !Number.isSafeInteger(grid.height) || grid.width < 1 || grid.height < 1 || grid.width > 2048 || grid.height > 2048 || grid.width * grid.height > 2097152 || grid.format !== "rgba16float" || !Array.isArray(grid.workgroup) || grid.workgroup.length !== 2 || grid.workgroup[0] !== 8 || grid.workgroup[1] !== 8 || !record3(timing) || Object.keys(timing).length !== 3 || !finite2(timing.fixedDt) || timing.fixedDt < 1 / 240 || timing.fixedDt > 1 / 15 || !Number.isSafeInteger(timing.maxStepsPerCall) || timing.maxStepsPerCall < 1 || timing.maxStepsPerCall > 512 || !Number.isSafeInteger(timing.maxStepIndex) || timing.maxStepIndex < 0 || timing.maxStepIndex > 36e3 || typeof feedback.stateResource !== "string" || !PROPERTY_RE.test(feedback.stateResource) || typeof feedback.displayResource !== "string" || !PROPERTY_RE.test(feedback.displayResource) || feedback.stateResource === feedback.displayResource || !boundedFloat(resolvedProperties?.intensity ?? "intensity", 0, 1) || !boundedFloat(resolvedProperties?.blockSize ?? "blockSize", 30, 150) || !boundedFloat(resolvedProperties?.drift ?? "drift", 0, 1) || !boundedFloat(resolvedProperties?.churn ?? "churn", 0, 1) || !boundedFloat(resolvedProperties?.blend ?? "blend", 0, 1) || uniformProperties !== void 0 && !boundedFloat(resolvedProperties?.seed ?? "seed", 0, 100))\n errors.push(`${prefix}.feedback is invalid or unbounded`);\n }\n validateProperties(\n value.properties,\n prefix,\n errors,\n value.uniformPacking === "compact" ? "compact" : void 0,\n value.uniformFloats === 256 ? 256 : void 0\n );\n if (value.interaction !== void 0) {\n const interaction = value.interaction;\n const properties = record3(value.properties) ? value.properties : {};\n const position = record3(interaction) && typeof interaction.positionProperty === "string" ? properties[interaction.positionProperty] : void 0;\n const active = record3(interaction) && typeof interaction.activeProperty === "string" ? properties[interaction.activeProperty] : void 0;\n if (!record3(interaction) || Object.keys(interaction).length !== 2 || value.kind === "simulation" || value.feedback !== void 0 && (!record3(value.feedback) || value.feedback.pointer !== "interaction-v1") || typeof interaction.positionProperty !== "string" || typeof interaction.activeProperty !== "string" || !PROPERTY_RE.test(interaction.positionProperty) || !PROPERTY_RE.test(interaction.activeProperty) || !Object.prototype.hasOwnProperty.call(\n properties,\n interaction.positionProperty\n ) || !Object.prototype.hasOwnProperty.call(\n properties,\n interaction.activeProperty\n ) || !record3(position) || position.type !== "vec2" || position.rebuild === true || position.min !== void 0 && (typeof position.min !== "number" || position.min > 0) || position.max !== void 0 && (typeof position.max !== "number" || position.max < 1) || !record3(active) || active.type !== "bool" || active.rebuild === true)\n errors.push(\n `${prefix}.interaction needs existing vec2 position and bool active properties`\n );\n }\n errors.push(\n ...validateParameterConstraintDefinitions(\n value.parameterConstraints,\n value.properties\n ).map((error) => `${prefix}.${error}`)\n );\n const provenance = value.provenance;\n if (!record3(provenance) || !["design-original", "user-authored", "imported"].includes(\n String(provenance.origin)\n ) || provenance.note !== void 0 && (typeof provenance.note !== "string" || provenance.note.length > 240)) {\n errors.push(`${prefix}.provenance is invalid`);\n } else if (provenance.origin === "imported" && !validImportedUpstream(provenance.upstream)) {\n errors.push(\n `${prefix}.provenance imported source needs repository, commit, file, and license`\n );\n }\n validatePorts(\n value.inputs,\n `${prefix}.inputs`,\n value.resources,\n errors,\n true,\n record3(value.optionalImage) && value.optionalImage.port === "image" ? "image" : void 0,\n value.properties\n );\n validatePorts(\n value.outputs,\n `${prefix}.outputs`,\n value.resources,\n errors,\n false\n );\n if (record3(value.resourceGraph) && (value.resourceGraph.abi === "stateful-resource-v2" || value.resourceGraph.abi === "stateful-resource-v3")) {\n const external = (Array.isArray(value.resources) ? value.resources : []).filter((resource) => resource.external).map((resource) => resource.name);\n const bound = Object.values(value.inputs ?? {}).filter((port) => port.kind === "texture-2d").map((port) => port.resource);\n if (value.resourceGraph.abi === "stateful-resource-v2" && external.length < 2 || external.length > 4 || bound.length !== external.length || new Set(bound).size !== external.length || external.some((name) => !bound.includes(name)))\n errors.push(\n `${prefix}.resourceGraph needs an exact named input for each external texture`\n );\n }\n if (record3(value.properties))\n for (const [name, candidate] of Object.entries(value.properties)) {\n if (!record3(candidate) || candidate.type !== "texture") continue;\n const port = record3(value.inputs) && typeof candidate.input === "string" ? value.inputs[candidate.input] : void 0;\n if (!record3(port) || !["texture-2d", "mask"].includes(String(port.kind)))\n errors.push(\n `${prefix} texture property "${name}" needs a matching texture or mask input`\n );\n }\n if (value.output !== void 0 && (typeof value.output !== "string" || record3(value.outputs) && !Object.values(value.outputs).some(\n (port) => record3(port) && port.resource === value.output\n ))) {\n errors.push(`${prefix}.output needs a matching named output port`);\n }\n if (!Array.isArray(value.passes) || !value.passes.length || value.passes.length > 16) {\n errors.push(`${prefix}.passes must contain 1\\u201316 passes`);\n } else {\n if (value.simulation) {\n const computePasses = value.passes.filter(\n (pass) => pass.kind === "compute"\n );\n const renderPasses = value.passes.filter(\n (pass) => pass.kind === "render"\n );\n const stateName = record3(value.simulation) ? value.simulation.stateResource : void 0;\n if (computePasses.length !== 1 || renderPasses.length !== 2 || computePasses[0]?.output !== stateName || !computePasses[0]?.previousFrameReads?.includes(String(stateName)) || !renderPasses[0]?.reads.includes(String(stateName)) || !renderPasses[0]?.draw || !!renderPasses[1]?.draw || !renderPasses[1]?.reads.includes(renderPasses[0].output) || !renderPasses[1]?.previousFrameReads?.includes(\n renderPasses[1].output\n ) || value.output !== renderPasses[1]?.output)\n errors.push(\n `${prefix}.simulation needs state compute, instanced particles, and a persistent trail pass`\n );\n } else if (!value.feedback && !value.statelessCompute && !value.resourceGraph && value.passes.some(\n (pass) => pass.dispatch || pass.draw || pass.additionalOutputs\n )) {\n errors.push(\n `${prefix}.passes use compute dispatch, draw, or extra outputs without an opt-in ABI`\n );\n }\n for (const [passIndex, pass] of value.passes.entries()) {\n if (!record3(pass) || typeof pass.id !== "string" || typeof pass.output !== "string" || typeof pass.wgsl !== "string" || !pass.wgsl.trim() || pass.wgsl.length > 32e3 || !Array.isArray(pass.reads) || pass.reads.length > 16 || !pass.reads.every((read) => typeof read === "string") || new Set(pass.reads).size !== pass.reads.length || pass.previousFrameReads !== void 0 && (!Array.isArray(pass.previousFrameReads) || pass.previousFrameReads.length > 16 || !pass.previousFrameReads.every(\n (read) => typeof read === "string"\n ) || new Set(pass.previousFrameReads).size !== pass.previousFrameReads.length) || pass.persistent !== void 0 && typeof pass.persistent !== "boolean" || pass.additionalOutputs !== void 0 && (!Array.isArray(pass.additionalOutputs) || pass.additionalOutputs.length !== 1 || !pass.additionalOutputs.every(\n (output) => typeof output === "string"\n )) || pass.dispatch !== void 0 && (!record3(pass.dispatch) || !isStatelessComputeDispatch(pass.dispatch) && !isLinearResourceDispatch(pass.dispatch) && Object.keys(pass.dispatch).length !== 2 || pass.kind !== "compute" || !(pass.dispatch.workgroupSize === 256 && pass.dispatch.elements === "simulation-count" || value.feedback && Array.isArray(pass.dispatch.workgroupSize) && pass.dispatch.workgroupSize.length === 2 && pass.dispatch.workgroupSize[0] === 8 && pass.dispatch.workgroupSize[1] === 8 && pass.dispatch.elements === "fixed-grid" || value.statelessCompute && isStatelessComputeDispatch(pass.dispatch) || value.resourceGraph && isLinearResourceDispatch(pass.dispatch))) || pass.draw !== void 0 && (!record3(pass.draw) || Object.keys(pass.draw).length !== 2 || pass.kind !== "render" || pass.draw.vertices !== 6 || pass.draw.instances !== "simulation-count" && !(record3(value.resourceGraph) && (value.resourceGraph.abi === "stateful-resource-v1" || value.resourceGraph.abi === "stateful-resource-v2" || value.resourceGraph.abi === "stateful-resource-v3") && isStatefulResourceDraw(pass.draw))) || pass.mesh !== void 0 && !isEffectMeshPassCompatible(\n pass,\n value.feedback !== void 0 || value.simulation !== void 0 || value.statelessCompute !== void 0 || value.resourceGraph !== void 0\n )) {\n errors.push(`${prefix}.passes[${passIndex}] is malformed`);\n } else {\n if (pass.original !== void 0) {\n if (!record3(pass.original))\n errors.push(\n `${prefix}.passes[${passIndex}] retired original metadata is invalid`\n );\n }\n if (value.simulation && pass.kind === "compute" && !pass.dispatch)\n errors.push(`${prefix}.passes[${passIndex}] needs bounded dispatch`);\n if (pass.kind === "render" && pass.original === void 0 && (!/@vertex\\s+fn\\s+vs\\s*\\(/.test(pass.wgsl) || !/@fragment\\s+fn\\s+fs\\s*\\(/.test(pass.wgsl))) {\n errors.push(\n `${prefix}.passes[${passIndex}] must expose vertex vs and fragment fs`\n );\n }\n if (pass.kind === "compute" && !/@compute(?:\\s*@workgroup_size\\s*\\([^)]*\\))?\\s+fn\\s+cs\\s*\\(/.test(\n pass.wgsl\n )) {\n errors.push(`${prefix}.passes[${passIndex}] must expose compute cs`);\n }\n }\n }\n const hasRetiredExecution = value.passes.some((pass) => pass.original !== void 0) || Array.isArray(value.resources) && value.resources.some(\n (resource) => resource.preprocess !== void 0\n );\n if ((!hasRetiredExecution || value.statelessCompute !== void 0) && !errors.some((error) => error.startsWith(`${prefix}.passes[`))) {\n errors.push(\n ...planEffectGraph(\n value\n ).errors.map((error) => `${prefix}: ${error}`)\n );\n }\n }\n return !errors.some((error) => error.startsWith(prefix));\n }\n function validateInstance(value, index, definitions, errors) {\n const prefix = `instance[${index}]`;\n if (!record3(value)) {\n errors.push(`${prefix} must be an object`);\n return false;\n }\n if (typeof value.id !== "string" || !ID_RE.test(value.id))\n errors.push(`${prefix}.id is invalid`);\n if (typeof value.nodeId !== "string" || !ID_RE.test(value.nodeId))\n errors.push(`${prefix}.nodeId is invalid`);\n const definition = definitions.get(\n definitionKey(String(value.definitionId), Number(value.definitionVersion))\n );\n if (!definition)\n errors.push(\n `${prefix}.definitionId and definitionVersion have no matching definition`\n );\n if (definition?.optionalImage && ["imageMeta", "imagePresent", "intrinsicAspect"].some(\n (key) => Object.prototype.hasOwnProperty.call(value, key)\n ))\n errors.push(`${prefix}.optionalImage metadata is runtime-resolved`);\n if (!Number.isSafeInteger(value.definitionVersion) || value.definitionVersion < 1)\n errors.push(`${prefix}.definitionVersion must be a positive integer`);\n if (!["fill", "layer", "backdrop"].includes(String(value.placement)) || definition && !definition.placements.includes(\n value.placement\n )) {\n errors.push(`${prefix}.placement is not supported by its definition`);\n }\n if (!record3(value.params)) errors.push(`${prefix}.params must be an object`);\n else if (definition && record3(definition.properties)) {\n for (const [name, param] of Object.entries(value.params)) {\n const prop = Object.prototype.hasOwnProperty.call(\n definition.properties,\n name\n ) ? definition.properties[name] : void 0;\n if (!prop)\n errors.push(`${prefix}.params contains unknown property "${name}"`);\n else validateValue(prop, param, name, errors);\n }\n }\n if (typeof value.enabled !== "boolean")\n errors.push(`${prefix}.enabled must be boolean`);\n if (!finiteUnit(value.opacity))\n errors.push(`${prefix}.opacity must be within 0\\u20131`);\n if (typeof value.seed !== "number" || !Number.isSafeInteger(value.seed) || value.seed < 0 || value.seed > 1e6)\n errors.push(`${prefix}.seed must be an integer within 0\\u20131000000`);\n if (value.clip !== "bounds" && value.clip !== "text")\n errors.push(`${prefix}.clip is invalid`);\n if (value.placement === "backdrop" && value.clip === "text")\n errors.push(`${prefix}.clip: backdrop-text-replacement-unsupported`);\n if (value.blend !== "normal") errors.push(`${prefix}.blend must be normal`);\n if (!record3(value.timing) || !isFiniteNativeUniformTiming(value.timing.speed) || value.timing.speed < 0 || typeof value.timing.paused !== "boolean" || !isFiniteNativeUniformTiming(value.timing.time) || value.timing.time < 0 || value.timing.seekRevision !== void 0 && (typeof value.timing.seekRevision !== "number" || !Number.isSafeInteger(value.timing.seekRevision) || value.timing.seekRevision < 0)) {\n errors.push(`${prefix}.timing is invalid`);\n }\n if (definition)\n errors.push(\n ...validateNativeParameterAnimation(\n definition,\n value.animation,\n validateValue\n ).map((error) => `${prefix}.${error}`)\n );\n if (definition && record3(value.params))\n errors.push(\n ...validateResolvedParameterConstraints(\n definition.parameterConstraints,\n definition.properties,\n value.params\n ).map((error) => `${prefix}.${error}`)\n );\n validateBindings(value.bindings, definition, prefix, errors);\n validateConditionalInputs(\n value.params,\n value.bindings,\n definition,\n prefix,\n errors\n );\n validateTransform(value.transform, prefix, errors);\n validateSourceSizing(value.sourceSizing, definition, prefix, errors);\n validateTextureBindingConflicts(\n value.params,\n value.bindings,\n definition,\n prefix,\n errors\n );\n return !errors.some((error) => error.startsWith(prefix));\n }\n function validatePreset(value, index, definitions, errors) {\n const prefix = `preset[${index}]`;\n if (!record3(value)) {\n errors.push(`${prefix} must be an object`);\n return false;\n }\n if (typeof value.id !== "string" || !ID_RE.test(value.id))\n errors.push(`${prefix}.id is invalid`);\n if (typeof value.name !== "string" || !value.name.trim() || value.name.length > 80)\n errors.push(`${prefix}.name is invalid`);\n if (!Number.isSafeInteger(value.definitionVersion) || value.definitionVersion < 1)\n errors.push(`${prefix}.definitionVersion must be a positive integer`);\n const definition = definitions.get(\n definitionKey(String(value.definitionId), Number(value.definitionVersion))\n );\n if (!definition)\n errors.push(\n `${prefix}.definitionId and definitionVersion have no matching definition`\n );\n if (definition?.optionalImage && ["imageMeta", "imagePresent", "intrinsicAspect"].some(\n (key) => Object.prototype.hasOwnProperty.call(value, key)\n ))\n errors.push(`${prefix}.optionalImage metadata is runtime-resolved`);\n if (!["fill", "layer", "backdrop"].includes(String(value.placement)) || definition && !definition.placements.includes(\n value.placement\n ))\n errors.push(`${prefix}.placement is not supported by its definition`);\n if (value.clip !== "bounds" && value.clip !== "text")\n errors.push(`${prefix}.clip is invalid`);\n if (value.placement === "backdrop" && value.clip === "text")\n errors.push(`${prefix}.clip: backdrop-text-replacement-unsupported`);\n if (!record3(value.provenance) || !["design-original", "imported", "user-authored"].includes(\n String(value.provenance.origin)\n ))\n errors.push(`${prefix}.provenance is invalid`);\n if (value.timing !== void 0 && (!record3(value.timing) || !isFiniteNativeUniformTiming(value.timing.speed) || value.timing.speed < 0 || typeof value.timing.paused !== "boolean" || !isFiniteNativeUniformTiming(value.timing.time) || value.timing.time < 0 || Object.keys(value.timing).some(\n (key) => !["speed", "paused", "time"].includes(key)\n )))\n errors.push(`${prefix}.timing is invalid`);\n if (definition)\n errors.push(\n ...validateNativeParameterAnimation(\n definition,\n value.animation,\n validateValue\n ).map((error) => `${prefix}.${error}`)\n );\n if (!record3(value.params)) {\n errors.push(`${prefix}.params must be an object`);\n } else if (definition && record3(definition.properties)) {\n for (const [name, param] of Object.entries(value.params)) {\n const prop = Object.prototype.hasOwnProperty.call(\n definition.properties,\n name\n ) ? definition.properties[name] : void 0;\n if (!prop)\n errors.push(`${prefix}.params contains unknown property "${name}"`);\n else {\n const valueErrors = [];\n validateValue(prop, param, name, valueErrors);\n errors.push(...valueErrors.map((error) => `${prefix}.params ${error}`));\n }\n }\n }\n if (definition && record3(value.params))\n errors.push(\n ...validateResolvedParameterConstraints(\n definition.parameterConstraints,\n definition.properties,\n value.params\n ).map((error) => `${prefix}.${error}`)\n );\n validateBindings(value.bindings, definition, prefix, errors);\n validateConditionalInputs(\n value.params,\n value.bindings,\n definition,\n prefix,\n errors\n );\n validateTransform(value.transform, prefix, errors);\n validateSourceSizing(value.sourceSizing, definition, prefix, errors);\n validateTextureBindingConflicts(\n value.params,\n value.bindings,\n definition,\n prefix,\n errors\n );\n return !errors.some((error) => error.startsWith(prefix));\n }\n function validateEffectDocument(value) {\n const errors = [];\n if (!record3(value))\n return { valid: false, errors: ["effect document must be an object"] };\n if (value.schemaVersion !== NATIVE_EFFECT_SCHEMA_VERSION)\n errors.push("effect schemaVersion must be 2");\n if (!Array.isArray(value.definitions) || value.definitions.length > 64)\n errors.push("definitions must be an array of at most 64");\n if (!Array.isArray(value.instances) || value.instances.length > 256)\n errors.push("instances must be an array of at most 256");\n if (value.presets !== void 0 && (!Array.isArray(value.presets) || value.presets.length > 128))\n errors.push("presets must be an array of at most 128");\n if (value.preview !== void 0) {\n if (!record3(value.preview) || Object.keys(value.preview).some(\n (key) => key !== "quality" && key !== "frameRateTarget" && key !== "colorMode" && key !== "dynamicRange"\n ) || !["auto", "performance", "quality"].includes(\n value.preview.quality\n ) || value.preview.frameRateTarget !== 60 && value.preview.frameRateTarget !== 120 || value.preview.colorMode !== void 0 && value.preview.colorMode !== "srgb" && value.preview.colorMode !== "display-p3" || value.preview.dynamicRange !== void 0 && value.preview.dynamicRange !== "sdr" && value.preview.dynamicRange !== "hdr")\n errors.push(\n "preview must specify quality and a 60 or 120 frameRateTarget, with supported optional output modes"\n );\n }\n const definitions = /* @__PURE__ */ new Map();\n if (Array.isArray(value.definitions))\n for (const [index, definition] of value.definitions.entries()) {\n if (validateDefinition(definition, index, errors)) {\n const key = definitionKey(definition.id, definition.version);\n if (definitions.has(key))\n errors.push(\n `duplicate definition id/version "${definition.id}" v${definition.version}`\n );\n definitions.set(key, definition);\n }\n }\n const instanceIds = /* @__PURE__ */ new Set();\n if (Array.isArray(value.instances))\n for (const [index, instance] of value.instances.entries()) {\n if (validateInstance(instance, index, definitions, errors)) {\n if (instanceIds.has(instance.id))\n errors.push(`duplicate instance id "${instance.id}"`);\n instanceIds.add(instance.id);\n }\n }\n const presetIds = /* @__PURE__ */ new Set();\n if (Array.isArray(value.presets))\n for (const [index, preset] of value.presets.entries()) {\n if (validatePreset(preset, index, definitions, errors)) {\n if (presetIds.has(preset.id))\n errors.push(`duplicate preset id "${preset.id}"`);\n presetIds.add(preset.id);\n }\n }\n if (!errors.length) {\n try {\n const serialized = JSON.stringify(value);\n if (!serialized || new TextEncoder().encode(serialized).byteLength > MAX_EFFECT_MANIFEST_BYTES) {\n errors.push(\n `effect manifest exceeds ${MAX_EFFECT_MANIFEST_BYTES} bytes`\n );\n }\n } catch {\n errors.push("effect manifest is not serializable JSON");\n }\n }\n return errors.length ? { valid: false, errors } : { valid: true, errors: [], document: value };\n }\n function packNativeProperties(definition, params = {}) {\n const validation = validateEffectDocument({\n schemaVersion: 2,\n definitions: [definition],\n instances: []\n });\n const errors = [...validation.errors];\n for (const [name, value] of Object.entries(params)) {\n const prop = Object.prototype.hasOwnProperty.call(\n definition.properties,\n name\n ) ? definition.properties[name] : void 0;\n if (!prop) errors.push(`unknown property "${name}"`);\n else validateValue(prop, value, name, errors);\n }\n if (errors.length) throw new NativeEffectPropertyValueError(errors);\n const constraintErrors = validateResolvedParameterConstraints(\n definition.parameterConstraints,\n definition.properties,\n params\n );\n if (constraintErrors.length)\n throw new NativeEffectParameterConstraintError(constraintErrors);\n const packed = new Float32Array(nativeEffectUniformFloats(definition));\n const layout = planNativePropertyLayout(definition);\n for (const [name, prop] of Object.entries(definition.properties)) {\n if (prop.type === "texture") continue;\n const value = resolvedEffectPropertyValue(definition, params, name);\n const offset = layout.offsets[name];\n if (prop.type === "float" || prop.type === "int")\n packed[offset] = value;\n else if (prop.type === "bool") packed[offset] = value ? 1 : 0;\n else if (prop.type === "enum")\n packed[offset] = prop.options.indexOf(value);\n else if (prop.type === "vec2")\n packed.set(value, offset);\n else if (prop.type === "position")\n packed.set(packNativePosition(value), offset);\n else if (prop.type === "color") {\n const color2 = value;\n packed.set([...linearSrgb(color2), color2.alpha], offset);\n } else if (prop.type === "color-array") {\n const colors = value;\n packed[offset] = colors.length;\n for (const [index, color2] of colors.entries())\n packed.set(\n [...linearSrgb(color2), color2.alpha],\n offset + (index + 1) * 4\n );\n } else if (prop.type === "color-ramp") {\n const stops = value;\n packed[offset] = stops.length;\n for (const [index, stop] of stops.entries()) {\n packed.set(\n [...linearSrgb(stop.color), stop.color.alpha],\n offset + (1 + index * 2) * 4\n );\n packed[offset + (2 + index * 2) * 4] = stop.position;\n }\n } else if (prop.type === "paint") {\n packed.set(\n packEffectPaint(value, prop.maxCount, linearSrgb),\n offset\n );\n } else if (prop.type === "record-array") {\n const rows = value;\n const rowLayout = planNativeRecordLayout(prop.fields);\n packed[offset] = rows.length;\n for (const [index, row] of rows.entries()) {\n const base = offset + 4 + index * rowLayout.stride;\n for (const [fieldName, field] of Object.entries(prop.fields)) {\n const fieldOffset = base + rowLayout.offsets[fieldName];\n const item = row[fieldName];\n if (field.type === "bool") packed[fieldOffset] = item ? 1 : 0;\n else if (field.type === "float" || field.type === "int")\n packed[fieldOffset] = item;\n else if (field.type === "vec2")\n packed.set(item, fieldOffset);\n else if (field.type === "color") {\n const color2 = item;\n packed.set([...linearSrgb(color2), color2.alpha], fieldOffset);\n }\n }\n }\n }\n }\n return packed;\n }\n function linearSrgb(color2) {\n const [r, g, b] = color2.components.map(\n (component) => component <= 0.04045 ? component / 12.92 : ((component + 0.055) / 1.055) ** 2.4\n );\n if (color2.space === "srgb") return [r, g, b];\n return [\n 1.2249401 * r - 0.2249401 * g,\n -0.0420569 * r + 1.0420569 * g,\n -0.0196376 * r - 0.0786361 * g + 1.0982737 * b\n ];\n }\n\n // shared/native-input-resources.ts\n function nativeWorkerInputAssetId(binding) {\n if (binding.sampleEncoding !== void 0 && binding.sampleEncoding !== "srgb-color" && binding.sampleEncoding !== "linear-data" || binding.preprocess !== void 0 || binding.mipmap !== void 0)\n return null;\n const id = `input:${JSON.stringify([binding.url, binding.sampleEncoding ?? "srgb-color"])}`;\n return id.length <= 4096 ? id : null;\n }\n var BUILTINS = /* @__PURE__ */ new Set(["source", "mask", "backdrop"]);\n function sameInput(a, b) {\n return a.kind === b.kind && (a.kind === "asset" ? a.url === b.url : a.kind === "authored-node" ? a.nodeId === b.nodeId && a.capture === b.capture : a.kind === "camera" ? true : a.source === b.source);\n }\n function planNativeInputResources(definition, instance) {\n const produced = new Set(\n definition.passes.flatMap((pass) => [\n pass.output,\n ...pass.additionalOutputs ?? []\n ])\n );\n const needed = new Set(\n definition.passes.flatMap((pass) => pass.reads).filter((read) => !produced.has(read))\n );\n const singleSourceBackend = (definition.statelessCompute !== void 0 || definition.simulation !== void 0 || definition.feedback !== void 0) && needed.size === 1 && needed.has("source");\n const inputs = /* @__PURE__ */ new Map();\n for (const [portName, port] of Object.entries(definition.inputs ?? {})) {\n if (port.kind !== "texture-2d" && port.kind !== "mask") continue;\n const resource = port.resource;\n if (!resource) continue;\n if (!effectInputEnabled(port, definition, instance.params)) {\n if (needed.has(resource)) {\n inputs.set(resource, { kind: "fallback", source: "transparent-data" });\n }\n continue;\n }\n const optionalNoise = definition.optionalImage !== void 0 && definition.passes[0]?.reads[1] === "noise" && portName === "noise";\n let binding = instance.bindings && Object.prototype.hasOwnProperty.call(instance.bindings, portName) ? instance.bindings[portName] : null;\n for (const [name, property] of Object.entries(definition.properties)) {\n if (property.type !== "texture" || property.input !== portName) continue;\n const value = Object.prototype.hasOwnProperty.call(instance.params, name) ? instance.params[name] : property.default;\n if (value === null) continue;\n if (binding)\n return {\n ok: false,\n code: "input-binding-conflict",\n detail: `Texture property ${name} conflicts with binding ${portName}.`\n };\n if (typeof value !== "object" || !("kind" in value) || value.kind !== "asset" || !("url" in value) || typeof value.url !== "string")\n return {\n ok: false,\n code: "input-texture-property-asset-required",\n detail: `Texture property ${name} needs an asset reference.`\n };\n binding = value;\n }\n if (!binding && needed.has(resource) && BUILTINS.has(resource))\n binding = {\n kind: "builtin",\n source: resource\n };\n if (!binding && needed.has(resource) && resource === "receiverGeometry")\n binding = { kind: "builtin", source: "receiver-geometry" };\n if (!binding && needed.has(resource) && resource === "receiverInterior")\n binding = { kind: "builtin", source: "receiver-interior" };\n if (!binding) {\n if (port.enabledWhen && needed.has(resource))\n return {\n ok: false,\n code: "input-conditional-binding-required",\n detail: `Input ${portName} needs a selected image in ${String(port.enabledWhen.equals)} mode.`\n };\n if (optionalNoise && needed.has(resource))\n return {\n ok: false,\n code: "optional-noise-asset-required",\n detail: "The second input needs a resolved linear data asset."\n };\n if (needed.has(resource) && port.optional && port.fallback === "transparent-data")\n inputs.set(resource, { kind: "fallback", source: "transparent-data" });\n continue;\n }\n if ((portName === definition.optionalImage?.port || optionalNoise) && binding.kind !== "asset")\n return {\n ok: false,\n code: optionalNoise ? "optional-noise-asset-required" : "optional-image-asset-required",\n detail: `Input ${portName} needs a decoded asset rather than an authored or composed source.`\n };\n if ((binding.kind === "authored-node" || binding.kind === "camera") && (definition.statelessCompute || definition.simulation || definition.feedback) && !singleSourceBackend)\n return {\n ok: false,\n code: "input-authored-mode-unsupported",\n detail: `Input ${portName} needs a render-pass effect for live capture.`\n };\n if (binding.kind === "asset") {\n const checked = checkEffectAssetUrl(binding.url);\n if (!checked.ok)\n return {\n ok: false,\n code: "input-asset-invalid",\n detail: `Input ${portName} has an invalid local asset path (${checked.reason}).`\n };\n const resourceSpec = definition.resources?.find(\n (candidate) => candidate.name === resource\n );\n binding = {\n kind: "asset",\n url: checked.url,\n ...resourceSpec?.sampleEncoding ? { sampleEncoding: resourceSpec.sampleEncoding } : {},\n ...resourceSpec?.preprocess ? { preprocess: resourceSpec.preprocess } : {},\n ...resourceSpec?.mipmap ? { mipmap: resourceSpec.mipmap } : {}\n };\n }\n if (binding.kind === "builtin" && binding.source === "backdrop" && instance.placement !== "backdrop")\n return {\n ok: false,\n code: "input-placement-unsupported",\n detail: `Input ${portName} cannot sample a backdrop on a ${instance.placement} instance.`\n };\n if ((binding.kind === "builtin" && binding.source !== "receiver-geometry" && binding.source !== "receiver-interior" || binding.kind === "authored-node" || binding.kind === "camera") && definition.resources?.some(\n (candidate) => candidate.name === resource && candidate.sampleEncoding === "linear-data"\n ))\n return {\n ok: false,\n code: "input-encoding-unsupported",\n detail: `Resource ${resource} needs a raw data asset, not a composed color source.`\n };\n const existing = inputs.get(resource);\n if (existing && !sameInput(existing, binding))\n return {\n ok: false,\n code: "input-resource-ambiguous",\n detail: `Resource ${resource} has conflicting input bindings.`\n };\n inputs.set(resource, binding);\n }\n for (const resource of needed) {\n if (inputs.has(resource)) continue;\n if (resource === "source" || resource === "mask") {\n inputs.set(resource, { kind: "builtin", source: resource });\n continue;\n }\n if (resource === "backdrop" && instance.placement === "backdrop") {\n inputs.set(resource, { kind: "builtin", source: "backdrop" });\n continue;\n }\n if (resource === "receiverGeometry") {\n inputs.set(resource, { kind: "builtin", source: "receiver-geometry" });\n continue;\n }\n if (resource === "receiverInterior") {\n inputs.set(resource, { kind: "builtin", source: "receiver-interior" });\n continue;\n }\n return {\n ok: false,\n code: "input-resource-missing",\n detail: `Pass input ${resource} has no available texture binding.`\n };\n }\n for (const resource of inputs.keys())\n if (!needed.has(resource))\n return {\n ok: false,\n code: "input-resource-unused",\n detail: `Bound input ${resource} is not read by a pass.`\n };\n return { ok: true, inputs };\n }\n\n // app/components/design/bridge/native-preview-policy.ts\n var DEFAULT_NATIVE_PREVIEW_POLICY = {\n quality: "auto",\n frameRateTarget: 60,\n colorMode: "srgb",\n dynamicRange: "sdr"\n };\n var NativePreviewPolicyController = class {\n constructor() {\n this.policy = DEFAULT_NATIVE_PREVIEW_POLICY;\n this.autoTier = 0;\n this.budgetFloorTier = 0;\n this.slowFrames = 0;\n this.fastFrames = 0;\n this.cadenceSlowFrames = 0;\n this.cadenceFastFrames = 0;\n this.lastSubmittedAt = null;\n this.nextSubmissionAt = null;\n this.overviewCompact = false;\n }\n resetDensityBudget() {\n this.autoTier = 0;\n this.budgetFloorTier = 0;\n this.slowFrames = 0;\n this.fastFrames = 0;\n this.resetCommittedCadence();\n }\n isOverviewCompact() {\n return this.overviewCompact;\n }\n setOverviewCompact(compact) {\n if (this.overviewCompact === compact) return false;\n this.overviewCompact = compact;\n this.resetCommittedCadence();\n this.lastSubmittedAt = null;\n this.nextSubmissionAt = null;\n return true;\n }\n setPolicy(policy) {\n if (this.policy.quality === policy.quality && this.policy.frameRateTarget === policy.frameRateTarget)\n return false;\n this.policy = { ...policy };\n this.resetCommittedCadence();\n this.autoTier = 0;\n this.budgetFloorTier = 0;\n this.slowFrames = 0;\n this.fastFrames = 0;\n this.lastSubmittedAt = null;\n this.nextSubmissionAt = null;\n return true;\n }\n status(deviceRatio, renderWallMs, rafIntervalMs) {\n const devicePixelRatio = Number.isFinite(deviceRatio) && deviceRatio > 0 ? deviceRatio : 1;\n const capped = Math.min(devicePixelRatio, 2);\n const scale = this.policy.quality === "performance" ? 0.75 : this.policy.quality === "auto" ? [1, 0.875, 0.75][this.autoTier] : 1;\n return {\n requestedQuality: this.policy.quality,\n frameRateTarget: this.policy.frameRateTarget,\n devicePixelRatio,\n effectivePixelRatio: Math.max(\n 0.5,\n this.overviewCompact ? Math.min(0.75, capped * scale) : capped * scale\n ),\n targetFrameIntervalMs: this.overviewCompact ? 1e3 / 15 : 1e3 / this.policy.frameRateTarget,\n ...renderWallMs === void 0 ? {} : { renderWallMs },\n ...rafIntervalMs === void 0 ? {} : { rafIntervalMs }\n };\n }\n isSubmissionDue(now, dirty, earlyWindowMs = 0.25) {\n if (!this.overviewCompact && dirty || this.lastSubmittedAt === null || this.nextSubmissionAt === null || now < this.lastSubmittedAt)\n return true;\n return now + earlyWindowMs >= this.nextSubmissionAt;\n }\n commitSubmission(now, dirty) {\n const interval = this.overviewCompact ? 1e3 / 15 : 1e3 / this.policy.frameRateTarget;\n if (!this.overviewCompact && dirty || this.lastSubmittedAt === null || this.nextSubmissionAt === null || now < this.lastSubmittedAt) {\n this.lastSubmittedAt = now;\n this.nextSubmissionAt = now + interval;\n return;\n }\n const elapsedIntervals = Math.max(\n 1,\n Math.floor((now + 0.25 - this.nextSubmissionAt) / interval) + 1\n );\n this.nextSubmissionAt += elapsedIntervals * interval;\n this.lastSubmittedAt = now;\n }\n shouldSubmit(now, dirty) {\n if (!this.isSubmissionDue(now, dirty)) return false;\n this.commitSubmission(now, dirty);\n return true;\n }\n observeResourceBudgetExceeded() {\n if (this.policy.quality !== "auto" || this.autoTier >= 2) return false;\n this.autoTier += 1;\n this.budgetFloorTier = this.autoTier;\n this.resetCommittedCadence();\n this.slowFrames = 0;\n this.fastFrames = 0;\n return true;\n }\n resetCommittedCadence() {\n this.cadenceSlowFrames = 0;\n this.cadenceFastFrames = 0;\n }\n // The caller supplies elapsed/commits from a continuous animation window, not adjacent burst completions.\n observeCommittedCadence(intervalMs, committedFrames = 1) {\n if (this.policy.quality !== "auto" || !Number.isFinite(intervalMs) || intervalMs <= 0 || !Number.isSafeInteger(committedFrames) || committedFrames <= 0) {\n this.resetCommittedCadence();\n return false;\n }\n const budget = this.overviewCompact ? 1e3 / 15 : 1e3 / this.policy.frameRateTarget;\n if (intervalMs > budget * 1.5) {\n this.cadenceFastFrames = 0;\n this.cadenceSlowFrames = Math.min(\n 8,\n this.cadenceSlowFrames + Math.min(8, committedFrames)\n );\n if (this.cadenceSlowFrames >= 8 && this.autoTier < 2) {\n this.autoTier++;\n this.resetCommittedCadence();\n return true;\n }\n } else if (intervalMs <= budget * 1.1) {\n this.cadenceSlowFrames = 0;\n this.cadenceFastFrames = Math.min(\n 90,\n this.cadenceFastFrames + Math.min(90, committedFrames)\n );\n if (this.cadenceFastFrames >= 90 && this.autoTier > this.budgetFloorTier) {\n this.autoTier--;\n this.resetCommittedCadence();\n return true;\n }\n } else {\n this.resetCommittedCadence();\n }\n return false;\n }\n observeRenderWall(wallMs) {\n if (this.policy.quality !== "auto" || !Number.isFinite(wallMs) || wallMs < 0)\n return false;\n const budget = this.overviewCompact ? 1e3 / 15 : 1e3 / this.policy.frameRateTarget;\n if (wallMs > budget * 0.85) {\n this.slowFrames += 1;\n this.fastFrames = 0;\n if (this.slowFrames >= 8 && this.autoTier < 2) {\n this.autoTier += 1;\n this.slowFrames = 0;\n return true;\n }\n } else if (wallMs < budget * 0.55) {\n this.fastFrames += 1;\n this.slowFrames = 0;\n if (this.fastFrames >= 90 && this.autoTier > this.budgetFloorTier) {\n this.autoTier -= 1;\n this.fastFrames = 0;\n return true;\n }\n } else {\n this.slowFrames = 0;\n this.fastFrames = 0;\n }\n return false;\n }\n };\n\n // app/components/design/bridge/native-worker-backdrop-route.ts\n function planNativeWorkerBackdropRoute(groupLocalOwnerId, composingOwnerId) {\n if (!groupLocalOwnerId) return "target-source";\n return groupLocalOwnerId === composingOwnerId ? "group-local" : "owner-output";\n }\n\n // shared/native-source-composition-tree.ts\n var MAX_NATIVE_SOURCE_PAINT_NODES = 512;\n var MAX_NATIVE_SOURCE_GROUP_DEPTH = 16;\n function validBox(box) {\n return [box.x, box.y, box.width, box.height].every(Number.isFinite) && Number.isFinite(box.x + box.width) && Number.isFinite(box.y + box.height) && box.width >= 0 && box.height >= 0;\n }\n function union(a, b) {\n const x = Math.min(a.x, b.x);\n const y = Math.min(a.y, b.y);\n return {\n x,\n y,\n width: Math.max(a.x + a.width, b.x + b.width) - x,\n height: Math.max(a.y + a.height, b.y + b.height) - y\n };\n }\n function flatten(group) {\n const children = [];\n for (const child of group.children) {\n if (child.kind !== "group") {\n children.push(child);\n continue;\n }\n const nested = flatten(child);\n if (!nested.isolate) children.push(...nested.children);\n else children.push(nested);\n }\n return { ...group, children };\n }\n function planNativeSourceComposition(paints) {\n const root = {\n kind: "group",\n id: "$root",\n isolationKind: "root",\n box: { x: 0, y: 0, width: 0, height: 0 },\n opacity: 1,\n isolate: false,\n children: []\n };\n const stack = [root];\n const closed = /* @__PURE__ */ new Set();\n const leafIds = /* @__PURE__ */ new Set();\n const groupIds = /* @__PURE__ */ new Set();\n let nodeCount = 1;\n let firstBox = true;\n for (const paint of paints) {\n if (!paint.id || paint.id === "$root" || leafIds.has(paint.id) || groupIds.has(paint.id) || !validBox(paint.box) || !Number.isFinite(paint.opacity) || paint.opacity < 0 || paint.opacity > 1 || paint.ownOpacityBaked && paint.opacity !== 1)\n return {\n ok: false,\n reason: "invalid-input",\n detail: "A source paint has invalid identity, geometry, or opacity."\n };\n if (paint.isolationPath.length > MAX_NATIVE_SOURCE_GROUP_DEPTH)\n return {\n ok: false,\n reason: "limit-exceeded",\n detail: "Source group nesting exceeds the bounded composition depth."\n };\n const pathIds = /* @__PURE__ */ new Set();\n for (const ancestor of paint.isolationPath) {\n const key = `${ancestor.kind}:${ancestor.id}`;\n if (!ancestor.id || ancestor.id === "$root" || ancestor.id === paint.id || pathIds.has(key) || leafIds.has(ancestor.id) || ancestor.kind === "opacity" && (!Number.isFinite(ancestor.opacity) || ancestor.opacity < 0 || ancestor.opacity > 1) || ancestor.kind === "clip" && !ancestor.clipId)\n return {\n ok: false,\n reason: "invalid-input",\n detail: "A source ancestor has invalid identity, opacity, or clip identity."\n };\n pathIds.add(key);\n }\n let common = 0;\n while (common < paint.isolationPath.length && common + 1 < stack.length && stack[common + 1].id === paint.isolationPath[common].id && stack[common + 1].isolationKind === paint.isolationPath[common].kind) {\n const current = stack[common + 1];\n const incoming = paint.isolationPath[common];\n if (incoming.kind === "opacity" && current.opacity !== incoming.opacity || incoming.kind === "clip" && current.clipId !== incoming.clipId)\n return {\n ok: false,\n reason: "invalid-hierarchy",\n detail: "A source group changed its opacity or clip identity within one paint order."\n };\n common += 1;\n }\n while (stack.length > common + 1) {\n const removed = stack.pop();\n closed.add(`${removed.isolationKind}:${removed.id}`);\n }\n for (const ancestor of paint.isolationPath.slice(common)) {\n if (closed.has(`${ancestor.kind}:${ancestor.id}`))\n return {\n ok: false,\n reason: "invalid-hierarchy",\n detail: "A source group reappeared after another paint group; DOM paint order cannot be preserved."\n };\n const group = {\n kind: "group",\n id: ancestor.id,\n isolationKind: ancestor.kind,\n box: paint.box,\n opacity: ancestor.kind === "opacity" ? ancestor.opacity : 1,\n clipId: ancestor.kind === "clip" ? ancestor.clipId : void 0,\n isolate: ancestor.kind === "clip" || ancestor.opacity < 1,\n children: []\n };\n stack[stack.length - 1].children.push(group);\n stack.push(group);\n groupIds.add(ancestor.id);\n nodeCount += 1;\n }\n const leaf = {\n kind: "leaf",\n id: paint.id,\n box: paint.box,\n opacity: paint.opacity,\n ownOpacityBaked: paint.ownOpacityBaked === true\n };\n stack[stack.length - 1].children.push(leaf);\n leafIds.add(paint.id);\n nodeCount += 1;\n if (nodeCount > MAX_NATIVE_SOURCE_PAINT_NODES)\n return {\n ok: false,\n reason: "limit-exceeded",\n detail: "Source paint nodes exceed the bounded composition size."\n };\n for (const group of stack) {\n const next = group === root && firstBox ? paint.box : union(group.box, paint.box);\n if (!validBox(next))\n return {\n ok: false,\n reason: "invalid-input",\n detail: "Source group bounds exceed finite geometry."\n };\n group.box = next;\n }\n firstBox = false;\n }\n return { ok: true, root: flatten(root), nodeCount };\n }\n\n // app/components/design/bridge/native-capture-roi.ts\n function planNativePhysicalRootBox(input) {\n const { width, height, left, top } = input;\n if (![width, height, left, top].every(Number.isSafeInteger) || width <= 0 || height <= 0 || left < 0 || top < 0 || left >= width || top >= height)\n return { ok: false };\n const origin = input.origin;\n if (origin && ![origin.x, origin.y].every(Number.isSafeInteger))\n return { ok: false };\n return {\n ok: true,\n box: { x: origin?.x ?? -left, y: origin?.y ?? -top, width, height }\n };\n }\n\n // app/components/design/bridge/native-source-affine-geometry.ts\n var components = (matrix) => [\n matrix.a,\n matrix.b,\n matrix.c,\n matrix.d,\n matrix.e,\n matrix.f\n ];\n function finiteMatrix(matrix) {\n return components(matrix).every(Number.isFinite);\n }\n function representableMatrix(matrix) {\n return components(matrix).every(\n (value) => Number.isFinite(Math.fround(value))\n );\n }\n function f32Matrix(matrix) {\n return {\n a: Math.fround(matrix.a),\n b: Math.fround(matrix.b),\n c: Math.fround(matrix.c),\n d: Math.fround(matrix.d),\n e: Math.fround(matrix.e),\n f: Math.fround(matrix.f)\n };\n }\n function composeNativeSourceAffine(outer, inner) {\n if (!finiteMatrix(outer) || !finiteMatrix(inner))\n return { ok: false, reason: "non-finite" };\n const matrix = {\n a: outer.a * inner.a + outer.c * inner.b,\n b: outer.b * inner.a + outer.d * inner.b,\n c: outer.a * inner.c + outer.c * inner.d,\n d: outer.b * inner.c + outer.d * inner.d,\n e: outer.a * inner.e + outer.c * inner.f + outer.e,\n f: outer.b * inner.e + outer.d * inner.f + outer.f\n };\n if (!finiteMatrix(matrix)) return { ok: false, reason: "non-finite" };\n if (!representableMatrix(matrix))\n return { ok: false, reason: "unrepresentable" };\n return { ok: true, matrix };\n }\n function invertNativeSourceAffine(matrix) {\n if (!finiteMatrix(matrix)) return { ok: false, reason: "non-finite" };\n if (!representableMatrix(matrix))\n return { ok: false, reason: "unrepresentable" };\n const rounded = f32Matrix(matrix);\n const determinant = rounded.a * rounded.d - rounded.b * rounded.c;\n if (!Number.isFinite(determinant))\n return { ok: false, reason: "unrepresentable" };\n if (determinant === 0) return { ok: false, reason: "singular" };\n const inverse = {\n a: rounded.d / determinant,\n b: -rounded.b / determinant,\n c: -rounded.c / determinant,\n d: rounded.a / determinant,\n e: (rounded.c * rounded.f - rounded.d * rounded.e) / determinant,\n f: (rounded.b * rounded.e - rounded.a * rounded.f) / determinant\n };\n if (!finiteMatrix(inverse) || !representableMatrix(inverse))\n return { ok: false, reason: "unrepresentable" };\n return { ok: true, matrix: f32Matrix(inverse) };\n }\n function mapNativeSourceAffine(matrix, point2) {\n return {\n x: matrix.a * point2.x + matrix.c * point2.y + matrix.e,\n y: matrix.b * point2.x + matrix.d * point2.y + matrix.f\n };\n }\n function planNativeSourceAffine(input) {\n const { localBox, localToTarget, physicalScale } = input;\n if (![localBox.x, localBox.y, localBox.width, localBox.height].every(\n Number.isFinite\n ) || localBox.width <= 0 || localBox.height <= 0 || !Number.isFinite(localBox.x + localBox.width) || !Number.isFinite(localBox.y + localBox.height))\n return { ok: false, reason: "invalid-box" };\n if (!Number.isFinite(physicalScale.x) || !Number.isFinite(physicalScale.y) || physicalScale.x <= 0 || physicalScale.y <= 0)\n return { ok: false, reason: "invalid-scale" };\n const scaled = composeNativeSourceAffine(\n {\n a: physicalScale.x,\n b: 0,\n c: 0,\n d: physicalScale.y,\n e: 0,\n f: 0\n },\n localToTarget\n );\n if (!scaled.ok) return scaled;\n const localToPhysical = f32Matrix(scaled.matrix);\n const inverted = invertNativeSourceAffine(localToPhysical);\n if (!inverted.ok) return inverted;\n const corners = [\n { x: localBox.x, y: localBox.y },\n { x: localBox.x + localBox.width, y: localBox.y },\n { x: localBox.x, y: localBox.y + localBox.height },\n { x: localBox.x + localBox.width, y: localBox.y + localBox.height }\n ].map((point2) => mapNativeSourceAffine(localToPhysical, point2));\n const xs = corners.map((point2) => point2.x);\n const ys = corners.map((point2) => point2.y);\n const left = Math.min(...xs);\n const top = Math.min(...ys);\n const right = Math.max(...xs);\n const bottom = Math.max(...ys);\n const physicalBounds = {\n x: left,\n y: top,\n width: right - left,\n height: bottom - top\n };\n if (![\n left,\n top,\n right,\n bottom,\n physicalBounds.width,\n physicalBounds.height\n ].every(Number.isFinite) || ![\n left,\n top,\n right,\n bottom,\n physicalBounds.width,\n physicalBounds.height,\n localBox.x,\n localBox.y,\n localBox.width,\n localBox.height\n ].every((value) => Number.isFinite(Math.fround(value))))\n return { ok: false, reason: "unrepresentable" };\n return {\n ok: true,\n localBox,\n localToPhysical,\n physicalToLocal: inverted.matrix,\n physicalBounds\n };\n }\n\n // app/components/design/bridge/native-group-local-backdrop-window.ts\n var checkedPlans = /* @__PURE__ */ new WeakSet();\n var MAX_EXACT_DIMENSION = 1048576;\n function validBox2(box) {\n return [\n box.x,\n box.y,\n box.width,\n box.height,\n box.x + box.width,\n box.y + box.height\n ].every(Number.isFinite) && box.width > 0 && box.height > 0;\n }\n function contains(outer, inner) {\n return inner.x >= outer.x && inner.y >= outer.y && inner.x + inner.width <= outer.x + outer.width && inner.y + inner.height <= outer.y + outer.height;\n }\n function packedCoordinate(position, origin, size, output) {\n const scaled = Math.fround(Math.fround(position) * size);\n const normalized = Math.fround(scaled / output);\n return Math.fround(Math.fround(origin + normalized) - 0.5);\n }\n function planNativeGroupLocalBackdropWindow(input) {\n const {\n incoming,\n output,\n extent,\n localBox,\n localToTarget: matrix,\n physicalScale: scale,\n receiverClip\n } = input;\n if (!validBox2(incoming) || !validBox2(localBox) || !validBox2(receiverClip) || ![\n incoming.x,\n incoming.y,\n incoming.width,\n incoming.height,\n output.width,\n output.height\n ].every(Number.isSafeInteger) || [incoming.width, incoming.height, output.width, output.height].some(\n (value) => value <= 0 || value > MAX_EXACT_DIMENSION\n ) || ![\n matrix.a,\n matrix.b,\n matrix.c,\n matrix.d,\n matrix.e,\n matrix.f,\n scale.x,\n scale.y\n ].every(Number.isFinite) || scale.x <= 0 || scale.y <= 0)\n return { ok: false, reason: "invalid-geometry" };\n if (!extent || !Number.isFinite(extent.pixelRatio) || extent.pixelRatio <= 0)\n return { ok: false, reason: "extent-invalid" };\n const dimensions = [\n extent.width,\n extent.height,\n extent.sourceWidth,\n extent.sourceHeight\n ];\n const insets = [extent.left, extent.top, extent.right, extent.bottom];\n if (!dimensions.every((value) => Number.isSafeInteger(value) && value > 0) || !insets.every((value) => Number.isSafeInteger(value) && value >= 0) || extent.width !== extent.sourceWidth + extent.left + extent.right || extent.height !== extent.sourceHeight + extent.top + extent.bottom || extent.width !== output.width || extent.height !== output.height || extent.expanded !== insets.some((value) => value > 0))\n return { ok: false, reason: "extent-invalid" };\n if (matrix.b !== 0 || matrix.c !== 0 || matrix.a <= 0 || matrix.d <= 0)\n return { ok: false, reason: "unsupported-affine" };\n const authoredCaptureWindow = {\n x: (matrix.a * localBox.x + matrix.e) * scale.x,\n y: (matrix.d * localBox.y + matrix.f) * scale.y,\n width: matrix.a * localBox.width * scale.x,\n height: matrix.d * localBox.height * scale.y\n };\n const replacementCoverage = {\n x: receiverClip.x * scale.x,\n y: receiverClip.y * scale.y,\n width: receiverClip.width * scale.x,\n height: receiverClip.height * scale.y\n };\n if (!validBox2(authoredCaptureWindow) || !validBox2(replacementCoverage))\n return { ok: false, reason: "invalid-geometry" };\n if (!contains(incoming, authoredCaptureWindow))\n return { ok: false, reason: "capture-window-unavailable" };\n if (!contains(authoredCaptureWindow, replacementCoverage))\n return { ok: false, reason: "receiver-outside-capture" };\n const affine = planNativeSourceAffine({\n localBox,\n localToTarget: matrix,\n physicalScale: scale\n });\n if (!affine.ok) return { ok: false, reason: "unsupported-affine" };\n const captureWindow = affine.physicalBounds;\n if (!contains(incoming, captureWindow))\n return { ok: false, reason: "capture-window-unavailable" };\n const sourceBox = {\n x: Math.fround(captureWindow.x - incoming.x),\n y: Math.fround(captureWindow.y - incoming.y),\n width: Math.fround(captureWindow.width),\n height: Math.fround(captureWindow.height)\n };\n if (!validBox2(sourceBox)) return { ok: false, reason: "invalid-geometry" };\n const exactCopy = Number.isInteger(sourceBox.x) && Number.isInteger(sourceBox.y) && sourceBox.width === output.width && sourceBox.height === output.height;\n const arithmeticEnvelope = exactCopy ? { x: 0, y: 0 } : {\n x: 2 ** -19 * Math.max(1, sourceBox.x + sourceBox.width),\n y: 2 ** -19 * Math.max(1, sourceBox.y + sourceBox.height)\n };\n const left = exactCopy ? sourceBox.x : Math.floor(\n packedCoordinate(0.5, sourceBox.x, sourceBox.width, output.width) - arithmeticEnvelope.x\n );\n const top = exactCopy ? sourceBox.y : Math.floor(\n packedCoordinate(0.5, sourceBox.y, sourceBox.height, output.height) - arithmeticEnvelope.y\n );\n const right = exactCopy ? sourceBox.x + output.width - 1 : Math.ceil(\n packedCoordinate(\n output.width - 0.5,\n sourceBox.x,\n sourceBox.width,\n output.width\n ) + arithmeticEnvelope.x\n );\n const bottom = exactCopy ? sourceBox.y + output.height - 1 : Math.ceil(\n packedCoordinate(\n output.height - 0.5,\n sourceBox.y,\n sourceBox.height,\n output.height\n ) + arithmeticEnvelope.y\n );\n const samplingPixels = {\n x: left,\n y: top,\n width: right - left + 1,\n height: bottom - top + 1\n };\n if (![left, top, right, bottom].every(Number.isSafeInteger) || !contains(\n { x: 0, y: 0, width: incoming.width, height: incoming.height },\n samplingPixels\n ))\n return { ok: false, reason: "sampling-window-unavailable" };\n const packet = Object.freeze([\n output.width,\n output.height,\n 0,\n exactCopy ? 1 : 0,\n sourceBox.x,\n sourceBox.y,\n sourceBox.width,\n sourceBox.height\n ]);\n const plan = Object.freeze({\n incoming: Object.freeze({ ...incoming }),\n output: Object.freeze({ ...output }),\n extent: Object.freeze({ ...extent }),\n captureWindow: Object.freeze(captureWindow),\n replacementCoverage: Object.freeze(replacementCoverage),\n sourceBox: Object.freeze(sourceBox),\n samplingPixels: Object.freeze(samplingPixels),\n arithmeticEnvelope: Object.freeze(arithmeticEnvelope),\n packet\n });\n checkedPlans.add(plan);\n return { ok: true, plan };\n }\n\n // app/components/design/bridge/native-source-coordinate-scale.ts\n function planNativeSourceCoordinateScale(input) {\n const first = input.spaces[0] ?? "target-local";\n if (first !== "target-local" && first !== "target-local-global" && first !== "target-viewport-axis-aligned" || input.spaces.some((space) => space !== first))\n return { ok: false, code: "source-coordinate-space-mixed" };\n const width = first === "target-viewport-axis-aligned" ? input.viewportWidth : input.localWidth;\n const height = first === "target-viewport-axis-aligned" ? input.viewportHeight : input.localHeight;\n const x = input.sourceWidth / width;\n const y = input.sourceHeight / height;\n if (![input.sourceWidth, input.sourceHeight, width, height, x, y].every(\n (value) => Number.isFinite(value) && value > 0\n ))\n return { ok: false, code: "source-coordinate-space-unreadable" };\n return { ok: true, x, y };\n }\n\n // app/components/design/bridge/native-source-sampling.ts\n function planNativeImageUpload(input) {\n if (input.imageRendering === void 0) return { ok: true, filter: "linear" };\n const value = input.imageRendering?.value;\n if (["auto", "smooth", "high-quality", "optimizeQuality"].includes(value))\n return { ok: true, filter: "linear" };\n if (!["pixelated", "crisp-edges", "optimizeSpeed"].includes(value))\n return { ok: false, reason: "value" };\n const { sourceSize, uploadedSize } = input;\n if (![\n sourceSize.width,\n sourceSize.height,\n uploadedSize.width,\n uploadedSize.height\n ].every((size) => Number.isSafeInteger(size) && size > 0))\n return { ok: false, reason: "geometry" };\n if (uploadedSize.width !== sourceSize.width || uploadedSize.height !== sourceSize.height)\n return { ok: false, reason: "downsample" };\n return { ok: true, filter: "nearest" };\n }\n function planNativeImageSampling(input) {\n const upload = planNativeImageUpload(input);\n if (!upload.ok || upload.filter === "linear") return upload;\n const { sourceSize, localBox, localToTarget, physicalScale } = input;\n const uv = input.uv ?? { x: 0, y: 0, width: 1, height: 1 };\n if (![\n localBox.x,\n localBox.y,\n localBox.width,\n localBox.height,\n localToTarget.a,\n localToTarget.b,\n localToTarget.c,\n localToTarget.d,\n localToTarget.e,\n localToTarget.f,\n physicalScale.x,\n physicalScale.y,\n uv.x,\n uv.y,\n uv.width,\n uv.height\n ].every(Number.isFinite) || localBox.width <= 0 || localBox.height <= 0 || physicalScale.x <= 0 || physicalScale.y <= 0 || uv.x < 0 || uv.y < 0 || uv.width <= 0 || uv.height <= 0 || uv.x + uv.width > 1 || uv.y + uv.height > 1 || localToTarget.a === 0 || localToTarget.d === 0 || localToTarget.b !== 0 || localToTarget.c !== 0)\n return { ok: false, reason: "geometry" };\n if (input.imageRendering.value !== "pixelated")\n return { ok: true, filter: "nearest" };\n const physicalWidth = localBox.width / uv.width * Math.abs(localToTarget.a) * physicalScale.x;\n const physicalHeight = localBox.height / uv.height * Math.abs(localToTarget.d) * physicalScale.y;\n const x = Math.max(1, Math.floor(physicalWidth / sourceSize.width + 0.5));\n const y = Math.max(1, Math.floor(physicalHeight / sourceSize.height + 0.5));\n if (![x, y].every(Number.isSafeInteger) || x * sourceSize.width > 8388608 || y * sourceSize.height > 8388608)\n return { ok: false, reason: "pixelated-scale" };\n return { ok: true, filter: "nearest", pixelated: { x, y } };\n }\n var nativePixelatedImageSamplingWgsl = `\nfn nativeImagePremult(value: vec4f, premultiplied: bool) -> vec4f {\n if (premultiplied) { return value; }\n return vec4f(value.rgb * value.a, value.a);\n}\nfn nativeSamplePixelated(image: texture_2d<f32>, uv: vec2f, multiple: vec2f, premultiplied: bool) -> vec4f {\n let extent = vec2f(textureDimensions(image));\n let intermediate = extent * multiple;\n let position = clamp(uv, vec2f(0.0), vec2f(1.0)) * intermediate - vec2f(0.5);\n let low = floor(position);\n let fraction = position - low;\n let first = vec2i(floor(clamp(low, vec2f(0.0), intermediate - vec2f(1.0)) / multiple));\n let second = vec2i(floor(clamp(low + vec2f(1.0), vec2f(0.0), intermediate - vec2f(1.0)) / multiple));\n let topLeft = nativeImagePremult(textureLoad(image, first, 0), premultiplied);\n let topRight = nativeImagePremult(textureLoad(image, vec2i(second.x, first.y), 0), premultiplied);\n let bottomLeft = nativeImagePremult(textureLoad(image, vec2i(first.x, second.y), 0), premultiplied);\n let bottomRight = nativeImagePremult(textureLoad(image, second, 0), premultiplied);\n let value = mix(mix(topLeft, topRight, fraction.x), mix(bottomLeft, bottomRight, fraction.x), fraction.y);\n if (premultiplied) { return value; }\n if (value.a > 0.0) { return vec4f(value.rgb / value.a, value.a); }\n return vec4f(0.0);\n}`;\n\n // app/components/design/bridge/native-color-mode.ts\n var LINEAR_SRGB_TO_DISPLAY_P3 = [\n [0.8224620105651395, 0.17753798943486054, 0],\n [0.03319415910219203, 0.966805840897808, 0],\n [0.01708266272173309, 0.0723974914511293, 0.9105198458271376]\n ];\n var p3 = LINEAR_SRGB_TO_DISPLAY_P3;\n var LINEAR_SRGB_TO_DISPLAY_P3_WGSL = `\nfn linearSrgbToDisplayP3(rgb: vec3f) -> vec3f {\n return vec3f(\n dot(rgb, vec3f(${p3[0].join(", ")})),\n dot(rgb, vec3f(${p3[1].join(", ")})),\n dot(rgb, vec3f(${p3[2].join(", ")}))\n );\n}`;\n\n // app/components/design/bridge/native-worker-gpu-wgsl.ts\n var nativeClipCoverageWgsl = `\nfn ellipseCoverage(p: vec2f, center: vec2f, radii: vec2f, pixelScale: f32) -> f32 {\n let q = p - center;\n let r = max(radii, vec2f(0.0001));\n let k0 = length(q / r);\n if (k0 < 0.00001) { return 1.0; }\n let k1 = length(q / (r * r));\n let distance = k0 * (k0 - 1.0) / max(k1, 0.00001);\n return clamp(0.5 - distance / pixelScale, 0.0, 1.0);\n}\nfn clipCoverage(p: vec2f, clip: Clip) -> f32 {\n let projected = vec3f(p, 1.0);\n let point = vec2f(dot(clip.inverseX.xyz, projected), dot(clip.inverseY.xyz, projected));\n let local = point - clip.rect.xy;\n let size = clip.rect.zw;\n let pixelScale = max(max(length(clip.inverseX.xy), length(clip.inverseY.xy)), 0.00001);\n if (local.x < -pixelScale || local.y < -pixelScale || local.x > size.x + pixelScale || local.y > size.y + pixelScale) {\n return 0.0;\n }\n var coverage = clamp(min(min(local.x, local.y), min(size.x - local.x, size.y - local.y)) / pixelScale + 0.5, 0.0, 1.0);\n let tl = clip.radiiTop.xy;\n let tr = clip.radiiTop.zw;\n let br = clip.radiiBottom.xy;\n let bl = clip.radiiBottom.zw;\n if (tl.x > 0.0 && tl.y > 0.0 && local.x < tl.x && local.y < tl.y) {\n coverage = min(coverage, ellipseCoverage(local, tl, tl, pixelScale));\n }\n if (tr.x > 0.0 && tr.y > 0.0 && local.x > size.x - tr.x && local.y < tr.y) {\n coverage = min(coverage, ellipseCoverage(local, vec2f(size.x - tr.x, tr.y), tr, pixelScale));\n }\n if (br.x > 0.0 && br.y > 0.0 && local.x > size.x - br.x && local.y > size.y - br.y) {\n coverage = min(coverage, ellipseCoverage(local, size - br, br, pixelScale));\n }\n if (bl.x > 0.0 && bl.y > 0.0 && local.x < bl.x && local.y > size.y - bl.y) {\n coverage = min(coverage, ellipseCoverage(local, vec2f(bl.x, size.y - bl.y), bl, pixelScale));\n }\n return coverage;\n}\n`;\n var compositeWgsl = `\nstruct Clip {\n rect: vec4f,\n radiiTop: vec4f,\n radiiBottom: vec4f,\n inverseX: vec4f,\n inverseY: vec4f,\n};\nstruct Draw {\n rect: vec4f,\n viewport: vec4f,\n opacity: vec4f,\n uv: vec4f,\n clipCount: vec4f,\n origin: vec4f,\n localBox: vec4f,\n inverseX: vec4f,\n inverseY: vec4f,\n clips: array<Clip, 8>\n};\n@group(0) @binding(0) var<uniform> draw: Draw;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var source: texture_2d<f32>;\nstruct VOut { @builtin(position) position: vec4f };\n@vertex fn vs(@builtin(vertex_index) i: u32) -> VOut {\n let xy = array<vec2f, 6>(vec2f(0,0), vec2f(1,0), vec2f(0,1), vec2f(0,1), vec2f(1,0), vec2f(1,1))[i];\n let p = draw.rect.xy - draw.origin.xy + xy * draw.rect.zw;\n var out: VOut;\n out.position = vec4f(2.0 * p.x / draw.viewport.x - 1.0, 1.0 - 2.0 * p.y / draw.viewport.y, 0.0, 1.0);\n return out;\n}\n${nativeClipCoverageWgsl}\n${nativePixelatedImageSamplingWgsl}\nfn cssEncode(v: f32) -> f32 {\n let bounded = clamp(v, 0.0, 1.0);\n return select(1.055 * pow(bounded, 1.0 / 2.4) - 0.055, 12.92 * bounded, bounded <= 0.0031308);\n}\n@fragment fn fs(input: VOut) -> @location(0) vec4f {\n let point = input.position.xy + draw.origin.xy;\n let projected = vec3f(point, 1.0);\n let local = vec2f(dot(draw.inverseX.xyz, projected), dot(draw.inverseY.xyz, projected));\n let localUv = (local - draw.localBox.xy) / draw.localBox.zw;\n var sample = vec4f(0.0);\n if (all(draw.viewport.zw > vec2f(0.0))) {\n sample = nativeSamplePixelated(source, draw.uv.xy + localUv * draw.uv.zw, draw.viewport.zw, draw.opacity.y > 0.5);\n } else {\n sample = textureSample(source, samp, draw.uv.xy + localUv * draw.uv.zw);\n }\n if (any(localUv < vec2f(0.0)) || any(localUv > vec2f(1.0))) {\n return vec4f(0.0);\n }\n var rgb = select(sample.rgb * sample.a, sample.rgb, draw.opacity.y > 0.5);\n if (draw.opacity.z > 0.5 && draw.opacity.w < 0.5) {\n let straight = select(vec3f(0.0), rgb / max(sample.a, 0.00001), sample.a > 0.00001);\n rgb = vec3f(cssEncode(straight.r), cssEncode(straight.g), cssEncode(straight.b)) * sample.a;\n }\n var coverage = 1.0;\n for (var i = 0u; i < 8u; i = i + 1u) {\n if (f32(i) >= draw.clipCount.x) { break; }\n coverage = min(coverage, clipCoverage(point, draw.clips[i]));\n }\n return vec4f(rgb, sample.a) * (draw.opacity.x * coverage);\n}`;\n var backdropReplaceWgsl = (receiverCoverage = false) => `\nstruct Clip {\n rect: vec4f,\n radiiTop: vec4f,\n radiiBottom: vec4f,\n inverseX: vec4f,\n inverseY: vec4f,\n};\nstruct Draw {\n rect: vec4f,\n viewport: vec4f,\n opacity: vec4f,\n uv: vec4f,\n clipCount: vec4f,\n origin: vec4f,\n localBox: vec4f,\n inverseX: vec4f,\n inverseY: vec4f,\n clips: array<Clip, 8>\n};\n@group(0) @binding(0) var<uniform> draw: Draw;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var priorScene: texture_2d<f32>;\n@group(0) @binding(3) var processedBackdrop: texture_2d<f32>;\n${receiverCoverage ? "@group(0) @binding(4) var receiverCoverageTexture: texture_2d<f32>;" : ""}\nstruct VOut { @builtin(position) position: vec4f };\n@vertex fn vs(@builtin(vertex_index) i: u32) -> VOut {\n let p = array<vec2f, 3>(vec2f(-1.0,-1.0), vec2f(3.0,-1.0), vec2f(-1.0,3.0))[i];\n var output: VOut;\n output.position = vec4f(p, 0.0, 1.0);\n return output;\n}\n${nativeClipCoverageWgsl}\n${nativePixelatedImageSamplingWgsl}\nfn cssEncode(v: f32) -> f32 {\n let bounded = clamp(v, 0.0, 1.0);\n return select(1.055 * pow(bounded, 1.0 / 2.4) - 0.055, 12.92 * bounded, bounded <= 0.0031308);\n}\nfn cssDecode(v: f32) -> f32 {\n let bounded = clamp(v, 0.0, 1.0);\n return select(pow((bounded + 0.055) / 1.055, 2.4), bounded / 12.92, bounded <= 0.04045);\n}\nfn decodePremult(value: vec4f) -> vec4f {\n let straight = select(vec3f(0.0), value.rgb / max(value.a, 0.00001), value.a > 0.00001);\n return vec4f(vec3f(cssDecode(straight.r), cssDecode(straight.g), cssDecode(straight.b)) * value.a, value.a);\n}\nfn encodePremult(value: vec4f) -> vec4f {\n let straight = select(vec3f(0.0), value.rgb / max(value.a, 0.00001), value.a > 0.00001);\n return vec4f(vec3f(cssEncode(straight.r), cssEncode(straight.g), cssEncode(straight.b)) * value.a, value.a);\n}\n@fragment fn fs(input: VOut) -> @location(0) vec4f {\n let previous = textureLoad(priorScene, vec2i(input.position.xy), 0);\n let point = input.position.xy + draw.origin.xy;\n if (draw.opacity.w > 0.5 &&\n (point.x < draw.rect.x || point.y < draw.rect.y ||\n point.x >= draw.rect.x + draw.rect.z || point.y >= draw.rect.y + draw.rect.w)) {\n return previous;\n }\n let projected = vec3f(point, 1.0);\n let local = vec2f(dot(draw.inverseX.xyz, projected), dot(draw.inverseY.xyz, projected));\n let localUv = (local - draw.localBox.xy) / draw.localBox.zw;\n if (any(localUv < vec2f(0.0)) || any(localUv > vec2f(1.0))) { return previous; }\n var effect = vec4f(0.0);\n if (all(draw.viewport.zw > vec2f(0.0))) {\n effect = nativeSamplePixelated(processedBackdrop, draw.uv.xy + localUv * draw.uv.zw, draw.viewport.zw, true);\n } else {\n effect = textureSampleLevel(processedBackdrop, samp, draw.uv.xy + localUv * draw.uv.zw, 0.0);\n }\n var coverage = 1.0;\n for (var i = 0u; i < 8u; i = i + 1u) {\n if (f32(i) >= draw.clipCount.x) { break; }\n coverage = min(coverage, clipCoverage(point, draw.clips[i]));\n }\n let weight = coverage * draw.opacity.x ${receiverCoverage ? "* textureSampleLevel(receiverCoverageTexture, samp, localUv, 0.0).a" : ""};\n if (weight <= 0.0) { return previous; }\n if (draw.opacity.z > 0.5 && draw.opacity.w < 0.5) {\n return encodePremult(mix(decodePremult(previous), effect, weight));\n }\n return mix(previous, effect, weight);\n}`;\n var cssPremultBlendWgsl = `\nfn cssEncodeChannel(v: f32) -> f32 {\n let bounded = clamp(v, 0.0, 1.0);\n return select(1.055 * pow(bounded, 1.0 / 2.4) - 0.055, 12.92 * bounded, bounded <= 0.0031308);\n}\nfn cssDecodeChannel(v: f32) -> f32 {\n let bounded = clamp(v, 0.0, 1.0);\n return select(pow((bounded + 0.055) / 1.055, 2.4), bounded / 12.92, bounded <= 0.04045);\n}\nfn cssToEncoded(value: vec4f) -> vec4f {\n let alpha = clamp(value.a, 0.0, 1.0);\n let straight = select(vec3f(0.0), value.rgb / max(alpha, 0.00001), alpha > 0.00001);\n return vec4f(vec3f(cssEncodeChannel(straight.r), cssEncodeChannel(straight.g), cssEncodeChannel(straight.b)) * alpha, alpha);\n}\nfn cssToLinear(value: vec4f) -> vec4f {\n let alpha = clamp(value.a, 0.0, 1.0);\n let straight = select(vec3f(0.0), value.rgb / max(alpha, 0.00001), alpha > 0.00001);\n return vec4f(vec3f(cssDecodeChannel(straight.r), cssDecodeChannel(straight.g), cssDecodeChannel(straight.b)) * alpha, alpha);\n}\nfn cssSourceOver(front: vec4f, back: vec4f) -> vec4f {\n let encodedFront = cssToEncoded(front);\n let encodedBack = cssToEncoded(back);\n let remaining = 1.0 - encodedFront.a;\n return cssToLinear(encodedFront + encodedBack * remaining);\n}\nfn cssMix(front: vec4f, back: vec4f, weight: f32) -> vec4f {\n return cssToLinear(mix(cssToEncoded(back), cssToEncoded(front), weight));\n}`;\n var cssSceneDecodeWgsl = `\nstruct Draw { viewport: vec4f };\n@group(0) @binding(0) var<uniform> draw: Draw;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var source: texture_2d<f32>;\nstruct VOut { @builtin(position) position: vec4f, @location(0) uv: vec2f };\n@vertex fn vs(@builtin(vertex_index) i: u32) -> VOut {\n let xy = array<vec2f, 6>(vec2f(0,0), vec2f(1,0), vec2f(0,1), vec2f(0,1), vec2f(1,0), vec2f(1,1))[i];\n var out: VOut;\n out.position = vec4f(2.0 * xy.x - 1.0, 1.0 - 2.0 * xy.y, 0.0, 1.0);\n out.uv = xy;\n return out;\n}\nfn cssDecode(v: f32) -> f32 {\n let bounded = clamp(v, 0.0, 1.0);\n return select(pow((bounded + 0.055) / 1.055, 2.4), bounded / 12.92, bounded <= 0.04045);\n}\n@fragment fn fs(input: VOut) -> @location(0) vec4f {\n let uv = input.position.xy / draw.viewport.xy;\n let encoded = textureSample(source, samp, uv);\n let straight = select(vec3f(0.0), encoded.rgb / max(encoded.a, 0.00001), encoded.a > 0.00001);\n return vec4f(vec3f(cssDecode(straight.r), cssDecode(straight.g), cssDecode(straight.b)) * encoded.a, encoded.a);\n}`;\n var groupLocalBackdropSourceWgsl = `\nstruct Draw { extent: vec4f, sourceBox: vec4f };\n@group(0) @binding(0) var<uniform> draw: Draw;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var source: texture_2d<f32>;\nstruct VOut { @builtin(position) position: vec4f };\n@vertex fn vs(@builtin(vertex_index) i: u32) -> VOut {\n let xy = array<vec2f, 6>(vec2f(0,0), vec2f(1,0), vec2f(0,1), vec2f(0,1), vec2f(1,0), vec2f(1,1))[i];\n var out: VOut;\n out.position = vec4f(2.0 * xy.x - 1.0, 1.0 - 2.0 * xy.y, 0.0, 1.0);\n return out;\n}\nfn cssDecode(v: f32) -> f32 {\n let bounded = clamp(v, 0.0, 1.0);\n return select(pow((bounded + 0.055) / 1.055, 2.4), bounded / 12.92, bounded <= 0.04045);\n}\nfn linearPremult(encoded: vec4f) -> vec4f {\n let alpha = clamp(encoded.a, 0.0, 1.0);\n let straight = select(vec3f(0.0), encoded.rgb / max(alpha, 0.00001), alpha > 0.00001);\n return vec4f(vec3f(cssDecode(straight.r), cssDecode(straight.g), cssDecode(straight.b)) * alpha, alpha);\n}\nfn samplePixel(pixel: vec2i) -> vec4f {\n return textureLoad(source, pixel, 0);\n}\n@fragment fn fs(input: VOut) -> @location(0) vec4f {\n if (draw.extent.w > 0.5) {\n let pixel = vec2i(input.position.xy) + vec2i(draw.sourceBox.xy);\n let encoded = samplePixel(pixel);\n return select(encoded, linearPremult(encoded), draw.extent.z > 0.5);\n }\n let scaled = input.position.xy * draw.sourceBox.zw;\n let normalized = scaled / draw.extent.xy;\n let coordinate = draw.sourceBox.xy + normalized - vec2f(0.5);\n let base = vec2i(floor(coordinate));\n let fraction = fract(coordinate);\n var p00 = samplePixel(base);\n var p10 = samplePixel(base + vec2i(1, 0));\n var p01 = samplePixel(base + vec2i(0, 1));\n var p11 = samplePixel(base + vec2i(1, 1));\n if (draw.extent.z > 0.5) {\n p00 = linearPremult(p00);\n p10 = linearPremult(p10);\n p01 = linearPremult(p01);\n p11 = linearPremult(p11);\n }\n return mix(mix(p00, p10, fraction.x), mix(p01, p11, fraction.x), fraction.y);\n}`;\n var fillCompositeWgsl = `\nstruct Draw { viewport: vec4f };\n@group(0) @binding(0) var<uniform> draw: Draw;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var foreground: texture_2d<f32>;\n@group(0) @binding(3) var background: texture_2d<f32>;\nstruct VOut { @builtin(position) position: vec4f, @location(0) uv: vec2f };\n@vertex fn vs(@builtin(vertex_index) i: u32) -> VOut {\n let xy = array<vec2f, 6>(vec2f(0,0), vec2f(1,0), vec2f(0,1), vec2f(0,1), vec2f(1,0), vec2f(1,1))[i];\n var out: VOut;\n out.position = vec4f(2.0 * xy.x - 1.0, 1.0 - 2.0 * xy.y, 0.0, 1.0);\n out.uv = xy;\n return out;\n}\n${cssPremultBlendWgsl}\n@fragment fn fs(input: VOut) -> @location(0) vec4f {\n let uv = input.position.xy / draw.viewport.xy;\n let front = textureSample(foreground, samp, uv);\n let back = textureSample(background, samp, uv);\n let remaining = 1.0 - clamp(front.a, 0.0, 1.0);\n if (draw.viewport.z > 0.5) { return cssSourceOver(front, back); }\n return vec4f(front.rgb + back.rgb * remaining, front.a + back.a * remaining);\n}`;\n var fillPresentationWgsl = `\nstruct Draw { viewport: vec4f, origin: vec4f };\n@group(0) @binding(0) var<uniform> draw: Draw;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var children: texture_2d<f32>;\n@group(0) @binding(3) var fill: texture_2d<f32>;\nstruct VOut { @builtin(position) position: vec4f };\n@vertex fn vs(@builtin(vertex_index) i: u32) -> VOut {\n let xy = array<vec2f, 6>(vec2f(0,0), vec2f(1,0), vec2f(0,1), vec2f(0,1), vec2f(1,0), vec2f(1,1))[i];\n var out: VOut;\n out.position = vec4f(2.0 * xy.x - 1.0, 1.0 - 2.0 * xy.y, 0.0, 1.0);\n return out;\n}\n${cssPremultBlendWgsl}\n@fragment fn fs(input: VOut) -> @location(0) vec4f {\n let pixel = vec2i(input.position.xy);\n let fillPixel = pixel - vec2i(draw.origin.xy);\n var back = vec4f(0.0);\n if (all(fillPixel >= vec2i(0)) && all(fillPixel < vec2i(textureDimensions(fill)))) {\n back = textureLoad(fill, fillPixel, 0);\n }\n let front = textureSampleLevel(children, samp, (vec2f(pixel) + vec2f(0.5)) / draw.viewport.xy, 0.0);\n let top = select(front, back, draw.origin.z > 0.5);\n let below = select(back, front, draw.origin.z > 0.5);\n let remaining = 1.0 - clamp(top.a, 0.0, 1.0);\n if (draw.viewport.z > 0.5) { return cssSourceOver(top, below); }\n return vec4f(top.rgb + below.rgb * remaining, top.a + below.a * remaining);\n}`;\n var fillCoveredUnderlayWgsl = `\nstruct Draw { viewport: vec4f, cssBlend: vec4f };\n@group(0) @binding(0) var<uniform> draw: Draw;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var effect: texture_2d<f32>;\n@group(0) @binding(3) var previous: texture_2d<f32>;\n@group(0) @binding(4) var outerCoverage: texture_2d<f32>;\n@group(0) @binding(5) var innerCoverage: texture_2d<f32>;\nstruct VOut { @builtin(position) position: vec4f, @location(0) uv: vec2f };\n@vertex fn vs(@builtin(vertex_index) i: u32) -> VOut {\n let xy = array<vec2f, 6>(vec2f(0,0), vec2f(1,0), vec2f(0,1), vec2f(0,1), vec2f(1,0), vec2f(1,1))[i];\n var out: VOut;\n out.position = vec4f(2.0 * xy.x - 1.0, 1.0 - 2.0 * xy.y, 0.0, 1.0);\n out.uv = xy;\n return out;\n}\n${cssPremultBlendWgsl}\n@fragment fn fs(input: VOut) -> @location(0) vec4f {\n let outer = clamp(textureSample(outerCoverage, samp, input.uv).a, 0.0, 1.0);\n let sampledInner = textureSample(innerCoverage, samp, input.uv).a;\n let prior = textureSample(previous, samp, input.uv);\n let sampledEffect = textureSample(effect, samp, input.uv);\n if (outer <= 0.000001) { return vec4f(0.0); }\n let inner = min(outer, clamp(sampledInner, 0.0, 1.0));\n let back = select(prior, vec4f(prior.rgb * prior.a, prior.a) / outer, draw.viewport.z > 0.5);\n let front = select(sampledEffect * (inner / outer), sampledEffect / outer, draw.viewport.w > 0.5);\n let remaining = 1.0 - clamp(front.a, 0.0, 1.0);\n if (draw.cssBlend.x > 0.5) { return cssSourceOver(front, back); }\n return vec4f(front.rgb + back.rgb * remaining, front.a + back.a * remaining);\n}`;\n var fillCoveredBoxWgsl = `\nstruct Draw { viewport: vec4f, cssBlend: vec4f };\n@group(0) @binding(0) var<uniform> draw: Draw;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var underlay: texture_2d<f32>;\n@group(0) @binding(3) var border: texture_2d<f32>;\n@group(0) @binding(4) var outerCoverage: texture_2d<f32>;\nstruct VOut { @builtin(position) position: vec4f, @location(0) uv: vec2f };\n@vertex fn vs(@builtin(vertex_index) i: u32) -> VOut {\n let xy = array<vec2f, 6>(vec2f(0,0), vec2f(1,0), vec2f(0,1), vec2f(0,1), vec2f(1,0), vec2f(1,1))[i];\n var out: VOut;\n out.position = vec4f(2.0 * xy.x - 1.0, 1.0 - 2.0 * xy.y, 0.0, 1.0);\n out.uv = xy;\n return out;\n}\n${cssPremultBlendWgsl}\n@fragment fn fs(input: VOut) -> @location(0) vec4f {\n let uv = input.position.xy / draw.viewport.xy;\n let outer = clamp(textureSample(outerCoverage, samp, uv).a, 0.0, 1.0);\n let prior = textureSample(underlay, samp, uv);\n let sampledBorder = textureSample(border, samp, uv);\n if (outer <= 0.000001) { return vec4f(0.0); }\n let borderPixel = vec4f(sampledBorder.rgb * sampledBorder.a, sampledBorder.a) / outer;\n let remaining = 1.0 - clamp(borderPixel.a, 0.0, 1.0);\n if (draw.cssBlend.x > 0.5) { return cssSourceOver(borderPixel, prior) * outer; }\n return vec4f(borderPixel.rgb + prior.rgb * remaining, borderPixel.a + prior.a * remaining) * outer;\n}`;\n var fillTextMixWgsl = `\nstruct Draw { viewport: vec4f };\n@group(0) @binding(0) var<uniform> draw: Draw;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var effectAtUnitOpacity: texture_2d<f32>;\n@group(0) @binding(3) var previousGlyph: texture_2d<f32>;\nstruct VOut { @builtin(position) position: vec4f, @location(0) uv: vec2f };\n@vertex fn vs(@builtin(vertex_index) i: u32) -> VOut {\n let xy = array<vec2f, 6>(vec2f(0,0), vec2f(1,0), vec2f(0,1), vec2f(0,1), vec2f(1,0), vec2f(1,1))[i];\n var out: VOut;\n out.position = vec4f(2.0 * xy.x - 1.0, 1.0 - 2.0 * xy.y, 0.0, 1.0);\n out.uv = xy;\n return out;\n}\n${cssPremultBlendWgsl}\n@fragment fn fs(input: VOut) -> @location(0) vec4f {\n let front = textureSample(effectAtUnitOpacity, samp, input.uv);\n let previous = textureSample(previousGlyph, samp, input.uv);\n let weight = clamp(draw.viewport.z, 0.0, 1.0);\n if (draw.viewport.w > 0.5) { return cssMix(front, previous, weight); }\n return mix(previous, front, weight);\n}`;\n var srgbEncodeWgsl = `\nfn encode(v: f32) -> f32 {\n return select(1.055 * pow(max(v, 0.0), 1.0 / 2.4) - 0.055, 12.92 * v, v <= 0.0031308);\n}`;\n var presentWgsl = (mode) => `\nstruct Draw { viewport: vec4f, opacity: vec4f };\n@group(0) @binding(0) var<uniform> draw: Draw;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var source: texture_2d<f32>;\n@group(0) @binding(3) var mask: texture_2d<f32>;\nstruct VOut { @builtin(position) position: vec4f, @location(0) uv: vec2f };\n@vertex fn vs(@builtin(vertex_index) i: u32) -> VOut {\n let xy = array<vec2f, 6>(vec2f(0,0), vec2f(1,0), vec2f(0,1), vec2f(0,1), vec2f(1,0), vec2f(1,1))[i];\n var out: VOut;\n out.position = vec4f(2.0 * xy.x - 1.0, 1.0 - 2.0 * xy.y, 0.0, 1.0);\n out.uv = xy;\n return out;\n}\n${srgbEncodeWgsl}\n${mode === "display-p3" ? LINEAR_SRGB_TO_DISPLAY_P3_WGSL : ""}\n@fragment fn fs(input: VOut) -> @location(0) vec4f {\n let c = textureSample(source, samp, input.uv);\n let m = textureSample(mask, samp, input.uv).a;\n let a = clamp(c.a * m * draw.opacity.x, 0.0, 1.0);\n let straight = select(vec3f(0.0), c.rgb / max(c.a, 0.00001), c.a > 0.00001);\n let displayColor = ${mode === "display-p3" ? "linearSrgbToDisplayP3(straight)" : "straight"};\n return vec4f(vec3f(encode(displayColor.r), encode(displayColor.g), encode(displayColor.b)) * a, a);\n}`;\n var exportPixelsWgsl = `\nstruct Draw { viewport: vec4f, opacity: vec4f };\n@group(0) @binding(0) var<uniform> draw: Draw;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var source: texture_2d<f32>;\nstruct VOut { @builtin(position) position: vec4f, @location(0) uv: vec2f };\n@vertex fn vs(@builtin(vertex_index) i: u32) -> VOut {\n let xy = array<vec2f, 6>(vec2f(0,0), vec2f(1,0), vec2f(0,1), vec2f(0,1), vec2f(1,0), vec2f(1,1))[i];\n var out: VOut;\n out.position = vec4f(2.0 * xy.x - 1.0, 1.0 - 2.0 * xy.y, 0.0, 1.0);\n out.uv = xy;\n return out;\n}\n${srgbEncodeWgsl}\n@fragment fn fs(input: VOut) -> @location(0) vec4f {\n let premult = textureSample(source, samp, input.uv);\n let straight = select(vec3f(0.0), premult.rgb / max(premult.a, 0.00001), premult.a > 0.00001);\n return vec4f(encode(straight.r), encode(straight.g), encode(straight.b), clamp(premult.a * draw.opacity.x, 0.0, 1.0));\n}`;\n var finishWgsl = `\nstruct Draw { viewport: vec4f, opacity: vec4f, clipRect: vec4f, radiiTop: vec4f, radiiBottom: vec4f, transformX: vec4f, transformY: vec4f };\n@group(0) @binding(0) var<uniform> draw: Draw;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var source: texture_2d<f32>;\n@group(0) @binding(3) var mask: texture_2d<f32>;\nstruct VOut { @builtin(position) position: vec4f, @location(0) uv: vec2f };\n@vertex fn vs(@builtin(vertex_index) i: u32) -> VOut {\n let xy = array<vec2f, 6>(vec2f(0,0), vec2f(1,0), vec2f(0,1), vec2f(0,1), vec2f(1,0), vec2f(1,1))[i];\n var out: VOut;\n out.position = vec4f(2.0 * xy.x - 1.0, 1.0 - 2.0 * xy.y, 0.0, 1.0);\n out.uv = xy;\n return out;\n}\n@fragment fn fs(input: VOut) -> @location(0) vec4f {\n let p = input.uv * draw.viewport.xy - draw.clipRect.xy;\n let size = draw.clipRect.zw;\n var inside = 1.0;\n let tl = draw.radiiTop.xy;\n let tr = draw.radiiTop.zw;\n let br = draw.radiiBottom.xy;\n let bl = draw.radiiBottom.zw;\n if (tl.x > 0.0 && tl.y > 0.0 && p.x < tl.x && p.y < tl.y) {\n let q = (p - tl) / tl;\n if (dot(q, q) > 1.0) { inside = 0.0; }\n }\n if (tr.x > 0.0 && tr.y > 0.0 && p.x > size.x - tr.x && p.y < tr.y) {\n let q = (p - vec2f(size.x - tr.x, tr.y)) / tr;\n if (dot(q, q) > 1.0) { inside = 0.0; }\n }\n if (br.x > 0.0 && br.y > 0.0 && p.x > size.x - br.x && p.y > size.y - br.y) {\n let q = (p - (size - br)) / br;\n if (dot(q, q) > 1.0) { inside = 0.0; }\n }\n if (bl.x > 0.0 && bl.y > 0.0 && p.x < bl.x && p.y > size.y - bl.y) {\n let q = (p - vec2f(bl.x, size.y - bl.y)) / bl;\n if (dot(q, q) > 1.0) { inside = 0.0; }\n }\n let sourceUv = vec2f(\n dot(draw.transformX.xyz, vec3f(input.uv, 1.0)),\n dot(draw.transformY.xyz, vec3f(input.uv, 1.0))\n );\n let withinSource = all(sourceUv >= vec2f(0.0)) && all(sourceUv <= vec2f(1.0));\n let sampled = textureSample(source, samp, clamp(sourceUv, vec2f(0.0), vec2f(1.0)));\n let c = select(vec4f(0.0), sampled, withinSource);\n let maskAlpha = textureSample(mask, samp, input.uv).a;\n let opacity = clamp(draw.opacity.x * inside, 0.0, 1.0);\n if (draw.opacity.y > 0.5) {\n let alpha = min(clamp(c.a, 0.0, 1.0), maskAlpha) * opacity;\n let rgb = select(vec3f(0.0), c.rgb * (alpha / max(c.a, 0.00001)), c.a > 0.00001);\n return vec4f(rgb, alpha);\n }\n return c * (opacity * maskAlpha);\n}`;\n var nativeWorkerExportRegionWgsl = `\nstruct Draw { viewport: vec4f, opacity: vec4f };\n@group(0) @binding(0) var<uniform> draw: Draw;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var source: texture_2d<f32>;\n@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {\n let xy = array<vec2f, 6>(vec2f(0,0), vec2f(1,0), vec2f(0,1), vec2f(0,1), vec2f(1,0), vec2f(1,1))[i];\n return vec4f(2.0 * xy.x - 1.0, 1.0 - 2.0 * xy.y, 0.0, 1.0);\n}\n${srgbEncodeWgsl}\n@fragment fn fs(@builtin(position) position: vec4f) -> @location(0) vec4f {\n let pixel = position.xy + draw.viewport.zw;\n if (any(pixel < vec2f(0.0)) || any(pixel >= draw.viewport.xy)) {\n return vec4f(0.0);\n }\n let premult = textureSampleLevel(source, samp, pixel / draw.viewport.xy, 0.0);\n let straight = select(vec3f(0.0), premult.rgb / max(premult.a, 0.00001), premult.a > 0.00001);\n return vec4f(encode(straight.r), encode(straight.g), encode(straight.b), clamp(premult.a * draw.opacity.x, 0.0, 1.0));\n}`;\n var inputMaskWgsl = `\nstruct Draw { viewport: vec4f, targetRect: vec4f, radiiTop: vec4f, radiiBottom: vec4f };\n@group(0) @binding(0) var<uniform> draw: Draw;\n@group(0) @binding(1) var samp: sampler;\n@group(0) @binding(2) var textCoverage: texture_2d<f32>;\nstruct VOut { @builtin(position) position: vec4f, @location(0) uv: vec2f };\n@vertex fn vs(@builtin(vertex_index) i: u32) -> VOut {\n let xy = array<vec2f, 6>(vec2f(0,0), vec2f(1,0), vec2f(0,1), vec2f(0,1), vec2f(1,0), vec2f(1,1))[i];\n var out: VOut;\n out.position = vec4f(2.0 * xy.x - 1.0, 1.0 - 2.0 * xy.y, 0.0, 1.0);\n out.uv = xy;\n return out;\n}\nfn ellipseCoverage(p: vec2f, center: vec2f, radii: vec2f) -> f32 {\n let q = p - center;\n let r = max(radii, vec2f(0.0001));\n let k0 = length(q / r);\n if (k0 < 0.00001) { return 1.0; }\n let k1 = length(q / (r * r));\n return clamp(0.5 - k0 * (k0 - 1.0) / max(k1, 0.00001), 0.0, 1.0);\n}\n@fragment fn fs(input: VOut) -> @location(0) vec4f {\n let p = input.uv * draw.viewport.xy - draw.targetRect.xy;\n let size = draw.targetRect.zw;\n var coverage = clamp(min(min(p.x, p.y), min(size.x - p.x, size.y - p.y)) + 0.5, 0.0, 1.0);\n let tl = draw.radiiTop.xy;\n let tr = draw.radiiTop.zw;\n let br = draw.radiiBottom.xy;\n let bl = draw.radiiBottom.zw;\n if (tl.x > 0.0 && tl.y > 0.0 && p.x < tl.x && p.y < tl.y) {\n coverage = min(coverage, ellipseCoverage(p, tl, tl));\n }\n if (tr.x > 0.0 && tr.y > 0.0 && p.x > size.x - tr.x && p.y < tr.y) {\n coverage = min(coverage, ellipseCoverage(p, vec2f(size.x - tr.x, tr.y), tr));\n }\n if (br.x > 0.0 && br.y > 0.0 && p.x > size.x - br.x && p.y > size.y - br.y) {\n coverage = min(coverage, ellipseCoverage(p, size - br, br));\n }\n if (bl.x > 0.0 && bl.y > 0.0 && p.x < bl.x && p.y > size.y - bl.y) {\n coverage = min(coverage, ellipseCoverage(p, vec2f(bl.x, size.y - bl.y), bl));\n }\n let alpha = coverage * textureSample(textCoverage, samp, input.uv).a;\n return vec4f(alpha, alpha, alpha, alpha);\n}`;\n\n // app/components/design/bridge/native-worker-compositor.ts\n var MAX_SOURCE_CLIPS = 8;\n var IDENTITY = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };\n var NativeWorkerCompositionError = class extends Error {\n constructor(code, message = code) {\n super(message);\n this.code = code;\n this.name = "NativeWorkerCompositionError";\n }\n };\n function failure(code, message = code) {\n throw new NativeWorkerCompositionError(code, message);\n }\n function intersects(a, b) {\n return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;\n }\n function validateTexture(texture, id) {\n if (!texture)\n failure(\n "native-dependency-missing",\n `Source ${id} has no rendered GPU texture.`\n );\n return texture;\n }\n function packNativeWorkerCompositeDraw(input) {\n const { item, physicalScale, origin, viewport, blendMode } = input;\n if (item.clips.length > MAX_SOURCE_CLIPS)\n failure(\n "source-clip-depth-unsupported",\n `A source requires more than ${MAX_SOURCE_CLIPS} nested clips.`\n );\n const affine = planNativeSourceAffine({\n localBox: item.localBox,\n localToTarget: item.localToTarget,\n physicalScale\n });\n if (!affine.ok)\n failure(\n `source-affine-${affine.reason}`,\n `Source ${item.id} has unsupported affine geometry: ${affine.reason}.`\n );\n const data = new Float32Array(36 + MAX_SOURCE_CLIPS * 20);\n data.set([\n item.rect.x * physicalScale.x,\n item.rect.y * physicalScale.y,\n item.rect.width * physicalScale.x,\n item.rect.height * physicalScale.y,\n viewport.width,\n viewport.height,\n input.pixelated?.x ?? 0,\n input.pixelated?.y ?? 0,\n item.opacity,\n item.premultiplied ? 1 : 0,\n item.groupResolve ? 0 : blendMode !== "linear" ? 1 : 0,\n item.groupResolve ? 1 : item.encodedScene ? 1 : 0,\n item.uv?.x ?? 0,\n item.uv?.y ?? 0,\n item.uv?.width ?? 1,\n item.uv?.height ?? 1,\n item.clips.length,\n 0,\n 0,\n 0,\n origin.x,\n origin.y,\n 0,\n 0,\n item.localBox.x,\n item.localBox.y,\n item.localBox.width,\n item.localBox.height,\n affine.physicalToLocal.a,\n affine.physicalToLocal.c,\n affine.physicalToLocal.e,\n 0,\n affine.physicalToLocal.b,\n affine.physicalToLocal.d,\n affine.physicalToLocal.f,\n 0\n ]);\n for (let index = 0; index < item.clips.length; index += 1) {\n const clip = item.clips[index];\n const clipAffine = planNativeSourceAffine({\n localBox: clip.localBox,\n localToTarget: clip.localToTarget,\n physicalScale\n });\n if (!clipAffine.ok)\n failure(\n `source-affine-${clipAffine.reason}`,\n `Source clip ${index} has unsupported affine geometry: ${clipAffine.reason}.`\n );\n data.set(\n [\n clip.localBox.x,\n clip.localBox.y,\n clip.localBox.width,\n clip.localBox.height,\n clip.radii.topLeft.x,\n clip.radii.topLeft.y,\n clip.radii.topRight.x,\n clip.radii.topRight.y,\n clip.radii.bottomRight.x,\n clip.radii.bottomRight.y,\n clip.radii.bottomLeft.x,\n clip.radii.bottomLeft.y,\n clipAffine.physicalToLocal.a,\n clipAffine.physicalToLocal.c,\n clipAffine.physicalToLocal.e,\n 0,\n clipAffine.physicalToLocal.b,\n clipAffine.physicalToLocal.d,\n clipAffine.physicalToLocal.f,\n 0\n ],\n 36 + index * 20\n );\n }\n return data;\n }\n async function composeNativeWorkerScene(input) {\n const { scene, records, encoder, bank, gpu, format, resolveRecord } = input;\n const surface = input.surface ?? {\n width: scene.width,\n height: scene.height,\n pixelRatio: scene.pixelRatio,\n viewport: scene.viewport\n };\n const outputName = input.outputName ?? "source";\n const blendMode = input.blendMode ?? "linear";\n const extent = surface.outputExtent;\n const physicalRoot = planNativePhysicalRootBox({\n width: surface.width,\n height: surface.height,\n left: extent?.left ?? 0,\n top: extent?.top ?? 0,\n origin: surface.viewport ? {\n x: Math.round(surface.viewport.x * surface.pixelRatio),\n y: Math.round(surface.viewport.y * surface.pixelRatio)\n } : void 0\n });\n if (!physicalRoot.ok) failure("source-capture-geometry-invalid");\n const rootBox = physicalRoot.box;\n const globalLocal = records.some(\n (record4) => record4.coordinateSpace === "target-local-global"\n );\n const local = surface.targetLocalSize ?? {\n width: surface.width / surface.pixelRatio,\n height: surface.height / surface.pixelRatio\n };\n const viewportSize = surface.targetViewportSize ?? surface.viewport ?? local;\n const sourceScale = surface.viewport && surface.pixelRatio ? { ok: true, x: surface.pixelRatio, y: surface.pixelRatio } : planNativeSourceCoordinateScale({\n spaces: records.map((record4) => record4.coordinateSpace),\n sourceWidth: globalLocal ? local.width * surface.pixelRatio : extent?.sourceWidth ?? surface.width,\n sourceHeight: globalLocal ? local.height * surface.pixelRatio : extent?.sourceHeight ?? surface.height,\n localWidth: !extent && surface.pixelRatio ? surface.width / surface.pixelRatio : local.width,\n localHeight: !extent && surface.pixelRatio ? surface.height / surface.pixelRatio : local.height,\n viewportWidth: viewportSize.width,\n viewportHeight: viewportSize.height\n });\n if (!sourceScale.ok) failure(sourceScale.code);\n const scaleX = sourceScale.x;\n const scaleY = sourceScale.y;\n const source = bank.texture(outputName, surface.width, surface.height);\n let compositionTarget = blendMode === "srgb-css-linear" ? bank.texture(\n `css-intermediate:${outputName}`,\n surface.width,\n surface.height\n ) : source;\n const rootPlanes = {\n primary: compositionTarget,\n companion: blendMode === "srgb-css-linear" ? source : void 0,\n key: outputName\n };\n const replacementTarget = (planes, current, width, height) => {\n if (current !== planes.primary && current !== planes.companion || planes.primary.width !== width || planes.primary.height !== height)\n failure("source-composition-plane-unavailable");\n if (!planes.companion)\n planes.companion = bank.texture(\n `backdrop-replacement:${planes.key}`,\n width,\n height\n );\n const next = current === planes.primary ? planes.companion : planes.primary;\n if (next === current || next.width !== width || next.height !== height)\n failure("source-composition-plane-unavailable");\n return next;\n };\n const compositePipeline = await gpu.pipeline(compositeWgsl, format, true, 1);\n const groupClips = /* @__PURE__ */ new Map();\n for (const record4 of records)\n for (const group of record4.groupClips) {\n const previous = groupClips.get(group.id);\n if (previous && JSON.stringify(previous) !== JSON.stringify(group.clip))\n failure(\n "source-clip-inconsistent",\n `Source clip ${group.id} changed within one composition frame.`\n );\n groupClips.set(group.id, group.clip);\n }\n const leaves = new Map(\n records.map((record4) => [`leaf:${record4.key}`, record4])\n );\n const planned = planNativeSourceComposition(\n records.map((record4) => ({\n id: `leaf:${record4.key}`,\n box: record4.rect,\n opacity: record4.opacity,\n ownOpacityBaked: !!record4.nativeInstanceId,\n isolationPath: record4.isolationPath\n }))\n );\n if (!planned.ok) failure(`source-${planned.reason}`, planned.detail);\n const resolved = /* @__PURE__ */ new Map();\n for (const record4 of records) {\n if (surface.viewport && (!intersects(surface.viewport, record4.rect) || !intersects(surface.viewport, record4.clip)))\n continue;\n const value = await resolveRecord(record4, {\n encoder,\n currentScene: null,\n incoming: null,\n encodedScene: blendMode !== "linear"\n });\n if (!value.texture && !value.backdropReplacement)\n failure(\n "native-dependency-missing",\n `Source ${record4.key} has no texture.`\n );\n if (record4.sourceRole === "ancestor-fill-prefix" && !value.texture)\n failure(\n "native-dependency-missing",\n "The staged ancestor Fill prefix is unavailable."\n );\n if (record4.nativeInstanceId && value.texture && record4.imageRendering && (record4.width !== value.texture.width || record4.height !== value.texture.height))\n failure("source-image-rendering-geometry");\n resolved.set(`leaf:${record4.key}`, value);\n }\n const hasBackdropReplacement = (node) => node.kind === "group" ? node.children.some(hasBackdropReplacement) : !!resolved.get(node.id)?.backdropReplacement;\n const drawItems = async (items, destination, originX, originY, width, height, scratchKey, initiallyDrawn = false, planes = { primary: destination, key: scratchKey }) => {\n let current = destination;\n let drawn = initiallyDrawn;\n let commands = [];\n const flush = () => {\n if (!commands.length && drawn) return;\n const pass2 = encoder.beginRenderPass({\n colorAttachments: [\n {\n view: current.createView(),\n loadOp: drawn ? "load" : "clear",\n storeOp: "store",\n clearValue: { r: 0, g: 0, b: 0, a: 0 }\n }\n ]\n });\n for (const command of commands) {\n pass2.setPipeline(compositePipeline);\n pass2.setBindGroup(0, command.bind);\n pass2.setScissorRect(command.x, command.y, command.w, command.h);\n pass2.draw(6);\n }\n pass2.end();\n commands = [];\n drawn = true;\n };\n for (const item of items) {\n if ("kind" in item) {\n flush();\n const groupKey = `${scratchKey}:deferred:${item.node.isolationKind}:${item.node.id}`;\n const clipShape = item.node.clipId ? groupClips.get(item.node.clipId) : void 0;\n if (item.node.isolationKind === "clip" && !clipShape)\n failure(\n "source-clip-missing",\n `Group ${item.node.id} has no clip geometry.`\n );\n const parentBox = {\n x: originX / scaleX,\n y: originY / scaleY,\n width: width / scaleX,\n height: height / scaleY\n };\n const containsParent = (box) => box.x <= parentBox.x && box.y <= parentBox.y && box.x + box.width >= parentBox.x + parentBox.width && box.y + box.height >= parentBox.y + parentBox.height;\n const radii = clipShape?.radii;\n const squareClip = radii && Object.values(radii).every(\n (corner) => corner.x === 0 && corner.y === 0\n );\n if (item.node.opacity === 1 && (item.node.isolationKind === "opacity" || clipShape && squareClip && containsParent(clipShape.rect) && clipShape.localToTarget.b === 0 && clipShape.localToTarget.c === 0)) {\n current = await drawItems(\n item.children,\n current,\n originX,\n originY,\n width,\n height,\n groupKey,\n true,\n planes\n );\n drawn = true;\n continue;\n }\n const clipBox = clipShape?.rect ?? item.node.box;\n const left = Math.max(\n originX,\n Math.floor(Math.max(item.node.box.x, clipBox.x) * scaleX)\n );\n const top = Math.max(\n originY,\n Math.floor(Math.max(item.node.box.y, clipBox.y) * scaleY)\n );\n const right = Math.min(\n originX + width,\n Math.ceil(\n Math.min(\n item.node.box.x + item.node.box.width,\n clipBox.x + clipBox.width\n ) * scaleX\n )\n );\n const bottom = Math.min(\n originY + height,\n Math.ceil(\n Math.min(\n item.node.box.y + item.node.box.height,\n clipBox.y + clipBox.height\n ) * scaleY\n )\n );\n if (right <= left || bottom <= top) continue;\n const groupWidth = right - left;\n const groupHeight = bottom - top;\n const groupTexture = bank.texture(\n `${groupKey}:working`,\n groupWidth,\n groupHeight\n );\n const fullBox = parentBox;\n const groupBox = {\n x: left / scaleX,\n y: top / scaleY,\n width: groupWidth / scaleX,\n height: groupHeight / scaleY\n };\n const seed = {\n id: `${groupKey}:incoming`,\n texture: current,\n rect: fullBox,\n localBox: fullBox,\n localToTarget: IDENTITY,\n clip: fullBox,\n clips: [],\n opacity: 1,\n premultiplied: true,\n encodedScene: blendMode !== "linear",\n backdropReplacement: false\n };\n const groupResult = await drawItems(\n [seed, ...item.children],\n groupTexture,\n left,\n top,\n groupWidth,\n groupHeight,\n groupKey\n );\n const resolve = {\n id: `${groupKey}:resolve`,\n texture: groupResult,\n rect: item.node.box,\n localBox: groupBox,\n localToTarget: IDENTITY,\n clip: item.node.box,\n clips: clipShape ? [clipShape] : [],\n opacity: item.node.opacity,\n premultiplied: true,\n encodedScene: blendMode !== "linear",\n backdropReplacement: true,\n groupResolve: true\n };\n current = await drawItems(\n [resolve],\n current,\n originX,\n originY,\n width,\n height,\n `${groupKey}:resolve`,\n true,\n planes\n );\n drawn = true;\n continue;\n }\n const clip = item.clip;\n const x = Math.max(0, Math.floor(clip.x * scaleX) - originX);\n const y = Math.max(0, Math.floor(clip.y * scaleY) - originY);\n const w = Math.min(width, Math.ceil((clip.x + clip.width) * scaleX) - originX) - x;\n const h = Math.min(height, Math.ceil((clip.y + clip.height) * scaleY) - originY) - y;\n if (w <= 0 || h <= 0) continue;\n if (item.backdropReplacement && item.record) {\n flush();\n let window;\n if (item.nestedBackdrop) {\n const plannedWindow = planNativeGroupLocalBackdropWindow({\n incoming: { x: originX, y: originY, width, height },\n output: item.nestedBackdrop.output,\n extent: item.nestedBackdrop.extent,\n localBox: item.localBox,\n localToTarget: item.localToTarget,\n physicalScale: { x: scaleX, y: scaleY },\n receiverClip: item.clip\n });\n if (!plannedWindow.ok)\n failure(\n "source-group-local-geometry-unsupported",\n plannedWindow.reason\n );\n window = plannedWindow.plan;\n }\n const staged = await resolveRecord(item.record, {\n encoder,\n currentScene: current,\n incoming: { x: originX, y: originY, width, height },\n encodedScene: blendMode !== "linear",\n window\n });\n if (staged.backdropReplacement === false)\n failure("backdrop-replacement-unavailable");\n item.texture = validateTexture(staged.texture, item.id);\n if (item.imageSampling && (item.imageSampling.sourceSize.width !== item.texture.width || item.imageSampling.sourceSize.height !== item.texture.height))\n failure("source-image-rendering-geometry");\n item.opacity = staged.opacity ?? item.opacity;\n item.premultiplied = staged.premultiplied ?? item.premultiplied;\n item.encodedScene = staged.encodedScene ?? item.encodedScene;\n item.receiverCoverage = staged.receiverCoverage ?? item.receiverCoverage;\n }\n const texture = validateTexture(item.texture, item.id);\n const sampling = planNativeImageSampling({\n imageRendering: item.imageSampling?.imageRendering,\n sourceSize: item.imageSampling?.sourceSize ?? {\n width: texture.width,\n height: texture.height\n },\n uploadedSize: { width: texture.width, height: texture.height },\n localBox: item.localBox,\n localToTarget: item.localToTarget,\n physicalScale: { x: scaleX, y: scaleY },\n uv: item.uv\n });\n if (!sampling.ok) failure(`source-image-rendering-${sampling.reason}`);\n const data = packNativeWorkerCompositeDraw({\n item,\n physicalScale: { x: scaleX, y: scaleY },\n origin: { x: originX, y: originY },\n viewport: { width, height },\n pixelated: sampling.pixelated,\n blendMode\n });\n if (item.backdropReplacement) {\n flush();\n const pipeline = await gpu.pipeline(\n backdropReplaceWgsl(!!item.receiverCoverage),\n format,\n false,\n item.receiverCoverage ? 3 : 2\n );\n const next = replacementTarget(planes, current, width, height);\n if (next === texture) failure("source-composition-plane-unavailable");\n const bind2 = gpu.bind(\n `scene:${item.id}:replace`,\n pipeline,\n current,\n texture,\n data,\n gpu.sampler(sampling.filter),\n item.receiverCoverage ? [item.receiverCoverage] : []\n );\n const pass2 = encoder.beginRenderPass({\n colorAttachments: [\n {\n view: next.createView(),\n loadOp: "clear",\n storeOp: "store",\n clearValue: { r: 0, g: 0, b: 0, a: 0 }\n }\n ]\n });\n pass2.setPipeline(pipeline);\n pass2.setBindGroup(0, bind2);\n pass2.draw(3);\n pass2.end();\n current = next;\n drawn = true;\n continue;\n }\n commands.push({\n bind: gpu.bind(\n `scene:${item.id}`,\n compositePipeline,\n texture,\n null,\n data,\n gpu.sampler(sampling.filter)\n ),\n x,\n y,\n w,\n h\n });\n }\n flush();\n return current;\n };\n const renderNode = async (node) => {\n if (node.kind === "leaf") {\n const record4 = leaves.get(node.id);\n if (!record4)\n failure("source-record-missing", `Source ${node.id} was not found.`);\n if (surface.viewport && (!intersects(surface.viewport, record4.rect) || !intersects(surface.viewport, record4.clip)))\n return null;\n const value = resolved.get(node.id);\n if (!value)\n failure(\n "native-dependency-missing",\n `Source ${node.id} was not resolved.`\n );\n return {\n id: node.id,\n record: record4,\n texture: value.texture,\n rect: record4.rect,\n localBox: record4.localBox,\n localToTarget: record4.localToTarget,\n clip: record4.clip,\n clips: record4.clips,\n opacity: value.opacity ?? node.opacity,\n premultiplied: value.premultiplied ?? !!record4.nativeInstanceId,\n encodedScene: value.encodedScene ?? false,\n backdropReplacement: value.backdropReplacement ?? false,\n receiverCoverage: value.receiverCoverage,\n nestedBackdrop: value.nestedBackdrop,\n uv: record4.uv,\n imageSampling: record4.imageRendering ? {\n imageRendering: record4.imageRendering,\n sourceSize: { width: record4.width, height: record4.height }\n } : void 0\n };\n }\n const children = [];\n for (const child of node.children) {\n const item = await renderNode(child);\n if (item) children.push(item);\n }\n if (hasBackdropReplacement(node))\n return { kind: "deferred-group", node, children };\n if (node.isolationKind === "root" || !node.isolate)\n failure("source-isolation-invalid", `Group ${node.id} was not isolated.`);\n const clipShape = node.clipId ? groupClips.get(node.clipId) : void 0;\n if (node.isolationKind === "clip" && !clipShape)\n failure("source-clip-missing", `Group ${node.id} has no clip geometry.`);\n const box = clipShape ? {\n x: Math.max(node.box.x, clipShape.rect.x),\n y: Math.max(node.box.y, clipShape.rect.y),\n width: Math.max(\n 0,\n Math.min(\n node.box.x + node.box.width,\n clipShape.rect.x + clipShape.rect.width\n ) - Math.max(node.box.x, clipShape.rect.x)\n ),\n height: Math.max(\n 0,\n Math.min(\n node.box.y + node.box.height,\n clipShape.rect.y + clipShape.rect.height\n ) - Math.max(node.box.y, clipShape.rect.y)\n )\n } : node.box;\n const left = Math.max(rootBox.x, Math.floor(box.x * scaleX));\n const top = Math.max(rootBox.y, Math.floor(box.y * scaleY));\n const right = Math.min(\n rootBox.x + rootBox.width,\n Math.ceil((box.x + box.width) * scaleX)\n );\n const bottom = Math.min(\n rootBox.y + rootBox.height,\n Math.ceil((box.y + box.height) * scaleY)\n );\n if (right <= left || bottom <= top) return null;\n const width = right - left;\n const height = bottom - top;\n const groupKey = `${blendMode}:${node.isolationKind}:${node.id}`;\n const groupTexture = await drawItems(\n children,\n bank.texture(groupKey, width, height),\n left,\n top,\n width,\n height,\n groupKey\n );\n const rect = {\n x: left / scaleX,\n y: top / scaleY,\n width: width / scaleX,\n height: height / scaleY\n };\n return {\n id: `group:${groupKey}`,\n texture: groupTexture,\n rect,\n localBox: rect,\n localToTarget: IDENTITY,\n clip: clipShape?.rect ?? rect,\n clips: clipShape ? [clipShape] : [],\n opacity: node.opacity,\n premultiplied: true,\n encodedScene: blendMode !== "linear",\n backdropReplacement: false\n };\n };\n const rootItems = [];\n for (const child of planned.root.children) {\n const item = await renderNode(child);\n if (item) rootItems.push(item);\n }\n compositionTarget = await drawItems(\n rootItems,\n compositionTarget,\n rootBox.x,\n rootBox.y,\n rootBox.width,\n rootBox.height,\n outputName,\n false,\n rootPlanes\n );\n if (blendMode !== "srgb-css-linear") return compositionTarget;\n const decoded = compositionTarget === source ? rootPlanes.primary : source;\n if (compositionTarget !== rootPlanes.primary && compositionTarget !== rootPlanes.companion || decoded === compositionTarget)\n failure("source-composition-plane-unavailable");\n const decodePipeline = await gpu.pipeline(\n cssSceneDecodeWgsl,\n format,\n false,\n 1\n );\n const bind = gpu.bind(\n `scene:${outputName}:decode-srgb`,\n decodePipeline,\n compositionTarget,\n null,\n new Float32Array([surface.width, surface.height, 0, 0])\n );\n const pass = encoder.beginRenderPass({\n colorAttachments: [\n {\n view: decoded.createView(),\n loadOp: "clear",\n storeOp: "store",\n clearValue: { r: 0, g: 0, b: 0, a: 0 }\n }\n ]\n });\n pass.setPipeline(decodePipeline);\n pass.setBindGroup(0, bind);\n pass.draw(6);\n pass.end();\n return decoded;\n }\n\n // app/components/design/bridge/native-effect-extent.ts\n function planNativeFillPresentationExtent(input) {\n const { fill, foreground, maxDimension, maxPixels } = input;\n let left = fill.left;\n let top = fill.top;\n let right = fill.right;\n let bottom = fill.bottom;\n for (const { rect, clip } of foreground) {\n if ([\n rect.x,\n rect.y,\n rect.width,\n rect.height,\n clip.x,\n clip.y,\n clip.width,\n clip.height\n ].some((value) => !Number.isFinite(value)) || rect.width < 0 || rect.height < 0 || clip.width < 0 || clip.height < 0)\n return {\n ok: false,\n code: "fill-foreground-extent-invalid",\n detail: "A Fill foreground has invalid output geometry."\n };\n const x = Math.max(rect.x, clip.x);\n const y = Math.max(rect.y, clip.y);\n const rightEdge = Math.min(rect.x + rect.width, clip.x + clip.width);\n const bottomEdge = Math.min(rect.y + rect.height, clip.y + clip.height);\n if (rightEdge <= x || bottomEdge <= y) continue;\n left = Math.max(left, Math.max(0, -Math.floor(x * fill.pixelRatio)));\n top = Math.max(top, Math.max(0, -Math.floor(y * fill.pixelRatio)));\n right = Math.max(\n right,\n Math.max(0, Math.ceil(rightEdge * fill.pixelRatio) - fill.sourceWidth)\n );\n bottom = Math.max(\n bottom,\n Math.max(0, Math.ceil(bottomEdge * fill.pixelRatio) - fill.sourceHeight)\n );\n }\n const width = fill.sourceWidth + left + right;\n const height = fill.sourceHeight + top + bottom;\n if (![left, top, right, bottom, width, height].every(Number.isSafeInteger) || width > maxDimension || height > maxDimension || width * height > maxPixels)\n return {\n ok: false,\n code: "fill-foreground-extent-budget-exceeded",\n detail: "The visible Fill foreground exceeds the supported output bounds."\n };\n return {\n ok: true,\n plan: {\n ...fill,\n left,\n top,\n right,\n bottom,\n width,\n height,\n expanded: fill.expanded || foreground.length > 0 && (left !== fill.left || top !== fill.top || right !== fill.right || bottom !== fill.bottom)\n }\n };\n }\n\n // app/components/design/bridge/native-worker-fill.ts\n var MAX_DIMENSION = 4096;\n var MAX_PIXELS = 8388608;\n var NativeWorkerFillError = class extends Error {\n constructor(code, message = code) {\n super(message);\n this.code = code;\n this.name = "NativeWorkerFillError";\n }\n };\n function failure2(code, message = code) {\n throw new NativeWorkerFillError(code, message);\n }\n function requireSize(texture, width, height, transparent, code) {\n if (texture !== transparent && (texture.width !== width || texture.height !== height))\n failure2(code);\n }\n function fillSurface(target, extent) {\n return {\n width: extent.width,\n height: extent.height,\n pixelRatio: target.pixelRatio,\n outputExtent: extent,\n targetLocalSize: {\n width: extent.sourceWidth / target.pixelRatio,\n height: extent.sourceHeight / target.pixelRatio\n },\n targetViewportSize: {\n width: target.rect.width,\n height: target.rect.height\n }\n };\n }\n async function renderNativeWorkerFill(input) {\n const {\n scene,\n target,\n instance,\n encoder,\n bank,\n gpu,\n format,\n transparent,\n foreground,\n previousFill,\n isTopFill,\n composeRecords,\n stageFillBackdrops\n } = input;\n if (instance.placement !== "fill") failure2("fill-placement-invalid");\n const extent = target.outputExtent;\n if (!extent || extent.width !== target.width || extent.height !== target.height)\n failure2("fill-presentation-geometry-unavailable");\n const phases = target.fillPhases;\n if (!phases)\n failure2(\n "fill-background-unavailable",\n "The authored Fill paint phases are required."\n );\n if (foreground.width !== target.width || foreground.height !== target.height)\n failure2("fill-effect-size-mismatch");\n const cssBlend = scene.colorSpace === "srgb" ? 1 : 0;\n const prefix = `fill:${instance.id}:`;\n const compose = (records, key, outputExtent = extent, blendMode = "linear", stagedNativeTextures2) => composeRecords(\n records,\n `${prefix}${key}`,\n fillSurface(target, outputExtent),\n blendMode,\n stagedNativeTextures2\n );\n const draw2 = async (key, wgsl, front, back, values, width = target.width, height = target.height, extras = []) => {\n const output = gpu.texture(bank, `${prefix}${key}`, width, height, format);\n if ([front, back, ...extras].includes(output)) failure2("fill-output-alias");\n const pipeline = await gpu.pipeline(wgsl, format, false, 2 + extras.length);\n const binding = gpu.bind(\n bank,\n `${prefix}${key}:bind`,\n pipeline,\n front,\n back,\n values,\n extras\n );\n const pass = encoder.beginRenderPass({\n colorAttachments: [\n {\n view: output.createView(),\n loadOp: "clear",\n storeOp: "store",\n clearValue: { r: 0, g: 0, b: 0, a: 0 }\n }\n ]\n });\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, binding);\n pass.draw(6);\n pass.end();\n return output;\n };\n const covered = async (key, wgsl, front, back, extras, initialBackground) => {\n for (const texture2 of [front, back, ...extras])\n requireSize(\n texture2,\n target.width,\n target.height,\n transparent,\n "fill-phase-size-mismatch"\n );\n return draw2(\n key,\n wgsl,\n front,\n back,\n new Float32Array([\n target.width,\n target.height,\n initialBackground ? 1 : 0,\n 0,\n cssBlend,\n 0,\n 0,\n 0\n ]),\n target.width,\n target.height,\n extras\n );\n };\n const composite = async (key, front, back, width = target.width, height = target.height) => {\n requireSize(\n front,\n width,\n height,\n transparent,\n "fill-foreground-size-mismatch"\n );\n requireSize(\n back,\n width,\n height,\n transparent,\n "fill-background-size-mismatch"\n );\n return draw2(\n key,\n fillCompositeWgsl,\n front,\n back,\n new Float32Array([width, height, cssBlend, 0]),\n width,\n height\n );\n };\n const compositePresentation = async (key, children2, fill, presentationExtent2, fillOnTop = false) => {\n requireSize(\n children2,\n presentationExtent2.width,\n presentationExtent2.height,\n transparent,\n "fill-presentation-size-mismatch"\n );\n if (fill.width !== target.width || fill.height !== target.height)\n failure2("fill-presentation-size-mismatch");\n return draw2(\n key,\n fillPresentationWgsl,\n children2,\n fill,\n new Float32Array([\n presentationExtent2.width,\n presentationExtent2.height,\n cssBlend,\n 0,\n presentationExtent2.left - extent.left,\n presentationExtent2.top - extent.top,\n fillOnTop ? 1 : 0,\n 0\n ]),\n presentationExtent2.width,\n presentationExtent2.height\n );\n };\n let underlayBase;\n let border;\n let outerCoverage;\n let innerCoverage;\n let glyphBase;\n if (previousFill) {\n ({ border, outerCoverage, innerCoverage } = previousFill);\n underlayBase = previousFill.underlay;\n glyphBase = previousFill.glyph;\n for (const value of [underlayBase, border, outerCoverage, innerCoverage])\n requireSize(\n value,\n target.width,\n target.height,\n transparent,\n "fill-dependency-unavailable"\n );\n } else {\n const phase = (records, name) => {\n if (records.length !== 1 || !records[0]?.assetId)\n failure2(\n "fill-box-phase-unavailable",\n `The authored Fill ${name} phase is unavailable.`\n );\n const texture2 = input.asset(records[0]);\n requireSize(\n texture2,\n target.width,\n target.height,\n transparent,\n "fill-phase-size-mismatch"\n );\n return texture2;\n };\n underlayBase = phase(phases.backgroundRecords, "background");\n border = phase(phases.borderRecords, "border");\n outerCoverage = phase(phases.outerCoverageRecords, "coverage");\n innerCoverage = phase(phases.innerCoverageRecords, "inner-coverage");\n glyphBase = phases.glyphRecords.length ? await compose(\n phases.glyphRecords,\n "glyph",\n extent,\n cssBlend && phases.glyphRecords.length > 1 ? "srgb-css-linear" : "linear"\n ) : void 0;\n }\n const textFill = instance.clip === "text";\n let underlay = await covered(\n "underlay",\n fillCoveredUnderlayWgsl,\n textFill ? transparent : foreground,\n underlayBase,\n [outerCoverage, innerCoverage],\n !previousFill\n );\n if (isTopFill && phases.insetShadowRecords.length) {\n const inset = await compose(phases.insetShadowRecords, "inset-shadow");\n underlay = await composite("underlay-inset", inset, underlay);\n }\n let glyph = glyphBase;\n if (textFill) {\n const opacity = instance.opacity;\n if (!Number.isFinite(opacity) || opacity < 0 || opacity > 1)\n failure2("fill-opacity-invalid");\n glyph = await draw2(\n "text",\n fillTextMixWgsl,\n foreground,\n glyphBase ?? transparent,\n new Float32Array([target.width, target.height, opacity, cssBlend])\n );\n }\n const carry = {\n underlay,\n glyph,\n border,\n outerCoverage,\n innerCoverage\n };\n if (!isTopFill)\n return { texture: underlay, carry, presentationExtent: extent };\n const box = await covered(\n "box",\n fillCoveredBoxWgsl,\n underlay,\n border,\n [outerCoverage],\n false\n );\n const fillPhase = await composite("phase", glyph ?? transparent, box);\n const outer = phases.outerShadowRecords;\n const outline = phases.outlineRecords;\n const children = phases.foregroundRecords;\n const visible = [...children, ...outer, ...outline];\n const planned = planNativeFillPresentationExtent({\n fill: extent,\n foreground: visible,\n maxDimension: MAX_DIMENSION,\n maxPixels: MAX_PIXELS\n });\n if (!planned.ok) failure2(planned.code, planned.detail);\n const presentationExtent = planned.plan;\n if (!visible.length) return { texture: fillPhase, carry, presentationExtent };\n const expanded = presentationExtent.width !== target.width || presentationExtent.height !== target.height || presentationExtent.left !== extent.left || presentationExtent.top !== extent.top;\n let base = fillPhase;\n if (outer.length) {\n const outerTexture = await compose(\n outer,\n "outer-shadow",\n presentationExtent\n );\n base = expanded ? await compositePresentation(\n "expanded-base",\n outerTexture,\n fillPhase,\n presentationExtent,\n true\n ) : await composite("expanded-base", fillPhase, outerTexture);\n }\n const nestedBackdrop = children.some(\n (record4) => scene.instances.some(\n (candidate) => candidate.id === record4.nativeInstanceId && candidate.placement === "backdrop"\n )\n );\n if (nestedBackdrop && !stageFillBackdrops)\n failure2(\n "fill-child-staging-unavailable",\n "Nested native Fill children require a staging transaction."\n );\n if (nestedBackdrop && expanded && !outer.length)\n base = await compositePresentation(\n "expanded-base",\n transparent,\n fillPhase,\n presentationExtent,\n true\n );\n const stagedNativeTextures = stageFillBackdrops ? await stageFillBackdrops(children, base, presentationExtent) : void 0;\n const overlay = [...children, ...outline];\n if (!overlay.length) return { texture: base, carry, presentationExtent };\n const overlayTexture = await compose(\n overlay,\n "child",\n presentationExtent,\n cssBlend && overlay.length > 1 ? "srgb-css-linear" : "linear",\n stagedNativeTextures\n );\n const texture = outer.length ? await composite(\n "final",\n overlayTexture,\n base,\n presentationExtent.width,\n presentationExtent.height\n ) : expanded ? await compositePresentation(\n "final",\n overlayTexture,\n fillPhase,\n presentationExtent\n ) : await composite("final", overlayTexture, fillPhase);\n return { texture, carry, presentationExtent };\n }\n\n // app/components/design/bridge/native-mesh-grid.ts\n var MAX_GRIDS_PER_DEVICE = 32;\n var deviceGrids = /* @__PURE__ */ new WeakMap();\n function nativeMeshGridBytes(mesh) {\n if (!isEffectMeshSpec(mesh)) throw new TypeError("Invalid native mesh grid");\n return mesh.columns * mesh.rows * 6 * Uint32Array.BYTES_PER_ELEMENT;\n }\n function acquireNativeMeshGrid(device, mesh) {\n const bytes = nativeMeshGridBytes(mesh);\n let grids = deviceGrids.get(device);\n if (!grids) {\n grids = /* @__PURE__ */ new Map();\n deviceGrids.set(device, grids);\n }\n const key = `${mesh.columns}x${mesh.rows}`;\n let grid = grids.get(key);\n if (!grid) {\n if (grids.size >= MAX_GRIDS_PER_DEVICE)\n throw new RangeError("Native mesh grid cache is full");\n const indices = new Uint32Array(bytes / Uint32Array.BYTES_PER_ELEMENT);\n const stride = mesh.columns + 1;\n let offset = 0;\n for (let row = 0; row < mesh.rows; row++) {\n for (let column = 0; column < mesh.columns; column++) {\n const first = row * stride + column;\n const next = first + stride;\n indices.set(\n [first, first + 1, next, first + 1, next + 1, next],\n offset\n );\n offset += 6;\n }\n }\n const buffer = device.createBuffer({\n size: bytes,\n usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST\n });\n try {\n device.queue.writeBuffer(buffer, 0, indices);\n } catch (error) {\n buffer.destroy();\n throw error;\n }\n grid = { buffer, indexCount: indices.length, bytes, references: 0 };\n grids.set(key, grid);\n }\n grid.references++;\n const acquired = grid;\n let released = false;\n return {\n buffer: acquired.buffer,\n indexCount: acquired.indexCount,\n bytes: acquired.bytes,\n release: () => {\n if (released) return;\n released = true;\n acquired.references--;\n if (acquired.references === 0) {\n acquired.buffer.destroy();\n grids.delete(key);\n if (grids.size === 0) deviceGrids.delete(device);\n }\n }\n };\n }\n\n // app/components/design/bridge/native-packed-uniform-arena.ts\n var NativePackedUniformArenaError = class extends Error {\n constructor(code) {\n super(code);\n this.code = code;\n this.name = "NativePackedUniformArenaError";\n }\n };\n var NativePackedUniformArena = class {\n constructor(options) {\n this.options = options;\n this.slots = /* @__PURE__ */ new Map();\n this.written = /* @__PURE__ */ new Set();\n this.allocatedEnd = 0;\n this.writtenEnd = 0;\n this.frame = null;\n this.phase = null;\n this.options = Object.freeze({ ...options });\n const { capacityBytes, alignment } = this.options;\n if (!Number.isSafeInteger(capacityBytes) || capacityBytes <= 0 || capacityBytes % 4 !== 0 || !Number.isSafeInteger(alignment) || alignment < 4 || alignment % 4 !== 0)\n throw new NativePackedUniformArenaError("uniform-arena-invalid-layout");\n this.staging = new Uint8Array(capacityBytes);\n }\n beginFrame() {\n if (this.frame !== null)\n throw new NativePackedUniformArenaError("uniform-arena-frame-active");\n this.frame = /* @__PURE__ */ Symbol("native-uniform-frame");\n this.phase = "recording";\n this.written.clear();\n this.writtenEnd = 0;\n return this.frame;\n }\n write(frame, drawKey, bytes) {\n this.assertFrame(frame);\n if (this.phase !== "recording")\n throw new NativePackedUniformArenaError("uniform-arena-frame-closed");\n if (!drawKey || bytes.byteLength === 0 || bytes.byteLength % 4 !== 0)\n throw new NativePackedUniformArenaError("uniform-arena-invalid-layout");\n if (this.written.has(drawKey))\n throw new NativePackedUniformArenaError("uniform-arena-duplicate-draw");\n let slot = this.slots.get(drawKey);\n if (slot && slot.byteLength !== bytes.byteLength)\n throw new NativePackedUniformArenaError(\n "uniform-arena-binding-size-changed"\n );\n if (!slot) {\n const offset2 = Math.ceil(this.allocatedEnd / this.options.alignment) * this.options.alignment;\n const size2 = Math.ceil(bytes.byteLength / 16) * 16;\n const end = offset2 + size2;\n if (!Number.isSafeInteger(end) || end > this.staging.byteLength)\n throw new NativePackedUniformArenaError(\n "uniform-arena-capacity-exceeded"\n );\n slot = {\n binding: Object.freeze({ buffer: this.options.buffer, offset: offset2, size: size2 }),\n byteLength: bytes.byteLength\n };\n this.slots.set(drawKey, slot);\n this.allocatedEnd = end;\n }\n const { offset, size } = slot.binding;\n this.staging.fill(0, offset, offset + size);\n this.staging.set(\n new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength),\n offset\n );\n this.written.add(drawKey);\n this.writtenEnd = Math.max(this.writtenEnd, offset + size);\n return slot.binding;\n }\n upload(frame) {\n this.assertFrame(frame);\n if (this.phase !== "recording")\n throw new NativePackedUniformArenaError("uniform-arena-frame-closed");\n if (!this.writtenEnd)\n throw new NativePackedUniformArenaError("uniform-arena-empty-frame");\n this.phase = "failed";\n this.options.upload(\n this.options.buffer,\n this.staging.subarray(0, this.writtenEnd)\n );\n this.assertFrame(frame);\n this.phase = "uploaded";\n }\n // All encoded consumers must be submitted before this arena can be written again.\n finishFrame(frame) {\n this.assertFrame(frame);\n if (this.phase !== "uploaded")\n throw new NativePackedUniformArenaError("uniform-arena-frame-closed");\n this.frame = null;\n this.phase = null;\n }\n // Abort is safe only when no command buffer consuming this frame was submitted.\n abortFrame(frame) {\n this.assertFrame(frame);\n this.frame = null;\n this.phase = null;\n }\n // Offsets restart at zero, so every binding handed out earlier is invalid.\n reset() {\n if (this.frame !== null)\n throw new NativePackedUniformArenaError("uniform-arena-frame-active");\n this.staging.fill(0, 0, this.allocatedEnd);\n this.slots.clear();\n this.allocatedEnd = 0;\n }\n assertFrame(frame) {\n if (this.frame !== frame)\n throw new NativePackedUniformArenaError("uniform-arena-frame-stale");\n }\n };\n\n // app/components/design/bridge/native-render-placement.ts\n function withoutComments(source) {\n let result = "";\n let depth = 0;\n for (let index = 0; index < source.length; index += 1) {\n const pair2 = source.slice(index, index + 2);\n if (pair2 === "/*") {\n depth += 1;\n index += 1;\n if (depth === 1) result += " ";\n } else if (depth > 0) {\n if (pair2 === "*/") {\n depth -= 1;\n index += 1;\n }\n } else if (pair2 === "//") {\n const end = source.indexOf("\\n", index + 2);\n if (end < 0) break;\n index = end;\n result += " ";\n } else {\n result += source[index];\n }\n }\n return result;\n }\n function nativeRenderPlacementConstants(wgsl, placement) {\n if (!wgsl.includes("NATIVE_GENERATED_FILL") || !/\\boverride\\s+NATIVE_GENERATED_FILL\\s*:\\s*bool\\b/.test(\n withoutComments(wgsl)\n ))\n return {};\n return { NATIVE_GENERATED_FILL: placement === "fill" ? 1 : 0 };\n }\n\n // app/components/design/bridge/native-worker-protocol.ts\n var NATIVE_WORKER_PROTOCOL_VERSION = 1;\n var NATIVE_WORKER_MAX_DIMENSION = 4096;\n var NATIVE_WORKER_MAX_PIXELS = 8388608;\n function nativeWorkerClockSampleValid(clock, nowEpochMs) {\n const sampledAt = clock.sampledAtEpochMs;\n return sampledAt === void 0 || typeof sampledAt === "number" && Number.isFinite(sampledAt) && sampledAt > 0 && Math.abs(nowEpochMs - sampledAt) <= 3e5;\n }\n\n // app/components/design/bridge/native-worker-gpu.ts\n var MAX_RESOURCE_BYTES = 402653184;\n var MAX_EFFECT_BYTES = 134217728;\n var NativeWorkerGpuError = class extends Error {\n constructor(code, message) {\n super(message);\n this.code = code;\n this.name = "NativeWorkerGpuError";\n }\n };\n var NativeWorkerGpuFlightCapacityError = class extends Error {\n constructor(message) {\n super(message);\n this.reason = "memory-budget";\n this.name = "NativeWorkerGpuFlightCapacityError";\n }\n };\n function createBank() {\n return {\n textures: /* @__PURE__ */ new Map(),\n depths: /* @__PURE__ */ new Map(),\n bindings: /* @__PURE__ */ new Map(),\n usedTextures: /* @__PURE__ */ new Set(),\n usedDepths: /* @__PURE__ */ new Set(),\n usedBindings: /* @__PURE__ */ new Set(),\n sceneTexture: null,\n generation: -1,\n compositionSignature: null,\n width: 0,\n height: 0,\n pixelRatio: 0\n };\n }\n function nativeWorkerTextureSizeValid(width, height) {\n return Number.isSafeInteger(width) && Number.isSafeInteger(height) && width > 0 && height > 0 && width <= NATIVE_WORKER_MAX_DIMENSION && height <= NATIVE_WORKER_MAX_DIMENSION && width * height <= NATIVE_WORKER_MAX_PIXELS;\n }\n function textureSize(width, height, format) {\n return width * height * (format === "rgba16float" ? 8 : 4);\n }\n var NativeWorkerGpu = class _NativeWorkerGpu {\n constructor(sceneId, canvas, device, context, format, ownsDevice) {\n this.sceneId = sceneId;\n this.canvas = canvas;\n this.device = device;\n this.ownsDevice = ownsDevice;\n this.bank = createBank();\n this.workingFormat = "rgba16float";\n this.presentedColorSpace = "srgb";\n this.finalTextures = [null, null, null];\n this.frontFinalIndex = 0;\n this.frontSlot = null;\n this.allocatedBytes = 0;\n this.allocatedUniformBytes = 0;\n this.reservedBytes = 0;\n this.transientBytes = 0;\n this.sharedBudget = null;\n this.flightSlots = [];\n this.leaseSlots = /* @__PURE__ */ new WeakMap();\n this.bankSlots = /* @__PURE__ */ new WeakMap();\n this.legacyLease = null;\n this.pipelineCache = /* @__PURE__ */ new Map();\n this.pipelineOrder = [];\n this.pipelineTextureCounts = /* @__PURE__ */ new WeakMap();\n this.effectLayouts = /* @__PURE__ */ new Map();\n this.preparedPlans = /* @__PURE__ */ new WeakMap();\n this.preparedProperties = /* @__PURE__ */ new WeakMap();\n this.meshGrids = /* @__PURE__ */ new Map();\n this.assets = /* @__PURE__ */ new Map();\n this.disposed = false;\n this.context = context;\n this.canvasFormat = format;\n this.sampler = device.createSampler({\n magFilter: "linear",\n minFilter: "linear"\n });\n this.nearestSampler = device.createSampler({\n magFilter: "nearest",\n minFilter: "nearest"\n });\n const uniformCapacity = 2097152;\n const uniformBuffer = device.createBuffer({\n size: uniformCapacity,\n usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST\n });\n const slot = {\n bank: this.bank,\n uniformBuffer,\n uniformArena: this.createUniformArena(uniformCapacity, uniformBuffer),\n uniformFrame: null,\n uniformUploaded: false,\n uniformCount: 0,\n uniformOccurrences: /* @__PURE__ */ new Map(),\n pendingFinalIndex: 1,\n reservedBytes: 0,\n uniformReservationBytes: 0,\n finalReservationBytes: 0,\n workReservationBytes: 0,\n activeLease: null,\n submitted: false,\n compositionSignature: null,\n width: 0,\n height: 0,\n pixelRatio: 0\n };\n this.flightSlots.push(slot);\n this.bankSlots.set(this.bank, slot);\n this.allocatedUniformBytes += uniformCapacity;\n this.white = this.createSolid([255, 255, 255, 255]);\n this.transparent = this.createSolid([0, 0, 0, 0]);\n }\n get uniformArena() {\n return this.flightSlots[0].uniformArena;\n }\n set uniformArena(value) {\n this.flightSlots[0].uniformArena = value;\n }\n get uniformBuffer() {\n return this.flightSlots[0].uniformBuffer;\n }\n get uniformFrame() {\n return this.flightSlots[0].uniformFrame;\n }\n set uniformFrame(value) {\n this.flightSlots[0].uniformFrame = value;\n }\n get uniformUploaded() {\n return this.flightSlots[0].uniformUploaded;\n }\n set uniformUploaded(value) {\n this.flightSlots[0].uniformUploaded = value;\n }\n get uniformCount() {\n return this.flightSlots[0].uniformCount;\n }\n set uniformCount(value) {\n this.flightSlots[0].uniformCount = value;\n }\n get uniformOccurrences() {\n return this.flightSlots[0].uniformOccurrences;\n }\n static async create(sceneId, canvas, sharedDevice) {\n if (!navigator.gpu)\n throw new NativeWorkerGpuError(\n "gpu-unavailable",\n "WebGPU is unavailable in the worker."\n );\n const adapter = sharedDevice ? null : await navigator.gpu.requestAdapter();\n if (!sharedDevice && !adapter)\n throw new NativeWorkerGpuError(\n "gpu-unavailable",\n "No WebGPU adapter is available."\n );\n const device = sharedDevice ?? await adapter.requestDevice();\n const context = canvas.getContext("webgpu");\n if (!context)\n throw new NativeWorkerGpuError(\n "canvas-unavailable",\n "The transferred canvas has no WebGPU context."\n );\n const format = navigator.gpu.getPreferredCanvasFormat();\n context.configure({\n device,\n format,\n alphaMode: "premultiplied",\n colorSpace: "srgb"\n });\n return new _NativeWorkerGpu(\n sceneId,\n canvas,\n device,\n context,\n format,\n !sharedDevice\n );\n }\n frontBank() {\n return this.frontSlot?.bank ?? this.bank;\n }\n frontTexture() {\n return this.finalTextures[this.frontFinalIndex]?.texture ?? null;\n }\n tryAcquireFlight(scene, compositionSignature) {\n this.assertLive();\n this.assertSceneSize(scene);\n const active = this.flightSlots.filter((slot2) => slot2.activeLease);\n if (active.length >= 2 || this.legacyLease)\n return { status: "capacity", reason: "flight-limit" };\n const slot = this.flightSlots.find((candidate) => !candidate.activeLease) ?? null;\n const reference = active[0];\n if (reference && (reference.compositionSignature !== compositionSignature || reference.width !== scene.width || reference.height !== scene.height || reference.pixelRatio !== scene.pixelRatio))\n return { status: "capacity", reason: "incompatible-scene" };\n const targetSlot = slot ?? this.createEmptyFlightSlot();\n const pendingFinalIndex = this.findPendingFinalIndex(targetSlot);\n if (pendingFinalIndex === null)\n return { status: "capacity", reason: "flight-limit" };\n targetSlot.pendingFinalIndex = pendingFinalIndex;\n const isSecond = active.length > 0;\n const uniformBytes = targetSlot.uniformBuffer ? 0 : 2097152;\n const finalBytes = textureSize(\n scene.width,\n scene.height,\n this.workingFormat\n );\n const pendingFinal = this.finalTextures[targetSlot.pendingFinalIndex];\n const finalReserve = Math.max(0, finalBytes - (pendingFinal?.bytes ?? 0));\n const reusableWork = targetSlot.compositionSignature === compositionSignature && targetSlot.width === scene.width && targetSlot.height === scene.height && targetSlot.pixelRatio === scene.pixelRatio;\n const workReserve = isSecond && !reusableWork && reference ? this.bankBytes(reference.bank) : 0;\n const reservation = uniformBytes + finalReserve + workReserve;\n try {\n this.prepareBank(targetSlot, scene, compositionSignature);\n this.reserveFlightBytes(\n targetSlot,\n reservation,\n "flight:reserve",\n uniformBytes,\n finalReserve,\n workReserve\n );\n if (!targetSlot.uniformBuffer) this.createFlightUniforms(targetSlot);\n } catch (error) {\n this.releaseFlightReservation(targetSlot);\n if (isSecond && error instanceof NativeWorkerGpuError && (error.code === "gpu-budget-exceeded" || error.code === "gpu-shared-budget-exceeded"))\n return { status: "capacity", reason: "memory-budget" };\n throw error;\n }\n const lease = Object.freeze({\n bank: targetSlot.bank\n });\n targetSlot.activeLease = lease;\n targetSlot.submitted = false;\n this.leaseSlots.set(lease, targetSlot);\n return { status: "acquired", lease };\n }\n beginFrame(lease) {\n const slot = lease ? this.slotForLease(lease) : this.legacySlotForRecording();\n if (slot.uniformFrame)\n throw new NativeWorkerGpuError(\n "frame-pipeline-busy",\n "A worker GPU frame is already recording."\n );\n slot.uniformFrame = slot.uniformArena.beginFrame();\n slot.uniformUploaded = false;\n slot.uniformCount = 0;\n slot.uniformOccurrences.clear();\n }\n uploadFrame(lease) {\n const slot = lease ? this.slotForLease(lease) : this.legacySlotForRecording();\n const frame = slot.uniformFrame;\n if (!frame)\n throw new NativeWorkerGpuError(\n "uniform-frame-missing",\n "The GPU frame has no packed uniforms."\n );\n if (!slot.uniformCount) return;\n slot.uniformArena.upload(frame);\n slot.uniformUploaded = true;\n }\n finishFrame(lease) {\n const slot = lease ? this.slotForLease(lease) : this.legacySlotForRecording();\n const frame = slot.uniformFrame;\n if (!frame) return;\n if (slot.uniformUploaded) slot.uniformArena.finishFrame(frame);\n else slot.uniformArena.abortFrame(frame);\n slot.uniformFrame = null;\n slot.uniformUploaded = false;\n slot.uniformCount = 0;\n }\n spareBank(scene, compositionSignature = null) {\n this.assertLive();\n if (this.legacyLease)\n throw new NativeWorkerGpuError(\n "frame-pipeline-busy",\n "The prior exclusive GPU operation has not released its lease."\n );\n if (this.flightSlots.some((slot2) => slot2.activeLease))\n throw new NativeWorkerGpuError(\n "frame-pipeline-busy",\n "An explicit worker flight is active during an exclusive GPU operation."\n );\n this.assertSceneSize(scene);\n const slot = this.frontSlot ?? this.flightSlots[0];\n const pendingFinalIndex = this.findPendingFinalIndex(slot);\n if (pendingFinalIndex === null)\n throw new NativeWorkerGpuError(\n "frame-pipeline-busy",\n "No non-visible final texture is available for an exclusive GPU operation."\n );\n slot.pendingFinalIndex = pendingFinalIndex;\n this.prepareBank(slot, scene, compositionSignature);\n this.legacyLease = Object.freeze({ bank: slot.bank });\n this.leaseSlots.set(this.legacyLease, slot);\n slot.activeLease = this.legacyLease;\n slot.submitted = false;\n return slot.bank;\n }\n prepareBank(slot, scene, compositionSignature) {\n const bank = slot.bank;\n const densityChanged = bank.pixelRatio !== scene.pixelRatio;\n const resized = bank.width !== scene.width || bank.height !== scene.height || densityChanged;\n const changed = bank.generation < 0 || bank.generation !== scene.generation || bank.compositionSignature !== compositionSignature;\n const reuseBindings = compositionSignature !== null && bank.compositionSignature === compositionSignature && !densityChanged;\n if (changed || resized) {\n if (slot.uniformFrame)\n throw new NativeWorkerGpuError(\n "frame-pipeline-busy",\n "The GPU scene changed during an active packed frame."\n );\n if (!reuseBindings) {\n bank.bindings.clear();\n slot.uniformArena?.reset();\n }\n }\n if (resized) {\n if (reuseBindings) bank.sceneTexture = null;\n else this.clearBank(bank);\n bank.width = scene.width;\n bank.height = scene.height;\n bank.pixelRatio = scene.pixelRatio;\n }\n bank.generation = scene.generation;\n bank.compositionSignature = compositionSignature;\n bank.usedTextures.clear();\n bank.usedDepths.clear();\n bank.usedBindings.clear();\n slot.compositionSignature = compositionSignature;\n slot.width = scene.width;\n slot.height = scene.height;\n slot.pixelRatio = scene.pixelRatio;\n return bank;\n }\n markFlightSubmitted(lease) {\n this.slotForLease(lease).submitted = true;\n }\n releaseFlight(lease) {\n const slot = this.slotForLease(lease);\n if (slot.uniformFrame)\n throw new NativeWorkerGpuError(\n "frame-pipeline-busy",\n "A worker GPU flight cannot be released while recording uniforms."\n );\n if (!slot.submitted) this.clearBank(slot.bank);\n this.releaseFlightReservation(slot);\n slot.activeLease = null;\n slot.submitted = false;\n if (this.legacyLease === lease) this.legacyLease = null;\n }\n endLegacyFlight() {\n const lease = this.legacyLease;\n if (!lease) return;\n this.slotForLease(lease).submitted = true;\n this.releaseFlight(lease);\n }\n legacySlotForRecording() {\n if (this.legacyLease) return this.slotForLease(this.legacyLease);\n if (this.flightSlots.some((slot2) => slot2.activeLease))\n throw new NativeWorkerGpuError(\n "frame-pipeline-busy",\n "An exclusive GPU frame cannot overlap a worker flight."\n );\n const slot = this.frontSlot ?? this.flightSlots[0];\n const lease = Object.freeze({ bank: slot.bank });\n this.legacyLease = lease;\n slot.activeLease = lease;\n slot.submitted = false;\n this.leaseSlots.set(lease, slot);\n return slot;\n }\n assertSceneSize(scene) {\n if (!nativeWorkerTextureSizeValid(scene.width, scene.height) || !Number.isFinite(scene.pixelRatio) || scene.pixelRatio <= 0)\n throw new NativeWorkerGpuError(\n "scene-size-invalid",\n "The native worker scene has invalid full-resolution geometry."\n );\n }\n createEmptyFlightSlot() {\n const slot = {\n bank: createBank(),\n uniformBuffer: null,\n uniformArena: null,\n uniformFrame: null,\n uniformUploaded: false,\n uniformCount: 0,\n uniformOccurrences: /* @__PURE__ */ new Map(),\n pendingFinalIndex: 2,\n reservedBytes: 0,\n uniformReservationBytes: 0,\n finalReservationBytes: 0,\n workReservationBytes: 0,\n activeLease: null,\n submitted: false,\n compositionSignature: null,\n width: 0,\n height: 0,\n pixelRatio: 0\n };\n this.flightSlots.push(slot);\n this.bankSlots.set(slot.bank, slot);\n return slot;\n }\n createFlightUniforms(slot) {\n const capacityBytes = 2097152;\n const buffer = this.device.createBuffer({\n size: capacityBytes,\n usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST\n });\n let arena;\n try {\n arena = this.createUniformArena(capacityBytes, buffer);\n } catch (error) {\n buffer.destroy();\n throw error;\n }\n slot.uniformBuffer = buffer;\n slot.uniformArena = arena;\n this.commitFlightReservation(slot, capacityBytes, "uniform");\n this.allocatedUniformBytes += capacityBytes;\n }\n reserveFlightBytes(slot, bytes, key, uniformBytes, finalBytes, workBytes) {\n if (bytes <= 0) return;\n if (this.resourceBytes() + bytes > MAX_RESOURCE_BYTES)\n throw this.budgetError(bytes, key);\n this.sharedBudget?.(bytes, key);\n slot.reservedBytes += bytes;\n slot.uniformReservationBytes += uniformBytes;\n slot.finalReservationBytes += finalBytes;\n slot.workReservationBytes += workBytes;\n this.reservedBytes += bytes;\n }\n findPendingFinalIndex(slot) {\n const occupied = /* @__PURE__ */ new Set();\n if (this.finalTextures[this.frontFinalIndex])\n occupied.add(this.frontFinalIndex);\n for (const candidate of this.flightSlots)\n if (candidate !== slot && candidate.activeLease)\n occupied.add(candidate.pendingFinalIndex);\n for (let index = 0; index < this.finalTextures.length; index++)\n if (!occupied.has(index)) return index;\n return null;\n }\n commitFlightReservation(slot, bytes, category) {\n const categoryKey = `${category}ReservationBytes`;\n const committed = Math.min(bytes, slot[categoryKey]);\n slot[categoryKey] -= committed;\n slot.reservedBytes -= committed;\n this.reservedBytes -= committed;\n }\n releaseFlightReservation(slot) {\n this.reservedBytes -= slot.reservedBytes;\n slot.reservedBytes = 0;\n slot.uniformReservationBytes = 0;\n slot.finalReservationBytes = 0;\n slot.workReservationBytes = 0;\n }\n bankBytes(bank) {\n return [...bank.textures.values(), ...bank.depths.values()].reduce(\n (total, resource) => total + resource.bytes,\n 0\n );\n }\n slotForLease(lease) {\n const slot = this.leaseSlots.get(lease);\n if (!slot || slot.activeLease !== lease)\n throw new NativeWorkerGpuError(\n "flight-lease-invalid",\n "The GPU flight lease is no longer active."\n );\n return slot;\n }\n slotForBank(bank) {\n const slot = this.bankSlots.get(bank);\n if (!slot)\n throw new NativeWorkerGpuError(\n "flight-bank-invalid",\n "The GPU work bank does not belong to this scene."\n );\n return slot;\n }\n capacityError(slot) {\n return this.flightSlots.indexOf(slot) > 0 && slot.activeLease !== null && !slot.submitted ? new NativeWorkerGpuFlightCapacityError(\n "The second native worker flight exceeded the reserved GPU budget."\n ) : null;\n }\n trimWork(target) {\n const isLease = !this.bankSlots.has(target);\n const slot = isLease ? this.slotForLease(target) : this.slotForBank(target);\n if (slot.uniformFrame)\n throw new NativeWorkerGpuError(\n "frame-pipeline-busy",\n "GPU work must finish before resource retirement."\n );\n const bank = slot.bank;\n this.trimBank(bank);\n }\n // The caller must await the GPU submission fence before retiring encoded textures.\n trimWorkExcept(target, retained) {\n const isLease = !this.bankSlots.has(target);\n const slot = isLease ? this.slotForLease(target) : this.slotForBank(target);\n if (slot.activeLease && slot.activeLease !== this.legacyLease)\n throw new NativeWorkerGpuError(\n "frame-pipeline-busy",\n "Work cannot be retired while an explicit worker flight owns the bank."\n );\n if (slot.uniformFrame)\n throw new NativeWorkerGpuError(\n "frame-pipeline-busy",\n "GPU work must finish before resource retirement."\n );\n const bank = slot.bank;\n bank.usedTextures.clear();\n for (const [key, resource] of bank.textures)\n if (resource.texture === retained) bank.usedTextures.add(key);\n bank.usedDepths.clear();\n bank.usedBindings.clear();\n this.trimBank(bank);\n if (!retained) bank.sceneTexture = null;\n }\n trimBank(bank) {\n for (const [key, resource] of bank.textures) {\n if (bank.usedTextures.has(key)) continue;\n resource.texture.destroy();\n this.allocatedBytes -= resource.bytes;\n bank.textures.delete(key);\n }\n for (const [key, resource] of bank.depths) {\n if (bank.usedDepths.has(key)) continue;\n resource.texture.destroy();\n this.allocatedBytes -= resource.bytes;\n bank.depths.delete(key);\n }\n for (const key of bank.bindings.keys())\n if (!bank.usedBindings.has(key)) bank.bindings.delete(key);\n }\n stageFinal(leaseOrScene, sceneOrTexture, textureOrEncoder, maybeEncoder) {\n this.assertLive();\n const explicitLease = this.leaseSlots.has(\n leaseOrScene\n );\n const lease = explicitLease ? leaseOrScene : this.legacyLease;\n if (!lease)\n throw new NativeWorkerGpuError(\n "flight-lease-invalid",\n "Final textures require an active GPU flight lease."\n );\n const slot = this.slotForLease(lease);\n const scene = explicitLease ? sceneOrTexture : leaseOrScene;\n const sceneTexture = explicitLease ? textureOrEncoder : sceneOrTexture;\n const encoder = explicitLease ? maybeEncoder : textureOrEncoder;\n const index = slot.pendingFinalIndex;\n let resource = this.finalTextures[index];\n if (resource && (resource.width !== scene.width || resource.height !== scene.height)) {\n resource.texture.destroy();\n this.allocatedBytes -= resource.bytes;\n resource = null;\n }\n if (!resource) {\n const bytes = textureSize(scene.width, scene.height, this.workingFormat);\n this.ensureBudget(bytes, `final:${index}`, slot, "final");\n resource = {\n texture: this.device.createTexture({\n size: [scene.width, scene.height],\n format: this.workingFormat,\n usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST\n }),\n width: scene.width,\n height: scene.height,\n format: this.workingFormat,\n bytes\n };\n this.finalTextures[index] = resource;\n this.commitFlightReservation(slot, bytes, "final");\n this.allocatedBytes += bytes;\n }\n encoder.copyTextureToTexture(\n { texture: sceneTexture },\n { texture: resource.texture },\n [scene.width, scene.height]\n );\n return resource.texture;\n }\n publish(leaseOrBank, validatedFinal, scene) {\n const explicitLease = this.leaseSlots.has(\n leaseOrBank\n );\n const slot = explicitLease ? this.slotForLease(leaseOrBank) : this.slotForBank(leaseOrBank);\n if (explicitLease)\n this.validatePublication(\n leaseOrBank,\n validatedFinal\n );\n else this.validatePublication(slot.bank, validatedFinal);\n const previousFront = this.frontFinalIndex;\n const nextFront = slot.pendingFinalIndex;\n slot.bank.sceneTexture = validatedFinal;\n this.frontFinalIndex = nextFront;\n slot.pendingFinalIndex = previousFront;\n this.frontSlot = slot;\n slot.submitted = true;\n void scene;\n }\n validatePublication(leaseOrBank, validatedFinal) {\n this.assertLive();\n const explicitLease = this.leaseSlots.has(\n leaseOrBank\n );\n const slot = explicitLease ? this.slotForLease(leaseOrBank) : this.slotForBank(leaseOrBank);\n if (this.finalTextures[slot.pendingFinalIndex]?.texture !== validatedFinal)\n throw new NativeWorkerGpuError(\n "frame-order-invalid",\n "The validated GPU final texture is no longer spare."\n );\n }\n preparePresentation(scene) {\n this.assertLive();\n if (this.canvas.width !== scene.width) this.canvas.width = scene.width;\n if (this.canvas.height !== scene.height) this.canvas.height = scene.height;\n if (this.presentedColorSpace !== scene.colorSpace) {\n this.context.configure({\n device: this.device,\n format: this.canvasFormat,\n alphaMode: "premultiplied",\n colorSpace: scene.colorSpace\n });\n this.presentedColorSpace = scene.colorSpace;\n }\n }\n reject(bank) {\n const slot = this.bankSlots.get(bank);\n if (!slot || slot === this.frontSlot) return;\n if (slot.activeLease && slot.submitted) return;\n if (slot.activeLease) this.releaseFlight(slot.activeLease);\n this.clearBank(bank);\n }\n texture(bank, key, width, height, format = this.workingFormat) {\n this.assertLive();\n if (!nativeWorkerTextureSizeValid(width, height))\n throw new NativeWorkerGpuError(\n "resource-size-unsupported",\n "The native GPU texture exceeds its dimension limit."\n );\n const existing = bank.textures.get(key);\n bank.usedTextures.add(key);\n if (existing?.width === width && existing.height === height && existing.format === format)\n return existing.texture;\n if (existing) {\n this.allocatedBytes -= existing.bytes;\n existing.texture.destroy();\n bank.textures.delete(key);\n }\n const bytes = textureSize(width, height, format);\n const slot = this.slotForBank(bank);\n this.ensureBudget(bytes, `work:${key}`, slot, "work");\n const texture = this.device.createTexture({\n size: [width, height],\n format,\n usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST\n });\n bank.textures.set(key, { texture, width, height, format, bytes });\n this.commitFlightReservation(slot, bytes, "work");\n this.allocatedBytes += bytes;\n return texture;\n }\n meshDepth(bank, width, height) {\n const key = `depth24plus:${width}x${height}`;\n bank.usedDepths.add(key);\n const existing = bank.depths.get(key);\n if (existing?.width === width && existing.height === height)\n return existing.texture;\n if (existing) {\n existing.texture.destroy();\n this.allocatedBytes -= existing.bytes;\n bank.depths.delete(key);\n }\n const bytes = width * height * 4;\n const slot = this.slotForBank(bank);\n this.ensureBudget(bytes, `depth:${key}`, slot, "work");\n const texture = this.device.createTexture({\n size: [width, height],\n format: "depth24plus",\n usage: GPUTextureUsage.RENDER_ATTACHMENT\n });\n bank.depths.set(key, {\n texture,\n width,\n height,\n format: "depth24plus",\n bytes\n });\n this.commitFlightReservation(slot, bytes, "work");\n this.allocatedBytes += bytes;\n return texture;\n }\n meshGrid(mesh, slot) {\n const key = `${mesh.columns}x${mesh.rows}`;\n const existing = this.meshGrids.get(key);\n if (existing) return existing;\n const bytes = nativeMeshGridBytes(mesh);\n this.ensureBudget(bytes, `mesh:${key}`, slot, "work");\n const lease = acquireNativeMeshGrid(this.device, mesh);\n this.meshGrids.set(key, lease);\n this.commitFlightReservation(slot, bytes, "work");\n this.allocatedBytes += bytes;\n return lease;\n }\n async pipeline(wgsl, format, blend, textureCount, placement, mesh = false) {\n this.assertLive();\n if (!Number.isSafeInteger(textureCount) || textureCount < 0 || textureCount > this.device.limits.maxSampledTexturesPerShaderStage)\n throw new NativeWorkerGpuError(\n "effect-input-limit",\n "The shader has more texture inputs than the GPU supports."\n );\n const constants = nativeRenderPlacementConstants(wgsl, placement);\n const key = JSON.stringify([format, blend, textureCount, constants, mesh]);\n const cached = this.pipelineCache.get(wgsl)?.get(key);\n if (cached) return cached;\n const module = this.device.createShaderModule({ code: wgsl });\n const info = await module.getCompilationInfo();\n const errors = info.messages.filter((message) => message.type === "error");\n if (errors.length)\n throw new NativeWorkerGpuError(\n "shader-pipeline-failed",\n errors.map(\n (message) => `${message.lineNum}:${message.linePos} ${message.message}`\n ).join("; ")\n );\n const layout = this.effectLayouts.get(textureCount) ?? this.createEffectLayout(textureCount);\n this.effectLayouts.set(textureCount, layout);\n const pipeline = await this.device.createRenderPipelineAsync({\n layout,\n vertex: { module, entryPoint: "vs" },\n fragment: {\n module,\n entryPoint: "fs",\n constants,\n targets: [\n {\n format,\n ...blend ? {\n blend: {\n color: {\n operation: "add",\n srcFactor: "one",\n dstFactor: "one-minus-src-alpha"\n },\n alpha: {\n operation: "add",\n srcFactor: "one",\n dstFactor: "one-minus-src-alpha"\n }\n }\n } : {}\n }\n ]\n },\n primitive: { topology: "triangle-list" },\n ...mesh ? {\n depthStencil: {\n format: "depth24plus",\n depthWriteEnabled: true,\n depthCompare: "less"\n }\n } : {}\n });\n if (this.disposed)\n throw new NativeWorkerGpuError(\n "device-disposed",\n "The GPU worker was disposed during pipeline creation."\n );\n let variants = this.pipelineCache.get(wgsl);\n if (!variants) {\n variants = /* @__PURE__ */ new Map();\n this.pipelineCache.set(wgsl, variants);\n }\n variants.set(key, pipeline);\n this.pipelineTextureCounts.set(pipeline, textureCount);\n this.pipelineOrder.push([wgsl, key]);\n while (this.pipelineOrder.length > 256) {\n const [oldWgsl, oldKey] = this.pipelineOrder.shift();\n const oldVariants = this.pipelineCache.get(oldWgsl);\n oldVariants?.delete(oldKey);\n if (!oldVariants?.size) this.pipelineCache.delete(oldWgsl);\n }\n return pipeline;\n }\n bind(bank, key, pipeline, source, mask, values, extraTextures = [], sampler = this.sampler) {\n this.assertLive();\n const slot = this.slotForBank(bank);\n const frame = slot.uniformFrame;\n if (!frame)\n throw new NativeWorkerGpuError(\n "uniform-frame-missing",\n "A draw was encoded without a worker uniform frame."\n );\n key = `${key}:uniform${values.byteLength}`;\n const occurrence = slot.uniformOccurrences.get(key) ?? 0;\n slot.uniformOccurrences.set(key, occurrence + 1);\n key = `${key}:${occurrence}`;\n bank.usedBindings.add(key);\n const packed = slot.uniformArena.write(frame, key, values);\n slot.uniformCount++;\n const { size, offset } = packed;\n let binding = bank.bindings.get(key);\n if (!binding || binding.buffer !== packed.buffer || binding.size !== size || binding.offset !== offset) {\n binding = {\n buffer: packed.buffer,\n offset,\n size,\n pipeline: null,\n sources: [],\n sampler: null,\n group: null\n };\n bank.bindings.set(key, binding);\n }\n const textureCount = this.pipelineTextureCounts.get(pipeline);\n const inputs = [\n ...source ? [source] : [],\n ...mask ? [mask] : [],\n ...extraTextures\n ];\n if (textureCount === void 0 || inputs.length !== textureCount)\n throw new NativeWorkerGpuError(\n "pipeline-binding-arity-mismatch",\n `A draw supplied ${inputs.length} textures to a pipeline requiring ${textureCount ?? "unknown"}.`\n );\n if (!binding.group || binding.pipeline !== pipeline || binding.sampler !== sampler || binding.sources.length !== inputs.length || inputs.some((texture, index) => texture !== binding.sources[index])) {\n binding.group = this.device.createBindGroup({\n layout: pipeline.getBindGroupLayout(0),\n entries: [\n { binding: 0, resource: { buffer: binding.buffer, offset, size } },\n ...textureCount ? [{ binding: 1, resource: sampler }] : [],\n ...inputs.map((texture, index) => ({\n binding: index + 2,\n resource: texture.createView()\n }))\n ]\n });\n binding.pipeline = pipeline;\n binding.sampler = sampler;\n binding.sources = inputs;\n }\n return binding.group;\n }\n async effect(bank, target, definition, instance, source, timeSeconds, encoder, inputs) {\n if (definition.feedback || definition.simulation || definition.statelessCompute || definition.resourceGraph)\n throw new NativeWorkerGpuError(\n "worker-capability-backend",\n `Effect ${instance.id} uses a GPU backend that is not available in the worker.`\n );\n if (definition.passes.some(\n (pass) => pass.kind !== "render" || pass.previousFrameReads?.length\n ))\n throw new NativeWorkerGpuError(\n "worker-capability-pass",\n `Effect ${instance.id} needs a temporal or non-render pass.`\n );\n const plan = this.preparedPlans.get(definition) ?? planEffectGraph(definition);\n if (plan.errors.length)\n throw new NativeWorkerGpuError(\n "effect-graph-invalid",\n plan.errors.join("; ")\n );\n const params = instance.animation ? resolveNativeParameterAnimation(\n definition,\n instance.params,\n instance.animation,\n timeSeconds\n ) : instance.params;\n const cached = this.preparedProperties.get(instance);\n const packedProperties = !instance.animation && cached?.definition === definition && cached.params === instance.params ? cached.packed : packNativeProperties(definition, params);\n this.preparedPlans.set(definition, plan);\n if (!instance.animation)\n this.preparedProperties.set(instance, {\n definition,\n params: instance.params,\n packed: packedProperties\n });\n const resources = new Map([\n ["source", source],\n ...inputs\n ]);\n let resourceBytes = 0;\n for (const pass of plan.passes) {\n if (pass.kind !== "render")\n throw new NativeWorkerGpuError(\n "worker-capability-pass",\n `Pass ${pass.id} cannot run in the worker render graph.`\n );\n const spec = definition.resources?.find(\n (resource) => resource.name === pass.output\n );\n if (spec?.kind && spec.kind !== "texture-2d")\n throw new NativeWorkerGpuError(\n "resource-kind-unsupported",\n `Pass ${pass.id} needs a non-texture output.`\n );\n const format = spec?.format ?? "rgba8unorm";\n if (format !== "rgba8unorm" && format !== "rgba16float")\n throw new NativeWorkerGpuError(\n "resource-format-unsupported",\n `Pass ${pass.id} requests unsupported output format.`\n );\n const width = spec?.size === "fixed" ? spec.width : target.width;\n const height = spec?.size === "fixed" ? spec.height : target.height;\n if (!width || !height || !nativeWorkerTextureSizeValid(width, height))\n throw new NativeWorkerGpuError(\n "resource-size-unsupported",\n `Pass ${pass.id} exceeds effect bounds.`\n );\n resourceBytes += textureSize(width, height, format) + (pass.mesh ? width * height * 4 : 0);\n if (resourceBytes > MAX_EFFECT_BYTES)\n throw new NativeWorkerGpuError(\n "resource-budget-exceeded",\n `Effect ${instance.id} exceeds its texture budget.`\n );\n const output2 = this.texture(\n bank,\n `effect:${instance.id}:${pass.output}`,\n width,\n height,\n format\n );\n const reads = pass.reads.map((name) => {\n const texture = resources.get(name);\n if (!texture)\n throw new NativeWorkerGpuError(\n "pass-input-missing",\n `Pass ${pass.id} has no texture for ${name}.`\n );\n return texture;\n });\n const pipeline = await this.pipeline(\n pass.wgsl,\n format,\n false,\n reads.length,\n instance.placement,\n pass.mesh !== void 0\n );\n const values = new Float32Array(\n 8 + nativeEffectUniformFloats(definition)\n );\n values.set([width, height, 1 / width, 1 / height], 0);\n values.set(\n packNativeUniformClock({\n time: timeSeconds,\n seed: instance.seed,\n pixelRatio: target.pixelRatio\n }),\n 4\n );\n values.set(packedProperties, 8);\n const input = reads[0] ?? null;\n const bind = this.bind(\n bank,\n `effect:${instance.id}:${pass.id}`,\n pipeline,\n input,\n reads[1] ?? null,\n values,\n reads.slice(2)\n );\n const depth = pass.mesh ? this.meshDepth(bank, width, height) : null;\n const grid = pass.mesh ? this.meshGrid(pass.mesh, this.slotForBank(bank)) : null;\n const render = encoder.beginRenderPass({\n colorAttachments: [\n {\n view: output2.createView(),\n loadOp: "clear",\n storeOp: "store",\n clearValue: { r: 0, g: 0, b: 0, a: 0 }\n }\n ],\n ...depth ? {\n depthStencilAttachment: {\n view: depth.createView(),\n depthLoadOp: "clear",\n depthStoreOp: "discard",\n depthClearValue: 1\n }\n } : {}\n });\n render.setPipeline(pipeline);\n render.setBindGroup(0, bind);\n if (grid) {\n render.setIndexBuffer(grid.buffer, "uint32");\n render.drawIndexed(grid.indexCount);\n } else render.draw(3);\n render.end();\n resources.set(pass.output, output2);\n }\n const outputName = definition.output ?? plan.passes[plan.passes.length - 1]?.output;\n if (!outputName) return source;\n const output = resources.get(outputName);\n if (!output)\n throw new NativeWorkerGpuError(\n "effect-output-missing",\n `Effect ${instance.id} has no output texture.`\n );\n return output;\n }\n asset(assetId, revision, generation) {\n void generation;\n const entry = this.assets.get(_NativeWorkerGpu.assetKey(assetId, revision));\n if (!entry)\n throw new NativeWorkerGpuError(\n "asset-missing",\n `Asset ${assetId} revision ${revision} is unavailable.`\n );\n return entry.texture;\n }\n hasAsset(assetId, revision, generation) {\n void generation;\n return this.assets.has(_NativeWorkerGpu.assetKey(assetId, revision));\n }\n static assetKey(assetId, revision) {\n return JSON.stringify([assetId, revision]);\n }\n retireIdleWorkForAssetUpload(asset) {\n if (this.flightSlots.some(\n (slot) => slot.activeLease && slot.activeLease !== this.legacyLease\n ))\n throw new NativeWorkerGpuError(\n "frame-pipeline-busy",\n "Asset uploads cannot retire work while an explicit worker flight is active."\n );\n if (this.assets.has(_NativeWorkerGpu.assetKey(asset.assetId, asset.revision)))\n return;\n const width = asset.kind === "bitmap" ? asset.bitmap.width : asset.width;\n const height = asset.kind === "bitmap" ? asset.bitmap.height : asset.height;\n if (!nativeWorkerTextureSizeValid(width, height)) return;\n const format = asset.kind === "bitmap" ? asset.sampleEncoding === "linear-data" ? "rgba8unorm" : "rgba8unorm-srgb" : "rgba16float";\n if (this.resourceBytes() + textureSize(width, height, format) > MAX_RESOURCE_BYTES)\n this.trimWorkExcept(this.bank, null);\n }\n uploadAsset(asset) {\n try {\n this.assertLive();\n if (asset.sceneId !== this.sceneId)\n throw new NativeWorkerGpuError(\n "scene-id-mismatch",\n "The asset belongs to another worker scene."\n );\n const key = _NativeWorkerGpu.assetKey(asset.assetId, asset.revision);\n if (this.assets.has(key)) return;\n const width = asset.kind === "bitmap" ? asset.bitmap.width : asset.width;\n const height = asset.kind === "bitmap" ? asset.bitmap.height : asset.height;\n const format = asset.kind === "bitmap" ? asset.sampleEncoding === "linear-data" ? "rgba8unorm" : "rgba8unorm-srgb" : "rgba16float";\n if (!nativeWorkerTextureSizeValid(width, height))\n throw new NativeWorkerGpuError(\n "asset-size-invalid",\n `Asset ${asset.assetId} exceeds texture limits.`\n );\n const bytes = textureSize(width, height, format);\n this.ensureBudget(bytes, `asset:${asset.assetId}`);\n const texture = this.device.createTexture({\n size: [width, height],\n format,\n usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC | (asset.kind === "bitmap" ? GPUTextureUsage.RENDER_ATTACHMENT : 0)\n });\n try {\n if (asset.kind === "bitmap") {\n this.device.queue.copyExternalImageToTexture(\n { source: asset.bitmap },\n { texture, colorSpace: "srgb", premultipliedAlpha: false },\n [width, height]\n );\n } else {\n const expected = width * height * 8;\n if (asset.data.byteLength !== expected)\n throw new NativeWorkerGpuError(\n "asset-data-invalid",\n `Asset ${asset.assetId} has invalid RGBA16F bytes.`\n );\n this.device.queue.writeTexture(\n { texture },\n asset.data,\n { bytesPerRow: width * 8, rowsPerImage: height },\n [width, height]\n );\n }\n } catch (error) {\n texture.destroy();\n throw error;\n }\n this.assets.set(key, { texture, width, height, format, bytes });\n this.allocatedBytes += bytes;\n } finally {\n if (asset.kind === "bitmap") asset.bitmap.close();\n }\n }\n retireAssets(keptKeys) {\n for (const [key, resource] of this.assets) {\n if (keptKeys.has(key)) continue;\n resource.texture.destroy();\n this.allocatedBytes -= resource.bytes;\n this.assets.delete(key);\n }\n }\n dropAsset(assetId, revision) {\n const key = _NativeWorkerGpu.assetKey(assetId, revision);\n const resource = this.assets.get(key);\n if (!resource) return;\n resource.texture.destroy();\n this.allocatedBytes -= resource.bytes;\n this.assets.delete(key);\n }\n transparentTexture() {\n return this.transparent;\n }\n whiteTexture() {\n return this.white;\n }\n resourceBytes() {\n return this.allocatedBytes + this.allocatedUniformBytes + this.reservedBytes + this.transientBytes;\n }\n setSharedBudget(check) {\n this.sharedBudget = check;\n }\n reserveTransient(bytes, key) {\n this.ensureBudget(bytes, key);\n this.transientBytes += bytes;\n }\n releaseTransient(bytes) {\n this.transientBytes -= bytes;\n }\n dispose() {\n if (this.disposed) return;\n this.disposed = true;\n for (const slot of this.flightSlots) {\n this.clearBank(slot.bank);\n this.releaseFlightReservation(slot);\n slot.activeLease = null;\n if (slot.uniformBuffer) {\n slot.uniformBuffer.destroy();\n this.allocatedUniformBytes -= 2097152;\n slot.uniformBuffer = null;\n slot.uniformArena = null;\n }\n }\n this.legacyLease = null;\n for (const grid of this.meshGrids.values()) {\n grid.release();\n this.allocatedBytes -= grid.bytes;\n }\n this.meshGrids.clear();\n this.retireAssets(/* @__PURE__ */ new Set());\n for (const resource of this.finalTextures)\n if (resource) {\n resource.texture.destroy();\n this.allocatedBytes -= resource.bytes;\n }\n this.finalTextures = [null, null, null];\n this.white.destroy();\n this.transparent.destroy();\n this.allocatedBytes -= 8;\n this.context.unconfigure();\n if (this.ownsDevice) this.device.destroy();\n }\n createSolid(color2) {\n const texture = this.device.createTexture({\n size: [1, 1],\n format: "rgba8unorm",\n usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST\n });\n this.device.queue.writeTexture(\n { texture },\n new Uint8Array(color2),\n { bytesPerRow: 4 },\n [1, 1]\n );\n this.allocatedBytes += 4;\n return texture;\n }\n createUniformArena(capacityBytes, buffer) {\n return new NativePackedUniformArena({\n buffer,\n capacityBytes,\n alignment: this.device.limits.minUniformBufferOffsetAlignment,\n upload: (buffer2, bytes) => this.device.queue.writeBuffer(buffer2, 0, bytes)\n });\n }\n createEffectLayout(count) {\n return this.device.createPipelineLayout({\n bindGroupLayouts: [\n this.device.createBindGroupLayout({\n entries: [\n {\n binding: 0,\n visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,\n buffer: { type: "uniform" }\n },\n ...count ? [\n {\n binding: 1,\n visibility: GPUShaderStage.FRAGMENT,\n sampler: { type: "filtering" }\n }\n ] : [],\n ...Array.from({ length: count }, (_, index) => ({\n binding: index + 2,\n visibility: GPUShaderStage.FRAGMENT,\n texture: { sampleType: "float" }\n }))\n ]\n })\n ]\n });\n }\n ensureBudget(bytes, key, slot, category) {\n const reservedBytes = category === "uniform" ? slot?.uniformReservationBytes : category === "final" ? slot?.finalReservationBytes : category === "work" ? slot?.workReservationBytes : 0;\n const credit = Math.min(bytes, reservedBytes ?? 0);\n const additional = bytes - credit;\n const allocated = this.resourceBytes();\n if (allocated + additional > MAX_RESOURCE_BYTES)\n throw this.capacityError(slot ?? this.flightSlots[0]) ?? this.budgetError(bytes, key);\n try {\n if (additional) this.sharedBudget?.(additional, key);\n } catch (error) {\n if (slot && error instanceof NativeWorkerGpuError && (error.code === "gpu-budget-exceeded" || error.code === "gpu-shared-budget-exceeded")) {\n const capacityError = this.capacityError(slot);\n if (capacityError) throw capacityError;\n }\n throw error;\n }\n }\n budgetError(bytes, key) {\n const work = this.flightSlots.reduce(\n (total, slot) => total + [...slot.bank.textures.values(), ...slot.bank.depths.values()].reduce(\n (subtotal, resource) => subtotal + resource.bytes,\n 0\n ),\n 0\n );\n const assets = [...this.assets.values()].reduce(\n (total, resource) => total + resource.bytes,\n 0\n );\n const finals = this.finalTextures.reduce(\n (total, resource) => total + (resource?.bytes ?? 0),\n 0\n );\n const allocated = this.resourceBytes();\n return new NativeWorkerGpuError(\n "gpu-budget-exceeded",\n `The native worker GPU resources exceed their bounded budget: ${key} requests ${bytes} bytes with ${allocated} bytes allocated; work ${work} bytes, assets ${assets} bytes/${this.assets.size} textures, finals ${finals} bytes/${this.finalTextures.filter(Boolean).length} textures.`\n );\n }\n clearBank(bank) {\n for (const resource of bank.textures.values()) {\n resource.texture.destroy();\n this.allocatedBytes -= resource.bytes;\n }\n bank.textures.clear();\n for (const resource of bank.depths.values()) {\n resource.texture.destroy();\n this.allocatedBytes -= resource.bytes;\n }\n bank.depths.clear();\n bank.bindings.clear();\n bank.usedTextures.clear();\n bank.usedDepths.clear();\n bank.usedBindings.clear();\n bank.sceneTexture = null;\n bank.generation = -1;\n bank.compositionSignature = null;\n }\n assertLive() {\n if (this.disposed)\n throw new NativeWorkerGpuError(\n "device-disposed",\n "The native worker GPU is disposed."\n );\n }\n };\n\n // app/components/design/bridge/native-worker-entry.ts\n var NativeWorkerSceneError = class extends Error {\n constructor(code, message) {\n super(message);\n this.code = code;\n this.name = "NativeWorkerSceneError";\n }\n };\n function checkedScene(scene, gpu) {\n if (scene.sceneId !== gpu.sceneId)\n throw new NativeWorkerSceneError(\n "scene-id-mismatch",\n "The scene belongs to another GPU surface."\n );\n if (!Number.isSafeInteger(scene.generation) || scene.generation < 1 || !Number.isSafeInteger(scene.sourceEpoch) || !Number.isSafeInteger(scene.authoredEpoch) || typeof scene.clock.playing !== "boolean" || !nativeWorkerClockSampleValid(\n scene.clock,\n performance.timeOrigin + performance.now()\n ) || ![\n scene.viewport.x,\n scene.viewport.y,\n scene.viewport.width,\n scene.viewport.height,\n scene.pixelRatio,\n scene.clock.timeSeconds,\n scene.clock.speed\n ].every(Number.isFinite) || scene.viewport.width <= 0 || scene.viewport.height <= 0 || scene.pixelRatio <= 0 || !nativeWorkerTextureSizeValid(scene.width, scene.height) || scene.width !== Math.ceil(scene.viewport.width * scene.pixelRatio) || scene.height !== Math.ceil(scene.viewport.height * scene.pixelRatio) || scene.colorSpace !== "srgb" && scene.colorSpace !== "display-p3" || scene.frameRateTarget !== void 0 && scene.frameRateTarget !== 60 && scene.frameRateTarget !== 120 || scene.compact !== void 0 && typeof scene.compact !== "boolean")\n throw new NativeWorkerSceneError(\n "scene-geometry-invalid",\n "The scene snapshot has invalid full-resolution geometry."\n );\n const requirements = /* @__PURE__ */ new Set();\n for (const asset of scene.requiredAssets) {\n if (requirements.has(asset.assetId) || !gpu.hasAsset(asset.assetId, asset.revision, scene.generation))\n throw new NativeWorkerSceneError(\n "scene-asset-missing",\n `Scene asset ${asset.assetId} revision ${asset.revision} is unavailable or duplicated.`\n );\n requirements.add(asset.assetId);\n }\n const definitions = new Set(\n scene.definitions.map(\n (definition) => `${definition.id}:${definition.version}`\n )\n );\n const instances = /* @__PURE__ */ new Set();\n for (const instance of scene.instances) {\n if (!definitions.has(\n `${instance.definitionId}:${instance.definitionVersion}`\n ) || instances.has(instance.id))\n throw new NativeWorkerSceneError(\n "scene-effect-invalid",\n `Effect ${instance.id} has no unique matching definition.`\n );\n instances.add(instance.id);\n }\n if (scene.targets.length !== scene.instances.length || scene.targets.some((target) => !instances.has(target.instanceId)))\n throw new NativeWorkerSceneError(\n "scene-target-invalid",\n "The scene target set does not match its effects."\n );\n const instancesById = new Map(\n scene.instances.map((instance) => [instance.id, instance])\n );\n const definitionsByKey = new Map(\n scene.definitions.map((definition) => [\n `${definition.id}:${definition.version}`,\n definition\n ])\n );\n for (const target of scene.targets) {\n const instance = instancesById.get(target.instanceId);\n const definition = instance ? definitionsByKey.get(\n `${instance.definitionId}:${instance.definitionVersion}`\n ) : void 0;\n if (!instance || !definition)\n throw new NativeWorkerSceneError(\n "scene-effect-invalid",\n `Effect ${target.instanceId} has no matching definition.`\n );\n const plan = planNativeInputResources(definition, instance);\n if (!plan.ok) throw new NativeWorkerSceneError(plan.code, plan.detail);\n const expectedInputAssets = [...plan.inputs].flatMap(\n ([resource, input]) => input.kind === "asset" ? [[resource, nativeWorkerInputAssetId(input)]] : []\n );\n const supplied = Object.entries(target.inputAssetIds ?? {});\n if (expectedInputAssets.length !== supplied.length || expectedInputAssets.some(\n ([resource, assetId]) => assetId === null || target.inputAssetIds?.[resource] !== assetId || !requirements.has(assetId)\n ))\n throw new NativeWorkerSceneError(\n "scene-input-asset-invalid",\n `Effect ${target.instanceId} has invalid input asset bindings.`\n );\n if (!target.groupLocalOwnerId) continue;\n const child = instancesById.get(target.instanceId);\n const owner = instancesById.get(target.groupLocalOwnerId);\n if (child?.placement !== "backdrop" || !owner || owner.placement !== "layer" && owner.placement !== "fill" || child.id === owner.id)\n throw new NativeWorkerSceneError(\n "scene-group-local-owner-invalid",\n `Backdrop ${target.instanceId} has an invalid native owner.`\n );\n }\n }\n function compatibleCameraContent(base, candidate) {\n return candidate.sceneId === base.sceneId && candidate.sourceEpoch === base.sourceEpoch && candidate.authoredEpoch === base.authoredEpoch && candidate.pixelRatio === base.pixelRatio && candidate.colorSpace === base.colorSpace && candidate.frameRateTarget === base.frameRateTarget && candidate.compact === base.compact && candidate.definitions === base.definitions && candidate.instances === base.instances && candidate.targets === base.targets && candidate.records === base.records && candidate.backdropRecords === base.backdropRecords && candidate.requiredAssets === base.requiredAssets;\n }\n function checkedCamera(camera, state) {\n const current = state.current;\n const staged = state.staged;\n if (!current || !state.currentSignature || camera.baseGeneration !== current.generation || camera.sceneId !== current.sceneId || camera.sourceEpoch !== current.sourceEpoch || camera.authoredEpoch !== current.authoredEpoch || camera.pixelRatio !== current.pixelRatio || staged !== null && !compatibleCameraContent(current, staged))\n throw new NativeWorkerSceneError(\n "worker-camera-base-stale",\n "The camera update no longer matches the committed native scene."\n );\n if (!Number.isSafeInteger(camera.generation) || camera.generation <= Math.max(current.generation, staged?.generation ?? 0) || !nativeWorkerTextureSizeValid(camera.width, camera.height) || !camera.viewport || !camera.clock || typeof camera.clock.playing !== "boolean" || !nativeWorkerClockSampleValid(\n camera.clock,\n performance.timeOrigin + performance.now()\n ) || ![\n camera.viewport.x,\n camera.viewport.y,\n camera.viewport.width,\n camera.viewport.height,\n camera.clock.timeSeconds,\n camera.clock.speed\n ].every(Number.isFinite) || camera.viewport.width <= 0 || camera.viewport.height <= 0 || camera.width !== Math.ceil(camera.viewport.width * camera.pixelRatio) || camera.height !== Math.ceil(camera.viewport.height * camera.pixelRatio))\n throw new NativeWorkerSceneError(\n "scene-geometry-invalid",\n "The camera update has invalid full-resolution geometry."\n );\n return {\n ...current,\n generation: camera.generation,\n viewport: camera.viewport,\n width: camera.width,\n height: camera.height,\n clock: camera.clock\n };\n }\n function clockTime(scene, anchorMs, nowMs) {\n const elapsedMs = scene.clock.sampledAtEpochMs === void 0 ? Math.max(0, nowMs - anchorMs) : Math.max(\n 0,\n performance.timeOrigin + nowMs - scene.clock.sampledAtEpochMs\n );\n return scene.clock.timeSeconds + (scene.clock.playing ? elapsedMs * scene.clock.speed / 1e3 : 0);\n }\n function localTime(instance, globalTime) {\n return instance.timing.time + (instance.timing.paused ? 0 : globalTime * instance.timing.speed);\n }\n function sceneCompositionSignature(scene) {\n const records = (values) => values.map((record4) => [\n record4.key,\n record4.nodeId,\n record4.kind,\n record4.sourceRole,\n record4.assetId,\n record4.nativeInstanceId,\n record4.imageSourceUrl,\n record4.imageRendering,\n record4.coordinateSpace,\n record4.opacity,\n record4.isolationPath,\n record4.groupClips.map((group) => group.id)\n ]);\n return JSON.stringify([\n scene.sourceEpoch,\n scene.authoredEpoch,\n scene.pixelRatio,\n scene.colorSpace,\n scene.definitions,\n scene.instances,\n scene.requiredAssets,\n records(scene.records),\n scene.targets.map((target) => [\n target.instanceId,\n target.definitionHash,\n target.sourceAssetId,\n target.maskAssetId,\n target.textMaskAssetId,\n target.receiverGeometryAssetId,\n target.receiverInteriorAssetId,\n target.groupLocalOwnerId,\n records(target.sourceRecords),\n records(target.fillLocalSourceRecords ?? []),\n target.fillPhases && Object.values(target.fillPhases).map((phase) => records(phase))\n ])\n ]);\n }\n function draw(encoder, target, pipeline, bind) {\n const pass = encoder.beginRenderPass({\n colorAttachments: [\n {\n view: target.createView(),\n loadOp: "clear",\n storeOp: "store",\n clearValue: { r: 0, g: 0, b: 0, a: 0 }\n }\n ]\n });\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bind);\n pass.draw(6);\n pass.end();\n }\n var NativeWorkerRenderer = class {\n constructor(scene, timeSeconds, gpu, bank, encoder) {\n this.scene = scene;\n this.timeSeconds = timeSeconds;\n this.gpu = gpu;\n this.bank = bank;\n this.encoder = encoder;\n this.instances = /* @__PURE__ */ new Map();\n this.targets = /* @__PURE__ */ new Map();\n this.definitions = /* @__PURE__ */ new Map();\n this.revisions = /* @__PURE__ */ new Map();\n this.outputs = /* @__PURE__ */ new Map();\n this.fillCarry = /* @__PURE__ */ new Map();\n this.active = /* @__PURE__ */ new Set();\n this.frozenBackdropOutputs = false;\n for (const instance of scene.instances)\n this.instances.set(instance.id, instance);\n for (const target of scene.targets)\n this.targets.set(target.instanceId, target);\n for (const definition of scene.definitions)\n this.definitions.set(\n `${definition.id}:${definition.version}`,\n definition\n );\n for (const asset of scene.requiredAssets)\n this.revisions.set(asset.assetId, asset.revision);\n }\n asset(assetId) {\n if (!assetId)\n throw new NativeWorkerSceneError(\n "native-dependency-missing",\n "A required source asset has no ID."\n );\n const revision = this.revisions.get(assetId);\n if (revision === void 0)\n throw new NativeWorkerSceneError(\n "native-dependency-missing",\n `Asset ${assetId} is absent from the scene snapshot.`\n );\n return this.gpu.asset(assetId, revision, this.scene.generation);\n }\n async compose(records, key, surface, blendMode, overrides, composingOwnerId) {\n const bank = this.bank;\n return composeNativeWorkerScene({\n scene: this.scene,\n records,\n surface,\n outputName: key,\n blendMode: blendMode ?? (this.scene.colorSpace === "srgb" && records.length > 1 ? "srgb-css-linear" : "linear"),\n format: this.gpu.workingFormat,\n encoder: this.encoder,\n bank: {\n texture: (name, width, height) => this.gpu.texture(bank, `composition:${name}`, width, height)\n },\n gpu: {\n pipeline: (wgsl, format, blend, textureCount) => this.gpu.pipeline(wgsl, format, blend, textureCount),\n bind: (name, pipeline, source, mask, data, sampler, extras) => this.gpu.bind(\n bank,\n `composition:${name}`,\n pipeline,\n source,\n mask,\n data,\n extras,\n sampler\n ),\n sampler: (filter) => filter === "nearest" ? this.gpu.nearestSampler : this.gpu.sampler\n },\n resolveRecord: (record4, context) => this.resolve(record4, context, overrides, composingOwnerId)\n });\n }\n async resolve(record4, context, overrides, composingOwnerId) {\n if (!record4.nativeInstanceId)\n return { texture: this.asset(record4.assetId), premultiplied: false };\n const instance = this.instances.get(record4.nativeInstanceId);\n const target = this.targets.get(record4.nativeInstanceId);\n if (!instance || !target)\n throw new NativeWorkerSceneError(\n "native-dependency-missing",\n `Native record ${record4.key} has no effect target.`\n );\n const override = overrides?.get(instance.id);\n if (override)\n return {\n texture: override,\n premultiplied: true,\n backdropReplacement: instance.placement === "backdrop",\n receiverCoverage: instance.placement === "backdrop" ? this.asset(target.maskAssetId) : void 0\n };\n if (record4.sourceRole === "ancestor-fill-prefix")\n throw new NativeWorkerSceneError(\n "native-dependency-missing",\n "The staged ancestor Fill prefix is unavailable."\n );\n if (instance.placement === "backdrop" && this.frozenBackdropOutputs) {\n const frozen = this.outputs.get(instance.id);\n if (!frozen)\n throw new NativeWorkerSceneError(\n "composition-backdrop-snapshot-missing",\n `Backdrop ${instance.id} was not rendered from the unfiltered scene.`\n );\n return {\n texture: frozen,\n premultiplied: true,\n backdropReplacement: true,\n receiverCoverage: this.asset(target.maskAssetId)\n };\n }\n const backdropRoute = instance.placement === "backdrop" ? planNativeWorkerBackdropRoute(\n target.groupLocalOwnerId,\n composingOwnerId\n ) : null;\n if (backdropRoute === "owner-output") {\n const ownerId = target.groupLocalOwnerId;\n const owner = this.instances.get(ownerId);\n const ownerTarget = this.targets.get(ownerId);\n if (!owner || !ownerTarget)\n throw new NativeWorkerSceneError(\n "native-dependency-missing",\n `Nested Glass ${instance.id} has no native owner.`\n );\n if (!this.outputs.has(instance.id))\n await this.renderTarget(ownerTarget, owner, context);\n const ownedOutput = this.outputs.get(instance.id);\n if (!ownedOutput)\n throw new NativeWorkerSceneError(\n "native-dependency-missing",\n `Nested Glass ${instance.id} has no staged owner output.`\n );\n return {\n texture: ownedOutput,\n premultiplied: true,\n backdropReplacement: true,\n receiverCoverage: this.asset(target.maskAssetId)\n };\n }\n if (instance.placement === "backdrop" && !context.currentScene)\n return {\n backdropReplacement: true,\n receiverCoverage: this.asset(target.maskAssetId),\n ...backdropRoute === "group-local" ? {\n nestedBackdrop: {\n output: { width: target.width, height: target.height },\n extent: target.outputExtent\n }\n } : {}\n };\n return {\n texture: await this.renderTarget(target, instance, context),\n premultiplied: true,\n backdropReplacement: instance.placement === "backdrop",\n receiverCoverage: instance.placement === "backdrop" ? this.asset(target.maskAssetId) : void 0\n };\n }\n async backdropSource(target, context) {\n const incoming = context.incoming;\n const current = context.currentScene;\n if (!incoming || !current)\n throw new NativeWorkerSceneError(\n "backdrop-source-missing",\n "The live scene behind Glass is unavailable."\n );\n const output = this.gpu.texture(\n this.bank,\n `backdrop:${target.instanceId}:source`,\n target.width,\n target.height\n );\n if (!context.window)\n throw new NativeWorkerSceneError(\n "backdrop-geometry-unsupported",\n "Glass requires a validated source window."\n );\n const packet = new Float32Array(context.window.packet);\n packet[2] = context.encodedScene ? 1 : 0;\n const pipeline = await this.gpu.pipeline(\n groupLocalBackdropSourceWgsl,\n this.gpu.workingFormat,\n false,\n 1\n );\n const bind = this.gpu.bind(\n this.bank,\n `backdrop:${target.instanceId}:source`,\n pipeline,\n current,\n null,\n packet\n );\n draw(this.encoder, output, pipeline, bind);\n return output;\n }\n async finish(target, instance, definition, source) {\n if (instance.placement === "backdrop" && instance.clip === "text")\n throw new NativeWorkerSceneError(\n "backdrop-text-replacement-unsupported",\n "Text-clipped backdrop replacement needs separate coverage."\n );\n const extent = target.outputExtent;\n const transform = planNativeEffectTransform(instance.transform, {\n width: target.width,\n height: target.height,\n pixelRatio: target.pixelRatio,\n target: {\n x: extent?.left ?? 0,\n y: extent?.top ?? 0,\n width: extent?.sourceWidth ?? target.width,\n height: extent?.sourceHeight ?? target.height\n }\n });\n if (!transform.ok)\n throw new NativeWorkerSceneError(transform.code, transform.detail);\n const radii = instance.placement === "backdrop" || instance.placement === "fill" || extent?.expanded ? [0, 0, 0, 0, 0, 0, 0, 0] : target.cornerRadii ?? [0, 0, 0, 0, 0, 0, 0, 0];\n const textClip = instance.clip === "text" && (instance.placement === "fill" || instance.placement === "layer" && definition.kind === "processor");\n const mask = textClip ? this.asset(target.textMaskAssetId) : this.gpu.whiteTexture();\n const output = this.gpu.texture(\n this.bank,\n `effect:${instance.id}:finish`,\n target.width,\n target.height\n );\n const pipeline = await this.gpu.pipeline(\n finishWgsl,\n this.gpu.workingFormat,\n false,\n 2\n );\n const values = new Float32Array([\n target.width,\n target.height,\n 0,\n 0,\n instance.placement === "backdrop" ? 1 : instance.opacity,\n textClip ? 1 : 0,\n 0,\n 0,\n 0,\n 0,\n target.width,\n target.height,\n ...radii,\n ...transform.rows[0],\n ...transform.rows[1]\n ]);\n const bind = this.gpu.bind(\n this.bank,\n `effect:${instance.id}:finish`,\n pipeline,\n source,\n mask,\n values\n );\n draw(this.encoder, output, pipeline, bind);\n return output;\n }\n async renderTarget(target, instance, context) {\n const cached = this.outputs.get(instance.id);\n if (cached) return cached;\n if (this.active.has(instance.id))\n throw new NativeWorkerSceneError(\n "effect-dependency-cycle",\n `Effect ${instance.id} recursively depends on itself.`\n );\n this.active.add(instance.id);\n try {\n const definition = this.definitions.get(\n `${instance.definitionId}:${instance.definitionVersion}`\n );\n if (!definition)\n throw new NativeWorkerSceneError(\n "effect-definition-missing",\n `Effect ${instance.id} has no definition.`\n );\n const surface = {\n width: target.width,\n height: target.height,\n pixelRatio: target.pixelRatio,\n outputExtent: target.outputExtent,\n targetLocalSize: {\n width: (target.outputExtent?.sourceWidth ?? target.width) / target.pixelRatio,\n height: (target.outputExtent?.sourceHeight ?? target.height) / target.pixelRatio\n },\n targetViewportSize: {\n width: target.rect.width,\n height: target.rect.height\n }\n };\n const layerChain = instance.placement === "layer" ? this.scene.instances.filter(\n (candidate) => candidate.placement === "layer" && candidate.nodeId === instance.nodeId\n ) : [];\n const layerIndex = layerChain.findIndex(\n (candidate) => candidate.id === instance.id\n );\n const previousLayer = layerIndex > 0 ? layerChain[layerIndex - 1] : void 0;\n let source;\n if (previousLayer) {\n const previousTarget = this.targets.get(previousLayer.id);\n if (!previousTarget)\n throw new NativeWorkerSceneError(\n "effect-layer-dependency-unavailable",\n "The previous Layer target is unavailable."\n );\n const previousOutput = await this.renderTarget(\n previousTarget,\n previousLayer,\n context\n );\n source = await this.alignedLayerSource(\n target,\n previousTarget,\n previousOutput\n );\n } else if (instance.placement === "backdrop" && context.window) {\n source = await this.backdropSource(target, context);\n } else if (instance.placement === "fill") {\n source = this.gpu.transparentTexture();\n } else {\n source = target.sourceRecords.length ? await this.compose(\n target.sourceRecords,\n `target:${instance.id}:source`,\n surface,\n void 0,\n void 0,\n instance.placement === "layer" ? instance.id : void 0\n ) : this.gpu.transparentTexture();\n }\n const finished = await this.runEffect(\n target,\n instance,\n definition,\n source\n );\n if (instance.placement === "fill") {\n const sameNodeFills = this.scene.instances.filter(\n (candidate) => candidate.nodeId === instance.nodeId && candidate.placement === "fill"\n );\n const index = sameNodeFills.findIndex(\n (candidate) => candidate.id === instance.id\n );\n const previous = sameNodeFills[index - 1];\n if (previous && !this.fillCarry.has(previous.id)) {\n const previousTarget = this.targets.get(previous.id);\n if (!previousTarget)\n throw new NativeWorkerSceneError(\n "fill-dependency-unavailable",\n "The previous Fill target is unavailable."\n );\n await this.renderTarget(previousTarget, previous, context);\n }\n const fill = await renderNativeWorkerFill({\n scene: this.scene,\n target,\n instance,\n encoder: this.encoder,\n bank: this.bank,\n gpu: this.gpu,\n format: this.gpu.workingFormat,\n transparent: this.gpu.transparentTexture(),\n foreground: finished,\n previousFill: previous ? this.fillCarry.get(previous.id) : void 0,\n isTopFill: index === sameNodeFills.length - 1 && !this.scene.instances.slice(\n this.scene.instances.findIndex(\n (candidate) => candidate.id === instance.id\n ) + 1\n ).some(\n (candidate) => candidate.nodeId === instance.nodeId && candidate.placement === "layer"\n ),\n asset: (record4) => this.asset(record4.assetId),\n composeRecords: (records, key, surface2, blendMode, overrides) => this.compose(records, key, surface2, blendMode, overrides),\n stageFillBackdrops: (records, backdrop, presentationExtent) => this.stageFillBackdrops(\n instance,\n records,\n backdrop,\n presentationExtent\n )\n });\n this.fillCarry.set(instance.id, fill.carry);\n this.outputs.set(instance.id, fill.texture);\n return fill.texture;\n }\n this.outputs.set(instance.id, finished);\n return finished;\n } finally {\n this.active.delete(instance.id);\n }\n }\n async runEffect(target, instance, definition, source) {\n const mask = definition.passes.some((pass) => pass.reads.includes("mask")) ? await this.effectMask(target, instance) : this.gpu.whiteTexture();\n const result = await this.gpu.effect(\n this.bank,\n target,\n definition,\n instance,\n source,\n localTime(instance, this.timeSeconds),\n this.encoder,\n new Map([\n ...Object.entries(target.inputAssetIds ?? {}).map(\n ([resource, assetId]) => [resource, this.asset(assetId)]\n ),\n ...target.receiverGeometryAssetId ? [\n [\n "receiverGeometry",\n this.asset(target.receiverGeometryAssetId)\n ]\n ] : [],\n ...target.receiverInteriorAssetId ? [\n [\n "receiverInterior",\n this.asset(target.receiverInteriorAssetId)\n ]\n ] : [],\n ["mask", mask]\n ])\n );\n return this.finish(\n target,\n instance.placement === "fill" && instance.clip === "text" ? { ...instance, opacity: 1 } : instance,\n definition,\n result\n );\n }\n async effectMask(target, instance) {\n if (instance.placement === "backdrop")\n return this.asset(target.maskAssetId);\n const text = instance.clip === "text" ? this.asset(target.textMaskAssetId) : this.gpu.whiteTexture();\n const extent = target.outputExtent;\n const radii = target.cornerRadii ?? [0, 0, 0, 0, 0, 0, 0, 0];\n if (!extent?.expanded && radii.every((radius) => radius === 0)) return text;\n const output = this.gpu.texture(\n this.bank,\n `effect:${instance.id}:input-mask`,\n target.width,\n target.height\n );\n const pipeline = await this.gpu.pipeline(\n inputMaskWgsl,\n this.gpu.workingFormat,\n false,\n 1\n );\n const bind = this.gpu.bind(\n this.bank,\n `effect:${instance.id}:input-mask`,\n pipeline,\n text,\n null,\n new Float32Array([\n target.width,\n target.height,\n 0,\n 0,\n extent?.left ?? 0,\n extent?.top ?? 0,\n extent?.sourceWidth ?? target.width,\n extent?.sourceHeight ?? target.height,\n ...radii\n ])\n );\n draw(this.encoder, output, pipeline, bind);\n return output;\n }\n async alignedLayerSource(target, previous, prior) {\n const extent = target.outputExtent;\n const priorExtent = previous.outputExtent;\n if (!extent || !priorExtent || prior.width !== priorExtent.width || prior.height !== priorExtent.height || prior.format !== this.gpu.workingFormat)\n throw new NativeWorkerSceneError(\n "effect-layer-dependency-stale",\n "The previous Layer output does not match its extent."\n );\n const left = extent.left - priorExtent.left;\n const top = extent.top - priorExtent.top;\n if (left < 0 || top < 0 || left + prior.width > extent.width || top + prior.height > extent.height)\n throw new NativeWorkerSceneError(\n "effect-layer-chain-geometry-invalid",\n "Chained Layer output cannot fit the next effect extent."\n );\n if (!left && !top && prior.width === extent.width && prior.height === extent.height)\n return prior;\n const aligned = this.gpu.texture(\n this.bank,\n `effect:${target.instanceId}:aligned-source`,\n extent.width,\n extent.height\n );\n const clear = this.encoder.beginRenderPass({\n colorAttachments: [\n {\n view: aligned.createView(),\n loadOp: "clear",\n storeOp: "store",\n clearValue: { r: 0, g: 0, b: 0, a: 0 }\n }\n ]\n });\n clear.end();\n this.encoder.copyTextureToTexture(\n { texture: prior },\n { texture: aligned, origin: [left, top, 0] },\n [prior.width, prior.height]\n );\n return aligned;\n }\n async stageFillBackdrops(parent, records, base, extent) {\n const staged = /* @__PURE__ */ new Map();\n for (const record4 of records) {\n const childId = record4.nativeInstanceId;\n if (!childId || staged.has(childId)) continue;\n const child = this.instances.get(childId);\n if (!child || child.placement !== "backdrop") continue;\n const target = this.targets.get(childId);\n const definition = child && this.definitions.get(\n `${child.definitionId}:${child.definitionVersion}`\n );\n if (!target || !definition || !target.fillLocalSourceRecords)\n throw new NativeWorkerSceneError(\n "fill-child-staging-unavailable",\n `Nested Glass ${childId} has no Fill-local source snapshot.`\n );\n const prefixes = target.fillLocalSourceRecords.filter(\n (source) => source.sourceRole === "ancestor-fill-prefix"\n );\n if (prefixes.length !== 1 || prefixes[0]?.nativeInstanceId !== parent.id)\n throw new NativeWorkerSceneError(\n "fill-child-source-invalid",\n `Nested Glass ${childId} has no unique ancestor Fill prefix.`\n );\n if (this.active.has(childId))\n throw new NativeWorkerSceneError(\n "effect-dependency-cycle",\n `Nested Glass ${childId} is recursively active.`\n );\n this.active.add(childId);\n try {\n const overrides = new Map([\n [parent.id, base],\n ...staged\n ]);\n const source = await this.compose(\n target.fillLocalSourceRecords,\n `fill-local:${parent.id}:${childId}`,\n {\n width: target.width,\n height: target.height,\n pixelRatio: target.pixelRatio,\n outputExtent: target.outputExtent,\n targetLocalSize: {\n width: (target.outputExtent?.sourceWidth ?? target.width) / target.pixelRatio,\n height: (target.outputExtent?.sourceHeight ?? target.height) / target.pixelRatio\n },\n targetViewportSize: {\n width: extent.width / extent.pixelRatio,\n height: extent.height / extent.pixelRatio\n }\n },\n void 0,\n overrides\n );\n const output = await this.runEffect(target, child, definition, source);\n staged.set(childId, output);\n this.outputs.set(childId, output);\n } finally {\n this.active.delete(childId);\n }\n }\n return staged;\n }\n async render(records) {\n return this.compose(records, "root", {\n width: this.scene.width,\n height: this.scene.height,\n pixelRatio: this.scene.pixelRatio,\n viewport: this.scene.viewport\n });\n }\n async renderExport() {\n if (this.scene.backdropRecords) {\n await this.compose(this.scene.backdropRecords, "export:backdrop", {\n width: this.scene.width,\n height: this.scene.height,\n pixelRatio: this.scene.pixelRatio,\n viewport: this.scene.viewport\n });\n this.frozenBackdropOutputs = true;\n }\n return this.compose(this.scene.records, "export:selection", {\n width: this.scene.width,\n height: this.scene.height,\n pixelRatio: this.scene.pixelRatio,\n viewport: this.scene.viewport\n });\n }\n provenance() {\n return this.scene.instances.map((instance) => ({\n instanceId: instance.id,\n definitionHash: this.targets.get(instance.id).definitionHash,\n payload: JSON.stringify(instance),\n localTime: localTime(instance, this.timeSeconds)\n }));\n }\n };\n var _NativeWorkerRuntime = class _NativeWorkerRuntime {\n constructor(post) {\n this.post = post;\n this.scenes = /* @__PURE__ */ new Map();\n this.animationCadence = /* @__PURE__ */ new Map();\n this.timer = null;\n this.pumpBusy = false;\n this.stagedCursor = 0;\n this.device = null;\n this.creatingDevice = null;\n this.gpuTail = Promise.resolve();\n this.flights = [];\n this.flightWaiters = [];\n this.recordingFlights = 0;\n this.settlingFlight = false;\n this.flightRecovery = false;\n this.pendingFlightFailure = null;\n this.secondFlightUnavailable = false;\n this.pendingExclusiveOperations = 0;\n this.pendingInit = /* @__PURE__ */ new Set();\n this.cancelledInit = /* @__PURE__ */ new Set();\n }\n serializeGpu(task) {\n const result = this.gpuTail.then(task);\n this.gpuTail = result.then(\n () => void 0,\n () => void 0\n );\n return result;\n }\n waitForFlights() {\n if (!this.flights.length && !this.flightRecovery && !this.recordingFlights)\n return Promise.resolve();\n return new Promise((resolve) => this.flightWaiters.push(resolve));\n }\n async withExclusiveGpu(task) {\n this.pendingExclusiveOperations++;\n try {\n await this.waitForFlights();\n return await this.serializeGpu(task);\n } finally {\n this.pendingExclusiveOperations--;\n this.schedule();\n }\n }\n finishFlightWaiters() {\n if (this.flights.length || this.flightRecovery || this.recordingFlights)\n return;\n this.secondFlightUnavailable = false;\n for (const resolve of this.flightWaiters.splice(0)) resolve();\n }\n sceneHasFlight(state) {\n return this.flights.some(\n (flight) => flight.items.some((item) => item.state === state)\n );\n }\n flightItemCurrent(item) {\n const { state, scene } = item;\n const compatibleNewerCamera = state.staged !== null && state.currentSignature !== null && state.stagedSignature === state.currentSignature && compatibleCameraContent(scene, state.staged);\n const predecessorAdopted = item.staged && state.current === scene && state.currentSignature === item.signatureAtStart && (state.staged === null || compatibleNewerCamera);\n const compatibleCameraArrived = !item.staged && item.stagedAtStart === null && compatibleNewerCamera;\n return !state.disposed && (predecessorAdopted || state.current === item.currentAtStart && (state.staged === item.stagedAtStart || compatibleCameraArrived) && (item.staged ? state.staged === scene : state.current === scene));\n }\n async settleFlights() {\n if (this.settlingFlight) return;\n this.settlingFlight = true;\n try {\n while (this.flights.length) {\n const flight = this.flights[0];\n try {\n if (this.pendingFlightFailure !== null) {\n const failure3 = this.pendingFlightFailure;\n this.pendingFlightFailure = null;\n await this.recoverFlights(failure3);\n return;\n }\n if (!flight.fence)\n await this.serializeGpu(() => this.presentFlight(flight));\n const pendingFence = flight.fence;\n if (!pendingFence)\n throw new NativeWorkerSceneError(\n "gpu-flight-fence-missing",\n "The shared GPU flight has no completion fence."\n );\n const fence = await pendingFence;\n if (fence.status === "failed") throw fence.error;\n let superseded = false;\n await this.serializeGpu(async () => {\n superseded = flight.items.some(\n (item) => !this.flightItemCurrent(item)\n );\n if (superseded) return;\n for (const item of flight.items)\n item.state.gpu.validatePublication(item.lease, item.final);\n for (const item of flight.items) {\n const { state, scene, lease } = item;\n state.gpu.publish(lease, item.final, scene);\n const staged = item.staged && state.staged === scene;\n if (staged) state.anchorMs = item.anchorAtStart;\n this.completeFrame(\n item.sceneId,\n state,\n scene,\n staged,\n flight.now,\n lease.bank,\n item.renderer,\n item.timeSeconds,\n lease,\n flight.presentationSubmittedAtMs\n );\n }\n });\n if (superseded) {\n await this.recoverFlights(null);\n return;\n }\n this.flights.shift();\n for (const item of flight.items) {\n item.state.gpu.releaseFlight(item.lease);\n item.state.busy = this.sceneHasFlight(item.state);\n }\n this.secondFlightUnavailable = false;\n this.schedule();\n } catch (error) {\n try {\n await this.recoverFlights(error);\n } catch (recoveryError) {\n const first = flight.items[0];\n if (first)\n this.error(\n first.sceneId,\n recoveryError,\n void 0,\n first.scene.generation\n );\n }\n return;\n }\n }\n } finally {\n this.settlingFlight = false;\n this.finishFlightWaiters();\n for (const [sceneId, state] of this.scenes)\n if (state.disposed && !state.busy)\n void this.serializeGpu(\n async () => this.disposeScene(sceneId, state)\n ).catch((error) => this.error(sceneId, error));\n this.schedule();\n }\n }\n async recoverFlights(error) {\n this.flightRecovery = true;\n const failed = this.flights.splice(0);\n try {\n await this.serializeGpu(async () => {\n const device = failed[0]?.items[0]?.state.gpu.device;\n let drainFailure = null;\n try {\n if (device) await device.queue.onSubmittedWorkDone();\n } catch (failure3) {\n drainFailure = failure3;\n }\n let releaseFailure = null;\n for (const flight of failed)\n for (const item of flight.items)\n try {\n item.state.gpu.releaseFlight(item.lease);\n } catch (failure3) {\n releaseFailure ?? (releaseFailure = failure3);\n }\n if (drainFailure || releaseFailure)\n throw new NativeWorkerSceneError(\n "gpu-flight-drain-failed",\n `The shared GPU flight could not drain safely: ${String(drainFailure ?? releaseFailure)}`\n );\n let restorationFailure = null;\n const affected = /* @__PURE__ */ new Map();\n for (const flight of failed)\n for (const item of flight.items) affected.set(item.state, item);\n for (const item of affected.values()) {\n const current = item.state.current;\n if (item.state.disposed || !current) continue;\n const front = item.state.gpu.frontTexture();\n if (front) {\n try {\n const bank = item.state.gpu.spareBank(\n current,\n item.state.currentSignature\n );\n try {\n await this.present(item.state.gpu, bank, current, front, null);\n } finally {\n item.state.gpu.endLegacyFlight();\n }\n } catch (restoreError) {\n restorationFailure ?? (restorationFailure = restoreError);\n }\n }\n }\n if (restorationFailure)\n throw new NativeWorkerSceneError(\n "presentation-restore-failed",\n `A validated shared frame could not be restored: ${String(restorationFailure)}`\n );\n });\n if (error !== null) {\n const dueByState = /* @__PURE__ */ new Map();\n for (const flight of failed)\n for (const item of flight.due) dueByState.set(item.state, item);\n const due = [...dueByState.values()];\n let isolated = false;\n for (const item of due) {\n if (item.state.disposed || (item.staged ? item.state.staged !== item.scene : item.state.current !== item.scene))\n continue;\n try {\n await this.serializeGpu(\n () => this.frame(\n item.sceneId,\n item.state,\n item.scene,\n performance.now()\n )\n );\n } catch (sceneError) {\n isolated = true;\n if (item.staged && item.state.staged === item.scene) {\n item.state.staged = null;\n item.state.stagedSignature = null;\n } else if (!item.staged)\n item.state.failedGeneration = item.scene.generation;\n this.error(\n item.sceneId,\n sceneError,\n void 0,\n item.scene.generation\n );\n }\n }\n if (!isolated && due[0])\n this.error(\n due[0].sceneId,\n new NativeWorkerSceneError(\n "gpu-batch-validation",\n `The shared GPU batch failed validation before individual scenes recovered: ${String(error)}`\n ),\n void 0,\n due[0].scene.generation\n );\n }\n } finally {\n for (const flight of failed)\n for (const item of flight.items) item.state.busy = false;\n this.flightRecovery = false;\n this.secondFlightUnavailable = false;\n this.finishFlightWaiters();\n }\n }\n cadenceForRate(rate, compact = false) {\n const key = compact ? "compact" : rate;\n let cadence = this.animationCadence.get(key);\n if (!cadence) {\n cadence = new NativePreviewPolicyController();\n cadence.setPolicy({ quality: "quality", frameRateTarget: rate });\n cadence.setOverviewCompact(compact);\n this.animationCadence.set(key, cadence);\n }\n return cadence;\n }\n totalResourceBytes() {\n let bytes = 0;\n for (const state of this.scenes.values())\n bytes += state.gpu.resourceBytes();\n return bytes;\n }\n async validateUploads(scene, state) {\n await Promise.all(\n scene.requiredAssets.map(\n (asset) => state.pendingUploads.get(\n NativeWorkerGpu.assetKey(asset.assetId, asset.revision)\n )\n )\n );\n if (state.disposed)\n throw new NativeWorkerSceneError(\n "worker-scene-unavailable",\n "The GPU scene was disposed during asset validation."\n );\n }\n async sharedDevice() {\n if (this.device) return this.device;\n if (!this.creatingDevice)\n this.creatingDevice = (async () => {\n if (!navigator.gpu)\n throw new NativeWorkerSceneError(\n "gpu-unavailable",\n "WebGPU is unavailable in the worker."\n );\n const adapter = await navigator.gpu.requestAdapter();\n if (!adapter)\n throw new NativeWorkerSceneError(\n "gpu-unavailable",\n "No WebGPU adapter is available."\n );\n const device = await adapter.requestDevice();\n this.device = device;\n device.addEventListener("uncapturederror", (event) => {\n const error = event.error;\n for (const [sceneId, state] of this.scenes) {\n if (state.current)\n state.failedGeneration = state.current.generation;\n this.post({\n type: "error",\n sceneId,\n generation: state.current?.generation,\n code: "gpu-uncaptured-error",\n message: error?.message || "The GPU reported an uncaptured error."\n });\n }\n });\n void device.lost.then((loss) => {\n for (const [sceneId, state] of this.scenes) {\n state.disposed = true;\n this.post({\n type: "error",\n sceneId,\n code: "gpu-device-lost",\n message: loss.message || "The GPU device was lost."\n });\n }\n });\n return device;\n })();\n return this.creatingDevice;\n }\n error(sceneId, error, requestId, generation) {\n const known = error instanceof NativeWorkerGpuError || error instanceof NativeWorkerSceneError || error instanceof NativeWorkerCompositionError || error instanceof NativeWorkerFillError;\n this.post({\n type: "error",\n sceneId,\n requestId,\n generation,\n code: known ? error.code : "worker-render-failed",\n message: error instanceof Error ? error.message : String(error)\n });\n }\n async handle(message) {\n if (message.type === "init") {\n if (this.scenes.has(message.sceneId) || this.pendingInit.has(message.sceneId)) {\n this.error(\n message.sceneId,\n new NativeWorkerSceneError(\n "worker-protocol-mismatch",\n "The GPU scene is already initializing."\n )\n );\n return;\n }\n this.pendingInit.add(message.sceneId);\n try {\n if (message.protocol !== NATIVE_WORKER_PROTOCOL_VERSION)\n throw new NativeWorkerSceneError(\n "worker-protocol-mismatch",\n "The GPU worker initialization is invalid."\n );\n const gpu = await this.serializeGpu(async () => {\n if (this.totalResourceBytes() + 2097160 > _NativeWorkerRuntime.MAX_SHARED_RESOURCE_BYTES)\n throw new NativeWorkerGpuError(\n "gpu-shared-budget-exceeded",\n "The shared GPU worker has reached its bounded resource budget."\n );\n const created = await NativeWorkerGpu.create(\n message.sceneId,\n message.canvas,\n await this.sharedDevice()\n );\n if (this.totalResourceBytes() + created.resourceBytes() > _NativeWorkerRuntime.MAX_SHARED_RESOURCE_BYTES) {\n created.dispose();\n throw new NativeWorkerGpuError(\n "gpu-shared-budget-exceeded",\n "The shared GPU worker has reached its bounded resource budget."\n );\n }\n created.setSharedBudget((bytes, key) => {\n if (this.totalResourceBytes() + bytes > _NativeWorkerRuntime.MAX_SHARED_RESOURCE_BYTES)\n throw new NativeWorkerGpuError(\n "gpu-shared-budget-exceeded",\n `The shared GPU worker cannot allocate ${key} within its bounded resource budget.`\n );\n });\n return created;\n });\n if (this.cancelledInit.delete(message.sceneId)) {\n gpu.dispose();\n return;\n }\n this.scenes.set(message.sceneId, {\n gpu,\n staged: null,\n current: null,\n currentSignature: null,\n stagedSignature: null,\n anchorMs: 0,\n stagedAnchorMs: 0,\n frame: 0,\n busy: false,\n disposed: false,\n visible: true,\n exports: [],\n cancelled: /* @__PURE__ */ new Set(),\n lastPresentationMs: -Infinity,\n activeExportId: null,\n failedGeneration: null,\n cadence: new NativePreviewPolicyController(),\n pendingUploads: /* @__PURE__ */ new Map(),\n unclaimedAssets: /* @__PURE__ */ new Map()\n });\n this.post({\n type: "ready",\n sceneId: message.sceneId,\n protocol: NATIVE_WORKER_PROTOCOL_VERSION\n });\n } catch (error) {\n this.error(message.sceneId, error);\n } finally {\n this.pendingInit.delete(message.sceneId);\n if (!this.scenes.size && !this.pendingInit.size && this.device) {\n this.device.destroy();\n this.device = null;\n this.creatingDevice = null;\n }\n }\n return;\n }\n if (message.type === "dispose" && this.pendingInit.has(message.sceneId)) {\n this.cancelledInit.add(message.sceneId);\n return;\n }\n const sceneId = message.type === "scene" ? message.scene.sceneId : message.sceneId;\n const state = this.scenes.get(sceneId);\n if (!state || state.disposed) {\n if (message.type === "asset" && message.kind === "bitmap")\n message.bitmap.close();\n this.error(\n sceneId,\n new NativeWorkerSceneError(\n "worker-scene-unavailable",\n "The worker scene is unavailable."\n )\n );\n return;\n }\n if (message.type === "visibility") {\n state.visible = message.visible;\n if (!state.visible)\n void this.withExclusiveGpu(async () => {\n if (!state.disposed && !state.visible)\n state.gpu.reject(state.gpu.frontBank());\n }).catch((error) => this.error(sceneId, error));\n if (!this.hasScheduledWork() && this.timer !== null) {\n cancelAnimationFrame(this.timer);\n this.timer = null;\n }\n this.schedule();\n return;\n }\n if (message.type === "asset") {\n const key = NativeWorkerGpu.assetKey(message.assetId, message.revision);\n state.unclaimedAssets.set(key, message.generation);\n const task = this.withExclusiveGpu(async () => {\n state.gpu.device.pushErrorScope("validation");\n let scopeOpen = true;\n try {\n state.gpu.retireIdleWorkForAssetUpload(message);\n state.gpu.uploadAsset(message);\n const validation = await state.gpu.device.popErrorScope();\n scopeOpen = false;\n if (validation)\n throw new NativeWorkerSceneError(\n "gpu-asset-validation",\n validation.message\n );\n await state.gpu.device.queue.onSubmittedWorkDone();\n } catch (error) {\n if (scopeOpen) await state.gpu.device.popErrorScope();\n await state.gpu.device.queue.onSubmittedWorkDone();\n state.gpu.dropAsset(message.assetId, message.revision);\n state.unclaimedAssets.delete(key);\n throw error;\n }\n });\n state.pendingUploads.set(key, task);\n void task.then(\n () => {\n if (state.pendingUploads.get(key) === task)\n state.pendingUploads.delete(key);\n },\n () => {\n if (state.pendingUploads.get(key) === task)\n state.pendingUploads.delete(key);\n }\n );\n void task.catch(\n (error) => this.error(sceneId, error, void 0, message.generation)\n );\n return;\n }\n if (message.type === "cancel-export") {\n if (state.activeExportId === message.requestId)\n state.cancelled.add(message.requestId);\n state.exports = state.exports.filter(\n (request) => request.requestId !== message.requestId\n );\n return;\n }\n if (message.type === "dispose") {\n state.disposed = true;\n if (!state.busy)\n void this.withExclusiveGpu(\n async () => this.disposeScene(sceneId, state)\n ).catch((error) => this.error(sceneId, error));\n if (!this.hasScheduledWork() && this.timer !== null) {\n cancelAnimationFrame(this.timer);\n this.timer = null;\n }\n return;\n }\n if (message.type === "scene") {\n try {\n await this.validateUploads(message.scene, state);\n checkedScene(message.scene, state.gpu);\n for (const asset of message.scene.requiredAssets)\n state.unclaimedAssets.delete(\n NativeWorkerGpu.assetKey(asset.assetId, asset.revision)\n );\n if (message.scene.generation <= Math.max(\n state.current?.generation ?? 0,\n state.staged?.generation ?? 0\n ))\n throw new NativeWorkerSceneError(\n "scene-generation-stale",\n "The native scene generation did not advance."\n );\n state.staged = message.scene;\n state.stagedSignature = sceneCompositionSignature(message.scene);\n state.stagedAnchorMs = performance.now();\n state.failedGeneration = null;\n this.post({\n type: "scene-staged",\n sceneId,\n generation: message.scene.generation,\n sourceEpoch: message.scene.sourceEpoch\n });\n this.schedule();\n } catch (error) {\n this.error(sceneId, error, void 0, message.scene.generation);\n }\n return;\n }\n if (message.type === "camera") {\n try {\n const scene = checkedCamera(message, state);\n state.staged = scene;\n state.stagedSignature = state.currentSignature;\n state.stagedAnchorMs = performance.now();\n state.failedGeneration = null;\n this.post({\n type: "scene-staged",\n sceneId,\n generation: scene.generation,\n sourceEpoch: scene.sourceEpoch\n });\n this.schedule();\n } catch (error) {\n this.error(sceneId, error, void 0, message.generation);\n }\n return;\n }\n if (message.type === "export-scene") {\n try {\n await this.validateUploads(message.scene, state);\n checkedScene(message.scene, state.gpu);\n for (const asset of message.scene.requiredAssets)\n state.unclaimedAssets.delete(\n NativeWorkerGpu.assetKey(asset.assetId, asset.revision)\n );\n if (message.scene.sceneId !== message.sceneId || message.scene.pixelRatio !== message.pixelRatio || (message.selectedNodeIds?.length || message.selectedInstanceIds?.length) && !message.selectionFiltered)\n throw new NativeWorkerSceneError(\n "composition-export-snapshot-invalid",\n "The export scene is not an exact filtered density snapshot."\n );\n state.exports.push(message);\n this.schedule();\n } catch (error) {\n this.error(sceneId, error, message.requestId);\n }\n return;\n }\n if (message.type === "export") {\n this.error(\n sceneId,\n new NativeWorkerSceneError(\n "composition-export-snapshot-required",\n "PNG requires a separate immutable export-density scene snapshot."\n ),\n message.requestId\n );\n }\n }\n hasScheduledWork() {\n for (const state of this.scenes.values())\n if (!state.disposed && (state.exports.length || state.visible && (state.staged && (!this.sceneHasFlight(state) || state.staged.clock.playing) || state.current?.clock.playing && state.failedGeneration !== state.current.generation)))\n return true;\n return false;\n }\n schedule() {\n if (this.timer !== null || this.pumpBusy || this.flightRecovery || this.pendingExclusiveOperations > 0 || this.recordingFlights > 0 || this.flightWaiters.length > 0 || this.flights.length === 2 || this.flights.length > 0 && this.secondFlightUnavailable || !this.hasScheduledWork())\n return;\n this.timer = requestAnimationFrame((now) => {\n this.timer = null;\n void this.pumpAll(now);\n });\n }\n async pumpAll(now) {\n if (this.pumpBusy) return;\n this.pumpBusy = true;\n try {\n const needsExclusive = this.pendingExclusiveOperations > 0 || [...this.scenes.values()].some(\n (state) => !state.disposed && (state.exports.length > 0 || state.visible && state.staged !== null && (state.current === null || state.stagedSignature !== state.currentSignature))\n );\n if (this.flights.length && needsExclusive) return;\n const due = [];\n const dueRates = /* @__PURE__ */ new Map();\n for (const [sceneId, state] of this.scenes) {\n const staged = state.staged !== null && state.current !== null && state.stagedSignature !== null && state.stagedSignature === state.currentSignature;\n const scene = staged ? state.staged : state.current;\n if (!scene || !state.visible || state.disposed) continue;\n if (staged && this.sceneHasFlight(state) && (!scene.clock.playing || !this.flights.some(\n (flight) => flight.items.some(\n (item) => item.state === state && (item.staged && item.scene === scene || item.scene === state.current && compatibleCameraContent(item.scene, scene))\n )\n )))\n continue;\n if (!staged && !scene.clock.playing) continue;\n if (state.failedGeneration === scene.generation) continue;\n const rate = scene.frameRateTarget ?? 60;\n const compact = scene.compact === true;\n state.cadence.setPolicy({ quality: "quality", frameRateTarget: rate });\n state.cadence.setOverviewCompact(compact);\n const key = compact ? "compact" : rate;\n if (!dueRates.has(key))\n dueRates.set(\n key,\n this.cadenceForRate(rate, compact).isSubmissionDue(now, false, 2)\n );\n if (dueRates.get(key)) due.push({ sceneId, state, scene, staged });\n }\n if (due.length && !needsExclusive) {\n for (const item of due) item.state.busy = true;\n try {\n this.recordingFlights++;\n let flight;\n try {\n flight = await this.serializeGpu(() => this.recordFlight(due, now));\n if (flight) this.flights.push(flight);\n } finally {\n this.recordingFlights--;\n this.finishFlightWaiters();\n }\n if (flight) {\n await this.serializeGpu(() => this.presentFlight(flight));\n const committedCadences = /* @__PURE__ */ new Set();\n for (const item of flight.items) {\n const cadence = this.cadenceForRate(\n item.scene.frameRateTarget ?? 60,\n item.scene.compact === true\n );\n if (committedCadences.has(cadence)) continue;\n committedCadences.add(cadence);\n cadence.commitSubmission(now, false);\n }\n void this.settleFlights();\n } else if (this.flights.length) {\n this.secondFlightUnavailable = true;\n }\n } catch (error) {\n if (this.flights.length) {\n this.pendingFlightFailure = error;\n void this.settleFlights();\n } else {\n for (const item of due) {\n if (item.state.disposed) continue;\n try {\n await this.serializeGpu(\n () => this.frame(item.sceneId, item.state, item.scene, now)\n );\n } catch (sceneError) {\n if (item.staged && item.state.staged === item.scene) {\n item.state.staged = null;\n item.state.stagedSignature = null;\n } else if (!item.staged)\n item.state.failedGeneration = item.scene.generation;\n this.error(\n item.sceneId,\n sceneError,\n void 0,\n item.scene.generation\n );\n }\n }\n }\n } finally {\n for (const item of due)\n if (!this.sceneHasFlight(item.state)) item.state.busy = false;\n }\n }\n if (this.flights.length) return;\n const exports = [...this.scenes].find(\n ([, state]) => !state.disposed && state.exports.length\n );\n if (exports) {\n const [sceneId, state] = exports;\n const request = state.exports.shift();\n if (request) {\n state.busy = true;\n try {\n await this.serializeGpu(\n () => this.exportScene(sceneId, state, request)\n );\n } catch (error) {\n this.error(\n sceneId,\n error,\n request.requestId,\n request.scene.generation\n );\n } finally {\n state.busy = false;\n }\n }\n }\n const scenes = [...this.scenes];\n for (let step = 0; step < scenes.length; step++) {\n const index = (this.stagedCursor + step) % scenes.length;\n const [sceneId, state] = scenes[index];\n const scene = state.staged;\n if (!scene || state.disposed || !state.visible) continue;\n if (state.current && state.stagedSignature !== null && state.stagedSignature === state.currentSignature)\n continue;\n state.cadence.setPolicy({\n quality: "quality",\n frameRateTarget: scene.frameRateTarget ?? 60\n });\n state.cadence.setOverviewCompact(scene.compact === true);\n if (!state.cadence.isSubmissionDue(now, true, 2)) continue;\n this.stagedCursor = (index + 1) % scenes.length;\n state.busy = true;\n try {\n await this.serializeGpu(() => this.frame(sceneId, state, scene, now));\n } catch (error) {\n if (state.staged === scene) {\n state.staged = null;\n state.stagedSignature = null;\n }\n this.error(sceneId, error, void 0, scene.generation);\n } finally {\n state.busy = false;\n }\n break;\n }\n } finally {\n for (const [sceneId, state] of this.scenes)\n if (state.disposed && !state.busy)\n await this.serializeGpu(\n async () => this.disposeScene(sceneId, state)\n );\n this.pumpBusy = false;\n this.schedule();\n }\n }\n async recordFlight(due, now) {\n const device = due[0]?.state.gpu.device;\n if (!device) return null;\n if (due.some((item) => item.state.gpu.device !== device))\n throw new NativeWorkerSceneError(\n "gpu-shared-device-mismatch",\n "The worker batch contains scenes from different GPU devices."\n );\n const acquired = [];\n let acquisitionComplete = false;\n try {\n for (const item of due) {\n if (item.state.disposed || (item.staged ? item.state.staged !== item.scene : item.state.current !== item.scene))\n continue;\n const result = item.state.gpu.tryAcquireFlight(\n item.scene,\n item.staged ? item.state.stagedSignature : item.state.currentSignature\n );\n if (result.status === "capacity") {\n if (this.flights.length) return null;\n throw new NativeWorkerSceneError(\n "gpu-flight-capacity",\n `The first GPU flight could not acquire a candidate: ${result.reason}`\n );\n }\n acquired.push({ ...item, lease: result.lease });\n }\n acquisitionComplete = true;\n } finally {\n if (!acquisitionComplete)\n for (const held of acquired) held.state.gpu.releaseFlight(held.lease);\n }\n if (!acquired.length) return null;\n const rendered = [];\n const buffers = [];\n let scopeOpen = false;\n let submitted = false;\n let failed = false;\n try {\n device.pushErrorScope("validation");\n scopeOpen = true;\n for (const item of acquired) {\n const { state, scene, lease } = item;\n const stagedAtStart = state.staged;\n const currentAtStart = state.current;\n const anchorAtStart = item.staged ? state.stagedAnchorMs : state.anchorMs;\n const signatureAtStart = item.staged ? state.stagedSignature : state.currentSignature;\n state.gpu.beginFrame(lease);\n const encoder = device.createCommandEncoder();\n const timeSeconds = clockTime(scene, anchorAtStart, now);\n const renderer = new NativeWorkerRenderer(\n scene,\n timeSeconds,\n state.gpu,\n lease.bank,\n encoder\n );\n const composed = await renderer.render(scene.records);\n const final = state.gpu.stageFinal(lease, scene, composed, encoder);\n state.gpu.uploadFrame(lease);\n buffers.push(encoder.finish());\n rendered.push({\n ...item,\n final,\n renderer,\n timeSeconds,\n stagedAtStart,\n currentAtStart,\n anchorAtStart,\n signatureAtStart\n });\n }\n device.queue.submit(buffers);\n submitted = true;\n for (const item of acquired)\n item.state.gpu.markFlightSubmitted(item.lease);\n const validationPromise = device.popErrorScope();\n scopeOpen = false;\n const validation = await validationPromise;\n if (validation)\n throw new NativeWorkerSceneError("gpu-validation", validation.message);\n return {\n items: rendered,\n due,\n now,\n fence: null,\n presentation: null,\n presentationSubmittedAtMs: null\n };\n } catch (error) {\n failed = true;\n if (scopeOpen) await device.popErrorScope();\n if (submitted) await device.queue.onSubmittedWorkDone();\n if (!submitted && this.flights.length && error instanceof NativeWorkerGpuFlightCapacityError)\n return null;\n throw error;\n } finally {\n for (const item of acquired) item.state.gpu.finishFrame(item.lease);\n if (failed)\n for (const item of acquired) item.state.gpu.releaseFlight(item.lease);\n }\n }\n presentFlight(flight) {\n return flight.presentation ?? (flight.presentation = this.submitPresentation(flight));\n }\n async submitPresentation(flight) {\n const device = flight.items[0]?.state.gpu.device;\n if (!device) return;\n if (flight.items.some((item) => !this.flightItemCurrent(item))) {\n flight.fence = device.queue.onSubmittedWorkDone().then(\n () => ({ status: "completed" }),\n (error) => ({ status: "failed", error })\n );\n return;\n }\n const buffers = [];\n let scopeOpen = false;\n let submitted = false;\n try {\n device.pushErrorScope("validation");\n scopeOpen = true;\n for (const item of flight.items) {\n const gpu = item.state.gpu;\n gpu.preparePresentation(item.scene);\n gpu.beginFrame(item.lease);\n const encoder = device.createCommandEncoder();\n const pipeline = await gpu.pipeline(\n presentWgsl(item.scene.colorSpace),\n gpu.canvasFormat,\n false,\n 2\n );\n const bind = gpu.bind(\n item.lease.bank,\n "presentation",\n pipeline,\n item.final,\n gpu.whiteTexture(),\n new Float32Array([\n item.scene.width,\n item.scene.height,\n 0,\n 0,\n 1,\n 0,\n 0,\n 0\n ])\n );\n draw(encoder, gpu.context.getCurrentTexture(), pipeline, bind);\n gpu.uploadFrame(item.lease);\n buffers.push(encoder.finish());\n }\n if (flight.items.every((item) => this.flightItemCurrent(item))) {\n device.queue.submit(buffers);\n submitted = true;\n flight.presentationSubmittedAtMs = performance.now();\n }\n const validationPromise = device.popErrorScope();\n scopeOpen = false;\n const completionPromise = device.queue.onSubmittedWorkDone();\n flight.fence = Promise.allSettled([\n validationPromise,\n completionPromise\n ]).then(([validation, completion]) => {\n const failures = [];\n if (validation.status === "rejected") failures.push(validation.reason);\n else if (validation.value)\n failures.push(\n new NativeWorkerSceneError(\n "gpu-validation",\n validation.value.message\n )\n );\n if (completion.status === "rejected") failures.push(completion.reason);\n return failures.length ? {\n status: "failed",\n error: failures.length === 1 ? failures[0] : Object.assign(\n new NativeWorkerSceneError(\n "gpu-presentation-failed",\n `GPU presentation validation and completion both failed: ${failures.map(String).join("; ")}`\n ),\n { errors: failures }\n )\n } : { status: "completed" };\n });\n } catch (error) {\n if (scopeOpen) await device.popErrorScope();\n if (submitted) await device.queue.onSubmittedWorkDone();\n throw error;\n } finally {\n for (const item of flight.items) item.state.gpu.finishFrame(item.lease);\n }\n }\n completeFrame(sceneId, state, scene, staged, now, bank, renderer, timeSeconds, lease, presentationSubmittedAtMs) {\n if (lease) state.gpu.trimWork(lease);\n else state.gpu.trimWork(bank);\n const cadenceKey = scene.compact ? "compact" : scene.frameRateTarget ?? 60;\n if (staged && scene.clock.playing && !this.animationCadence.has(cadenceKey))\n this.cadenceForRate(\n scene.frameRateTarget ?? 60,\n scene.compact === true\n ).commitSubmission(now, false);\n if (staged) {\n state.current = scene;\n state.staged = null;\n state.currentSignature = state.stagedSignature;\n state.stagedSignature = null;\n }\n state.frame++;\n state.lastPresentationMs = now;\n state.cadence.commitSubmission(now, staged);\n for (const [key, generation] of state.unclaimedAssets)\n if (generation <= scene.generation) state.unclaimedAssets.delete(key);\n const held = new Set(\n [\n ...state.current?.requiredAssets ?? [],\n ...state.staged?.requiredAssets ?? [],\n ...state.exports.flatMap((pending) => pending.scene.requiredAssets),\n ...this.flights.flatMap(\n (flight) => flight.items.filter((item) => item.state === state).flatMap((item) => item.scene.requiredAssets)\n )\n ].map((asset) => NativeWorkerGpu.assetKey(asset.assetId, asset.revision))\n );\n for (const key of state.unclaimedAssets.keys()) held.add(key);\n state.gpu.retireAssets(held);\n this.post({\n type: "committed",\n sceneId,\n generation: scene.generation,\n sourceEpoch: scene.sourceEpoch,\n frame: state.frame,\n timeSeconds,\n presentedAtMs: performance.now(),\n ...presentationSubmittedAtMs !== null && presentationSubmittedAtMs !== void 0 ? { presentationSubmittedAtMs } : {},\n ...staged ? { committedInstances: renderer.provenance() } : {}\n });\n }\n async frame(sceneId, state, scene, now) {\n const gpu = state.gpu;\n const staged = state.staged === scene;\n const anchor = staged ? state.stagedAnchorMs : state.anchorMs;\n const timeSeconds = clockTime(scene, anchor, now);\n const bank = gpu.spareBank(\n scene,\n staged ? state.stagedSignature : state.currentSignature\n );\n gpu.device.pushErrorScope("validation");\n let scopeOpen = true;\n let submitted = false;\n gpu.beginFrame();\n let frameOpen = true;\n try {\n const encoder = gpu.device.createCommandEncoder();\n const renderer = new NativeWorkerRenderer(\n scene,\n timeSeconds,\n gpu,\n bank,\n encoder\n );\n const composed = await renderer.render(scene.records);\n const final = gpu.stageFinal(scene, composed, encoder);\n gpu.uploadFrame();\n gpu.device.queue.submit([encoder.finish()]);\n submitted = true;\n const validation = await gpu.device.popErrorScope();\n scopeOpen = false;\n if (validation)\n throw new NativeWorkerSceneError("gpu-validation", validation.message);\n await gpu.device.queue.onSubmittedWorkDone();\n if (state.disposed || staged && state.staged !== scene) return;\n gpu.finishFrame();\n frameOpen = false;\n await this.present(gpu, bank, scene, final, state.current);\n if (state.disposed) return;\n if (staged && state.staged !== scene) {\n const front = gpu.frontTexture();\n if (state.current && front) {\n try {\n await this.present(gpu, bank, state.current, front, null);\n } catch (error) {\n throw new NativeWorkerSceneError(\n "presentation-restore-failed",\n `The last validated frame could not be restored: ${String(error)}`\n );\n }\n }\n return;\n }\n gpu.publish(bank, final, scene);\n if (staged) state.anchorMs = anchor;\n this.completeFrame(\n sceneId,\n state,\n scene,\n staged,\n now,\n bank,\n renderer,\n timeSeconds\n );\n } catch (error) {\n if (scopeOpen) {\n const validation = await gpu.device.popErrorScope();\n if (validation && !(error instanceof Error))\n error = new NativeWorkerSceneError(\n "gpu-validation",\n validation.message\n );\n }\n if (submitted) await gpu.device.queue.onSubmittedWorkDone();\n if (staged && state.staged === scene) {\n state.staged = null;\n state.stagedSignature = null;\n }\n throw error;\n } finally {\n if (frameOpen) gpu.finishFrame();\n gpu.endLegacyFlight();\n }\n }\n async present(gpu, bank, scene, final, previous) {\n gpu.preparePresentation(scene);\n gpu.beginFrame();\n let scopeOpen = false;\n let failure3;\n try {\n gpu.device.pushErrorScope("validation");\n scopeOpen = true;\n const encoder = gpu.device.createCommandEncoder();\n const pipeline = await gpu.pipeline(\n presentWgsl(scene.colorSpace),\n gpu.canvasFormat,\n false,\n 2\n );\n const bind = gpu.bind(\n bank,\n "presentation",\n pipeline,\n final,\n gpu.whiteTexture(),\n new Float32Array([scene.width, scene.height, 0, 0, 1, 0, 0, 0])\n );\n draw(encoder, gpu.context.getCurrentTexture(), pipeline, bind);\n gpu.uploadFrame();\n gpu.device.queue.submit([encoder.finish()]);\n const validation = await gpu.device.popErrorScope();\n scopeOpen = false;\n if (validation)\n throw new NativeWorkerSceneError("gpu-validation", validation.message);\n await gpu.device.queue.onSubmittedWorkDone();\n } catch (error) {\n failure3 = error;\n if (scopeOpen) await gpu.device.popErrorScope();\n await gpu.device.queue.onSubmittedWorkDone();\n } finally {\n gpu.finishFrame();\n }\n if (failure3) {\n const front = gpu.frontTexture();\n if (previous && front) {\n try {\n await this.present(gpu, bank, previous, front, null);\n } catch (restoreError) {\n throw new NativeWorkerSceneError(\n "presentation-restore-failed",\n `The last validated frame could not be restored: ${String(restoreError)}`\n );\n }\n }\n throw failure3;\n }\n }\n async exportScene(sceneId, state, request) {\n state.activeExportId = request.requestId;\n const gpu = state.gpu;\n let bank = null;\n let frameOpen = false;\n let scopeOpen = false;\n let readback = null;\n let readbackBytes = 0;\n let readbackReserved = false;\n let submitted = false;\n let mapped = false;\n let cancelled = state.cancelled.delete(request.requestId);\n let failed = false;\n let failure3;\n let response = null;\n const cleanup = (action) => {\n try {\n action();\n } catch (error) {\n if (!failed) {\n failed = true;\n failure3 = error;\n }\n }\n };\n try {\n if (!cancelled) {\n const planned = planNativeExportRegion({\n viewport: {\n width: Math.ceil(request.scene.viewport.width),\n height: Math.ceil(request.scene.viewport.height)\n },\n cropRect: request.cropRect,\n pixelRatio: request.pixelRatio\n });\n if (!planned.ok)\n throw new NativeWorkerSceneError(\n `composition-${planned.code}`,\n "The selected PNG region has unsupported geometry."\n );\n bank = gpu.spareBank(request.scene);\n gpu.beginFrame();\n frameOpen = true;\n gpu.device.pushErrorScope("validation");\n scopeOpen = true;\n const encoder = gpu.device.createCommandEncoder();\n const renderer = new NativeWorkerRenderer(\n request.scene,\n request.timeSeconds,\n gpu,\n bank,\n encoder\n );\n const composed = await renderer.renderExport();\n gpu.uploadFrame();\n gpu.device.queue.submit([encoder.finish()]);\n submitted = true;\n const compositionValidation = await gpu.device.popErrorScope();\n scopeOpen = false;\n if (compositionValidation)\n throw new NativeWorkerSceneError(\n "gpu-validation",\n compositionValidation.message\n );\n await gpu.device.queue.onSubmittedWorkDone();\n gpu.finishFrame();\n frameOpen = false;\n gpu.trimWorkExcept(bank, composed);\n gpu.beginFrame();\n frameOpen = true;\n gpu.device.pushErrorScope("validation");\n scopeOpen = true;\n const outputEncoder = gpu.device.createCommandEncoder();\n const output = gpu.texture(\n bank,\n "export:output",\n planned.width,\n planned.height,\n "rgba8unorm"\n );\n const pipeline = await gpu.pipeline(\n nativeWorkerExportRegionWgsl,\n "rgba8unorm",\n false,\n 1\n );\n const crop = planned.region;\n const bind = gpu.bind(\n bank,\n "export:color",\n pipeline,\n composed,\n null,\n new Float32Array([\n request.scene.width,\n request.scene.height,\n (crop.x - request.scene.viewport.x) * request.pixelRatio,\n (crop.y - request.scene.viewport.y) * request.pixelRatio,\n 1,\n 0,\n 0,\n 0\n ])\n );\n draw(outputEncoder, output, pipeline, bind);\n const bytesPerRow = Math.ceil(planned.width * 4 / 256) * 256;\n readbackBytes = bytesPerRow * planned.height;\n gpu.reserveTransient(readbackBytes, "export:readback");\n readbackReserved = true;\n readback = gpu.device.createBuffer({\n size: readbackBytes,\n usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ\n });\n outputEncoder.copyTextureToBuffer(\n { texture: output },\n { buffer: readback, bytesPerRow },\n [planned.width, planned.height]\n );\n gpu.uploadFrame();\n gpu.device.queue.submit([outputEncoder.finish()]);\n submitted = true;\n const validation = await gpu.device.popErrorScope();\n scopeOpen = false;\n if (validation)\n throw new NativeWorkerSceneError(\n "gpu-validation",\n validation.message\n );\n await gpu.device.queue.onSubmittedWorkDone();\n cancelled = state.cancelled.delete(request.requestId);\n if (!cancelled) {\n await readback.mapAsync(GPUMapMode.READ);\n mapped = true;\n cancelled = state.cancelled.delete(request.requestId);\n if (!cancelled) {\n const mappedBytes = new Uint8Array(readback.getMappedRange());\n const rgba = new Uint8Array(planned.width * planned.height * 4);\n for (let row = 0; row < planned.height; row++)\n rgba.set(\n mappedBytes.subarray(\n row * bytesPerRow,\n row * bytesPerRow + planned.width * 4\n ),\n row * planned.width * 4\n );\n response = {\n type: "exported",\n sceneId,\n requestId: request.requestId,\n generation: request.scene.generation,\n sourceEpoch: request.scene.sourceEpoch,\n width: planned.width,\n height: planned.height,\n rgba: rgba.buffer,\n timeSeconds: request.timeSeconds,\n committedInstances: renderer.provenance()\n };\n }\n }\n }\n } catch (error) {\n failed = true;\n failure3 = error;\n if (scopeOpen) {\n try {\n await gpu.device.popErrorScope();\n } catch (scopeError) {\n failure3 = scopeError;\n }\n }\n if (submitted) {\n try {\n await gpu.device.queue.onSubmittedWorkDone();\n } catch (queueError) {\n failure3 = queueError;\n }\n }\n } finally {\n if (mapped) cleanup(() => readback?.unmap());\n if (readback) {\n const buffer = readback;\n cleanup(() => buffer.destroy());\n }\n if (readbackReserved) cleanup(() => gpu.releaseTransient(readbackBytes));\n if (frameOpen) cleanup(() => gpu.finishFrame());\n if (bank) {\n const finishedBank = bank;\n cleanup(() => gpu.trimWorkExcept(finishedBank, null));\n }\n cleanup(() => gpu.endLegacyFlight());\n state.activeExportId = null;\n cancelled = state.cancelled.delete(request.requestId) || cancelled;\n const held = new Set(\n [\n ...state.current?.requiredAssets ?? [],\n ...state.staged?.requiredAssets ?? [],\n ...state.exports.flatMap((pending) => pending.scene.requiredAssets)\n ].map(\n (asset) => NativeWorkerGpu.assetKey(asset.assetId, asset.revision)\n )\n );\n for (const key of state.unclaimedAssets.keys()) held.add(key);\n cleanup(() => gpu.retireAssets(held));\n }\n if (cancelled) return;\n if (failed) this.error(sceneId, failure3, request.requestId);\n else if (response) this.post(response, [response.rgba]);\n }\n disposeScene(sceneId, state) {\n state.gpu.dispose();\n this.scenes.delete(sceneId);\n if (!this.scenes.size && this.device) {\n this.device.destroy();\n this.device = null;\n this.creatingDevice = null;\n }\n }\n };\n _NativeWorkerRuntime.MAX_SHARED_RESOURCE_BYTES = 2147483648;\n var NativeWorkerRuntime = _NativeWorkerRuntime;\n var workerScope = globalThis;\n var runtime = new NativeWorkerRuntime(\n (message, transfer) => workerScope.postMessage(message, transfer)\n );\n workerScope.onmessage = (event) => {\n void runtime.handle(event.data);\n };\n})();\n';