@tempo-ai/visual-review 0.0.142 → 0.0.144-staging.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +10 -0
  2. package/dist/bin.js +1 -31
  3. package/dist/chunk-52K7VV3D.js +1 -0
  4. package/dist/chunk-DXPI3C2L.js +1 -0
  5. package/dist/chunk-GBYDKH7R.js +1 -0
  6. package/dist/chunk-HBU3VTFZ.js +1 -0
  7. package/dist/chunk-LC4ZHZOJ.js +1 -0
  8. package/dist/chunk-OU25755E.js +1 -0
  9. package/dist/chunk-VXZ23ZMX.js +1 -0
  10. package/dist/claim-IQILN5LU.js +1 -0
  11. package/dist/cli-DCBGPPCW.js +1 -0
  12. package/dist/index.d.ts +206 -111
  13. package/dist/index.js +1 -72
  14. package/dist/install-browsers-YO57KLRL.js +1 -0
  15. package/dist/report-HPEESVEL.js +1 -0
  16. package/dist/sdk-runtime/browser-runtime.cjs +12 -0
  17. package/dist/sdk-runtime/node/astro.cjs +224 -0
  18. package/dist/sdk-runtime/node/core.cjs +154 -0
  19. package/dist/sdk-runtime/node/nuxt.cjs +69 -0
  20. package/dist/sdk-runtime/node/svelte.cjs +20 -0
  21. package/dist/sdk-runtime/node/vue.cjs +18 -0
  22. package/dist/sdk-runtime/runtime.json +58 -0
  23. package/package.json +13 -30
  24. package/dist/bin.js.map +0 -1
  25. package/dist/chunk-BTZJDIC4.js +0 -227
  26. package/dist/chunk-BTZJDIC4.js.map +0 -1
  27. package/dist/chunk-EWF3ZRZK.js +0 -64420
  28. package/dist/chunk-EWF3ZRZK.js.map +0 -1
  29. package/dist/chunk-EYRAT56C.js +0 -42
  30. package/dist/chunk-EYRAT56C.js.map +0 -1
  31. package/dist/chunk-H7MXR6QX.js +0 -360
  32. package/dist/chunk-H7MXR6QX.js.map +0 -1
  33. package/dist/chunk-Q6FW7NII.js +0 -376
  34. package/dist/chunk-Q6FW7NII.js.map +0 -1
  35. package/dist/chunk-WQOUTFK5.js +0 -260
  36. package/dist/chunk-WQOUTFK5.js.map +0 -1
  37. package/dist/chunk-WRI3HTCJ.js +0 -39
  38. package/dist/chunk-WRI3HTCJ.js.map +0 -1
  39. package/dist/claim-TARSUW6K.js +0 -14
  40. package/dist/claim-TARSUW6K.js.map +0 -1
  41. package/dist/cli-JLERE5LZ.js +0 -20
  42. package/dist/cli-JLERE5LZ.js.map +0 -1
  43. package/dist/index.js.map +0 -1
  44. package/dist/install-browsers-VPIMDVB6.js +0 -9
  45. package/dist/install-browsers-VPIMDVB6.js.map +0 -1
  46. package/dist/report-5LJCK3JT.js +0 -13
  47. package/dist/report-5LJCK3JT.js.map +0 -1
@@ -0,0 +1 @@
1
+ import{createRequire as e}from"node:module";e(import.meta.url);import{buildBitbucketNoVisualChangeComment as t,upsertBitbucketStickyComment as n}from"./chunk-VXZ23ZMX.js";import{DEFAULT_VISUAL_REVIEW_INGEST_URL as r,declareNoVisualChangeIfPresent as s,detectCiContext as i,fetchWithRetry as a,readCiState as o,resolveIngestCredential as c,writeCiState as l}from"./chunk-LC4ZHZOJ.js";import{__commonJS as d,__require as u,__toESM as p}from"./chunk-52K7VV3D.js";var h=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/identity.js"(e){var t=Symbol.for("yaml.alias"),n=Symbol.for("yaml.document"),r=Symbol.for("yaml.map"),s=Symbol.for("yaml.pair"),i=Symbol.for("yaml.scalar"),a=Symbol.for("yaml.seq"),o=Symbol.for("yaml.node.type"),isAlias=e=>!!e&&"object"==typeof e&&e[o]===t,isDocument=e=>!!e&&"object"==typeof e&&e[o]===n,isMap=e=>!!e&&"object"==typeof e&&e[o]===r,isPair=e=>!!e&&"object"==typeof e&&e[o]===s,isScalar=e=>!!e&&"object"==typeof e&&e[o]===i,isSeq=e=>!!e&&"object"==typeof e&&e[o]===a;function isCollection(e){if(e&&"object"==typeof e)switch(e[o]){case r:case a:return!0}return!1}function isNode(e){if(e&&"object"==typeof e)switch(e[o]){case t:case r:case i:case a:return!0}return!1}var hasAnchor=e=>(isScalar(e)||isCollection(e))&&!!e.anchor;e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=o,e.PAIR=s,e.SCALAR=i,e.SEQ=a,e.hasAnchor=hasAnchor,e.isAlias=isAlias,e.isCollection=isCollection,e.isDocument=isDocument,e.isMap=isMap,e.isNode=isNode,e.isPair=isPair,e.isScalar=isScalar,e.isSeq=isSeq}}),m=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/visit.js"(e){var t=h(),n=Symbol("break visit"),r=Symbol("skip children"),s=Symbol("remove node");function visit(e,n){const r=initVisitor(n);if(t.isDocument(e)){const t=visit_(null,e.contents,r,Object.freeze([e]));t===s&&(e.contents=null)}else visit_(null,e,r,Object.freeze([]))}function visit_(e,r,i,a){const o=callVisitor(e,r,i,a);if(t.isNode(o)||t.isPair(o))return replaceNode(e,a,o),visit_(e,o,i,a);if("symbol"!=typeof o)if(t.isCollection(r)){a=Object.freeze(a.concat(r));for(let e=0;e<r.items.length;++e){const t=visit_(e,r.items[e],i,a);if("number"==typeof t)e=t-1;else{if(t===n)return n;t===s&&(r.items.splice(e,1),e-=1)}}}else if(t.isPair(r)){a=Object.freeze(a.concat(r));const e=visit_("key",r.key,i,a);if(e===n)return n;e===s&&(r.key=null);const t=visit_("value",r.value,i,a);if(t===n)return n;t===s&&(r.value=null)}return o}async function visitAsync(e,n){const r=initVisitor(n);if(t.isDocument(e)){const t=await visitAsync_(null,e.contents,r,Object.freeze([e]));t===s&&(e.contents=null)}else await visitAsync_(null,e,r,Object.freeze([]))}async function visitAsync_(e,r,i,a){const o=await callVisitor(e,r,i,a);if(t.isNode(o)||t.isPair(o))return replaceNode(e,a,o),visitAsync_(e,o,i,a);if("symbol"!=typeof o)if(t.isCollection(r)){a=Object.freeze(a.concat(r));for(let e=0;e<r.items.length;++e){const t=await visitAsync_(e,r.items[e],i,a);if("number"==typeof t)e=t-1;else{if(t===n)return n;t===s&&(r.items.splice(e,1),e-=1)}}}else if(t.isPair(r)){a=Object.freeze(a.concat(r));const e=await visitAsync_("key",r.key,i,a);if(e===n)return n;e===s&&(r.key=null);const t=await visitAsync_("value",r.value,i,a);if(t===n)return n;t===s&&(r.value=null)}return o}function initVisitor(e){return"object"==typeof e&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function callVisitor(e,n,r,s){return"function"==typeof r?r(e,n,s):t.isMap(n)?r.Map?.(e,n,s):t.isSeq(n)?r.Seq?.(e,n,s):t.isPair(n)?r.Pair?.(e,n,s):t.isScalar(n)?r.Scalar?.(e,n,s):t.isAlias(n)?r.Alias?.(e,n,s):void 0}function replaceNode(e,n,r){const s=n[n.length-1];if(t.isCollection(s))s.items[e]=r;else if(t.isPair(s))"key"===e?s.key=r:s.value=r;else{if(!t.isDocument(s)){const e=t.isAlias(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${e} parent`)}s.contents=r}}visit.BREAK=n,visit.SKIP=r,visit.REMOVE=s,visitAsync.BREAK=n,visitAsync.SKIP=r,visitAsync.REMOVE=s,e.visit=visit,e.visitAsync=visitAsync}}),f=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/directives.js"(e){var t=h(),n=m(),r={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=e=>e.replace(/[!,[\]{}]/g,e=>r[e]),s=class _Directives{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},_Directives.defaultYaml,e),this.tags=Object.assign({},_Directives.defaultTags,t)}clone(){const e=new _Directives(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},_Directives.defaultTags)}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},_Directives.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(2!==n.length&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[e,r]=n;return this.tags[e]=r,!0}case"%YAML":{if(this.yaml.explicit=!0,1!==n.length)return t(0,"%YAML directive should contain exactly one part"),!1;const[e]=n;if("1.1"===e||"1.2"===e)return this.yaml.version=e,!0;{const n=/^\d+\.\d+$/.test(e);return t(6,`Unsupported YAML version ${e}`,n),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if("!"===e)return"!";if("!"!==e[0])return t(`Not a valid tag: ${e}`),null;if("<"===e[1]){const n=e.slice(2,-1);return"!"===n||"!!"===n?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(">"!==e[e.length-1]&&t("Verbatim tags must end with a >"),n)}const[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);const s=this.tags[n];if(s)try{return s+decodeURIComponent(r)}catch(e){return t(String(e)),null}return"!"===n?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+escapeTagName(e.substring(n.length));return"!"===e[0]?e:`!<${e}>`}toString(e){const r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],s=Object.entries(this.tags);let i;if(e&&s.length>0&&t.isNode(e.contents)){const r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[t,n]of s)"!!"===t&&"tag:yaml.org,2002:"===n||e&&!i.some(e=>e.startsWith(n))||r.push(`%TAG ${t} ${n}`);return r.join("\n")}};s.defaultYaml={explicit:!1,version:"1.2"},s.defaultTags={"!!":"tag:yaml.org,2002:"},e.Directives=s}}),g=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/anchors.js"(e){var t=h(),n=m();function anchorIsValid(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const t=JSON.stringify(e),n=`Anchor must not contain whitespace or control characters: ${t}`;throw new Error(n)}return!0}function anchorNames(e){const t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function findNewAnchor(e,t){for(let n=1;;++n){const r=`${e}${n}`;if(!t.has(r))return r}}function createNodeAnchors(e,n){const r=[],s=new Map;let i=null;return{onAnchor:t=>{r.push(t),i??(i=anchorNames(e));const s=findNewAnchor(n,i);return i.add(s),s},setAnchors:()=>{for(const e of r){const n=s.get(e);if("object"!=typeof n||!n.anchor||!t.isScalar(n.node)&&!t.isCollection(n.node)){const t=new Error("Failed to resolve repeated object (this should not happen)");throw t.source=e,t}n.node.anchor=n.anchor}},sourceObjects:s}}e.anchorIsValid=anchorIsValid,e.anchorNames=anchorNames,e.createNodeAnchors=createNodeAnchors,e.findNewAnchor=findNewAnchor}}),y=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/applyReviver.js"(e){function applyReviver(e,t,n,r){if(r&&"object"==typeof r)if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){const n=r[t],s=applyReviver(e,r,String(t),n);void 0===s?delete r[t]:s!==n&&(r[t]=s)}else if(r instanceof Map)for(const t of Array.from(r.keys())){const n=r.get(t),s=applyReviver(e,r,t,n);void 0===s?r.delete(t):s!==n&&r.set(t,s)}else if(r instanceof Set)for(const t of Array.from(r)){const n=applyReviver(e,r,t,t);void 0===n?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(const[t,n]of Object.entries(r)){const s=applyReviver(e,r,t,n);void 0===s?delete r[t]:s!==n&&(r[t]=s)}return e.call(t,n,r)}e.applyReviver=applyReviver}}),v=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/toJS.js"(e){var t=h();function toJS(e,n,r){if(Array.isArray(e))return e.map((e,t)=>toJS(e,String(t),r));if(e&&"function"==typeof e.toJSON){if(!r||!t.hasAnchor(e))return e.toJSON(n,r);const s={aliasCount:0,count:1,res:void 0};r.anchors.set(e,s),r.onCreate=e=>{s.res=e,delete r.onCreate};const i=e.toJSON(n,r);return r.onCreate&&r.onCreate(i),i}return"bigint"!=typeof e||r?.keep?e:Number(e)}e.toJS=toJS}}),E=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Node.js"(e){var t=y(),n=h(),r=v(),s=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:s,maxAliasCount:i,onAnchor:a,reviver:o}={}){if(!n.isDocument(e))throw new TypeError("A document argument is required");const c={anchors:new Map,doc:e,keep:!0,mapAsMap:!0===s,mapKeyWarned:!1,maxAliasCount:"number"==typeof i?i:100},l=r.toJS(this,"",c);if("function"==typeof a)for(const{count:e,res:t}of c.anchors.values())a(t,e);return"function"==typeof o?t.applyReviver(o,{"":l},"",l):l}};e.NodeBase=s}}),T=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Alias.js"(e){var t=g(),n=m(),r=h(),s=E(),i=v(),a=class extends s.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let s,i;t?.aliasResolveCache?s=t.aliasResolveCache:(s=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&s.push(t)}}),t&&(t.aliasResolveCache=s));for(const e of s){if(e===this)break;e.anchor===this.source&&(i=e)}return i}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:r,maxAliasCount:s}=t,a=this.resolve(r,t);if(!a){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(e)}let o=n.get(a);if(o||(i.toJS(a,null,t),o=n.get(a)),void 0===o?.res){const e="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(e)}if(s>=0&&(o.count+=1,0===o.aliasCount&&(o.aliasCount=getAliasCount(r,a,n)),o.count*o.aliasCount>s)){const e="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(e)}return o.res}toString(e,n,r){const s=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(e)}if(e.implicitKey)return`${s} `}return s}};function getAliasCount(e,t,n){if(r.isAlias(t)){const r=t.resolve(e),s=n&&r&&n.get(r);return s?s.count*s.aliasCount:0}if(r.isCollection(t)){let r=0;for(const s of t.items){const t=getAliasCount(e,s,n);t>r&&(r=t)}return r}if(r.isPair(t)){const r=getAliasCount(e,t.key,n),s=getAliasCount(e,t.value,n);return Math.max(r,s)}return 1}e.Alias=a}}),w=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Scalar.js"(e){var t=h(),n=E(),r=v(),isScalarValue=e=>!e||"function"!=typeof e&&"object"!=typeof e,s=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};s.BLOCK_FOLDED="BLOCK_FOLDED",s.BLOCK_LITERAL="BLOCK_LITERAL",s.PLAIN="PLAIN",s.QUOTE_DOUBLE="QUOTE_DOUBLE",s.QUOTE_SINGLE="QUOTE_SINGLE",e.Scalar=s,e.isScalarValue=isScalarValue}}),S=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/createNode.js"(e){var t=T(),n=h(),r=w(),s="tag:yaml.org,2002:";function findTagObject(e,t,n){if(t){const e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw new Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function createNode(e,i,a){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){const t=a.schema[n.MAP].createNode?.(a.schema,null,a);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||"undefined"!=typeof BigInt&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:o,onAnchor:c,onTagObj:l,schema:d,sourceObjects:u}=a;let p;if(o&&e&&"object"==typeof e){if(p=u.get(e),p)return p.anchor??(p.anchor=c(e)),new t.Alias(p.anchor);p={anchor:null,node:null},u.set(e,p)}i?.startsWith("!!")&&(i=s+i.slice(2));let h=findTagObject(e,i,d.tags);if(!h){if(e&&"function"==typeof e.toJSON&&(e=e.toJSON()),!e||"object"!=typeof e){const t=new r.Scalar(e);return p&&(p.node=t),t}h=e instanceof Map?d[n.MAP]:Symbol.iterator in Object(e)?d[n.SEQ]:d[n.MAP]}l&&(l(h),delete a.onTagObj);const m=h?.createNode?h.createNode(a.schema,e,a):"function"==typeof h?.nodeClass?.from?h.nodeClass.from(a.schema,e,a):new r.Scalar(e);return i?m.tag=i:h.default||(m.tag=h.tag),p&&(p.node=m),m}e.createNode=createNode}}),b=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Collection.js"(e){var t=S(),n=h(),r=E();function collectionFromPath(e,n,r){let s=r;for(let e=n.length-1;e>=0;--e){const t=n[e];if("number"==typeof t&&Number.isInteger(t)&&t>=0){const e=[];e[t]=s,s=e}else s=new Map([[t,s]])}return t.createNode(s,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var isEmptyPath=e=>null==e||"object"==typeof e&&!!e[Symbol.iterator]().next().done,s=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(isEmptyPath(e))this.add(t);else{const[r,...s]=e,i=this.get(r,!0);if(n.isCollection(i))i.addIn(s,t);else{if(void 0!==i||!this.schema)throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`);this.set(r,collectionFromPath(this.schema,s,t))}}}deleteIn(e){const[t,...r]=e;if(0===r.length)return this.delete(t);const s=this.get(t,!0);if(n.isCollection(s))return s.deleteIn(r);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){const[r,...s]=e,i=this.get(r,!0);return 0===s.length?!t&&n.isScalar(i)?i.value:i:n.isCollection(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;const r=t.value;return null==r||e&&n.isScalar(r)&&null==r.value&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){const[t,...r]=e;if(0===r.length)return this.has(t);const s=this.get(t,!0);return!!n.isCollection(s)&&s.hasIn(r)}setIn(e,t){const[r,...s]=e;if(0===s.length)this.set(r,t);else{const e=this.get(r,!0);if(n.isCollection(e))e.setIn(s,t);else{if(void 0!==e||!this.schema)throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`);this.set(r,collectionFromPath(this.schema,s,t))}}}};e.Collection=s,e.collectionFromPath=collectionFromPath,e.isEmptyPath=isEmptyPath}}),A=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/stringify/stringifyComment.js"(e){var stringifyComment=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function indentComment(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var lineComment=(e,t,n)=>e.endsWith("\n")?indentComment(n,t):n.includes("\n")?"\n"+indentComment(n,t):(e.endsWith(" ")?"":" ")+n;e.indentComment=indentComment,e.lineComment=lineComment,e.stringifyComment=stringifyComment}}),_=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/stringify/foldFlowLines.js"(e){var t="flow",n="block",r="quoted";function foldFlowLines(e,t,s="flow",{indentAtStart:i,lineWidth:a=80,minContentWidth:o=20,onFold:c,onOverflow:l}={}){if(!a||a<0)return e;a<o&&(o=0);const d=Math.max(1+o,1+a-t.length);if(e.length<=d)return e;const u=[],p={};let h,m,f=a-t.length;"number"==typeof i&&(i>a-Math.max(2,o)?u.push(0):f=a-i);let g=!1,y=-1,v=-1,E=-1;s===n&&(y=consumeMoreIndentedLines(e,y,t.length),-1!==y&&(f=y+d));for(let i;i=e[y+=1];){if(s===r&&"\\"===i){switch(v=y,e[y+1]){case"x":y+=3;break;case"u":y+=5;break;case"U":y+=9;break;default:y+=1}E=y}if("\n"===i)s===n&&(y=consumeMoreIndentedLines(e,y,t.length)),f=y+t.length+d,h=void 0;else{if(" "===i&&m&&" "!==m&&"\n"!==m&&"\t"!==m){const t=e[y+1];t&&" "!==t&&"\n"!==t&&"\t"!==t&&(h=y)}if(y>=f)if(h)u.push(h),f=h+d,h=void 0;else if(s===r){for(;" "===m||"\t"===m;)m=i,i=e[y+=1],g=!0;const t=y>E+1?y-2:v-1;if(p[t])return e;u.push(t),p[t]=!0,f=t+d,h=void 0}else g=!0}m=i}if(g&&l&&l(),0===u.length)return e;c&&c();let T=e.slice(0,u[0]);for(let n=0;n<u.length;++n){const i=u[n],a=u[n+1]||e.length;0===i?T=`\n${t}${e.slice(0,a)}`:(s===r&&p[i]&&(T+=`${e[i]}\\`),T+=`\n${t}${e.slice(i+1,a)}`)}return T}function consumeMoreIndentedLines(e,t,n){let r=t,s=t+1,i=e[s];for(;" "===i||"\t"===i;)if(t<s+n)i=e[++t];else{do{i=e[++t]}while(i&&"\n"!==i);r=t,s=t+1,i=e[s]}return r}e.FOLD_BLOCK=n,e.FOLD_FLOW=t,e.FOLD_QUOTED=r,e.foldFlowLines=foldFlowLines}}),k=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/stringify/stringifyString.js"(e){var t,n=w(),r=_(),getFoldOptions=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),containsDocumentMarker=e=>/^(%|---|\.\.\.)/m.test(e);function lineLengthOverLimit(e,t,n){if(!t||t<0)return!1;const r=t-n,s=e.length;if(s<=r)return!1;for(let t=0,n=0;t<s;++t)if("\n"===e[t]){if(t-n>r)return!0;if(n=t+1,s-n<=r)return!1}return!0}function doubleQuotedString(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:s}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(containsDocumentMarker(e)?" ":"");let o="",c=0;for(let e=0,t=n[e];t;t=n[++e])if(" "===t&&"\\"===n[e+1]&&"n"===n[e+2]&&(o+=n.slice(c,e)+"\\ ",e+=1,c=e,t="\\"),"\\"===t)switch(n[e+1]){case"u":{o+=n.slice(c,e);const t=n.substr(e+2,4);switch(t){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:"00"===t.substr(0,2)?o+="\\x"+t.substr(2):o+=n.substr(e,6)}e+=5,c=e+1}break;case"n":if(s||'"'===n[e+2]||n.length<i)e+=1;else{for(o+=n.slice(c,e)+"\n\n";"\\"===n[e+2]&&"n"===n[e+3]&&'"'!==n[e+4];)o+="\n",e+=2;o+=a," "===n[e+2]&&(o+="\\"),e+=1,c=e+1}break;default:e+=1}return o=c?o+n.slice(c):n,s?o:r.foldFlowLines(o,a,r.FOLD_QUOTED,getFoldOptions(t,!1))}function singleQuotedString(e,t){if(!1===t.options.singleQuote||t.implicitKey&&e.includes("\n")||/[ \t]\n|\n[ \t]/.test(e))return doubleQuotedString(e,t);const n=t.indent||(containsDocumentMarker(e)?" ":""),s="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&\n${n}`)+"'";return t.implicitKey?s:r.foldFlowLines(s,n,r.FOLD_FLOW,getFoldOptions(t,!1))}function quotedString(e,t){const{singleQuote:n}=t.options;let r;if(!1===n)r=doubleQuotedString;else{const t=e.includes('"'),s=e.includes("'");r=t&&!s?singleQuotedString:s&&!t?doubleQuotedString:n?singleQuotedString:doubleQuotedString}return r(e,t)}try{t=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{t=/\n+(?!\n|$)/g}function blockString({comment:e,type:s,value:i},a,o,c){const{blockQuote:l,commentString:d,lineWidth:u}=a.options;if(!l||/\n[\t ]+$/.test(i))return quotedString(i,a);const p=a.indent||(a.forceBlockIndent||containsDocumentMarker(i)?" ":""),h="literal"===l||"folded"!==l&&s!==n.Scalar.BLOCK_FOLDED&&(s===n.Scalar.BLOCK_LITERAL||!lineLengthOverLimit(i,u,p.length));if(!i)return h?"|\n":">\n";let m,f;for(f=i.length;f>0;--f){const e=i[f-1];if("\n"!==e&&"\t"!==e&&" "!==e)break}let g=i.substring(f);const y=g.indexOf("\n");-1===y?m="-":i===g||y!==g.length-1?(m="+",c&&c()):m="",g&&(i=i.slice(0,-g.length),"\n"===g[g.length-1]&&(g=g.slice(0,-1)),g=g.replace(t,`$&${p}`));let v,E=!1,T=-1;for(v=0;v<i.length;++v){const e=i[v];if(" "===e)E=!0;else{if("\n"!==e)break;T=v}}let w=i.substring(0,T<v?T+1:v);w&&(i=i.substring(w.length),w=w.replace(/\n+/g,`$&${p}`));const S=p?"2":"1";let b=(E?S:"")+m;if(e&&(b+=" "+d(e.replace(/ ?[\r\n]+/g," ")),o&&o()),!h){const e=i.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${p}`);let t=!1;const o=getFoldOptions(a,!0);"folded"!==l&&s!==n.Scalar.BLOCK_FOLDED&&(o.onOverflow=()=>{t=!0});const c=r.foldFlowLines(`${w}${e}${g}`,p,r.FOLD_BLOCK,o);if(!t)return`>${b}\n${p}${c}`}return i=i.replace(/\n+/g,`$&${p}`),`|${b}\n${p}${w}${i}${g}`}function plainString(e,t,s,i){const{type:a,value:o}=e,{actualString:c,implicitKey:l,indent:d,indentStep:u,inFlow:p}=t;if(l&&o.includes("\n")||p&&/[[\]{},]/.test(o))return quotedString(o,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return l||p||!o.includes("\n")?quotedString(o,t):blockString(e,t,s,i);if(!l&&!p&&a!==n.Scalar.PLAIN&&o.includes("\n"))return blockString(e,t,s,i);if(containsDocumentMarker(o)){if(""===d)return t.forceBlockIndent=!0,blockString(e,t,s,i);if(l&&d===u)return quotedString(o,t)}const h=o.replace(/\n+/g,`$&\n${d}`);if(c){const test=e=>e.default&&"tag:yaml.org,2002:str"!==e.tag&&e.test?.test(h),{compat:e,tags:n}=t.doc.schema;if(n.some(test)||e?.some(test))return quotedString(o,t)}return l?h:r.foldFlowLines(h,d,r.FOLD_FLOW,getFoldOptions(t,!1))}function stringifyString(e,t,r,s){const{implicitKey:i,inFlow:a}=t,o="string"==typeof e.value?e:Object.assign({},e,{value:String(e.value)});let{type:c}=e;c!==n.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(c=n.Scalar.QUOTE_DOUBLE);const _stringify=e=>{switch(e){case n.Scalar.BLOCK_FOLDED:case n.Scalar.BLOCK_LITERAL:return i||a?quotedString(o.value,t):blockString(o,t,r,s);case n.Scalar.QUOTE_DOUBLE:return doubleQuotedString(o.value,t);case n.Scalar.QUOTE_SINGLE:return singleQuotedString(o.value,t);case n.Scalar.PLAIN:return plainString(o,t,r,s);default:return null}};let l=_stringify(c);if(null===l){const{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=_stringify(r),null===l)throw new Error(`Unsupported default string type ${r}`)}return l}e.stringifyString=stringifyString}}),I=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/stringify/stringify.js"(e){var t=g(),n=h(),r=A(),s=k();function createStringifyContext(e,t){const n=Object.assign({blockQuote:!0,commentString:r.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t);let s;switch(n.collectionStyle){case"block":s=!1;break;case"flow":s=!0;break;default:s=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:"number"==typeof n.indent?" ".repeat(n.indent):" ",inFlow:s,options:n}}function getTagObject(e,t){if(t.tag){const n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let r,s;if(n.isScalar(t)){s=t.value;let n=e.filter(e=>e.identify?.(s));if(n.length>1){const e=n.filter(e=>e.test);e.length>0&&(n=e)}r=n.find(e=>e.format===t.format)??n.find(e=>!e.format)}else s=t,r=e.find(e=>e.nodeClass&&s instanceof e.nodeClass);if(!r){const e=s?.constructor?.name??(null===s?"null":typeof s);throw new Error(`Tag not resolved for ${e} value`)}return r}function stringifyProps(e,r,{anchors:s,doc:i}){if(!i.directives)return"";const a=[],o=(n.isScalar(e)||n.isCollection(e))&&e.anchor;o&&t.anchorIsValid(o)&&(s.add(o),a.push(`&${o}`));const c=e.tag??(r.default?null:r.tag);return c&&a.push(i.directives.tagString(c)),a.join(" ")}function stringify2(e,t,r,i){if(n.isPair(e))return e.toString(t,r,i);if(n.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let a;const o=n.isNode(e)?e:t.doc.createNode(e,{onTagObj:e=>a=e});a??(a=getTagObject(t.doc.schema.tags,o));const c=stringifyProps(o,a,t);c.length>0&&(t.indentAtStart=(t.indentAtStart??0)+c.length+1);const l="function"==typeof a.stringify?a.stringify(o,t,r,i):n.isScalar(o)?s.stringifyString(o,t,r,i):o.toString(t,r,i);return c?n.isScalar(o)||"{"===l[0]||"["===l[0]?`${c} ${l}`:`${c}\n${t.indent}${l}`:l}e.createStringifyContext=createStringifyContext,e.stringify=stringify2}}),C=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/stringify/stringifyPair.js"(e){var t=h(),n=w(),r=I(),s=A();function stringifyPair({key:e,value:i},a,o,c){const{allNullValues:l,doc:d,indent:u,indentStep:p,options:{commentString:h,indentSeq:m,simpleKeys:f}}=a;let g=t.isNode(e)&&e.comment||null;if(f){if(g)throw new Error("With simple keys, key nodes cannot have comments");if(t.isCollection(e)||!t.isNode(e)&&"object"==typeof e){const e="With simple keys, collection cannot be used as a key value";throw new Error(e)}}let y=!f&&(!e||g&&null==i&&!a.inFlow||t.isCollection(e)||(t.isScalar(e)?e.type===n.Scalar.BLOCK_FOLDED||e.type===n.Scalar.BLOCK_LITERAL:"object"==typeof e));a=Object.assign({},a,{allNullValues:!1,implicitKey:!y&&(f||!l),indent:u+p});let v,E,T,w=!1,S=!1,b=r.stringify(e,a,()=>w=!0,()=>S=!0);if(!y&&!a.inFlow&&b.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");y=!0}if(a.inFlow){if(l||null==i)return w&&o&&o(),""===b?"?":y?`? ${b}`:b}else if(l&&!f||null==i&&y)return b=`? ${b}`,g&&!w?b+=s.lineComment(b,a.indent,h(g)):S&&c&&c(),b;w&&(g=null),y?(g&&(b+=s.lineComment(b,a.indent,h(g))),b=`? ${b}\n${u}:`):(b=`${b}:`,g&&(b+=s.lineComment(b,a.indent,h(g)))),t.isNode(i)?(v=!!i.spaceBefore,E=i.commentBefore,T=i.comment):(v=!1,E=null,T=null,i&&"object"==typeof i&&(i=d.createNode(i))),a.implicitKey=!1,y||g||!t.isScalar(i)||(a.indentAtStart=b.length+1),S=!1,m||!(p.length>=2)||a.inFlow||y||!t.isSeq(i)||i.flow||i.tag||i.anchor||(a.indent=a.indent.substring(2));let A=!1;const _=r.stringify(i,a,()=>A=!0,()=>S=!0);let k=" ";if(g||v||E){if(k=v?"\n":"",E){const e=h(E);k+=`\n${s.indentComment(e,a.indent)}`}""!==_||a.inFlow?k+=`\n${a.indent}`:"\n"===k&&T&&(k="\n\n")}else if(!y&&t.isCollection(i)){const e=_[0],t=_.indexOf("\n"),n=-1!==t,r=a.inFlow??i.flow??0===i.items.length;if(n||!r){let r=!1;if(n&&("&"===e||"!"===e)){let n=_.indexOf(" ");"&"===e&&-1!==n&&n<t&&"!"===_[n+1]&&(n=_.indexOf(" ",n+1)),(-1===n||t<n)&&(r=!0)}r||(k=`\n${a.indent}`)}}else""!==_&&"\n"!==_[0]||(k="");return b+=k+_,a.inFlow?A&&o&&o():T&&!A?b+=s.lineComment(b,a.indent,h(T)):S&&c&&c(),b}e.stringifyPair=stringifyPair}}),R=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/log.js"(e){var t=u("process");function debug(e,...t){"debug"===e&&console.log(...t)}function warn(e,n){"debug"!==e&&"warn"!==e||("function"==typeof t.emitWarning?t.emitWarning(n):console.warn(n))}e.debug=debug,e.warn=warn}}),P=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/yaml-1.1/merge.js"(e){var t=h(),n=w(),r="<<",s={identify:e=>e===r||"symbol"==typeof e&&e.description===r,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new n.Scalar(Symbol(r)),{addToJSMap:addMergeToJSMap}),stringify:()=>r},isMergeKey=(e,r)=>(s.identify(r)||t.isScalar(r)&&(!r.type||r.type===n.Scalar.PLAIN)&&s.identify(r.value))&&e?.doc.schema.tags.some(e=>e.tag===s.tag&&e.default);function addMergeToJSMap(e,n,r){if(r=e&&t.isAlias(r)?r.resolve(e.doc):r,t.isSeq(r))for(const t of r.items)mergeValue(e,n,t);else if(Array.isArray(r))for(const t of r)mergeValue(e,n,t);else mergeValue(e,n,r)}function mergeValue(e,n,r){const s=e&&t.isAlias(r)?r.resolve(e.doc):r;if(!t.isMap(s))throw new Error("Merge sources must be maps or map aliases");const i=s.toJSON(null,e,Map);for(const[e,t]of i)n instanceof Map?n.has(e)||n.set(e,t):n instanceof Set?n.add(e):Object.prototype.hasOwnProperty.call(n,e)||Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0});return n}e.addMergeToJSMap=addMergeToJSMap,e.isMergeKey=isMergeKey,e.merge=s}}),N=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/addPairToJSMap.js"(e){var t=R(),n=P(),r=I(),s=h(),i=v();function addPairToJSMap(e,t,{key:r,value:a}){if(s.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,a);else if(n.isMergeKey(e,r))n.addMergeToJSMap(e,t,a);else{const n=i.toJS(r,"",e);if(t instanceof Map)t.set(n,i.toJS(a,n,e));else if(t instanceof Set)t.add(n);else{const s=stringifyKey(r,n,e),o=i.toJS(a,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}function stringifyKey(e,n,i){if(null===n)return"";if("object"!=typeof n)return String(n);if(s.isNode(e)&&i?.doc){const n=r.createStringifyContext(i.doc,{});n.anchors=new Set;for(const e of i.anchors.keys())n.anchors.add(e.anchor);n.inFlow=!0,n.inStringifyKey=!0;const s=e.toString(n);if(!i.mapKeyWarned){let e=JSON.stringify(s);e.length>40&&(e=e.substring(0,36)+'..."'),t.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return s}return JSON.stringify(n)}e.addPairToJSMap=addPairToJSMap}}),O=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Pair.js"(e){var t=S(),n=C(),r=N(),s=h();function createPair(e,n,r){const s=t.createNode(e,void 0,r),a=t.createNode(n,void 0,r);return new i(s,a)}var i=class _Pair{constructor(e,t=null){Object.defineProperty(this,s.NODE_TYPE,{value:s.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return s.isNode(t)&&(t=t.clone(e)),s.isNode(n)&&(n=n.clone(e)),new _Pair(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return r.addPairToJSMap(t,n,this)}toString(e,t,r){return e?.doc?n.stringifyPair(this,e,t,r):JSON.stringify(this)}};e.Pair=i,e.createPair=createPair}}),D=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/stringify/stringifyCollection.js"(e){var t=h(),n=I(),r=A();function stringifyCollection(e,t,n){const r=t.inFlow??e.flow,s=r?stringifyFlowCollection:stringifyBlockCollection;return s(e,t,n)}function stringifyBlockCollection({comment:e,items:s},i,{blockItemPrefix:a,flowChars:o,itemIndent:c,onChompKeep:l,onComment:d}){const{indent:u,options:{commentString:p}}=i,h=Object.assign({},i,{indent:c,type:null});let m=!1;const f=[];for(let e=0;e<s.length;++e){const o=s[e];let l=null;if(t.isNode(o))!m&&o.spaceBefore&&f.push(""),addCommentBefore(i,f,o.commentBefore,m),o.comment&&(l=o.comment);else if(t.isPair(o)){const e=t.isNode(o.key)?o.key:null;e&&(!m&&e.spaceBefore&&f.push(""),addCommentBefore(i,f,e.commentBefore,m))}m=!1;let d=n.stringify(o,h,()=>l=null,()=>m=!0);l&&(d+=r.lineComment(d,c,p(l))),m&&l&&(m=!1),f.push(a+d)}let g;if(0===f.length)g=o.start+o.end;else{g=f[0];for(let e=1;e<f.length;++e){const t=f[e];g+=t?`\n${u}${t}`:"\n"}}return e?(g+="\n"+r.indentComment(p(e),u),d&&d()):m&&l&&l(),g}function stringifyFlowCollection({items:e},s,{flowChars:i,itemIndent:a}){const{indent:o,indentStep:c,flowCollectionPadding:l,options:{commentString:d}}=s;a+=c;const u=Object.assign({},s,{indent:a,inFlow:!0,type:null});let p=!1,h=0;const m=[];for(let i=0;i<e.length;++i){const o=e[i];let c=null;if(t.isNode(o))o.spaceBefore&&m.push(""),addCommentBefore(s,m,o.commentBefore,!1),o.comment&&(c=o.comment);else if(t.isPair(o)){const e=t.isNode(o.key)?o.key:null;e&&(e.spaceBefore&&m.push(""),addCommentBefore(s,m,e.commentBefore,!1),e.comment&&(p=!0));const n=t.isNode(o.value)?o.value:null;n?(n.comment&&(c=n.comment),n.commentBefore&&(p=!0)):null==o.value&&e?.comment&&(c=e.comment)}c&&(p=!0);let l=n.stringify(o,u,()=>c=null);i<e.length-1&&(l+=","),c&&(l+=r.lineComment(l,a,d(c))),!p&&(m.length>h||l.includes("\n"))&&(p=!0),m.push(l),h=m.length}const{start:f,end:g}=i;if(0===m.length)return f+g;if(!p){const e=m.reduce((e,t)=>e+t.length+2,2);p=s.options.lineWidth>0&&e>s.options.lineWidth}if(p){let e=f;for(const t of m)e+=t?`\n${c}${o}${t}`:"\n";return`${e}\n${o}${g}`}return`${f}${l}${m.join(" ")}${l}${g}`}function addCommentBefore({indent:e,options:{commentString:t}},n,s,i){if(s&&i&&(s=s.replace(/^\n+/,"")),s){const i=r.indentComment(t(s),e);n.push(i.trimStart())}}e.stringifyCollection=stringifyCollection}}),L=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/YAMLMap.js"(e){var t=D(),n=N(),r=b(),s=h(),i=O(),a=w();function findPair(e,t){const n=s.isScalar(t)?t.value:t;for(const r of e)if(s.isPair(r)){if(r.key===t||r.key===n)return r;if(s.isScalar(r.key)&&r.key.value===n)return r}}var o=class extends r.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(s.MAP,e),this.items=[]}static from(e,t,n){const{keepUndefined:r,replacer:s}=n,a=new this(e),add=(e,o)=>{if("function"==typeof s)o=s.call(t,e,o);else if(Array.isArray(s)&&!s.includes(e))return;(void 0!==o||r)&&a.items.push(i.createPair(e,o,n))};if(t instanceof Map)for(const[e,n]of t)add(e,n);else if(t&&"object"==typeof t)for(const e of Object.keys(t))add(e,t[e]);return"function"==typeof e.sortMapEntries&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=s.isPair(e)?e:e&&"object"==typeof e&&"key"in e?new i.Pair(e.key,e.value):new i.Pair(e,e?.value);const r=findPair(this.items,n.key),o=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);s.isScalar(r.value)&&a.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(o){const e=this.items.findIndex(e=>o(n,e)<0);-1===e?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){const t=findPair(this.items,e);if(!t)return!1;const n=this.items.splice(this.items.indexOf(t),1);return n.length>0}get(e,t){const n=findPair(this.items,e),r=n?.value;return(!t&&s.isScalar(r)?r.value:r)??void 0}has(e){return!!findPair(this.items,e)}set(e,t){this.add(new i.Pair(e,t),!0)}toJSON(e,t,r){const s=r?new r:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(s);for(const e of this.items)n.addPairToJSMap(t,s,e);return s}toString(e,n,r){if(!e)return JSON.stringify(this);for(const e of this.items)if(!s.isPair(e))throw new Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),t.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:n})}};e.YAMLMap=o,e.findPair=findPair}}),M=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/common/map.js"(e){var t=h(),n=L(),r={collection:"map",default:!0,nodeClass:n.YAMLMap,tag:"tag:yaml.org,2002:map",resolve:(e,n)=>(t.isMap(e)||n("Expected a mapping for this tag"),e),createNode:(e,t,r)=>n.YAMLMap.from(e,t,r)};e.map=r}}),x=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/YAMLSeq.js"(e){var t=S(),n=D(),r=b(),s=h(),i=w(),a=v(),o=class extends r.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(s.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=asItemIndex(e);if("number"!=typeof t)return!1;const n=this.items.splice(t,1);return n.length>0}get(e,t){const n=asItemIndex(e);if("number"!=typeof n)return;const r=this.items[n];return!t&&s.isScalar(r)?r.value:r}has(e){const t=asItemIndex(e);return"number"==typeof t&&t<this.items.length}set(e,t){const n=asItemIndex(e);if("number"!=typeof n)throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];s.isScalar(r)&&i.isScalarValue(t)?r.value=t:this.items[n]=t}toJSON(e,t){const n=[];t?.onCreate&&t.onCreate(n);let r=0;for(const e of this.items)n.push(a.toJS(e,String(r++),t));return n}toString(e,t,r){return e?n.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,n,r){const{replacer:s}=r,i=new this(e);if(n&&Symbol.iterator in Object(n)){let e=0;for(let a of n){if("function"==typeof s){const t=n instanceof Set?a:String(e++);a=s.call(n,t,a)}i.items.push(t.createNode(a,void 0,r))}}return i}};function asItemIndex(e){let t=s.isScalar(e)?e.value:e;return t&&"string"==typeof t&&(t=Number(t)),"number"==typeof t&&Number.isInteger(t)&&t>=0?t:null}e.YAMLSeq=o}}),F=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/common/seq.js"(e){var t=h(),n=x(),r={collection:"seq",default:!0,nodeClass:n.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve:(e,n)=>(t.isSeq(e)||n("Expected a sequence for this tag"),e),createNode:(e,t,r)=>n.YAMLSeq.from(e,t,r)};e.seq=r}}),B=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/common/string.js"(e){var t=k(),n={identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:(e,n,r,s)=>(n=Object.assign({actualString:!0},n),t.stringifyString(e,n,r,s))};e.string=n}}),H=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/common/null.js"(e){var t=w(),n={identify:e=>null==e,createNode:()=>new t.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new t.Scalar(null),stringify:({source:e},t)=>"string"==typeof e&&n.test.test(e)?e:t.options.nullStr};e.nullTag=n}}),U=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/core/bool.js"(e){var t=w(),n={identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new t.Scalar("t"===e[0]||"T"===e[0]),stringify({source:e,value:t},r){if(e&&n.test.test(e)){const n="t"===e[0]||"T"===e[0];if(t===n)return e}return t?r.options.trueStr:r.options.falseStr}};e.boolTag=n}}),j=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/stringify/stringifyNumber.js"(e){function stringifyNumber({format:e,minFractionDigits:t,tag:n,value:r}){if("bigint"==typeof r)return String(r);const s="number"==typeof r?r:Number(r);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let i=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!n||"tag:yaml.org,2002:float"===n)&&/^\d/.test(i)){let e=i.indexOf(".");e<0&&(e=i.length,i+=".");let n=t-(i.length-e-1);for(;n-- >0;)i+="0"}return i}e.stringifyNumber=stringifyNumber}}),$=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/core/float.js"(e){var t=w(),n=j(),r={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>"nan"===e.slice(-3).toLowerCase()?NaN:"-"===e[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:n.stringifyNumber},s={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){const t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},i={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){const n=new t.Scalar(parseFloat(e)),r=e.indexOf(".");return-1!==r&&"0"===e[e.length-1]&&(n.minFractionDigits=e.length-r-1),n},stringify:n.stringifyNumber};e.float=i,e.floatExp=s,e.floatNaN=r}}),G=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/core/int.js"(e){var t=j(),intIdentify=e=>"bigint"==typeof e||Number.isInteger(e),intResolve=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function intStringify(e,n,r){const{value:s}=e;return intIdentify(s)&&s>=0?r+s.toString(n):t.stringifyNumber(e)}var n={identify:e=>intIdentify(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>intResolve(e,2,8,n),stringify:e=>intStringify(e,8,"0o")},r={identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>intResolve(e,0,10,n),stringify:t.stringifyNumber},s={identify:e=>intIdentify(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>intResolve(e,2,16,n),stringify:e=>intStringify(e,16,"0x")};e.int=r,e.intHex=s,e.intOct=n}}),q=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/core/schema.js"(e){var t=M(),n=H(),r=F(),s=B(),i=U(),a=$(),o=G(),c=[t.map,r.seq,s.string,n.nullTag,i.boolTag,o.intOct,o.int,o.intHex,a.floatNaN,a.floatExp,a.float];e.schema=c}}),W=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/json/schema.js"(e){var t=w(),n=M(),r=F();function intIdentify(e){return"bigint"==typeof e||Number.isInteger(e)}var stringifyJSON=({value:e})=>JSON.stringify(e),s=[{identify:e=>"string"==typeof e,default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:stringifyJSON},{identify:e=>null==e,createNode:()=>new t.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:stringifyJSON},{identify:e=>"boolean"==typeof e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>"true"===e,stringify:stringifyJSON},{identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>intIdentify(e)?e.toString():JSON.stringify(e)},{identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:stringifyJSON}],i={default:!0,tag:"",test:/^/,resolve:(e,t)=>(t(`Unresolved plain scalar ${JSON.stringify(e)}`),e)},a=[n.map,r.seq].concat(s,i);e.schema=a}}),V=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/yaml-1.1/binary.js"(e){var t=u("buffer"),n=w(),r=k(),s={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,n){if("function"==typeof t.Buffer)return t.Buffer.from(e,"base64");if("function"==typeof atob){const t=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return n("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:s,value:i},a,o,c){if(!i)return"";const l=i;let d;if("function"==typeof t.Buffer)d=l instanceof t.Buffer?l.toString("base64"):t.Buffer.from(l.buffer).toString("base64");else{if("function"!=typeof btoa)throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");{let e="";for(let t=0;t<l.length;++t)e+=String.fromCharCode(l[t]);d=btoa(e)}}if(s??(s=n.Scalar.BLOCK_LITERAL),s!==n.Scalar.QUOTE_DOUBLE){const e=Math.max(a.options.lineWidth-a.indent.length,a.options.minContentWidth),t=Math.ceil(d.length/e),r=new Array(t);for(let n=0,s=0;n<t;++n,s+=e)r[n]=d.substr(s,e);d=r.join(s===n.Scalar.BLOCK_LITERAL?"\n":" ")}return r.stringifyString({comment:e,type:s,value:d},a,o,c)}};e.binary=s}}),K=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/yaml-1.1/pairs.js"(e){var t=h(),n=O(),r=w(),s=x();function resolvePairs(e,s){if(t.isSeq(e))for(let i=0;i<e.items.length;++i){let a=e.items[i];if(!t.isPair(a)){if(t.isMap(a)){a.items.length>1&&s("Each pair must have its own sequence indicator");const e=a.items[0]||new n.Pair(new r.Scalar(null));if(a.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${a.commentBefore}\n${e.key.commentBefore}`:a.commentBefore),a.comment){const t=e.value??e.key;t.comment=t.comment?`${a.comment}\n${t.comment}`:a.comment}a=e}e.items[i]=t.isPair(a)?a:new n.Pair(a)}}else s("Expected a sequence for this tag");return e}function createPairs(e,t,r){const{replacer:i}=r,a=new s.YAMLSeq(e);a.tag="tag:yaml.org,2002:pairs";let o=0;if(t&&Symbol.iterator in Object(t))for(let e of t){let s,c;if("function"==typeof i&&(e=i.call(t,String(o++),e)),Array.isArray(e)){if(2!==e.length)throw new TypeError(`Expected [key, value] tuple: ${e}`);s=e[0],c=e[1]}else if(e&&e instanceof Object){const t=Object.keys(e);if(1!==t.length)throw new TypeError(`Expected tuple with one key, not ${t.length} keys`);s=t[0],c=e[s]}else s=e;a.items.push(n.createPair(s,c,r))}return a}var i={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:resolvePairs,createNode:createPairs};e.createPairs=createPairs,e.pairs=i,e.resolvePairs=resolvePairs}}),Y=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/yaml-1.1/omap.js"(e){var t=h(),n=v(),r=L(),s=x(),i=K(),a=class _YAMLOMap extends s.YAMLSeq{constructor(){super(),this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=_YAMLOMap.tag}toJSON(e,r){if(!r)return super.toJSON(e);const s=new Map;r?.onCreate&&r.onCreate(s);for(const e of this.items){let i,a;if(t.isPair(e)?(i=n.toJS(e.key,"",r),a=n.toJS(e.value,i,r)):i=n.toJS(e,"",r),s.has(i))throw new Error("Ordered maps must not include duplicate keys");s.set(i,a)}return s}static from(e,t,n){const r=i.createPairs(e,t,n),s=new this;return s.items=r.items,s}};a.tag="tag:yaml.org,2002:omap";var o={collection:"seq",identify:e=>e instanceof Map,nodeClass:a,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,n){const r=i.resolvePairs(e,n),s=[];for(const{key:e}of r.items)t.isScalar(e)&&(s.includes(e.value)?n(`Ordered maps must not include duplicate keys: ${e.value}`):s.push(e.value));return Object.assign(new a,r)},createNode:(e,t,n)=>a.from(e,t,n)};e.YAMLOMap=a,e.omap=o}}),z=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/yaml-1.1/bool.js"(e){var t=w();function boolStringify({value:e,source:t},s){const i=e?n:r;return t&&i.test.test(t)?t:e?s.options.trueStr:s.options.falseStr}var n={identify:e=>!0===e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new t.Scalar(!0),stringify:boolStringify},r={identify:e=>!1===e,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new t.Scalar(!1),stringify:boolStringify};e.falseTag=r,e.trueTag=n}}),J=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/yaml-1.1/float.js"(e){var t=w(),n=j(),r={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>"nan"===e.slice(-3).toLowerCase()?NaN:"-"===e[0]?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:n.stringifyNumber},s={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){const t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},i={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){const n=new t.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(-1!==r){const t=e.substring(r+1).replace(/_/g,"");"0"===t[t.length-1]&&(n.minFractionDigits=t.length)}return n},stringify:n.stringifyNumber};e.float=i,e.floatExp=s,e.floatNaN=r}}),Q=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/yaml-1.1/int.js"(e){var t=j(),intIdentify=e=>"bigint"==typeof e||Number.isInteger(e);function intResolve(e,t,n,{intAsBigInt:r}){const s=e[0];if("-"!==s&&"+"!==s||(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}const t=BigInt(e);return"-"===s?BigInt(-1)*t:t}const i=parseInt(e,n);return"-"===s?-1*i:i}function intStringify(e,n,r){const{value:s}=e;if(intIdentify(s)){const e=s.toString(n);return s<0?"-"+r+e.substr(1):r+e}return t.stringifyNumber(e)}var n={identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>intResolve(e,2,2,n),stringify:e=>intStringify(e,2,"0b")},r={identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>intResolve(e,1,8,n),stringify:e=>intStringify(e,8,"0")},s={identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>intResolve(e,0,10,n),stringify:t.stringifyNumber},i={identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>intResolve(e,2,16,n),stringify:e=>intStringify(e,16,"0x")};e.int=s,e.intBin=n,e.intHex=i,e.intOct=r}}),X=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/yaml-1.1/set.js"(e){var t=h(),n=O(),r=L(),s=class _YAMLSet extends r.YAMLMap{constructor(e){super(e),this.tag=_YAMLSet.tag}add(e){let s;s=t.isPair(e)?e:e&&"object"==typeof e&&"key"in e&&"value"in e&&null===e.value?new n.Pair(e.key,null):new n.Pair(e,null);const i=r.findPair(this.items,s.key);i||this.items.push(s)}get(e,n){const s=r.findPair(this.items,e);return!n&&t.isPair(s)?t.isScalar(s.key)?s.key.value:s.key:s}set(e,t){if("boolean"!=typeof t)throw new Error("Expected boolean value for set(key, value) in a YAML set, not "+typeof t);const s=r.findPair(this.items,e);s&&!t?this.items.splice(this.items.indexOf(s),1):!s&&t&&this.items.push(new n.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,r){const{replacer:s}=r,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)"function"==typeof s&&(e=s.call(t,e,e)),i.items.push(n.createPair(e,null,r));return i}};s.tag="tag:yaml.org,2002:set";var i={collection:"map",identify:e=>e instanceof Set,nodeClass:s,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>s.from(e,t,n),resolve(e,n){if(t.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new s,e);n("Set items must all have null values")}else n("Expected a mapping for this tag");return e}};e.YAMLSet=s,e.set=i}}),Z=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js"(e){var t=j();function parseSexagesimal(e,t){const n=e[0],r="-"===n||"+"===n?e.substring(1):e,num=e=>t?BigInt(e):Number(e),s=r.replace(/_/g,"").split(":").reduce((e,t)=>e*num(60)+num(t),num(0));return"-"===n?num(-1)*s:s}function stringifySexagesimal(e){let{value:n}=e,num=e=>e;if("bigint"==typeof n)num=e=>BigInt(e);else if(isNaN(n)||!isFinite(n))return t.stringifyNumber(e);let r="";n<0&&(r="-",n*=num(-1));const s=num(60),i=[n%s];return n<60?i.unshift(0):(n=(n-i[0])/s,i.unshift(n%s),n>=60&&(n=(n-i[0])/s,i.unshift(n))),r+i.map(e=>String(e).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var n={identify:e=>"bigint"==typeof e||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>parseSexagesimal(e,n),stringify:stringifySexagesimal},r={identify:e=>"number"==typeof e,default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>parseSexagesimal(e,!1),stringify:stringifySexagesimal},s={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){const t=e.match(s.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,n,r,i,a,o,c]=t.map(Number),l=t[7]?Number((t[7]+"00").substr(1,3)):0;let d=Date.UTC(n,r-1,i,a||0,o||0,c||0,l);const u=t[8];if(u&&"Z"!==u){let e=parseSexagesimal(u,!1);Math.abs(e)<30&&(e*=60),d-=6e4*e}return new Date(d)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};e.floatTime=r,e.intTime=n,e.timestamp=s}}),ee=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/yaml-1.1/schema.js"(e){var t=M(),n=H(),r=F(),s=B(),i=V(),a=z(),o=J(),c=Q(),l=P(),d=Y(),u=K(),p=X(),h=Z(),m=[t.map,r.seq,s.string,n.nullTag,a.trueTag,a.falseTag,c.intBin,c.intOct,c.int,c.intHex,o.floatNaN,o.floatExp,o.float,i.binary,l.merge,d.omap,u.pairs,p.set,h.intTime,h.floatTime,h.timestamp];e.schema=m}}),te=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/tags.js"(e){var t=M(),n=H(),r=F(),s=B(),i=U(),a=$(),o=G(),c=q(),l=W(),d=V(),u=P(),p=Y(),h=K(),m=ee(),f=X(),g=Z(),y=new Map([["core",c.schema],["failsafe",[t.map,r.seq,s.string]],["json",l.schema],["yaml11",m.schema],["yaml-1.1",m.schema]]),v={binary:d.binary,bool:i.boolTag,float:a.float,floatExp:a.floatExp,floatNaN:a.floatNaN,floatTime:g.floatTime,int:o.int,intHex:o.intHex,intOct:o.intOct,intTime:g.intTime,map:t.map,merge:u.merge,null:n.nullTag,omap:p.omap,pairs:h.pairs,seq:r.seq,set:f.set,timestamp:g.timestamp},E={"tag:yaml.org,2002:binary":d.binary,"tag:yaml.org,2002:merge":u.merge,"tag:yaml.org,2002:omap":p.omap,"tag:yaml.org,2002:pairs":h.pairs,"tag:yaml.org,2002:set":f.set,"tag:yaml.org,2002:timestamp":g.timestamp};function getTags(e,t,n){const r=y.get(t);if(r&&!e)return n&&!r.includes(u.merge)?r.concat(u.merge):r.slice();let s=r;if(!s){if(!Array.isArray(e)){const e=Array.from(y.keys()).filter(e=>"yaml11"!==e).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}s=[]}if(Array.isArray(e))for(const t of e)s=s.concat(t);else"function"==typeof e&&(s=e(s.slice()));return n&&(s=s.concat(u.merge)),s.reduce((e,t)=>{const n="string"==typeof t?v[t]:t;if(!n){const e=JSON.stringify(t),n=Object.keys(v).map(e=>JSON.stringify(e)).join(", ");throw new Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}e.coreKnownTags=E,e.getTags=getTags}}),ne=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/schema/Schema.js"(e){var t=h(),n=M(),r=F(),s=B(),i=te(),sortMapEntriesByKey=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,a=class _Schema{constructor({compat:e,customTags:a,merge:o,resolveKnownTags:c,schema:l,sortMapEntries:d,toStringDefaults:u}){this.compat=Array.isArray(e)?i.getTags(e,"compat"):e?i.getTags(null,e):null,this.name="string"==typeof l&&l||"core",this.knownTags=c?i.coreKnownTags:{},this.tags=i.getTags(a,this.name,o),this.toStringOptions=u??null,Object.defineProperty(this,t.MAP,{value:n.map}),Object.defineProperty(this,t.SCALAR,{value:s.string}),Object.defineProperty(this,t.SEQ,{value:r.seq}),this.sortMapEntries="function"==typeof d?d:!0===d?sortMapEntriesByKey:null}clone(){const e=Object.create(_Schema.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};e.Schema=a}}),re=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/stringify/stringifyDocument.js"(e){var t=h(),n=I(),r=A();function stringifyDocument(e,s){const i=[];let a=!0===s.directives;if(!1!==s.directives&&e.directives){const t=e.directives.toString(e);t?(i.push(t),a=!0):e.directives.docStart&&(a=!0)}a&&i.push("---");const o=n.createStringifyContext(e,s),{commentString:c}=o.options;if(e.commentBefore){1!==i.length&&i.unshift("");const t=c(e.commentBefore);i.unshift(r.indentComment(t,""))}let l=!1,d=null;if(e.contents){if(t.isNode(e.contents)){if(e.contents.spaceBefore&&a&&i.push(""),e.contents.commentBefore){const t=c(e.contents.commentBefore);i.push(r.indentComment(t,""))}o.forceBlockIndent=!!e.comment,d=e.contents.comment}const s=d?void 0:()=>l=!0;let u=n.stringify(e.contents,o,()=>d=null,s);d&&(u+=r.lineComment(u,"",c(d))),"|"!==u[0]&&">"!==u[0]||"---"!==i[i.length-1]?i.push(u):i[i.length-1]=`--- ${u}`}else i.push(n.stringify(e.contents,o));if(e.directives?.docEnd)if(e.comment){const t=c(e.comment);t.includes("\n")?(i.push("..."),i.push(r.indentComment(t,""))):i.push(`... ${t}`)}else i.push("...");else{let t=e.comment;t&&l&&(t=t.replace(/^\n+/,"")),t&&(l&&!d||""===i[i.length-1]||i.push(""),i.push(r.indentComment(c(t),"")))}return i.join("\n")+"\n"}e.stringifyDocument=stringifyDocument}}),se=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/Document.js"(e){var t=T(),n=b(),r=h(),s=O(),i=v(),a=ne(),o=re(),c=g(),l=y(),d=S(),u=f(),p=class _Document{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let s=null;"function"==typeof t||Array.isArray(t)?s=t:void 0===n&&t&&(n=t,t=void 0);const i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:a}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new u.Directives({version:a}),this.setSchema(a,n),this.contents=void 0===e?null:this.createNode(e,s,n)}clone(){const e=Object.create(_Document.prototype,{[r.NODE_TYPE]:{value:r.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=r.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){assertCollection(this.contents)&&this.contents.add(e)}addIn(e,t){assertCollection(this.contents)&&this.contents.addIn(e,t)}createAlias(e,n){if(!e.anchor){const t=c.anchorNames(this);e.anchor=!n||t.has(n)?c.findNewAnchor(n||"a",t):n}return new t.Alias(e.anchor)}createNode(e,t,n){let s;if("function"==typeof t)e=t.call({"":e},"",e),s=t;else if(Array.isArray(t)){const keyToStr=e=>"number"==typeof e||e instanceof String||e instanceof Number,e=t.filter(keyToStr).map(String);e.length>0&&(t=t.concat(e)),s=t}else void 0===n&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:i,anchorPrefix:a,flow:o,keepUndefined:l,onTagObj:u,tag:p}=n??{},{onAnchor:h,setAnchors:m,sourceObjects:f}=c.createNodeAnchors(this,a||"a"),g={aliasDuplicateObjects:i??!0,keepUndefined:l??!1,onAnchor:h,onTagObj:u,replacer:s,schema:this.schema,sourceObjects:f},y=d.createNode(e,p,g);return o&&r.isCollection(y)&&(y.flow=!0),m(),y}createPair(e,t,n={}){const r=this.createNode(e,null,n),i=this.createNode(t,null,n);return new s.Pair(r,i)}delete(e){return!!assertCollection(this.contents)&&this.contents.delete(e)}deleteIn(e){return n.isEmptyPath(e)?null!=this.contents&&(this.contents=null,!0):!!assertCollection(this.contents)&&this.contents.deleteIn(e)}get(e,t){return r.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return n.isEmptyPath(e)?!t&&r.isScalar(this.contents)?this.contents.value:this.contents:r.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return!!r.isCollection(this.contents)&&this.contents.has(e)}hasIn(e){return n.isEmptyPath(e)?void 0!==this.contents:!!r.isCollection(this.contents)&&this.contents.hasIn(e)}set(e,t){null==this.contents?this.contents=n.collectionFromPath(this.schema,[e],t):assertCollection(this.contents)&&this.contents.set(e,t)}setIn(e,t){n.isEmptyPath(e)?this.contents=t:null==this.contents?this.contents=n.collectionFromPath(this.schema,Array.from(e),t):assertCollection(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){let n;switch("number"==typeof e&&(e=String(e)),e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new u.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new u.Directives({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{const t=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else{if(!n)throw new Error("With a null YAML version, the { schema: Schema } option is required");this.schema=new a.Schema(Object.assign(n,t))}}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:s,reviver:a}={}){const o={anchors:new Map,doc:this,keep:!e,mapAsMap:!0===n,mapKeyWarned:!1,maxAliasCount:"number"==typeof r?r:100},c=i.toJS(this.contents,t??"",o);if("function"==typeof s)for(const{count:e,res:t}of o.anchors.values())s(t,e);return"function"==typeof a?l.applyReviver(a,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return o.stringifyDocument(this,e)}};function assertCollection(e){if(r.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}e.Document=p}}),ie=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/errors.js"(e){var t=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},n=class extends t{constructor(e,t,n){super("YAMLParseError",e,t,n)}},r=class extends t{constructor(e,t,n){super("YAMLWarning",e,t,n)}},prettifyError=(e,t)=>n=>{if(-1===n.pos[0])return;n.linePos=n.pos.map(e=>t.linePos(e));const{line:r,col:s}=n.linePos[0];n.message+=` at line ${r}, column ${s}`;let i=s-1,a=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(i>=60&&a.length>80){const e=Math.min(i-39,a.length-79);a="…"+a.substring(e),i-=e-1}if(a.length>80&&(a=a.substring(0,79)+"…"),r>1&&/^ *$/.test(a.substring(0,i))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+"…\n"),a=n+a}if(/[^ ]/.test(a)){let e=1;const t=n.linePos[1];t?.line===r&&t.col>s&&(e=Math.max(1,Math.min(t.col-s,80-i)));const o=" ".repeat(i)+"^".repeat(e);n.message+=`:\n\n${a}\n${o}\n`}};e.YAMLError=t,e.YAMLParseError=n,e.YAMLWarning=r,e.prettifyError=prettifyError}}),ae=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/resolve-props.js"(e){function resolveProps(e,{flow:t,indicator:n,next:r,offset:s,onError:i,parentIndent:a,startOnNewline:o}){let c=!1,l=o,d=o,u="",p="",h=!1,m=!1,f=null,g=null,y=null,v=null,E=null,T=null,w=null;for(const s of e)switch(m&&("space"!==s.type&&"newline"!==s.type&&"comma"!==s.type&&i(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),f&&(l&&"comment"!==s.type&&"newline"!==s.type&&i(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),f=null),s.type){case"space":t||"doc-start"===n&&"flow-collection"===r?.type||!s.source.includes("\t")||(f=s),d=!0;break;case"comment":{d||i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const e=s.source.substring(1)||" ";u?u+=p+e:u=e,p="",l=!1;break}case"newline":l?u?u+=s.source:T&&"seq-item-ind"===n||(c=!0):p+=s.source,l=!0,h=!0,(g||y)&&(v=s),d=!0;break;case"anchor":g&&i(s,"MULTIPLE_ANCHORS","A node can have at most one anchor"),s.source.endsWith(":")&&i(s.offset+s.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=s,w??(w=s.offset),l=!1,d=!1,m=!0;break;case"tag":y&&i(s,"MULTIPLE_TAGS","A node can have at most one tag"),y=s,w??(w=s.offset),l=!1,d=!1,m=!0;break;case n:(g||y)&&i(s,"BAD_PROP_ORDER",`Anchors and tags must be after the ${s.source} indicator`),T&&i(s,"UNEXPECTED_TOKEN",`Unexpected ${s.source} in ${t??"collection"}`),T=s,l="seq-item-ind"===n||"explicit-key-ind"===n,d=!1;break;case"comma":if(t){E&&i(s,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),E=s,l=!1,d=!1;break}default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${s.type} token`),l=!1,d=!1}const S=e[e.length-1],b=S?S.offset+S.source.length:s;return m&&r&&"space"!==r.type&&"newline"!==r.type&&"comma"!==r.type&&("scalar"!==r.type||""!==r.source)&&i(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f&&(l&&f.indent<=a||"block-map"===r?.type||"block-seq"===r?.type)&&i(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:E,found:T,spaceBefore:c,comment:u,hasNewline:h,anchor:g,tag:y,newlineAfterProp:v,end:b,start:w??b}}e.resolveProps=resolveProps}}),oe=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/util-contains-newline.js"(e){function containsNewline(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes("\n"))return!0;if(e.end)for(const t of e.end)if("newline"===t.type)return!0;return!1;case"flow-collection":for(const t of e.items){for(const e of t.start)if("newline"===e.type)return!0;if(t.sep)for(const e of t.sep)if("newline"===e.type)return!0;if(containsNewline(t.key)||containsNewline(t.value))return!0}return!1;default:return!0}}e.containsNewline=containsNewline}}),ce=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/util-flow-indent-check.js"(e){var t=oe();function flowIndentCheck(e,n,r){if("flow-collection"===n?.type){const s=n.end[0];if(s.indent===e&&("]"===s.source||"}"===s.source)&&t.containsNewline(n)){const e="Flow end indicator should be more indented than parent";r(s,"BAD_INDENT",e,!0)}}}e.flowIndentCheck=flowIndentCheck}}),le=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/util-map-includes.js"(e){var t=h();function mapIncludes(e,n,r){const{uniqueKeys:s}=e.options;if(!1===s)return!1;const i="function"==typeof s?s:(e,n)=>e===n||t.isScalar(e)&&t.isScalar(n)&&e.value===n.value;return n.some(e=>i(e.key,r))}e.mapIncludes=mapIncludes}}),de=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/resolve-block-map.js"(e){var t=O(),n=L(),r=ae(),s=oe(),i=ce(),a=le(),o="All mapping items must start at the same column";function resolveBlockMap({composeNode:e,composeEmptyNode:c},l,d,u,p){const h=p?.nodeClass??n.YAMLMap,m=new h(l.schema);l.atRoot&&(l.atRoot=!1);let f=d.offset,g=null;for(const n of d.items){const{start:p,key:h,sep:y,value:v}=n,E=r.resolveProps(p,{indicator:"explicit-key-ind",next:h??y?.[0],offset:f,onError:u,parentIndent:d.indent,startOnNewline:!0}),T=!E.found;if(T){if(h&&("block-seq"===h.type?u(f,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==d.indent&&u(f,"BAD_INDENT",o)),!E.anchor&&!E.tag&&!y){g=E.end,E.comment&&(m.comment?m.comment+="\n"+E.comment:m.comment=E.comment);continue}(E.newlineAfterProp||s.containsNewline(h))&&u(h??p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else E.found?.indent!==d.indent&&u(f,"BAD_INDENT",o);l.atKey=!0;const w=E.end,S=h?e(l,h,E,u):c(l,w,p,null,E,u);l.schema.compat&&i.flowIndentCheck(d.indent,h,u),l.atKey=!1,a.mapIncludes(l,m.items,S)&&u(w,"DUPLICATE_KEY","Map keys must be unique");const b=r.resolveProps(y??[],{indicator:"map-value-ind",next:v,offset:S.range[2],onError:u,parentIndent:d.indent,startOnNewline:!h||"block-scalar"===h.type});if(f=b.end,b.found){T&&("block-map"!==v?.type||b.hasNewline||u(f,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),l.options.strict&&E.start<b.found.offset-1024&&u(S.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const r=v?e(l,v,b,u):c(l,f,y,null,b,u);l.schema.compat&&i.flowIndentCheck(d.indent,v,u),f=r.range[2];const s=new t.Pair(S,r);l.options.keepSourceTokens&&(s.srcToken=n),m.items.push(s)}else{T&&u(S.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),b.comment&&(S.comment?S.comment+="\n"+b.comment:S.comment=b.comment);const e=new t.Pair(S);l.options.keepSourceTokens&&(e.srcToken=n),m.items.push(e)}}return g&&g<f&&u(g,"IMPOSSIBLE","Map comment with trailing content"),m.range=[d.offset,f,g??f],m}e.resolveBlockMap=resolveBlockMap}}),ue=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/resolve-block-seq.js"(e){var t=x(),n=ae(),r=ce();function resolveBlockSeq({composeNode:e,composeEmptyNode:s},i,a,o,c){const l=c?.nodeClass??t.YAMLSeq,d=new l(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let u=a.offset,p=null;for(const{start:t,value:c}of a.items){const l=n.resolveProps(t,{indicator:"seq-item-ind",next:c,offset:u,onError:o,parentIndent:a.indent,startOnNewline:!0});if(!l.found){if(!(l.anchor||l.tag||c)){p=l.end,l.comment&&(d.comment=l.comment);continue}"block-seq"===c?.type?o(l.end,"BAD_INDENT","All sequence items must start at the same column"):o(u,"MISSING_CHAR","Sequence item without - indicator")}const h=c?e(i,c,l,o):s(i,l.end,t,null,l,o);i.schema.compat&&r.flowIndentCheck(a.indent,c,o),u=h.range[2],d.items.push(h)}return d.range=[a.offset,u,p??u],d}e.resolveBlockSeq=resolveBlockSeq}}),pe=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/resolve-end.js"(e){function resolveEnd(e,t,n,r){let s="";if(e){let i=!1,a="";for(const o of e){const{source:e,type:c}=o;switch(c){case"space":i=!0;break;case"comment":{n&&!i&&r(o,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const t=e.substring(1)||" ";s?s+=a+t:s=t,a="";break}case"newline":s&&(a+=e),i=!0;break;default:r(o,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=e.length}}return{comment:s,offset:t}}e.resolveEnd=resolveEnd}}),he=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/resolve-flow-collection.js"(e){var t=h(),n=O(),r=L(),s=x(),i=pe(),a=ae(),o=oe(),c=le(),l="Block collections are not allowed within flow collections",isBlock=e=>e&&("block-map"===e.type||"block-seq"===e.type);function resolveFlowCollection({composeNode:e,composeEmptyNode:d},u,p,h,m){const f="{"===p.start.source,g=f?"flow map":"flow sequence",y=m?.nodeClass??(f?r.YAMLMap:s.YAMLSeq),v=new y(u.schema);v.flow=!0;const E=u.atRoot;E&&(u.atRoot=!1),u.atKey&&(u.atKey=!1);let T=p.offset+p.start.source.length;for(let s=0;s<p.items.length;++s){const i=p.items[s],{start:m,key:y,sep:E,value:w}=i,S=a.resolveProps(m,{flow:g,indicator:"explicit-key-ind",next:y??E?.[0],offset:T,onError:h,parentIndent:p.indent,startOnNewline:!1});if(!S.found){if(!(S.anchor||S.tag||E||w)){0===s&&S.comma?h(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${g}`):s<p.items.length-1&&h(S.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${g}`),S.comment&&(v.comment?v.comment+="\n"+S.comment:v.comment=S.comment),T=S.end;continue}!f&&u.options.strict&&o.containsNewline(y)&&h(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(0===s)S.comma&&h(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${g}`);else if(S.comma||h(S.start,"MISSING_CHAR",`Missing , between ${g} items`),S.comment){let e="";e:for(const t of m)switch(t.type){case"comma":case"space":break;case"comment":e=t.source.substring(1);break e;default:break e}if(e){let n=v.items[v.items.length-1];t.isPair(n)&&(n=n.value??n.key),n.comment?n.comment+="\n"+e:n.comment=e,S.comment=S.comment.substring(e.length+1)}}if(f||E||S.found){u.atKey=!0;const t=S.end,s=y?e(u,y,S,h):d(u,t,m,null,S,h);isBlock(y)&&h(s.range,"BLOCK_IN_FLOW",l),u.atKey=!1;const o=a.resolveProps(E??[],{flow:g,indicator:"map-value-ind",next:w,offset:s.range[2],onError:h,parentIndent:p.indent,startOnNewline:!1});if(o.found){if(!f&&!S.found&&u.options.strict){if(E)for(const e of E){if(e===o.found)break;if("newline"===e.type){h(e,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}S.start<o.found.offset-1024&&h(o.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else w&&("source"in w&&":"===w.source?.[0]?h(w,"MISSING_CHAR",`Missing space after : in ${g}`):h(o.start,"MISSING_CHAR",`Missing , or : between ${g} items`));const b=w?e(u,w,o,h):o.found?d(u,o.end,E,null,o,h):null;b?isBlock(w)&&h(b.range,"BLOCK_IN_FLOW",l):o.comment&&(s.comment?s.comment+="\n"+o.comment:s.comment=o.comment);const A=new n.Pair(s,b);if(u.options.keepSourceTokens&&(A.srcToken=i),f){const e=v;c.mapIncludes(u,e.items,s)&&h(t,"DUPLICATE_KEY","Map keys must be unique"),e.items.push(A)}else{const e=new r.YAMLMap(u.schema);e.flow=!0,e.items.push(A);const t=(b??s).range;e.range=[s.range[0],t[1],t[2]],v.items.push(e)}T=b?b.range[2]:o.end}else{const t=w?e(u,w,S,h):d(u,S.end,E,null,S,h);v.items.push(t),T=t.range[2],isBlock(w)&&h(t.range,"BLOCK_IN_FLOW",l)}}const w=f?"}":"]",[S,...b]=p.end;let A=T;if(S?.source===w)A=S.offset+S.source.length;else{const e=g[0].toUpperCase()+g.substring(1),t=E?`${e} must end with a ${w}`:`${e} in block collection must be sufficiently indented and end with a ${w}`;h(T,E?"MISSING_CHAR":"BAD_INDENT",t),S&&1!==S.source.length&&b.unshift(S)}if(b.length>0){const e=i.resolveEnd(b,A,u.options.strict,h);e.comment&&(v.comment?v.comment+="\n"+e.comment:v.comment=e.comment),v.range=[p.offset,A,e.offset]}else v.range=[p.offset,A,A];return v}e.resolveFlowCollection=resolveFlowCollection}}),me=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/compose-collection.js"(e){var t=h(),n=w(),r=L(),s=x(),i=de(),a=ue(),o=he();function resolveCollection(e,t,n,r,s,c){const l="block-map"===n.type?i.resolveBlockMap(e,t,n,r,c):"block-seq"===n.type?a.resolveBlockSeq(e,t,n,r,c):o.resolveFlowCollection(e,t,n,r,c),d=l.constructor;return"!"===s||s===d.tagName?(l.tag=d.tagName,l):(s&&(l.tag=s),l)}function composeCollection(e,i,a,o,c){const l=o.tag,d=l?i.directives.tagName(l.source,e=>c(l,"TAG_RESOLVE_FAILED",e)):null;if("block-seq"===a.type){const{anchor:e,newlineAfterProp:t}=o,n=e&&l?e.offset>l.offset?e:l:e??l;if(n&&(!t||t.offset<n.offset)){const e="Missing newline after block sequence props";c(n,"MISSING_CHAR",e)}}const u="block-map"===a.type?"map":"block-seq"===a.type?"seq":"{"===a.start.source?"map":"seq";if(!l||!d||"!"===d||d===r.YAMLMap.tagName&&"map"===u||d===s.YAMLSeq.tagName&&"seq"===u)return resolveCollection(e,i,a,c,d);let p=i.schema.tags.find(e=>e.tag===d&&e.collection===u);if(!p){const t=i.schema.knownTags[d];if(t?.collection!==u)return t?c(l,"BAD_COLLECTION_TYPE",`${t.tag} used for ${u} collection, but expects ${t.collection??"scalar"}`,!0):c(l,"TAG_RESOLVE_FAILED",`Unresolved tag: ${d}`,!0),resolveCollection(e,i,a,c,d);i.schema.tags.push(Object.assign({},t,{default:!1})),p=t}const h=resolveCollection(e,i,a,c,d,p),m=p.resolve?.(h,e=>c(l,"TAG_RESOLVE_FAILED",e),i.options)??h,f=t.isNode(m)?m:new n.Scalar(m);return f.range=h.range,f.tag=d,p?.format&&(f.format=p.format),f}e.composeCollection=composeCollection}}),fe=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/resolve-block-scalar.js"(e){var t=w();function resolveBlockScalar(e,n,r){const s=n.offset,i=parseBlockScalarHeader(n,e.options.strict,r);if(!i)return{value:"",type:null,comment:"",range:[s,s,s]};const a=">"===i.mode?t.Scalar.BLOCK_FOLDED:t.Scalar.BLOCK_LITERAL,o=n.source?splitLines(n.source):[];let c=o.length;for(let e=o.length-1;e>=0;--e){const t=o[e][1];if(""!==t&&"\r"!==t)break;c=e}if(0===c){const e="+"===i.chomp&&o.length>0?"\n".repeat(Math.max(1,o.length-1)):"";let t=s+i.length;return n.source&&(t+=n.source.length),{value:e,type:a,comment:i.comment,range:[s,t,t]}}let l=n.indent+i.indent,d=n.offset+i.length,u=0;for(let t=0;t<c;++t){const[n,s]=o[t];if(""!==s&&"\r"!==s){if(n.length<l){const e="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";r(d+n.length,"MISSING_CHAR",e)}if(0===i.indent&&(l=n.length),u=t,0===l&&!e.atRoot){const e="Block scalar values in collections must be indented";r(d,"BAD_INDENT",e)}break}0===i.indent&&n.length>l&&(l=n.length),d+=n.length+s.length+1}for(let e=o.length-1;e>=c;--e)o[e][0].length>l&&(c=e+1);let p="",h="",m=!1;for(let e=0;e<u;++e)p+=o[e][0].slice(l)+"\n";for(let e=u;e<c;++e){let[n,s]=o[e];d+=n.length+s.length+1;const c="\r"===s[s.length-1];if(c&&(s=s.slice(0,-1)),s&&n.length<l){const e=i.indent?"explicit indentation indicator":"first line",t=`Block scalar lines must not be less indented than their ${e}`;r(d-s.length-(c?2:1),"BAD_INDENT",t),n=""}a===t.Scalar.BLOCK_LITERAL?(p+=h+n.slice(l)+s,h="\n"):n.length>l||"\t"===s[0]?(" "===h?h="\n":m||"\n"!==h||(h="\n\n"),p+=h+n.slice(l)+s,h="\n",m=!0):""===s?"\n"===h?p+="\n":h="\n":(p+=h+s,h=" ",m=!1)}switch(i.chomp){case"-":break;case"+":for(let e=c;e<o.length;++e)p+="\n"+o[e][0].slice(l);"\n"!==p[p.length-1]&&(p+="\n");break;default:p+="\n"}const f=s+i.length+n.source.length;return{value:p,type:a,comment:i.comment,range:[s,f,f]}}function parseBlockScalarHeader({offset:e,props:t},n,r){if("block-scalar-header"!==t[0].type)return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;const{source:s}=t[0],i=s[0];let a=0,o="",c=-1;for(let t=1;t<s.length;++t){const n=s[t];if(o||"-"!==n&&"+"!==n){const r=Number(n);!a&&r?a=r:-1===c&&(c=e+t)}else o=n}-1!==c&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,d="",u=s.length;for(let e=1;e<t.length;++e){const s=t[e];switch(s.type){case"space":l=!0;case"newline":u+=s.source.length;break;case"comment":if(n&&!l){const e="Comments must be separated from other tokens by white space characters";r(s,"MISSING_CHAR",e)}u+=s.source.length,d=s.source.substring(1);break;case"error":r(s,"UNEXPECTED_TOKEN",s.message),u+=s.source.length;break;default:{const e=`Unexpected token in block scalar header: ${s.type}`;r(s,"UNEXPECTED_TOKEN",e);const t=s.source;t&&"string"==typeof t&&(u+=t.length)}}}return{mode:i,indent:a,chomp:o,comment:d,length:u}}function splitLines(e){const t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),s=r?.[1]?[r[1],n.slice(r[1].length)]:["",n],i=[s];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}e.resolveBlockScalar=resolveBlockScalar}}),ge=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/resolve-flow-scalar.js"(e){var t=w(),n=pe();function resolveFlowScalar(e,r,s){const{offset:i,type:a,source:o,end:c}=e;let l,d;const _onError=(e,t,n)=>s(i+e,t,n);switch(a){case"scalar":l=t.Scalar.PLAIN,d=plainValue(o,_onError);break;case"single-quoted-scalar":l=t.Scalar.QUOTE_SINGLE,d=singleQuotedValue(o,_onError);break;case"double-quoted-scalar":l=t.Scalar.QUOTE_DOUBLE,d=doubleQuotedValue(o,_onError);break;default:return s(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${a}`),{value:"",type:null,comment:"",range:[i,i+o.length,i+o.length]}}const u=i+o.length,p=n.resolveEnd(c,u,r,s);return{value:d,type:l,comment:p.comment,range:[i,u,p.offset]}}function plainValue(e,t){let n="";switch(e[0]){case"\t":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":n=`block scalar indicator ${e[0]}`;break;case"@":case"`":n=`reserved character ${e[0]}`}return n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),foldLines(e)}function singleQuotedValue(e,t){return"'"===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR","Missing closing 'quote"),foldLines(e.slice(1,-1)).replace(/''/g,"'")}function foldLines(e){let t,n;try{t=new RegExp("(.*?)(?<![ \t])[ \t]*\r?\n","sy"),n=new RegExp("[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\r?\n","sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let s=r[1],i=" ",a=t.lastIndex;for(n.lastIndex=a;r=n.exec(e);)""===r[1]?"\n"===i?s+=i:i="\n":(s+=i+r[1],i=" "),a=n.lastIndex;const o=/[ \t]*(.*)/sy;return o.lastIndex=a,r=o.exec(e),s+i+(r?.[1]??"")}function doubleQuotedValue(e,t){let n="";for(let s=1;s<e.length-1;++s){const i=e[s];if("\r"!==i||"\n"!==e[s+1])if("\n"===i){const{fold:t,offset:r}=foldNewline(e,s);n+=t,s=r}else if("\\"===i){let i=e[++s];const a=r[i];if(a)n+=a;else if("\n"===i)for(i=e[s+1];" "===i||"\t"===i;)i=e[1+ ++s];else if("\r"===i&&"\n"===e[s+1])for(i=e[1+ ++s];" "===i||"\t"===i;)i=e[1+ ++s];else if("x"===i||"u"===i||"U"===i){const r={x:2,u:4,U:8}[i];n+=parseCharCode(e,s+1,r,t),s+=r}else{const r=e.substr(s-1,2);t(s-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${r}`),n+=r}}else if(" "===i||"\t"===i){const t=s;let r=e[s+1];for(;" "===r||"\t"===r;)r=e[1+ ++s];"\n"===r||"\r"===r&&"\n"===e[s+2]||(n+=s>t?e.slice(t,s+1):i)}else n+=i}return'"'===e[e.length-1]&&1!==e.length||t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function foldNewline(e,t){let n="",r=e[t+1];for(;!(" "!==r&&"\t"!==r&&"\n"!==r&&"\r"!==r||"\r"===r&&"\n"!==e[t+2]);)"\n"===r&&(n+="\n"),t+=1,r=e[t+1];return n||(n=" "),{fold:n,offset:t}}var r={0:"\0",a:"",b:"\b",e:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function parseCharCode(e,t,n,r){const s=e.substr(t,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s),a=i?parseInt(s,16):NaN;if(isNaN(a)){const s=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}return String.fromCodePoint(a)}e.resolveFlowScalar=resolveFlowScalar}}),ye=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/compose-scalar.js"(e){var t=h(),n=w(),r=fe(),s=ge();function composeScalar(e,i,a,o){const{value:c,type:l,comment:d,range:u}="block-scalar"===i.type?r.resolveBlockScalar(e,i,o):s.resolveFlowScalar(i,e.options.strict,o),p=a?e.directives.tagName(a.source,e=>o(a,"TAG_RESOLVE_FAILED",e)):null;let h,m;h=e.options.stringKeys&&e.atKey?e.schema[t.SCALAR]:p?findScalarTagByName(e.schema,c,p,a,o):"scalar"===i.type?findScalarTagByTest(e,c,i,o):e.schema[t.SCALAR];try{const r=h.resolve(c,e=>o(a??i,"TAG_RESOLVE_FAILED",e),e.options);m=t.isScalar(r)?r:new n.Scalar(r)}catch(e){const t=e instanceof Error?e.message:String(e);o(a??i,"TAG_RESOLVE_FAILED",t),m=new n.Scalar(c)}return m.range=u,m.source=c,l&&(m.type=l),p&&(m.tag=p),h.format&&(m.format=h.format),d&&(m.comment=d),m}function findScalarTagByName(e,n,r,s,i){if("!"===r)return e[t.SCALAR];const a=[];for(const t of e.tags)if(!t.collection&&t.tag===r){if(!t.default||!t.test)return t;a.push(t)}for(const e of a)if(e.test?.test(n))return e;const o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,"tag:yaml.org,2002:str"!==r),e[t.SCALAR])}function findScalarTagByTest({atKey:e,directives:n,schema:r},s,i,a){const o=r.tags.find(t=>(!0===t.default||e&&"key"===t.default)&&t.test?.test(s))||r[t.SCALAR];if(r.compat){const e=r.compat.find(e=>e.default&&e.test?.test(s))??r[t.SCALAR];if(o.tag!==e.tag){const t=n.tagString(o.tag),r=n.tagString(e.tag),s=`Value may be parsed as either ${t} or ${r}`;a(i,"TAG_RESOLVE_FAILED",s,!0)}}return o}e.composeScalar=composeScalar}}),ve=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/util-empty-scalar-position.js"(e){function emptyScalarPosition(e,t,n){if(t){n??(n=t.length);for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];"space"===n?.type;)e+=n.source.length,n=t[++r];break}}return e}e.emptyScalarPosition=emptyScalarPosition}}),Ee=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/compose-node.js"(e){var t=T(),n=h(),r=me(),s=ye(),i=pe(),a=ve(),o={composeNode,composeEmptyNode};function composeNode(e,t,i,a){const c=e.atKey,{spaceBefore:l,comment:d,anchor:u,tag:p}=i;let h,m=!0;switch(t.type){case"alias":h=composeAlias(e,t,a),(u||p)&&a(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":h=s.composeScalar(e,t,p,a),u&&(h.anchor=u.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":h=r.composeCollection(o,e,t,i,a),u&&(h.anchor=u.source.substring(1));break;default:{const n="error"===t.type?t.message:`Unsupported token (type: ${t.type})`;a(t,"UNEXPECTED_TOKEN",n),h=composeEmptyNode(e,t.offset,void 0,null,i,a),m=!1}}if(u&&""===h.anchor&&a(u,"BAD_ALIAS","Anchor cannot be an empty string"),c&&e.options.stringKeys&&(!n.isScalar(h)||"string"!=typeof h.value||h.tag&&"tag:yaml.org,2002:str"!==h.tag)){const e="With stringKeys, all keys must be strings";a(p??t,"NON_STRING_KEY",e)}return l&&(h.spaceBefore=!0),d&&("scalar"===t.type&&""===t.source?h.comment=d:h.commentBefore=d),e.options.keepSourceTokens&&m&&(h.srcToken=t),h}function composeEmptyNode(e,t,n,r,{spaceBefore:i,comment:o,anchor:c,tag:l,end:d},u){const p={type:"scalar",offset:a.emptyScalarPosition(t,n,r),indent:-1,source:""},h=s.composeScalar(e,p,l,u);return c&&(h.anchor=c.source.substring(1),""===h.anchor&&u(c,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(h.spaceBefore=!0),o&&(h.comment=o,h.range[2]=d),h}function composeAlias({options:e},{offset:n,source:r,end:s},a){const o=new t.Alias(r.substring(1));""===o.source&&a(n,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&a(n+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const c=n+r.length,l=i.resolveEnd(s,c,e.strict,a);return o.range=[n,c,l.offset],l.comment&&(o.comment=l.comment),o}e.composeEmptyNode=composeEmptyNode,e.composeNode=composeNode}}),Te=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/compose-doc.js"(e){var t=se(),n=Ee(),r=pe(),s=ae();function composeDoc(e,i,{offset:a,start:o,value:c,end:l},d){const u=Object.assign({_directives:i},e),p=new t.Document(void 0,u),h={atKey:!1,atRoot:!0,directives:p.directives,options:p.options,schema:p.schema},m=s.resolveProps(o,{indicator:"doc-start",next:c??l?.[0],offset:a,onError:d,parentIndent:0,startOnNewline:!0});m.found&&(p.directives.docStart=!0,!c||"block-map"!==c.type&&"block-seq"!==c.type||m.hasNewline||d(m.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),p.contents=c?n.composeNode(h,c,m,d):n.composeEmptyNode(h,m.end,o,null,m,d);const f=p.contents.range[2],g=r.resolveEnd(l,f,!1,d);return g.comment&&(p.comment=g.comment),p.range=[a,f,g.offset],p}e.composeDoc=composeDoc}}),we=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/compose/composer.js"(e){var t=u("process"),n=f(),r=se(),s=ie(),i=h(),a=Te(),o=pe();function getErrorPos(e){if("number"==typeof e)return[e,e+1];if(Array.isArray(e))return 2===e.length?e:[e[0],e[1]];const{offset:t,source:n}=e;return[t,t+("string"==typeof n?n.length:1)]}function parsePrelude(e){let t="",n=!1,r=!1;for(let s=0;s<e.length;++s){const i=e[s];switch(i[0]){case"#":t+=(""===t?"":r?"\n\n":"\n")+(i.substring(1)||" "),n=!0,r=!1;break;case"%":"#"!==e[s+1]?.[0]&&(s+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var c=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{const i=getErrorPos(e);r?this.warnings.push(new s.YAMLWarning(i,t,n)):this.errors.push(new s.YAMLParseError(i,t,n))},this.directives=new n.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=parsePrelude(this.prelude);if(n){const s=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!s)e.commentBefore=n;else if(i.isCollection(s)&&!s.flow&&s.items.length>0){let e=s.items[0];i.isPair(e)&&(e=e.key);const t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{const e=s.commentBefore;s.commentBefore=e?`${n}\n${e}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:parsePrelude(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(const t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(t.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,n,r)=>{const s=getErrorPos(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=a.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{const t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new s.YAMLParseError(getErrorPos(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){const t="Unexpected doc-end without preceding document";this.errors.push(new s.YAMLParseError(getErrorPos(e),"UNEXPECTED_TOKEN",t));break}this.doc.directives.docEnd=!0;const t=o.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){const e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new s.YAMLParseError(getErrorPos(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){const e=Object.assign({_directives:this.directives},this.options),n=new r.Document(void 0,e);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,t,t],this.decorate(n,!1),yield n}}};e.Composer=c}}),Se=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/parse/cst-scalar.js"(e){var t=fe(),n=ge(),r=ie(),s=k();function resolveAsScalar(e,s=!0,i){if(e){const _onError=(e,t,n)=>{const s="number"==typeof e?e:Array.isArray(e)?e[0]:e.offset;if(!i)throw new r.YAMLParseError([s,s+1],t,n);i(s,t,n)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return n.resolveFlowScalar(e,s,_onError);case"block-scalar":return t.resolveBlockScalar({options:{strict:s}},e,_onError)}}return null}function createScalarToken(e,t){const{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:a=-1,type:o="PLAIN"}=t,c=s.stringifyString({type:o,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),l=t.end??[{type:"newline",offset:-1,indent:r,source:"\n"}];switch(c[0]){case"|":case">":{const e=c.indexOf("\n"),t=c.substring(0,e),n=c.substring(e+1)+"\n",s=[{type:"block-scalar-header",offset:a,indent:r,source:t}];return addEndtoBlockProps(s,l)||s.push({type:"newline",offset:-1,indent:r,source:"\n"}),{type:"block-scalar",offset:a,indent:r,props:s,source:n}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:c,end:l};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:c,end:l};default:return{type:"scalar",offset:a,indent:r,source:c,end:l}}}function setScalarValue(e,t,n={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:a=!1,type:o}=n,c="indent"in e?e.indent:null;if(r&&"number"==typeof c&&(c+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");o=">"===t.source[0]?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}const l=s.stringifyString({type:o,value:t},{implicitKey:i||null===c,indent:null!==c&&c>0?" ".repeat(c):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":setBlockScalarValue(e,l);break;case'"':setFlowScalarValue(e,l,"double-quoted-scalar");break;case"'":setFlowScalarValue(e,l,"single-quoted-scalar");break;default:setFlowScalarValue(e,l,"scalar")}}function setBlockScalarValue(e,t){const n=t.indexOf("\n"),r=t.substring(0,n),s=t.substring(n+1)+"\n";if("block-scalar"===e.type){const t=e.props[0];if("block-scalar-header"!==t.type)throw new Error("Invalid block scalar header");t.source=r,e.source=s}else{const{offset:t}=e,n="indent"in e?e.indent:-1,i=[{type:"block-scalar-header",offset:t,indent:n,source:r}];addEndtoBlockProps(i,"end"in e?e.end:void 0)||i.push({type:"newline",offset:-1,indent:n,source:"\n"});for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:"block-scalar",indent:n,props:i,source:s})}}function addEndtoBlockProps(e,t){if(t)for(const n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function setFlowScalarValue(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{const r=e.props.slice(1);let s=t.length;"block-scalar-header"===e.props[0].type&&(s-=e.props[0].source.length);for(const e of r)e.offset+=s;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case"block-map":case"block-seq":{const r=e.offset+t.length,s={type:"newline",offset:r,indent:e.indent,source:"\n"};delete e.items,Object.assign(e,{type:n,source:t,end:[s]});break}default:{const r="indent"in e?e.indent:-1,s="end"in e&&Array.isArray(e.end)?e.end.filter(e=>"space"===e.type||"comment"===e.type||"newline"===e.type):[];for(const t of Object.keys(e))"type"!==t&&"offset"!==t&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:s})}}}e.createScalarToken=createScalarToken,e.resolveAsScalar=resolveAsScalar,e.setScalarValue=setScalarValue}}),be=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/parse/cst-stringify.js"(e){var stringify2=e=>"type"in e?stringifyToken(e):stringifyItem(e);function stringifyToken(e){switch(e.type){case"block-scalar":{let t="";for(const n of e.props)t+=stringifyToken(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(const n of e.items)t+=stringifyItem(n);return t}case"flow-collection":{let t=e.start.source;for(const n of e.items)t+=stringifyItem(n);for(const n of e.end)t+=n.source;return t}case"document":{let t=stringifyItem(e);if(e.end)for(const n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(const n of e.end)t+=n.source;return t}}}function stringifyItem({start:e,key:t,sep:n,value:r}){let s="";for(const t of e)s+=t.source;if(t&&(s+=stringifyToken(t)),n)for(const e of n)s+=e.source;return r&&(s+=stringifyToken(r)),s}e.stringify=stringify2}}),Ae=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/parse/cst-visit.js"(e){var t=Symbol("break visit"),n=Symbol("skip children"),r=Symbol("remove item");function visit(e,t){"type"in e&&"document"===e.type&&(e={start:e.start,value:e.value}),_visit(Object.freeze([]),e,t)}function _visit(e,n,s){let i=s(n,e);if("symbol"==typeof i)return i;for(const a of["key","value"]){const o=n[a];if(o&&"items"in o){for(let n=0;n<o.items.length;++n){const i=_visit(Object.freeze(e.concat([[a,n]])),o.items[n],s);if("number"==typeof i)n=i-1;else{if(i===t)return t;i===r&&(o.items.splice(n,1),n-=1)}}"function"==typeof i&&"key"===a&&(i=i(n,e))}}return"function"==typeof i?i(n,e):i}visit.BREAK=t,visit.SKIP=n,visit.REMOVE=r,visit.itemAtPath=(e,t)=>{let n=e;for(const[e,r]of t){const t=n?.[e];if(!t||!("items"in t))return;n=t.items[r]}return n},visit.parentCollection=(e,t)=>{const n=visit.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],s=n?.[r];if(s&&"items"in s)return s;throw new Error("Parent collection not found")},e.visit=visit}}),_e=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/parse/cst.js"(e){var t=Se(),n=be(),r=Ae(),s="\ufeff",i="",a="",o="",isCollection=e=>!!e&&"items"in e,isScalar=e=>!!e&&("scalar"===e.type||"single-quoted-scalar"===e.type||"double-quoted-scalar"===e.type||"block-scalar"===e.type);function prettyToken(e){switch(e){case s:return"<BOM>";case i:return"<DOC>";case a:return"<FLOW_END>";case o:return"<SCALAR>";default:return JSON.stringify(e)}}function tokenType(e){switch(e){case s:return"byte-order-mark";case i:return"doc-mode";case a:return"flow-error-end";case o:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case"\n":case"\r\n":return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=s,e.DOCUMENT=i,e.FLOW_END=a,e.SCALAR=o,e.isCollection=isCollection,e.isScalar=isScalar,e.prettyToken=prettyToken,e.tokenType=tokenType}}),ke=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/parse/lexer.js"(e){var t=_e();function isEmpty(e){switch(e){case void 0:case" ":case"\n":case"\r":case"\t":return!0;default:return!1}}var n=new Set("0123456789ABCDEFabcdef"),r=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),s=new Set(",[]{}"),i=new Set(" ,[]{}\n\r\t"),isNotAnchorChar=e=>!e||i.has(e),a=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if("string"!=typeof e)throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;" "===t||"\t"===t;)t=this.buffer[++e];return!t||"#"===t||"\n"===t||"\r"===t&&"\n"===this.buffer[e+1]}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;" "===t;)t=this.buffer[++n+e];if("\r"===t){const t=this.buffer[n+e+1];if("\n"===t||!t&&!this.atEnd)return e+n+1}return"\n"===t||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if("-"===t||"."===t){const t=this.buffer.substr(e,3);if(("---"===t||"..."===t)&&isEmpty(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return("number"!=typeof e||-1!==e&&e<this.pos)&&(e=this.buffer.indexOf("\n",this.pos),this.lineEndPos=e),-1===e?this.atEnd?this.buffer.substring(this.pos):null:("\r"===this.buffer[e-1]&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(null===e)return this.setNext("stream");if(e[0]===t.BOM&&(yield*this.pushCount(1),e=e.substring(1)),"%"===e[0]){let t=e.length,n=e.indexOf("#");for(;-1!==n;){const r=e[n-1];if(" "===r||"\t"===r){t=n-1;break}n=e.indexOf("#",n+1)}for(;;){const n=e[t-1];if(" "!==n&&"\t"!==n)break;t-=1}const r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){const t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield t.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if("-"===e||"."===e){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const e=this.peek(3);if(("---"===e||"..."===e)&&isEmpty(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,"---"===e?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!isEmpty(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){const[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if(("-"===e||"?"===e||":"===e)&&isEmpty(t)){const e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);const e=this.getLine();if(null===e)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(isNotAnchorChar),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=(yield*this.parseBlockScalarHeader()),t+=(yield*this.pushSpaces(!0)),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,r=-1;do{e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=(yield*this.pushSpaces(!0))}while(e+n>0);const s=this.getLine();if(null===s)return this.setNext("flow");if(-1!==r&&r<this.indentNext&&"#"!==s[0]||0===r&&(s.startsWith("---")||s.startsWith("..."))&&isEmpty(s[3])){const e=r===this.indentNext-1&&1===this.flowLevel&&("]"===s[0]||"}"===s[0]);if(!e)return this.flowLevel=0,yield t.FLOW_END,yield*this.parseLineStart()}let i=0;for(;","===s[i];)i+=(yield*this.pushCount(1)),i+=(yield*this.pushSpaces(!0)),this.flowKey=!1;switch(i+=(yield*this.pushIndicators()),s[i]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(isNotAnchorChar),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const e=this.charAt(1);if(this.flowKey||isEmpty(e)||","===e)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if("'"===e)for(;-1!==t&&"'"===this.buffer[t+1];)t=this.buffer.indexOf("'",t+2);else for(;-1!==t;){let e=0;for(;"\\"===this.buffer[t-1-e];)e+=1;if(e%2==0)break;t=this.buffer.indexOf('"',t+1)}const n=this.buffer.substring(0,t);let r=n.indexOf("\n",this.pos);if(-1!==r){for(;-1!==r;){const e=this.continueScalar(r+1);if(-1===e)break;r=n.indexOf("\n",e)}-1!==r&&(t=r-("\r"===n[r-1]?2:1))}if(-1===t){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){const t=this.buffer[++e];if("+"===t)this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if("-"!==t)break}return yield*this.pushUntil(e=>isEmpty(e)||"#"===e)}*parseBlockScalar(){let e,n=this.pos-1,r=0;e:for(let t=this.pos;e=this.buffer[t];++t)switch(e){case" ":r+=1;break;case"\n":n=t,r=0;break;case"\r":{const e=this.buffer[t+1];if(!e&&!this.atEnd)return this.setNext("block-scalar");if("\n"===e)break}default:break e}if(!e&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){-1===this.blockScalarIndent?this.indentNext=r:this.indentNext=this.blockScalarIndent+(0===this.indentNext?1:this.indentNext);do{const e=this.continueScalar(n+1);if(-1===e)break;n=this.buffer.indexOf("\n",e)}while(-1!==n);if(-1===n){if(!this.atEnd)return this.setNext("block-scalar");n=this.buffer.length}}let s=n+1;for(e=this.buffer[s];" "===e;)e=this.buffer[++s];if("\t"===e){for(;"\t"===e||" "===e||"\r"===e||"\n"===e;)e=this.buffer[++s];n=s-1}else if(!this.blockScalarKeep)for(;;){let e=n-1,t=this.buffer[e];"\r"===t&&(t=this.buffer[--e]);const s=e;for(;" "===t;)t=this.buffer[--e];if(!("\n"===t&&e>=this.pos&&e+1+r>s))break;n=e}return yield t.SCALAR,yield*this.pushToIndex(n+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){const e=this.flowLevel>0;let n,r=this.pos-1,i=this.pos-1;for(;n=this.buffer[++i];)if(":"===n){const t=this.buffer[i+1];if(isEmpty(t)||e&&s.has(t))break;r=i}else if(isEmpty(n)){let t=this.buffer[i+1];if("\r"===n&&("\n"===t?(i+=1,n="\n",t=this.buffer[i+1]):r=i),"#"===t||e&&s.has(t))break;if("\n"===n){const e=this.continueScalar(i+1);if(-1===e)break;i=Math.max(i,e-2)}}else{if(e&&s.has(n))break;r=i}return n||this.atEnd?(yield t.SCALAR,yield*this.pushToIndex(r+1,!0),e?"flow":"doc"):this.setNext("plain-scalar")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){const n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(isNotAnchorChar))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(isEmpty(t)||e&&s.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if("<"===this.charAt(1)){let e=this.pos+2,t=this.buffer[e];for(;!isEmpty(t)&&">"!==t;)t=this.buffer[++e];return yield*this.pushToIndex(">"===t?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(r.has(t))t=this.buffer[++e];else{if("%"!==t||!n.has(this.buffer[e+1])||!n.has(this.buffer[e+2]))break;t=this.buffer[e+=3]}return yield*this.pushToIndex(e,!1)}}*pushNewline(){const e=this.buffer[this.pos];return"\n"===e?yield*this.pushCount(1):"\r"===e&&"\n"===this.charAt(1)?yield*this.pushCount(2):0}*pushSpaces(e){let t,n=this.pos-1;do{t=this.buffer[++n]}while(" "===t||e&&"\t"===t);const r=n-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};e.Lexer=a}}),Ie=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/parse/line-counter.js"(e){var t=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){const r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(0===t)return{line:0,col:e};const r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};e.LineCounter=t}}),Ce=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/parse/parser.js"(e){var t=u("process"),n=_e(),r=ke();function includesToken(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function findNonEmptyIndex(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function isFlowToken(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function getPrevProps(e){switch(e.type){case"document":return e.start;case"block-map":{const t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function getFirstKeyStartProps(e){if(0===e.length)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;"space"===e[++t]?.type;);return e.splice(t,e.length)}function fixFlowSeqItems(e){if("flow-seq-start"===e.start.type)for(const t of e.items)!t.sep||t.value||includesToken(t.start,"explicit-key-ind")||includesToken(t.sep,"map-value-ind")||(t.key&&(t.value=t.key),delete t.key,isFlowToken(t.value)?t.value.end?Array.prototype.push.apply(t.value.end,t.sep):t.value.end=t.sep:Array.prototype.push.apply(t.start,t.sep),delete t.sep)}var s=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new r.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&0===this.offset&&this.onNewLine(0);for(const n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,t.env.LOG_TOKENS&&console.log("|",n.prettyToken(e)),this.atScalar)return this.atScalar=!1,yield*this.step(),void(this.offset+=e.length);const r=n.tokenType(e);if(r)if("scalar"===r)this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&" "===e[0]&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{const t=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:t,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){const e={type:this.type,offset:this.offset,indent:this.indent,source:this.source};return e}*step(){const e=this.peek(1);if("doc-end"!==this.type||"doc-end"===e?.type){if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}else{for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source})}}peek(e){return this.stack[this.stack.length-e]}*pop(e){const t=e??this.stack.pop();if(t)if(0===this.stack.length)yield t;else{const e=this.peek(1);switch("block-scalar"===t.type?t.indent="indent"in e?e.indent:0:"flow-collection"===t.type&&"document"===e.type&&(t.indent=0),"flow-collection"===t.type&&fixFlowSeqItems(t),e.type){case"document":e.value=t;break;case"block-scalar":e.props.push(t);break;case"block-map":{const n=e.items[e.items.length-1];if(n.value)return e.items.push({start:[],key:t,sep:[]}),void(this.onKeyLine=!0);if(!n.sep)return Object.assign(n,{key:t,sep:[]}),void(this.onKeyLine=!n.explicitKey);n.value=t;break}case"block-seq":{const n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case"flow-collection":{const n=e.items[e.items.length-1];return void(!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]}))}default:yield*this.pop(),yield*this.pop(t)}if(!("document"!==e.type&&"block-map"!==e.type&&"block-seq"!==e.type||"block-map"!==t.type&&"block-seq"!==t.type)){const n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&-1===findNonEmptyIndex(n.start)&&(0===t.indent||n.start.every(e=>"comment"!==e.type||e.indent<t.indent))&&("document"===e.type?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}else{const e="Tried to pop an empty stack";yield{type:"error",offset:this.offset,source:"",message:e}}}*stream(){switch(this.type){case"directive-line":return void(yield{type:"directive",offset:this.offset,source:this.source});case"byte-order-mark":case"space":case"comment":case"newline":return void(yield this.sourceToken);case"doc-mode":case"doc-start":{const e={type:"document",offset:this.offset,start:[]};return"doc-start"===this.type&&e.start.push(this.sourceToken),void this.stack.push(e)}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":return void(-1!==findNonEmptyIndex(e.start)?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken));case"anchor":case"tag":case"space":case"comment":case"newline":return void e.start.push(this.sourceToken)}const t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if("map-value-ind"===this.type){const t=getPrevProps(this.peek(2)),n=getFirstKeyStartProps(t);let r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken];const s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":return void e.props.push(this.sourceToken);case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0,r=Array.isArray(n)?n[n.length-1]:void 0;"comment"===r?.type?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2],r=n?.value?.end;if(Array.isArray(r))return Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&"seq-item-ind"!==this.type;let s=[];if(r&&t.sep&&!t.value){const n=[];for(let r=0;r<t.sep.length;++r){const s=t.sep[r];switch(s.type){case"newline":n.push(r);break;case"space":break;case"comment":s.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(s=t.sep.splice(n[1]))}switch(this.type){case"anchor":case"tag":return void(r||t.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken));case"explicit-key-ind":return t.sep||t.explicitKey?r||t.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}):(t.start.push(this.sourceToken),t.explicitKey=!0),void(this.onKeyLine=!0);case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(includesToken(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(isFlowToken(t.key)&&!includesToken(t.sep,"newline")){const e=getFirstKeyStartProps(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(includesToken(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const e=getFirstKeyStartProps(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:s,key:null,sep:[this.sourceToken]}):includesToken(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return void(this.onKeyLine=!0);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const n=this.flowScalar(this.type);return void(r||t.value?(e.items.push({start:s,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0))}default:{const r=this.startBlockValue(e);if(r){if("block-seq"===r.type){if(!t.explicitKey&&t.sep&&!includesToken(t.sep,"newline"))return void(yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source}))}else n&&e.items.push({start:s});return void this.stack.push(r)}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0,r=Array.isArray(n)?n[n.length-1]:void 0;"comment"===r?.type?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const n=e.items[e.items.length-2],r=n?.value?.end;if(Array.isArray(r))return Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),void e.items.pop()}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;return void t.start.push(this.sourceToken);case"seq-item-ind":if(this.indent!==e.indent)break;return void(t.value||includesToken(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken))}if(this.indent>e.indent){const t=this.startBlockValue(e);if(t)return void this.stack.push(t)}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if("flow-error-end"===this.type){let e;do{yield*this.pop(),e=this.peek(1)}while("flow-collection"===e?.type)}else if(0===e.end.length){switch(this.type){case"comma":case"explicit-key-ind":return void(!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken));case"map-value-ind":return void(!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]}));case"space":case"comment":case"newline":case"anchor":case"tag":return void(!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken));case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const n=this.flowScalar(this.type);return void(!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]}))}case"flow-map-end":case"flow-seq-end":return void e.end.push(this.sourceToken)}const n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const t=this.peek(2);if("block-map"===t.type&&("map-value-ind"===this.type&&t.indent===e.indent||"newline"===this.type&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if("map-value-ind"===this.type&&"flow-collection"!==t.type){const n=getPrevProps(t),r=getFirstKeyStartProps(n);fixFlowSeqItems(e);const s=e.end.splice(1,e.end.length);s.push(this.sourceToken);const i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf("\n")+1;for(;0!==e;)this.onNewLine(this.offset+e),e=this.source.indexOf("\n",e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=getPrevProps(e),n=getFirstKeyStartProps(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=getPrevProps(e),n=getFirstKeyStartProps(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return"comment"===this.type&&(!(this.indent<=t)&&e.every(e=>"newline"===e.type||"space"===e.type))}*documentEnd(e){"doc-mode"!==this.type&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],"newline"===this.type&&(yield*this.pop())}}};e.Parser=s}}),Re=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/public-api.js"(e){var t=we(),n=se(),r=ie(),s=R(),i=h(),a=Ie(),o=Ce();function parseOptions(e){const t=!1!==e.prettyErrors,n=e.lineCounter||t&&new a.LineCounter||null;return{lineCounter:n,prettyErrors:t}}function parseAllDocuments(e,n={}){const{lineCounter:s,prettyErrors:i}=parseOptions(n),a=new o.Parser(s?.addNewLine),c=new t.Composer(n),l=Array.from(c.compose(a.parse(e)));if(i&&s)for(const t of l)t.errors.forEach(r.prettifyError(e,s)),t.warnings.forEach(r.prettifyError(e,s));return l.length>0?l:Object.assign([],{empty:!0},c.streamInfo())}function parseDocument(e,n={}){const{lineCounter:s,prettyErrors:i}=parseOptions(n),a=new o.Parser(s?.addNewLine),c=new t.Composer(n);let l=null;for(const t of c.compose(a.parse(e),!0,e.length))if(l){if("silent"!==l.options.logLevel){l.errors.push(new r.YAMLParseError(t.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}}else l=t;return i&&s&&(l.errors.forEach(r.prettifyError(e,s)),l.warnings.forEach(r.prettifyError(e,s))),l}function parse2(e,t,n){let r;"function"==typeof t?r=t:void 0===n&&t&&"object"==typeof t&&(n=t);const i=parseDocument(e,n);if(!i)return null;if(i.warnings.forEach(e=>s.warn(i.options.logLevel,e)),i.errors.length>0){if("silent"!==i.options.logLevel)throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function stringify2(e,t,r){let s=null;if("function"==typeof t||Array.isArray(t)?s=t:void 0===r&&t&&(r=t),"string"==typeof r&&(r=r.length),"number"==typeof r){const e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(void 0===e){const{keepUndefined:e}=r??t??{};if(!e)return}return i.isDocument(e)&&!s?e.toString(r):new n.Document(e,s,r).toString(r)}e.parse=parse2,e.parseAllDocuments=parseAllDocuments,e.parseDocument=parseDocument,e.stringify=stringify2}}),Pe=d({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/index.js"(e){var t=we(),n=se(),r=ne(),s=ie(),i=T(),a=h(),o=O(),c=w(),l=L(),d=x(),u=_e(),p=ke(),f=Ie(),g=Ce(),y=Re(),v=m();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=s.YAMLError,e.YAMLParseError=s.YAMLParseError,e.YAMLWarning=s.YAMLWarning,e.Alias=i.Alias,e.isAlias=a.isAlias,e.isCollection=a.isCollection,e.isDocument=a.isDocument,e.isMap=a.isMap,e.isNode=a.isNode,e.isPair=a.isPair,e.isScalar=a.isScalar,e.isSeq=a.isSeq,e.Pair=o.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=d.YAMLSeq,e.CST=u,e.Lexer=p.Lexer,e.LineCounter=f.LineCounter,e.Parser=g.Parser,e.parse=y.parse,e.parseAllDocuments=y.parseAllDocuments,e.parseDocument=y.parseDocument,e.stringify=y.stringify,e.visit=v.visit,e.visitAsync=v.visitAsync}});import{execFileSync as Ne,spawn as Oe}from"child_process";import{randomUUID as De}from"crypto";import{mkdir as Le,mkdtemp as Me,rm as xe,writeFile as Fe}from"fs/promises";import{tmpdir as Be}from"os";import He from"path";var Ue="data-tempo-projection-pending",je="data-tempo-projection-unavailable",$e=3,Ge="canvasProtocol",qe={canvasPath:"canvasPath",storyboardId:"storyboardId",width:"width",height:"height",idle:"tempoCaptureIdle"},We={width:1600,height:1200},Ve="data-tempo-storyboard-render-id",Ke=`[${Ue}]`,Ye='[data-render-error="true"]',ze="data-render-error-message";function buildCanvasStoryboardRenderId(e,t){return`canvas:${encodeURIComponent(e.trim())}#storyboard:${encodeURIComponent(t.trim())}`}function buildStoryboardRenderSelector(e){return`[${Ve}=${JSON.stringify(e)}]`}function buildCanvasHostUrl(e,t=!1){const n=new URL(e);return n.searchParams.set(Ge,String($e)),t&&n.searchParams.set("canvasRegistration","incremental"),n}function buildDirectRenderUrl(e,t){const n=void 0!==t.width,r=void 0!==t.height;if(n!==r)throw new Error("Direct render width and height must be provided together");const s=buildCanvasHostUrl(e);return s.searchParams.delete(qe.idle),s.searchParams.set(qe.canvasPath,t.canvasPath),s.searchParams.set(qe.storyboardId,t.storyboardId),n&&r?(s.searchParams.set(qe.width,String(t.width)),s.searchParams.set(qe.height,String(t.height))):(s.searchParams.delete(qe.width),s.searchParams.delete(qe.height)),s.toString()}function buildDirectRenderIdleUrl(e){const t=buildCanvasHostUrl(e);for(const e of Object.values(qe))t.searchParams.delete(e);return t.searchParams.set(qe.idle,"1"),t.toString()}import{createHash as Je}from"crypto";import{readFile as Qe,realpath as Xe}from"fs/promises";import{readFileSync as Ze,realpathSync as et}from"fs";import{isAbsolute as tt,relative as nt,resolve as rt}from"path";async function readBrowserRuntimeScript(e=process.env.TEMPO_SDK_RUNTIME_PATH){if(!e||!tt(e))throw new Error("Tempo browser runtime is not provisioned. Set TEMPO_SDK_RUNTIME_PATH to the host's private runtime directory.");const t=JSON.parse(await Qe(rt(e,"runtime.json"),"utf8")),n=t.browser;if(1!==t.tempoRuntimeContract||"string"!=typeof n?.file||"string"!=typeof n?.sha256)throw new Error("Incompatible Tempo browser runtime. Update the host application.");const r=await Xe(e),s=await Xe(rt(r,n.file)),i=nt(r,s);if(tt(i)||".."===i||i.startsWith("../")||i.startsWith("..\\"))throw new Error("Tempo browser runtime path escapes its directory.");const a=await Qe(s,"utf8");if(Je("sha256").update(a).digest("hex")!==n.sha256)throw new Error("Tempo browser runtime artifact failed its integrity check.");return a}import{createHash as st}from"crypto";import{PNG as it}from"pngjs";var at=Date.UTC(2026,0,1,12,0,0);function buildFreezeInitScript(){return`(() => {\n const FROZEN_NOW = ${at};\n const RealDate = Date;\n class FrozenDate extends RealDate {\n constructor(...args) {\n if (args.length === 0) {\n super(FROZEN_NOW);\n } else {\n super(...args);\n }\n }\n static now() {\n return FROZEN_NOW;\n }\n }\n FrozenDate.parse = RealDate.parse;\n FrozenDate.UTC = RealDate.UTC;\n Date = FrozenDate;\n globalThis.Date = FrozenDate;\n if (typeof performance !== "undefined") {\n const origin = performance.now();\n const realNow = performance.now.bind(performance);\n performance.now = () => realNow() - origin;\n }\n let seed;\n globalThis.__tempoResetCaptureDeterminism = () => {\n seed = 0x74656d70;\n };\n globalThis.__tempoResetCaptureDeterminism();\n Math.random = () => {\n seed |= 0;\n seed = (seed + 0x6d2b79f5) | 0;\n let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n})();`}var ot="\n@layer tempo-capture-motion {\n*, *::before, *::after {\n animation-duration: 0s !important;\n animation-delay: 0s !important;\n transition-duration: 0s !important;\n transition-delay: 0s !important;\n scroll-behavior: auto !important;\n caret-color: transparent !important;\n}\n}\n",ct=["target","fonts","suspense","content-quiet","paint"],lt=2e3,dt=300,ut=15e3,pt=50,ht="(function() {\n try {\n if (location.pathname.includes('/__tempo/astro/')) {\n var meta = document.querySelector('meta[name=\"tempo-astro-storyboard\"]');\n if (!meta) return false;\n var receipt = JSON.parse(meta.content);\n var address = location.pathname.split('/__tempo/astro/')[1].replace(/\\/$/, '').split('/');\n if (receipt.canvasPath !== decodeURIComponent(address[0]) || receipt.storyboardId !== decodeURIComponent(address[1])) return false;\n }\n if (document.querySelector('script[data-island-id]')) return false;\n return Array.from(document.querySelectorAll('astro-island[ssr]')).every(function(island) {\n var mode = island.getAttribute('client');\n if (mode === 'media') return !matchMedia(JSON.parse(island.getAttribute('opts') || '{}').value).matches;\n if (mode === 'visible') return !Array.from(island.children).some(function(child) {\n var r = child.getBoundingClientRect();\n return r.bottom > 0 && r.right > 0 && r.top < innerHeight && r.left < innerWidth && (r.width > 0 || r.height > 0);\n });\n return false;\n });\n } catch { return false; }\n})()";function buildSettleWaitScript(e){const t=Math.max(0,Math.round(e.quietMs??dt)),n=Math.max(1,Math.round(e.stepTimeoutMs??ut)),r=Math.max(1,Math.round(e.quietTimeoutMs??n)),s=Math.max(1,Math.round(e.pollMs??pt));return`\n (function() {\n var selector = ${JSON.stringify(e.selector)};\n var waitForMedia = ${!1!==e.waitForMedia};\n var pendingSelector = ${JSON.stringify(e.pendingSelector??null)};\n var quietMs = ${t};\n var stepTimeoutMs = ${n};\n var quietTimeoutMs = ${r};\n var quietBestEffort = ${!0===e.quietBestEffort?"true":"false"};\n var strictVideoFrames = ${!0===e.strictVideoFrames?"true":"false"};\n var pollMs = ${s};\n var runPaint = ${!1===e.paint?"false":"true"};\n var steps = {};\n // Cleared when the content-quiet step gives up under best effort.\n var quiet = true;\n // Monotonic and immune to the determinism kit's frozen Date.\n var now = typeof performance !== 'undefined' && performance && typeof performance.now === 'function'\n ? function() { return performance.now(); }\n : function() { return Date.now(); };\n\n function failure(step, message) {\n return { ok: false, step: step, message: message, steps: steps };\n }\n\n // Polls \`check\` until it answers true, or \`budgetMs\` elapses. The\n // first check runs synchronously so an already-settled step costs no\n // poll interval. A step run with \`giveUp\` resolves at its budget\n // instead of failing, recording that the content never held still.\n function until(step, check, budgetMs, giveUp) {\n var started = now();\n return new Promise(function(resolve, reject) {\n function tick() {\n var done;\n try {\n done = check();\n } catch (error) {\n steps[step] = Math.round(now() - started);\n reject(failure(step, String((error && error.message) || error)));\n return;\n }\n if (done) {\n steps[step] = Math.round(now() - started);\n resolve();\n return;\n }\n if (now() - started >= budgetMs) {\n steps[step] = Math.round(now() - started);\n if (step === 'content-quiet' && pendingStrictVideo !== null) {\n reject(failure(step, pendingStrictVideo + '; Timeout ' + budgetMs + 'ms exceeded'));\n return;\n }\n if (giveUp) {\n quiet = false;\n resolve();\n return;\n }\n reject(failure(step, 'Timeout ' + budgetMs + 'ms exceeded'));\n return;\n }\n setTimeout(tick, pollMs);\n }\n tick();\n });\n }\n\n var quietKey = null;\n var quietSince = 0;\n var pendingStrictVideo = null;\n // When a rendered video was first seen without a decoded frame, and how\n // long that may hold the quiet window before we give up on it.\n var videoWaitStartedAt = null;\n var videoWaitCapMs = ${lt};\n // Images that take part in the capture: laid out and not hidden. A\n // hidden responsive variant never starts native lazy loading and must\n // not hold the window; a rendered lazy image never starts either,\n // because a capture does not scroll, so it is asked for eagerly.\n function renderedMatches(target, tag) {\n var all = Array.prototype.slice.call(target.querySelectorAll(tag));\n var rendered = [];\n for (var i = 0; i < all.length; i++) {\n var el = all[i];\n if (el.getClientRects().length === 0) continue;\n var visibility = getComputedStyle(el).visibility;\n if (visibility === 'hidden' || visibility === 'collapse') continue;\n rendered.push(el);\n }\n return rendered;\n }\n function renderedImages(target) {\n return renderedMatches(target, 'img');\n }\n // The source each image was last asked to decode, and whether that\n // decode has settled. A new source asks again.\n var decodes = typeof WeakMap === 'function' ? new WeakMap() : null;\n function imageDecoded(img) {\n if (!decodes || typeof img.decode !== 'function') return true;\n var src = img.currentSrc || img.src;\n var entry = decodes.get(img);\n if (!entry || entry.src !== src) {\n entry = { src: src, done: false };\n decodes.set(img, entry);\n var settled = function() { entry.done = true; };\n img.decode().then(settled, settled);\n }\n return entry.done;\n }\n // Preserve the bounded readiness heuristic for live screenshots.\n // Strict baselines additionally prove decoding below: Chromium's\n // suspended metadata startup can report readyState 3/4 with no frame.\n function videoFrameReady(video) {\n if (video.error) return true;\n if (video.preload === 'none') return true;\n var networkState = video.networkState;\n if (networkState === 0 /* NETWORK_EMPTY */) return true;\n if (networkState === 3 /* NETWORK_NO_SOURCE */) return true;\n return video.readyState >= 2 /* HAVE_CURRENT_DATA */;\n }\n function videoSource(video) {\n var source = video.querySelector('source[src]');\n return video.currentSrc || video.src || (source && source.src) || '(no source)';\n }\n var posterDecodes = strictVideoFrames ? new WeakMap() : null;\n function videoPosterDecoded(video) {\n var src = video.poster;\n var crossOrigin = video.crossOrigin;\n var entry = posterDecodes.get(video);\n if (!entry || entry.src !== src || entry.crossOrigin !== crossOrigin) {\n var image = video.ownerDocument.createElement('img');\n entry = { src: src, crossOrigin: crossOrigin, image: image, done: false, error: null };\n posterDecodes.set(video, entry);\n // Match the poster request's CORS/credentials policy before it\n // starts. A no-CORS image could decode a blocked video poster.\n image.crossOrigin = crossOrigin;\n image.src = src;\n image.decode().then(\n function() { entry.done = true; },\n function(error) { entry.error = String((error && error.message) || error); }\n );\n }\n if (entry.error !== null) {\n throw new Error('Video poster could not decode: ' + src + ': ' + entry.error);\n }\n return entry.done;\n }\n var videoFrames = strictVideoFrames ? new Map() : null;\n function frameSource(video) {\n return JSON.stringify([video.currentSrc, video.src, video.crossOrigin,\n Array.prototype.map.call(video.querySelectorAll('source'), function(source) {\n return [source.src, source.type, source.media];\n })]);\n }\n function resetVideoFrame(entry) {\n entry.generation++;\n if (entry.callbackId !== null) {\n entry.video.cancelVideoFrameCallback(entry.callbackId);\n entry.callbackId = null;\n }\n entry.presented = false;\n quietKey = null;\n }\n function releaseVideoFrame(entry) {\n resetVideoFrame(entry);\n entry.video.removeEventListener('emptied', entry.reset);\n entry.video.removeEventListener('loadstart', entry.reset);\n entry.video.removeEventListener('seeking', entry.reset);\n videoFrames.delete(entry.video);\n }\n function releaseVideoFrames() {\n if (videoFrames) videoFrames.forEach(releaseVideoFrame);\n }\n function decodedVideoFrames(video) {\n if (typeof video.webkitDecodedFrameCount === 'number') {\n return video.webkitDecodedFrameCount;\n }\n if (typeof video.getVideoPlaybackQuality === 'function') {\n var quality = video.getVideoPlaybackQuality();\n return quality.totalVideoFrames - quality.droppedVideoFrames;\n }\n return 0;\n }\n function strictVideoFrameReady(video) {\n if (video.error) {\n throw new Error('Video frame failed for ' + videoSource(video) +\n ' (media error ' + video.error.code + '): ' + (video.error.message || 'media unavailable'));\n }\n var entry = videoFrames.get(video);\n var source = frameSource(video);\n if (entry && entry.source !== source) {\n releaseVideoFrame(entry);\n entry = null;\n }\n if (video.seeking) {\n if (entry) resetVideoFrame(entry);\n return false;\n }\n // Do not start media the author deliberately left unplayed. A\n // decoded poster is valid evidence only while it is the intended\n // still surface, never as a substitute for an autoplay/seek frame.\n if (video.preload === 'none' && video.paused && !video.autoplay &&\n video.currentTime === 0 && video.played.length === 0 && video.poster) {\n if (entry) releaseVideoFrame(entry);\n return videoPosterDecoded(video);\n }\n if (video.readyState < 2 /* HAVE_CURRENT_DATA */) {\n if (entry) resetVideoFrame(entry);\n return false;\n }\n if (entry && entry.presented) return true;\n // A paused video may decode its first frame without delivering a\n // pending presentation callback. The callback wakes suspended startup;\n // decoded-frame evidence independently satisfies readiness, including\n // when decoding races its registration. readyState and seeking still\n // gate both paths.\n if (decodedVideoFrames(video) > 0) {\n if (entry) releaseVideoFrame(entry);\n return true;\n }\n if (!entry) {\n entry = { video: video, source: source, callbackId: null,\n generation: 0, presented: false, reset: null };\n entry.reset = function() { resetVideoFrame(entry); };\n video.addEventListener('emptied', entry.reset);\n video.addEventListener('loadstart', entry.reset);\n video.addEventListener('seeking', entry.reset);\n videoFrames.set(video, entry);\n }\n if (entry.callbackId === null && typeof video.requestVideoFrameCallback === 'function') {\n var generation = entry.generation;\n // Chromium uses this request to resume suspended metadata startup,\n // even for media outside the viewport. It neither plays nor seeks.\n entry.callbackId = video.requestVideoFrameCallback(function() {\n if (entry.generation !== generation) return;\n entry.callbackId = null;\n entry.presented = !video.seeking && frameSource(video) === entry.source;\n });\n }\n return false;\n }\n function contentQuiet() {\n pendingStrictVideo = null;\n var target = document.querySelector(selector);\n if (!target) {\n releaseVideoFrames();\n return false;\n }\n var videos = waitForMedia ? renderedMatches(target, 'video') : [];\n if (strictVideoFrames) {\n videoFrames.forEach(function(entry) {\n if (videos.indexOf(entry.video) === -1) releaseVideoFrame(entry);\n });\n for (var v = 0; v < videos.length; v++) {\n if (!strictVideoFrameReady(videos[v]) && pendingStrictVideo === null) {\n pendingStrictVideo = 'Video frame not ready for ' + videoSource(videos[v]) +\n ' (readyState=' + videos[v].readyState + ', networkState=' + videos[v].networkState +\n ', seeking=' + videos[v].seeking + ', decodedFrames=' + decodedVideoFrames(videos[v]) +\n ', poster=' + (videos[v].poster || '(none)') + ')';\n }\n }\n if (pendingStrictVideo !== null) {\n quietKey = null;\n return false;\n }\n }\n var images = waitForMedia ? renderedImages(target) : [];\n for (var i = 0; i < images.length; i++) {\n if (images[i].loading === 'lazy') images[i].loading = 'eager';\n }\n for (var j = 0; j < images.length; j++) {\n if (!images[j].complete) {\n // Load/error handlers can replace content without moving its\n // geometry: start a fresh quiet window once they have run.\n quietKey = null;\n return false;\n }\n }\n // A loaded image can still paint as empty space until it decodes\n // (decoding="async" lets the browser paint first). Ask each source\n // to decode once; a failed decode counts as finished.\n var decoding = false;\n for (var d = 0; d < images.length; d++) {\n if (!imageDecoded(images[d])) decoding = true;\n }\n if (decoding) {\n quietKey = null;\n return false;\n }\n // Preserve the existing bounded wait for live screenshots. Strict\n // media readiness above cannot be bypassed by this cap.\n for (var w = 0; !strictVideoFrames && w < videos.length; w++) {\n if (!videoFrameReady(videos[w])) {\n if (videoWaitStartedAt === null) videoWaitStartedAt = now();\n if (now() - videoWaitStartedAt < videoWaitCapMs) {\n quietKey = null;\n return false;\n }\n break;\n }\n }\n var rect = target.getBoundingClientRect();\n var text = target.innerText || '';\n var key = [\n rect.x,\n rect.y,\n rect.width,\n rect.height,\n target.querySelectorAll('*').length,\n text.length,\n images.length\n ].join(',');\n var at = now();\n if (quietKey !== key) {\n quietKey = key;\n quietSince = at;\n return false;\n }\n return at - quietSince >= quietMs;\n }\n\n function paint() {\n if (!runPaint) return Promise.resolve();\n var started = now();\n return new Promise(function(resolve) {\n requestAnimationFrame(function() {\n requestAnimationFrame(function() {\n steps.paint = Math.round(now() - started);\n resolve();\n });\n });\n });\n }\n\n return until('target', function() {\n return document.querySelector(selector) !== null;\n }, stepTimeoutMs, false)\n .then(function() {\n return until('fonts', function() {\n var fonts = document.fonts;\n return !fonts || fonts.status === 'loaded';\n }, stepTimeoutMs, false);\n })\n .then(function() {\n return until('suspense', function() {\n if (!${ht}) return false;\n if (!pendingSelector) return true;\n var target = document.querySelector(selector);\n if (!target) return false;\n return !target.querySelector(pendingSelector);\n }, stepTimeoutMs, false);\n })\n .then(function() {\n return until('content-quiet', contentQuiet, quietTimeoutMs, quietBestEffort);\n })\n .then(paint)\n .then(\n function() {\n releaseVideoFrames();\n return { ok: true, steps: steps, quiet: quiet };\n },\n function(caught) {\n releaseVideoFrames();\n if (caught && caught.ok === false) return caught;\n return failure('paint', String((caught && caught.message) || caught));\n }\n );\n })()\n `}var mt="9",ft="system-1",gt=1;function buildEnvFingerprint(e){const t={os:e.os,browser:`chromium-${e.browserVersion}`,dpr:gt,fontsBundleVersion:ft,kitVersion:mt};return{fingerprint:[t.os,t.browser,`dpr${t.dpr}`,`fonts-${t.fontsBundleVersion}`,`kit-${t.kitVersion}`].join("/"),parts:t}}function isNavigationInterruptedError(e){return/Execution context was destroyed|most likely because of a navigation|Cannot find context with specified id|[Ff]rame was detached|Navigation interrupted|is interrupted by another navigation|Inspected target navigated or closed|Cannot find object with id|context was destroyed/.test(e)}var yt=["--force-color-profile=srgb",`--force-device-scale-factor=${gt}`,"--hide-scrollbars","--disable-lcd-text","--disable-partial-raster"];async function alignCaptureFonts(e){await e.send("Page.setFontFamilies",{fontFamilies:{standard:"Times New Roman",fixed:"darwin"===process.platform?"Menlo":"Courier New",serif:"Times New Roman",sansSerif:"Arial",cursive:"Script",fantasy:"Impact",math:"Latin Modern Math"}})}async function alignCaptureSubframeFonts(e){let t=!1;for(const n of e.frames()){if(n===e.mainFrame())continue;let r;try{r=await e.context().newCDPSession(n)}catch(e){if(e instanceof Error&&e.message.includes("does not have a separate CDP session"))continue;throw e}try{await alignCaptureFonts(r),t=!0}finally{await r.detach()}}return t}async function settlePage(e,t,n={}){const r=n.quietMs??300,s=n.timeoutMs??15e3,i=s*ct.length,a=Date.now()+i;let o=0;for(;;){let c;try{c=await e.evaluate(buildSettleWaitScript({selector:t,pendingSelector:Ke,quietMs:r,strictVideoFrames:!0,stepTimeoutMs:Math.max(1,Math.min(s,a-Date.now()))}))}catch(e){const t=e instanceof Error?e.message:String(e);if(!isNavigationInterruptedError(t))throw e;if(o+=1,Date.now()>=a)throw new Error(`settle: Timeout ${i}ms exceeded; the document was replaced ${o} times while waiting`);continue}for(const e of ct){const t=c.steps[e];void 0!==t&&n.onStep?.(e,t)}if(!c.ok)throw new Error(`settle.${c.step}: ${c.message}`);return}}import{spawn as vt}from"child_process";import{createRequire as Et}from"module";import Tt from"path";var wt=48e4;function isMissingBrowserError(e){const t=e instanceof Error?e.message:String(e);return t.includes("Executable doesn't exist")||/playwright install(?!-deps)/.test(t)}function autoInstallDisabled(){return"1"===process.env.TEMPO_MCP_NO_AUTO_INSTALL}async function installChromium(e,t=vt){const n=Et(import.meta.url),r=Tt.join(Tt.dirname(n.resolve("playwright/package.json")),"cli.js");await new Promise((n,s)=>{const i=t(process.execPath,[r,"install","chromium"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});let a="";const collect=e=>{a=(a+String(e)).slice(-2e3)};i.stdout?.on("data",collect),i.stderr?.on("data",collect);const o=setTimeout(()=>{i.kill("SIGKILL"),s(new Error(`Chromium download timed out after ${wt/6e4} minutes. Run \`npx playwright install chromium\` manually.`))},wt);i.on("error",e=>{clearTimeout(o),s(e)}),i.on("exit",t=>{clearTimeout(o),0===t?(e("Chromium installed."),n()):s(new Error(`playwright install chromium exited with ${t}: ${a.trim().slice(-500)}`))})})}var escapeHtml=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),St="<style>html{width:100%;height:100%;}</style>";function serializeAttributes(e,t=!1){return Object.entries(e).filter(([e])=>t||"style"!==e).map(([e,t])=>` ${e}="${escapeHtml(t)}"`).join("")}function buildBodyStyle(e){const t=(e??"").split(";").map(e=>e.trim()).filter(e=>{const t=e.indexOf(":");if(t<=0)return!1;const n=e.slice(0,t).trim().toLowerCase();return"width"!==n&&"height"!==n});return t.push("width: 100%","height: 100%","margin: 0"),`${t.join("; ")};`}function buildStoryboardHtmlDocument(e,t){const n=t.title?`<title>${escapeHtml(t.title)}</title>`:"",r=/<base[\s>]/i.test(e.headHtml)?"":`<base href="${escapeHtml(t.baseUrl)}">`;return["<!DOCTYPE html>",`<html${serializeAttributes(e.htmlAttributes,t.preserveBody)}>`,"<head>",'<meta charset="utf-8">',n,r,t.preserveBody?"":St,e.headHtml,"</head>",t.preserveBody?e.elementHtml:`<body${serializeAttributes(e.bodyAttributes)} style="${escapeHtml(buildBodyStyle(e.bodyAttributes.style))}">`,t.preserveBody?"":e.elementHtml,t.preserveBody?"":"</body>","</html>"].join("")}import{randomBytes as bt}from"crypto";import{readFile as At,stat as _t}from"fs/promises";import kt from"path";import{createHash as It}from"crypto";import{createRequire as Ct}from"module";var Rt,Pt=25165824,Nt=67108864,Ot=33554432,Dt=Ct(import.meta.url),loadSharp=()=>Rt??=Dt("sharp");function createCaptureImageNormalizer(){const e=new Map;let t=0;return async n=>{if(255!==n[0]||216!==n[1]||255!==n[2])return n;if(n.length>Pt)throw new Error("capture JPEG exceeds the 24 MiB input limit");const r=It("sha256").update(n).digest("hex"),s=e.get(r);if(s)return e.delete(r),e.set(r,s),s;const i=loadSharp(),a=await i(n,{limitInputPixels:Nt}).keepExif().png().toBuffer();if(e.has(r))return e.get(r);if(a.length<=Ot){for(;t+a.length>Ot;){const n=e.keys().next().value;t-=e.get(n).length,e.delete(n)}e.set(r,a),t+=a.length}return a}}async function installCaptureImages(e,t){const n=await e.context().newCDPSession(e),r=new Map,s=new Set,i=new Map;let a=!1;const handle=async e=>{const{requestId:s,networkId:o,request:c,responseStatusCode:l,responseHeaders:d=[]}=e,u={canceled:!1};o&&i.set(o,u);try{const e=d.find(e=>"content-type"===e.name.toLowerCase())?.value.split(";",1)[0].trim().toLowerCase(),r="image/jpeg"===e||"image/jpg"===e||"application/octet-stream"===e||!e;if(200!==l||!r)return void await n.send("Fetch.continueRequest",{requestId:s});const i=Number(d.find(e=>"content-length"===e.name.toLowerCase())?.value);if(i>Pt)throw new Error("capture image exceeds the 24 MiB input limit");let a;const o=await Promise.race([n.send("Fetch.getResponseBody",{requestId:s}),new Promise((e,t)=>{a=setTimeout(()=>t(new Error("capture image download exceeded 30 seconds")),3e4)}),new Promise((e,t)=>{u.cancelBody=()=>t(new Error("capture image request was canceled")),u.canceled&&u.cancelBody()})]).finally(()=>{clearTimeout(a),u.cancelBody=void 0}),c=Buffer.from(o.body,o.base64Encoded?"base64":"utf8"),p=await t(c);if(p===c)return void await n.send("Fetch.continueRequest",{requestId:s});const h=new Set(["content-type","content-encoding","content-length","etag","content-md5","digest","content-digest","repr-digest"]),m=d.filter(e=>!h.has(e.name.toLowerCase()));m.push({name:"Content-Type",value:"image/png"}),await n.send("Fetch.fulfillRequest",{requestId:s,responseCode:l,responseHeaders:m,body:p.toString("base64")})}catch(e){a||u.canceled||r.set(c.url,String(e)),await n.send("Fetch.failRequest",{requestId:s,errorReason:"Failed"}).catch(()=>{})}finally{o&&i.get(o)===u&&i.delete(o)}};return n.on("Network.loadingFailed",e=>{if(!e.canceled)return;const t=i.get(e.requestId);t&&(t.canceled=!0,t.cancelBody?.())}),n.on("Fetch.requestPaused",e=>{const t=handle(e);s.add(t),t.finally(()=>s.delete(t)).catch(()=>{})}),await n.send("Network.enable"),await n.send("Fetch.enable",{patterns:[{resourceType:"Image",requestStage:"Response"}]}),{assertHealthy(){if(r.size)throw new Error(`capture image normalization failed: ${[...r].map(([e,t])=>`${e}: ${t}`).join("; ")}`)},async dispose(){a=!0,await n.send("Fetch.disable").catch(()=>{}),await n.detach().catch(()=>{}),await Promise.allSettled([...s])}}}import Lt from"path";import{realpath as Mt,stat as xt}from"fs/promises";import Ft from"oxc-parser/src-js/generated/visit/keys.js";var Bt=Ft;Bt.default;import{parseSync as Ht}from"oxc-parser";function sourceVersionHash(e){let t=5381,n=0;for(let r=0;r<e.length;r++){const s=e.charCodeAt(r);t=(t<<5)+t^s,n=s+(n<<6)+(n<<16)-n|0}return toHex8(t)+toHex8(n)}function toHex8(e){return(e>>>0).toString(16).padStart(8,"0")}import{parseSync as Ut}from"oxc-parser";var jt,$t=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),Gt="�";!function(e){e[e.EOF=-1]="EOF",e[e.NULL=0]="NULL",e[e.TABULATION=9]="TABULATION",e[e.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",e[e.LINE_FEED=10]="LINE_FEED",e[e.FORM_FEED=12]="FORM_FEED",e[e.SPACE=32]="SPACE",e[e.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",e[e.QUOTATION_MARK=34]="QUOTATION_MARK",e[e.AMPERSAND=38]="AMPERSAND",e[e.APOSTROPHE=39]="APOSTROPHE",e[e.HYPHEN_MINUS=45]="HYPHEN_MINUS",e[e.SOLIDUS=47]="SOLIDUS",e[e.DIGIT_0=48]="DIGIT_0",e[e.DIGIT_9=57]="DIGIT_9",e[e.SEMICOLON=59]="SEMICOLON",e[e.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",e[e.EQUALS_SIGN=61]="EQUALS_SIGN",e[e.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.LATIN_CAPITAL_A=65]="LATIN_CAPITAL_A",e[e.LATIN_CAPITAL_Z=90]="LATIN_CAPITAL_Z",e[e.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",e[e.GRAVE_ACCENT=96]="GRAVE_ACCENT",e[e.LATIN_SMALL_A=97]="LATIN_SMALL_A",e[e.LATIN_SMALL_Z=122]="LATIN_SMALL_Z"}(jt||(jt={}));var qt,Wt={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function isSurrogate(e){return e>=55296&&e<=57343}function isSurrogatePair(e){return e>=56320&&e<=57343}function getSurrogatePairCodePoint(e,t){return 1024*(e-55296)+9216+t}function isControlCodePoint(e){return 32!==e&&10!==e&&13!==e&&9!==e&&12!==e&&e>=1&&e<=31||e>=127&&e<=159}function isUndefinedCodePoint(e){return e>=64976&&e<=65007||$t.has(e)}!function(e){e.controlCharacterInInputStream="control-character-in-input-stream",e.noncharacterInInputStream="noncharacter-in-input-stream",e.surrogateInInputStream="surrogate-in-input-stream",e.nonVoidHtmlElementStartTagWithTrailingSolidus="non-void-html-element-start-tag-with-trailing-solidus",e.endTagWithAttributes="end-tag-with-attributes",e.endTagWithTrailingSolidus="end-tag-with-trailing-solidus",e.unexpectedSolidusInTag="unexpected-solidus-in-tag",e.unexpectedNullCharacter="unexpected-null-character",e.unexpectedQuestionMarkInsteadOfTagName="unexpected-question-mark-instead-of-tag-name",e.invalidFirstCharacterOfTagName="invalid-first-character-of-tag-name",e.unexpectedEqualsSignBeforeAttributeName="unexpected-equals-sign-before-attribute-name",e.missingEndTagName="missing-end-tag-name",e.unexpectedCharacterInAttributeName="unexpected-character-in-attribute-name",e.unknownNamedCharacterReference="unknown-named-character-reference",e.missingSemicolonAfterCharacterReference="missing-semicolon-after-character-reference",e.unexpectedCharacterAfterDoctypeSystemIdentifier="unexpected-character-after-doctype-system-identifier",e.unexpectedCharacterInUnquotedAttributeValue="unexpected-character-in-unquoted-attribute-value",e.eofBeforeTagName="eof-before-tag-name",e.eofInTag="eof-in-tag",e.missingAttributeValue="missing-attribute-value",e.missingWhitespaceBetweenAttributes="missing-whitespace-between-attributes",e.missingWhitespaceAfterDoctypePublicKeyword="missing-whitespace-after-doctype-public-keyword",e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers="missing-whitespace-between-doctype-public-and-system-identifiers",e.missingWhitespaceAfterDoctypeSystemKeyword="missing-whitespace-after-doctype-system-keyword",e.missingQuoteBeforeDoctypePublicIdentifier="missing-quote-before-doctype-public-identifier",e.missingQuoteBeforeDoctypeSystemIdentifier="missing-quote-before-doctype-system-identifier",e.missingDoctypePublicIdentifier="missing-doctype-public-identifier",e.missingDoctypeSystemIdentifier="missing-doctype-system-identifier",e.abruptDoctypePublicIdentifier="abrupt-doctype-public-identifier",e.abruptDoctypeSystemIdentifier="abrupt-doctype-system-identifier",e.cdataInHtmlContent="cdata-in-html-content",e.incorrectlyOpenedComment="incorrectly-opened-comment",e.eofInScriptHtmlCommentLikeText="eof-in-script-html-comment-like-text",e.eofInDoctype="eof-in-doctype",e.nestedComment="nested-comment",e.abruptClosingOfEmptyComment="abrupt-closing-of-empty-comment",e.eofInComment="eof-in-comment",e.incorrectlyClosedComment="incorrectly-closed-comment",e.eofInCdata="eof-in-cdata",e.absenceOfDigitsInNumericCharacterReference="absence-of-digits-in-numeric-character-reference",e.nullCharacterReference="null-character-reference",e.surrogateCharacterReference="surrogate-character-reference",e.characterReferenceOutsideUnicodeRange="character-reference-outside-unicode-range",e.controlCharacterReference="control-character-reference",e.noncharacterCharacterReference="noncharacter-character-reference",e.missingWhitespaceBeforeDoctypeName="missing-whitespace-before-doctype-name",e.missingDoctypeName="missing-doctype-name",e.invalidCharacterSequenceAfterDoctypeName="invalid-character-sequence-after-doctype-name",e.duplicateAttribute="duplicate-attribute",e.nonConformingDoctype="non-conforming-doctype",e.missingDoctype="missing-doctype",e.misplacedDoctype="misplaced-doctype",e.endTagWithoutMatchingOpenElement="end-tag-without-matching-open-element",e.closingOfElementWithOpenChildElements="closing-of-element-with-open-child-elements",e.disallowedContentInNoscriptInHead="disallowed-content-in-noscript-in-head",e.openElementsLeftAfterEof="open-elements-left-after-eof",e.abandonedHeadElementChild="abandoned-head-element-child",e.misplacedStartTagForHeadElement="misplaced-start-tag-for-head-element",e.nestedNoscriptInHead="nested-noscript-in-head",e.eofInElementThatCanContainOnlyText="eof-in-element-that-can-contain-only-text"}(qt||(qt={}));var Vt,Kt=65536,Yt=class{constructor(e){this.handler=e,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=!1,this.lastChunkWritten=!1,this.endOfChunkHit=!1,this.bufferWaterline=Kt,this.isEol=!1,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1}get col(){return this.pos-this.lineStartPos+Number(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(e,t){const{line:n,col:r,offset:s}=this,i=r+t,a=s+t;return{code:e,startLine:n,endLine:n,startCol:i,endCol:i,startOffset:a,endOffset:a}}_err(e){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(e,0)))}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos}_processSurrogate(e){if(this.pos!==this.html.length-1){const t=this.html.charCodeAt(this.pos+1);if(isSurrogatePair(t))return this.pos++,this._addGap(),getSurrogatePairCodePoint(e,t)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,jt.EOF;return this._err(qt.surrogateInInputStream),e}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0)}write(e,t){this.html.length>0?this.html+=e:this.html=e,this.endOfChunkHit=!1,this.lastChunkWritten=t}insertHtmlAtCurrentPos(e){this.html=this.html.substring(0,this.pos+1)+e+this.html.substring(this.pos+1),this.endOfChunkHit=!1}startsWith(e,t){if(this.pos+e.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,!1;if(t)return this.html.startsWith(e,this.pos);for(let t=0;t<e.length;t++){const n=32|this.html.charCodeAt(this.pos+t);if(n!==e.charCodeAt(t))return!1}return!0}peek(e){const t=this.pos+e;if(t>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,jt.EOF;const n=this.html.charCodeAt(t);return n===jt.CARRIAGE_RETURN?jt.LINE_FEED:n}advance(){if(this.pos++,this.isEol&&(this.isEol=!1,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,jt.EOF;let e=this.html.charCodeAt(this.pos);if(e===jt.CARRIAGE_RETURN)return this.isEol=!0,this.skipNextNewLine=!0,jt.LINE_FEED;if(e===jt.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine))return this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance();this.skipNextNewLine=!1,isSurrogate(e)&&(e=this._processSurrogate(e));const t=null===this.handler.onParseError||e>31&&e<127||e===jt.LINE_FEED||e===jt.CARRIAGE_RETURN||e>159&&e<64976;return t||this._checkForProblematicCharacters(e),e}_checkForProblematicCharacters(e){isControlCodePoint(e)?this._err(qt.controlCharacterInInputStream):isUndefinedCodePoint(e)&&this._err(qt.noncharacterInInputStream)}retreat(e){for(this.pos-=e;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=!1}};function getTokenAttr(e,t){for(let n=e.attrs.length-1;n>=0;n--)if(e.attrs[n].name===t)return e.attrs[n].value;return null}!function(e){e[e.CHARACTER=0]="CHARACTER",e[e.NULL_CHARACTER=1]="NULL_CHARACTER",e[e.WHITESPACE_CHARACTER=2]="WHITESPACE_CHARACTER",e[e.START_TAG=3]="START_TAG",e[e.END_TAG=4]="END_TAG",e[e.COMMENT=5]="COMMENT",e[e.DOCTYPE=6]="DOCTYPE",e[e.EOF=7]="EOF",e[e.HIBERNATION=8]="HIBERNATION"}(Vt||(Vt={}));var zt,Jt,Qt=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms„‹•˜¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(e=>e.charCodeAt(0))),Xt=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]);zt=String.fromCodePoint;function replaceCodePoint(e){var t;return e>=55296&&e<=57343||e>1114111?65533:null!==(t=Xt.get(e))&&void 0!==t?t:e}!function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"}(Jt||(Jt={}));var Zt,en,tn,nn=32;function isNumber(e){return e>=Jt.ZERO&&e<=Jt.NINE}function isHexadecimalCharacter(e){return e>=Jt.UPPER_A&&e<=Jt.UPPER_F||e>=Jt.LOWER_A&&e<=Jt.LOWER_F}function isAsciiAlphaNumeric(e){return e>=Jt.UPPER_A&&e<=Jt.UPPER_Z||e>=Jt.LOWER_A&&e<=Jt.LOWER_Z||isNumber(e)}function isEntityInAttributeInvalidEnd(e){return e===Jt.EQUALS||isAsciiAlphaNumeric(e)}!function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"}(Zt||(Zt={})),function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"}(en||(en={})),function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"}(tn||(tn={}));var rn,sn,an,on,cn,ln=class{constructor(e,t,n){this.decodeTree=e,this.emitCodePoint=t,this.errors=n,this.state=en.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=tn.Strict}startEntity(e){this.decodeMode=e,this.state=en.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(e,t){switch(this.state){case en.EntityStart:return e.charCodeAt(t)===Jt.NUM?(this.state=en.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1)):(this.state=en.NamedEntity,this.stateNamedEntity(e,t));case en.NumericStart:return this.stateNumericStart(e,t);case en.NumericDecimal:return this.stateNumericDecimal(e,t);case en.NumericHex:return this.stateNumericHex(e,t);case en.NamedEntity:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){return t>=e.length?-1:(e.charCodeAt(t)|nn)===Jt.LOWER_X?(this.state=en.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1)):(this.state=en.NumericDecimal,this.stateNumericDecimal(e,t))}addToNumericResult(e,t,n,r){if(t!==n){const s=n-t;this.result=this.result*Math.pow(r,s)+Number.parseInt(e.substr(t,s),r),this.consumed+=s}}stateNumericHex(e,t){const n=t;for(;t<e.length;){const r=e.charCodeAt(t);if(!isNumber(r)&&!isHexadecimalCharacter(r))return this.addToNumericResult(e,n,t,16),this.emitNumericEntity(r,3);t+=1}return this.addToNumericResult(e,n,t,16),-1}stateNumericDecimal(e,t){const n=t;for(;t<e.length;){const r=e.charCodeAt(t);if(!isNumber(r))return this.addToNumericResult(e,n,t,10),this.emitNumericEntity(r,2);t+=1}return this.addToNumericResult(e,n,t,10),-1}emitNumericEntity(e,t){var n;if(this.consumed<=t)return null===(n=this.errors)||void 0===n||n.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===Jt.SEMI)this.consumed+=1;else if(this.decodeMode===tn.Strict)return 0;return this.emitCodePoint(replaceCodePoint(this.result),this.consumed),this.errors&&(e!==Jt.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(e,t){const{decodeTree:n}=this;let r=n[this.treeIndex],s=(r&Zt.VALUE_LENGTH)>>14;for(;t<e.length;t++,this.excess++){const i=e.charCodeAt(t);if(this.treeIndex=determineBranch(n,r,this.treeIndex+Math.max(1,s),i),this.treeIndex<0)return 0===this.result||this.decodeMode===tn.Attribute&&(0===s||isEntityInAttributeInvalidEnd(i))?0:this.emitNotTerminatedNamedEntity();if(r=n[this.treeIndex],s=(r&Zt.VALUE_LENGTH)>>14,0!==s){if(i===Jt.SEMI)return this.emitNamedEntityData(this.treeIndex,s,this.consumed+this.excess);this.decodeMode!==tn.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var e;const{result:t,decodeTree:n}=this,r=(n[t]&Zt.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,r,this.consumed),null===(e=this.errors)||void 0===e||e.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,n){const{decodeTree:r}=this;return this.emitCodePoint(1===t?r[e]&~Zt.VALUE_LENGTH:r[e+1],n),3===t&&this.emitCodePoint(r[e+2],n),n}end(){var e;switch(this.state){case en.NamedEntity:return 0===this.result||this.decodeMode===tn.Attribute&&this.result!==this.treeIndex?0:this.emitNotTerminatedNamedEntity();case en.NumericDecimal:return this.emitNumericEntity(0,2);case en.NumericHex:return this.emitNumericEntity(0,3);case en.NumericStart:return null===(e=this.errors)||void 0===e||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case en.EntityStart:return 0}}};function determineBranch(e,t,n,r){const s=(t&Zt.BRANCH_LENGTH)>>7,i=t&Zt.JUMP_TABLE;if(0===s)return 0!==i&&r===i?n:-1;if(i){const t=r-i;return t<0||t>=s?-1:e[n+t]-1}let a=n,o=a+s-1;for(;a<=o;){const t=a+o>>>1,n=e[t];if(n<r)a=t+1;else{if(!(n>r))return e[t+s];o=t-1}}return-1}!function(e){e.HTML="http://www.w3.org/1999/xhtml",e.MATHML="http://www.w3.org/1998/Math/MathML",e.SVG="http://www.w3.org/2000/svg",e.XLINK="http://www.w3.org/1999/xlink",e.XML="http://www.w3.org/XML/1998/namespace",e.XMLNS="http://www.w3.org/2000/xmlns/"}(rn||(rn={})),function(e){e.TYPE="type",e.ACTION="action",e.ENCODING="encoding",e.PROMPT="prompt",e.NAME="name",e.COLOR="color",e.FACE="face",e.SIZE="size"}(sn||(sn={})),function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks"}(an||(an={})),function(e){e.A="a",e.ADDRESS="address",e.ANNOTATION_XML="annotation-xml",e.APPLET="applet",e.AREA="area",e.ARTICLE="article",e.ASIDE="aside",e.B="b",e.BASE="base",e.BASEFONT="basefont",e.BGSOUND="bgsound",e.BIG="big",e.BLOCKQUOTE="blockquote",e.BODY="body",e.BR="br",e.BUTTON="button",e.CAPTION="caption",e.CENTER="center",e.CODE="code",e.COL="col",e.COLGROUP="colgroup",e.DD="dd",e.DESC="desc",e.DETAILS="details",e.DIALOG="dialog",e.DIR="dir",e.DIV="div",e.DL="dl",e.DT="dt",e.EM="em",e.EMBED="embed",e.FIELDSET="fieldset",e.FIGCAPTION="figcaption",e.FIGURE="figure",e.FONT="font",e.FOOTER="footer",e.FOREIGN_OBJECT="foreignObject",e.FORM="form",e.FRAME="frame",e.FRAMESET="frameset",e.H1="h1",e.H2="h2",e.H3="h3",e.H4="h4",e.H5="h5",e.H6="h6",e.HEAD="head",e.HEADER="header",e.HGROUP="hgroup",e.HR="hr",e.HTML="html",e.I="i",e.IMG="img",e.IMAGE="image",e.INPUT="input",e.IFRAME="iframe",e.KEYGEN="keygen",e.LABEL="label",e.LI="li",e.LINK="link",e.LISTING="listing",e.MAIN="main",e.MALIGNMARK="malignmark",e.MARQUEE="marquee",e.MATH="math",e.MENU="menu",e.META="meta",e.MGLYPH="mglyph",e.MI="mi",e.MO="mo",e.MN="mn",e.MS="ms",e.MTEXT="mtext",e.NAV="nav",e.NOBR="nobr",e.NOFRAMES="noframes",e.NOEMBED="noembed",e.NOSCRIPT="noscript",e.OBJECT="object",e.OL="ol",e.OPTGROUP="optgroup",e.OPTION="option",e.P="p",e.PARAM="param",e.PLAINTEXT="plaintext",e.PRE="pre",e.RB="rb",e.RP="rp",e.RT="rt",e.RTC="rtc",e.RUBY="ruby",e.S="s",e.SCRIPT="script",e.SEARCH="search",e.SECTION="section",e.SELECT="select",e.SOURCE="source",e.SMALL="small",e.SPAN="span",e.STRIKE="strike",e.STRONG="strong",e.STYLE="style",e.SUB="sub",e.SUMMARY="summary",e.SUP="sup",e.TABLE="table",e.TBODY="tbody",e.TEMPLATE="template",e.TEXTAREA="textarea",e.TFOOT="tfoot",e.TD="td",e.TH="th",e.THEAD="thead",e.TITLE="title",e.TR="tr",e.TRACK="track",e.TT="tt",e.U="u",e.UL="ul",e.SVG="svg",e.VAR="var",e.WBR="wbr",e.XMP="xmp"}(on||(on={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.A=1]="A",e[e.ADDRESS=2]="ADDRESS",e[e.ANNOTATION_XML=3]="ANNOTATION_XML",e[e.APPLET=4]="APPLET",e[e.AREA=5]="AREA",e[e.ARTICLE=6]="ARTICLE",e[e.ASIDE=7]="ASIDE",e[e.B=8]="B",e[e.BASE=9]="BASE",e[e.BASEFONT=10]="BASEFONT",e[e.BGSOUND=11]="BGSOUND",e[e.BIG=12]="BIG",e[e.BLOCKQUOTE=13]="BLOCKQUOTE",e[e.BODY=14]="BODY",e[e.BR=15]="BR",e[e.BUTTON=16]="BUTTON",e[e.CAPTION=17]="CAPTION",e[e.CENTER=18]="CENTER",e[e.CODE=19]="CODE",e[e.COL=20]="COL",e[e.COLGROUP=21]="COLGROUP",e[e.DD=22]="DD",e[e.DESC=23]="DESC",e[e.DETAILS=24]="DETAILS",e[e.DIALOG=25]="DIALOG",e[e.DIR=26]="DIR",e[e.DIV=27]="DIV",e[e.DL=28]="DL",e[e.DT=29]="DT",e[e.EM=30]="EM",e[e.EMBED=31]="EMBED",e[e.FIELDSET=32]="FIELDSET",e[e.FIGCAPTION=33]="FIGCAPTION",e[e.FIGURE=34]="FIGURE",e[e.FONT=35]="FONT",e[e.FOOTER=36]="FOOTER",e[e.FOREIGN_OBJECT=37]="FOREIGN_OBJECT",e[e.FORM=38]="FORM",e[e.FRAME=39]="FRAME",e[e.FRAMESET=40]="FRAMESET",e[e.H1=41]="H1",e[e.H2=42]="H2",e[e.H3=43]="H3",e[e.H4=44]="H4",e[e.H5=45]="H5",e[e.H6=46]="H6",e[e.HEAD=47]="HEAD",e[e.HEADER=48]="HEADER",e[e.HGROUP=49]="HGROUP",e[e.HR=50]="HR",e[e.HTML=51]="HTML",e[e.I=52]="I",e[e.IMG=53]="IMG",e[e.IMAGE=54]="IMAGE",e[e.INPUT=55]="INPUT",e[e.IFRAME=56]="IFRAME",e[e.KEYGEN=57]="KEYGEN",e[e.LABEL=58]="LABEL",e[e.LI=59]="LI",e[e.LINK=60]="LINK",e[e.LISTING=61]="LISTING",e[e.MAIN=62]="MAIN",e[e.MALIGNMARK=63]="MALIGNMARK",e[e.MARQUEE=64]="MARQUEE",e[e.MATH=65]="MATH",e[e.MENU=66]="MENU",e[e.META=67]="META",e[e.MGLYPH=68]="MGLYPH",e[e.MI=69]="MI",e[e.MO=70]="MO",e[e.MN=71]="MN",e[e.MS=72]="MS",e[e.MTEXT=73]="MTEXT",e[e.NAV=74]="NAV",e[e.NOBR=75]="NOBR",e[e.NOFRAMES=76]="NOFRAMES",e[e.NOEMBED=77]="NOEMBED",e[e.NOSCRIPT=78]="NOSCRIPT",e[e.OBJECT=79]="OBJECT",e[e.OL=80]="OL",e[e.OPTGROUP=81]="OPTGROUP",e[e.OPTION=82]="OPTION",e[e.P=83]="P",e[e.PARAM=84]="PARAM",e[e.PLAINTEXT=85]="PLAINTEXT",e[e.PRE=86]="PRE",e[e.RB=87]="RB",e[e.RP=88]="RP",e[e.RT=89]="RT",e[e.RTC=90]="RTC",e[e.RUBY=91]="RUBY",e[e.S=92]="S",e[e.SCRIPT=93]="SCRIPT",e[e.SEARCH=94]="SEARCH",e[e.SECTION=95]="SECTION",e[e.SELECT=96]="SELECT",e[e.SOURCE=97]="SOURCE",e[e.SMALL=98]="SMALL",e[e.SPAN=99]="SPAN",e[e.STRIKE=100]="STRIKE",e[e.STRONG=101]="STRONG",e[e.STYLE=102]="STYLE",e[e.SUB=103]="SUB",e[e.SUMMARY=104]="SUMMARY",e[e.SUP=105]="SUP",e[e.TABLE=106]="TABLE",e[e.TBODY=107]="TBODY",e[e.TEMPLATE=108]="TEMPLATE",e[e.TEXTAREA=109]="TEXTAREA",e[e.TFOOT=110]="TFOOT",e[e.TD=111]="TD",e[e.TH=112]="TH",e[e.THEAD=113]="THEAD",e[e.TITLE=114]="TITLE",e[e.TR=115]="TR",e[e.TRACK=116]="TRACK",e[e.TT=117]="TT",e[e.U=118]="U",e[e.UL=119]="UL",e[e.SVG=120]="SVG",e[e.VAR=121]="VAR",e[e.WBR=122]="WBR",e[e.XMP=123]="XMP"}(cn||(cn={}));var dn=new Map([[on.A,cn.A],[on.ADDRESS,cn.ADDRESS],[on.ANNOTATION_XML,cn.ANNOTATION_XML],[on.APPLET,cn.APPLET],[on.AREA,cn.AREA],[on.ARTICLE,cn.ARTICLE],[on.ASIDE,cn.ASIDE],[on.B,cn.B],[on.BASE,cn.BASE],[on.BASEFONT,cn.BASEFONT],[on.BGSOUND,cn.BGSOUND],[on.BIG,cn.BIG],[on.BLOCKQUOTE,cn.BLOCKQUOTE],[on.BODY,cn.BODY],[on.BR,cn.BR],[on.BUTTON,cn.BUTTON],[on.CAPTION,cn.CAPTION],[on.CENTER,cn.CENTER],[on.CODE,cn.CODE],[on.COL,cn.COL],[on.COLGROUP,cn.COLGROUP],[on.DD,cn.DD],[on.DESC,cn.DESC],[on.DETAILS,cn.DETAILS],[on.DIALOG,cn.DIALOG],[on.DIR,cn.DIR],[on.DIV,cn.DIV],[on.DL,cn.DL],[on.DT,cn.DT],[on.EM,cn.EM],[on.EMBED,cn.EMBED],[on.FIELDSET,cn.FIELDSET],[on.FIGCAPTION,cn.FIGCAPTION],[on.FIGURE,cn.FIGURE],[on.FONT,cn.FONT],[on.FOOTER,cn.FOOTER],[on.FOREIGN_OBJECT,cn.FOREIGN_OBJECT],[on.FORM,cn.FORM],[on.FRAME,cn.FRAME],[on.FRAMESET,cn.FRAMESET],[on.H1,cn.H1],[on.H2,cn.H2],[on.H3,cn.H3],[on.H4,cn.H4],[on.H5,cn.H5],[on.H6,cn.H6],[on.HEAD,cn.HEAD],[on.HEADER,cn.HEADER],[on.HGROUP,cn.HGROUP],[on.HR,cn.HR],[on.HTML,cn.HTML],[on.I,cn.I],[on.IMG,cn.IMG],[on.IMAGE,cn.IMAGE],[on.INPUT,cn.INPUT],[on.IFRAME,cn.IFRAME],[on.KEYGEN,cn.KEYGEN],[on.LABEL,cn.LABEL],[on.LI,cn.LI],[on.LINK,cn.LINK],[on.LISTING,cn.LISTING],[on.MAIN,cn.MAIN],[on.MALIGNMARK,cn.MALIGNMARK],[on.MARQUEE,cn.MARQUEE],[on.MATH,cn.MATH],[on.MENU,cn.MENU],[on.META,cn.META],[on.MGLYPH,cn.MGLYPH],[on.MI,cn.MI],[on.MO,cn.MO],[on.MN,cn.MN],[on.MS,cn.MS],[on.MTEXT,cn.MTEXT],[on.NAV,cn.NAV],[on.NOBR,cn.NOBR],[on.NOFRAMES,cn.NOFRAMES],[on.NOEMBED,cn.NOEMBED],[on.NOSCRIPT,cn.NOSCRIPT],[on.OBJECT,cn.OBJECT],[on.OL,cn.OL],[on.OPTGROUP,cn.OPTGROUP],[on.OPTION,cn.OPTION],[on.P,cn.P],[on.PARAM,cn.PARAM],[on.PLAINTEXT,cn.PLAINTEXT],[on.PRE,cn.PRE],[on.RB,cn.RB],[on.RP,cn.RP],[on.RT,cn.RT],[on.RTC,cn.RTC],[on.RUBY,cn.RUBY],[on.S,cn.S],[on.SCRIPT,cn.SCRIPT],[on.SEARCH,cn.SEARCH],[on.SECTION,cn.SECTION],[on.SELECT,cn.SELECT],[on.SOURCE,cn.SOURCE],[on.SMALL,cn.SMALL],[on.SPAN,cn.SPAN],[on.STRIKE,cn.STRIKE],[on.STRONG,cn.STRONG],[on.STYLE,cn.STYLE],[on.SUB,cn.SUB],[on.SUMMARY,cn.SUMMARY],[on.SUP,cn.SUP],[on.TABLE,cn.TABLE],[on.TBODY,cn.TBODY],[on.TEMPLATE,cn.TEMPLATE],[on.TEXTAREA,cn.TEXTAREA],[on.TFOOT,cn.TFOOT],[on.TD,cn.TD],[on.TH,cn.TH],[on.THEAD,cn.THEAD],[on.TITLE,cn.TITLE],[on.TR,cn.TR],[on.TRACK,cn.TRACK],[on.TT,cn.TT],[on.U,cn.U],[on.UL,cn.UL],[on.SVG,cn.SVG],[on.VAR,cn.VAR],[on.WBR,cn.WBR],[on.XMP,cn.XMP]]);function getTagID(e){var t;return null!==(t=dn.get(e))&&void 0!==t?t:cn.UNKNOWN}var un,pn=cn,hn={[rn.HTML]:new Set([pn.ADDRESS,pn.APPLET,pn.AREA,pn.ARTICLE,pn.ASIDE,pn.BASE,pn.BASEFONT,pn.BGSOUND,pn.BLOCKQUOTE,pn.BODY,pn.BR,pn.BUTTON,pn.CAPTION,pn.CENTER,pn.COL,pn.COLGROUP,pn.DD,pn.DETAILS,pn.DIR,pn.DIV,pn.DL,pn.DT,pn.EMBED,pn.FIELDSET,pn.FIGCAPTION,pn.FIGURE,pn.FOOTER,pn.FORM,pn.FRAME,pn.FRAMESET,pn.H1,pn.H2,pn.H3,pn.H4,pn.H5,pn.H6,pn.HEAD,pn.HEADER,pn.HGROUP,pn.HR,pn.HTML,pn.IFRAME,pn.IMG,pn.INPUT,pn.LI,pn.LINK,pn.LISTING,pn.MAIN,pn.MARQUEE,pn.MENU,pn.META,pn.NAV,pn.NOEMBED,pn.NOFRAMES,pn.NOSCRIPT,pn.OBJECT,pn.OL,pn.P,pn.PARAM,pn.PLAINTEXT,pn.PRE,pn.SCRIPT,pn.SECTION,pn.SELECT,pn.SOURCE,pn.STYLE,pn.SUMMARY,pn.TABLE,pn.TBODY,pn.TD,pn.TEMPLATE,pn.TEXTAREA,pn.TFOOT,pn.TH,pn.THEAD,pn.TITLE,pn.TR,pn.TRACK,pn.UL,pn.WBR,pn.XMP]),[rn.MATHML]:new Set([pn.MI,pn.MO,pn.MN,pn.MS,pn.MTEXT,pn.ANNOTATION_XML]),[rn.SVG]:new Set([pn.TITLE,pn.FOREIGN_OBJECT,pn.DESC]),[rn.XLINK]:new Set,[rn.XML]:new Set,[rn.XMLNS]:new Set},mn=new Set([pn.H1,pn.H2,pn.H3,pn.H4,pn.H5,pn.H6]);on.STYLE,on.SCRIPT,on.XMP,on.IFRAME,on.NOEMBED,on.NOFRAMES,on.PLAINTEXT;!function(e){e[e.DATA=0]="DATA",e[e.RCDATA=1]="RCDATA",e[e.RAWTEXT=2]="RAWTEXT",e[e.SCRIPT_DATA=3]="SCRIPT_DATA",e[e.PLAINTEXT=4]="PLAINTEXT",e[e.TAG_OPEN=5]="TAG_OPEN",e[e.END_TAG_OPEN=6]="END_TAG_OPEN",e[e.TAG_NAME=7]="TAG_NAME",e[e.RCDATA_LESS_THAN_SIGN=8]="RCDATA_LESS_THAN_SIGN",e[e.RCDATA_END_TAG_OPEN=9]="RCDATA_END_TAG_OPEN",e[e.RCDATA_END_TAG_NAME=10]="RCDATA_END_TAG_NAME",e[e.RAWTEXT_LESS_THAN_SIGN=11]="RAWTEXT_LESS_THAN_SIGN",e[e.RAWTEXT_END_TAG_OPEN=12]="RAWTEXT_END_TAG_OPEN",e[e.RAWTEXT_END_TAG_NAME=13]="RAWTEXT_END_TAG_NAME",e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]="SCRIPT_DATA_LESS_THAN_SIGN",e[e.SCRIPT_DATA_END_TAG_OPEN=15]="SCRIPT_DATA_END_TAG_OPEN",e[e.SCRIPT_DATA_END_TAG_NAME=16]="SCRIPT_DATA_END_TAG_NAME",e[e.SCRIPT_DATA_ESCAPE_START=17]="SCRIPT_DATA_ESCAPE_START",e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]="SCRIPT_DATA_ESCAPE_START_DASH",e[e.SCRIPT_DATA_ESCAPED=19]="SCRIPT_DATA_ESCAPED",e[e.SCRIPT_DATA_ESCAPED_DASH=20]="SCRIPT_DATA_ESCAPED_DASH",e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]="SCRIPT_DATA_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START",e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]="SCRIPT_DATA_DOUBLE_ESCAPED",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END",e[e.BEFORE_ATTRIBUTE_NAME=31]="BEFORE_ATTRIBUTE_NAME",e[e.ATTRIBUTE_NAME=32]="ATTRIBUTE_NAME",e[e.AFTER_ATTRIBUTE_NAME=33]="AFTER_ATTRIBUTE_NAME",e[e.BEFORE_ATTRIBUTE_VALUE=34]="BEFORE_ATTRIBUTE_VALUE",e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED",e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED",e[e.ATTRIBUTE_VALUE_UNQUOTED=37]="ATTRIBUTE_VALUE_UNQUOTED",e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]="AFTER_ATTRIBUTE_VALUE_QUOTED",e[e.SELF_CLOSING_START_TAG=39]="SELF_CLOSING_START_TAG",e[e.BOGUS_COMMENT=40]="BOGUS_COMMENT",e[e.MARKUP_DECLARATION_OPEN=41]="MARKUP_DECLARATION_OPEN",e[e.COMMENT_START=42]="COMMENT_START",e[e.COMMENT_START_DASH=43]="COMMENT_START_DASH",e[e.COMMENT=44]="COMMENT",e[e.COMMENT_LESS_THAN_SIGN=45]="COMMENT_LESS_THAN_SIGN",e[e.COMMENT_LESS_THAN_SIGN_BANG=46]="COMMENT_LESS_THAN_SIGN_BANG",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH",e[e.COMMENT_END_DASH=49]="COMMENT_END_DASH",e[e.COMMENT_END=50]="COMMENT_END",e[e.COMMENT_END_BANG=51]="COMMENT_END_BANG",e[e.DOCTYPE=52]="DOCTYPE",e[e.BEFORE_DOCTYPE_NAME=53]="BEFORE_DOCTYPE_NAME",e[e.DOCTYPE_NAME=54]="DOCTYPE_NAME",e[e.AFTER_DOCTYPE_NAME=55]="AFTER_DOCTYPE_NAME",e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD",e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER",e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER",e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS",e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD",e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER",e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER",e[e.BOGUS_DOCTYPE=67]="BOGUS_DOCTYPE",e[e.CDATA_SECTION=68]="CDATA_SECTION",e[e.CDATA_SECTION_BRACKET=69]="CDATA_SECTION_BRACKET",e[e.CDATA_SECTION_END=70]="CDATA_SECTION_END",e[e.CHARACTER_REFERENCE=71]="CHARACTER_REFERENCE",e[e.AMBIGUOUS_AMPERSAND=72]="AMBIGUOUS_AMPERSAND"}(un||(un={}));var fn={DATA:un.DATA,RCDATA:un.RCDATA,RAWTEXT:un.RAWTEXT,SCRIPT_DATA:un.SCRIPT_DATA,PLAINTEXT:un.PLAINTEXT,CDATA_SECTION:un.CDATA_SECTION};function isAsciiDigit(e){return e>=jt.DIGIT_0&&e<=jt.DIGIT_9}function isAsciiUpper(e){return e>=jt.LATIN_CAPITAL_A&&e<=jt.LATIN_CAPITAL_Z}function isAsciiLower(e){return e>=jt.LATIN_SMALL_A&&e<=jt.LATIN_SMALL_Z}function isAsciiLetter(e){return isAsciiLower(e)||isAsciiUpper(e)}function isAsciiAlphaNumeric2(e){return isAsciiLetter(e)||isAsciiDigit(e)}function toAsciiLower(e){return e+32}function isWhitespace(e){return e===jt.SPACE||e===jt.LINE_FEED||e===jt.TABULATION||e===jt.FORM_FEED}function isScriptDataDoubleEscapeSequenceEnd(e){return isWhitespace(e)||e===jt.SOLIDUS||e===jt.GREATER_THAN_SIGN}function getErrorForNumericCharacterReference(e){return e===jt.NULL?qt.nullCharacterReference:e>1114111?qt.characterReferenceOutsideUnicodeRange:isSurrogate(e)?qt.surrogateCharacterReference:isUndefinedCodePoint(e)?qt.noncharacterCharacterReference:isControlCodePoint(e)||e===jt.CARRIAGE_RETURN?qt.controlCharacterReference:null}var gn,yn=class{constructor(e,t){this.options=e,this.handler=t,this.paused=!1,this.inLoop=!1,this.inForeignNode=!1,this.lastStartTagName="",this.active=!1,this.state=un.DATA,this.returnState=un.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new Yt(t),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new ln(Qt,(e,t)=>{this.preprocessor.pos=this.entityStartPos+t-1,this._flushCodePointConsumedAsCharacterReference(e)},t.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(qt.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:e=>{this._err(qt.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+e)},validateNumericCharacterReference:e=>{const t=getErrorForNumericCharacterReference(e);t&&this._err(t,1)}}:void 0)}_err(e,t=0){var n,r;null===(r=(n=this.handler).onParseError)||void 0===r||r.call(n,this.preprocessor.getError(e,t))}getCurrentLocation(e){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-e,startOffset:this.preprocessor.offset-e,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=!0;this.active&&!this.paused;){this.consumedAfterSnapshot=0;const e=this._consume();this._ensureHibernation()||this._callState(e)}this.inLoop=!1}}pause(){this.paused=!0}resume(e){if(!this.paused)throw new Error("Parser was already resumed");this.paused=!1,this.inLoop||(this._runParsingLoop(),this.paused||null==e||e())}write(e,t,n){this.active=!0,this.preprocessor.write(e,t),this._runParsingLoop(),this.paused||null==n||n()}insertHtmlAtCurrentPos(e){this.active=!0,this.preprocessor.insertHtmlAtCurrentPos(e),this._runParsingLoop()}_ensureHibernation(){return!!this.preprocessor.endOfChunkHit&&(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=!1,!0)}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(e){this.consumedAfterSnapshot+=e;for(let t=0;t<e;t++)this.preprocessor.advance()}_consumeSequenceIfMatch(e,t){return!!this.preprocessor.startsWith(e,t)&&(this._advanceBy(e.length-1),!0)}_createStartTagToken(){this.currentToken={type:Vt.START_TAG,tagName:"",tagID:cn.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:Vt.END_TAG,tagName:"",tagID:cn.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(2)}}_createCommentToken(e){this.currentToken={type:Vt.COMMENT,data:"",location:this.getCurrentLocation(e)}}_createDoctypeToken(e){this.currentToken={type:Vt.DOCTYPE,name:e,forceQuirks:!1,publicId:null,systemId:null,location:this.currentLocation}}_createCharacterToken(e,t){this.currentCharacterToken={type:e,chars:t,location:this.currentLocation}}_createAttr(e){this.currentAttr={name:e,value:""},this.currentLocation=this.getCurrentLocation(0)}_leaveAttrName(){var e,t;const n=this.currentToken;if(null===getTokenAttr(n,this.currentAttr.name)){if(n.attrs.push(this.currentAttr),n.location&&this.currentLocation){const r=null!==(e=(t=n.location).attrs)&&void 0!==e?e:t.attrs=Object.create(null);r[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue()}}else this._err(qt.duplicateAttribute)}_leaveAttrValue(){this.currentLocation&&(this.currentLocation.endLine=this.preprocessor.line,this.currentLocation.endCol=this.preprocessor.col,this.currentLocation.endOffset=this.preprocessor.offset)}prepareToken(e){this._emitCurrentCharacterToken(e.location),this.currentToken=null,e.location&&(e.location.endLine=this.preprocessor.line,e.location.endCol=this.preprocessor.col+1,e.location.endOffset=this.preprocessor.offset+1),this.currentLocation=this.getCurrentLocation(-1)}emitCurrentTagToken(){const e=this.currentToken;this.prepareToken(e),e.tagID=getTagID(e.tagName),e.type===Vt.START_TAG?(this.lastStartTagName=e.tagName,this.handler.onStartTag(e)):(e.attrs.length>0&&this._err(qt.endTagWithAttributes),e.selfClosing&&this._err(qt.endTagWithTrailingSolidus),this.handler.onEndTag(e)),this.preprocessor.dropParsedChunk()}emitCurrentComment(e){this.prepareToken(e),this.handler.onComment(e),this.preprocessor.dropParsedChunk()}emitCurrentDoctype(e){this.prepareToken(e),this.handler.onDoctype(e),this.preprocessor.dropParsedChunk()}_emitCurrentCharacterToken(e){if(this.currentCharacterToken){switch(e&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=e.startLine,this.currentCharacterToken.location.endCol=e.startCol,this.currentCharacterToken.location.endOffset=e.startOffset),this.currentCharacterToken.type){case Vt.CHARACTER:this.handler.onCharacter(this.currentCharacterToken);break;case Vt.NULL_CHARACTER:this.handler.onNullCharacter(this.currentCharacterToken);break;case Vt.WHITESPACE_CHARACTER:this.handler.onWhitespaceCharacter(this.currentCharacterToken)}this.currentCharacterToken=null}}_emitEOFToken(){const e=this.getCurrentLocation(0);e&&(e.endLine=e.startLine,e.endCol=e.startCol,e.endOffset=e.startOffset),this._emitCurrentCharacterToken(e),this.handler.onEof({type:Vt.EOF,location:e}),this.active=!1}_appendCharToCurrentCharacterToken(e,t){if(this.currentCharacterToken){if(this.currentCharacterToken.type===e)return void(this.currentCharacterToken.chars+=t);this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk()}this._createCharacterToken(e,t)}_emitCodePoint(e){const t=isWhitespace(e)?Vt.WHITESPACE_CHARACTER:e===jt.NULL?Vt.NULL_CHARACTER:Vt.CHARACTER;this._appendCharToCurrentCharacterToken(t,String.fromCodePoint(e))}_emitChars(e){this._appendCharToCurrentCharacterToken(Vt.CHARACTER,e)}_startCharacterReference(){this.returnState=this.state,this.state=un.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?tn.Attribute:tn.Legacy)}_isCharacterReferenceInAttribute(){return this.returnState===un.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===un.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===un.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(e){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(e):this._emitCodePoint(e)}_callState(e){switch(this.state){case un.DATA:this._stateData(e);break;case un.RCDATA:this._stateRcdata(e);break;case un.RAWTEXT:this._stateRawtext(e);break;case un.SCRIPT_DATA:this._stateScriptData(e);break;case un.PLAINTEXT:this._statePlaintext(e);break;case un.TAG_OPEN:this._stateTagOpen(e);break;case un.END_TAG_OPEN:this._stateEndTagOpen(e);break;case un.TAG_NAME:this._stateTagName(e);break;case un.RCDATA_LESS_THAN_SIGN:this._stateRcdataLessThanSign(e);break;case un.RCDATA_END_TAG_OPEN:this._stateRcdataEndTagOpen(e);break;case un.RCDATA_END_TAG_NAME:this._stateRcdataEndTagName(e);break;case un.RAWTEXT_LESS_THAN_SIGN:this._stateRawtextLessThanSign(e);break;case un.RAWTEXT_END_TAG_OPEN:this._stateRawtextEndTagOpen(e);break;case un.RAWTEXT_END_TAG_NAME:this._stateRawtextEndTagName(e);break;case un.SCRIPT_DATA_LESS_THAN_SIGN:this._stateScriptDataLessThanSign(e);break;case un.SCRIPT_DATA_END_TAG_OPEN:this._stateScriptDataEndTagOpen(e);break;case un.SCRIPT_DATA_END_TAG_NAME:this._stateScriptDataEndTagName(e);break;case un.SCRIPT_DATA_ESCAPE_START:this._stateScriptDataEscapeStart(e);break;case un.SCRIPT_DATA_ESCAPE_START_DASH:this._stateScriptDataEscapeStartDash(e);break;case un.SCRIPT_DATA_ESCAPED:this._stateScriptDataEscaped(e);break;case un.SCRIPT_DATA_ESCAPED_DASH:this._stateScriptDataEscapedDash(e);break;case un.SCRIPT_DATA_ESCAPED_DASH_DASH:this._stateScriptDataEscapedDashDash(e);break;case un.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:this._stateScriptDataEscapedLessThanSign(e);break;case un.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:this._stateScriptDataEscapedEndTagOpen(e);break;case un.SCRIPT_DATA_ESCAPED_END_TAG_NAME:this._stateScriptDataEscapedEndTagName(e);break;case un.SCRIPT_DATA_DOUBLE_ESCAPE_START:this._stateScriptDataDoubleEscapeStart(e);break;case un.SCRIPT_DATA_DOUBLE_ESCAPED:this._stateScriptDataDoubleEscaped(e);break;case un.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:this._stateScriptDataDoubleEscapedDash(e);break;case un.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:this._stateScriptDataDoubleEscapedDashDash(e);break;case un.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:this._stateScriptDataDoubleEscapedLessThanSign(e);break;case un.SCRIPT_DATA_DOUBLE_ESCAPE_END:this._stateScriptDataDoubleEscapeEnd(e);break;case un.BEFORE_ATTRIBUTE_NAME:this._stateBeforeAttributeName(e);break;case un.ATTRIBUTE_NAME:this._stateAttributeName(e);break;case un.AFTER_ATTRIBUTE_NAME:this._stateAfterAttributeName(e);break;case un.BEFORE_ATTRIBUTE_VALUE:this._stateBeforeAttributeValue(e);break;case un.ATTRIBUTE_VALUE_DOUBLE_QUOTED:this._stateAttributeValueDoubleQuoted(e);break;case un.ATTRIBUTE_VALUE_SINGLE_QUOTED:this._stateAttributeValueSingleQuoted(e);break;case un.ATTRIBUTE_VALUE_UNQUOTED:this._stateAttributeValueUnquoted(e);break;case un.AFTER_ATTRIBUTE_VALUE_QUOTED:this._stateAfterAttributeValueQuoted(e);break;case un.SELF_CLOSING_START_TAG:this._stateSelfClosingStartTag(e);break;case un.BOGUS_COMMENT:this._stateBogusComment(e);break;case un.MARKUP_DECLARATION_OPEN:this._stateMarkupDeclarationOpen(e);break;case un.COMMENT_START:this._stateCommentStart(e);break;case un.COMMENT_START_DASH:this._stateCommentStartDash(e);break;case un.COMMENT:this._stateComment(e);break;case un.COMMENT_LESS_THAN_SIGN:this._stateCommentLessThanSign(e);break;case un.COMMENT_LESS_THAN_SIGN_BANG:this._stateCommentLessThanSignBang(e);break;case un.COMMENT_LESS_THAN_SIGN_BANG_DASH:this._stateCommentLessThanSignBangDash(e);break;case un.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:this._stateCommentLessThanSignBangDashDash(e);break;case un.COMMENT_END_DASH:this._stateCommentEndDash(e);break;case un.COMMENT_END:this._stateCommentEnd(e);break;case un.COMMENT_END_BANG:this._stateCommentEndBang(e);break;case un.DOCTYPE:this._stateDoctype(e);break;case un.BEFORE_DOCTYPE_NAME:this._stateBeforeDoctypeName(e);break;case un.DOCTYPE_NAME:this._stateDoctypeName(e);break;case un.AFTER_DOCTYPE_NAME:this._stateAfterDoctypeName(e);break;case un.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._stateAfterDoctypePublicKeyword(e);break;case un.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:this._stateBeforeDoctypePublicIdentifier(e);break;case un.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:this._stateDoctypePublicIdentifierDoubleQuoted(e);break;case un.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:this._stateDoctypePublicIdentifierSingleQuoted(e);break;case un.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:this._stateAfterDoctypePublicIdentifier(e);break;case un.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:this._stateBetweenDoctypePublicAndSystemIdentifiers(e);break;case un.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._stateAfterDoctypeSystemKeyword(e);break;case un.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:this._stateBeforeDoctypeSystemIdentifier(e);break;case un.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:this._stateDoctypeSystemIdentifierDoubleQuoted(e);break;case un.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:this._stateDoctypeSystemIdentifierSingleQuoted(e);break;case un.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:this._stateAfterDoctypeSystemIdentifier(e);break;case un.BOGUS_DOCTYPE:this._stateBogusDoctype(e);break;case un.CDATA_SECTION:this._stateCdataSection(e);break;case un.CDATA_SECTION_BRACKET:this._stateCdataSectionBracket(e);break;case un.CDATA_SECTION_END:this._stateCdataSectionEnd(e);break;case un.CHARACTER_REFERENCE:this._stateCharacterReference();break;case un.AMBIGUOUS_AMPERSAND:this._stateAmbiguousAmpersand(e);break;default:throw new Error("Unknown state")}}_stateData(e){switch(e){case jt.LESS_THAN_SIGN:this.state=un.TAG_OPEN;break;case jt.AMPERSAND:this._startCharacterReference();break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this._emitCodePoint(e);break;case jt.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateRcdata(e){switch(e){case jt.AMPERSAND:this._startCharacterReference();break;case jt.LESS_THAN_SIGN:this.state=un.RCDATA_LESS_THAN_SIGN;break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this._emitChars(Gt);break;case jt.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateRawtext(e){switch(e){case jt.LESS_THAN_SIGN:this.state=un.RAWTEXT_LESS_THAN_SIGN;break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this._emitChars(Gt);break;case jt.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateScriptData(e){switch(e){case jt.LESS_THAN_SIGN:this.state=un.SCRIPT_DATA_LESS_THAN_SIGN;break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this._emitChars(Gt);break;case jt.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_statePlaintext(e){switch(e){case jt.NULL:this._err(qt.unexpectedNullCharacter),this._emitChars(Gt);break;case jt.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateTagOpen(e){if(isAsciiLetter(e))this._createStartTagToken(),this.state=un.TAG_NAME,this._stateTagName(e);else switch(e){case jt.EXCLAMATION_MARK:this.state=un.MARKUP_DECLARATION_OPEN;break;case jt.SOLIDUS:this.state=un.END_TAG_OPEN;break;case jt.QUESTION_MARK:this._err(qt.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=un.BOGUS_COMMENT,this._stateBogusComment(e);break;case jt.EOF:this._err(qt.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break;default:this._err(qt.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=un.DATA,this._stateData(e)}}_stateEndTagOpen(e){if(isAsciiLetter(e))this._createEndTagToken(),this.state=un.TAG_NAME,this._stateTagName(e);else switch(e){case jt.GREATER_THAN_SIGN:this._err(qt.missingEndTagName),this.state=un.DATA;break;case jt.EOF:this._err(qt.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break;default:this._err(qt.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=un.BOGUS_COMMENT,this._stateBogusComment(e)}}_stateTagName(e){const t=this.currentToken;switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:this.state=un.BEFORE_ATTRIBUTE_NAME;break;case jt.SOLIDUS:this.state=un.SELF_CLOSING_START_TAG;break;case jt.GREATER_THAN_SIGN:this.state=un.DATA,this.emitCurrentTagToken();break;case jt.NULL:this._err(qt.unexpectedNullCharacter),t.tagName+=Gt;break;case jt.EOF:this._err(qt.eofInTag),this._emitEOFToken();break;default:t.tagName+=String.fromCodePoint(isAsciiUpper(e)?toAsciiLower(e):e)}}_stateRcdataLessThanSign(e){e===jt.SOLIDUS?this.state=un.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=un.RCDATA,this._stateRcdata(e))}_stateRcdataEndTagOpen(e){isAsciiLetter(e)?(this.state=un.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(e)):(this._emitChars("</"),this.state=un.RCDATA,this._stateRcdata(e))}handleSpecialEndTag(e){if(!this.preprocessor.startsWith(this.lastStartTagName,!1))return!this._ensureHibernation();this._createEndTagToken();const t=this.currentToken;t.tagName=this.lastStartTagName;const n=this.preprocessor.peek(this.lastStartTagName.length);switch(n){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=un.BEFORE_ATTRIBUTE_NAME,!1;case jt.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=un.SELF_CLOSING_START_TAG,!1;case jt.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=un.DATA,!1;default:return!this._ensureHibernation()}}_stateRcdataEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars("</"),this.state=un.RCDATA,this._stateRcdata(e))}_stateRawtextLessThanSign(e){e===jt.SOLIDUS?this.state=un.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=un.RAWTEXT,this._stateRawtext(e))}_stateRawtextEndTagOpen(e){isAsciiLetter(e)?(this.state=un.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(e)):(this._emitChars("</"),this.state=un.RAWTEXT,this._stateRawtext(e))}_stateRawtextEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars("</"),this.state=un.RAWTEXT,this._stateRawtext(e))}_stateScriptDataLessThanSign(e){switch(e){case jt.SOLIDUS:this.state=un.SCRIPT_DATA_END_TAG_OPEN;break;case jt.EXCLAMATION_MARK:this.state=un.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break;default:this._emitChars("<"),this.state=un.SCRIPT_DATA,this._stateScriptData(e)}}_stateScriptDataEndTagOpen(e){isAsciiLetter(e)?(this.state=un.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(e)):(this._emitChars("</"),this.state=un.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars("</"),this.state=un.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEscapeStart(e){e===jt.HYPHEN_MINUS?(this.state=un.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=un.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEscapeStartDash(e){e===jt.HYPHEN_MINUS?(this.state=un.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=un.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEscaped(e){switch(e){case jt.HYPHEN_MINUS:this.state=un.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break;case jt.LESS_THAN_SIGN:this.state=un.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this._emitChars(Gt);break;case jt.EOF:this._err(qt.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateScriptDataEscapedDash(e){switch(e){case jt.HYPHEN_MINUS:this.state=un.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break;case jt.LESS_THAN_SIGN:this.state=un.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this.state=un.SCRIPT_DATA_ESCAPED,this._emitChars(Gt);break;case jt.EOF:this._err(qt.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=un.SCRIPT_DATA_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataEscapedDashDash(e){switch(e){case jt.HYPHEN_MINUS:this._emitChars("-");break;case jt.LESS_THAN_SIGN:this.state=un.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break;case jt.GREATER_THAN_SIGN:this.state=un.SCRIPT_DATA,this._emitChars(">");break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this.state=un.SCRIPT_DATA_ESCAPED,this._emitChars(Gt);break;case jt.EOF:this._err(qt.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=un.SCRIPT_DATA_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataEscapedLessThanSign(e){e===jt.SOLIDUS?this.state=un.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:isAsciiLetter(e)?(this._emitChars("<"),this.state=un.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(e)):(this._emitChars("<"),this.state=un.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataEscapedEndTagOpen(e){isAsciiLetter(e)?(this.state=un.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(e)):(this._emitChars("</"),this.state=un.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataEscapedEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars("</"),this.state=un.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataDoubleEscapeStart(e){if(this.preprocessor.startsWith(Wt.SCRIPT,!1)&&isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(Wt.SCRIPT.length))){this._emitCodePoint(e);for(let e=0;e<Wt.SCRIPT.length;e++)this._emitCodePoint(this._consume());this.state=un.SCRIPT_DATA_DOUBLE_ESCAPED}else this._ensureHibernation()||(this.state=un.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataDoubleEscaped(e){switch(e){case jt.HYPHEN_MINUS:this.state=un.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break;case jt.LESS_THAN_SIGN:this.state=un.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this._emitChars(Gt);break;case jt.EOF:this._err(qt.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateScriptDataDoubleEscapedDash(e){switch(e){case jt.HYPHEN_MINUS:this.state=un.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break;case jt.LESS_THAN_SIGN:this.state=un.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this.state=un.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Gt);break;case jt.EOF:this._err(qt.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=un.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataDoubleEscapedDashDash(e){switch(e){case jt.HYPHEN_MINUS:this._emitChars("-");break;case jt.LESS_THAN_SIGN:this.state=un.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break;case jt.GREATER_THAN_SIGN:this.state=un.SCRIPT_DATA,this._emitChars(">");break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this.state=un.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Gt);break;case jt.EOF:this._err(qt.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=un.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataDoubleEscapedLessThanSign(e){e===jt.SOLIDUS?(this.state=un.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=un.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(e))}_stateScriptDataDoubleEscapeEnd(e){if(this.preprocessor.startsWith(Wt.SCRIPT,!1)&&isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(Wt.SCRIPT.length))){this._emitCodePoint(e);for(let e=0;e<Wt.SCRIPT.length;e++)this._emitCodePoint(this._consume());this.state=un.SCRIPT_DATA_ESCAPED}else this._ensureHibernation()||(this.state=un.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(e))}_stateBeforeAttributeName(e){switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:break;case jt.SOLIDUS:case jt.GREATER_THAN_SIGN:case jt.EOF:this.state=un.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(e);break;case jt.EQUALS_SIGN:this._err(qt.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=un.ATTRIBUTE_NAME;break;default:this._createAttr(""),this.state=un.ATTRIBUTE_NAME,this._stateAttributeName(e)}}_stateAttributeName(e){switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:case jt.SOLIDUS:case jt.GREATER_THAN_SIGN:case jt.EOF:this._leaveAttrName(),this.state=un.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(e);break;case jt.EQUALS_SIGN:this._leaveAttrName(),this.state=un.BEFORE_ATTRIBUTE_VALUE;break;case jt.QUOTATION_MARK:case jt.APOSTROPHE:case jt.LESS_THAN_SIGN:this._err(qt.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(e);break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this.currentAttr.name+=Gt;break;default:this.currentAttr.name+=String.fromCodePoint(isAsciiUpper(e)?toAsciiLower(e):e)}}_stateAfterAttributeName(e){switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:break;case jt.SOLIDUS:this.state=un.SELF_CLOSING_START_TAG;break;case jt.EQUALS_SIGN:this.state=un.BEFORE_ATTRIBUTE_VALUE;break;case jt.GREATER_THAN_SIGN:this.state=un.DATA,this.emitCurrentTagToken();break;case jt.EOF:this._err(qt.eofInTag),this._emitEOFToken();break;default:this._createAttr(""),this.state=un.ATTRIBUTE_NAME,this._stateAttributeName(e)}}_stateBeforeAttributeValue(e){switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:break;case jt.QUOTATION_MARK:this.state=un.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break;case jt.APOSTROPHE:this.state=un.ATTRIBUTE_VALUE_SINGLE_QUOTED;break;case jt.GREATER_THAN_SIGN:this._err(qt.missingAttributeValue),this.state=un.DATA,this.emitCurrentTagToken();break;default:this.state=un.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(e)}}_stateAttributeValueDoubleQuoted(e){switch(e){case jt.QUOTATION_MARK:this.state=un.AFTER_ATTRIBUTE_VALUE_QUOTED;break;case jt.AMPERSAND:this._startCharacterReference();break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this.currentAttr.value+=Gt;break;case jt.EOF:this._err(qt.eofInTag),this._emitEOFToken();break;default:this.currentAttr.value+=String.fromCodePoint(e)}}_stateAttributeValueSingleQuoted(e){switch(e){case jt.APOSTROPHE:this.state=un.AFTER_ATTRIBUTE_VALUE_QUOTED;break;case jt.AMPERSAND:this._startCharacterReference();break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this.currentAttr.value+=Gt;break;case jt.EOF:this._err(qt.eofInTag),this._emitEOFToken();break;default:this.currentAttr.value+=String.fromCodePoint(e)}}_stateAttributeValueUnquoted(e){switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:this._leaveAttrValue(),this.state=un.BEFORE_ATTRIBUTE_NAME;break;case jt.AMPERSAND:this._startCharacterReference();break;case jt.GREATER_THAN_SIGN:this._leaveAttrValue(),this.state=un.DATA,this.emitCurrentTagToken();break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this.currentAttr.value+=Gt;break;case jt.QUOTATION_MARK:case jt.APOSTROPHE:case jt.LESS_THAN_SIGN:case jt.EQUALS_SIGN:case jt.GRAVE_ACCENT:this._err(qt.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(e);break;case jt.EOF:this._err(qt.eofInTag),this._emitEOFToken();break;default:this.currentAttr.value+=String.fromCodePoint(e)}}_stateAfterAttributeValueQuoted(e){switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:this._leaveAttrValue(),this.state=un.BEFORE_ATTRIBUTE_NAME;break;case jt.SOLIDUS:this._leaveAttrValue(),this.state=un.SELF_CLOSING_START_TAG;break;case jt.GREATER_THAN_SIGN:this._leaveAttrValue(),this.state=un.DATA,this.emitCurrentTagToken();break;case jt.EOF:this._err(qt.eofInTag),this._emitEOFToken();break;default:this._err(qt.missingWhitespaceBetweenAttributes),this.state=un.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(e)}}_stateSelfClosingStartTag(e){switch(e){case jt.GREATER_THAN_SIGN:{const e=this.currentToken;e.selfClosing=!0,this.state=un.DATA,this.emitCurrentTagToken();break}case jt.EOF:this._err(qt.eofInTag),this._emitEOFToken();break;default:this._err(qt.unexpectedSolidusInTag),this.state=un.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(e)}}_stateBogusComment(e){const t=this.currentToken;switch(e){case jt.GREATER_THAN_SIGN:this.state=un.DATA,this.emitCurrentComment(t);break;case jt.EOF:this.emitCurrentComment(t),this._emitEOFToken();break;case jt.NULL:this._err(qt.unexpectedNullCharacter),t.data+=Gt;break;default:t.data+=String.fromCodePoint(e)}}_stateMarkupDeclarationOpen(e){this._consumeSequenceIfMatch(Wt.DASH_DASH,!0)?(this._createCommentToken(Wt.DASH_DASH.length+1),this.state=un.COMMENT_START):this._consumeSequenceIfMatch(Wt.DOCTYPE,!1)?(this.currentLocation=this.getCurrentLocation(Wt.DOCTYPE.length+1),this.state=un.DOCTYPE):this._consumeSequenceIfMatch(Wt.CDATA_START,!0)?this.inForeignNode?this.state=un.CDATA_SECTION:(this._err(qt.cdataInHtmlContent),this._createCommentToken(Wt.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=un.BOGUS_COMMENT):this._ensureHibernation()||(this._err(qt.incorrectlyOpenedComment),this._createCommentToken(2),this.state=un.BOGUS_COMMENT,this._stateBogusComment(e))}_stateCommentStart(e){switch(e){case jt.HYPHEN_MINUS:this.state=un.COMMENT_START_DASH;break;case jt.GREATER_THAN_SIGN:{this._err(qt.abruptClosingOfEmptyComment),this.state=un.DATA;const e=this.currentToken;this.emitCurrentComment(e);break}default:this.state=un.COMMENT,this._stateComment(e)}}_stateCommentStartDash(e){const t=this.currentToken;switch(e){case jt.HYPHEN_MINUS:this.state=un.COMMENT_END;break;case jt.GREATER_THAN_SIGN:this._err(qt.abruptClosingOfEmptyComment),this.state=un.DATA,this.emitCurrentComment(t);break;case jt.EOF:this._err(qt.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+="-",this.state=un.COMMENT,this._stateComment(e)}}_stateComment(e){const t=this.currentToken;switch(e){case jt.HYPHEN_MINUS:this.state=un.COMMENT_END_DASH;break;case jt.LESS_THAN_SIGN:t.data+="<",this.state=un.COMMENT_LESS_THAN_SIGN;break;case jt.NULL:this._err(qt.unexpectedNullCharacter),t.data+=Gt;break;case jt.EOF:this._err(qt.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+=String.fromCodePoint(e)}}_stateCommentLessThanSign(e){const t=this.currentToken;switch(e){case jt.EXCLAMATION_MARK:t.data+="!",this.state=un.COMMENT_LESS_THAN_SIGN_BANG;break;case jt.LESS_THAN_SIGN:t.data+="<";break;default:this.state=un.COMMENT,this._stateComment(e)}}_stateCommentLessThanSignBang(e){e===jt.HYPHEN_MINUS?this.state=un.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=un.COMMENT,this._stateComment(e))}_stateCommentLessThanSignBangDash(e){e===jt.HYPHEN_MINUS?this.state=un.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=un.COMMENT_END_DASH,this._stateCommentEndDash(e))}_stateCommentLessThanSignBangDashDash(e){e!==jt.GREATER_THAN_SIGN&&e!==jt.EOF&&this._err(qt.nestedComment),this.state=un.COMMENT_END,this._stateCommentEnd(e)}_stateCommentEndDash(e){const t=this.currentToken;switch(e){case jt.HYPHEN_MINUS:this.state=un.COMMENT_END;break;case jt.EOF:this._err(qt.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+="-",this.state=un.COMMENT,this._stateComment(e)}}_stateCommentEnd(e){const t=this.currentToken;switch(e){case jt.GREATER_THAN_SIGN:this.state=un.DATA,this.emitCurrentComment(t);break;case jt.EXCLAMATION_MARK:this.state=un.COMMENT_END_BANG;break;case jt.HYPHEN_MINUS:t.data+="-";break;case jt.EOF:this._err(qt.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+="--",this.state=un.COMMENT,this._stateComment(e)}}_stateCommentEndBang(e){const t=this.currentToken;switch(e){case jt.HYPHEN_MINUS:t.data+="--!",this.state=un.COMMENT_END_DASH;break;case jt.GREATER_THAN_SIGN:this._err(qt.incorrectlyClosedComment),this.state=un.DATA,this.emitCurrentComment(t);break;case jt.EOF:this._err(qt.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+="--!",this.state=un.COMMENT,this._stateComment(e)}}_stateDoctype(e){switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:this.state=un.BEFORE_DOCTYPE_NAME;break;case jt.GREATER_THAN_SIGN:this.state=un.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(e);break;case jt.EOF:{this._err(qt.eofInDoctype),this._createDoctypeToken(null);const e=this.currentToken;e.forceQuirks=!0,this.emitCurrentDoctype(e),this._emitEOFToken();break}default:this._err(qt.missingWhitespaceBeforeDoctypeName),this.state=un.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(e)}}_stateBeforeDoctypeName(e){if(isAsciiUpper(e))this._createDoctypeToken(String.fromCharCode(toAsciiLower(e))),this.state=un.DOCTYPE_NAME;else switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:break;case jt.NULL:this._err(qt.unexpectedNullCharacter),this._createDoctypeToken(Gt),this.state=un.DOCTYPE_NAME;break;case jt.GREATER_THAN_SIGN:{this._err(qt.missingDoctypeName),this._createDoctypeToken(null);const e=this.currentToken;e.forceQuirks=!0,this.emitCurrentDoctype(e),this.state=un.DATA;break}case jt.EOF:{this._err(qt.eofInDoctype),this._createDoctypeToken(null);const e=this.currentToken;e.forceQuirks=!0,this.emitCurrentDoctype(e),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(e)),this.state=un.DOCTYPE_NAME}}_stateDoctypeName(e){const t=this.currentToken;switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:this.state=un.AFTER_DOCTYPE_NAME;break;case jt.GREATER_THAN_SIGN:this.state=un.DATA,this.emitCurrentDoctype(t);break;case jt.NULL:this._err(qt.unexpectedNullCharacter),t.name+=Gt;break;case jt.EOF:this._err(qt.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.name+=String.fromCodePoint(isAsciiUpper(e)?toAsciiLower(e):e)}}_stateAfterDoctypeName(e){const t=this.currentToken;switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:break;case jt.GREATER_THAN_SIGN:this.state=un.DATA,this.emitCurrentDoctype(t);break;case jt.EOF:this._err(qt.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._consumeSequenceIfMatch(Wt.PUBLIC,!1)?this.state=un.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(Wt.SYSTEM,!1)?this.state=un.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(qt.invalidCharacterSequenceAfterDoctypeName),t.forceQuirks=!0,this.state=un.BOGUS_DOCTYPE,this._stateBogusDoctype(e))}}_stateAfterDoctypePublicKeyword(e){const t=this.currentToken;switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:this.state=un.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break;case jt.QUOTATION_MARK:this._err(qt.missingWhitespaceAfterDoctypePublicKeyword),t.publicId="",this.state=un.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break;case jt.APOSTROPHE:this._err(qt.missingWhitespaceAfterDoctypePublicKeyword),t.publicId="",this.state=un.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break;case jt.GREATER_THAN_SIGN:this._err(qt.missingDoctypePublicIdentifier),t.forceQuirks=!0,this.state=un.DATA,this.emitCurrentDoctype(t);break;case jt.EOF:this._err(qt.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(qt.missingQuoteBeforeDoctypePublicIdentifier),t.forceQuirks=!0,this.state=un.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBeforeDoctypePublicIdentifier(e){const t=this.currentToken;switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:break;case jt.QUOTATION_MARK:t.publicId="",this.state=un.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break;case jt.APOSTROPHE:t.publicId="",this.state=un.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break;case jt.GREATER_THAN_SIGN:this._err(qt.missingDoctypePublicIdentifier),t.forceQuirks=!0,this.state=un.DATA,this.emitCurrentDoctype(t);break;case jt.EOF:this._err(qt.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(qt.missingQuoteBeforeDoctypePublicIdentifier),t.forceQuirks=!0,this.state=un.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateDoctypePublicIdentifierDoubleQuoted(e){const t=this.currentToken;switch(e){case jt.QUOTATION_MARK:this.state=un.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break;case jt.NULL:this._err(qt.unexpectedNullCharacter),t.publicId+=Gt;break;case jt.GREATER_THAN_SIGN:this._err(qt.abruptDoctypePublicIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=un.DATA;break;case jt.EOF:this._err(qt.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.publicId+=String.fromCodePoint(e)}}_stateDoctypePublicIdentifierSingleQuoted(e){const t=this.currentToken;switch(e){case jt.APOSTROPHE:this.state=un.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break;case jt.NULL:this._err(qt.unexpectedNullCharacter),t.publicId+=Gt;break;case jt.GREATER_THAN_SIGN:this._err(qt.abruptDoctypePublicIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=un.DATA;break;case jt.EOF:this._err(qt.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.publicId+=String.fromCodePoint(e)}}_stateAfterDoctypePublicIdentifier(e){const t=this.currentToken;switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:this.state=un.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break;case jt.GREATER_THAN_SIGN:this.state=un.DATA,this.emitCurrentDoctype(t);break;case jt.QUOTATION_MARK:this._err(qt.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),t.systemId="",this.state=un.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case jt.APOSTROPHE:this._err(qt.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),t.systemId="",this.state=un.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case jt.EOF:this._err(qt.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(qt.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=un.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBetweenDoctypePublicAndSystemIdentifiers(e){const t=this.currentToken;switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:break;case jt.GREATER_THAN_SIGN:this.emitCurrentDoctype(t),this.state=un.DATA;break;case jt.QUOTATION_MARK:t.systemId="",this.state=un.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case jt.APOSTROPHE:t.systemId="",this.state=un.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case jt.EOF:this._err(qt.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(qt.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=un.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateAfterDoctypeSystemKeyword(e){const t=this.currentToken;switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:this.state=un.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break;case jt.QUOTATION_MARK:this._err(qt.missingWhitespaceAfterDoctypeSystemKeyword),t.systemId="",this.state=un.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case jt.APOSTROPHE:this._err(qt.missingWhitespaceAfterDoctypeSystemKeyword),t.systemId="",this.state=un.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case jt.GREATER_THAN_SIGN:this._err(qt.missingDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=un.DATA,this.emitCurrentDoctype(t);break;case jt.EOF:this._err(qt.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(qt.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=un.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBeforeDoctypeSystemIdentifier(e){const t=this.currentToken;switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:break;case jt.QUOTATION_MARK:t.systemId="",this.state=un.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case jt.APOSTROPHE:t.systemId="",this.state=un.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case jt.GREATER_THAN_SIGN:this._err(qt.missingDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=un.DATA,this.emitCurrentDoctype(t);break;case jt.EOF:this._err(qt.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(qt.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=un.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateDoctypeSystemIdentifierDoubleQuoted(e){const t=this.currentToken;switch(e){case jt.QUOTATION_MARK:this.state=un.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break;case jt.NULL:this._err(qt.unexpectedNullCharacter),t.systemId+=Gt;break;case jt.GREATER_THAN_SIGN:this._err(qt.abruptDoctypeSystemIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=un.DATA;break;case jt.EOF:this._err(qt.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.systemId+=String.fromCodePoint(e)}}_stateDoctypeSystemIdentifierSingleQuoted(e){const t=this.currentToken;switch(e){case jt.APOSTROPHE:this.state=un.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break;case jt.NULL:this._err(qt.unexpectedNullCharacter),t.systemId+=Gt;break;case jt.GREATER_THAN_SIGN:this._err(qt.abruptDoctypeSystemIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=un.DATA;break;case jt.EOF:this._err(qt.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.systemId+=String.fromCodePoint(e)}}_stateAfterDoctypeSystemIdentifier(e){const t=this.currentToken;switch(e){case jt.SPACE:case jt.LINE_FEED:case jt.TABULATION:case jt.FORM_FEED:break;case jt.GREATER_THAN_SIGN:this.emitCurrentDoctype(t),this.state=un.DATA;break;case jt.EOF:this._err(qt.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(qt.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=un.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBogusDoctype(e){const t=this.currentToken;switch(e){case jt.GREATER_THAN_SIGN:this.emitCurrentDoctype(t),this.state=un.DATA;break;case jt.NULL:this._err(qt.unexpectedNullCharacter);break;case jt.EOF:this.emitCurrentDoctype(t),this._emitEOFToken()}}_stateCdataSection(e){switch(e){case jt.RIGHT_SQUARE_BRACKET:this.state=un.CDATA_SECTION_BRACKET;break;case jt.EOF:this._err(qt.eofInCdata),this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateCdataSectionBracket(e){e===jt.RIGHT_SQUARE_BRACKET?this.state=un.CDATA_SECTION_END:(this._emitChars("]"),this.state=un.CDATA_SECTION,this._stateCdataSection(e))}_stateCdataSectionEnd(e){switch(e){case jt.GREATER_THAN_SIGN:this.state=un.DATA;break;case jt.RIGHT_SQUARE_BRACKET:this._emitChars("]");break;default:this._emitChars("]]"),this.state=un.CDATA_SECTION,this._stateCdataSection(e)}}_stateCharacterReference(){let e=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(e<0){if(!this.preprocessor.lastChunkWritten)return this.active=!1,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,void(this.preprocessor.endOfChunkHit=!0);e=this.entityDecoder.end()}0===e?(this.preprocessor.pos=this.entityStartPos,this._flushCodePointConsumedAsCharacterReference(jt.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&isAsciiAlphaNumeric2(this.preprocessor.peek(1))?un.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState}_stateAmbiguousAmpersand(e){isAsciiAlphaNumeric2(e)?this._flushCodePointConsumedAsCharacterReference(e):(e===jt.SEMICOLON&&this._err(qt.unknownNamedCharacterReference),this.state=this.returnState,this._callState(e))}},vn=new Set([cn.DD,cn.DT,cn.LI,cn.OPTGROUP,cn.OPTION,cn.P,cn.RB,cn.RP,cn.RT,cn.RTC]),En=new Set([...vn,cn.CAPTION,cn.COLGROUP,cn.TBODY,cn.TD,cn.TFOOT,cn.TH,cn.THEAD,cn.TR]),Tn=new Set([cn.APPLET,cn.CAPTION,cn.HTML,cn.MARQUEE,cn.OBJECT,cn.TABLE,cn.TD,cn.TEMPLATE,cn.TH]),wn=new Set([...Tn,cn.OL,cn.UL]),Sn=new Set([...Tn,cn.BUTTON]),bn=new Set([cn.ANNOTATION_XML,cn.MI,cn.MN,cn.MO,cn.MS,cn.MTEXT]),An=new Set([cn.DESC,cn.FOREIGN_OBJECT,cn.TITLE]),_n=new Set([cn.TR,cn.TEMPLATE,cn.HTML]),kn=new Set([cn.TBODY,cn.TFOOT,cn.THEAD,cn.TEMPLATE,cn.HTML]),In=new Set([cn.TABLE,cn.TEMPLATE,cn.HTML]),Cn=new Set([cn.TD,cn.TH]),Rn=class{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(e,t,n){this.treeAdapter=t,this.handler=n,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=cn.UNKNOWN,this.current=e}_indexOf(e){return this.items.lastIndexOf(e,this.stackTop)}_isInTemplate(){return this.currentTagId===cn.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===rn.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop]}push(e,t){this.stackTop++,this.items[this.stackTop]=e,this.current=e,this.tagIDs[this.stackTop]=t,this.currentTagId=t,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(e,t,!0)}pop(){const e=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(e,!0)}replace(e,t){const n=this._indexOf(e);this.items[n]=t,n===this.stackTop&&(this.current=t)}insertAfter(e,t,n){const r=this._indexOf(e)+1;this.items.splice(r,0,t),this.tagIDs.splice(r,0,n),this.stackTop++,r===this.stackTop&&this._updateCurrentElement(),this.current&&void 0!==this.currentTagId&&this.handler.onItemPush(this.current,this.currentTagId,r===this.stackTop)}popUntilTagNamePopped(e){let t=this.stackTop+1;do{t=this.tagIDs.lastIndexOf(e,t-1)}while(t>0&&this.treeAdapter.getNamespaceURI(this.items[t])!==rn.HTML);this.shortenToLength(Math.max(t,0))}shortenToLength(e){for(;this.stackTop>=e;){const t=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,this.stackTop<e)}}popUntilElementPopped(e){const t=this._indexOf(e);this.shortenToLength(Math.max(t,0))}popUntilPopped(e,t){const n=this._indexOfTagNames(e,t);this.shortenToLength(Math.max(n,0))}popUntilNumberedHeaderPopped(){this.popUntilPopped(mn,rn.HTML)}popUntilTableCellPopped(){this.popUntilPopped(Cn,rn.HTML)}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1)}_indexOfTagNames(e,t){for(let n=this.stackTop;n>=0;n--)if(e.has(this.tagIDs[n])&&this.treeAdapter.getNamespaceURI(this.items[n])===t)return n;return-1}clearBackTo(e,t){const n=this._indexOfTagNames(e,t);this.shortenToLength(n+1)}clearBackToTableContext(){this.clearBackTo(In,rn.HTML)}clearBackToTableBodyContext(){this.clearBackTo(kn,rn.HTML)}clearBackToTableRowContext(){this.clearBackTo(_n,rn.HTML)}remove(e){const t=this._indexOf(e);t>=0&&(t===this.stackTop?this.pop():(this.items.splice(t,1),this.tagIDs.splice(t,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(e,!1)))}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===cn.BODY?this.items[1]:null}contains(e){return this._indexOf(e)>-1}getCommonAncestor(e){const t=this._indexOf(e)-1;return t>=0?this.items[t]:null}isRootHtmlElementCurrent(){return 0===this.stackTop&&this.tagIDs[0]===cn.HTML}hasInDynamicScope(e,t){for(let n=this.stackTop;n>=0;n--){const r=this.tagIDs[n];switch(this.treeAdapter.getNamespaceURI(this.items[n])){case rn.HTML:if(r===e)return!0;if(t.has(r))return!1;break;case rn.SVG:if(An.has(r))return!1;break;case rn.MATHML:if(bn.has(r))return!1}}return!0}hasInScope(e){return this.hasInDynamicScope(e,Tn)}hasInListItemScope(e){return this.hasInDynamicScope(e,wn)}hasInButtonScope(e){return this.hasInDynamicScope(e,Sn)}hasNumberedHeaderInScope(){for(let e=this.stackTop;e>=0;e--){const t=this.tagIDs[e];switch(this.treeAdapter.getNamespaceURI(this.items[e])){case rn.HTML:if(mn.has(t))return!0;if(Tn.has(t))return!1;break;case rn.SVG:if(An.has(t))return!1;break;case rn.MATHML:if(bn.has(t))return!1}}return!0}hasInTableScope(e){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===rn.HTML)switch(this.tagIDs[t]){case e:return!0;case cn.TABLE:case cn.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let e=this.stackTop;e>=0;e--)if(this.treeAdapter.getNamespaceURI(this.items[e])===rn.HTML)switch(this.tagIDs[e]){case cn.TBODY:case cn.THEAD:case cn.TFOOT:return!0;case cn.TABLE:case cn.HTML:return!1}return!0}hasInSelectScope(e){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===rn.HTML)switch(this.tagIDs[t]){case e:return!0;case cn.OPTION:case cn.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;void 0!==this.currentTagId&&vn.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;void 0!==this.currentTagId&&En.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(e){for(;void 0!==this.currentTagId&&this.currentTagId!==e&&En.has(this.currentTagId);)this.pop()}},Pn=3;!function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element"}(gn||(gn={}));var Nn={type:gn.Marker},On=class{constructor(e){this.treeAdapter=e,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(e,t){const n=[],r=t.length,s=this.treeAdapter.getTagName(e),i=this.treeAdapter.getNamespaceURI(e);for(let e=0;e<this.entries.length;e++){const t=this.entries[e];if(t.type===gn.Marker)break;const{element:a}=t;if(this.treeAdapter.getTagName(a)===s&&this.treeAdapter.getNamespaceURI(a)===i){const t=this.treeAdapter.getAttrList(a);t.length===r&&n.push({idx:e,attrs:t})}}return n}_ensureNoahArkCondition(e){if(this.entries.length<Pn)return;const t=this.treeAdapter.getAttrList(e),n=this._getNoahArkConditionCandidates(e,t);if(n.length<Pn)return;const r=new Map(t.map(e=>[e.name,e.value]));let s=0;for(let e=0;e<n.length;e++){const t=n[e];t.attrs.every(e=>r.get(e.name)===e.value)&&(s+=1,s>=Pn&&this.entries.splice(t.idx,1))}}insertMarker(){this.entries.unshift(Nn)}pushElement(e,t){this._ensureNoahArkCondition(e),this.entries.unshift({type:gn.Element,element:e,token:t})}insertElementAfterBookmark(e,t){const n=this.entries.indexOf(this.bookmark);this.entries.splice(n,0,{type:gn.Element,element:e,token:t})}removeEntry(e){const t=this.entries.indexOf(e);-1!==t&&this.entries.splice(t,1)}clearToLastMarker(){const e=this.entries.indexOf(Nn);-1===e?this.entries.length=0:this.entries.splice(0,e+1)}getElementEntryInScopeWithTagName(e){const t=this.entries.find(t=>t.type===gn.Marker||this.treeAdapter.getTagName(t.element)===e);return t&&t.type===gn.Element?t:null}getElementEntry(e){return this.entries.find(t=>t.type===gn.Element&&t.element===e)}},Dn={createDocument:()=>({nodeName:"#document",mode:an.NO_QUIRKS,childNodes:[]}),createDocumentFragment:()=>({nodeName:"#document-fragment",childNodes:[]}),createElement:(e,t,n)=>({nodeName:e,tagName:e,attrs:n,namespaceURI:t,childNodes:[],parentNode:null}),createCommentNode:e=>({nodeName:"#comment",data:e,parentNode:null}),createTextNode:e=>({nodeName:"#text",value:e,parentNode:null}),appendChild(e,t){e.childNodes.push(t),t.parentNode=e},insertBefore(e,t,n){const r=e.childNodes.indexOf(n);e.childNodes.splice(r,0,t),t.parentNode=e},setTemplateContent(e,t){e.content=t},getTemplateContent:e=>e.content,setDocumentType(e,t,n,r){const s=e.childNodes.find(e=>"#documentType"===e.nodeName);if(s)s.name=t,s.publicId=n,s.systemId=r;else{const s={nodeName:"#documentType",name:t,publicId:n,systemId:r,parentNode:null};Dn.appendChild(e,s)}},setDocumentMode(e,t){e.mode=t},getDocumentMode:e=>e.mode,detachNode(e){if(e.parentNode){const t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null}},insertText(e,t){if(e.childNodes.length>0){const n=e.childNodes[e.childNodes.length-1];if(Dn.isTextNode(n))return void(n.value+=t)}Dn.appendChild(e,Dn.createTextNode(t))},insertTextBefore(e,t,n){const r=e.childNodes[e.childNodes.indexOf(n)-1];r&&Dn.isTextNode(r)?r.value+=t:Dn.insertBefore(e,Dn.createTextNode(t),n)},adoptAttributes(e,t){const n=new Set(e.attrs.map(e=>e.name));for(let r=0;r<t.length;r++)n.has(t[r].name)||e.attrs.push(t[r])},getFirstChild:e=>e.childNodes[0],getChildNodes:e=>e.childNodes,getParentNode:e=>e.parentNode,getAttrList:e=>e.attrs,getTagName:e=>e.tagName,getNamespaceURI:e=>e.namespaceURI,getTextNodeContent:e=>e.value,getCommentNodeContent:e=>e.data,getDocumentTypeNodeName:e=>e.name,getDocumentTypeNodePublicId:e=>e.publicId,getDocumentTypeNodeSystemId:e=>e.systemId,isTextNode:e=>"#text"===e.nodeName,isCommentNode:e=>"#comment"===e.nodeName,isDocumentTypeNode:e=>"#documentType"===e.nodeName,isElementNode:e=>Object.prototype.hasOwnProperty.call(e,"tagName"),setNodeSourceCodeLocation(e,t){e.sourceCodeLocation=t},getNodeSourceCodeLocation:e=>e.sourceCodeLocation,updateNodeSourceCodeLocation(e,t){e.sourceCodeLocation={...e.sourceCodeLocation,...t}}},Ln="html",Mn="about:legacy-compat",xn="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",Fn=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"],Bn=[...Fn,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],Hn=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),Un=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],jn=[...Un,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function hasPrefix(e,t){return t.some(t=>e.startsWith(t))}function isConforming(e){return e.name===Ln&&null===e.publicId&&(null===e.systemId||e.systemId===Mn)}function getDocumentMode(e){if(e.name!==Ln)return an.QUIRKS;const{systemId:t}=e;if(t&&t.toLowerCase()===xn)return an.QUIRKS;let{publicId:n}=e;if(null!==n){if(n=n.toLowerCase(),Hn.has(n))return an.QUIRKS;let e=null===t?Bn:Fn;if(hasPrefix(n,e))return an.QUIRKS;if(e=null===t?Un:jn,hasPrefix(n,e))return an.LIMITED_QUIRKS}return an.NO_QUIRKS}var $n={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},Gn="definitionurl",qn="definitionURL",Wn=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e])),Vn=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:rn.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:rn.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:rn.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:rn.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:rn.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:rn.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:rn.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:rn.XML}],["xml:space",{prefix:"xml",name:"space",namespace:rn.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:rn.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:rn.XMLNS}]]),Kn=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),Yn=new Set([cn.B,cn.BIG,cn.BLOCKQUOTE,cn.BODY,cn.BR,cn.CENTER,cn.CODE,cn.DD,cn.DIV,cn.DL,cn.DT,cn.EM,cn.EMBED,cn.H1,cn.H2,cn.H3,cn.H4,cn.H5,cn.H6,cn.HEAD,cn.HR,cn.I,cn.IMG,cn.LI,cn.LISTING,cn.MENU,cn.META,cn.NOBR,cn.OL,cn.P,cn.PRE,cn.RUBY,cn.S,cn.SMALL,cn.SPAN,cn.STRONG,cn.STRIKE,cn.SUB,cn.SUP,cn.TABLE,cn.TT,cn.U,cn.UL,cn.VAR]);function causesExit(e){const t=e.tagID,n=t===cn.FONT&&e.attrs.some(({name:e})=>e===sn.COLOR||e===sn.SIZE||e===sn.FACE);return n||Yn.has(t)}function adjustTokenMathMLAttrs(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===Gn){e.attrs[t].name=qn;break}}function adjustTokenSVGAttrs(e){for(let t=0;t<e.attrs.length;t++){const n=Wn.get(e.attrs[t].name);null!=n&&(e.attrs[t].name=n)}}function adjustTokenXMLAttrs(e){for(let t=0;t<e.attrs.length;t++){const n=Vn.get(e.attrs[t].name);n&&(e.attrs[t].prefix=n.prefix,e.attrs[t].name=n.name,e.attrs[t].namespace=n.namespace)}}function adjustTokenSVGTagName(e){const t=Kn.get(e.tagName);null!=t&&(e.tagName=t,e.tagID=getTagID(e.tagName))}function isMathMLTextIntegrationPoint(e,t){return t===rn.MATHML&&(e===cn.MI||e===cn.MO||e===cn.MN||e===cn.MS||e===cn.MTEXT)}function isHtmlIntegrationPoint(e,t,n){if(t===rn.MATHML&&e===cn.ANNOTATION_XML)for(let e=0;e<n.length;e++)if(n[e].name===sn.ENCODING){const t=n[e].value.toLowerCase();return t===$n.TEXT_HTML||t===$n.APPLICATION_XML}return t===rn.SVG&&(e===cn.FOREIGN_OBJECT||e===cn.DESC||e===cn.TITLE)}function isIntegrationPoint(e,t,n,r){return(!r||r===rn.HTML)&&isHtmlIntegrationPoint(e,t,n)||(!r||r===rn.MATHML)&&isMathMLTextIntegrationPoint(e,t)}var zn,Jn="hidden",Qn=8,Xn=3;!function(e){e[e.INITIAL=0]="INITIAL",e[e.BEFORE_HTML=1]="BEFORE_HTML",e[e.BEFORE_HEAD=2]="BEFORE_HEAD",e[e.IN_HEAD=3]="IN_HEAD",e[e.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",e[e.AFTER_HEAD=5]="AFTER_HEAD",e[e.IN_BODY=6]="IN_BODY",e[e.TEXT=7]="TEXT",e[e.IN_TABLE=8]="IN_TABLE",e[e.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",e[e.IN_CAPTION=10]="IN_CAPTION",e[e.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",e[e.IN_TABLE_BODY=12]="IN_TABLE_BODY",e[e.IN_ROW=13]="IN_ROW",e[e.IN_CELL=14]="IN_CELL",e[e.IN_SELECT=15]="IN_SELECT",e[e.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",e[e.IN_TEMPLATE=17]="IN_TEMPLATE",e[e.AFTER_BODY=18]="AFTER_BODY",e[e.IN_FRAMESET=19]="IN_FRAMESET",e[e.AFTER_FRAMESET=20]="AFTER_FRAMESET",e[e.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",e[e.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET"}(zn||(zn={}));var Zn={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},er=new Set([cn.TABLE,cn.TBODY,cn.TFOOT,cn.THEAD,cn.TR]),tr={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:Dn,onParseError:null},nr=class{constructor(e,t,n=null,r=null){this.fragmentContext=n,this.scriptHandler=r,this.currentToken=null,this.stopped=!1,this.insertionMode=zn.INITIAL,this.originalInsertionMode=zn.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=!1,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=!1,this.framesetOk=!0,this.skipNextNewLine=!1,this.fosterParentingEnabled=!1,this.options={...tr,...e},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=!0),this.document=null!=t?t:this.treeAdapter.createDocument(),this.tokenizer=new yn(this.options,this),this.activeFormattingElements=new On(this.treeAdapter),this.fragmentContextID=n?getTagID(this.treeAdapter.getTagName(n)):cn.UNKNOWN,this._setContextModes(null!=n?n:this.document,this.fragmentContextID),this.openElements=new Rn(this.document,this.treeAdapter,this)}static parse(e,t){const n=new this(t);return n.tokenizer.write(e,!0),n.document}static getFragmentParser(e,t){const n={...tr,...t};null!=e||(e=n.treeAdapter.createElement(on.TEMPLATE,rn.HTML,[]));const r=n.treeAdapter.createElement("documentmock",rn.HTML,[]),s=new this(n,r,e);return s.fragmentContextID===cn.TEMPLATE&&s.tmplInsertionModeStack.unshift(zn.IN_TEMPLATE),s._initTokenizerForFragmentParsing(),s._insertFakeRootElement(),s._resetInsertionMode(),s._findFormInFragmentContext(),s}getFragment(){const e=this.treeAdapter.getFirstChild(this.document),t=this.treeAdapter.createDocumentFragment();return this._adoptNodes(e,t),t}_err(e,t,n){var r;if(!this.onParseError)return;const s=null!==(r=e.location)&&void 0!==r?r:Zn,i={code:t,startLine:s.startLine,startCol:s.startCol,startOffset:s.startOffset,endLine:n?s.startLine:s.endLine,endCol:n?s.startCol:s.endCol,endOffset:n?s.startOffset:s.endOffset};this.onParseError(i)}onItemPush(e,t,n){var r,s;null===(s=(r=this.treeAdapter).onItemPush)||void 0===s||s.call(r,e),n&&this.openElements.stackTop>0&&this._setContextModes(e,t)}onItemPop(e,t){var n,r;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(e,this.currentToken),null===(r=(n=this.treeAdapter).onItemPop)||void 0===r||r.call(n,e,this.openElements.current),t){let e,t;0===this.openElements.stackTop&&this.fragmentContext?(e=this.fragmentContext,t=this.fragmentContextID):({current:e,currentTagId:t}=this.openElements),this._setContextModes(e,t)}}_setContextModes(e,t){const n=e===this.document||e&&this.treeAdapter.getNamespaceURI(e)===rn.HTML;this.currentNotInHTML=!n,this.tokenizer.inForeignNode=!n&&void 0!==e&&void 0!==t&&!this._isIntegrationPoint(t,e)}_switchToTextParsing(e,t){this._insertElement(e,rn.HTML),this.tokenizer.state=t,this.originalInsertionMode=this.insertionMode,this.insertionMode=zn.TEXT}switchToPlaintextParsing(){this.insertionMode=zn.TEXT,this.originalInsertionMode=zn.IN_BODY,this.tokenizer.state=fn.PLAINTEXT}_getAdjustedCurrentElement(){return 0===this.openElements.stackTop&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let e=this.fragmentContext;for(;e;){if(this.treeAdapter.getTagName(e)===on.FORM){this.formElement=e;break}e=this.treeAdapter.getParentNode(e)}}_initTokenizerForFragmentParsing(){if(this.fragmentContext&&this.treeAdapter.getNamespaceURI(this.fragmentContext)===rn.HTML)switch(this.fragmentContextID){case cn.TITLE:case cn.TEXTAREA:this.tokenizer.state=fn.RCDATA;break;case cn.STYLE:case cn.XMP:case cn.IFRAME:case cn.NOEMBED:case cn.NOFRAMES:case cn.NOSCRIPT:this.tokenizer.state=fn.RAWTEXT;break;case cn.SCRIPT:this.tokenizer.state=fn.SCRIPT_DATA;break;case cn.PLAINTEXT:this.tokenizer.state=fn.PLAINTEXT}}_setDocumentType(e){const t=e.name||"",n=e.publicId||"",r=e.systemId||"";if(this.treeAdapter.setDocumentType(this.document,t,n,r),e.location){const t=this.treeAdapter.getChildNodes(this.document),n=t.find(e=>this.treeAdapter.isDocumentTypeNode(e));n&&this.treeAdapter.setNodeSourceCodeLocation(n,e.location)}}_attachElementToTree(e,t){if(this.options.sourceCodeLocationInfo){const n=t&&{...t,startTag:t};this.treeAdapter.setNodeSourceCodeLocation(e,n)}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(e);else{const t=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(null!=t?t:this.document,e)}}_appendElement(e,t){const n=this.treeAdapter.createElement(e.tagName,t,e.attrs);this._attachElementToTree(n,e.location)}_insertElement(e,t){const n=this.treeAdapter.createElement(e.tagName,t,e.attrs);this._attachElementToTree(n,e.location),this.openElements.push(n,e.tagID)}_insertFakeElement(e,t){const n=this.treeAdapter.createElement(e,rn.HTML,[]);this._attachElementToTree(n,null),this.openElements.push(n,t)}_insertTemplate(e){const t=this.treeAdapter.createElement(e.tagName,rn.HTML,e.attrs),n=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(t,n),this._attachElementToTree(t,e.location),this.openElements.push(t,e.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,null)}_insertFakeRootElement(){const e=this.treeAdapter.createElement(on.HTML,rn.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(e,null),this.treeAdapter.appendChild(this.openElements.current,e),this.openElements.push(e,cn.HTML)}_appendCommentNode(e,t){const n=this.treeAdapter.createCommentNode(e.data);this.treeAdapter.appendChild(t,n),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,e.location)}_insertCharacters(e){let t,n;if(this._shouldFosterParentOnInsertion()?(({parent:t,beforeElement:n}=this._findFosterParentingLocation()),n?this.treeAdapter.insertTextBefore(t,e.chars,n):this.treeAdapter.insertText(t,e.chars)):(t=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(t,e.chars)),!e.location)return;const r=this.treeAdapter.getChildNodes(t),s=n?r.lastIndexOf(n):r.length,i=r[s-1],a=this.treeAdapter.getNodeSourceCodeLocation(i);if(a){const{endLine:t,endCol:n,endOffset:r}=e.location;this.treeAdapter.updateNodeSourceCodeLocation(i,{endLine:t,endCol:n,endOffset:r})}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(i,e.location)}_adoptNodes(e,t){for(let n=this.treeAdapter.getFirstChild(e);n;n=this.treeAdapter.getFirstChild(e))this.treeAdapter.detachNode(n),this.treeAdapter.appendChild(t,n)}_setEndLocation(e,t){if(this.treeAdapter.getNodeSourceCodeLocation(e)&&t.location){const n=t.location,r=this.treeAdapter.getTagName(e),s=t.type===Vt.END_TAG&&r===t.tagName?{endTag:{...n},endLine:n.endLine,endCol:n.endCol,endOffset:n.endOffset}:{endLine:n.startLine,endCol:n.startCol,endOffset:n.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(e,s)}}shouldProcessStartTagTokenInForeignContent(e){if(!this.currentNotInHTML)return!1;let t,n;return 0===this.openElements.stackTop&&this.fragmentContext?(t=this.fragmentContext,n=this.fragmentContextID):({current:t,currentTagId:n}=this.openElements),(e.tagID!==cn.SVG||this.treeAdapter.getTagName(t)!==on.ANNOTATION_XML||this.treeAdapter.getNamespaceURI(t)!==rn.MATHML)&&(this.tokenizer.inForeignNode||(e.tagID===cn.MGLYPH||e.tagID===cn.MALIGNMARK)&&void 0!==n&&!this._isIntegrationPoint(n,t,rn.HTML))}_processToken(e){switch(e.type){case Vt.CHARACTER:this.onCharacter(e);break;case Vt.NULL_CHARACTER:this.onNullCharacter(e);break;case Vt.COMMENT:this.onComment(e);break;case Vt.DOCTYPE:this.onDoctype(e);break;case Vt.START_TAG:this._processStartTag(e);break;case Vt.END_TAG:this.onEndTag(e);break;case Vt.EOF:this.onEof(e);break;case Vt.WHITESPACE_CHARACTER:this.onWhitespaceCharacter(e)}}_isIntegrationPoint(e,t,n){const r=this.treeAdapter.getNamespaceURI(t),s=this.treeAdapter.getAttrList(t);return isIntegrationPoint(e,r,s,n)}_reconstructActiveFormattingElements(){const e=this.activeFormattingElements.entries.length;if(e){const t=this.activeFormattingElements.entries.findIndex(e=>e.type===gn.Marker||this.openElements.contains(e.element)),n=-1===t?e-1:t-1;for(let e=n;e>=0;e--){const t=this.activeFormattingElements.entries[e];this._insertElement(t.token,this.treeAdapter.getNamespaceURI(t.element)),t.element=this.openElements.current}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=zn.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(cn.P),this.openElements.popUntilTagNamePopped(cn.P)}_resetInsertionMode(){for(let e=this.openElements.stackTop;e>=0;e--)switch(0===e&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[e]){case cn.TR:return void(this.insertionMode=zn.IN_ROW);case cn.TBODY:case cn.THEAD:case cn.TFOOT:return void(this.insertionMode=zn.IN_TABLE_BODY);case cn.CAPTION:return void(this.insertionMode=zn.IN_CAPTION);case cn.COLGROUP:return void(this.insertionMode=zn.IN_COLUMN_GROUP);case cn.TABLE:return void(this.insertionMode=zn.IN_TABLE);case cn.BODY:return void(this.insertionMode=zn.IN_BODY);case cn.FRAMESET:return void(this.insertionMode=zn.IN_FRAMESET);case cn.SELECT:return void this._resetInsertionModeForSelect(e);case cn.TEMPLATE:return void(this.insertionMode=this.tmplInsertionModeStack[0]);case cn.HTML:return void(this.insertionMode=this.headElement?zn.AFTER_HEAD:zn.BEFORE_HEAD);case cn.TD:case cn.TH:if(e>0)return void(this.insertionMode=zn.IN_CELL);break;case cn.HEAD:if(e>0)return void(this.insertionMode=zn.IN_HEAD)}this.insertionMode=zn.IN_BODY}_resetInsertionModeForSelect(e){if(e>0)for(let t=e-1;t>0;t--){const e=this.openElements.tagIDs[t];if(e===cn.TEMPLATE)break;if(e===cn.TABLE)return void(this.insertionMode=zn.IN_SELECT_IN_TABLE)}this.insertionMode=zn.IN_SELECT}_isElementCausesFosterParenting(e){return er.has(e)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&void 0!==this.openElements.currentTagId&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let e=this.openElements.stackTop;e>=0;e--){const t=this.openElements.items[e];switch(this.openElements.tagIDs[e]){case cn.TEMPLATE:if(this.treeAdapter.getNamespaceURI(t)===rn.HTML)return{parent:this.treeAdapter.getTemplateContent(t),beforeElement:null};break;case cn.TABLE:{const n=this.treeAdapter.getParentNode(t);return n?{parent:n,beforeElement:t}:{parent:this.openElements.items[e-1],beforeElement:null}}}}return{parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(e){const t=this._findFosterParentingLocation();t.beforeElement?this.treeAdapter.insertBefore(t.parent,e,t.beforeElement):this.treeAdapter.appendChild(t.parent,e)}_isSpecialElement(e,t){const n=this.treeAdapter.getNamespaceURI(e);return hn[n].has(t)}onCharacter(e){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode)characterInForeignContent(this,e);else switch(this.insertionMode){case zn.INITIAL:tokenInInitialMode(this,e);break;case zn.BEFORE_HTML:tokenBeforeHtml(this,e);break;case zn.BEFORE_HEAD:tokenBeforeHead(this,e);break;case zn.IN_HEAD:tokenInHead(this,e);break;case zn.IN_HEAD_NO_SCRIPT:tokenInHeadNoScript(this,e);break;case zn.AFTER_HEAD:tokenAfterHead(this,e);break;case zn.IN_BODY:case zn.IN_CAPTION:case zn.IN_CELL:case zn.IN_TEMPLATE:characterInBody(this,e);break;case zn.TEXT:case zn.IN_SELECT:case zn.IN_SELECT_IN_TABLE:this._insertCharacters(e);break;case zn.IN_TABLE:case zn.IN_TABLE_BODY:case zn.IN_ROW:characterInTable(this,e);break;case zn.IN_TABLE_TEXT:characterInTableText(this,e);break;case zn.IN_COLUMN_GROUP:tokenInColumnGroup(this,e);break;case zn.AFTER_BODY:tokenAfterBody(this,e);break;case zn.AFTER_AFTER_BODY:tokenAfterAfterBody(this,e)}}onNullCharacter(e){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode)nullCharacterInForeignContent(this,e);else switch(this.insertionMode){case zn.INITIAL:tokenInInitialMode(this,e);break;case zn.BEFORE_HTML:tokenBeforeHtml(this,e);break;case zn.BEFORE_HEAD:tokenBeforeHead(this,e);break;case zn.IN_HEAD:tokenInHead(this,e);break;case zn.IN_HEAD_NO_SCRIPT:tokenInHeadNoScript(this,e);break;case zn.AFTER_HEAD:tokenAfterHead(this,e);break;case zn.TEXT:this._insertCharacters(e);break;case zn.IN_TABLE:case zn.IN_TABLE_BODY:case zn.IN_ROW:characterInTable(this,e);break;case zn.IN_COLUMN_GROUP:tokenInColumnGroup(this,e);break;case zn.AFTER_BODY:tokenAfterBody(this,e);break;case zn.AFTER_AFTER_BODY:tokenAfterAfterBody(this,e)}}onComment(e){if(this.skipNextNewLine=!1,this.currentNotInHTML)appendComment(this,e);else switch(this.insertionMode){case zn.INITIAL:case zn.BEFORE_HTML:case zn.BEFORE_HEAD:case zn.IN_HEAD:case zn.IN_HEAD_NO_SCRIPT:case zn.AFTER_HEAD:case zn.IN_BODY:case zn.IN_TABLE:case zn.IN_CAPTION:case zn.IN_COLUMN_GROUP:case zn.IN_TABLE_BODY:case zn.IN_ROW:case zn.IN_CELL:case zn.IN_SELECT:case zn.IN_SELECT_IN_TABLE:case zn.IN_TEMPLATE:case zn.IN_FRAMESET:case zn.AFTER_FRAMESET:appendComment(this,e);break;case zn.IN_TABLE_TEXT:tokenInTableText(this,e);break;case zn.AFTER_BODY:appendCommentToRootHtmlElement(this,e);break;case zn.AFTER_AFTER_BODY:case zn.AFTER_AFTER_FRAMESET:appendCommentToDocument(this,e)}}onDoctype(e){switch(this.skipNextNewLine=!1,this.insertionMode){case zn.INITIAL:doctypeInInitialMode(this,e);break;case zn.BEFORE_HEAD:case zn.IN_HEAD:case zn.IN_HEAD_NO_SCRIPT:case zn.AFTER_HEAD:this._err(e,qt.misplacedDoctype);break;case zn.IN_TABLE_TEXT:tokenInTableText(this,e)}}onStartTag(e){this.skipNextNewLine=!1,this.currentToken=e,this._processStartTag(e),e.selfClosing&&!e.ackSelfClosing&&this._err(e,qt.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(e){this.shouldProcessStartTagTokenInForeignContent(e)?startTagInForeignContent(this,e):this._startTagOutsideForeignContent(e)}_startTagOutsideForeignContent(e){switch(this.insertionMode){case zn.INITIAL:tokenInInitialMode(this,e);break;case zn.BEFORE_HTML:startTagBeforeHtml(this,e);break;case zn.BEFORE_HEAD:startTagBeforeHead(this,e);break;case zn.IN_HEAD:startTagInHead(this,e);break;case zn.IN_HEAD_NO_SCRIPT:startTagInHeadNoScript(this,e);break;case zn.AFTER_HEAD:startTagAfterHead(this,e);break;case zn.IN_BODY:startTagInBody(this,e);break;case zn.IN_TABLE:startTagInTable(this,e);break;case zn.IN_TABLE_TEXT:tokenInTableText(this,e);break;case zn.IN_CAPTION:startTagInCaption(this,e);break;case zn.IN_COLUMN_GROUP:startTagInColumnGroup(this,e);break;case zn.IN_TABLE_BODY:startTagInTableBody(this,e);break;case zn.IN_ROW:startTagInRow(this,e);break;case zn.IN_CELL:startTagInCell(this,e);break;case zn.IN_SELECT:startTagInSelect(this,e);break;case zn.IN_SELECT_IN_TABLE:startTagInSelectInTable(this,e);break;case zn.IN_TEMPLATE:startTagInTemplate(this,e);break;case zn.AFTER_BODY:startTagAfterBody(this,e);break;case zn.IN_FRAMESET:startTagInFrameset(this,e);break;case zn.AFTER_FRAMESET:startTagAfterFrameset(this,e);break;case zn.AFTER_AFTER_BODY:startTagAfterAfterBody(this,e);break;case zn.AFTER_AFTER_FRAMESET:startTagAfterAfterFrameset(this,e)}}onEndTag(e){this.skipNextNewLine=!1,this.currentToken=e,this.currentNotInHTML?endTagInForeignContent(this,e):this._endTagOutsideForeignContent(e)}_endTagOutsideForeignContent(e){switch(this.insertionMode){case zn.INITIAL:tokenInInitialMode(this,e);break;case zn.BEFORE_HTML:endTagBeforeHtml(this,e);break;case zn.BEFORE_HEAD:endTagBeforeHead(this,e);break;case zn.IN_HEAD:endTagInHead(this,e);break;case zn.IN_HEAD_NO_SCRIPT:endTagInHeadNoScript(this,e);break;case zn.AFTER_HEAD:endTagAfterHead(this,e);break;case zn.IN_BODY:endTagInBody(this,e);break;case zn.TEXT:endTagInText(this,e);break;case zn.IN_TABLE:endTagInTable(this,e);break;case zn.IN_TABLE_TEXT:tokenInTableText(this,e);break;case zn.IN_CAPTION:endTagInCaption(this,e);break;case zn.IN_COLUMN_GROUP:endTagInColumnGroup(this,e);break;case zn.IN_TABLE_BODY:endTagInTableBody(this,e);break;case zn.IN_ROW:endTagInRow(this,e);break;case zn.IN_CELL:endTagInCell(this,e);break;case zn.IN_SELECT:endTagInSelect(this,e);break;case zn.IN_SELECT_IN_TABLE:endTagInSelectInTable(this,e);break;case zn.IN_TEMPLATE:endTagInTemplate(this,e);break;case zn.AFTER_BODY:endTagAfterBody(this,e);break;case zn.IN_FRAMESET:endTagInFrameset(this,e);break;case zn.AFTER_FRAMESET:endTagAfterFrameset(this,e);break;case zn.AFTER_AFTER_BODY:tokenAfterAfterBody(this,e)}}onEof(e){switch(this.insertionMode){case zn.INITIAL:tokenInInitialMode(this,e);break;case zn.BEFORE_HTML:tokenBeforeHtml(this,e);break;case zn.BEFORE_HEAD:tokenBeforeHead(this,e);break;case zn.IN_HEAD:tokenInHead(this,e);break;case zn.IN_HEAD_NO_SCRIPT:tokenInHeadNoScript(this,e);break;case zn.AFTER_HEAD:tokenAfterHead(this,e);break;case zn.IN_BODY:case zn.IN_TABLE:case zn.IN_CAPTION:case zn.IN_COLUMN_GROUP:case zn.IN_TABLE_BODY:case zn.IN_ROW:case zn.IN_CELL:case zn.IN_SELECT:case zn.IN_SELECT_IN_TABLE:eofInBody(this,e);break;case zn.TEXT:eofInText(this,e);break;case zn.IN_TABLE_TEXT:tokenInTableText(this,e);break;case zn.IN_TEMPLATE:eofInTemplate(this,e);break;case zn.AFTER_BODY:case zn.IN_FRAMESET:case zn.AFTER_FRAMESET:case zn.AFTER_AFTER_BODY:case zn.AFTER_AFTER_FRAMESET:stopParsing(this,e)}}onWhitespaceCharacter(e){if(this.skipNextNewLine&&(this.skipNextNewLine=!1,e.chars.charCodeAt(0)===jt.LINE_FEED)){if(1===e.chars.length)return;e.chars=e.chars.substr(1)}if(this.tokenizer.inForeignNode)this._insertCharacters(e);else switch(this.insertionMode){case zn.IN_HEAD:case zn.IN_HEAD_NO_SCRIPT:case zn.AFTER_HEAD:case zn.TEXT:case zn.IN_COLUMN_GROUP:case zn.IN_SELECT:case zn.IN_SELECT_IN_TABLE:case zn.IN_FRAMESET:case zn.AFTER_FRAMESET:this._insertCharacters(e);break;case zn.IN_BODY:case zn.IN_CAPTION:case zn.IN_CELL:case zn.IN_TEMPLATE:case zn.AFTER_BODY:case zn.AFTER_AFTER_BODY:case zn.AFTER_AFTER_FRAMESET:whitespaceCharacterInBody(this,e);break;case zn.IN_TABLE:case zn.IN_TABLE_BODY:case zn.IN_ROW:characterInTable(this,e);break;case zn.IN_TABLE_TEXT:whitespaceCharacterInTableText(this,e)}}};function aaObtainFormattingElementEntry(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return n?e.openElements.contains(n.element)?e.openElements.hasInScope(t.tagID)||(n=null):(e.activeFormattingElements.removeEntry(n),n=null):genericEndTagInBody(e,t),n}function aaObtainFurthestBlock(e,t){let n=null,r=e.openElements.stackTop;for(;r>=0;r--){const s=e.openElements.items[r];if(s===t.element)break;e._isSpecialElement(s,e.openElements.tagIDs[r])&&(n=s)}return n||(e.openElements.shortenToLength(Math.max(r,0)),e.activeFormattingElements.removeEntry(t)),n}function aaInnerLoop(e,t,n){let r=t,s=e.openElements.getCommonAncestor(t);for(let i=0,a=s;a!==n;i++,a=s){s=e.openElements.getCommonAncestor(a);const n=e.activeFormattingElements.getElementEntry(a),o=n&&i>=Xn,c=!n||o;c?(o&&e.activeFormattingElements.removeEntry(n),e.openElements.remove(a)):(a=aaRecreateElementFromEntry(e,n),r===t&&(e.activeFormattingElements.bookmark=n),e.treeAdapter.detachNode(r),e.treeAdapter.appendChild(a,r),r=a)}return r}function aaRecreateElementFromEntry(e,t){const n=e.treeAdapter.getNamespaceURI(t.element),r=e.treeAdapter.createElement(t.token.tagName,n,t.token.attrs);return e.openElements.replace(t.element,r),t.element=r,r}function aaInsertLastNodeInCommonAncestor(e,t,n){const r=e.treeAdapter.getTagName(t),s=getTagID(r);if(e._isElementCausesFosterParenting(s))e._fosterParentElement(n);else{const r=e.treeAdapter.getNamespaceURI(t);s===cn.TEMPLATE&&r===rn.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,n)}}function aaReplaceFormattingElement(e,t,n){const r=e.treeAdapter.getNamespaceURI(n.element),{token:s}=n,i=e.treeAdapter.createElement(s.tagName,r,s.attrs);e._adoptNodes(t,i),e.treeAdapter.appendChild(t,i),e.activeFormattingElements.insertElementAfterBookmark(i,s),e.activeFormattingElements.removeEntry(n),e.openElements.remove(n.element),e.openElements.insertAfter(t,i,s.tagID)}function callAdoptionAgency(e,t){for(let n=0;n<Qn;n++){const n=aaObtainFormattingElementEntry(e,t);if(!n)break;const r=aaObtainFurthestBlock(e,n);if(!r)break;e.activeFormattingElements.bookmark=n;const s=aaInnerLoop(e,r,n.element),i=e.openElements.getCommonAncestor(n.element);e.treeAdapter.detachNode(s),i&&aaInsertLastNodeInCommonAncestor(e,i,s),aaReplaceFormattingElement(e,r,n)}}function appendComment(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode)}function appendCommentToRootHtmlElement(e,t){e._appendCommentNode(t,e.openElements.items[0])}function appendCommentToDocument(e,t){e._appendCommentNode(t,e.document)}function stopParsing(e,t){if(e.stopped=!0,t.location){const n=e.fragmentContext?0:2;for(let r=e.openElements.stackTop;r>=n;r--)e._setEndLocation(e.openElements.items[r],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){const n=e.openElements.items[0],r=e.treeAdapter.getNodeSourceCodeLocation(n);if(r&&!r.endTag&&(e._setEndLocation(n,t),e.openElements.stackTop>=1)){const n=e.openElements.items[1],r=e.treeAdapter.getNodeSourceCodeLocation(n);r&&!r.endTag&&e._setEndLocation(n,t)}}}}function doctypeInInitialMode(e,t){e._setDocumentType(t);const n=t.forceQuirks?an.QUIRKS:getDocumentMode(t);isConforming(t)||e._err(t,qt.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,n),e.insertionMode=zn.BEFORE_HTML}function tokenInInitialMode(e,t){e._err(t,qt.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,an.QUIRKS),e.insertionMode=zn.BEFORE_HTML,e._processToken(t)}function startTagBeforeHtml(e,t){t.tagID===cn.HTML?(e._insertElement(t,rn.HTML),e.insertionMode=zn.BEFORE_HEAD):tokenBeforeHtml(e,t)}function endTagBeforeHtml(e,t){const n=t.tagID;n!==cn.HTML&&n!==cn.HEAD&&n!==cn.BODY&&n!==cn.BR||tokenBeforeHtml(e,t)}function tokenBeforeHtml(e,t){e._insertFakeRootElement(),e.insertionMode=zn.BEFORE_HEAD,e._processToken(t)}function startTagBeforeHead(e,t){switch(t.tagID){case cn.HTML:startTagInBody(e,t);break;case cn.HEAD:e._insertElement(t,rn.HTML),e.headElement=e.openElements.current,e.insertionMode=zn.IN_HEAD;break;default:tokenBeforeHead(e,t)}}function endTagBeforeHead(e,t){const n=t.tagID;n===cn.HEAD||n===cn.BODY||n===cn.HTML||n===cn.BR?tokenBeforeHead(e,t):e._err(t,qt.endTagWithoutMatchingOpenElement)}function tokenBeforeHead(e,t){e._insertFakeElement(on.HEAD,cn.HEAD),e.headElement=e.openElements.current,e.insertionMode=zn.IN_HEAD,e._processToken(t)}function startTagInHead(e,t){switch(t.tagID){case cn.HTML:startTagInBody(e,t);break;case cn.BASE:case cn.BASEFONT:case cn.BGSOUND:case cn.LINK:case cn.META:e._appendElement(t,rn.HTML),t.ackSelfClosing=!0;break;case cn.TITLE:e._switchToTextParsing(t,fn.RCDATA);break;case cn.NOSCRIPT:e.options.scriptingEnabled?e._switchToTextParsing(t,fn.RAWTEXT):(e._insertElement(t,rn.HTML),e.insertionMode=zn.IN_HEAD_NO_SCRIPT);break;case cn.NOFRAMES:case cn.STYLE:e._switchToTextParsing(t,fn.RAWTEXT);break;case cn.SCRIPT:e._switchToTextParsing(t,fn.SCRIPT_DATA);break;case cn.TEMPLATE:e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=!1,e.insertionMode=zn.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(zn.IN_TEMPLATE);break;case cn.HEAD:e._err(t,qt.misplacedStartTagForHeadElement);break;default:tokenInHead(e,t)}}function endTagInHead(e,t){switch(t.tagID){case cn.HEAD:e.openElements.pop(),e.insertionMode=zn.AFTER_HEAD;break;case cn.BODY:case cn.BR:case cn.HTML:tokenInHead(e,t);break;case cn.TEMPLATE:templateEndTagInHead(e,t);break;default:e._err(t,qt.endTagWithoutMatchingOpenElement)}}function templateEndTagInHead(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==cn.TEMPLATE&&e._err(t,qt.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(cn.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,qt.endTagWithoutMatchingOpenElement)}function tokenInHead(e,t){e.openElements.pop(),e.insertionMode=zn.AFTER_HEAD,e._processToken(t)}function startTagInHeadNoScript(e,t){switch(t.tagID){case cn.HTML:startTagInBody(e,t);break;case cn.BASEFONT:case cn.BGSOUND:case cn.HEAD:case cn.LINK:case cn.META:case cn.NOFRAMES:case cn.STYLE:startTagInHead(e,t);break;case cn.NOSCRIPT:e._err(t,qt.nestedNoscriptInHead);break;default:tokenInHeadNoScript(e,t)}}function endTagInHeadNoScript(e,t){switch(t.tagID){case cn.NOSCRIPT:e.openElements.pop(),e.insertionMode=zn.IN_HEAD;break;case cn.BR:tokenInHeadNoScript(e,t);break;default:e._err(t,qt.endTagWithoutMatchingOpenElement)}}function tokenInHeadNoScript(e,t){const n=t.type===Vt.EOF?qt.openElementsLeftAfterEof:qt.disallowedContentInNoscriptInHead;e._err(t,n),e.openElements.pop(),e.insertionMode=zn.IN_HEAD,e._processToken(t)}function startTagAfterHead(e,t){switch(t.tagID){case cn.HTML:startTagInBody(e,t);break;case cn.BODY:e._insertElement(t,rn.HTML),e.framesetOk=!1,e.insertionMode=zn.IN_BODY;break;case cn.FRAMESET:e._insertElement(t,rn.HTML),e.insertionMode=zn.IN_FRAMESET;break;case cn.BASE:case cn.BASEFONT:case cn.BGSOUND:case cn.LINK:case cn.META:case cn.NOFRAMES:case cn.SCRIPT:case cn.STYLE:case cn.TEMPLATE:case cn.TITLE:e._err(t,qt.abandonedHeadElementChild),e.openElements.push(e.headElement,cn.HEAD),startTagInHead(e,t),e.openElements.remove(e.headElement);break;case cn.HEAD:e._err(t,qt.misplacedStartTagForHeadElement);break;default:tokenAfterHead(e,t)}}function endTagAfterHead(e,t){switch(t.tagID){case cn.BODY:case cn.HTML:case cn.BR:tokenAfterHead(e,t);break;case cn.TEMPLATE:templateEndTagInHead(e,t);break;default:e._err(t,qt.endTagWithoutMatchingOpenElement)}}function tokenAfterHead(e,t){e._insertFakeElement(on.BODY,cn.BODY),e.insertionMode=zn.IN_BODY,modeInBody(e,t)}function modeInBody(e,t){switch(t.type){case Vt.CHARACTER:characterInBody(e,t);break;case Vt.WHITESPACE_CHARACTER:whitespaceCharacterInBody(e,t);break;case Vt.COMMENT:appendComment(e,t);break;case Vt.START_TAG:startTagInBody(e,t);break;case Vt.END_TAG:endTagInBody(e,t);break;case Vt.EOF:eofInBody(e,t)}}function whitespaceCharacterInBody(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function characterInBody(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function htmlStartTagInBody(e,t){0===e.openElements.tmplCount&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function bodyStartTagInBody(e,t){const n=e.openElements.tryPeekProperlyNestedBodyElement();n&&0===e.openElements.tmplCount&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(n,t.attrs))}function framesetStartTagInBody(e,t){const n=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&n&&(e.treeAdapter.detachNode(n),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,rn.HTML),e.insertionMode=zn.IN_FRAMESET)}function addressStartTagInBody(e,t){e.openElements.hasInButtonScope(cn.P)&&e._closePElement(),e._insertElement(t,rn.HTML)}function numberedHeaderStartTagInBody(e,t){e.openElements.hasInButtonScope(cn.P)&&e._closePElement(),void 0!==e.openElements.currentTagId&&mn.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,rn.HTML)}function preStartTagInBody(e,t){e.openElements.hasInButtonScope(cn.P)&&e._closePElement(),e._insertElement(t,rn.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function formStartTagInBody(e,t){const n=e.openElements.tmplCount>0;e.formElement&&!n||(e.openElements.hasInButtonScope(cn.P)&&e._closePElement(),e._insertElement(t,rn.HTML),n||(e.formElement=e.openElements.current))}function listItemStartTagInBody(e,t){e.framesetOk=!1;const n=t.tagID;for(let t=e.openElements.stackTop;t>=0;t--){const r=e.openElements.tagIDs[t];if(n===cn.LI&&r===cn.LI||(n===cn.DD||n===cn.DT)&&(r===cn.DD||r===cn.DT)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r);break}if(r!==cn.ADDRESS&&r!==cn.DIV&&r!==cn.P&&e._isSpecialElement(e.openElements.items[t],r))break}e.openElements.hasInButtonScope(cn.P)&&e._closePElement(),e._insertElement(t,rn.HTML)}function plaintextStartTagInBody(e,t){e.openElements.hasInButtonScope(cn.P)&&e._closePElement(),e._insertElement(t,rn.HTML),e.tokenizer.state=fn.PLAINTEXT}function buttonStartTagInBody(e,t){e.openElements.hasInScope(cn.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(cn.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,rn.HTML),e.framesetOk=!1}function aStartTagInBody(e,t){const n=e.activeFormattingElements.getElementEntryInScopeWithTagName(on.A);n&&(callAdoptionAgency(e,t),e.openElements.remove(n.element),e.activeFormattingElements.removeEntry(n)),e._reconstructActiveFormattingElements(),e._insertElement(t,rn.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function bStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,rn.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function nobrStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(cn.NOBR)&&(callAdoptionAgency(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,rn.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function appletStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,rn.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function tableStartTagInBody(e,t){e.treeAdapter.getDocumentMode(e.document)!==an.QUIRKS&&e.openElements.hasInButtonScope(cn.P)&&e._closePElement(),e._insertElement(t,rn.HTML),e.framesetOk=!1,e.insertionMode=zn.IN_TABLE}function areaStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,rn.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function isHiddenInput(e){const t=getTokenAttr(e,sn.TYPE);return null!=t&&t.toLowerCase()===Jn}function inputStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,rn.HTML),isHiddenInput(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function paramStartTagInBody(e,t){e._appendElement(t,rn.HTML),t.ackSelfClosing=!0}function hrStartTagInBody(e,t){e.openElements.hasInButtonScope(cn.P)&&e._closePElement(),e._appendElement(t,rn.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function imageStartTagInBody(e,t){t.tagName=on.IMG,t.tagID=cn.IMG,areaStartTagInBody(e,t)}function textareaStartTagInBody(e,t){e._insertElement(t,rn.HTML),e.skipNextNewLine=!0,e.tokenizer.state=fn.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=!1,e.insertionMode=zn.TEXT}function xmpStartTagInBody(e,t){e.openElements.hasInButtonScope(cn.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,fn.RAWTEXT)}function iframeStartTagInBody(e,t){e.framesetOk=!1,e._switchToTextParsing(t,fn.RAWTEXT)}function rawTextStartTagInBody(e,t){e._switchToTextParsing(t,fn.RAWTEXT)}function selectStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,rn.HTML),e.framesetOk=!1,e.insertionMode=e.insertionMode===zn.IN_TABLE||e.insertionMode===zn.IN_CAPTION||e.insertionMode===zn.IN_TABLE_BODY||e.insertionMode===zn.IN_ROW||e.insertionMode===zn.IN_CELL?zn.IN_SELECT_IN_TABLE:zn.IN_SELECT}function optgroupStartTagInBody(e,t){e.openElements.currentTagId===cn.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,rn.HTML)}function rbStartTagInBody(e,t){e.openElements.hasInScope(cn.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,rn.HTML)}function rtStartTagInBody(e,t){e.openElements.hasInScope(cn.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(cn.RTC),e._insertElement(t,rn.HTML)}function mathStartTagInBody(e,t){e._reconstructActiveFormattingElements(),adjustTokenMathMLAttrs(t),adjustTokenXMLAttrs(t),t.selfClosing?e._appendElement(t,rn.MATHML):e._insertElement(t,rn.MATHML),t.ackSelfClosing=!0}function svgStartTagInBody(e,t){e._reconstructActiveFormattingElements(),adjustTokenSVGAttrs(t),adjustTokenXMLAttrs(t),t.selfClosing?e._appendElement(t,rn.SVG):e._insertElement(t,rn.SVG),t.ackSelfClosing=!0}function genericStartTagInBody(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,rn.HTML)}function startTagInBody(e,t){switch(t.tagID){case cn.I:case cn.S:case cn.B:case cn.U:case cn.EM:case cn.TT:case cn.BIG:case cn.CODE:case cn.FONT:case cn.SMALL:case cn.STRIKE:case cn.STRONG:bStartTagInBody(e,t);break;case cn.A:aStartTagInBody(e,t);break;case cn.H1:case cn.H2:case cn.H3:case cn.H4:case cn.H5:case cn.H6:numberedHeaderStartTagInBody(e,t);break;case cn.P:case cn.DL:case cn.OL:case cn.UL:case cn.DIV:case cn.DIR:case cn.NAV:case cn.MAIN:case cn.MENU:case cn.ASIDE:case cn.CENTER:case cn.FIGURE:case cn.FOOTER:case cn.HEADER:case cn.HGROUP:case cn.DIALOG:case cn.DETAILS:case cn.ADDRESS:case cn.ARTICLE:case cn.SEARCH:case cn.SECTION:case cn.SUMMARY:case cn.FIELDSET:case cn.BLOCKQUOTE:case cn.FIGCAPTION:addressStartTagInBody(e,t);break;case cn.LI:case cn.DD:case cn.DT:listItemStartTagInBody(e,t);break;case cn.BR:case cn.IMG:case cn.WBR:case cn.AREA:case cn.EMBED:case cn.KEYGEN:areaStartTagInBody(e,t);break;case cn.HR:hrStartTagInBody(e,t);break;case cn.RB:case cn.RTC:rbStartTagInBody(e,t);break;case cn.RT:case cn.RP:rtStartTagInBody(e,t);break;case cn.PRE:case cn.LISTING:preStartTagInBody(e,t);break;case cn.XMP:xmpStartTagInBody(e,t);break;case cn.SVG:svgStartTagInBody(e,t);break;case cn.HTML:htmlStartTagInBody(e,t);break;case cn.BASE:case cn.LINK:case cn.META:case cn.STYLE:case cn.TITLE:case cn.SCRIPT:case cn.BGSOUND:case cn.BASEFONT:case cn.TEMPLATE:startTagInHead(e,t);break;case cn.BODY:bodyStartTagInBody(e,t);break;case cn.FORM:formStartTagInBody(e,t);break;case cn.NOBR:nobrStartTagInBody(e,t);break;case cn.MATH:mathStartTagInBody(e,t);break;case cn.TABLE:tableStartTagInBody(e,t);break;case cn.INPUT:inputStartTagInBody(e,t);break;case cn.PARAM:case cn.TRACK:case cn.SOURCE:paramStartTagInBody(e,t);break;case cn.IMAGE:imageStartTagInBody(e,t);break;case cn.BUTTON:buttonStartTagInBody(e,t);break;case cn.APPLET:case cn.OBJECT:case cn.MARQUEE:appletStartTagInBody(e,t);break;case cn.IFRAME:iframeStartTagInBody(e,t);break;case cn.SELECT:selectStartTagInBody(e,t);break;case cn.OPTION:case cn.OPTGROUP:optgroupStartTagInBody(e,t);break;case cn.NOEMBED:case cn.NOFRAMES:rawTextStartTagInBody(e,t);break;case cn.FRAMESET:framesetStartTagInBody(e,t);break;case cn.TEXTAREA:textareaStartTagInBody(e,t);break;case cn.NOSCRIPT:e.options.scriptingEnabled?rawTextStartTagInBody(e,t):genericStartTagInBody(e,t);break;case cn.PLAINTEXT:plaintextStartTagInBody(e,t);break;case cn.COL:case cn.TH:case cn.TD:case cn.TR:case cn.HEAD:case cn.FRAME:case cn.TBODY:case cn.TFOOT:case cn.THEAD:case cn.CAPTION:case cn.COLGROUP:break;default:genericStartTagInBody(e,t)}}function bodyEndTagInBody(e,t){if(e.openElements.hasInScope(cn.BODY)&&(e.insertionMode=zn.AFTER_BODY,e.options.sourceCodeLocationInfo)){const n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e._setEndLocation(n,t)}}function htmlEndTagInBody(e,t){e.openElements.hasInScope(cn.BODY)&&(e.insertionMode=zn.AFTER_BODY,endTagAfterBody(e,t))}function addressEndTagInBody(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n))}function formEndTagInBody(e){const t=e.openElements.tmplCount>0,{formElement:n}=e;t||(e.formElement=null),(n||t)&&e.openElements.hasInScope(cn.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(cn.FORM):n&&e.openElements.remove(n))}function pEndTagInBody(e){e.openElements.hasInButtonScope(cn.P)||e._insertFakeElement(on.P,cn.P),e._closePElement()}function liEndTagInBody(e){e.openElements.hasInListItemScope(cn.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(cn.LI),e.openElements.popUntilTagNamePopped(cn.LI))}function ddEndTagInBody(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n))}function numberedHeaderEndTagInBody(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function appletEndTagInBody(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker())}function brEndTagInBody(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(on.BR,cn.BR),e.openElements.pop(),e.framesetOk=!1}function genericEndTagInBody(e,t){const n=t.tagName,r=t.tagID;for(let t=e.openElements.stackTop;t>0;t--){const s=e.openElements.items[t],i=e.openElements.tagIDs[t];if(r===i&&(r!==cn.UNKNOWN||e.treeAdapter.getTagName(s)===n)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.stackTop>=t&&e.openElements.shortenToLength(t);break}if(e._isSpecialElement(s,i))break}}function endTagInBody(e,t){switch(t.tagID){case cn.A:case cn.B:case cn.I:case cn.S:case cn.U:case cn.EM:case cn.TT:case cn.BIG:case cn.CODE:case cn.FONT:case cn.NOBR:case cn.SMALL:case cn.STRIKE:case cn.STRONG:callAdoptionAgency(e,t);break;case cn.P:pEndTagInBody(e);break;case cn.DL:case cn.UL:case cn.OL:case cn.DIR:case cn.DIV:case cn.NAV:case cn.PRE:case cn.MAIN:case cn.MENU:case cn.ASIDE:case cn.BUTTON:case cn.CENTER:case cn.FIGURE:case cn.FOOTER:case cn.HEADER:case cn.HGROUP:case cn.DIALOG:case cn.ADDRESS:case cn.ARTICLE:case cn.DETAILS:case cn.SEARCH:case cn.SECTION:case cn.SUMMARY:case cn.LISTING:case cn.FIELDSET:case cn.BLOCKQUOTE:case cn.FIGCAPTION:addressEndTagInBody(e,t);break;case cn.LI:liEndTagInBody(e);break;case cn.DD:case cn.DT:ddEndTagInBody(e,t);break;case cn.H1:case cn.H2:case cn.H3:case cn.H4:case cn.H5:case cn.H6:numberedHeaderEndTagInBody(e);break;case cn.BR:brEndTagInBody(e);break;case cn.BODY:bodyEndTagInBody(e,t);break;case cn.HTML:htmlEndTagInBody(e,t);break;case cn.FORM:formEndTagInBody(e);break;case cn.APPLET:case cn.OBJECT:case cn.MARQUEE:appletEndTagInBody(e,t);break;case cn.TEMPLATE:templateEndTagInHead(e,t);break;default:genericEndTagInBody(e,t)}}function eofInBody(e,t){e.tmplInsertionModeStack.length>0?eofInTemplate(e,t):stopParsing(e,t)}function endTagInText(e,t){var n;t.tagID===cn.SCRIPT&&(null===(n=e.scriptHandler)||void 0===n||n.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode}function eofInText(e,t){e._err(t,qt.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function characterInTable(e,t){if(void 0!==e.openElements.currentTagId&&er.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=!1,e.originalInsertionMode=e.insertionMode,e.insertionMode=zn.IN_TABLE_TEXT,t.type){case Vt.CHARACTER:characterInTableText(e,t);break;case Vt.WHITESPACE_CHARACTER:whitespaceCharacterInTableText(e,t)}else tokenInTable(e,t)}function captionStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,rn.HTML),e.insertionMode=zn.IN_CAPTION}function colgroupStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,rn.HTML),e.insertionMode=zn.IN_COLUMN_GROUP}function colStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(on.COLGROUP,cn.COLGROUP),e.insertionMode=zn.IN_COLUMN_GROUP,startTagInColumnGroup(e,t)}function tbodyStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,rn.HTML),e.insertionMode=zn.IN_TABLE_BODY}function tdStartTagInTable(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(on.TBODY,cn.TBODY),e.insertionMode=zn.IN_TABLE_BODY,startTagInTableBody(e,t)}function tableStartTagInTable(e,t){e.openElements.hasInTableScope(cn.TABLE)&&(e.openElements.popUntilTagNamePopped(cn.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function inputStartTagInTable(e,t){isHiddenInput(t)?e._appendElement(t,rn.HTML):tokenInTable(e,t),t.ackSelfClosing=!0}function formStartTagInTable(e,t){e.formElement||0!==e.openElements.tmplCount||(e._insertElement(t,rn.HTML),e.formElement=e.openElements.current,e.openElements.pop())}function startTagInTable(e,t){switch(t.tagID){case cn.TD:case cn.TH:case cn.TR:tdStartTagInTable(e,t);break;case cn.STYLE:case cn.SCRIPT:case cn.TEMPLATE:startTagInHead(e,t);break;case cn.COL:colStartTagInTable(e,t);break;case cn.FORM:formStartTagInTable(e,t);break;case cn.TABLE:tableStartTagInTable(e,t);break;case cn.TBODY:case cn.TFOOT:case cn.THEAD:tbodyStartTagInTable(e,t);break;case cn.INPUT:inputStartTagInTable(e,t);break;case cn.CAPTION:captionStartTagInTable(e,t);break;case cn.COLGROUP:colgroupStartTagInTable(e,t);break;default:tokenInTable(e,t)}}function endTagInTable(e,t){switch(t.tagID){case cn.TABLE:e.openElements.hasInTableScope(cn.TABLE)&&(e.openElements.popUntilTagNamePopped(cn.TABLE),e._resetInsertionMode());break;case cn.TEMPLATE:templateEndTagInHead(e,t);break;case cn.BODY:case cn.CAPTION:case cn.COL:case cn.COLGROUP:case cn.HTML:case cn.TBODY:case cn.TD:case cn.TFOOT:case cn.TH:case cn.THEAD:case cn.TR:break;default:tokenInTable(e,t)}}function tokenInTable(e,t){const n=e.fosterParentingEnabled;e.fosterParentingEnabled=!0,modeInBody(e,t),e.fosterParentingEnabled=n}function whitespaceCharacterInTableText(e,t){e.pendingCharacterTokens.push(t)}function characterInTableText(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=!0}function tokenInTableText(e,t){let n=0;if(e.hasNonWhitespacePendingCharacterToken)for(;n<e.pendingCharacterTokens.length;n++)tokenInTable(e,e.pendingCharacterTokens[n]);else for(;n<e.pendingCharacterTokens.length;n++)e._insertCharacters(e.pendingCharacterTokens[n]);e.insertionMode=e.originalInsertionMode,e._processToken(t)}var rr=new Set([cn.CAPTION,cn.COL,cn.COLGROUP,cn.TBODY,cn.TD,cn.TFOOT,cn.TH,cn.THEAD,cn.TR]);function startTagInCaption(e,t){const n=t.tagID;rr.has(n)?e.openElements.hasInTableScope(cn.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(cn.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=zn.IN_TABLE,startTagInTable(e,t)):startTagInBody(e,t)}function endTagInCaption(e,t){const n=t.tagID;switch(n){case cn.CAPTION:case cn.TABLE:e.openElements.hasInTableScope(cn.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(cn.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=zn.IN_TABLE,n===cn.TABLE&&endTagInTable(e,t));break;case cn.BODY:case cn.COL:case cn.COLGROUP:case cn.HTML:case cn.TBODY:case cn.TD:case cn.TFOOT:case cn.TH:case cn.THEAD:case cn.TR:break;default:endTagInBody(e,t)}}function startTagInColumnGroup(e,t){switch(t.tagID){case cn.HTML:startTagInBody(e,t);break;case cn.COL:e._appendElement(t,rn.HTML),t.ackSelfClosing=!0;break;case cn.TEMPLATE:startTagInHead(e,t);break;default:tokenInColumnGroup(e,t)}}function endTagInColumnGroup(e,t){switch(t.tagID){case cn.COLGROUP:e.openElements.currentTagId===cn.COLGROUP&&(e.openElements.pop(),e.insertionMode=zn.IN_TABLE);break;case cn.TEMPLATE:templateEndTagInHead(e,t);break;case cn.COL:break;default:tokenInColumnGroup(e,t)}}function tokenInColumnGroup(e,t){e.openElements.currentTagId===cn.COLGROUP&&(e.openElements.pop(),e.insertionMode=zn.IN_TABLE,e._processToken(t))}function startTagInTableBody(e,t){switch(t.tagID){case cn.TR:e.openElements.clearBackToTableBodyContext(),e._insertElement(t,rn.HTML),e.insertionMode=zn.IN_ROW;break;case cn.TH:case cn.TD:e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(on.TR,cn.TR),e.insertionMode=zn.IN_ROW,startTagInRow(e,t);break;case cn.CAPTION:case cn.COL:case cn.COLGROUP:case cn.TBODY:case cn.TFOOT:case cn.THEAD:e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=zn.IN_TABLE,startTagInTable(e,t));break;default:startTagInTable(e,t)}}function endTagInTableBody(e,t){const n=t.tagID;switch(t.tagID){case cn.TBODY:case cn.TFOOT:case cn.THEAD:e.openElements.hasInTableScope(n)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=zn.IN_TABLE);break;case cn.TABLE:e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=zn.IN_TABLE,endTagInTable(e,t));break;case cn.BODY:case cn.CAPTION:case cn.COL:case cn.COLGROUP:case cn.HTML:case cn.TD:case cn.TH:case cn.TR:break;default:endTagInTable(e,t)}}function startTagInRow(e,t){switch(t.tagID){case cn.TH:case cn.TD:e.openElements.clearBackToTableRowContext(),e._insertElement(t,rn.HTML),e.insertionMode=zn.IN_CELL,e.activeFormattingElements.insertMarker();break;case cn.CAPTION:case cn.COL:case cn.COLGROUP:case cn.TBODY:case cn.TFOOT:case cn.THEAD:case cn.TR:e.openElements.hasInTableScope(cn.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=zn.IN_TABLE_BODY,startTagInTableBody(e,t));break;default:startTagInTable(e,t)}}function endTagInRow(e,t){switch(t.tagID){case cn.TR:e.openElements.hasInTableScope(cn.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=zn.IN_TABLE_BODY);break;case cn.TABLE:e.openElements.hasInTableScope(cn.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=zn.IN_TABLE_BODY,endTagInTableBody(e,t));break;case cn.TBODY:case cn.TFOOT:case cn.THEAD:(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(cn.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=zn.IN_TABLE_BODY,endTagInTableBody(e,t));break;case cn.BODY:case cn.CAPTION:case cn.COL:case cn.COLGROUP:case cn.HTML:case cn.TD:case cn.TH:break;default:endTagInTable(e,t)}}function startTagInCell(e,t){const n=t.tagID;rr.has(n)?(e.openElements.hasInTableScope(cn.TD)||e.openElements.hasInTableScope(cn.TH))&&(e._closeTableCell(),startTagInRow(e,t)):startTagInBody(e,t)}function endTagInCell(e,t){const n=t.tagID;switch(n){case cn.TD:case cn.TH:e.openElements.hasInTableScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=zn.IN_ROW);break;case cn.TABLE:case cn.TBODY:case cn.TFOOT:case cn.THEAD:case cn.TR:e.openElements.hasInTableScope(n)&&(e._closeTableCell(),endTagInRow(e,t));break;case cn.BODY:case cn.CAPTION:case cn.COL:case cn.COLGROUP:case cn.HTML:break;default:endTagInBody(e,t)}}function startTagInSelect(e,t){switch(t.tagID){case cn.HTML:startTagInBody(e,t);break;case cn.OPTION:e.openElements.currentTagId===cn.OPTION&&e.openElements.pop(),e._insertElement(t,rn.HTML);break;case cn.OPTGROUP:e.openElements.currentTagId===cn.OPTION&&e.openElements.pop(),e.openElements.currentTagId===cn.OPTGROUP&&e.openElements.pop(),e._insertElement(t,rn.HTML);break;case cn.HR:e.openElements.currentTagId===cn.OPTION&&e.openElements.pop(),e.openElements.currentTagId===cn.OPTGROUP&&e.openElements.pop(),e._appendElement(t,rn.HTML),t.ackSelfClosing=!0;break;case cn.INPUT:case cn.KEYGEN:case cn.TEXTAREA:case cn.SELECT:e.openElements.hasInSelectScope(cn.SELECT)&&(e.openElements.popUntilTagNamePopped(cn.SELECT),e._resetInsertionMode(),t.tagID!==cn.SELECT&&e._processStartTag(t));break;case cn.SCRIPT:case cn.TEMPLATE:startTagInHead(e,t)}}function endTagInSelect(e,t){switch(t.tagID){case cn.OPTGROUP:e.openElements.stackTop>0&&e.openElements.currentTagId===cn.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===cn.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===cn.OPTGROUP&&e.openElements.pop();break;case cn.OPTION:e.openElements.currentTagId===cn.OPTION&&e.openElements.pop();break;case cn.SELECT:e.openElements.hasInSelectScope(cn.SELECT)&&(e.openElements.popUntilTagNamePopped(cn.SELECT),e._resetInsertionMode());break;case cn.TEMPLATE:templateEndTagInHead(e,t)}}function startTagInSelectInTable(e,t){const n=t.tagID;n===cn.CAPTION||n===cn.TABLE||n===cn.TBODY||n===cn.TFOOT||n===cn.THEAD||n===cn.TR||n===cn.TD||n===cn.TH?(e.openElements.popUntilTagNamePopped(cn.SELECT),e._resetInsertionMode(),e._processStartTag(t)):startTagInSelect(e,t)}function endTagInSelectInTable(e,t){const n=t.tagID;n===cn.CAPTION||n===cn.TABLE||n===cn.TBODY||n===cn.TFOOT||n===cn.THEAD||n===cn.TR||n===cn.TD||n===cn.TH?e.openElements.hasInTableScope(n)&&(e.openElements.popUntilTagNamePopped(cn.SELECT),e._resetInsertionMode(),e.onEndTag(t)):endTagInSelect(e,t)}function startTagInTemplate(e,t){switch(t.tagID){case cn.BASE:case cn.BASEFONT:case cn.BGSOUND:case cn.LINK:case cn.META:case cn.NOFRAMES:case cn.SCRIPT:case cn.STYLE:case cn.TEMPLATE:case cn.TITLE:startTagInHead(e,t);break;case cn.CAPTION:case cn.COLGROUP:case cn.TBODY:case cn.TFOOT:case cn.THEAD:e.tmplInsertionModeStack[0]=zn.IN_TABLE,e.insertionMode=zn.IN_TABLE,startTagInTable(e,t);break;case cn.COL:e.tmplInsertionModeStack[0]=zn.IN_COLUMN_GROUP,e.insertionMode=zn.IN_COLUMN_GROUP,startTagInColumnGroup(e,t);break;case cn.TR:e.tmplInsertionModeStack[0]=zn.IN_TABLE_BODY,e.insertionMode=zn.IN_TABLE_BODY,startTagInTableBody(e,t);break;case cn.TD:case cn.TH:e.tmplInsertionModeStack[0]=zn.IN_ROW,e.insertionMode=zn.IN_ROW,startTagInRow(e,t);break;default:e.tmplInsertionModeStack[0]=zn.IN_BODY,e.insertionMode=zn.IN_BODY,startTagInBody(e,t)}}function endTagInTemplate(e,t){t.tagID===cn.TEMPLATE&&templateEndTagInHead(e,t)}function eofInTemplate(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(cn.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):stopParsing(e,t)}function startTagAfterBody(e,t){t.tagID===cn.HTML?startTagInBody(e,t):tokenAfterBody(e,t)}function endTagAfterBody(e,t){var n;if(t.tagID===cn.HTML){if(e.fragmentContext||(e.insertionMode=zn.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===cn.HTML){e._setEndLocation(e.openElements.items[0],t);const r=e.openElements.items[1];r&&!(null===(n=e.treeAdapter.getNodeSourceCodeLocation(r))||void 0===n?void 0:n.endTag)&&e._setEndLocation(r,t)}}else tokenAfterBody(e,t)}function tokenAfterBody(e,t){e.insertionMode=zn.IN_BODY,modeInBody(e,t)}function startTagInFrameset(e,t){switch(t.tagID){case cn.HTML:startTagInBody(e,t);break;case cn.FRAMESET:e._insertElement(t,rn.HTML);break;case cn.FRAME:e._appendElement(t,rn.HTML),t.ackSelfClosing=!0;break;case cn.NOFRAMES:startTagInHead(e,t)}}function endTagInFrameset(e,t){t.tagID!==cn.FRAMESET||e.openElements.isRootHtmlElementCurrent()||(e.openElements.pop(),e.fragmentContext||e.openElements.currentTagId===cn.FRAMESET||(e.insertionMode=zn.AFTER_FRAMESET))}function startTagAfterFrameset(e,t){switch(t.tagID){case cn.HTML:startTagInBody(e,t);break;case cn.NOFRAMES:startTagInHead(e,t)}}function endTagAfterFrameset(e,t){t.tagID===cn.HTML&&(e.insertionMode=zn.AFTER_AFTER_FRAMESET)}function startTagAfterAfterBody(e,t){t.tagID===cn.HTML?startTagInBody(e,t):tokenAfterAfterBody(e,t)}function tokenAfterAfterBody(e,t){e.insertionMode=zn.IN_BODY,modeInBody(e,t)}function startTagAfterAfterFrameset(e,t){switch(t.tagID){case cn.HTML:startTagInBody(e,t);break;case cn.NOFRAMES:startTagInHead(e,t)}}function nullCharacterInForeignContent(e,t){t.chars=Gt,e._insertCharacters(t)}function characterInForeignContent(e,t){e._insertCharacters(t),e.framesetOk=!1}function popUntilHtmlOrIntegrationPoint(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==rn.HTML&&void 0!==e.openElements.currentTagId&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop()}function startTagInForeignContent(e,t){if(causesExit(t))popUntilHtmlOrIntegrationPoint(e),e._startTagOutsideForeignContent(t);else{const n=e._getAdjustedCurrentElement(),r=e.treeAdapter.getNamespaceURI(n);r===rn.MATHML?adjustTokenMathMLAttrs(t):r===rn.SVG&&(adjustTokenSVGTagName(t),adjustTokenSVGAttrs(t)),adjustTokenXMLAttrs(t),t.selfClosing?e._appendElement(t,r):e._insertElement(t,r),t.ackSelfClosing=!0}}function endTagInForeignContent(e,t){if(t.tagID===cn.P||t.tagID===cn.BR)return popUntilHtmlOrIntegrationPoint(e),void e._endTagOutsideForeignContent(t);for(let n=e.openElements.stackTop;n>0;n--){const r=e.openElements.items[n];if(e.treeAdapter.getNamespaceURI(r)===rn.HTML){e._endTagOutsideForeignContent(t);break}const s=e.treeAdapter.getTagName(r);if(s.toLowerCase()===t.tagName){t.tagName=s,e.openElements.shortenToLength(n);break}}}String.prototype.codePointAt,on.AREA,on.BASE,on.BASEFONT,on.BGSOUND,on.BR,on.COL,on.EMBED,on.FRAME,on.HR,on.IMG,on.INPUT,on.KEYGEN,on.LINK,on.META,on.PARAM,on.SOURCE,on.TRACK,on.WBR;function parse(e,t){return nr.parse(e,t)}function annotateHtmlSource(e,t){const n=parse(e,{sourceCodeLocationInfo:!0}),r=new Map,stampsFor=e=>Object.entries(t(e)).map(([e,t])=>{if(!/^[a-z][a-z0-9-]*$/.test(e))throw new Error(`Invalid HTML annotation name: ${e}`);return` ${e}="${escapeAttribute2(t)}"`}).join(""),s=impliedBodyInsertion(n);null!==s&&r.set(s,`<body${stampsFor(s)}>`);const visit=t=>{if("tagName"in t){const n=t.sourceCodeLocation?.startTag?.startOffset;if(void 0!==n){const t=/^<[^\s/>]+/.exec(e.slice(n));t&&r.set(n+t[0].length,stampsFor(n))}"content"in t&&visit(t.content)}if("childNodes"in t)for(const e of t.childNodes)visit(e)};visit(n);const i=[];let a=0;for(const[t,n]of[...r].sort(([e],[t])=>e-t))i.push(e.slice(a,t),n),a=t;return i.push(e.slice(a)),i.join("")}function impliedBodyInsertion(e){const t=e.childNodes.find(e=>"tagName"in e&&"html"===e.tagName);if(!t||!("childNodes"in t))return null;const n=t.childNodes.find(e=>"tagName"in e&&"body"===e.tagName);if(!n||n.sourceCodeLocation)return null;const r=t.childNodes.find(e=>"tagName"in e&&"head"===e.tagName),s=e.childNodes.find(e=>"#documentType"===e.nodeName);return Math.max(0,s?.sourceCodeLocation?.endOffset??0,t.sourceCodeLocation?.startTag?.endOffset??0,r?.sourceCodeLocation?.endOffset??0)}function escapeAttribute2(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;")}var sr=".tempo-html-paste",ir=[".html",".htm"];function hasHtmlStoryboardEntryExtension(e){const t=e.toLowerCase();return ir.some(e=>t.endsWith(e))}function annotateHtmlStoryboardRevision(e,t){const n=sourceVersionHash(e);return annotateHtmlSource(e,e=>({"data-tempo-filepath":t.filepath,"data-tempo-position":String(e),"data-tempo-modifiedts":String(Math.trunc(t.mtime)),"data-tempo-source-version":n}))}async function authorizeHtmlStoryboardResource(e){const t=await Mt(e);if(!(await xt(t)).isFile()||!hasHtmlStoryboardEntryExtension(t))throw new Error("HTML storyboard source must be an existing .html or .htm file");const n=Lt.dirname(t);return{filepath:t,authorization:{root:n,entryFile:Lt.basename(n)===sr?t:null}}}var ar=new Set([...ir,".css",".js",".mjs",".cjs",".png",".jpg",".jpeg",".gif",".svg",".webp",".avif",".ico",".bmp",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".ogg",".wav",".webm"]);function isWithinRoot(e,t){const n=Lt.relative(e,t);return""===n||!n.startsWith(`..${Lt.sep}`)&&".."!==n&&!Lt.isAbsolute(n)}async function resolveHtmlStoryboardResource(e,t){if(/%2f|%5c/i.test(t))return{status:400};let n;try{n=decodeURIComponent(t).replace(/^[/\\]+/,"")}catch{return{status:400}}if(!n)return{status:400};if(!ar.has(Lt.extname(n).toLowerCase()))return{status:403};const r=Lt.resolve(e.root,n);if(!isWithinRoot(e.root,r))return{status:403};let s;try{s=await Mt(r)}catch{return{status:404}}if(!isWithinRoot(e.root,s)||null!==e.entryFile&&s!==e.entryFile||!ar.has(Lt.extname(s).toLowerCase()))return{status:403};try{if(!(await xt(s)).isFile())return{status:404}}catch{return{status:404}}return{status:200,filepath:s}}var or={".html":"text/html",".htm":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".cjs":"text/javascript",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".bmp":"image/bmp",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".mp3":"audio/mpeg",".mp4":"video/mp4",".ogg":"audio/ogg",".wav":"audio/wav",".webm":"video/webm"};async function openHeadlessHtmlSource(e,t,n=createCaptureImageNormalizer()){const r=await authorizeHtmlStoryboardResource(t),s=await At(r.filepath,"utf8"),i=annotateHtmlStoryboardRevision(s,{filepath:r.filepath,mtime:(await _t(r.filepath)).mtimeMs}),a=`https://${bt(24).toString("hex")}.tempo-html.invalid`,o=`${a}/${encodeURIComponent(kt.basename(r.filepath))}`,c=new Set,handler=async e=>{const t=e.request(),s=new URL(t.url());if(s.origin!==a)return"file:"===s.protocol||t.isNavigationRequest()?e.abort("blockedbyclient"):e.fallback();const o=await resolveHtmlStoryboardResource(r.authorization,s.pathname);if(200!==o.status)return c.add(`${s.pathname}: ${o.status}`),e.fulfill({status:o.status,body:""});try{const s=o.filepath===r.filepath?i:await At(o.filepath),a="image"===t.resourceType()&&Buffer.isBuffer(s)?await n(s):s;await e.fulfill({status:200,contentType:a!==s?"image/png":or[kt.extname(o.filepath).toLowerCase()],headers:{"cache-control":"no-store","content-security-policy":"sandbox allow-scripts allow-same-origin"},body:a})}catch(t){c.add(`${s.pathname}: ${String(t)}`),await e.abort().catch(()=>{})}};return await e.route("**/*",handler),{url:o,assertResources(){if(c.size)throw new Error(`HTML storyboard resources failed: ${[...c].join(", ")}`)},dispose:()=>e.unroute("**/*",handler)}}function astroStoryboardPath(e,t){return`/__tempo/astro/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function astroCaptureUrl(e,t){if("astro"!==t.source?.kind)throw new Error("Expected an Astro document component");return new URL(astroStoryboardPath(t.source.canvasPath,t.storyboardId).slice(1),e.replace(/\/?$/,"/")).href}async function settleAstroDocument(e,t,n){if("astro"!==t.source?.kind)throw new Error("Expected an Astro document component");const r=await e.locator('meta[name="tempo-astro-storyboard"]').getAttribute("content",{timeout:n}),s=r&&JSON.parse(r);if(!s||s.canvasPath!==t.source.canvasPath||s.storyboardId!==t.storyboardId||t.source.revision&&s.revision!==t.source.revision)throw new Error("Astro preview does not match the requested storyboard revision");await e.waitForFunction(ht,void 0,{timeout:n})}var cr='return (function documentVisualReadiness(doc, options) {\n return new Promise(function (resolve) {\n var view = doc.defaultView;\n var failures = [];\n var failedLinks = new WeakMap();\n var checks = new Set();\n var cleanups = new Set();\n var stopped = false;\n var timer;\n var observer;\n var remaining = Math.max(\n 0,\n Math.min(\n options.timeoutMs,\n options.resourceBudget\n ? options.resourceBudget.remainingMs\n : options.timeoutMs,\n ),\n );\n var timerAt;\n var queued = 0;\n var admittedSlice;\n var checksPending = false;\n var checksDirty = false;\n var revision = 0;\n var terminalResolve;\n var terminal = new Promise(function (done) {\n terminalResolve = done;\n });\n function failure(kind, url) {\n if (\n !failures.some(function (item) {\n return item.kind === kind && item.url === url;\n })\n )\n failures.push(url ? { kind: kind, url: url } : { kind: kind });\n }\n function finish(status) {\n if (stopped) return;\n if (status === "ready" && options.onReadyProof) options.onReadyProof();\n if (stopped) return;\n stopped = true;\n if (options.resourceBudget)\n options.resourceBudget.remainingMs = queued\n ? remaining\n : Math.max(\n 0,\n remaining - (timerAt === undefined ? 0 : Date.now() - timerAt),\n );\n clearTimeout(timer);\n if (observer) observer.disconnect();\n for (var cleanup of cleanups) cleanup();\n cleanups.clear();\n checks.clear();\n if (options.signal) options.signal.removeEventListener("abort", cancel);\n terminalResolve();\n resolve({ status: status, failures: failures });\n }\n function cancel() {\n finish("cancelled");\n }\n if (options.signal && options.signal.aborted) {\n cancel();\n return;\n }\n if (!view) {\n cancel();\n return;\n }\n if (options.signal)\n options.signal.addEventListener("abort", cancel, { once: true });\n function startTimer() {\n timerAt = Date.now();\n timer = setTimeout(function () {\n finish("timeout");\n }, remaining);\n }\n startTimer();\n async function work(callback) {\n if (!options.scheduleWork) return callback();\n if (stopped) return;\n if (queued++ === 0) {\n clearTimeout(timer);\n remaining = Math.max(0, remaining - (Date.now() - timerAt));\n }\n try {\n if (\n admittedSlice &&\n admittedSlice.canContinue &&\n admittedSlice.canContinue()\n )\n return callback(admittedSlice);\n return await Promise.race([\n terminal,\n options.scheduleWork(function (slice) {\n admittedSlice = slice;\n if (!stopped) return callback(slice);\n }, options.signal),\n ]);\n } finally {\n if (--queued === 0 && !stopped) startTimer();\n }\n }\n async function mapWork(items, callback) {\n var rows = [];\n var offset = 0;\n while (offset < items.length && !stopped) {\n await work(function (slice) {\n var limit = Math.min(offset + 32, items.length);\n do {\n var value = callback(items[offset++]);\n if (value !== undefined) rows.push(value);\n } while (offset < limit && (!slice || slice.hasTime()));\n });\n }\n return rows;\n }\n if (remaining <= 0) {\n finish("timeout");\n return;\n }\n function changed() {\n if (stopped) return;\n if (!options.scheduleWork) {\n for (var check of checks) check();\n return;\n }\n if (checksPending) {\n checksDirty = true;\n return;\n }\n checksPending = true;\n checksDirty = false;\n mapWork(Array.from(checks), function (check) {\n check();\n })\n .finally(function () {\n checksPending = false;\n if (checksDirty) changed();\n })\n .catch(function () {\n finish("cancelled");\n });\n }\n observer = new view.MutationObserver(function () {\n revision++;\n changed();\n });\n observer.observe(doc, { subtree: true, childList: true, attributes: true });\n // Opt-in admission may begin after a resource\'s terminal event. Preserve\n // its URL-scoped failure evidence while the initial inventory is queued.\n if (options.scheduleWork) {\n var captureError = function (event) {\n var link = event.target;\n if (\n link &&\n link.tagName === "LINK" &&\n link.relList.contains("stylesheet") &&\n applicable(link)\n ) {\n failedLinks.set(link, link.href);\n failure("stylesheet", link.href);\n changed();\n }\n };\n doc.addEventListener("error", captureError, true);\n cleanups.add(function () {\n doc.removeEventListener("error", captureError, true);\n });\n }\n\n function applicable(link) {\n return (\n link.isConnected &&\n !link.disabled &&\n (!link.media || !view.matchMedia || view.matchMedia(link.media).matches)\n );\n }\n function links() {\n return Array.from(doc.querySelectorAll(\'link[rel~="stylesheet"]\')).filter(\n applicable,\n );\n }\n function visibleImage(img) {\n if (!img.isConnected) return false;\n var rect = img.getBoundingClientRect();\n var style = view.getComputedStyle(img);\n return (\n rect.width > 0 &&\n rect.height > 0 &&\n rect.bottom > 0 &&\n rect.right > 0 &&\n rect.top < view.innerHeight &&\n rect.left < view.innerWidth &&\n style.visibility !== "hidden" &&\n style.visibility !== "collapse"\n );\n }\n function images() {\n return Array.from(doc.querySelectorAll("img"))\n .filter(visibleImage)\n .map(function (img) {\n return [img, img.currentSrc, img.src, img.srcset];\n });\n }\n async function scheduledImages() {\n var candidates,\n selected = [],\n offset = 0;\n do {\n await work(function (slice) {\n if (!candidates) candidates = Array.from(doc.querySelectorAll("img"));\n var limit = Math.min(offset + 32, candidates.length);\n while (offset < limit) {\n var img = candidates[offset++];\n if (visibleImage(img))\n selected.push([img, img.currentSrc, img.src, img.srcset]);\n if (slice && !slice.hasTime()) break;\n }\n });\n } while (!stopped && candidates && offset < candidates.length);\n return selected;\n }\n function decodeImage(img) {\n if (!img.isConnected || !visibleImage(img)) return {};\n if (!img.naturalWidth) {\n failure("image", img.currentSrc || img.src);\n return {};\n }\n // A holder keeps a resource decode promise outside CPU admission.\n return {\n decode:\n img.decode &&\n img.decode().catch(function () {\n failure("image", img.currentSrc || img.src);\n }),\n };\n }\n function waitElement(element, ready, kind, url) {\n if (ready()) return Promise.resolve();\n return new Promise(function (done) {\n function requestCheck() {\n if (options.scheduleWork) changed();\n else check();\n }\n function cleanup() {\n element.removeEventListener("load", requestCheck);\n element.removeEventListener("error", error);\n checks.delete(check);\n cleanups.delete(cleanup);\n }\n function check() {\n if (ready()) {\n cleanup();\n done();\n }\n }\n function error() {\n failure(kind, url);\n if (kind === "stylesheet") failedLinks.set(element, url);\n cleanup();\n done();\n }\n cleanups.add(cleanup);\n checks.add(check);\n element.addEventListener("load", requestCheck);\n element.addEventListener("error", error);\n check();\n });\n }\n function inventory(includeImages) {\n return {\n links: links().map(function (link) {\n // Resource evidence can change during a font/image await without\n // changing this node\'s URL or media. Revalidate the same readiness\n // facts, not CSSStyleSheet object identities or a content hash.\n return [\n link,\n link.href,\n link.media,\n !!link.sheet,\n link.getAttribute("data-tempo-stylesheet-pending") === link.href,\n link.getAttribute("data-tempo-stylesheet-error") === link.href,\n ];\n }),\n images: includeImages ? images() : [],\n styles: Array.from(doc.querySelectorAll("style")).map(function (style) {\n return [style, style.textContent];\n }),\n };\n }\n async function scheduledInventory(includeImages) {\n var candidates,\n offset = 0;\n var result = { revision: revision, links: [], images: [], styles: [] };\n // Small inventories finish in one admission. Large ones retain the\n // same 32-node/time bound, without paying a task per resource category.\n do {\n await work(function (slice) {\n if (!candidates)\n candidates = Array.from(\n doc.querySelectorAll(\n includeImages\n ? \'link[rel~="stylesheet"],img,style\'\n : \'link[rel~="stylesheet"],style\',\n ),\n );\n var limit = Math.min(offset + 32, candidates.length);\n while (offset < limit) {\n var node = candidates[offset++];\n if (node.localName === "link" && applicable(node)) {\n result.links.push([\n node,\n node.href,\n node.media,\n !!node.sheet,\n node.getAttribute("data-tempo-stylesheet-pending") ===\n node.href,\n node.getAttribute("data-tempo-stylesheet-error") === node.href,\n ]);\n } else if (node.localName === "img" && visibleImage(node)) {\n result.images.push([\n node,\n node.currentSrc,\n node.src,\n node.srcset,\n ]);\n } else if (node.localName === "style") {\n result.styles.push([node, node.textContent]);\n }\n if (slice && !slice.hasTime()) break;\n }\n });\n } while (!stopped && candidates && offset < candidates.length);\n return result;\n }\n function same(a, b) {\n return ["links", "images", "styles"].every(function (key) {\n return (\n a[key].length === b[key].length &&\n a[key].every(function (row, i) {\n return row.every(function (value, j) {\n return value === b[key][i][j];\n });\n })\n );\n });\n }\n async function run() {\n while (!stopped) {\n var before = options.scheduleWork\n ? await scheduledInventory(false)\n : inventory(false);\n if (stopped) return;\n await Promise.race([\n terminal,\n Promise.all(\n before.links\n .map(function (row) {\n return row[0];\n })\n .map(function (link) {\n if (\n (!link.sheet &&\n (options.failedStylesheetUrls || []).includes(link.href)) ||\n link.getAttribute("data-tempo-stylesheet-error") === link.href\n ) {\n failedLinks.set(link, link.href);\n failure("stylesheet", link.href);\n }\n return waitElement(\n link,\n function () {\n return (\n !applicable(link) ||\n (link.getAttribute("data-tempo-stylesheet-pending") !==\n link.href &&\n (!!link.sheet || failedLinks.get(link) === link.href))\n );\n },\n "stylesheet",\n link.href,\n );\n }),\n ),\n ]);\n if (stopped) return;\n // Force stylesheet application/layout BEFORE reading the current font\n // promise. A previously fulfilled promise cannot certify newly used fonts.\n var readFontPromise = function () {\n if (doc.documentElement) doc.documentElement.getBoundingClientRect();\n // Read the CURRENT promise in the same admitted layout callback.\n return { promise: doc.fonts && doc.fonts.ready };\n };\n var currentFonts = options.scheduleWork\n ? await work(readFontPromise)\n : readFontPromise();\n if (stopped) return;\n var fontPromise = currentFonts.promise;\n var fontRejected = false;\n await Promise.race([\n terminal,\n Promise.resolve(fontPromise).catch(function () {\n fontRejected = true;\n failure("font");\n }),\n ]);\n if (stopped) return;\n // Fonts can change which images are visible. Capture the image evidence\n // only after their layout settles, before awaiting any selected decode.\n var selected = options.scheduleWork\n ? await scheduledImages()\n : images();\n if (stopped) return;\n before.images = selected;\n if (options.scheduleWork) {\n var pendingImages = [],\n pendingLoads = [];\n var imageWaits = await mapWork(selected, function (row) {\n var img = row[0];\n if (img.loading === "lazy") img.loading = "eager";\n // Warm images need no load-event continuation. Prepare their\n // decodes in this bounded batch rather than one new task per image.\n if (img.complete) {\n var proof = decodeImage(img);\n return Promise.race([terminal, Promise.resolve(proof.decode)]);\n }\n pendingImages.push(img);\n pendingLoads.push(\n Promise.race([\n terminal,\n waitElement(\n img,\n function () {\n return (\n !img.isConnected || !visibleImage(img) || img.complete\n );\n },\n "image",\n img.currentSrc || img.src,\n ),\n ]),\n );\n });\n await Promise.race([terminal, Promise.all(pendingLoads)]);\n if (stopped) return;\n // Load events often arrive together from the browser cache. Decode\n // their now-ready images in bounded batches, rather than granting\n // each event its own renderer task. Warm decodes above stay in flight.\n var loadedDecodes = await mapWork(pendingImages, function (img) {\n var proof = decodeImage(img);\n return Promise.race([terminal, Promise.resolve(proof.decode)]);\n });\n await Promise.race([\n terminal,\n Promise.all(imageWaits.concat(loadedDecodes)),\n ]);\n } else {\n await Promise.race([\n terminal,\n Promise.all(\n selected.map(async function (row) {\n var img = row[0];\n if (img.loading === "lazy") img.loading = "eager";\n await Promise.race([\n terminal,\n waitElement(\n img,\n function () {\n return (\n !img.isConnected || !visibleImage(img) || img.complete\n );\n },\n "image",\n img.currentSrc || img.src,\n ),\n ]);\n if (stopped || !img.isConnected || !visibleImage(img)) return;\n if (!img.naturalWidth) {\n failure("image", img.currentSrc || img.src);\n return;\n }\n if (img.decode)\n await img.decode().catch(function () {\n failure("image", img.currentSrc || img.src);\n });\n }),\n ),\n ]);\n }\n if (stopped) return;\n if (doc.fonts)\n doc.fonts.forEach(function (face) {\n if (face.status === "error") failure("font", face.family);\n });\n var after = options.scheduleWork\n ? await scheduledInventory(true)\n : inventory(true);\n if (stopped) return;\n // A scheduled inventory can span multiple tasks. A mutation during\n // its geometry reads cannot certify a mixed document observation.\n if (options.scheduleWork && observer.takeRecords().length) revision++;\n if (\n (!options.scheduleWork ||\n options.requireStableDom === false ||\n (before.revision === after.revision &&\n after.revision === revision)) &&\n same(before, after) &&\n (!doc.fonts ||\n fontRejected ||\n (doc.fonts.status !== "loading" && doc.fonts.ready === fontPromise))\n ) {\n finish("ready");\n return;\n }\n // Let resource events and the deadline run if this document keeps\n // discovering assets; never monopolize the microtask queue.\n await Promise.race([\n terminal,\n new Promise(function (done) {\n var retry = setTimeout(function () {\n cleanups.delete(cleanup);\n done();\n }, 0);\n function cleanup() {\n clearTimeout(retry);\n done();\n }\n cleanups.add(cleanup);\n }),\n ]);\n }\n }\n // Unexpected browser/document loss is not a successful fallback rendering.\n run().catch(function () {\n finish("cancelled");\n });\n });\n})(doc, options);';function buildVisualReadyWaitScript(e,t=[]){return`(function(doc, options) {${cr}})(document, ${JSON.stringify({timeoutMs:e,failedStylesheetUrls:t})})`}function requireVisualReadiness(e,t){if("ready"!==e?.status)throw new Error(`[frame-pool-readiness:${e?.status??"invalid"}] Document assets did not settle`);if(!t)throw new Error("[frame-pool-readiness:timeout] Native asset requests did not settle")}function extractStoryboardDomInPage(e){const readAttributes=e=>{const t={};for(const n of Array.from(e.attributes))/^on/i.test(n.name)||(t[n.name]=n.value);return t},t=document.querySelector(e);if(!t)throw new Error(`storyboard element not found for selector ${e}`);const n=document.head.cloneNode(!0),r=t.cloneNode(!0),s=[t,...Array.from(t.querySelectorAll("*"))],i=[r,...Array.from(r.querySelectorAll("*"))],a=new Map;s.forEach((e,t)=>a.set(e,i[t]));const o=Array.from(document.head.querySelectorAll("*")),c=Array.from(n.querySelectorAll("*"));o.forEach((e,t)=>a.set(e,c[t]));const l=Array.from(document.querySelectorAll("style,link[rel~='stylesheet']"));l.forEach(e=>{const t=a.get(e)??e.cloneNode(!0);a.has(e)||n.appendChild(t);const r=e.sheet;if(r)if(r.disabled)t.parentNode?.removeChild(t);else try{const n=document.createElement("style");for(const t of Array.from(e.attributes))["href","rel","integrity","crossorigin"].includes(t.name)||n.setAttribute(t.name,t.value);let s=Array.from(r.cssRules).map(e=>e.cssText).join("\n");const i=r.href??document.baseURI;s=s.replace(/url\(\s*(['"]?)([^'")]+?)\1\s*\)/gi,(e,t,n)=>{try{return`url("${new URL(n,i).href}")`}catch{return e}}),n.textContent=s,t.parentNode?.replaceChild(n,t)}catch{}});for(const e of Array.from(document.adoptedStyleSheets??[])){if(e.disabled)continue;const t=document.createElement("style");t.textContent=Array.from(e.cssRules).map(e=>e.cssText).join("\n"),n.appendChild(t)}s.forEach((e,t)=>{const n=i[t];e instanceof HTMLInputElement?(n.setAttribute("value",e.value),n.toggleAttribute("checked",e.checked)):e instanceof HTMLTextAreaElement?n.textContent=e.value:e instanceof HTMLOptionElement&&n.toggleAttribute("selected",e.selected)});for(const e of[n,r]){for(const t of Array.from(e.querySelectorAll("script")))t.remove();for(const t of[e,...Array.from(e.querySelectorAll("*"))])for(const e of Array.from(t.attributes))(/^on/i.test(e.name)||/^(href|src|action|formaction)$/i.test(e.name)&&/^\s*javascript:/i.test(e.value))&&t.removeAttribute(e.name)}return{headHtml:n.innerHTML,htmlAttributes:readAttributes(document.documentElement),bodyAttributes:readAttributes(document.body),elementHtml:r.outerHTML}}function assessPageStylesInPage(e){let t=0,n=0;for(const e of Array.from(document.styleSheets))try{t+=e.cssRules.length}catch{n+=1}let r=0;for(const e of Array.from(document.querySelectorAll("style")))r+=(e.textContent??"").length;const s=document.querySelector(e)??document.body;return{authorRuleCount:t,unreadableSheetCount:n,styleTextBytes:r,classElementCount:s.querySelectorAll("[class]").length,inlineStyledElementCount:s.querySelectorAll("[style]").length}}function watchRenderErrorsInPage(e){const t=document.querySelector(e.selector),n=[],record=()=>{if(t)for(const r of Array.from(t.querySelectorAll(e.errorSelector))){const t=r.getAttribute(e.messageAttribute)||"unknown error";n.includes(t)||n.push(t)}};record();const r=new MutationObserver(record);t&&r.observe(t,{subtree:!0,childList:!0,attributes:!0,attributeFilter:[e.messageAttribute]}),window.__tempoCaptureRenderErrors=()=>(r.takeRecords(),r.disconnect(),record(),n)}function readRenderErrorsInPage(){const e=window,t=e.__tempoCaptureRenderErrors;return delete e.__tempoCaptureRenderErrors,t?t():[]}async function inlinePortableHtmlInPage(e){const t=[],warn=e=>{t.push(e)},cssUrlMatcher=()=>/url\(\s*(['"]?)([^'")]+?)\1\s*\)/gi,isPubliclyFetchableUrl=e=>{if("http:"!==e.protocol&&"https:"!==e.protocol)return!1;const t=e.hostname;return!t.endsWith(".tempo-html.invalid")&&("localhost"!==t&&!t.endsWith(".localhost")&&("::1"!==t&&"[::1]"!==t&&"0.0.0.0"!==t&&(!/^127\./.test(t)&&!(/^10\./.test(t)||/^192\.168\./.test(t)||/^172\.(1[6-9]|2\d|3[01])\./.test(t)))))},resolveAssetUrl=(e,t)=>{const n=e?.trim();if(!n||n.startsWith("data:")||n.startsWith("#"))return null;try{const e=new URL(n,t);return isPubliclyFetchableUrl(e)?null:e.href}catch{return null}},bytesToBase64=e=>{let t="";const n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)},blobToDataUrl=async(e,t)=>{const n=new Uint8Array(await e.arrayBuffer()),r=e.type||t||"application/octet-stream";return`data:${r};base64,${bytesToBase64(n)}`},inlineCssUrls=async(e,t)=>{const n=new Map;for(const r of e.matchAll(cssUrlMatcher())){const e=r[2].trim(),s=resolveAssetUrl(e,t);s&&n.set(e,s)}if(0===n.size)return e;const r=new Map;return await Promise.all(Array.from(n,async([e,t])=>{try{const n=await fetch(t);if(!n.ok)throw new Error(`HTTP ${n.status}`);const s=await n.blob(),i=s.type||n.headers.get("content-type")||"";r.set(e,await blobToDataUrl(s,i))}catch(e){warn(`failed to inline CSS asset ${t}: ${String(e)}`)}})),0===r.size?e:e.replace(cssUrlMatcher(),(e,t,n)=>{const s=r.get(n.trim());return s?`url("${s}")`:e})},n=(new DOMParser).parseFromString(e.html,"text/html"),r=n.querySelector("base[href]")?.getAttribute("href")??e.baseUrl;await Promise.all(Array.from(n.querySelectorAll("style")).map(async e=>{const t=e.textContent??"";t.includes("url(")&&(e.textContent=await inlineCssUrls(t,r))})),await Promise.all(Array.from(n.querySelectorAll('[style*="url("]')).map(async e=>{const t=e.getAttribute("style");t&&e.setAttribute("style",await inlineCssUrls(t,r))})),await Promise.all(Array.from(n.querySelectorAll('link[rel~="stylesheet"][href]')).map(async e=>{const t=resolveAssetUrl(e.getAttribute("href"),r);if(t)try{const r=await fetch(t);if(!r.ok)throw new Error(`HTTP ${r.status}`);const s=await inlineCssUrls(await r.text(),t),i=n.createElement("style");i.setAttribute("data-tempo-inlined-stylesheet","true");const a=e.getAttribute("media");a&&i.setAttribute("media",a),i.textContent=s,e.replaceWith(i)}catch(e){warn(`failed to inline stylesheet ${t}: ${String(e)}`)}})),await Promise.all(Array.from(n.querySelectorAll("img[src]")).map(async e=>{const t=resolveAssetUrl(e.getAttribute("src"),r);if(t)try{const n=await fetch(t);if(!n.ok)throw new Error(`HTTP ${n.status}`);const r=await n.blob(),s=r.type||n.headers.get("content-type")||"";if(!s.toLowerCase().startsWith("image/"))return;e.setAttribute("src",await blobToDataUrl(r,s)),e.removeAttribute("srcset"),e.setAttribute("loading","eager"),e.setAttribute("decoding","sync")}catch(e){warn(`failed to inline image ${t}: ${String(e)}`)}}));for(const e of Array.from(n.querySelectorAll("script")))e.remove();const s=n.querySelector("base[href]");return s&&resolveAssetUrl(s.getAttribute("href"),e.baseUrl)&&s.remove(),{html:`<!DOCTYPE html>${n.documentElement.outerHTML}`,warnings:t}}function installRenderProfileInPage(){const e=window;performance.setResourceTimingBufferSize(1e4);const readTargetSelector=()=>{const e=new URLSearchParams(window.location.search),t=e.get("canvasPath")?.trim()??e.get("pageFile")?.trim(),n=e.get("storyboardId")?.trim()??e.get("exportName")?.trim();if(!t||!n)return"";const r=`canvas:${encodeURIComponent(t)}#storyboard:${encodeURIComponent(n)}`;return`[data-tempo-storyboard-render-id=${JSON.stringify(r)}]`},t={startedAtMs:performance.now(),fullNavigation:!0,targetSelector:readTargetSelector(),targetAttachedMs:null,reactInjectedMs:null,reactCommits:[],longTaskCount:0,longTaskDurationMs:0,begin(e){this.startedAtMs=performance.now(),this.fullNavigation=!1,this.targetSelector=e,this.targetAttachedMs=null,this.reactInjectedMs=null,this.reactCommits=[],this.longTaskCount=0,this.longTaskDurationMs=0}};e.__tempoCaptureRenderProfile=t;const markTargetAttached=()=>{null===t.targetAttachedMs&&t.targetSelector&&document.querySelector(t.targetSelector)&&(t.targetAttachedMs=performance.now()-t.startedAtMs)};markTargetAttached(),new MutationObserver(markTargetAttached).observe(document,{childList:!0,subtree:!0});try{new PerformanceObserver(e=>{for(const n of e.getEntries())t.longTaskCount+=1,t.longTaskDurationMs+=n.duration}).observe({type:"longtask",buffered:!0})}catch{}if(e.__REACT_DEVTOOLS_GLOBAL_HOOK__)return;let n=0;const r=new Map;e.__REACT_DEVTOOLS_GLOBAL_HOOK__={supportsFiber:!0,renderers:r,inject:e=>(t.reactInjectedMs??=performance.now()-t.startedAtMs,n+=1,r.set(n,e),n),onCommitFiberRoot(e,n){const r=n.current;t.reactCommits.push({atMs:performance.now()-t.startedAtMs,actualDurationMs:"number"==typeof r?.actualDuration?r.actualDuration:0})},onCommitFiberUnmount(){},checkDCE(){},onScheduleFiberRoot(){}}}function readRenderProfileInPage(e){const t=window,n=t.__tempoCaptureRenderProfile,r=n?.startedAtMs??0,s=performance.getEntriesByType("navigation")[0],i=performance.getEntriesByType("resource").filter(e=>e.startTime>=r),a=`/${e.replace(/^tempo\//,"")}`,o=i.filter(e=>{const t=new URL(e.name).pathname;return t.includes("/designs/")&&t.includes(".canvas")}),c=o.find(e=>new URL(e.name).pathname===a),l=i.filter(e=>"script"===e.initiatorType),d=n?.reactCommits??[];return{domContentLoadedMs:n?.fullNavigation?s?.domContentLoadedEventEnd??0:0,targetAttachedMs:n?.targetAttachedMs??performance.now()-r,targetModuleLoadedMs:c?c.responseEnd-r:0,lastCanvasModuleLoadedMs:Math.max(0,...o.map(e=>e.responseEnd-r)),lastScriptLoadedMs:Math.max(0,...l.map(e=>e.responseEnd-r)),reactInjectedMs:n?.reactInjectedMs??0,reactFirstCommitMs:d[0]?.atMs??0,reactLastCommitMs:d[d.length-1]?.atMs??0,reactCommitWorkMs:d.reduce((e,t)=>e+t.actualDurationMs,0),reactCommitCount:d.length,longTaskCount:n?.longTaskCount??0,longTaskDurationMs:n?.longTaskDurationMs??0,requestCount:i.length,scriptRequestCount:l.length,canvasModuleRequestCount:o.length,unrelatedCanvasModuleRequestCount:o.filter(e=>new URL(e.name).pathname!==a).length}}function storyboardRenderId(e,t){return buildCanvasStoryboardRenderId(e,t)}function buildDirectRenderUrl2(e,t){return buildDirectRenderUrl(e,{canvasPath:t.hostCanvasPath,storyboardId:t.storyboardId,width:t.width,height:t.height})}function sha256Hex(e){return st("sha256").update(e).digest("hex")}function looksBlank(e){let t;try{t=it.sync.read(Buffer.from(e))}catch{return!0}for(let e=0;e<t.data.length;e+=4){const n=t.data[e+3];if(0!==n&&(255!==t.data[e]||255!==t.data[e+1]||255!==t.data[e+2]))return!1}return!0}var lr=42e4,dr=`[${je}]`,ur=class extends Error{constructor(e){super(e),this.code="content-unavailable",this.name="ContentUnavailableError"}};async function settleCapturePage(e,t,n){await settlePage(e,t,n);const r=n?.contentUnavailableTimeoutMs??lr,s=Date.now()+r;for(;await e.locator(t).locator(dr).count();){try{await e.waitForFunction(({selector:e,unavailable:t})=>{const n=document.querySelector(e);return n&&!n.querySelector(t)},{selector:t,unavailable:dr},{timeout:Math.max(1,s-Date.now())})}catch(e){if(!(e instanceof Error)||"TimeoutError"!==e.name)throw e;throw new ur(`Storyboard content remained unavailable after ${r}ms. Check the Flutter devserver compile log or the external content producer; increase contentUnavailableTimeoutMs for a slower cold build.`)}await settlePage(e,t,n)}await alignCaptureSubframeFonts(e)&&await settlePage(e,t,n)}function isPageGoneError(e){return/Target closed|Target page, context or browser has been closed|Page closed|Target crashed/.test(e)}function isBrowserGoneError(e){return/Browser has been closed|Browser closed|browser has disconnected|Browser process crashed/.test(e)}var pr=new WeakSet;function markNavigated(e,t){t&&null!==e&&"object"==typeof e&&pr.add(e)}function readNavigatedMark(e){return null!==e&&"object"==typeof e&&pr.has(e)}function documentReplaced(e,t,n){return t.navigationRequests>e.navigationRequests+n||t.documentCommits>e.documentCommits+n}var hr=3;function decideBoardRetry(e,t,n=hr){if("content-unavailable"===e.status)return"accept";if(t>=n-1)return"accept";if("render-error"===e.status){const t=e.error??"";return isBrowserGoneError(t)?"accept":isPageGoneError(t)?"retry-fresh-worker":e.navigated||isNavigationInterruptedError(t)?"retry":"accept"}return e.navigated?"retry":"accept"}function navigatedRejectionError(e){return`document reloaded during every attempt (${e}); the capture never saw one stable document`}function finalizeAcceptedAttempt(e,t){const{result:n}=e;return e.navigated&&"render-error"!==n.status&&"content-unavailable"!==n.status?{canvasPath:n.canvasPath,storyboardId:n.storyboardId,status:"render-error",error:navigatedRejectionError(t),timings:n.timings}:"render-error"===n.status&&t>1?{...n,error:`after ${t} attempts: ${n.error}`}:n}function reloadStormWindowFor(e){return Math.max(8,4*Math.max(1,Math.floor(e)))}function isReloadStorm(e,t){return!(e.length<t)&&e.slice(-t).every(Boolean)}var mr=class extends Error{constructor(){super(...arguments),this.name="CaptureReloadStormError"}};function describeRetryReason(e){return"render-error"===e.status&&isPageGoneError(e.error??"")?"page closed mid-capture":"document reloaded mid-capture"}var fr=We;async function startCaptureSession(e){const t=e.log??(()=>{}),n=e.parallelPages??1,r=createCaptureImageNormalizer(),{chromium:s}=await(import("playwright"));let i;try{i=await s.launch({args:yt})}catch(e){if(!isMissingBrowserError(e)||autoInstallDisabled())throw e;t("[capture] Chromium is not installed — downloading it now (one-time, ~2 min)"),await installChromium(t),i=await s.launch({args:yt})}const{fingerprint:a}=buildEnvFingerprint({os:process.platform,browserVersion:i.version()}),browserGoneError=e=>new Error(`capture browser is gone; cannot open a fresh page: ${e}`),createCaptureWorker=async t=>{const n=Date.now(),s=await i.newContext({deviceScaleFactor:t.deviceScaleFactor??gt,viewport:t.viewport??fr,reducedMotion:"reduce",colorScheme:"light",timezoneId:"UTC",locale:"en-US",serviceWorkers:"block"});process.env.TEMPO_SDK_RUNTIME_PATH&&await s.addInitScript(await readBrowserRuntimeScript()),await s.addInitScript(buildFreezeInitScript()),await s.addInitScript(installRenderProfileInPage);const a=await s.newPage(),o=await installCaptureImages(a,r),c=await s.newCDPSession(a),l={context:s,page:a,images:o,contextMs:Date.now()-n,contextClaimed:!1,hasNavigated:!1,counters:{navigationRequests:0,documentCommits:0},documentsLoaded:0,navigationsInFlight:0,async dispose(){await o.dispose(),await c.detach().catch(()=>{}),await a.close().catch(()=>{}),await s.close().catch(()=>{})}},isMainFrameNavigation=e=>{try{return e.isNavigationRequest()&&e.frame()===a.mainFrame()}catch{return!1}};return a.on("request",e=>{isMainFrameNavigation(e)&&(e.redirectedFrom()||(l.counters.navigationRequests+=1,l.navigationsInFlight+=1))}),a.on("requestfailed",e=>{isMainFrameNavigation(e)&&(l.navigationsInFlight=Math.max(0,l.navigationsInFlight-1))}),c.on("Page.frameNavigated",({frame:e})=>{e.parentId||(l.counters.documentCommits+=1)}),await c.send("Page.enable"),await alignCaptureFonts(c),a.on("domcontentloaded",()=>{l.documentsLoaded+=1,l.navigationsInFlight=0,l.hasNavigated&&a.addStyleTag({content:ot}).catch(()=>{})}),e.timing?.recordBoard("context",l.contextMs),l},sleep4=e=>new Promise(t=>setTimeout(t,e)),awaitDocumentQuiet=async(e,t)=>{const n=500,r=Date.now()+Math.min(t,1e4),settleLoad=async()=>{for(;e.navigationsInFlight>0&&Date.now()<r;)await sleep4(50);await e.page.waitForLoadState("load",{timeout:Math.max(1,r-Date.now())}).catch(()=>{})};await settleLoad();let s=e.counters.navigationRequests,i=Date.now();for(;Date.now()<r;)if(await sleep4(100),e.counters.navigationRequests!==s||e.navigationsInFlight>0)s=e.counters.navigationRequests,i=Date.now(),await settleLoad();else if(Date.now()-i>=n)return},withSettledStoryboard=async(t,n,s,i,a)=>{const o=n.viewport??(t.width&&t.height?{width:Math.ceil(t.width),height:Math.ceil(t.height)}:fr);if("html"===t.source?.kind||"astro"===t.source?.kind){const a=await createCaptureWorker({...n,viewport:o});s.contextMs=a.contextMs;try{const o="html"===t.source.kind?await openHeadlessHtmlSource(a.context,t.source.filepath,r):{url:astroCaptureUrl(await(e.getAppUrl?.()??Promise.reject(new Error("Astro component capture requires the app dev server"))),t),assertResources(){}},c=new Set;a.page.on("pageerror",e=>c.add(e.message)),a.page.on("response",e=>{e.status()>=400&&c.add(`${e.status()} ${e.url()}`)}),a.page.on("requestfailed",e=>c.add(`${e.failure()?.errorText} ${e.url()}`));const l={...a.counters},d=Date.now(),u=await a.page.goto(o.url,{waitUntil:"load",timeout:n.settleTimeoutMs??e.settleTimeoutMs??3e4});if("astro"===t.source.kind){if(!u?.ok())throw new Error(`Astro storyboard returned HTTP ${u?.status()}`);await settleAstroDocument(a.page,t,n.settleTimeoutMs??e.settleTimeoutMs??3e4)}s.navigateMs=Date.now()-d,await a.page.addStyleTag({content:ot});const p=Date.now();await settleCapturePage(a.page,"body",{timeoutMs:n.settleTimeoutMs??e.settleTimeoutMs??3e4,contentUnavailableTimeoutMs:n.contentUnavailableTimeoutMs??e.contentUnavailableTimeoutMs});const h=await a.page.evaluate(buildVisualReadyWaitScript(n.settleTimeoutMs??e.settleTimeoutMs??3e4));if(requireVisualReadiness(h,!0),h.failures.length)throw new Error(`HTML storyboard visual resources failed: ${JSON.stringify(h.failures)}`);if(o.assertResources(),"astro"===t.source.kind&&c.size)throw new Error(`Astro storyboard failed: ${[...c].join("; ")}`);s.settleMs=Date.now()-p,a.images.assertHealthy();const m=await i(a.page,"body");if(a.images.assertHealthy(),o.assertResources(),"astro"===t.source.kind&&c.size)throw new Error(`Astro storyboard failed: ${[...c].join("; ")}`);if(a.page.url()!==o.url)throw new Error("HTML storyboard navigated away from its accepted source");return{value:m,navigated:documentReplaced(l,a.counters,1)}}finally{await a.dispose()}}const c=storyboardRenderId(t.hostCanvasPath,t.storyboardId),l=buildStoryboardRenderSelector(c),d=void 0===a,u=a??await createCaptureWorker({...n,viewport:o}),{page:p}=u;u.contextClaimed||(s.contextMs=u.contextMs,u.contextClaimed=!0);const h={...u.counters},m=u.hasNavigated?0:1,navigatedSinceStart=()=>documentReplaced(h,u.counters,m);try{const r=Date.now();try{const r=p.viewportSize();r?.width===o.width&&r?.height===o.height||await p.setViewportSize(o);const s=buildDirectRenderUrl2(e.hostUrl,t);u.hasNavigated?(u.currentSelector===l&&(await p.evaluate(e=>{history.replaceState(history.state,"",e),window.dispatchEvent(new PopStateEvent("popstate",{state:history.state}))},buildDirectRenderIdleUrl(e.hostUrl)),await p.waitForSelector(u.currentSelector,{state:"detached",timeout:n.settleTimeoutMs??e.settleTimeoutMs??3e4})),await p.evaluate(({url:e,nextSelector:t})=>{const n=window;n.__tempoResetCaptureDeterminism?.(),n.__tempoCaptureRenderProfile?.begin(t),history.replaceState(history.state,"",e),window.dispatchEvent(new PopStateEvent("popstate",{state:history.state}))},{url:s,nextSelector:l})):(await p.goto(s,{waitUntil:"domcontentloaded"}),await p.addStyleTag({content:ot}),u.hasNavigated=!0),u.currentSelector=l}finally{s.navigateMs=Date.now()-r,e.timing?.recordBoard("navigate",s.navigateMs)}const a=Date.now();try{await settleCapturePage(p,l,{timeoutMs:n.settleTimeoutMs??e.settleTimeoutMs??3e4,contentUnavailableTimeoutMs:n.contentUnavailableTimeoutMs??e.contentUnavailableTimeoutMs,onStep:(t,n)=>e.timing?.recordBoard(`settle.${t}`,n)})}finally{s.settleMs=Date.now()-a,e.timing?.recordBoard("settle",s.settleMs)}const c=await p.evaluate(readRenderProfileInPage,t.hostCanvasPath);e.timing?.recordBoard("render.dom-content-loaded",c.domContentLoadedMs),e.timing?.recordBoard("render.react-injected",c.reactInjectedMs),e.timing?.recordBoard("render.react-first-commit",c.reactFirstCommitMs),e.timing?.recordBoard("render.react-last-commit",c.reactLastCommitMs),e.timing?.recordBoard("render.react-commit-work",c.reactCommitWorkMs),e.timing?.recordBoard("render.target-module",c.targetModuleLoadedMs),e.timing?.recordBoard("render.target-attached",c.targetAttachedMs),e.timing?.recordBoard("render.last-canvas-module",c.lastCanvasModuleLoadedMs),e.timing?.recordBoard("render.last-script",c.lastScriptLoadedMs),e.timing?.recordBoard("render.long-task-time",c.longTaskDurationMs),e.timing?.recordBoard("requests.all",c.requestCount,"count"),e.timing?.recordBoard("requests.script",c.scriptRequestCount,"count"),e.timing?.recordBoard("requests.canvas-module",c.canvasModuleRequestCount,"count"),e.timing?.recordBoard("requests.unrelated-canvas",c.unrelatedCanvasModuleRequestCount,"count"),e.timing?.recordBoard("react.commits",c.reactCommitCount,"count"),e.timing?.recordBoard("render.long-tasks",c.longTaskCount,"count"),await p.evaluate(watchRenderErrorsInPage,{selector:l,errorSelector:Ye,messageAttribute:ze}),u.images.assertHealthy();const d=await i(p,l);if(u.images.assertHealthy(),await p.locator(l).locator(dr).count())throw new ur("Storyboard content became unavailable during capture. Check the Flutter devserver compile log or the external content producer and retry.");const h=await p.evaluate(readRenderErrorsInPage);if(h.length>0)throw new Error(`storyboard rendered its error boundary: ${h.join("; ")}`);return{value:d,navigated:navigatedSinceStart()}}catch(e){throw markNavigated(e,navigatedSinceStart()),e}finally{d&&await u.dispose()}},captureStoryboardArtifactsOnce=async t=>{const n=t.artifacts??["png"],r={contextMs:0,navigateMs:0,settleMs:0};return withSettledStoryboard(t,t,r,async(r,s)=>{const i={};if(i.styles=await r.evaluate(assessPageStylesInPage,s),n.includes("png")){const e=new Uint8Array(await(t.source?r.screenshot({type:"png",animations:"disabled"}):r.locator(s).screenshot({type:"png",animations:"disabled"}))),n=it.sync.read(Buffer.from(e));i.png={pngBytes:e,width:n.width,height:n.height}}if(n.includes("html")){const n=t.source?r.url():`${new URL(e.hostUrl).origin}/`,a=await r.evaluate(extractStoryboardDomInPage,s),o=buildStoryboardHtmlDocument(a,{baseUrl:n,preserveBody:Boolean(t.source)});if(t.portableHtml??!0){const e=await r.evaluate(inlinePortableHtmlInPage,{html:o,baseUrl:n});i.html={html:e.html,baseUrl:n,portable:!0,warnings:e.warnings}}else i.html={html:o,baseUrl:n,portable:!1,warnings:[]}}return i})},captureStoryboardArtifacts=async e=>{const n=`${e.hostCanvasPath}#${e.storyboardId}`;for(let r=0;;r+=1){const s=r>=hr-1,a=r+1;let o;try{o=await captureStoryboardArtifactsOnce(e)}catch(e){if(e instanceof ur)throw e;const r=e instanceof Error?e.message:String(e);if(!i.isConnected())throw browserGoneError(r);const o=!isBrowserGoneError(r)&&(readNavigatedMark(e)||isNavigationInterruptedError(r)||isPageGoneError(r));if(s||!o)throw e;t(`[capture] ${n}: ${r.split("\n")[0]} (attempt ${a}/${hr}) — re-capturing`);continue}if(!o.navigated)return o.value;if(s)throw new Error(navigatedRejectionError(a));t(`[capture] ${n}: document reloaded mid-capture (attempt ${a}/${hr}) — re-capturing`)}},captureOne=async(t,n)=>{const r={contextMs:0,navigateMs:0,settleMs:0,screenshotMs:0};try{const{value:s,navigated:i}=await withSettledStoryboard({source:t.source,hostCanvasPath:t.hostCanvasPath,storyboardId:t.storyboardId,width:t.layout.width,height:t.layout.height},{},r,async(n,s)=>{const i=Date.now();let a,o;try{const e=n.locator(s);a=new Uint8Array(await(t.source?n.screenshot({type:"png",animations:"disabled"}):e.screenshot({type:"png",animations:"disabled"}))),o=(new TextEncoder).encode((await n.evaluate(extractStoryboardDomInPage,s)).elementHtml)}finally{r.screenshotMs=Date.now()-i,e.timing?.recordBoard("screenshot",r.screenshotMs)}return{canvasPath:t.canvasPath,storyboardId:t.storyboardId,status:looksBlank(a)?"empty":"ok",pngHash:sha256Hex(a),pngBytes:a,htmlHash:sha256Hex(o),htmlBytes:o,timings:r}},n);return{result:s,status:s.status,navigated:i}}catch(e){const n={canvasPath:t.canvasPath,storyboardId:t.storyboardId,status:e instanceof ur?"content-unavailable":"render-error",error:e instanceof Error?e.message:String(e),timings:r};return{result:n,status:n.status,error:n.error,navigated:readNavigatedMark(e)}}};return{browserVersion:i.version(),envFingerprint:a,captureBoards:async(r,s)=>{if(0===r.length)return[];const a=s?.label??"capture",o=e.settleTimeoutMs??3e4,c=new Array(r.length),l=Math.max(1,Math.min(n,r.length)),d=reloadStormWindowFor(l),u=[];let p=0,h=!1,m=0,f=0;const g=Array.from({length:l},async()=>{let n=await createCaptureWorker({});const replaceWorker=async()=>{if(await n.dispose(),!i.isConnected())throw browserGoneError("browser disconnected");try{n=await createCaptureWorker({})}catch(e){throw browserGoneError(e instanceof Error?e.message:String(e))}};try{for(;;){if(h)return;const s=m;if(m+=1,s>=r.length)return;const i=r[s],l=`${i.canvasPath}#${i.storyboardId}`;let g,y=0;for(let r=0;;r+=1){const s=await captureOne(i,n),c=decideBoardRetry(s,r);if("accept"===c){g=finalizeAcceptedAttempt(s,r+1),r>0&&e.timing?.recordBoard("capture.retries",r,"count");break}const d=describeRetryReason(s);"document reloaded mid-capture"===d&&(y+=1),t(`${a}: ${l}: ${d} (attempt ${r+1}/${hr}) — re-capturing`),"retry-fresh-worker"===c?await replaceWorker():await awaitDocumentQuiet(n,o)}if(c[s]=g,f+=1,f%10!=0&&f!==r.length||t(`${a}: ${f}/${r.length}`),p+=y,u.push(y>0),u.length>d&&u.shift(),isReloadStorm(u,d))throw h=!0,new mr(`capture aborted: the document reloaded during the last ${d} storyboards in a row (${p} re-captures so far) — check the devserver output and storyboard navigation for repeated reloads`);"render-error"===g.status&&await replaceWorker()}}finally{await n.dispose()}});return await Promise.all(g),c},captureStoryboard:async e=>{const{png:t}=await captureStoryboardArtifacts({...e,artifacts:["png"]});return t},captureStoryboardHtml:async e=>{const{html:t}=await captureStoryboardArtifacts({...e,artifacts:["html"],portableHtml:e.portable??!0});return t},captureStoryboardArtifacts,dispose:async()=>{await i.close().catch(()=>{})}}}import{PNG as gr}from"pngjs";import{readFile as yr}from"fs/promises";import vr from"path";import{randomUUID as Er}from"crypto";import{mkdir as Tr,readFile as wr,writeFile as Sr}from"fs/promises";import br from"path";var Ar=br.join(".tempo","workspace-nonce");async function readTextFileOptional(e){try{return await wr(e,"utf-8")}catch(e){if("ENOENT"===e.code)return null;throw e}}async function ensureTempoWorkspaceNonce(e){const t=br.join(e,Ar);await Tr(br.dirname(t),{recursive:!0});const n=(await readTextFileOptional(t))?.trim();if(n)return n;const r=Er();try{return await Sr(t,`${r}\n`,{encoding:"utf-8",flag:"wx"}),r}catch(e){const n=(await readTextFileOptional(t))?.trim();if(n)return n;throw e}}import{existsSync as _r,readFileSync as kr}from"fs";import{dirname as Ir,join as Cr,resolve as Rr}from"path";function usesPrivateSdkRuntime(e){let t=Rr(e);for(;;){const e=Cr(t,"node_modules/tempo-sdk/package.json");if(_r(e))try{return 1===JSON.parse(kr(e,"utf8")).tempoRuntimeContract}catch{return!1}const n=Ir(t);if(n===t)return!1;t=n}}function tempoSdkRuntimeEnvironment(e=process.env,t){const n=e.TEMPO_SDK_RUNTIME_PATH;if(!n)return{};if(t&&!usesPrivateSdkRuntime(t))return{};const r=Cr(n,"browser-runtime.cjs");if(!_r(r))return{TEMPO_SDK_RUNTIME_PATH:n};const s=`--require ${JSON.stringify(r)}`,i=e.NODE_OPTIONS??"";return{TEMPO_SDK_RUNTIME_PATH:n,NODE_OPTIONS:i.includes(s)?i:[i,s].filter(Boolean).join(" ")}}import{createHash as Pr}from"crypto";import{readFile as Nr,realpath as Or}from"fs/promises";import Dr from"path";var Lr=1;function tempoSdkRuntimeCompatibilityError(e){return void 0===e.tempoRuntimeContract?"tempo-sdk is a legacy release without a runtime contract; Tempo moves it to tempo-sdk@latest when the canvas starts":e.tempoRuntimeContract===Lr?null:`tempo-sdk requires runtime contract ${String(e.tempoRuntimeContract)}; update Tempo before updating the SDK`}async function tempoSdkRuntimeProvisioningError(e,t){const n=tempoSdkRuntimeCompatibilityError(e);if(n)return n;if(!t||!Dr.isAbsolute(t))return"The private Tempo SDK runtime is not provisioned; update Tempo before updating the SDK";try{const n=JSON.parse(await Nr(Dr.join(t,"runtime.json"),"utf8"));if(!(n.tempoRuntimeContract===e.tempoRuntimeContract&&n.node&&"object"==typeof n.node&&Object.hasOwn(n.node,"index")&&n.browser&&n.serverBrowser))return"The private Tempo SDK runtime is missing or incompatible; update Tempo before updating the SDK";const r=await Or(t);for(const e of[...Object.values(n.node),n.browser,n.serverBrowser]){if(!e||"string"!=typeof e.file||"string"!=typeof e.sha256)return"The private Tempo SDK runtime has an invalid artifact descriptor; update Tempo before updating the SDK";const t=await Or(Dr.resolve(r,e.file)),n=Dr.relative(r,t);if(n.startsWith("..")||Dr.isAbsolute(n))return"The private Tempo SDK runtime artifact is outside its installation; update Tempo before updating the SDK";const s=Pr("sha256").update(await Nr(t)).digest("hex");if(s!==e.sha256)return"The private Tempo SDK runtime artifact failed verification; update Tempo before updating the SDK"}return null}catch{}return"The private Tempo SDK runtime is missing or incompatible; update Tempo before updating the SDK"}async function assertTempoSdkInstallRuntime(e,t){let n;try{n=JSON.parse(await Nr(Dr.join(e,"package.json"),"utf8"))}catch{return}const r=n.dependencies?.["tempo-sdk"]??n.devDependencies?.["tempo-sdk"];if("latest"!==r)return;const s=await tempoSdkRuntimeProvisioningError({tempoRuntimeContract:1},t);if(s)throw new Error(s)}function parseFlutterPreview(e){const t=`preview ${JSON.stringify(e)}`;if(e.includes("\\"))return{error:`${t} uses a backslash; use "/" (paths in canvases are POSIX).`};const n=e.lastIndexOf("#");if(n<0)return{error:`${t} needs "#<function>" after the file, e.g. "../../lib/cards.dart#productCard".`};const r=e.slice(0,n),s=e.slice(n+1);return r.startsWith("./")||r.startsWith("../")?r.endsWith(".dart")?/[?#]/.test(r)||r.includes("//")?{error:`${t} must not contain "?", "#", or empty path segments.`}:/^[A-Za-z$][A-Za-z0-9_$]*$/.test(s)?{file:r,functionName:s}:{error:`${t}: ${JSON.stringify(s)} is not a public Dart function name.`}:{error:`${t} must name a .dart file.`}:{error:r.startsWith("lib/")?`${t} is no longer relative to a Flutter app folder; write the path from this canvas file, starting with "./" or "../".`:`${t} must be a path relative to this canvas file and start with "./" or "../", like a relative import.`}}import{lstatSync as Mr,realpathSync as xr}from"fs";import Fr from"path";function canonicalPathAllowMissing(e){const t=Fr.resolve(e);try{return xr.native(t)}catch(e){const n=e.code;if("ENOENT"!==n&&"ENOTDIR"!==n)throw e;let r=!1;try{r=Mr(t).isSymbolicLink()}catch(e){if("ENOENT"!==e.code&&"ENOTDIR"!==e.code)throw e}if(r)throw e;const s=Fr.dirname(t);if(s===t)throw e;return Fr.join(canonicalPathAllowMissing(s),Fr.basename(t))}}function flutterPreviewKey(e,t,n){return`${Fr.relative(canonicalPathAllowMissing(e),canonicalPathAllowMissing(t)).split(Fr.sep).join("/")}#${n}`}function flutterPreviewForCanvas(e,t,n){const r=e.lastIndexOf("#");if(r<0)throw new Error("Flutter preview key has no function");const s=Fr.resolve(canonicalPathAllowMissing(n),e.slice(0,r)),i=Fr.relative(Fr.dirname(canonicalPathAllowMissing(t)),s).split(Fr.sep).join("/");return`${i.startsWith(".")?i:`./${i}`}#${e.slice(r+1)}`}function pathInside(e,t){const n=Fr.relative(e,t);return""===n||".."!==n&&!n.startsWith(`..${Fr.sep}`)&&!Fr.isAbsolute(n)}import{readFile as Br,stat as Hr}from"fs/promises";import Ur from"path";import{parseSync as jr}from"oxc-parser";var $r={Storyboard:{importSource:"tempo-sdk/canvas",kind:"component",requiresComponentProp:!0,allowsVrt:!0,componentFileExtension:".tsx"},SvelteStoryboard:{importSource:"tempo-sdk/canvas/svelte",kind:"component",uiFramework:"svelte",requiresComponentProp:!0,allowsVrt:!0,componentFileExtension:".svelte"},VueStoryboard:{importSource:"tempo-sdk/canvas/vue",kind:"component",uiFramework:"vue",requiresComponentProp:!0,allowsVrt:!0,componentFileExtension:".vue"},AstroStoryboard:{importSource:"tempo-sdk/canvas/astro",kind:"component",uiFramework:"astro",requiresComponentProp:!0,allowsVrt:!0,componentFileExtension:".astro",componentImportQuery:"?tempo-component"},FlutterStoryboard:{importSource:"tempo-sdk/canvas",kind:"component",requiresComponentProp:!1,allowsVrt:!0},RouteStoryboard:{importSource:"tempo-sdk/canvas",kind:"route",requiresComponentProp:!1,allowsVrt:!1},HtmlStoryboard:{importSource:"tempo-sdk/canvas",kind:"html",requiresComponentProp:!1,allowsVrt:!0},LegacyStoryboardV1:{importSource:"tempo-sdk/canvas",kind:"component",requiresComponentProp:!1,allowsVrt:!1}},Gr=$r,qr=Object.keys(Gr);function componentFrameworkForStoryboard(e){return e.componentFramework??e.runtimeFramework??e.uiFramework}var Wr=new Set(["tempo-sdk/canvas",...qr.map(e=>Gr[e].importSource)]),Vr=new Set(["Canvas",...qr]),Kr=`<Canvas> children must be ${formatAlternatives(qr.map(e=>`<${e}>`))} declarations`,Yr=new Set(["Canvas","CanvasContext","getCanvasStoryboardRenderId","CanvasHost","buildRenderContentFiberSelector","buildRenderContentSelector","buildRenderSelector","captureStoryboardCombined","captureStoryboardHtml","captureStoryboardImage","stripRenderContentWrapperAttributes","stripRenderContentWrapperFromCombinedCapture","watchStoryboardCombined","getCanvasHostRuntime","getOptionalCanvasHostRuntime","useActiveState","FlutterStoryboard","HtmlStoryboard","LegacyStoryboardV1","RouteStoryboard","Storyboard","StoryboardSlot"]),zr={x:0,y:0},Jr={...zr,width:600,height:400},Qr="No <Canvas> declaration found in canvas file";function parseCanvasFile(e,t){const n=[];let r;try{const s=jr(e,t);r=s.program;for(const e of s.errors??[])n.push({message:e.message??"Unable to parse canvas source",span:toSpan(e)??toSpan(e?.labels?.[0]),kind:"structural"})}catch(t){return{filePath:e,pageName:fallbackPageName(e),imports:[],misimportedSdkCanvasImports:[],storyboards:[],errors:[{message:t instanceof Error?t.message:"Unable to parse canvas source",kind:"structural"}]}}const s=readImports(r),i=readMisimportedSdkCanvasImports(r),{legacyObjects:a,stringBindings:o}=readObjectExpressionBindings(r,s,t);let c=null;const l=[];walk2(r,e=>{if("JSXElement"!==e.type)return;const t=resolveSdkComponent(e.openingElement?.name,s),r=resolveMisimportedNamespaceSdkComponent(e.openingElement?.name,s,i);r&&i.add(r),"Canvas"!==t?isStoryboardSdkComponent(t)&&l.push({element:e,component:t}):c?n.push({message:"Canvas file must declare exactly one <Canvas> element",span:toSpan(e),kind:"structural"}):c=e});const d=c?readDirectCanvasStoryboardElements(c,s):[],u=new Set(d.map(e=>e.element)),p=d.map(e=>readStoryboard(e.element,e.component,s,a,t,n));for(const e of l)u.has(e.element)||n.push({message:`<${e.component}> declarations must be direct children of the <Canvas> element`,span:toSpan(e.element),kind:"structural"});if(reportDuplicateStoryboardIds(p,n),c)n.push(...validateCanvasChildren(c,s));else if(i.all.length>0)for(const e of i.all)n.push({message:misimportedSdkCanvasImportMessage(e),span:e.sourceSpan,kind:"structural"});else n.push({message:Qr,kind:"structural"});const h=c?.openingElement,m=readResolvableStringAttribute(h,"name",o),f=readStringAttribute(h,"path"),g=readResolvableStringAttribute(h,"backgroundColor",o)??readResolvableStringAttribute(h,"background",o);return h&&!m&&n.push({message:'<Canvas> must include a literal "name" prop',span:toSpan(h),kind:"degraded"}),{filePath:e,canvasPath:f?.value,pageName:m?.value??fallbackPageName(e),backgroundColor:g?.value,canvasElementSpan:toSpan(c),canvasOpeningElementSpan:toSpan(h),canvasChildrenInsertionOffset:"number"==typeof c?.closingElement?.start?c.closingElement.start:void 0,nameSpan:m?.valueSpan,nameAttributeSpan:m?.attributeSpan,pathSpan:f?.valueSpan,pathAttributeSpan:f?.attributeSpan,backgroundColorSpan:g?.valueSpan,backgroundColorAttributeSpan:g?.attributeSpan,imports:s.all,misimportedSdkCanvasImports:i.all,storyboards:p,errors:n}}function misimportedSdkCanvasImportMessage(e){return`Tempo canvas components must be imported from "tempo-sdk/canvas" — found import of ${e.importedNames.join(", ")} from "${e.source}"`}function readMisimportedSdkCanvasImports(e){const t=[],n=new Map,r=new Map,add=e=>{const r=spanKey(e.sourceSpan);n.has(r)||(n.set(r,e),t.push(e))};for(const t of e?.body??[]){if("ImportDeclaration"!==t?.type||"string"!=typeof t.source?.value||!isWrongTempoSdkCanvasImportSource(t.source.value)||"type"===t.importKind)continue;const e=t.source.value,n=toSpan(t.source);if(!n)continue;const s=(t.specifiers??[]).filter(e=>"type"!==e?.importKind),i=s.map(readImportedName),a={source:e,sourceSpan:n,importedNames:i,rewritable:s.length>0&&s.every(e=>"ImportSpecifier"===e?.type&&Yr.has(readImportedName(e)))},o=s.some(e=>"ImportSpecifier"===e?.type&&Vr.has(readImportedName(e)));o&&add(a);for(const e of s){if("ImportNamespaceSpecifier"!==e?.type)continue;const t=e.local?.name;"string"==typeof t&&r.set(t,a)}}return{all:t,byDeclarationKey:n,namespaceCandidatesByLocalName:r,add}}function readImports(e){const t=[],n=new Map,r=new Map,s=new Set;for(const i of e?.body??[]){if("ImportDeclaration"!==i?.type||"string"!=typeof i.source?.value)continue;const e=i.source.value,a=isSdkImportSource(e);for(const o of i.specifiers??[]){const c=o.local?.name;if("string"!=typeof c)continue;const l=readImportedName(o),d={localName:c,source:e,importedName:l,kind:readImportKind(o),importKind:"type"===o.importKind?"type":"value",span:toSpan(o)??toSpan(i)??{start:0,end:0},declarationSpan:toSpan(i)??{start:0,end:0},specifierCount:i.specifiers?.length??0,namedSpecifierCount:(i.specifiers??[]).filter(e=>"ImportSpecifier"===e?.type).length,hasDefaultSpecifier:(i.specifiers??[]).some(e=>"ImportDefaultSpecifier"===e?.type),hasNamespaceSpecifier:(i.specifiers??[]).some(e=>"ImportNamespaceSpecifier"===e?.type)};t.push(d),n.set(c,d),a&&("ImportNamespaceSpecifier"!==o.type?Vr.has(l)&&r.set(c,l):s.add(c))}}return{all:t,byLocalName:n,sdkLocalNames:r,sdkNamespaces:s}}function readObjectExpressionBindings(e,t,n){const r=new Map,s=new Map;for(const i of readTopLevelVariableDeclarators(e)){if("Identifier"!==i.id?.type)continue;const e=unwrapTsExpression(i.init);if("ObjectExpression"!==e?.type)continue;const a=i.id.name;r.set(a,readLegacyStoryboardObject(a,e,t,n));const o=readObjectStringProperties(e);o.size>0&&s.set(a,o)}return{legacyObjects:r,stringBindings:s}}function readTopLevelVariableDeclarators(e){const t=[];for(const n of e?.body??[]){const e="VariableDeclaration"===n?.type?n:"ExportNamedDeclaration"===n?.type&&"VariableDeclaration"===n.declaration?.type?n.declaration:null;e&&t.push(...e.declarations??[])}return t}function readLegacyStoryboardObject(e,t,n,r){const s=[],i=getObjectProperty(t,"name"),a=i?readStringLiteralValue(i.value):null,o=getObjectProperty(t,"layout"),c=o?readLayoutExpression(o.value,"LegacyStoryboardV1"):{value:zr,errors:[{message:'<LegacyStoryboardV1> storyboard object must include a literal "layout" object',span:toSpan(t),kind:"degraded"}]},l=getObjectProperty(t,"render"),d=readRenderComponentReference(l?.value,n,r);return i&&!a&&s.push({message:"<LegacyStoryboardV1> storyboard.name must be a string literal when set",span:toSpan(i),kind:"degraded"}),s.push(...c.errors),{bindingName:e,displayName:a?.value,component:d??void 0,objectSpan:toSpan(t),objectClose:readLayoutClose(t),nameSpan:a?.span,namePropertySpan:toSpan(i),layoutPropertySpan:toSpan(o),layout:c.value,layoutSpans:c.spans,errors:s}}function readObjectStringProperties(e){const t=new Map;for(const n of e.properties??[]){if("Property"!==n?.type||n.computed)continue;const e=readPropertyKeyName(n.key),r=readStringLiteralValue(n.value);e&&r&&t.set(e,r)}return t}function readStoryboard(e,t,n,r,s,i){const a=e.openingElement,o=[],c=readStringAttribute(a,"id"),l=readStringAttribute(a,"name"),d="LegacyStoryboardV1"===t?readExpressionReference(a,"storyboard",s):void 0,u=d?.expression&&isIdentifierExpression(d.expression)?r.get(d.expression):void 0,p="LegacyStoryboardV1"===t?{value:u?.layout??zr,spans:u?.layoutSpans,attributeSpan:void 0,errors:u?.errors??(d?[{message:"<LegacyStoryboardV1> storyboard prop must reference a same-file object literal",span:d.span,kind:"degraded"}]:[{message:'<LegacyStoryboardV1> must include a "storyboard" expression prop',span:toSpan(a),kind:"degraded"}])}:readLayout(a,t),h=Gr[t];c||o.push({message:`<${t}> must include a literal "id" prop`,span:toSpan(a),kind:"structural"}),p.errors.length>0&&o.push(...p.errors);const m={storyboardKey:c?.value??"",displayName:l?.value??u?.displayName,kind:h.kind,...h.uiFramework?{componentFramework:h.uiFramework}:{},..."svelte"===h.uiFramework?{uiFramework:h.uiFramework}:"astro"===h.uiFramework?{runtimeFramework:h.uiFramework}:{},layout:p.value,editable:Boolean(c)&&0===p.errors.length,jsxElementSpan:toSpan(e)??{start:0,end:0},openingElementSpan:toSpan(a),idSpan:c?.valueSpan,idAttributeSpan:c?.attributeSpan,nameSpan:l?.valueSpan??u?.nameSpan,nameAttributeSpan:l?.attributeSpan??u?.namePropertySpan,layoutAttributeSpan:p.attributeSpan,layoutSpans:p.spans,props:readExpressionReference(a,"props",s),component:u?.component,legacyV1:d?{storyboard:d,objectName:u?.bindingName,objectSpan:u?.objectSpan,objectClose:u?.objectClose,namePropertySpan:u?.namePropertySpan,layoutPropertySpan:u?.layoutPropertySpan}:void 0,errors:o};if(h.requiresComponentProp){const e=readComponentReference(a,n,s);e?m.component=e:o.push({message:`<${t}> must include a "component" expression prop`,span:toSpan(a),kind:"degraded"})}if(h.allowsVrt){const e=readVrt(a,o);e&&(e.value&&(m.vrt=e.value),m.vrtAttributeSpan=e.attributeSpan)}if("RouteStoryboard"===t){const e=readStringAttribute(a,"route");e?(m.route=e.value,m.routeSpan=e.valueSpan,m.routeAttributeSpan=e.attributeSpan):o.push({message:'<RouteStoryboard> must include a literal "route" prop',span:toSpan(a),kind:"degraded"})}if("HtmlStoryboard"===t){const e=readStringAttribute(a,"filepath"),t=readStringAttribute(a,"src");m.filepath=e?.value.trim()?e.value:void 0,m.filepathSpan=e?.valueSpan,m.filepathAttributeSpan=e?.attributeSpan,m.src=t?.value,m.srcSpan=t?.valueSpan,m.srcAttributeSpan=t?.attributeSpan,e?.value.trim()||t?.value.trim()||o.push({message:'<HtmlStoryboard> must include a literal "filepath" or "src" prop',span:toSpan(a),kind:"degraded"})}if("FlutterStoryboard"===t){const e=readStringAttribute(a,"preview");if(e?.value.trim()){m.preview=e.value,m.previewSpan=e.valueSpan,m.previewAttributeSpan=e.attributeSpan;const t=parseFlutterPreview(e.value);"error"in t&&o.push({message:`flutter_preview_invalid: ${t.error}`,span:e.valueSpan,kind:"structural"})}else o.push({message:'<FlutterStoryboard> must include a literal "preview" prop naming a Flutter @Preview function, e.g. preview="../../lib/cards.dart#productCard"',span:toSpan(getAttribute(a,"preview")??a),kind:"structural"})}return i.push(...o),m}function readDirectCanvasStoryboardElements(e,t){const n=[];for(const r of e.children??[]){if("JSXElement"!==r?.type)continue;const e=resolveSdkComponent(r.openingElement?.name,t);isStoryboardSdkComponent(e)&&n.push({element:r,component:e})}return n}function reportDuplicateStoryboardIds(e,t){const n=new Map;for(const t of e){if(!t.storyboardKey)continue;const e=n.get(t.storyboardKey);e?e.push(t):n.set(t.storyboardKey,[t])}for(const[e,r]of n)r.length<2||t.push({message:`Duplicate storyboard id "${e}" (${r.length} declarations) — storyboard ids must be unique`,span:r[1]?.jsxElementSpan,kind:"structural"})}function validateCanvasChildren(e,t){const n=[];for(const r of e.children??[])if(r&&("JSXText"!==r.type||"string"!=typeof r.value||""!==r.value.trim()))if("JSXExpressionContainer"!==r.type){if("JSXElement"===r.type){const e=resolveSdkComponent(r.openingElement?.name,t);if(isStoryboardSdkComponent(e))continue;const s=resolveNewerSdkStoryboardComponent(r.openingElement?.name,t);if(s){n.push(newerSdkStoryboardError(r,s));continue}}n.push({message:Kr,span:toSpan(r),kind:"structural"})}else{if("JSXEmptyExpression"===r.expression?.type)continue;n.push({message:"<Canvas> children must be static storyboard declarations, not expressions",span:toSpan(r),kind:"structural"})}return n}var Xr=/(^|\/)tempo-sdk\/canvas(\/[^/]+)?$/;function resolveNewerSdkStoryboardComponent(e,t){let n,r;if("JSXIdentifier"===e?.type){const s=t.byLocalName.get(e.name);if("named"!==s?.kind)return null;n=s.importedName,r=s.source}else{if("JSXMemberExpression"!==e?.type||"JSXIdentifier"!==e.object?.type||"JSXIdentifier"!==e.property?.type)return null;{const s=t.byLocalName.get(e.object.name);if("namespace"!==s?.kind)return null;n=e.property.name,r=s.source}}const s=Xr.test(r),i=n.endsWith("Storyboard");return s&&i?n:null}function newerSdkStoryboardError(e,t){const n=e.openingElement,r=readStringAttribute(n,"id")?.value,s=null!=readVrt(n,[])?.value,i=r?` id="${r}"`:"";return{message:`<${t}${i}> is a storyboard from a newer tempo-sdk than this reader supports`,span:toSpan(e),kind:"structural",newerSdkStoryboard:{component:t,...r?{storyboardKey:r}:{},vrt:s}}}function readVrt(e,t){const n=getAttribute(e,"vrt");if(!n)return null;const r=toSpan(n);if(null==n.value)return{value:{},attributeSpan:r};const s=unwrapTsExpression(unwrapAttributeExpression(n.value));if("Literal"===s?.type&&!0===s.value)return{value:{},attributeSpan:r};if("Literal"===s?.type&&!1===s.value)return{value:null,attributeSpan:r};if("ObjectExpression"!==s?.type)return t.push({message:"<Storyboard> vrt must be a boolean literal or an object literal ({ threshold?, skip?, ignore? })",span:toSpan(s)??r,kind:"degraded"}),{value:null,attributeSpan:r};const i={};for(const e of s.properties??[]){if("Property"!==e?.type||e.computed){t.push({message:"<Storyboard> vrt must contain only literal properties",span:toSpan(e??s),kind:"degraded"});continue}const n=readPropertyKeyName(e.key);if("threshold"===n){const n=readNumberLiteral(e.value);n&&n.value>=0&&n.value<=.5?i.threshold=n.value:t.push({message:"<Storyboard> vrt.threshold must be a number literal between 0 and 0.5",span:toSpan(e),kind:"degraded"});continue}if("skip"!==n){if("ignore"===n){const n=readVrtIgnoreRegions(e.value,t);n&&(i.ignore=n);continue}t.push({message:`<Storyboard> vrt has unknown property "${n??"?"}" — expected threshold, skip, or ignore`,span:toSpan(e),kind:"degraded"})}else"Literal"===e.value?.type&&"boolean"==typeof e.value.value?e.value.value&&(i.skip=!0):t.push({message:"<Storyboard> vrt.skip must be a boolean literal",span:toSpan(e),kind:"degraded"})}return{value:i,attributeSpan:r}}function readVrtIgnoreRegions(e,t){if("ArrayExpression"!==e?.type)return t.push({message:"<Storyboard> vrt.ignore must be an array of { x, y, w, h } literals",span:toSpan(e),kind:"degraded"}),null;const n=[];for(const r of e.elements??[]){const s={};for(const e of["x","y","w","h"]){const t=getObjectProperty(r,e),n=t?readNumberLiteral(t.value):null;n&&(s[e]=n.value)}if(void 0===s.x||void 0===s.y||void 0===s.w||void 0===s.h)return t.push({message:"<Storyboard> vrt.ignore regions must be { x, y, w, h } number literals",span:toSpan(r)??toSpan(e),kind:"degraded"}),null;n.push(s)}return n}function readComponentReference(e,t,n){const r=getAttribute(e,"component"),s=unwrapAttributeExpression(r?.value),i=toSpan(s);if(!s||!i)return null;const a="Identifier"===s.type?s.name:"MemberExpression"===s.type&&"Identifier"===s.object?.type?s.object.name:void 0;return{expression:n.slice(i.start,i.end),span:i,attributeSpan:toSpan(r),localName:a,import:a?t.byLocalName.get(a):void 0}}function readRenderComponentReference(e,t,n){if("ArrowFunctionExpression"!==e?.type)return null;const r=unwrapTsExpression(e.body);if("JSXElement"!==r?.type)return null;const s=r.openingElement?.name;if("JSXIdentifier"!==s?.type)return null;const i=toSpan(s);return i&&"string"==typeof s.name?{expression:n.slice(i.start,i.end),span:i,localName:s.name,import:t.byLocalName.get(s.name)}:null}function readExpressionReference(e,t,n){const r=getAttribute(e,t),s=unwrapAttributeExpression(r?.value),i=toSpan(s);if(s&&i)return{expression:n.slice(i.start,i.end),span:i,attributeSpan:toSpan(r)}}function isIdentifierExpression(e){return/^[A-Za-z_$][\w$]*$/.test(e)}function readLayout(e,t){const n=requiresFixedLayoutSize(t),r=getAttribute(e,"layout"),s=unwrapAttributeExpression(r?.value);if(!s)return{value:n?Jr:zr,attributeSpan:toSpan(r),errors:[{message:`<${t}> must include a literal "layout" object prop`,span:toSpan(e),kind:"degraded"}]};const i=readLayoutExpression(s,t);return{...i,attributeSpan:toSpan(r)}}function readLayoutExpression(e,t){const n=[],r=requiresFixedLayoutSize(t);if("ObjectExpression"!==e.type)return{value:r?Jr:zr,spans:{layoutClose:readLayoutClose(e)},errors:[{message:`<${t}> layout must be an object literal`,span:toSpan(e),kind:"degraded"}]};const s={layoutClose:readLayoutClose(e)},i={...zr},a=getObjectProperty(e,"width"),o=getObjectProperty(e,"height"),c=getObjectProperty(e,"intrinsicSizing"),l="root-element"===c?.value?.value,d=Boolean(a&&o),u=r||d&&!l,p=!r&&Boolean(a)!==Boolean(o);p&&n.push({message:"layout.width and layout.height must be set together",span:toSpan(e),kind:"degraded"});const h=u?{width:a?readNumberLiteral(a.value):null,height:o?readNumberLiteral(o.value):null}:null,m=u?["x","y","width","height"]:["x","y"];for(const c of m){const l="width"===c?a:"height"===c?o:getObjectProperty(e,c),d="width"===c||"height"===c?h?.[c]:l?readNumberLiteral(l.value):null,u="x"===c||"y"===c||r||Boolean(h?.width&&h.height);d?u&&(i[c]=d.value,s[c]=d.span):n.push({message:`<${t}> layout.${c} must be a number literal`,span:toSpan(l??e),kind:"degraded"})}const f=getObjectProperty(e,"zIndex");if(f){const e=readNumberLiteral(f.value);e?(i.zIndex=e.value,s.zIndex=e.span):n.push({message:`<${t}> layout.zIndex must be a number literal`,span:toSpan(f),kind:"degraded"})}const g=c&&("Literal"!==c.value?.type||!l);return g&&n.push({message:`<${t}> layout.intrinsicSizing must be "root-element" when set`,span:toSpan(c),kind:"degraded"}),{value:i,spans:s,errors:n}}function readStringLiteralValue(e){return"Literal"===e?.type&&"string"==typeof e.value?{value:e.value,span:toSpan(e)??{start:0,end:0}}:null}function unwrapTsExpression(e){let t=e;for(;"TSSatisfiesExpression"===t?.type||"TSAsExpression"===t?.type||"TSNonNullExpression"===t?.type||"ParenthesizedExpression"===t?.type;)t=t.expression;return t}function readResolvableStringAttribute(e,t,n){const r=readStringAttribute(e,t);if(r)return r;const s=getAttribute(e,t),i=unwrapAttributeExpression(s?.value),a=toSpan(i),o=toSpan(s);if(!i||!a||!o)return null;const c=resolveStringMemberExpression(i,n);return c?{value:c.value,valueSpan:a,attributeSpan:o}:null}function resolveStringMemberExpression(e,t){if("MemberExpression"!==e?.type)return null;if("Identifier"!==e.object?.type)return null;const n=readPropertyKeyName(e.property);return n?t.get(e.object.name)?.get(n)??null:null}function readStringAttribute(e,t){const n=getAttribute(e,t);if(!n)return null;const r=n.value;if("Literal"===r?.type&&"string"==typeof r.value)return{value:r.value,valueSpan:toSpan(r)??toSpan(n)??{start:0,end:0},attributeSpan:toSpan(n)??{start:0,end:0}};const s=unwrapTsExpression(unwrapAttributeExpression(r)),i="Literal"===s?.type&&"string"==typeof s.value?s.value:"TemplateLiteral"===s?.type&&0===(s.expressions?.length??0)&&1===s.quasis?.length&&"string"==typeof s.quasis[0]?.value?.cooked?s.quasis[0].value.cooked:null;return null!==i?{value:i,valueSpan:toSpan(s)??toSpan(n)??{start:0,end:0},attributeSpan:toSpan(n)??{start:0,end:0}}:null}function getAttribute(e,t){for(const n of e?.attributes??[])if("JSXAttribute"===n?.type&&"JSXIdentifier"===n.name?.type&&n.name.name===t)return n;return null}function unwrapAttributeExpression(e){return e?"JSXExpressionContainer"===e.type?e.expression:e:null}function readPropertyKeyName(e){return"Identifier"===e?.type?e.name:"Literal"===e?.type&&"string"==typeof e.value?e.value:null}function getObjectProperty(e,t){if("ObjectExpression"!==e?.type)return null;for(const n of e.properties??[]){if("Property"!==n?.type||n.computed)continue;const e=readPropertyKeyName(n.key);if(e===t)return n}return null}function readNumberLiteral(e){return"Literal"===e?.type&&"number"==typeof e.value&&Number.isFinite(e.value)?{value:e.value,span:toSpan(e)??{start:0,end:0}}:"UnaryExpression"===e?.type&&"-"===e.operator&&"Literal"===e.argument?.type&&"number"==typeof e.argument.value&&Number.isFinite(e.argument.value)?{value:-e.argument.value,span:toSpan(e)??{start:0,end:0}}:null}function resolveSdkComponent(e,t){return"JSXIdentifier"===e?.type?t.sdkLocalNames.get(e.name)??null:"JSXMemberExpression"===e?.type&&"JSXIdentifier"===e.object?.type&&"JSXIdentifier"===e.property?.type&&t.sdkNamespaces.has(e.object.name)&&Vr.has(e.property.name)?e.property.name:null}function resolveMisimportedNamespaceSdkComponent(e,t,n){if("JSXMemberExpression"!==e?.type||"JSXIdentifier"!==e.object?.type||"JSXIdentifier"!==e.property?.type||!Vr.has(e.property.name))return null;const r=t.byLocalName.get(e.object.name);return"namespace"===r?.kind&&isWrongTempoSdkCanvasImportSource(r.source)?n.namespaceCandidatesByLocalName.get(e.object.name)??null:null}function isStoryboardSdkComponent(e){return null!==e&&"Canvas"!==e}function formatAlternatives(e){return e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")}, or ${e[e.length-1]}`}function requiresFixedLayoutSize(e){return"RouteStoryboard"===e||"HtmlStoryboard"===e||"FlutterStoryboard"===e}function readImportedName(e){return"ImportDefaultSpecifier"===e.type?"default":"ImportNamespaceSpecifier"===e.type?"*":e.imported?.name??e.local?.name??"unknown"}function readImportKind(e){return"ImportDefaultSpecifier"===e.type?"default":"ImportNamespaceSpecifier"===e.type?"namespace":"named"}function isSdkImportSource(e){for(const t of Wr)if(e===t||e.endsWith(`/${t}`))return!0;return!1}function isWrongTempoSdkCanvasImportSource(e){return("tempo-sdk"===e||e.startsWith("tempo-sdk/"))&&!isSdkImportSource(e)}function spanKey(e){return`${e.start}:${e.end}`}function readLayoutClose(e){return"number"==typeof e?.end&&Number.isFinite(e.end)?e.end-1:void 0}function fallbackPageName(e){const t=e.replace(/\\/g,"/"),n=t.split("/").filter(Boolean),r=n.length>0?n[n.length-1]:e,s=n.length>1?n[n.length-2]:r,i=/^index\.canvas\.[tj]sx?$/.test(r)?s:r.replace(/\.canvas\.[tj]sx?$/,"");return i.split(/[-_\s]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function toSpan(e){return"number"==typeof e?.start&&Number.isFinite(e.start)&&"number"==typeof e?.end&&Number.isFinite(e.end)?{start:e.start,end:e.end}:void 0}function walk2(e,t,n=new Set){if(e&&"object"==typeof e&&!n.has(e)){n.add(e),t(e);for(const r of Object.values(e))if(r)if(Array.isArray(r))for(const e of r)walk2(e,t,n);else"object"==typeof r&&walk2(r,t,n)}}var Zr=p(Pe(),1);import{copyFile as es,mkdir as ts,readdir as ns,realpath as rs,stat as ss}from"fs/promises";import is from"path";import{pathToFileURL as as}from"url";import{mkdir as os,readdir as cs,readFile as ls,rm as ds,stat as us}from"fs/promises";import ps from"path";import{mkdir as hs,rename as ms,rm as fs,writeFile as gs}from"fs/promises";import ys from"path";function ensureTrailingNewline(e){return e.endsWith("\n")?e:`${e}\n`}var vs=[10,25,50,100,200];function sleep(e){return new Promise(t=>setTimeout(t,e))}function isTransientFsLockError(e){const t=e?.code;return"EPERM"===t||"EACCES"===t||"EBUSY"===t}var Es="copyfile|unlink|rename|rmdir|open|scandir";function isTransientFsLockOutput(e){if(/resource busy or locked/i.test(e))return!0;const t="EBUSY|EPERM|EACCES",n="[\\s\\S]{0,400}?";return new RegExp(`\\b(?:${t})\\b${n}\\b(?:${Es})\\b`,"i").test(e)||new RegExp(`\\b(?:${Es})\\b${n}\\b(?:${t})\\b`,"i").test(e)}async function renameWithRetry(e,t){let n;for(let r=0;r<=vs.length;r+=1)try{return void await ms(e,t)}catch(e){if(!isTransientFsLockError(e))throw e;n=e;const t=vs[r];if(void 0===t)break;await sleep(t)}throw n}async function atomicWriteText(e,t){const n=ys.dirname(e);await hs(n,{recursive:!0});const r=ensureTrailingNewline(t),s=`${e}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;await gs(s,r,"utf-8");try{await renameWithRetry(s,e)}catch(t){if(await fs(s,{force:!0}).catch(()=>{}),isTransientFsLockError(t))return void await gs(e,r,"utf-8");throw t}}var Ts=class extends Error{constructor(e,t,n){super(t),this.code=e,this.name="TempoDevServerError",n&&(this.recoveryHint=n)}},ws=class extends Ts{constructor(e){super("config_missing",`Missing tempo.config.json in ${e}`),this.name="ConfigMissingError"}},Ss=class extends Ts{constructor(e,t){super("config_invalid",`Invalid tempo.config.json at ${e}: ${t}`),this.name="ConfigInvalidError"}},bs=class extends Ts{constructor(e,t,n){const r=n.trim().length>0?`\n${n}`:"";super("install_failed",`Install command failed (${t??"unknown"}): ${e}${r}`),this.name="InstallFailedError"}},As=class extends Ts{constructor(e,t,n){super("install_network_error",`${n.hint}\n\nPackage download failed (${n.code}): ${e}\n${t.trim()}`),this.name="InstallNetworkError",this.recoveryHint=n.hint}},_s=class extends Ts{constructor(e,t){super("install_timeout",`Dependency installation produced no output for 5 minutes and was stopped. Check the install logs, your connection, or a waiting install script before retrying.\n\nCommand: ${e}\n${t.trim()}`),this.recoveryHint="No install output for 5 minutes. Check the install logs and your connection, then retry.",this.name="InstallTimeoutError"}},ks=class extends Ts{constructor(e,t){super("tool_missing",`Required package manager "${e}" was not found while starting the Tempo canvas devserver from ${t}. Install ${e} or enable it with Corepack, then retry.`),this.name="ToolMissingError"}},Is=class extends Ts{constructor(e,t){super("node_version_unsupported",`The Tempo canvas devserver resolved Node.js ${e}, but this project's devserver requires ${t}. Install a compatible Node version or update PATH so the devserver uses it.`),this.name="NodeVersionUnsupportedError"}},Cs=class extends Ts{constructor(e,t){super("install_permission_denied",`Install command hit a filesystem permission/locked-file error: ${e}\n${t.trim()}`),this.name="InstallPermissionDeniedError"}},Rs=class extends Ts{constructor(e,t){super("install_file_locked",`Install command was blocked by a file another program had open: ${e}\n${t.trim()}`),this.name="InstallFileLockedError"}},Ps=class extends Ts{constructor(e,t){super("install_dependency_conflict",`Install command hit a dependency resolution conflict: ${e}\n${t.trim()}`),this.name="InstallDependencyConflictError"}},Ns=class extends Ts{constructor(e,t,n){const r="concurrent-install"===n?"Install command was interrupted — node_modules changed while it ran, because another install was running in the same folder at the same time":"Install command could not move a package aside because node_modules is in an inconsistent state (npm ENOTEMPTY) — left behind when an earlier install was cut short, or by another install running in the same folder",s="concurrent-install"===n?"Wait for any other install in this folder to finish, then retry the canvas.":"If no other install is running, delete that folder's node_modules and retry the canvas.";super("install_interrupted",`${r}: ${e}\n${t.trim()}\n\n${s}`),this.name="InstallInterruptedError",this.evidence=n}};function shellDialectRewriteHint(e){return`Hint: Tempo runs tempo.config.json's "${e}" through the platform shell, which is cmd.exe on Windows — it cannot parse PowerShell. Rewrite the command as a plain, cross-platform invocation with no shell conditionals (e.g. "npm install", or "npm install --prefix .. && npm install" — cmd supports \`&&\`). Avoid PowerShell-only syntax: \`if (...) { ... } else { ... }\`, \`Test-Path\`, \`$env:FOO\`. If you need cmd's own conditional, it is \`if exist package.json (...) else (...)\`.`}var Os=class extends Ts{constructor(e,t){super("install_shell_dialect_mismatch",`The install command isn't valid for the shell Tempo runs commands with — nothing was installed, because nothing ran: ${e}\n${t.trim()}\n\n${shellDialectRewriteHint("scripts.install")}`),this.name="InstallShellDialectMismatchError"}},Ds=class extends Ts{constructor(e,t){super("start_shell_dialect_mismatch",`The canvas devserver start command isn't valid for the shell Tempo runs commands with — the canvas host was not started: ${e}\n${t.trim()}\n\n${shellDialectRewriteHint("scripts.start")}`),this.name="StartShellDialectMismatchError"}},Ls=class extends Ts{constructor(e){super("flutter_sdk_missing",`Flutter storyboards need the Flutter SDK, but ${e} Install Flutter (https://docs.flutter.dev/get-started/install) and put \`flutter\` on PATH, or set TEMPO_FLUTTER_BIN to the flutter executable, then restart the canvas.`,"Install Flutter or set TEMPO_FLUTTER_BIN, then restart the canvas."),this.name="FlutterSdkMissingError"}},Ms=class extends Ts{constructor(e,t){super("flutter_app_invalid",`Flutter storyboards cannot load this package: ${e} ${t}. Give its pubspec a top-level \`name:\` that is a Dart identifier (e.g. \`name: my_app\`).`,"Fix the package pubspec.yaml, then save it."),this.pubspecPath=e,this.name="FlutterAppInvalidError"}},xs=class extends Ts{constructor(e,t){const n=t.trim(),r=n?`\n\nLast output from flutter run:\n${n}`:"";super("flutter_run_failed",`${e}${r}\n\nFix the error above in the Flutter package, then restart the canvas.`,"Fix the Flutter error shown in the details, then restart the canvas."),this.outputTail=n,this.name="FlutterRunFailedError"}},Fs=class extends Ts{constructor(e){super("start_failed",e),this.name="StartFailedError"}},Bs=class extends Ts{constructor(){super("daemonized_start_requires_stop",'The canvas devserver start command exited successfully before the host became ready, which means it launched the host in the background. Add a matching non-empty "scripts.stop" command to tempo.config.json so Tempo can stop and restart that external host safely.'),this.name="DaemonizedStartRequiresStopError"}},Hs=class extends Ts{constructor(e){super("process_crashed",e),this.name="ProcessCrashedError"}},Us=class extends Ts{constructor(e,t){super("io_failed",`Failed to write ${e}: ${t}`),this.name="IoFailedError"}},js=class extends Ts{constructor(){super("disposed","TempoDevServer has been disposed"),this.name="DisposedError"}},$s=class extends Ts{constructor(e){super("validation_error",e),this.name="ValidationError"}},Gs=class extends Ts{constructor(e){const t=e.upgradeError??null,n=e.missingImport??null,r=null!==n,s=r?"Tempo's managed SDK update completed, but the installed tempo-sdk is still too old. ":"Tempo's managed SDK update completed, but the running host still serves an incompatible identity. ",i=e.managedUpgradeAttempted?t?`Tempo's managed SDK update failed:\n${upgradeErrorExcerpt(t)}\n`:s:t?`Tempo's managed SDK update did not run:\n${upgradeErrorExcerpt(t)}\n`:"Tempo's managed SDK update did not run for this workspace. ",a=e.projectNodeHint??null,o=a?`${a}\n`:"";let c="The Tempo host answered, but it did not prove the current served host contract. The Tempo plugin may be inactive (ensure TEMPO=true is forwarded across the launch boundary) or the running tempo-sdk may be stale. ";n&&(c=`The Tempo host stopped while loading its config: the installed tempo-sdk is older than this Tempo and has no ${n}, which the generated host config imports. `),super("canvas_host_sdk_incompatible",`${c}${i}${o}Run \`${e.remediationCommand}\` in \`${e.remediationDirectory}\`, restart the configured host if it is externally managed, then choose Retry.`),this.managedUpgradeAttempted=e.managedUpgradeAttempted,this.remediationCommand=e.remediationCommand,this.remediationDirectory=e.remediationDirectory,this.upgradeError=t,this.projectNodeHint=a,this.missingImport=n,this.name="CanvasHostIdentityError"}},qs=6,Ws=700;function upgradeErrorExcerpt(e){const t=e.split("\n").map(e=>e.trim()).filter(e=>e.length>0).filter(e=>!/complete log of this run/i.test(e)&&!/^at\s/.test(e)).slice(0,qs),n=t.join("\n");return 0===n.length?e.trim():n.length>Ws?`${n.slice(0,Ws)}…`:n}var Vs=class extends Ts{constructor(e){super("root_deps_missing",`The project root at ${e} has a package.json but no installed dependencies. Run the project's install command (e.g. \`bun install\`, \`pnpm install\`, \`npm install\`) at ${e}, then retry. For a durable fix, set scripts.install in tempo/tempo.config.json to a command that installs BOTH the project root and the tempo root (e.g. \`cd .. && npm install && cd tempo && npm install\`) — a custom value runs verbatim and Tempo never rewrites it.`),this.projectRoot=e,this.name="MissingRootDepsError"}};function toPosixPath(e){return e.replace(/\\/g,"/")}function toRelativeImportSpecifier(e,t){const n=toPosixPath(ps.relative(e,t)),r=n.replace(/\.(tsx|ts|jsx|js)$/,"");return r.startsWith(".")?r:`./${r}`}async function readTextFileOptional2(e){try{return await ls(e,"utf-8")}catch(e){if("ENOENT"===e.code)return null;throw e}}async function atomicWriteText2(e,t){try{await atomicWriteText(e,t)}catch(t){throw new Us(e,t instanceof Error?t.message:String(t))}}var Ks="index.canvas.tsx",Ys=".canvas-host-requested.json";async function scanCanvasFiles(e){const t=[];return await walkPagesDir(e,t),t.sort(),t}async function walkPagesDir(e,t){let n;try{n=await cs(e,{withFileTypes:!0})}catch(e){if("ENOENT"===e.code)return;throw e}for(const r of n){const n=ps.join(e,r.name);r.isDirectory()?await walkPagesDir(n,t):r.isFile()&&r.name===Ks&&t.push(n)}}var zs=class{constructor(e,t,n,r){this.pendingRequestedCanvasPaths=null,this.requestedThisSession=new Set,this.requestedCanvasesQueue=Promise.resolve(),this.projectRoot=e,this.tempoRoot=t,this.requestedCanvasesPath=ps.join(t,".tempo",Ys),this.pruneRecheckDelayMs=r?.pruneRecheckDelayMs??50}dispose(){}async runRequestedCanvasesExclusive(e){const t=this.requestedCanvasesQueue;let n;this.requestedCanvasesQueue=new Promise(e=>{n=e}),await t;try{return await e()}finally{n()}}buildEntry(e){return{importPath:toPosixPath(ps.relative(this.projectRoot,e)),importSpecifier:toRelativeImportSpecifier(ps.join(this.tempoRoot,".tempo"),e)}}async resetRequestedCanvases(){await this.runRequestedCanvasesExclusive(async()=>{this.pendingRequestedCanvasPaths=null,this.requestedThisSession.clear(),await ds(this.requestedCanvasesPath,{force:!0})})}async resetStaleRequestedCanvases(){await this.runRequestedCanvasesExclusive(async()=>{const e=[...this.requestedThisSession];this.pendingRequestedCanvasPaths=e,0===e.length?await ds(this.requestedCanvasesPath,{force:!0}):await this.writeRequestedCanvasPaths(e),this.pendingRequestedCanvasPaths=null})}requestedPathToAbsolutePath(e){if("string"!=typeof e||0===e.length)return null;const t=ps.resolve(this.projectRoot,e),n=toPosixPath(ps.relative(this.projectRoot,t));return".."===n||n.startsWith("../")||ps.isAbsolute(n)?null:t}toRequestedPath(e){return toPosixPath(ps.relative(this.projectRoot,e))}async readRequestedCanvasPaths(){const e=await readTextFileOptional2(this.requestedCanvasesPath);if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}const n=t.canvases;if(!Array.isArray(n))return[];const r=[],s=new Set;for(const e of n){if("string"!=typeof e)continue;const t=this.requestedPathToAbsolutePath(e);if(!t)continue;const n=this.toRequestedPath(t);s.has(n)||(s.add(n),r.push(n))}if(!this.pendingRequestedCanvasPaths)return r;const i=[...r],a=new Set(i);for(const e of this.pendingRequestedCanvasPaths)a.has(e)||(a.add(e),i.push(e));return i}async writeRequestedCanvasPaths(e){await os(ps.dirname(this.requestedCanvasesPath),{recursive:!0}),await atomicWriteText2(this.requestedCanvasesPath,JSON.stringify({version:1,canvases:e},null,2))}async pruneDeletedRequestedPaths(e){const t=new Set([...e,...this.requestedThisSession]),n=[];for(const e of t){const t=this.requestedPathToAbsolutePath(e);t&&(await this.canvasFileExistsWithRecheck(t)&&n.push(e))}return{requestedPaths:n,changed:n.length!==e.length||n.some((t,n)=>t!==e[n])}}async canvasFileExistsWithRecheck(e){for(let t=0;;t+=1)try{return await ls(e,"utf-8"),!0}catch(e){if("ENOENT"!==e.code)throw e;if(t>=1)return!1;await new Promise(e=>setTimeout(e,this.pruneRecheckDelayMs))}}async getRequestedCanvasPaths(){return this.runRequestedCanvasesExclusive(()=>this.readRequestedCanvasPaths())}async ensureReactCanvasHostEntry(e){const t=ps.resolve(e);try{if(!(await us(t)).isFile())return null}catch(e){if("ENOENT"===e.code)return null;throw e}return this.runRequestedCanvasesExclusive(async()=>{const e=this.toRequestedPath(t);this.requestedThisSession.add(e);const n=await this.pruneDeletedRequestedPaths(await this.readRequestedCanvasPaths()),r=n.requestedPaths.indexOf(e),s=-1===r?[...n.requestedPaths,e]:n.requestedPaths,i=n.changed||-1===r;if(i){this.pendingRequestedCanvasPaths=s;try{await this.writeRequestedCanvasPaths(s),this.pendingRequestedCanvasPaths=null}catch{}}const a=this.buildEntry(t);return{entry:a,changed:i}})}async collectReactCanvasHostEntries(){return this.runRequestedCanvasesExclusive(async()=>{const e=await this.pruneDeletedRequestedPaths(await this.readRequestedCanvasPaths());return(e.changed||this.pendingRequestedCanvasPaths)&&(this.pendingRequestedCanvasPaths=e.requestedPaths,await this.writeRequestedCanvasPaths(e.requestedPaths),this.pendingRequestedCanvasPaths=null),e.requestedPaths.flatMap(e=>{const t=this.requestedPathToAbsolutePath(e);return t?[this.buildEntry(t)]:[]})})}},Js=p(Pe(),1);import{readdir as Qs}from"fs/promises";import Xs from"path";var Zs=new Set(["node_modules","build","tempo","android","ios","macos","linux","windows","web","lib","test"]),ei=4,ti=3,ni=2e3;function readPubspecFacts(e){let t;try{t=(0,Js.parse)(e)}catch{return null}if(!isRecord(t)||"string"!=typeof t.name)return null;const n=isRecord(t.dependencies)?t.dependencies:{},r=n.flutter,s=Array.isArray(t.workspace)?t.workspace.filter(e=>"string"==typeof e):null;return{name:t.name.trim(),dependsOnFlutter:isRecord(r)&&"flutter"===r.sdk,workspaceMember:"workspace"===t.resolution,workspace:s}}async function findFlutterPackages(e){const t=Xs.resolve(e),n=await readPubspecAt(t),r=new Set(n?.dependsOnFlutter?[t]:[]);for(const e of n?.workspace??[])for(const n of await expandGlob(t,e))r.add(n);for(const e of await readMelosPackageGlobs(t))for(const n of await expandGlob(t,e))r.add(n);for(const e of await findPackageFolders(t))r.add(e);const s=[];for(const e of[...r].sort()){const n=await readPubspecAt(e);n?.dependsOnFlutter&&s.push(await toCandidate(t,e,n))}return s}async function toCandidate(e,t,n){const r=Xs.relative(e,t).split(Xs.sep).join("/");return{dir:t,relativeDir:""===r?".":r,packageName:n.name,workspaceMember:n.workspaceMember,hasMain:null!==await readTextFileOptional2(Xs.join(t,"lib","main.dart"))}}async function findPackageFolders(e){const t=[];let n=ni,r=[e];for(let e=1;e<=ti;e++){const e=[];for(const s of r)for(const r of await listSearchableFolders(s)){if(0===n)return t;n-=1;const i=Xs.join(s,r),a=await readTextFileOptional2(Xs.join(i,"pubspec.yaml"));if(null===a){e.push(i);continue}t.push(i);const o=readPubspecFacts(a)?.workspace??[];t.push(...await expandWorkspaceEntries(i,o))}r=e}return t}async function readPubspecAt(e){const t=await readTextFileOptional2(Xs.join(e,"pubspec.yaml"));return null===t?null:readPubspecFacts(t)}async function readMelosPackageGlobs(e){const t=await readTextFileOptional2(Xs.join(e,"melos.yaml"));if(null===t)return[];try{const e=(0,Js.parse)(t);return isRecord(e)&&Array.isArray(e.packages)?e.packages.filter(e=>"string"==typeof e):[]}catch{return[]}}async function expandWorkspaceEntries(e,t){const n=new Set;for(const r of t)for(const t of await expandGlob(e,r))n.add(t);return[...n].sort()}async function expandGlob(e,t){const n=t.replace(/\\/g,"/").split("/").filter(e=>""!==e&&"."!==e);if(n.some(e=>".."===e))return[];let r=[e];for(const e of n){const t=[];for(const n of r)if("**"===e)t.push(...await descendants(n,ei));else if(e.includes("*")){const r=globSegmentMatcher(e);for(const e of await listSearchableFolders(n))r.test(e)&&t.push(Xs.join(n,e))}else t.push(Xs.join(n,e));r=t}return r}async function descendants(e,t){const n=[e];if(0===t)return n;for(const r of await listSearchableFolders(e))n.push(...await descendants(Xs.join(e,r),t-1));return n}async function listSearchableFolders(e){let t;try{t=await Qs(e,{withFileTypes:!0})}catch{return[]}return t.filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&!Zs.has(e.name)).map(e=>e.name).sort()}function globSegmentMatcher(e){const t=e.split("*").map(e=>e.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join("[^/]*");return new RegExp(`^${t}$`)}function isRecord(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}var ri=".flutter-host",si="tempo_flutter_host",ii="/__tempo/flutter/",ai="@tempo-owned: flutter-host",oi=[3,4,0],ci="__tempo_sentinel__",li="fonts/Roboto-Regular.ttf",di=new Set([".dart_tool","build"]);async function discoverPreviews(e,t){const n=is.join(e,"lib"),r=await listDartFiles(n),s=new Map,i=[];for(const n of r){const r=await readTextFileOptional2(n);if(null===r)continue;const a=toPosix(is.relative(e,n)),o=scanDartSourceForPreviews(r);if(0===o.previews.length&&0===o.skipped.length)continue;const c=resolveLibraryFile(a,o.partOf,t);for(const e of o.skipped)i.push({file:a,...e});for(const e of o.previews){if(null===c){i.push({file:a,line:e.line,name:e.name,reason:"part-file"});continue}const t=`${a}#${e.name}`;s.has(t)||s.set(t,{file:a,name:e.name,key:t,returns:e.returns,libraryFile:c,label:e.label,size:e.size})}}const a=[...s.values()].sort((e,t)=>e.key<t.key?-1:e.key>t.key?1:0);return{previews:a,skipped:i}}async function listDartFiles(e){let t;try{t=await ns(e,{withFileTypes:!0})}catch(e){if("ENOENT"===e.code)return[];throw e}const n=[];for(const r of t.sort((e,t)=>e.name<t.name?-1:1)){const t=is.join(e,r.name);if(r.isDirectory()){const e=di.has(r.name)||r.name.startsWith(".");e||n.push(...await listDartFiles(t));continue}r.isFile()&&r.name.endsWith(".dart")&&n.push(t)}return n}function resolveLibraryFile(e,t,n){if(null===t)return e;if(null===t.uri)return null;const r=`package:${n}/`,s=/^[A-Za-z][A-Za-z0-9+.-]*:/.test(t.uri);let i;if(t.uri.startsWith(r))i=is.posix.normalize(`lib/${t.uri.slice(r.length)}`);else{if(s)return null;i=is.posix.normalize(is.posix.join(is.posix.dirname(e),t.uri))}return i.startsWith("lib/")?i:null}var ui=/@(?:[A-Za-z_$][\w$]*\.)?Preview\s*\(/y,pi=/@[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*/y,hi=/(?:([A-Za-z_$][\w$]*)\.)?([A-Za-z_$][\w$]*)(\??)\s+([A-Za-z_$][\w$]*)\s*\(/y,mi=/[A-Za-z_$][\w$]*/g;function scanDartSourceForPreviews(e){const t=blankDartCommentsAndStrings(e),n=computeBraceDepths(t),r=[],s=[];for(let i=t.indexOf("@");-1!==i;){ui.lastIndex=i;const a=ui.exec(t);if(!a){i=t.indexOf("@",i+1);continue}const o=lineNumberAt(e,i),c=ui.lastIndex-1,l=matchingCloseIndex(t,c,"(",")"),d=-1===l?t.length:l+1;i=t.indexOf("@",d);const u=skipWhitespaceAndAnnotations(t,d);if(n[a.index]>0){s.push({line:o,name:declaredNameAt(t,u),reason:"not-top-level"});continue}const p=readFunctionDeclaration(t,u);"unsupported"!==p.kind?p.name.startsWith("_")?s.push({line:o,name:p.name,reason:"private"}):p.hasRequiredParameters?s.push({line:o,name:p.name,reason:"required-parameters"}):r.push({name:p.name,line:o,returns:p.kind,...readPreviewArguments(e,t,c,l)}):s.push({line:o,name:p.name,reason:"unsupported-declaration"})}return{previews:r,skipped:s,partOf:readPartOf(e,t)}}var fi=/^\d+(?:\.\d+)?$/;function readPreviewArguments(e,t,n,r){const s={label:null,size:null};if(-1===r)return s;for(const i of splitTopLevelArguments(t,n+1,r)){const n=/^\s*([A-Za-z_$][\w$]*)\s*:\s*/.exec(t.slice(i.start,i.end));if(!n)continue;const r=i.start+n[0].length;"name"===n[1]?s.label=readPlainStringLiteral(e,t,r,i.end):"size"===n[1]&&(s.size=readSizeLiteral(t.slice(r,i.end)))}return s}function splitTopLevelArguments(e,t,n){const r=[];let s=0,i=t;for(let a=t;a<n;a+=1){const t=e[a];"("===t||"["===t||"{"===t?s+=1:")"===t||"]"===t||"}"===t?s-=1:","===t&&0===s&&(r.push({start:i,end:a}),i=a+1)}return r.push({start:i,end:n}),r}function readPlainStringLiteral(e,t,n,r){const s=t.slice(n,r).trim(),i=s[0],a=("'"===i||'"'===i)&&s.length>=2&&s[s.length-1]===i&&!s.startsWith(i.repeat(3))&&s.indexOf(i,1)===s.length-1;if(!a)return null;const o=t.indexOf(i,n)+1,c=e.slice(o,o+s.length-2);return c.includes("$")?null:c.replace(/\\(.)/g,"$1")}function readSizeLiteral(e){const t=e.trim().replace(/^const\s+/,""),n=/^Size\s*\(\s*([^,()]+?)\s*,\s*([^,()]+?)\s*,?\s*\)$/.exec(t),r=/^Size\.square\s*\(\s*([^,()]+?)\s*,?\s*\)$/.exec(t),[s,i]=n?[n[1],n[2]]:r?[r[1],r[1]]:[null,null];if(null===s||null===i)return null;if(!fi.test(s)||!fi.test(i))return null;const a={width:Number(s),height:Number(i)};return a.width>0&&a.height>0?a:null}function readFunctionDeclaration(e,t){hi.lastIndex=t;const n=hi.exec(e);if(!n)return{kind:"unsupported",name:declaredNameAt(e,t)};const[,,r,s,i]=n;if("Function"===i){const t=matchingCloseIndex(e,hi.lastIndex-1,"(",")");return{kind:"unsupported",name:-1===t?null:declaredNameAt(e,t+1)}}const a=""===s&&("Widget"===r||"WidgetBuilder"===r);if(!a)return{kind:"unsupported",name:i};const o=hi.lastIndex-1,c=matchingCloseIndex(e,o,"(",")"),l=-1===c?"":e.slice(o+1,c).trim();return{kind:r,name:i,hasRequiredParameters:parametersRequireArguments(l)}}function parametersRequireArguments(e){return""!==e&&(!e.startsWith("[")&&(!e.startsWith("{")||/\brequired\b/.test(e)))}function skipWhitespaceAndAnnotations(e,t){let n=skipWhitespace(e,t);for(;"@"===e[n];){pi.lastIndex=n;const t=pi.exec(e);if(!t)return n;if(n=skipWhitespace(e,pi.lastIndex),"("===e[n]){const t=matchingCloseIndex(e,n,"(",")");if(-1===t)return e.length;n=skipWhitespace(e,t+1)}}return n}function skipWhitespace(e,t){let n=t;for(;n<e.length&&/\s/.test(e[n]);)n+=1;return n}function declaredNameAt(e,t){const n=e.slice(t).search(/[({=;]/);if(-1===n)return null;const r=e.slice(t,t+n).match(mi);return r?r[r.length-1]:null}function readPartOf(e,t){const n=/^\s*part\s+of\b/m.exec(t);if(!n)return null;const r=/^\s*part\s+of\s+(['"])([^'"]+)\1/m.exec(e.slice(n.index));return{uri:r?r[2]:null}}function matchingCloseIndex(e,t,n,r){let s=0;for(let i=t;i<e.length;i+=1)if(e[i]===n)s+=1;else if(e[i]===r&&(s-=1,0===s))return i;return-1}function computeBraceDepths(e){const t=new Uint16Array(e.length+1);let n=0;for(let r=0;r<e.length;r+=1)t[r]=n,"{"===e[r]?n+=1:"}"===e[r]&&n>0&&(n-=1);return t[e.length]=n,t}function lineNumberAt(e,t){let n=1;for(let r=0;r<t;r+=1)10===e.charCodeAt(r)&&(n+=1);return n}function blankDartCommentsAndStrings(e){const t=e.split(""),blank=(e,n)=>{for(let r=e;r<n;r+=1)"\n"!==t[r]&&(t[r]=" ")},blockCommentEnd=t=>{let n=0,r=t;for(;r<e.length;)if(e.startsWith("/*",r))n+=1,r+=2;else if(e.startsWith("*/",r)){if(n-=1,r+=2,0===n)return r}else r+=1;return e.length},isRawStringStart=t=>t>0&&"r"===e[t-1]&&!(t>1&&/[\w$]/.test(e[t-2])),scanCode=(t,n)=>{let r=0,s=t;for(;s<e.length;){const t=e[s];if(e.startsWith("//",s)){const t=e.indexOf("\n",s),n=-1===t?e.length:t;blank(s,n),s=n}else if(e.startsWith("/*",s)){const e=blockCommentEnd(s);blank(s,e),s=e}else if("'"===t||'"'===t)s=scanString(s,isRawStringStart(s));else{if(n)if("{"===t)r+=1;else if("}"===t){if(0===r)return s;r-=1}s+=1}}return s},scanString=(t,n)=>{const r=e[t],s=e.startsWith(r.repeat(3),t)?r.repeat(3):r,i=t+s.length;let a=i;for(;a<e.length;)if(n||"\\"!==e[a]){if(e.startsWith(s,a))return blank(i,a),a+s.length;if(1===s.length&&"\n"===e[a])return blank(i,a),a;!n&&e.startsWith("${",a)?a=scanCode(a+2,!0)+1:a+=1}else a+=2;return blank(i,e.length),e.length};return scanCode(0,!1),t.join("")}async function ensureFlutterHost(e){const t=is.join(e.tempoRoot,ri),n=[...new Set(e.packages.map(e=>e.dir))].sort();if(!n.length)throw new Ms(t,"has no resolved preview packages");await ts(t,{recursive:!0});const r=await rs(t),s=await rs(e.hostRoot??e.tempoRoot),i=await Promise.all(n.map(async e=>{const t=await rs(e).catch(()=>{throw new Ms(is.join(e,"pubspec.yaml"),"does not exist")}),n=is.join(e,"pubspec.yaml"),r=await readTextFileOptional2(n);if(null===r)throw new Ms(n,"does not exist");const s=parseFlutterAppPubspec((0,Zr.stringify)(await effectivePubspec(e,r)),n);return{...s,dir:t,discovery:await discoverPreviews(t,s.packageName)}})),a=new Map,o={},c=new Map,l=new Map;for(const e of i){if(e.packageName===si||a.has(e.packageName)&&a.get(e.packageName)!==e.dir)throw new Ts("flutter_packages_conflict",`Package ${e.packageName} conflicts between ${a.get(e.packageName)??t} and ${e.dir}.`);a.set(e.packageName,e.dir);const n=await appDependencyOverrides(e.dir,e.dependencyOverrides),s=e.workspaceMember?await workspaceDependencyOverrides(e.dir,r,e.packageName):null;s&&l.set(e.dir,s.root);const i=mergeDependencyOverrides(s?.overrides??null,null===n?null:rebaseDependencyOverrides(n,e.dir,r));for(const[t,n]of Object.entries(i??{})){if(t in o&&stableDescriptor(o[t])!==stableDescriptor(n))throw new Ts("flutter_packages_conflict",`Dependency ${t} has conflicting overrides in ${c.get(t)} and ${e.dir}: ${JSON.stringify(o[t])} versus ${JSON.stringify(n)}.`);o[t]=n,c.set(t,e.dir)}}for(const[e,t]of a){const n=o[e];if(n&&(!n.path||is.resolve(r,n.path)!==t))throw new Ts("flutter_packages_conflict",`Override for hosted package ${e} redirects ${t} to ${JSON.stringify(n)}.`)}const d=i.map(e=>e.packageName).join(", "),u={previews:i.flatMap(e=>e.discovery.previews.map(t=>({...t,packageName:e.packageName,key:flutterPreviewKey(s,is.join(e.dir,t.file),t.name)}))),skipped:i.flatMap(e=>e.discovery.skipped)},p=i.map(e=>e.dartSdkConstraint).sort((e,t)=>{const n=e.match(/\d+/g)?.map(Number)??[],r=t.match(/\d+/g)?.map(Number)??[];for(let e=0;e<3;e++)if(n[e]!==r[e])return(n[e]??0)-(r[e]??0);const s=e.includes("-"),i=t.includes("-");return s!==i?s?-1:1:e.localeCompare(t,void 0,{numeric:!0})}).at(-1),h=[],m=await bundleRobotoFont({hostDir:t,flutterSdkRoot:e.flutterSdkRoot??null});m.written&&h.push(m.written);const f=[["pubspec.yaml",buildHostPubspec({packageName:d,packages:i.map(e=>({name:e.packageName,path:pathFromHost(r,e.dir)})),dartSdkConstraint:p,dependencyOverrides:Object.keys(o).length?o:null,fromWorkspace:i.some(e=>e.workspaceMember),robotoAsset:"bundled"===m.status?li:null})],["lib/main.dart",vi],["lib/tempo_assets.dart",yi],["lib/tempo_previews.dart",buildPreviewRegistry(d,u.previews)],["lib/tempo_layers.dart",buildLayersBridge({roots:i.map(e=>({uri:as(e.dir).href,relative:toPosix(is.relative(s,e.dir))})),hostDirUri:as(r).href})],["web/index.html",Ei],["web/flutter_bootstrap.js",Ti]],g=[];for(const[e,n]of f){const r=is.join(t,e),s=await reconcileOwnedFile(r,n);"written"===s&&h.push(r),"user-owned"===s&&g.push(r)}const y=l.size===i.length&&1===new Set(l.values()).size?[...l.values()][0]:null,v=y?[y]:i.map(e=>e.dir),E=await Promise.all(v.map(e=>readTextFileOptional2(is.join(e,"pubspec.lock")))),T=1===v.length?v[0]:1===E.filter(Boolean).length?v[E.findIndex(Boolean)]:null,w=T?await seedHostLockFromApp(t,T):null;null!==w&&h.push(w);const S=is.join(t,"lib","tempo_previews.dart");return{hostDir:t,packageName:d,previewsChanged:h.includes(S),previews:u.previews,skipped:u.skipped,writtenFiles:h,userOwnedFiles:g,roboto:m.status}}async function bundleRobotoFont(e){if(null===e.flutterSdkRoot)return{status:"sdk-fonts-missing",written:null};const t=is.join(e.flutterSdkRoot,"bin","cache","artifacts","material_fonts","Roboto-Regular.ttf"),n=await ss(t).catch(()=>null);if(!n?.isFile())return{status:"sdk-fonts-missing",written:null};const r=is.join(e.hostDir,li),s=await ss(r).catch(()=>null);return s?.isFile()&&s.size===n.size?{status:"bundled",written:null}:(await ts(is.dirname(r),{recursive:!0}),await es(t,r),{status:"bundled",written:r})}async function reconcileOwnedFile(e,t){const n=await readTextFileOptional2(e);return n===t?"unchanged":null===n||isTempoOwned(n)?(await atomicWriteText2(e,t),"written"):"user-owned"}function isTempoOwned(e){return e.slice(0,200).includes(ai)}function pathFromHost(e,t){const n=is.relative(e,t);return toPosix(is.isAbsolute(n)?t:n)}async function seedHostLockFromApp(e,t){const n=is.join(e,"pubspec.lock");if(null!==await readTextFileOptional2(n))return null;const r=await readTextFileOptional2(is.join(t,"pubspec.lock"));return null===r?null:(await atomicWriteText2(n,r),n)}var gi=/^[A-Za-z_][A-Za-z0-9_]*$/;function parseFlutterAppPubspec(e,t){let n;try{n=(0,Zr.parse)(e)}catch(e){const n=e instanceof Error?e.message.split("\n")[0]:"";throw new Ms(t,`is not valid YAML (${n})`)}const r=null!==n&&"object"==typeof n?n:{},s=r.name;if("string"!=typeof s||""===s.trim())throw new Ms(t,"has no top-level `name:`");const i=s.trim();if(!gi.test(i))throw new Ms(t,`has \`name: ${i}\`, which is not a Dart identifier`);return{packageName:i,dartSdkConstraint:hostDartSdkConstraint(r.environment?.sdk),dependencyOverrides:asDependencyOverrides(r.dependency_overrides),workspaceMember:"workspace"===r.resolution}}function asDependencyOverrides(e){const t=null!==e&&"object"==typeof e;return!t||Array.isArray(e)?null:Object.keys(e).length>0?e:null}async function appDependencyOverrides(e,t){const n=await readTextFileOptional2(is.join(e,"pubspec_overrides.yaml"));if(null===n)return t;try{const e=(0,Zr.parse)(n),r=null!==e&&"object"==typeof e&&"dependency_overrides"in e;return r?asDependencyOverrides(e.dependency_overrides):t}catch(t){throw new Ms(is.join(e,"pubspec_overrides.yaml"),`is invalid: ${String(t)}`)}}async function effectivePubspec(e,t){const n=parseYamlOptional(t)??{},r=is.join(e,"pubspec_overrides.yaml"),s=await readTextFileOptional2(r);if(null===s)return n;try{const e=(0,Zr.parse)(s);if(null!==e&&("object"!=typeof e||Array.isArray(e)))throw new Error("expected a YAML mapping");for(const t of["dependency_overrides","workspace","resolution"])e&&t in e&&(n[t]=e[t]);return n}catch(e){throw new Ms(r,`is invalid: ${String(e)}`)}}function rebaseDependencyOverrides(e,t,n){const r={};for(const[s,i]of Object.entries(e)){const e=null===i||"object"!=typeof i||Array.isArray(i)?null:i,a="string"==typeof e?.path?e.path:null;r[s]=null===a?i:{...e,path:pathFromHost(n,canonicalPathAllowMissing(is.resolve(t,a)))}}return r}async function workspaceDependencyOverrides(e,t,n){for(let r=is.dirname(e);r!==is.dirname(r);r=is.dirname(r)){const s=await readTextFileOptional2(is.join(r,"pubspec.yaml")),i=null===s?null:await effectivePubspec(r,s),a=Array.isArray(i?.workspace)?i.workspace.filter(e=>"string"==typeof e):null;if(!a)continue;const o=await expandWorkspaceEntries(r,a),c=await Promise.all(o.map(e=>rs(e).catch(()=>null)));if(!c.includes(e))continue;const l={};for(const r of c){if(null===r||r===e)continue;const s=await readTextFileOptional2(is.join(r,"pubspec.yaml")),i=null===s?null:parseYamlOptional(s)?.name;"string"==typeof i&&i!==n&&(l[i]={path:pathFromHost(t,r)})}const d={},u=new Map;for(const e of[...new Set([r,...c.filter(e=>null!==e)])]){const n=parseYamlOptional(await readTextFileOptional2(is.join(e,"pubspec.yaml"))??""),r=await appDependencyOverrides(e,asDependencyOverrides(n?.dependency_overrides)),s=null===r?{}:rebaseDependencyOverrides(r,e,t);for(const[t,n]of Object.entries(s)){if(u.has(t))throw new Ts("flutter_packages_conflict",`Workspace dependency ${t} is overridden by both ${u.get(t)} and ${e}. Define it once in the workspace.`);d[t]=n,u.set(t,e)}}return{root:r,overrides:mergeDependencyOverrides(l,d)}}return null}async function flutterWorkspaceDirectories(e){const t=new Set;for(const n of e){const e=await readTextFileOptional2(is.join(n,"pubspec.yaml"));if(null!==e&&"workspace"===(await effectivePubspec(n,e)).resolution)for(let e=is.dirname(n);e!==is.dirname(e);e=is.dirname(e)){const r=await readTextFileOptional2(is.join(e,"pubspec.yaml"));if(null===r)continue;const s=(await effectivePubspec(e,r)).workspace;if(!Array.isArray(s))continue;const i=await expandWorkspaceEntries(e,s.filter(e=>"string"==typeof e)),a=i.map(canonicalPathAllowMissing);if(a.includes(n)){for(const n of[e,...a])t.add(n);break}}}return[...t]}function mergeDependencyOverrides(e,t){const n={...e,...t};return Object.keys(n).length>0?n:null}function parseYamlOptional(e){try{const t=(0,Zr.parse)(e);return null!==t&&"object"==typeof t?t:null}catch{return null}}function hostDartSdkConstraint(e){const t="string"==typeof e?/(?:\^|>=)\s*((\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?)/.exec(e):null;if(!t)return`^${oi.join(".")}`;const n=[Number(t[2]),Number(t[3]),Number(t[4])],r=compareVersions(n,oi)>=0;return r?`^${t[1]}`:`^${oi.join(".")}`}function compareVersions(e,t){for(let n=0;n<3;n+=1)if(e[n]!==t[n])return e[n]-t[n];return 0}function buildHostPubspec(e){const t=e.robotoAsset?`\n # The Flutter web engine's default text font, from the Flutter SDK, so text\n # renders without fetching it from fonts.gstatic.com (offline included).\n fonts:\n - family: Roboto\n fonts:\n - asset: ${e.robotoAsset}\n`:"",n=e.fromWorkspace?"The app's overrides and its pub workspace's packages":"The app's overrides",r=null===e.dependencyOverrides?"":`\n# ${n}: pub applies them only in the root package.\n${(0,Zr.stringify)({dependency_overrides:e.dependencyOverrides})}`;return`# ${ai}\n# Generated by Tempo: the Flutter Web host that renders the @Preview functions\n# of ${e.packageName} on the canvas. Rewritten when the app changes; delete\n# the first line to stop Tempo from managing this file.\nname: ${si}\npublish_to: none\n\nenvironment:\n sdk: ${JSON.stringify(e.dartSdkConstraint)}\n\ndependencies:\n flutter:\n sdk: flutter\n${e.packages.map(e=>` ${e.name}:\n path: ${JSON.stringify(e.path)}`).join("\n")}\n\nflutter:\n uses-material-design: true\n${t}${r}`}function buildPreviewRegistry(e,t){const libraryOf=t=>`package:${t.packageName??e}/${t.libraryFile.replace(/^lib\//,"")}`,n=[...new Set(t.map(libraryOf))].sort(),r=new Map(n.map((e,t)=>[e,`p${t}`])),s=n.map(e=>`import ${dartString(e)} as ${r.get(e)};`),i=t.map(t=>{const n=`${r.get(libraryOf(t))}.${t.name}()`,s="WidgetBuilder"===t.returns?`Builder(builder: ${n})`:n;return` ${dartString(t.key)}: () => tempoPreviewAssets(${dartString(t.packageName??e)}, ${s}),`});return[`// ${ai}`,`// Generated by Tempo from the @Preview functions in package:${e}.`,"// Rewritten whenever the preview set changes; delete the first line to stop","// Tempo from managing this file.","import 'package:flutter/widgets.dart';","import 'tempo_assets.dart';",...s.length>0?["",...s]:[],"","/// Every renderable @Preview function, keyed `<file in the app>#<function>`","/// (the `preview` prop of a FlutterStoryboard).","final Map<String, Widget Function()> tempoPreviews ="," <String, Widget Function()>{",...i,"};",""].join("\n")}function dartString(e){const t=e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\$/g,"\\$").replace(/\n/g,"\\n");return`'${t}'`}function toPosix(e){return e.split(is.sep).join("/")}var yi=`// ${ai}\nimport 'dart:typed_data';\nimport 'dart:ui' show ImmutableBuffer;\nimport 'package:flutter/services.dart';\nimport 'package:flutter/widgets.dart';\n\nfinal Map<String, AssetBundle> _bundles = <String, AssetBundle>{};\n\nWidget tempoPreviewAssets(String package, Widget child) => DefaultAssetBundle(\n bundle: _bundles.putIfAbsent(package, () => _PreviewAssetBundle(package)),\n child: child,\n);\n\nclass _PreviewAssetBundle extends PlatformAssetBundle {\n _PreviewAssetBundle(this.package);\n final String package;\n\n String _assetKey(String key) {\n if (key.startsWith('packages/') ||\n key == 'AssetManifest.json' ||\n key == 'AssetManifest.bin' ||\n key == 'AssetManifest.bin.json' ||\n key == 'FontManifest.json') return key;\n return 'packages/$package/$key';\n }\n\n @override\n Future<ByteData> load(String key) => super.load(_assetKey(key));\n\n @override\n Future<ImmutableBuffer> loadBuffer(String key) async {\n final ByteData data = await load(key);\n return ImmutableBuffer.fromUint8List(Uint8List.sublistView(data));\n }\n}\n`,vi=`// ${ai}\n// Generated by Tempo: renders one @Preview per Flutter view so the canvas can\n// show many storyboards from a single engine. Delete the first line to stop\n// Tempo from managing this file.\nimport 'dart:js_interop';\nimport 'dart:ui' show FlutterView;\nimport 'dart:ui_web' as ui_web;\n\nimport 'package:flutter/material.dart';\n\nimport 'tempo_layers.dart';\nimport 'tempo_previews.dart';\n\n/// The preview key of the hidden view the canvas adds to work around\n/// flutter/flutter#185034. It must paint nothing.\nconst String tempoSentinelPreviewKey = '${ci}';\n\n/// \`window.__tempoFlutter\`, owned by the canvas SDK's Flutter runtime.\n@JS('__tempoFlutter')\nexternal _TempoFlutterHooks? get _tempoFlutterHooks;\n\nextension type _TempoFlutterHooks._(JSObject _) implements JSObject {\n /// The ratio the SDK sizes each view's relay at\n /// (FLUTTER_DEVICE_PIXEL_RATIO in the SDK's flutter-runtime.ts).\n external JSNumber? get devicePixelRatio;\n}\n\nvoid main() {\n // Every view renders at the SDK's ratio, not the browser's. Each view reads\n // it when the page adds the view, so it is set before any exists.\n final double? ratio = _tempoFlutterHooks?.devicePixelRatio?.toDartDouble;\n if (ratio != null && ratio > 0) ui_web.debugOverrideDevicePixelRatio(ratio);\n // Before runWidget: a hot restart re-runs main(), a hot reload does not.\n installTempoLayers();\n runWidget(const TempoMultiViewApp());\n}\n\n/// One [View] per Flutter view the page added; rebuilt when views come and go.\nclass TempoMultiViewApp extends StatefulWidget {\n const TempoMultiViewApp({super.key});\n\n @override\n State<TempoMultiViewApp> createState() => _TempoMultiViewAppState();\n}\n\nclass _TempoMultiViewAppState extends State<TempoMultiViewApp>\n with WidgetsBindingObserver {\n @override\n void initState() {\n super.initState();\n WidgetsBinding.instance.addObserver(this);\n }\n\n @override\n void dispose() {\n WidgetsBinding.instance.removeObserver(this);\n super.dispose();\n }\n\n @override\n void didChangeMetrics() {\n // Fires when the page adds or removes a view.\n setState(() {});\n }\n\n @override\n void reassemble() {\n super.reassemble();\n // A hot reload: source lines may have moved under unchanged widgets.\n tempoLayersReassembled();\n }\n\n @override\n Widget build(BuildContext context) {\n return ViewCollection(\n views: <Widget>[\n for (final FlutterView view\n in WidgetsBinding.instance.platformDispatcher.views)\n View(\n key: ValueKey<int>(view.viewId),\n view: view,\n child: previewFor(view),\n ),\n ],\n );\n }\n}\n\n/// The widget for one view, chosen by the \`preview\` key in its initialData.\nWidget previewFor(FlutterView view) {\n final Object? data = ui_web.views.getInitialData(view.viewId)?.dartify();\n final Map<Object?, Object?> fields = data is Map<Object?, Object?>\n ? data\n : const <Object?, Object?>{};\n final Object? previewField = fields['preview'];\n final String previewKey = previewField is String ? previewField : '';\n // No shell, no MaterialApp: the sentinel exists only to size the engine's\n // shared surface and must own no painted content.\n if (previewKey == tempoSentinelPreviewKey) return const SizedBox.shrink();\n final Widget Function()? build = tempoPreviews[previewKey];\n // Building inside a Builder confines a throwing preview function to its\n // own view: Flutter swaps that subtree for an ErrorWidget.\n final Widget child = build == null\n ? TempoPreviewMissing(previewKey: previewKey)\n : Builder(builder: (BuildContext context) => build());\n return TempoPreviewShell(\n width: _asDouble(fields['width']),\n height: _asDouble(fields['height']),\n child: child,\n );\n}\n\ndouble? _asDouble(Object? value) => value is num ? value.toDouble() : null;\n\n/// What a bare widget needs to lay out: Material theme, text direction,\n/// a Navigator and Overlay, on a transparent background, at the storyboard's\n/// size in the top-left corner.\nclass TempoPreviewShell extends StatelessWidget {\n const TempoPreviewShell({\n super.key,\n required this.width,\n required this.height,\n required this.child,\n });\n\n final double? width;\n final double? height;\n final Widget child;\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n debugShowCheckedModeBanner: false,\n home: Material(\n type: MaterialType.transparency,\n child: Align(\n alignment: Alignment.topLeft,\n child: SizedBox(width: width, height: height, child: child),\n ),\n ),\n );\n }\n}\n\n/// Shown instead of throwing when a storyboard names an unknown preview.\nclass TempoPreviewMissing extends StatelessWidget {\n const TempoPreviewMissing({super.key, required this.previewKey});\n\n final String previewKey;\n\n @override\n Widget build(BuildContext context) {\n final String known = tempoPreviews.keys.isEmpty\n ? '(none found in lib/)'\n : tempoPreviews.keys.join('\\n');\n return Padding(\n padding: const EdgeInsets.all(12),\n child: Text(\n 'No public top-level @Preview function for "$previewKey".\\n'\n 'Known previews:\\n$known',\n style: const TextStyle(color: Color(0xFFB00020), fontSize: 13),\n ),\n );\n }\n}\n`;function buildLayersBridge(e){return`// ${ai}\n// Generated by Tempo: reports the app's own widgets in every Flutter view to\n// the canvas as layer snapshots, so they can be selected like React layers.\n// Delete the first line to stop Tempo from managing this file.\nimport 'dart:async';\nimport 'dart:convert';\nimport 'dart:js_interop';\nimport 'dart:ui_web' as ui_web;\n\nimport 'package:flutter/rendering.dart';\nimport 'package:flutter/scheduler.dart';\nimport 'package:flutter/widgets.dart';\n\n/// The app's real directory. Widgets created in files under it are the\n/// user's; Flutter's, packages' and this host's are not.\nconst List<String> _packageUris = <String>[${e.roots.map(e=>dartString(e.uri)).join(", ")}];\n\n/// This host project's real directory. Never the user's code, even when the\n/// app is the project root and contains it.\nconst String _hostDirUri = ${dartString(e.hostDirUri)};\n\n/// The app's directory relative to the canvas host's root, the tempo folder\n/// ('..' when the app is the project root). React layers'\n/// data-tempo-filepath is relative to the same root, e.g. '../src/App.tsx'.\nconst List<String> _packageRelativePaths = <String>[${e.roots.map(e=>dartString(e.relative)).join(", ")}];\n\n/// The hidden view that sizes the engine's surface. It has no layers.\nconst String _sentinelPreviewKey = ${dartString(ci)};\n\n/// While frames are continuous, at most one walk per interval.\nconst Duration _walkInterval = Duration(milliseconds: 50);\n\n// Compared with creation locations in one form: decoded, Windows drive\n// letter in lower case ('C:' and 'c:' name the same drive, and Node's file\n// URLs and the kernel's URIs need not agree).\nfinal List<String> _packageDirs = _packageUris.map(_comparableFileUri).toList();\nfinal String _hostDir = _comparableFileUri(_hostDirUri);\n\n/// Layer ids: a counter kept on each Element, which lives across rebuilds\n/// and hot reloads. identityHashCode is random on the web and two widgets\n/// could share one. A hot restart starts a new engine and a new count.\nfinal Expando<int> _layerIds = Expando<int>('tempo layer id');\nint _lastLayerId = 0;\n\n/// \`window.__tempoFlutter\`, owned by the canvas SDK's Flutter runtime.\n@JS('__tempoFlutter')\nexternal _TempoFlutterRuntime? get _runtime;\n\nextension type _TempoFlutterRuntime._(JSObject _) implements JSObject {\n /// True in documents that select; the walk runs only then.\n external JSAny? get wantLayers;\n\n /// Receives one snapshot as a JSON string.\n external void onLayers(JSString snapshot);\n}\n\n_TempoLayers? _layers;\n\n/// Starts reporting layers. Called from main() before runWidget.\nvoid installTempoLayers() {\n WidgetsFlutterBinding.ensureInitialized();\n // Makes createdByLocalProject mean "created in the app directory". The\n // default, anything outside package:flutter, would also count pub\n // packages and this host. The inspector compares paths case-sensitively,\n // so a Windows drive letter is registered in both cases.\n // ignore: invalid_use_of_protected_member\n WidgetInspectorService.instance.addPubRootDirectories(<String>[\n for (final uri in _packageUris) ...<String>[\n _withDriveLetterCase(uri, upper: false),\n _withDriveLetterCase(uri, upper: true),\n ],\n ]);\n final _TempoLayers layers = _TempoLayers();\n _layers = layers;\n // Registered after the rendering binding's own callback, so it runs once\n // the frame's layout and paint are done.\n SchedulerBinding.instance.addPersistentFrameCallback(layers.onFrame);\n}\n\n/// Called from the shell's State.reassemble on every hot reload. The next\n/// snapshot is pushed even if nothing moved (_pushIfChanged compares\n/// \`reloads\` with the nodes), so the canvas re-reads source line tables, and\n/// a reload that changes only paint (a color) still bumps the view's rev: that\n/// attribute change is the content revision that makes the board's resting\n/// screenshot stale. Animations push nothing and stay live-only.\nvoid tempoLayersReassembled() {\n _layers?.reloads += 1;\n}\n\n/// What one view last pushed, so an unchanged walk pushes nothing.\nclass _ViewState {\n _ViewState({required this.isSentinel});\n\n final bool isSentinel;\n int rev = 0;\n int pushedReloads = -1;\n String? pushedNodes;\n // A failing walk repeats every frame; it is reported until it succeeds once.\n bool failureReported = false;\n}\n\nclass _TempoLayers {\n int reloads = 0;\n final Map<int, _ViewState> _views = <int, _ViewState>{};\n final Stopwatch _sinceWalk = Stopwatch();\n Timer? _deferredWalk;\n\n void onFrame(Duration timeStamp) {\n if (!_wantsLayers(_runtime)) return;\n // This window's walk is already due; it will read the latest frame.\n if (_deferredWalk != null) return;\n final Duration wait = _walkInterval - _sinceWalk.elapsed;\n if (!_sinceWalk.isRunning || wait <= Duration.zero) {\n _walk();\n return;\n }\n _deferredWalk = Timer(wait, () {\n _deferredWalk = null;\n _walk();\n });\n }\n\n void _walk() {\n // Every publish goes through here, the deferred walk's timer included.\n // A hot restart installs a new instance, but a timer this one deferred\n // can still fire within the window after it; publishing then would push\n // this instance's old \`reloads\`, which the canvas reads as a hot reload.\n if (!identical(_layers, this)) return;\n final _TempoFlutterRuntime? runtime = _runtime;\n if (runtime == null || !_wantsLayers(runtime)) return;\n try {\n _walkViews(runtime);\n } finally {\n // The window starts when the walk ends: a walk slower than the window\n // still leaves the frames after it free.\n _sinceWalk\n ..reset()\n ..start();\n }\n }\n\n void _walkViews(_TempoFlutterRuntime runtime) {\n final Set<int> liveViews = <int>{};\n final Element? root = WidgetsBinding.instance.rootElement;\n for (final Element viewElement in _viewElementsUnder(root)) {\n final int viewId = (viewElement.widget as View).view.viewId;\n liveViews.add(viewId);\n final _ViewState state = _views.putIfAbsent(\n viewId,\n () => _ViewState(isSentinel: _previewKeyOf(viewId) == _sentinelPreviewKey),\n );\n if (state.isSentinel) continue;\n try {\n _pushIfChanged(runtime, viewId, state, _appNodesUnder(viewElement));\n state.failureReported = false;\n } catch (error, stack) {\n // One view's failure never stops the views walked after it, and a\n // failure that repeats every frame is reported once.\n if (state.failureReported) continue;\n state.failureReported = true;\n FlutterError.reportError(FlutterErrorDetails(\n exception: error,\n stack: stack,\n library: 'Tempo layers',\n context: ErrorDescription('while reporting the layers of Flutter view $viewId'),\n ));\n }\n }\n // A removed view's state goes with it; a re-added id starts over.\n _views.removeWhere((int viewId, _ViewState state) => !liveViews.contains(viewId));\n }\n\n void _pushIfChanged(\n _TempoFlutterRuntime runtime,\n int viewId,\n _ViewState state,\n List<Map<String, Object?>> nodeList,\n ) {\n final String nodes = jsonEncode(nodeList);\n final bool unchanged = nodes == state.pushedNodes && reloads == state.pushedReloads;\n if (unchanged) return;\n state.rev += 1;\n state.pushedNodes = nodes;\n state.pushedReloads = reloads;\n final int rev = state.rev;\n runtime.onLayers('{"viewId":$viewId,"rev":$rev,"reloads":$reloads,"nodes":$nodes}'.toJS);\n }\n}\n\nbool _wantsLayers(_TempoFlutterRuntime? runtime) =>\n runtime != null && runtime.wantLayers.dartify() == true;\n\n/// The shell's View elements, one per Flutter view.\nList<Element> _viewElementsUnder(Element? root) {\n final List<Element> views = <Element>[];\n void visit(Element element) {\n if (element.widget is View) {\n views.add(element);\n return;\n }\n element.visitChildren(visit);\n }\n\n if (root != null) visit(root);\n return views;\n}\n\nString? _previewKeyOf(int viewId) {\n final Object? data = ui_web.views.getInitialData(viewId)?.dartify();\n if (data is! Map<Object?, Object?>) return null;\n final Object? preview = data['preview'];\n return preview is String ? preview : null;\n}\n\n/// The app's widgets under one view, in pre-order (paint order among\n/// siblings). Framework elements between two of them are skipped, so each\n/// node's parent is its nearest app-widget ancestor.\nList<Map<String, Object?>> _appNodesUnder(Element viewElement) {\n final List<Map<String, Object?>> nodes = <Map<String, Object?>>[];\n final Map<String, Object?> Function(Element) readProperties =\n _newInspectorPropertiesReader();\n final _ViewTransforms transforms = _ViewTransforms();\n\n // [clipAbove]: the clip every render object above this element paints\n // under, in view coordinates; null when nothing clips.\n void visit(\n Element element,\n String? appParent,\n bool ancestorsPaint,\n Rect? clipAbove,\n ) {\n final RenderObject? renderObject = element.renderObject;\n // Once something here paints nothing, nothing under it paints either.\n final bool renderObjectHides = element is RenderObjectElement &&\n renderObject != null &&\n _paintsNothing(renderObject);\n final bool paintsSubtree =\n ancestorsPaint && !renderObjectHides && !_hidesBuiltChild(element.widget);\n // The element that owns a render object adds its parent's clip, once.\n // A component shares the render object of a descendant, which adds it\n // when the walk gets there.\n final Rect? clip = element is RenderObjectElement && renderObject != null\n ? _clipUnderParent(renderObject, clipAbove, transforms)\n : clipAbove;\n String? parentOfChildren = appParent;\n final _AppLocation? location = _appLocationOf(element, readProperties);\n if (location != null) {\n final String id = _layerIdOf(element);\n // A component's box is its descendant render object's, so it is cut\n // by that object's clip.\n final Rect? nodeClip = element is RenderObjectElement || renderObject == null\n ? clip\n : _clipUnderParent(renderObject, clipAbove, transforms);\n final Rect? measured = _paintedRectInView(renderObject, transforms);\n nodes.add(\n _nodeFor(id, appParent, element, location, ancestorsPaint, measured, nodeClip),\n );\n parentOfChildren = id;\n }\n element.visitChildren(\n (Element child) => visit(child, parentOfChildren, paintsSubtree, clip),\n );\n }\n\n viewElement.visitChildren((Element child) => visit(child, null, true, null));\n return nodes;\n}\n\nclass _AppLocation {\n const _AppLocation(this.file, this.line, this.column);\n\n /// Relative to the canvas host's root, e.g. '../flutter-app/lib/cards.dart'.\n final String file;\n\n /// 1-based.\n final int line;\n\n /// 1-based.\n final int column;\n}\n\n/// The inspector's per-node properties, including \`creationLocation\` and\n/// \`createdByLocalProject\`. On Flutter 3.47 the serializer is the only way\n/// to a widget's creation location (3.50 adds CreationLocation.of). A fresh\n/// reader per walk, since the serializer keeps every local node it describes.\nMap<String, Object?> Function(Element) _newInspectorPropertiesReader() {\n // ignore: invalid_use_of_visible_for_testing_member\n final delegate = InspectorSerializationDelegate(service: WidgetInspectorService.instance);\n return (Element element) =>\n delegate.additionalNodeProperties(element.toDiagnosticsNode());\n}\n\n/// Where the app created [element]'s widget, or null when the widget is not\n/// the app's own.\n_AppLocation? _appLocationOf(\n Element element,\n Map<String, Object?> Function(Element) readProperties,\n) {\n // The cheap test first: it rejects framework widgets without building a\n // diagnostics node.\n if (!debugIsWidgetLocalCreation(element.widget)) return null;\n final Map<String, Object?> properties = readProperties(element);\n final Object? location = properties['creationLocation'];\n final bool isLocal = properties['createdByLocalProject'] == true;\n if (!isLocal || location is! Map<String, Object?>) return null;\n final String? file = _hostRootRelativeFile(location['file']);\n final Object? line = location['line'];\n final Object? column = location['column'];\n if (file == null || line is! int || column is! int) return null;\n return _AppLocation(file, line, column);\n}\n\n/// A creation location's file as React layers name theirs, relative to the\n/// canvas host's root; null outside the app or inside this host.\nString? _hostRootRelativeFile(Object? fileUri) {\n if (fileUri is! String) return null;\n final String file = _comparableFileUri(fileUri);\n final bool inHost = file.startsWith('$_hostDir/');\n if (inHost) return null;\n for (int i = 0; i < _packageDirs.length; i++) {\n final dir = _packageDirs[i];\n if (!file.startsWith('$dir/')) continue;\n final relative = file.substring(dir.length + 1);\n final prefix = _packageRelativePaths[i];\n return prefix.isEmpty ? relative : '$prefix/$relative';\n }\n return null;\n}\n\nfinal RegExp _windowsDrive = RegExp(r'^file:///([A-Za-z]):');\n\n/// [fileUri] decoded, with a Windows drive letter in lower case.\nString _comparableFileUri(String fileUri) =>\n _withDriveLetterCase(Uri.decodeFull(fileUri), upper: false);\n\n/// [fileUri] with its Windows drive letter, if it has one, in one case.\nString _withDriveLetterCase(String fileUri, {required bool upper}) {\n final RegExpMatch? drive = _windowsDrive.firstMatch(fileUri);\n if (drive == null) return fileUri;\n final String letter = drive.group(1)!;\n final String casedLetter = upper ? letter.toUpperCase() : letter.toLowerCase();\n return 'file:///' + casedLetter + ':' + fileUri.substring(drive.end);\n}\n\nString _layerIdOf(Element element) {\n final int id = _layerIds[element] ??= ++_lastLayerId;\n return id.toString();\n}\n\nMap<String, Object?> _nodeFor(\n String id,\n String? parent,\n Element element,\n _AppLocation location,\n bool ancestorsPaint,\n Rect? measured,\n Rect? clip,\n) {\n final RenderObject? renderObject = element.renderObject;\n // A box its parent does not paint (a kept-alive page scrolled out of its\n // list) has a zero paint transform, which maps to NaN; NaN would also\n // make jsonEncode throw.\n final bool finite = measured != null && measured.isFinite;\n // What the clips above leave of it: a list row laid out in the cache\n // extent below a viewport is not on screen and must not take presses\n // meant for what is painted there (a bottom navigation bar).\n final Rect? visible = finite ? _clippedTo(measured, clip) : null;\n final Rect rect = visible ?? Rect.zero;\n final bool hidden = _hidesBuiltChild(element.widget) ||\n (renderObject != null && _paintsNothing(renderObject));\n return <String, Object?>{\n 'id': id,\n 'parent': parent,\n 'name': element.widget.runtimeType.toString(),\n 'file': location.file,\n 'line': location.line,\n 'column': location.column,\n 'x': rect.left,\n 'y': rect.top,\n 'width': rect.width,\n 'height': rect.height,\n 'painted': visible != null && ancestorsPaint && !hidden,\n };\n}\n\n/// [clipAbove] narrowed by the clip [renderObject]'s parent paints it under\n/// (describeApproximatePaintClip: a viewport, a ClipRect, an overflowing\n/// Flex or Stack), in view coordinates. One call per render object; a\n/// transform only where the parent clips.\nRect? _clipUnderParent(\n RenderObject renderObject,\n Rect? clipAbove,\n _ViewTransforms transforms,\n) {\n final RenderObject? parent = renderObject.parent;\n // The parents' clips read the child's layout (a viewport reads the\n // sliver's constraints), which a child never laid out does not have.\n if (parent == null || !_isLaidOut(renderObject)) return clipAbove;\n final Rect? local = parent.describeApproximatePaintClip(renderObject);\n if (local == null) return clipAbove;\n final Rect inView = MatrixUtils.transformRect(transforms.of(parent), local);\n return clipAbove == null ? inView : clipAbove.intersect(inView);\n}\n\n/// Each render object's transform to its view, the value of\n/// getTransformTo(null), for one walk. getTransformTo multiplies the whole\n/// chain from the object up to the view, so asking it for every node cost\n/// O(nodes × depth): two thirds of a 27 ms walk on a 572-node screen in a\n/// debug web build. A transform is its parent's followed by the parent's\n/// paint transform for it, so here each object on the way is computed once.\n/// Layout cannot change during a walk, so neither can a transform.\nclass _ViewTransforms {\n final Map<RenderObject, Matrix4> _byObject =\n Map<RenderObject, Matrix4>.identity();\n\n Matrix4 of(RenderObject renderObject) {\n final Matrix4? known = _byObject[renderObject];\n if (known != null) return known;\n final RenderObject? parent = renderObject.parent;\n final Matrix4 transform;\n // Like getTransformTo(null), stop below the root (the view's\n // RenderView): its own transform is the device pixel ratio, and view\n // coordinates are logical pixels.\n if (parent == null || parent.parent == null) {\n transform = Matrix4.identity();\n } else {\n transform = of(parent).clone();\n parent.applyPaintTransform(renderObject, transform);\n }\n _byObject[renderObject] = transform;\n return transform;\n }\n}\n\nbool _isLaidOut(RenderObject renderObject) {\n if (renderObject is RenderBox) return renderObject.hasSize;\n if (renderObject is RenderSliver) return renderObject.geometry != null;\n return true;\n}\n\n/// [rect] cut to [clip] (null: nothing clips), or null when nothing of it is\n/// left on screen. A rect with no area (a SizedBox spacer) keeps its place\n/// while it lies within the clip.\nRect? _clippedTo(Rect rect, Rect? clip) {\n if (clip == null) return rect;\n final Rect inside = rect.intersect(clip);\n final bool outside = inside.width < 0 || inside.height < 0;\n final bool lostItsArea = !rect.isEmpty && inside.isEmpty;\n if (outside || lostItsArea) return null;\n return inside;\n}\n\n/// The rect [renderObject] paints, as axis-aligned bounds in the view's\n/// logical pixels (CSS pixels relative to the view's host element), or null\n/// when it has nothing of its own to paint: detached, a box never laid out,\n/// or a sliver with no extent in its viewport.\nRect? _paintedRectInView(\n RenderObject? renderObject,\n _ViewTransforms transforms,\n) {\n if (renderObject == null || !renderObject.attached) return null;\n final Rect? bounds = _ownPaintBounds(renderObject);\n if (bounds == null) return null;\n return MatrixUtils.transformRect(transforms.of(renderObject), bounds);\n}\n\n/// [renderObject]'s own paint bounds, in its coordinates. A sliver's is its\n/// crossAxisExtent × paintExtent along its axis (RenderSliver.paintBounds),\n/// and the viewport's paint transform places it, paintOrigin included. The\n/// sliver's box ancestor (the viewport) is the wrong stand-in: every sliver\n/// would cover the whole viewport, and a later one would win every press.\nRect? _ownPaintBounds(RenderObject renderObject) {\n if (renderObject is RenderBox) {\n return renderObject.hasSize ? Offset.zero & renderObject.size : null;\n }\n if (renderObject is RenderSliver) {\n final SliverGeometry? geometry = renderObject.geometry;\n final bool paintsInViewport =\n geometry != null && geometry.visible && geometry.paintExtent > 0;\n return paintsInViewport ? renderObject.paintBounds : null;\n }\n return null;\n}\n\n/// Whether [renderObject] and its subtree paint nothing: it hides its own\n/// subtree, or its parent skips it (paintsChild false: an Offstage's or\n/// transparent Opacity's child, a kept-alive child scrolled out of a list or\n/// page view).\nbool _paintsNothing(RenderObject renderObject) {\n if (_hidesSubtree(renderObject)) return true;\n final RenderObject? parent = renderObject.parent;\n if (parent == null) return false;\n // RenderIndexedStack paints only the child at index, but does not say so\n // through paintsChild (Flutter 3.47).\n if (parent is RenderIndexedStack) {\n return !identical(_shownIndexedStackChild(parent), renderObject);\n }\n return !parent.paintsChild(renderObject);\n}\n\n/// Whether [renderObject] paints none of its subtree: offstage, opacity 0,\n/// or a sliver its viewport does not paint (scrolled out, or not laid out).\nbool _hidesSubtree(RenderObject renderObject) {\n if (renderObject is RenderOffstage) return renderObject.offstage;\n if (renderObject is RenderSliverOffstage) return renderObject.offstage;\n if (renderObject is RenderOpacity) return renderObject.opacity == 0;\n if (renderObject is RenderSliverOpacity) return renderObject.opacity == 0;\n if (renderObject is RenderAnimatedOpacityMixin<RenderObject>) {\n return renderObject.opacity.value == 0;\n }\n if (renderObject is RenderSliver) {\n final SliverGeometry? geometry = renderObject.geometry;\n return geometry == null || !geometry.visible;\n }\n return false;\n}\n\n/// The child a RenderIndexedStack paints, or null when its index is null.\nRenderBox? _shownIndexedStackChild(RenderIndexedStack stack) {\n final int? index = stack.index;\n if (index == null) return null;\n RenderBox? child = stack.firstChild;\n for (int position = 0; position < index && child != null; position += 1) {\n child = stack.childAfter(child);\n }\n return child;\n}\n\n/// A hidden Visibility that keeps its child built (maintainState) paints none\n/// of it. With maintainSize it hides through a private render object that\n/// skips painting (Visibility.maintain included), so only the widget tells;\n/// without it the child sits in an Offstage. Without maintainState the child\n/// is not built and the replacement shows, so nothing is hidden.\nbool _hidesBuiltChild(Widget widget) {\n if (widget is Visibility) return !widget.visible && widget.maintainState;\n if (widget is SliverVisibility) return !widget.visible && widget.maintainState;\n return false;\n}\n`}var Ei=`<!DOCTYPE html>\n\x3c!-- ${ai} --\x3e\n\x3c!-- Generated by Tempo. The canvas host page loads flutter_bootstrap.js\n itself and adds one Flutter view per storyboard; this page only exists\n because flutter run requires it. --\x3e\n<html>\n<head>\n <meta charset="UTF-8">\n <title>Tempo Flutter host</title>\n</head>\n<body>\n <script src="flutter_bootstrap.js" async><\/script>\n</body>\n</html>\n`,Ti=`// ${ai}\n{{flutter_js}}\n{{flutter_build_config}}\n{\n const reportBootFailure = (err) => window.dispatchEvent(new CustomEvent("tempo-flutter-error", { detail: { message: String(err?.message ?? err) } }));\n _flutter.loader.load({\n config: { entrypointBaseUrl: "${ii}", canvasKitBaseUrl: "${ii}canvaskit/" },\n onEntrypointLoaded: (init) => (async () => {\n const engine = await init.initializeEngine({ multiViewEnabled: true, assetBase: "${ii}" });\n const app = await engine.runApp();\n window.__tempoFlutterApp = { app, generation: (window.__tempoFlutterApp?.generation ?? 0) + 1 };\n window.dispatchEvent(new CustomEvent("tempo-flutter-app", { detail: window.__tempoFlutterApp }));\n })().catch(reportBootFailure),\n }).catch(reportBootFailure);\n}\n`;function stableDescriptor(e){return null===e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?`[${e.map(stableDescriptor).join(",")}]`:`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${stableDescriptor(t)}`).join(",")}}`}async function scanFlutterBoards(e,t){const n=[];for(const r of await scanCanvasFiles(e)){const e=r,s=await Br(e,"utf8").catch(()=>"");if(!s.includes("FlutterStoryboard"))continue;let i;try{i=parseCanvasFile(e,s)}catch{continue}for(const r of i.storyboards){if(void 0===r.preview)continue;const s=parseFlutterPreview(r.preview);let i=null;if(!("error"in s))try{i=flutterPreviewKey(t,Ur.resolve(Ur.dirname(canonicalPathAllowMissing(e)),s.file),s.functionName)}catch{}n.push({canvasFile:e,storyboardId:r.storyboardKey,preview:r.preview,key:i})}}return n}async function resolveFlutterPreviews(e,t,n){const r=new Map,s=new Map,i=[],a=canonicalPathAllowMissing(t);let o;for(const t of e){const problem=(e,n)=>i.push({...t,code:e,message:n}),e=parseFlutterPreview(t.preview);if("error"in e){let r=e.error;if(/^lib\/[^#?]+\.dart#[A-Za-z$][A-Za-z0-9_$]*$/.test(t.preview)){const[e,s]=t.preview.split("#"),i=await(o??=findFlutterPackages(a)),c=await Promise.all(i.map(async t=>(await Hr(Ur.join(t.dir,e)).catch(()=>null))?.isFile()?Ur.join(t.dir,e):null)),l=c.filter(e=>null!==e);1===l.length&&(r+=` For example, ${JSON.stringify(flutterPreviewForCanvas(flutterPreviewKey(n,l[0],s),t.canvasFile,n))}.`)}problem("flutter_preview_invalid",r);continue}const c=Ur.resolve(Ur.dirname(canonicalPathAllowMissing(t.canvasFile)),e.file);let l;try{l=canonicalPathAllowMissing(c)}catch{problem("flutter_preview_file_missing",`${e.file} is missing or inaccessible.`);continue}if(!pathInside(a,c)||!pathInside(a,l)){problem("flutter_preview_outside_project",`${e.file} points outside this project.`);continue}const d=Ur.relative(a,l).split(Ur.sep).join("/");if(!(await Hr(l).catch(()=>null))?.isFile()){problem("flutter_preview_file_missing",`${d} does not exist.`);continue}let u,p=Ur.dirname(l);for(;pathInside(a,p)&&!(await Hr(Ur.join(p,"pubspec.yaml")).catch(()=>null))?.isFile();){const e=Ur.dirname(p);if(e===p)break;p=e}if(!pathInside(a,p)){problem("flutter_package_missing",`No pubspec.yaml above ${d} inside the project.`);continue}try{let e=s.get(p);e||(e=(async()=>{const e=Ur.join(p,"pubspec.yaml"),t=await Br(e,"utf8"),n=parseFlutterAppPubspec(t,e);if(!readPubspecFacts(t)?.dependsOnFlutter)throw new Error(`${e} must depend on flutter: { sdk: flutter }.`);return{dir:p,name:n.packageName,discovery:await discoverPreviews(p,n.packageName)}})(),s.set(p,e)),u=await e}catch(e){problem("flutter_package_invalid",e instanceof Error?e.message:String(e));continue}if(!pathInside(Ur.join(p,"lib"),l)){problem("flutter_preview_outside_lib",`${d} must be inside its package's lib/ directory.`);continue}const h=Ur.relative(p,l).split(Ur.sep).join("/");if(!u.discovery.previews.some(t=>t.file===h&&t.name===e.functionName)){const t=u.discovery.previews.filter(e=>e.file===h).map(e=>e.name);problem("flutter_preview_not_found",`${d} has no public top-level @Preview function ${e.functionName}. Available: ${t.join(", ")||"none"}.`);continue}t.key=flutterPreviewKey(n,l,e.functionName),r.set(p,u)}return{boards:e,packages:[...r.values()].sort((e,t)=>e.dir.localeCompare(t.dir)),problems:i}}var wi="latest";function isPinnedTempoSdkSpec(e){return/^(workspace:|file:|link:|portal:|git|https?:|ssh:|github:)/.test(e)}function managedTempoSdkSpec(e){return isPinnedTempoSdkSpec(e)?e:wi}function missingInstallEnvironment(e){const t=e instanceof Error?e.message:String(e);return/(?:^|[\s/"'])(?:docker|pnpm|yarn|bun)(?:["'])?: (?:command )?not found\b/im.test(t)||/['"](?:docker|pnpm|yarn|bun)['"] is not recognized as an internal or external command/i.test(t)||/cannot connect to the docker daemon/i.test(t)||/is the docker daemon running\?/i.test(t)}import{readFile as Si}from"fs/promises";import bi from"path";import{parseEnv as Ai}from"util";async function readOptional(e){try{return await Si(e,"utf-8")}catch(e){const t=e.code;if("ENOENT"===t||"ENOTDIR"===t)return"";throw e}}async function readInstallRegistryEnv(e,t,n){const r=bi.resolve(t),s=bi.resolve(e),i=bi.relative(r,s);if(".."===i||i.startsWith(`..${bi.sep}`)||bi.isAbsolute(i))return{};const a=[r];if(i)for(const e of i.split(bi.sep))a.push(bi.join(a[a.length-1],e));const o=await Promise.all(a.map(e=>readOptional(bi.join(e,".npmrc")))),c=new Set;for(const e of o)for(const t of e.split(/\r?\n/))if(!/^\s*[#;]/.test(t))for(const e of t.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g))c.add(e[1]);if(0===c.size)return{};let l={};if([...c].some(e=>void 0===n[e])){const e=await Promise.all(a.flatMap(e=>[".env",".env.local"].map(t=>readOptional(bi.join(e,t)))));for(const t of e)l={...l,...Ai(t)}}return Object.fromEntries([...c].flatMap(e=>{const t=n[e]??l[e];return void 0===t?[]:[[e,t]]}))}var _i=p(Pe(),1);import{readFile as ki}from"fs/promises";import Ii from"os";import Ci from"path";var Ri="npm_config_registry",Pi="pnpm_config_registry",Ni="npm_config_cache_dir",Oi="pnpm_config_cache_dir",Di="pnpm_config_minimum_release_age_exclude";async function readPackageManagerConfigEnv(e,t){const n={},r=findEnvKey(t,Ri),s=findEnvKey(t,Pi);r&&!s&&(n[Pi]=t[r]),s&&!r&&(n[Ri]=t[s]);const i=t.TEMPO_E2E_PNPM_CACHE_DIR;i&&(n[findEnvKey(t,Ni)??Ni]=i,n[findEnvKey(t,Oi)??Oi]=i);const a=new Set([...envReleaseAgeExclusions(t),...await workspaceReleaseAgeExclusions(e),...await globalReleaseAgeExclusions(t),"tempo-sdk"]),o=findEnvKey(t,Di)??Di;return n[o]=JSON.stringify([...a]),n}function findEnvKey(e,t){return Object.keys(e).find(n=>n.toLowerCase()===t&&void 0!==e[n])??null}function envReleaseAgeExclusions(e){const t=findEnvKey(e,Di),n=t?e[t]?.trim():"";if(!n)return[];try{const e=JSON.parse(n);if(Array.isArray(e))return e.map(String)}catch{}return n.split(",").map(e=>e.trim()).filter(Boolean)}async function workspaceReleaseAgeExclusions(e){let t=Ci.resolve(e);for(;;){const e=await readOptional2(Ci.join(t,"pnpm-workspace.yaml"));if(null!==e)return releaseAgeExclusionsIn(e);const n=Ci.dirname(t);if(n===t)return[];t=n}}async function globalReleaseAgeExclusions(e){const t=e.XDG_CONFIG_HOME?Ci.join(e.XDG_CONFIG_HOME,"pnpm"):"darwin"===process.platform?Ci.join(Ii.homedir(),"Library/Preferences/pnpm"):"win32"===process.platform&&e.LOCALAPPDATA?Ci.join(e.LOCALAPPDATA,"pnpm/config"):Ci.join(Ii.homedir(),".config/pnpm"),n=await readOptional2(Ci.join(t,"config.yaml"));return null===n?[]:releaseAgeExclusionsIn(n)}function releaseAgeExclusionsIn(e){try{const t=(0,_i.parse)(e)?.minimumReleaseAgeExclude;return Array.isArray(t)?t.map(String):[]}catch{return[]}}async function readOptional2(e){try{return await ki(e,"utf-8")}catch{return null}}import{spawn as Li}from"child_process";import{createHash as Mi,randomUUID as xi}from"crypto";import Fi from"fs";import{access as Bi,mkdir as Hi,mkdtemp as Ui,readdir as ji,readFile as $i,rm as Gi,stat as qi,writeFile as Wi}from"fs/promises";import{request as Vi}from"http";import{createServer as Ki,connect as Yi}from"net";import zi from"os";import Ji from"path";function abortableWait(e){const error=()=>{const t=new Error(e);return t.name="AbortError",t},throwIfAborted=e=>{if(e?.aborted)throw error()},sleep4=(e,t)=>(throwIfAborted(t),new Promise((n,r)=>{const s=setTimeout(()=>{t?.removeEventListener("abort",onAbort),n()},e),onAbort=()=>{clearTimeout(s),r(error())};t?.addEventListener("abort",onAbort,{once:!0}),t?.aborted&&onAbort()})),race=(e,t)=>(throwIfAborted(t),t?new Promise((n,r)=>{const onAbort=()=>r(error()),cleanup=()=>t.removeEventListener("abort",onAbort);t.addEventListener("abort",onAbort,{once:!0}),e.then(e=>{cleanup(),n(e)},e=>{cleanup(),r(e)}),t.aborted&&onAbort()}):e);return{error,throwIfAborted,sleep:sleep4,race}}var Qi=Symbol.for("@modules/file-watcher:watch-provider");function getSlot(){const e=globalThis;return e[Qi]??={provider:null},e[Qi]}function getInstalledWatchProvider(){return getSlot().provider}import Xi from"picomatch";function asSubtreePath(e){const t=e.endsWith("/**")?e.slice(0,-3):e.endsWith("/")?e.slice(0,-1):e;return 0===t.length||Xi.scan(t).isGlob?null:t}function splitIgnorePatterns(e){const t=[],n=[];for(const r of e){const e=asSubtreePath(r);null!==e?t.push(e):n.push(Xi.makeRe(r,{dot:!0}))}return{nativeIgnorePaths:t,relativePathFilters:n}}function createEventKeepFilter(e,t){return 0===t.length?()=>!0:n=>{let r=n.startsWith(e)?n.slice(e.length):n;"win32"===process.platform&&(r=r.replaceAll("\\","/")),r.startsWith("/")&&(r=r.slice(1));for(const e of t)if(e.test(r))return!1;return!0}}import{lstat as Zi,readdir as ea,readFile as ta,writeFile as na}from"fs/promises";import{isAbsolute as ra,join as sa,resolve as ia}from"path";var aa=32,oa=64;function resolveIgnoreRoots(e,t){const n=new Set;for(const r of t)r&&n.add(ra(r)?ia(r):ia(e,r));return n}async function scanTree(e,t=[],n=()=>!0){const r=resolveIgnoreRoots(e,t),s=new Map,i=[],a=[{dir:e,depth:0}];for(let e=a.pop();void 0!==e;e=a.pop()){const{dir:t,depth:o}=e;let c;try{c=await ea(t,{withFileTypes:!0})}catch{continue}for(const e of c){const c=sa(t,e.name);!r.has(c)&&n(c)&&(e.isDirectory()&&!n(`${c}/`)||(e.isDirectory()&&!e.isSymbolicLink()?(s.set(c,{mtimeMs:0,size:0,isDir:!0}),o<oa&&a.push({dir:c,depth:o+1})):i.push(c)))}}for(let e=0;e<i.length;e+=aa){const t=i.slice(e,e+aa);await Promise.all(t.map(async e=>{try{const t=await Zi(e);s.set(e,{mtimeMs:t.mtimeMs,size:t.size,isDir:!1})}catch{}}))}return s}function diffScans(e,t){const n=[];for(const[r,s]of t){const t=e.get(r);t?s.isDir||t.mtimeMs===s.mtimeMs&&t.size===s.size||n.push({path:r,type:"update"}):n.push({path:r,type:"create"})}for(const r of e.keys())t.has(r)||n.push({path:r,type:"delete"});return n}async function writeScanSnapshot(e,t){const n={version:1,entries:[...t].map(([e,t])=>[e,t.mtimeMs,t.size,t.isDir?1:0])};await na(e,JSON.stringify(n))}async function readScanSnapshot(e){try{const t=JSON.parse(await ta(e,"utf8"));if(1!==t?.version||!Array.isArray(t.entries))return null;const n=new Map;for(const[e,r,s,i]of t.entries)n.set(e,{mtimeMs:r,size:s,isDir:1===i});return n}catch{return null}}function deliver(e,t){return e.delivery=e.delivery.then(async()=>{e.active&&await e.onScan(t)}).catch(t=>{try{e.onError(t instanceof Error?t:new Error(String(t)))}catch{}}),e.delivery}function unchanged(e,t){if(!e||e.size!==t.size)return!1;for(const[n,r]of t){const t=e.get(n);if(!t||t.isDir!==r.isDir||!r.isDir&&(t.mtimeMs!==r.mtimeMs||t.size!==r.size))return!1}return!0}function createPollingScanPool(e=scanTree){const t=new Map;let n=Promise.resolve();async function subscribe(r,s,i){const a=[...new Set(s.filter(e=>!splitIgnorePatterns([e]).relativePathFilters.length||e.endsWith("/**")||e.endsWith("/")))].sort(),o=JSON.stringify([r,a]);let c=t.get(o);c||(c={root:r,readers:new Set,timer:null,running:null,baseline:null,scanCount:0,lastDurationMs:0,lastCompletedAt:0,unchangedScans:0},t.set(o,c));const l=c,d={...i,active:!0,delivery:Promise.resolve()};l.readers.add(d);const{nativeIgnorePaths:u,relativePathFilters:p}=splitIgnorePatterns(a),h=createEventKeepFilter(r,p);function schedule(){if(l.timer&&clearTimeout(l.timer),l.timer=null,!l.readers.size||l.running)return;const e=Math.min(...[...l.readers].map(e=>Math.min(e.interval*2**l.unchangedScans,Math.max(e.interval,e.maxIdleInterval??e.interval)))),t=Math.max(0,e-(performance.now()-l.lastCompletedAt));l.timer=setTimeout(()=>{l.timer=null,run().catch(()=>{})},t)}function run(){if(l.running)return l.running;const t=n.then(async()=>{if(!l.readers.size)return;const t=performance.now(),n=await e(r,u,h);l.lastDurationMs=performance.now()-t,l.scanCount++,l.unchangedScans=unchanged(l.baseline,n)?Math.min(30,l.unchangedScans+1):0,l.baseline=n,await Promise.all([...l.readers].map(e=>deliver(e,n)))});return n=t.catch(()=>{}),l.running=t.catch(e=>{l.unchangedScans=0;for(const t of l.readers)try{t.onError(e instanceof Error?e:new Error(String(e)))}catch{}throw e}).finally(()=>{l.running=null,l.lastCompletedAt=performance.now(),schedule()}),l.running}try{l.baseline?(await deliver(d,l.baseline),schedule()):await run()}catch(e){throw d.active=!1,l.readers.delete(d),l.readers.size||(l.timer&&clearTimeout(l.timer),t.get(o)===l&&t.delete(o)),e}return{async unsubscribe(){d.active=!1,l.readers.delete(d),await d.delivery,l.readers.size?schedule():(l.timer&&clearTimeout(l.timer),l.timer=null,t.get(o)===l&&t.delete(o),await(l.running?.catch(()=>{})))}}}return{subscribe,getDiagnostics:()=>[...t.values()].map(e=>({root:e.root,consumers:e.readers.size,entries:e.baseline?.size??0,scanCount:e.scanCount,lastDurationMs:e.lastDurationMs,scanning:null!==e.running}))}}var ca=createPollingScanPool();import{lstat as la,realpath as da,stat as ua}from"fs/promises";import{createRequire as pa}from"module";import{relative as ha}from"path";var ma=100,fa=1e3,ga=3e4,ya=500,va=5e3,Ea=10,Ta=100,wa=50,Sa=pa("undefined"!=typeof __filename?__filename:import.meta.url),ba=null;function loadNativeWatcher(){return ba??=Promise.resolve().then(()=>{const e=Sa("@parcel/watcher");return e.default??e}),ba}async function watch(e,t,n={}){const r=getInstalledWatchProvider();return r?r.watch(e,t,n):watchLocal(e,t,n)}async function watchLocal(e,t,n={}){const{backend:r="native"}=n;if("polling"===r)return watchWithPolling(e,t,n);const s=await loadNativeWatcher(),{ignore:i=[],debounceMs:a=ma,maxBatchSize:o=fa,coalesce:c=!0,onError:l=e=>{console.error("[file-watcher] Error:",e.message)},autoRecover:d=!1,snapshotPath:u,resumeFromSnapshot:p}=n,h=u??(d?`/tmp/file-watcher-snapshot-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`:void 0),m=await resolveRootPath(e),{nativeIgnorePaths:f,relativePathFilters:g}=splitIgnorePatterns(i),y=createEventKeepFilter(m.realPath,g);let v=[],E=null,T=!1,w=null,S=0;const b=new Set;function trackNativeOp(e){b.add(e);const forget=()=>{b.delete(e)};return e.then(forget,forget),e}async function drainNativeOps(){for(;b.size>0;)await Promise.allSettled([...b])}function scheduleFlush(){E||T||(E=setTimeout(()=>{E=null,flush().catch(e=>{l(e instanceof Error?e:new Error(String(e)))})},a))}async function flush(){if(T)return;if(0===v.length)return;const e=v.splice(0,o),n=await Promise.all(e.map(e=>parcelEventToFileEvent(e,m)));if(T)return;const r=c?dedupeEvents(n):n;r.length>0&&t(r),v.length>0&&!T&&scheduleFlush()}async function flushAll(){for(E&&(clearTimeout(E),E=null);v.length>0&&!T;)await flush()}async function handleErrorWithRecovery(e){if(T)return;const t=w;if(w=null,t)try{await trackNativeOp(t.unsubscribe())}catch{}if(!T)if(S++,S>wa)l(new Error(`Too many recovery restarts (${wa}), giving up`));else{if(h)try{await trackNativeOp(s.writeSnapshot(m.realPath,h))}catch(e){l(new Error(`Snapshot failed during recovery: ${e instanceof Error?e.message:String(e)}`))}await flushAll(),await new Promise(e=>setTimeout(e,Ta)),T||(console.log(`[file-watcher] Restarting after ${e} (attempt ${S}/${wa})...`),await subscribe(h))}}async function subscribe(e){if(!T){if(e)try{const t=(await trackNativeOp(s.getEventsSince(m.realPath,e,{ignore:f}))).filter(e=>y(e.path));t.length>0&&(v.push(...t),scheduleFlush())}catch(e){l(new Error(`Recovery from snapshot failed: ${e instanceof Error?e.message:String(e)}`))}try{const e=await trackNativeOp(s.subscribe(m.realPath,(e,t)=>{if(T)return;if(e){const t=e.message?.includes("Interrupted system call");return d?void handleErrorWithRecovery(t?"EINTR":"error"):void l(e)}S=0;const n=t.filter(e=>y(e.path));if(0===n.length)return;const r=ga-v.length;if(r<=0)return d?void handleErrorWithRecovery("buffer overflow"):void l(new Error("Event buffer full, dropping events"));if(n.length>r){if(d)return void handleErrorWithRecovery("buffer overflow");l(new Error("Event buffer full, dropping events"))}v.push(...n.slice(0,r)),scheduleFlush()},{ignore:f}));if(T)return void await trackNativeOp(e.unsubscribe()).catch(()=>{});w=e}catch(e){T||l(e instanceof Error?e:new Error(String(e)))}}}return await subscribe(p),{async unsubscribe(){T=!0,E&&(clearTimeout(E),E=null),v=[];const e=w;w=null,e&&await trackNativeOp(e.unsubscribe()),await drainNativeOps()}}}async function watchWithPolling(e,t,n){const{ignore:r=[],debounceMs:s=ma,maxBatchSize:i=fa,coalesce:a=!0,onError:o=e=>{console.error("[file-watcher] Error:",e.message)},snapshotPath:c,resumeFromSnapshot:l,pollingIntervalMs:d=ya}=n,u=await resolveRootPath(e),{relativePathFilters:p}=splitIgnorePatterns(r),h=createEventKeepFilter(u.realPath,p),m=Math.max(Ea,d),f=c??l;let g=null,y=!1;l&&(g=await readScanSnapshot(l),g||o(new Error(`Resume snapshot missing or unreadable: ${l}`)));let v=[],E=null,T=!1;function scheduleFlush(){E||T||(E=setTimeout(()=>{E=null,flush().catch(e=>{o(e instanceof Error?e:new Error(String(e)))})},s))}async function flush(){if(T)return;if(0===v.length)return;const e=v.splice(0,i),n=await Promise.all(e.map(e=>parcelEventToFileEvent(e,u)));if(T)return;const r=a?dedupeEvents(n):n;r.length>0&&t(r),v.length>0&&!T&&scheduleFlush()}const w=await ca.subscribe(u.realPath,r,{interval:m,maxIdleInterval:void 0===n.pollingIntervalMs?va:m,onError:o,async onScan(e){if(T)return;const t=g;g=e;const n=t?diffScans(t,e):[];if(y||=!t||n.length>0,f&&y&&await writeScanSnapshot(f,e).then(()=>{y=!1},()=>{}),T||!t)return;const r=n.filter(e=>h(e.path));if(!r.length)return;const s=ga-v.length;r.length>s&&o(new Error("Event buffer full, dropping events")),v.push(...r.slice(0,Math.max(0,s))),scheduleFlush()}});return{async unsubscribe(){T=!0,E&&(clearTimeout(E),E=null),await w.unsubscribe(),v=[]}}}function dedupeEvents(e){const t=new Map;for(const n of e){const e=t.get(n.path);if(!e){const e="create"!==n.type;t.set(n.path,{existedBefore:e,current:n});continue}const r="delete"!==n.type;if(!e.existedBefore&&!r){t.delete(n.path);continue}let s;s=!e.existedBefore&&r?"create":e.existedBefore&&!r?"delete":"update",t.set(n.path,{existedBefore:e.existedBefore,current:{...n,type:s}})}return Array.from(t.values()).map(e=>e.current)}async function resolveRootPath(e){try{const t=await la(e),n=t.isSymbolicLink(),r=await da(e);return{originalPath:e,realPath:r,isSymlink:n}}catch{return{originalPath:e,realPath:e,isSymlink:!1}}}async function getFileKind(e){try{const t=await ua(e);return t.isDirectory()?"directory":t.isFile()?"file":"unknown"}catch{return"unknown"}}async function parcelEventToFileEvent(e,t){let n=e.path;"darwin"===process.platform&&(n=n.normalize("NFC"));const r="delete"===e.type?"unknown":await getFileKind(n),s=ha(t.realPath,n);let i;if(t.isSymlink){const e=t.originalPath+n.slice(t.realPath.length);i={path:e,relativePath:ha(t.originalPath,e)}}return{type:e.type,kind:r,path:n,relativePath:s,symlink:i}}function createReconciliationQueue(e,t={}){const n=t.now??Date.now,r=t.minIntervalMs??5e3;let s=0,i=0,a=!1,o=!1,c=0,l=Number.NEGATIVE_INFINITY,d=null;function schedule(){if(o||a||null!==d||i===s)return;const e=l-n();e<=0?run():d=setTimeout(()=>{d=null,run()},e)}async function run(){if(o||a)return;a=!0;const d=s;l=n()+r;try{await e(),o||(i=d),c=0}catch(e){const r=[5e3,15e3,6e4];l=n()+r[Math.min(c++,r.length-1)];try{t.onError?.(e)}catch{}}finally{a=!1,schedule()}}return{invalidate(){o||(s++,schedule())},dispose(){o=!0,null!==d&&clearTimeout(d),d=null},getDiagnostics:()=>({dirtyRevision:s,completedRevision:i,running:a,failures:c,pending:!o&&s!==i})}}import{mkdir as Aa,readFile as _a,rename as ka,writeFile as Ia}from"fs/promises";import{execFile as Ca,spawn as Ra,spawnSync as Pa}from"child_process";import Na from"net";import Oa from"path";import{promisify as Da}from"util";import{spawn as La}from"child_process";import Ma from"path";var xa="TEMPO_NODE_TOOLCHAIN_BIN_DIR",Fa="TEMPO_NODE_TOOLCHAIN_RUNTIME";function getBundledNodeBinDir(){const e=process.env[xa];return e&&e.trim().length>0?e:null}var Ba=!1;function isBundledNodeActivated(){return Ba}function setBundledNodeActivated(e){Ba=Ba||e}function shouldUseBundledNode(e){return null==e.systemNodeVersion||!(!e.requireFloor||e.floorOk)}function applyBundledNodeEnv(e,t){if(!t)return e;const n=prependDirToPathEnv(e,t);return"native"===e[Fa]?delete n.ELECTRON_RUN_AS_NODE:n.ELECTRON_RUN_AS_NODE="1",n}function prependDirToPathEnv(e,t){const n=Object.keys(e).find(e=>"path"===e.toLowerCase()),r=n?e[n]:e.PATH,s=[t,r].filter(e=>Boolean(e)).join(Ma.delimiter);return{...e,[n??"PATH"]:s}}function removeDirFromPathEnv(e,t,n=Ma.delimiter){const r=Object.keys(e).find(e=>"path"===e.toLowerCase()),s=r?e[r]:e.PATH;if(!s)return e;const i=s.split(n).filter(e=>e&&e!==t).join(n);return i===s?e:{...e,[r??"PATH"]:i}}function probeNodeVersion(e){return new Promise(t=>{const n=La('node -p "process.versions.node"',{shell:!0,stdio:["ignore","pipe","ignore"],windowsHide:!0,env:e});let r="";n.stdout?.on("data",e=>{r+=String(e)}),n.on("error",()=>t(null)),n.on("close",e=>{t(0===e&&r.trim()||null)})})}import{appendFileSync as Ha,mkdirSync as Ua,renameSync as ja,statSync as $a,unlinkSync as Ga}from"fs";import{homedir as qa}from"os";import{dirname as Wa,join as Va}from"path";var Ka,Ya=1048576,za=Va(qa(),"tempo-devserver-debug.log"),Ja=Ya,Qa=!1;function ensureInitialized(){if(!Qa){Qa=!0;try{Ua(Wa(za),{recursive:!0})}catch{}}}function rotateIfNeeded(){let e;try{e=$a(za).size}catch{return}if(e<Ja)return;const t=`${za}.1`;try{Ga(t)}catch{}try{ja(za,t)}catch{try{Ga(za)}catch{}}}function devLog(e,t){try{Ka?.(e,t)}catch{}let n;ensureInitialized();try{n=`${JSON.stringify({ts:(new Date).toISOString(),kind:e,...void 0!==t?{d:t}:{}})}\n`}catch{n=`${JSON.stringify({ts:(new Date).toISOString(),kind:e})}\n`}try{rotateIfNeeded(),Ha(za,n)}catch{}}function devTimer(e,t){const n=Date.now();return devLog(`${e}:start`,t),{done(t){const r=Date.now()-n;devLog(`${e}:done`,{elapsedMs:r,...t??{}})}}}var Xa=9e5,Za=/\x1b\[[0-9;]*m/g,eo=/another next dev server is already running/i,to=/another nuxt dev(?: server)? is already running/i,no=/(?:taskkill[ \t]+\/PID[ \t]+|PID[ \t]*:[ \t]*|\(PID[ \t]+)(\d+)/i,ro=/(?:Local|URL)[ \t]*:[ \t]*https?:\/\/[^\s/]+:(\d+)/i;function findLockConflictSignature(e){const t=e.search(eo);if(t>=0)return{framework:"next",index:t};const n=e.search(to);return n>=0?{framework:"nuxt",index:n}:null}function parseDevServerLockConflict(e){if(!e)return null;const t=e.replace(Za,""),n=findLockConflictSignature(t);if(!n)return null;const r=t.slice(n.index),s=r.match(no);if(!s)return null;const i=Number(s[1]);if(!Number.isInteger(i)||i<=1||i===process.pid)return null;const a=r.match(ro),o=a?Number(a[1]):null;return{framework:n.framework,pid:i,port:null!=o&&Number.isInteger(o)&&o>0&&o<65536?o:null}}function devServerLockConflictFramework(e){return e?findLockConflictSignature(e.replace(Za,""))?.framework??null:null}function splitOutputAtDevServerLockConflict(e){const t=e.replace(Za,""),n=findLockConflictSignature(t);return n?{ownOutput:t.slice(0,n.index),conflictStarted:!0}:{ownOutput:t,conflictStarted:!1}}function isShellParseAbortOutput(e){return/\bwas unexpected at this time\b/i.test(e)||/is not a valid statement separator/i.test(e)}var so=[{construct:"the `Test-Path` cmdlet",pattern:/\bTest-Path\b/i},{construct:"a parenthesised condition with a `{ … }` block",pattern:/\b(?:if|foreach|while)\s*\([^)]*\)\s*\{/i},{construct:"a brace-form `else` block",pattern:/\}\s*else\b|\belse\s*\{/i},{construct:"a PowerShell variable (`$env:`/`$PSItem`/`$_`)",pattern:/\$(?:env:|PSItem\b|_\b)/i},{construct:"a PowerShell cmdlet (Verb-Noun form like `Get-ChildItem`)",pattern:/\b(?:Get|Set|New|Remove|Copy|Move|Rename|Start|Stop|Invoke|Write|Read|Out|Select|Where|ForEach|Import|Export|Add|Clear)-[A-Z][A-Za-z]+\b/}];function stripQuotedSpans(e){let t="",n=null;for(let r=0;r<e.length;r+=1){const s=e[r];if('"'!==n)"'"!==n?"\\"!==s?'"'!==s&&"'"!==s?t+=s:(n=s,t+=" "):(t+=" ",r+=1):"'"===s&&(n=null);else{if("\\"===s){r+=1;continue}'"'===s&&(n=null)}}return t}function findPowerShellSyntax(e){const t=stripQuotedSpans(e);for(const e of so)if(e.pattern.test(t))return e.construct;return null}function describePowerShellRejection(e){return`Tempo rejected it before running anything: the command contains PowerShell-only syntax (${e}), which the shell Tempo spawns commands with (cmd.exe on Windows) cannot parse.`}function extractLeadingEnvAssignments(e){const t={};let n=e;const r=/^([A-Za-z_][A-Za-z0-9_]*)=([^\s"'`$\\]*)\s+(?=\S)/;for(;;){const e=r.exec(n);if(!e)break;t[e[1]]=e[2],n=n.slice(e[0].length)}return 0===Object.keys(t).length?{command:e,env:t}:{command:n,env:t}}function classifyDevServerOutput(e){const t=matchClass(e);return t?{class:t.class,hint:t.hint,...t.errorCode?{errorCode:t.errorCode}:{},...t.metadata?{metadata:t.metadata}:{},line:e.trim().slice(0,500),observedAt:Date.now()}:null}function matchMissingTempoSdkImport(e){const t=e.match(/The requested module 'file:[^']*\/tempo-sdk\/[^']*' does not provide an export named '([^']+)'/);if(t)return`export \`${t[1]}\``;const n=e.match(/Missing "\.\/([^"]+)" specifier in "tempo-sdk" package/)??e.match(/Package subpath '\.\/([^']+)' is not defined by "exports" in .*[\\/]tempo-sdk[\\/]package\.json/);return n?`entry \`tempo-sdk/${n[1]}\``:null}function installedPackageRoot(e){const t=e.replace(/\\/g,"/"),n="/node_modules/",r=t.lastIndexOf(n);if(r<0)return null;const s=t.slice(r+n.length).split("/"),i=s[0]?.startsWith("@")?s.slice(0,2):s.slice(0,1);return 0===i.length||i.some(e=>!e)?null:`${t.slice(0,r+n.length)}${i.join("/")}`}function isPackageMissingItsOwnFile(e){const t=e.match(/Cannot find (?:module|package) ['"]((?:\/|[A-Za-z]:[\\/])[^'"]+)['"]/);if(!t)return!1;const n=e.match(/imported from ((?:\/|[A-Za-z]:[\\/])[^\s'"]+)/)?.[1]??e.match(/Require stack:\s*\n\s*-\s*(\S+)/)?.[1];if(!n)return!1;const r=installedPackageRoot(t[1]);return null!==r&&r===installedPackageRoot(n)}function createDevServerOutputClassifier(){let e="",t=null,n=!1;return r=>{const s=r.replace(/\x1b\[[0-9;]*m/g,""),i=(e+s).split(/\r?\n/);e=(i.pop()??"").slice(-2e3);let a=classifyDevServerOutput(s);for(const e of i){const r=e.match(/^\s*[⨯✘×]\s+(.+?\.css:\d+(?::\d+)?)/);if(r?(t=r[1].slice(0,250),n=!1):(/^\s*[⨯✘×]\s+/.test(e)||/(?:✓.*Compiled|GET\s+\/tempo-host\S*\s+200\b)/.test(e))&&(t=null,n=!1),/Parsing CSS source code failed/.test(e)&&(n=!0),n&&/@import rules must precede|Can't resolve|Cannot resolve|Unexpected token|Unknown word/.test(e)){const n=[t,e.trim().slice(0,250)].filter(Boolean).join(" — ");a={class:"compile-error",hint:`The stylesheet failed to compile: ${n}`,line:n,observedAt:Date.now()}}}return a}}function buildHostUnresponsiveHint(e,t,n=Date.now()){const r=Math.max(0,Math.round((n-t)/1e3));return{class:"host-unresponsive",hint:`The canvas dev server is running but has stopped answering requests at ${e} (no response for ${r}s). It may be wedged after a dependency change or an interrupted install; retrying restarts it.`,errorCode:"not_reachable",line:`url health probe failed: ${e}`,observedAt:n}}function matchClass(e){if(isShellParseAbortOutput(e))return{class:"shell-dialect-mismatch",hint:"The dev command failed to PARSE in the shell (Tempo runs commands through cmd.exe on Windows) — nothing actually ran. This almost always means the command was written in PowerShell syntax, which cmd.exe cannot parse: `if (...) { ... } else { ... }`, `Test-Path`, `$env:FOO`. Rewrite it as a single, plain, cross-platform invocation with no shell conditionals — e.g. `npm exec next dev -p ${APP_PORT}` or simply `npm run dev` when it does not need Tempo's optional allocated helper port (legacy `${PORT}` also works). Chaining with `&&` is fine; cmd supports it. If the app lives in a subdirectory, set `appDir` in tempo.config.json instead of `cd`/`pushd`-ing inside the command."};const t=devServerLockConflictFramework(e);if(t){const n=parseDevServerLockConflict(e);return{class:"dev-lock-conflict",hint:describeDevLockConflict(t,n?.pid??null),...n?{metadata:{lockHolderPid:n.pid,...null!=n.port?{lockHolderPort:n.port}:{}}}:{}}}if(/EADDRINUSE|address already in use/i.test(e))return{class:"port-in-use",hint:"Another process is holding the dev server's port. Tempo will retry standard Vite/Next starts on a free local port; custom start scripts may need their port changed."};if(/(?:'|")nuxt(?:'|") is not recognized as an internal or external command|command not found:\s*nuxt\b|\bnuxt: (?:command )?not found/i.test(e))return{class:"tool-missing",hint:"The `nuxt` command was not found. Tempo's Nuxt sidecar runs the app's own Nuxt from the project root's node_modules, so install the app's dependencies at the project root, then retry the canvas."};if(/\bspawn EBADF\b/.test(e))return{class:"dev-server-fork-failed",hint:"The dev server could not fork its worker process (spawn EBADF). If this is a Nuxt 3 app, its CLI does this when it runs without a terminal: add `--no-fork` to the `nuxt dev` command (rerunning canvas_project_init rewrites the Tempo sidecar's `dev` script for Nuxt 3). Otherwise check that the dev command does not depend on an interactive terminal."};if(/\bNUXT_B8006\b|No Nuxt version could be found from/.test(e))return{class:"tool-missing",hint:"Nuxt could not be found from the Tempo sidecar (tempo/). Do not install nuxt into tempo/: install the app's own dependencies, then rerun canvas_project_init, which links tempo/ to the app's nuxt and vue (pnpm, or npm when tempo/ is outside the app's install), and retry the canvas. A sidecar that yarn or bun installs cannot reach a Nuxt app in a subfolder with its own install."};const n=matchMissingTempoSdkImport(e);if(n)return{class:"tempo-sdk-outdated",hint:`The canvas host's tempo-sdk is older than this Tempo: it has no ${n}, which the host config imports. Run start_canvas_devserver({ update_sdk: true }) to upgrade tempo-sdk to latest and restart the canvas host. Custom environments must provide the private runtime in their own launch environment.`,errorCode:"canvas_host_sdk_incompatible",metadata:{missingTempoSdkImport:n}};if(/tempo-sdk\/nuxt/.test(e)&&/Cannot find (?:module|package) ['"]@nuxt\/kit['"]/.test(e))return{class:"module-not-found",hint:"The Tempo sidecar's tempo-sdk is older than the one whose Nuxt module imports nuxt/kit, so it looks for @nuxt/kit in tempo/node_modules, where none is installed. Update tempo-sdk in tempo/package.json to the newest version and reinstall with start_canvas_devserver({ force_install: true })."};if(/tempo-sdk\/nuxt/.test(e)&&/could not (?:be )?load|error (?:occurred )?while importing/i.test(e))return{class:"module-not-found",hint:"The Nuxt sidecar could not load the Tempo Nuxt module (tempo-sdk/nuxt). Reinstall the canvas dependencies so tempo/node_modules has a tempo-sdk that ships it, then retry the canvas."};if(/(?:'|")?flutter(?:\.bat)?(?:'|")? is not recognized as an internal or external command|command not found:\s*flutter\b|\bflutter: (?:command )?not found/i.test(e))return{class:"tool-missing",hint:"The Flutter SDK was not found. Install Flutter and put `flutter` on PATH, or set TEMPO_FLUTTER_BIN to the flutter executable, then restart the canvas.",errorCode:"flutter_sdk_missing"};if(/(?:'|")?(?:npm|pnpm|yarn|bun)(?:'|")? is not recognized as an internal or external command|command not found:\s*(?:npm|pnpm|yarn|bun)|(?:npm|pnpm|yarn|bun): command not found/i.test(e))return{class:"tool-missing",hint:"The package manager required by this project was not found on PATH. Install it or enable it with Corepack, then retry the canvas."};if(isUnsupportedHostNodeOutput(e))return{class:"node-version-unsupported",hint:"The dev server is using an unsupported Node.js version. Install the version required by Vite/Next/Nuxt or update PATH so Tempo resolves it.",errorCode:"node_version_unsupported"};if(isPackageMissingItsOwnFile(e))return{class:"installed-packages-changed",hint:"The canvas server's installed packages changed while it was running (a reinstall or cleanup removed files it had loaded), and it can't recover on its own. Retry restarts it."};const r=e.match(/Missing\s+["'](\.\/[^"']+)["']\s+specifier\s+in\s+["']([^"']+)["']/i);if(r){const[,e,t]=r,n=`${t}${e.slice(1)}`;return{class:"package-subpath-export-missing",hint:`Vite could not resolve package subpath ${n}. Fix the import path or the package export map; this is a package export issue, not a local install strategy issue.`}}if(/ERESOLVE|unable to resolve dependency tree|could not resolve dependency/i.test(e))return{class:"dependency-conflict",hint:"Package installation hit a dependency resolution conflict. Tempo avoids strict CI installs locally; if this persists, package.json or the lockfile needs a targeted dependency fix."};if(/(?:EPERM|EACCES).*?(?:unlink|rename|rmdir).*?(?:node_modules|\.node|lightningcss|esbuild|swc)|operation not permitted.*?(?:node_modules|\.node|lightningcss|esbuild|swc)/i.test(e))return{class:"native-binary-locked",hint:"A native dependency binary in node_modules is locked by another process. Close running dev servers/editors using it and retry; Tempo will avoid unnecessary root reinstalls."};if(/ERR_PNPM_OUTDATED_LOCKFILE|ERR_PNPM_FROZEN_LOCKFILE_WITH_OUTDATED_LOCKFILE|YN0028|package-lock\.json.*out of sync|npm ci.*(?:in sync|can only install)|lockfile would have been modified|cannot install with.*frozen-lockfile/i.test(e))return{class:"lockfile-install-strict",hint:"A strict CI-style install failed because the lockfile is stale. Tempo local canvas startup should use non-destructive install commands instead."};const s=e.match(/(?:Failed to resolve import|Module not found:?\s+(?:Can't resolve|Error:?\s+Can't resolve))\s+["']?([^"'\s\n]+)/i);if(s){const t=s[1],n=classifySourceImportSpecifier(t);if(n){const r=extractImporterFromLine(e);return{class:"source-import-unresolved",hint:`Unresolved source import: ${t}${r?` from ${r}`:""}. This is not an npm package; fix the import path, restore the missing source file, or update the canvas wrapper to import an existing file.`,metadata:{importSpecifier:t,importer:r,importKind:n}}}return isTailwindDependency(t)?{class:"module-not-found",hint:`Tailwind dependency missing: ${t}. Run install from Tempo or reinstall project dependencies, then retry the canvas.`}:{class:"module-not-found",hint:`Missing dependency: ${t}. Install it at the project root (e.g. \`bun install\`, \`pnpm install\`, \`npm install\`) or add it to package.json and retry.`}}return/tailwind\.config\.(?:js|ts|cjs|mjs)/i.test(e)&&/(?:changed|updated|reloaded|invalidat)/i.test(e)?{class:"tailwind-config-change",hint:"tailwind.config.* changed. Class autocomplete and color picker may show stale results until the dev server is restarted."}:/(?:Cannot apply unknown utility class|class [`"'][^`"']+[`"'] does not exist|Unknown utility class)/i.test(e)?{class:"tailwind-css-error",hint:"Tailwind CSS could not resolve a utility from global CSS. Tempo checks the app's global CSS, tailwind.config.*, and Tailwind source paths during setup; restart the canvas after repair or inspect the CSS error line."}:/No utility classes were detected in your source files/i.test(e)?{class:"tailwind-source-missing",hint:"Tailwind did not find any source files to scan. Tempo's setup should write @source entries for src/app/components/packages and canvas files; restart the canvas so the repaired stylesheet is used."}:/Failed to load font|downloadable font|OTS parsing error|(?:font|woff2?|ttf|otf).*ERR_/i.test(e)?{class:"font-load-failure",hint:"Font failed to load. Check the font URL/path and CORS headers; Tempo allows stylesheet and font CORS in the projection, but missing files or blocked remote font hosts still need app-side fixes."}:/Syntax\s*Error|SyntaxError:|Unexpected token/i.test(e)?{class:"syntax-error",hint:"A source file has a syntax error. Check the dev server output (or the error overlay on the affected storyboard) for the file and position."}:/JavaScript heap out of memory|FATAL ERROR.*Allocation failed|ENOMEM/i.test(e)?{class:"out-of-memory",hint:"The dev server ran out of memory. Bump NODE_OPTIONS=--max-old-space-size=8192 or reduce the repo's scanned scope (tsconfig include paths)."}:/EACCES|EPERM|permission denied/i.test(e)?{class:"permission-denied",hint:"A file or port required by the dev server is not accessible to this process. Check ownership of node_modules and the dev server's port."}:/ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY/.test(e)?{class:"pnpm-needs-ci",hint:"pnpm refused to manipulate node_modules without a TTY. Tempo normally sets CI=1 — if you see this, the env was wiped. File a bug."}:/^\s*(?:error\s|Error:\s+Parsing CSS source code failed|[✘❌✗⨯]\s)/i.test(e)&&e.length>20?{class:"compile-error",hint:"The dev server reported a compile error. Open the affected storyboard to see the error overlay, or check the terminal for the full stack."}:null}function describeDevLockConflict(e,t){const n=null===t?"":` (PID ${t})`;return"nuxt"===e?`Another Nuxt dev server${n} is already running in this folder and holds Nuxt's dev lock, so this one refused to start. Close the other Tempo window or terminal running \`nuxt dev\` here, then retry.`:null===t?"Another dev server is already running in this project's canvas folder and is holding Next.js's dev lock. Tempo is retrying; if the canvas doesn't come up, close other windows or terminals running this project.":`Another dev server${n} is already running in this project's canvas folder and is holding Next.js's dev lock. Tempo will retry in an isolated build directory; if the canvas doesn't come up, close the other window or terminal running this project.`}var io=[/You are using Node\.js .*Vite requires Node\.js version/i,/requires Node\.js version/i,/Unsupported engine/i,/crypto\.hash is not a function/i,/(?:node|node\.exe): (?:command not found|not found)/i,/['"]node['"] is not recognized as an internal or external command/i,/spawn node ENOENT/i,/\/usr\/bin\/env:\s*['"]?node['"]?:\s*No such file or directory/i];function isViteRuntimeFrame(e){return/[\\/]node_modules[\\/]vite[\\/]|[\\/]vite[\\/]dist[\\/]node/i.test(e)}function isUnsupportedHostNodeOutput(e){if(io.some(t=>t.test(e)))return!0;const t=e.split(/\r?\n/);return!!t.some((e,n)=>/ERR_REQUIRE_ESM/i.test(e)&&[e,...t.slice(n+1,n+4)].some(isViteRuntimeFrame))||t.some((e,n)=>/^\s*SyntaxError:\s*Unexpected (?:token|reserved word)/i.test(e)&&/\?\?=|\?\.|&&=|\|\|=|Unexpected reserved word/i.test(e)&&t.slice(n+1,n+4).some(isViteRuntimeFrame))}function isTailwindDependency(e){return"tailwindcss"===e||e.startsWith("@tailwindcss/")}function classifySourceImportSpecifier(e){return e.startsWith("@/")||e.startsWith("~/")?"source-alias":e.startsWith("./")||e.startsWith("../")?"relative":e.startsWith("/")?"absolute":null}function extractImporterFromLine(e){const t=/\sfrom\s+["']([^"']+)["']/i.exec(e);if(t?.[1])return normalizeImporterPath(t[1]);const n=/(?:^|\n|[\s([])(\.{0,2}\/[^:\n]+?\.(?:[cm]?[jt]sx?|css|scss|sass|less|mdx?)):\d+:\d+/i.exec(e);return n?.[1]?normalizeImporterPath(n[1]):null}function normalizeImporterPath(e){return e.replace(/^\.\//,"")}import{execFile as ao}from"child_process";import{promisify as oo}from"util";var co=oo(ao);function parseNetstatListenerPid(e,t){if(!e)return null;for(const n of e.split(/\r?\n/)){const e=n.trim().split(/\s+/);if(5!==e.length)continue;if("TCP"!==e[0].toUpperCase())continue;const r=e[1];if(!r.endsWith(`:${t}`))continue;const s=Number(e[4]);if(!Number.isInteger(s)||s<=0)continue;const i=e[3].toUpperCase(),a=e[2],o="LISTENING"===i||"0.0.0.0:0"===a||"[::]:0"===a||"*:*"===a;if(o)return s}return null}function parseLsofListenerPid(e){if(!e)return null;for(const t of e.split(/\r?\n/)){const e=Number(t.trim());if(Number.isInteger(e)&&e>0)return e}return null}async function findPortListenerPid(e){try{if("win32"===process.platform){const{stdout:t}=await co("netstat",["-ano"],{windowsHide:!0,maxBuffer:4194304});return parseNetstatListenerPid(t,e)}const{stdout:t}=await co("lsof",["-nP","-t",`-iTCP:${e}`,"-sTCP:LISTEN"],{windowsHide:!0});return parseLsofListenerPid(t)}catch{return null}}import{appendFile as lo,mkdir as uo,open as po,rename as ho,rm as mo,stat as fo,writeFile as go}from"fs/promises";import{dirname as yo}from"path";var vo=class{constructor({filePath:e,maxBytesPerFile:t}){if(this.pending=[],this.pendingAppendBytes=0,this.draining=!1,this.currentSizeBytes=null,!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytesPerFile must be a positive safe integer");this.filePath=e,this.priorFilePath=`${e}.1`,this.maxBytesPerFile=t}append(e){const t=Buffer.from(e);if(0===t.length)return;t.length>this.maxBytesPerFile&&this.pending.push({kind:"dropped",bytes:t.length-this.maxBytesPerFile});const n=t.length>this.maxBytesPerFile?t.subarray(t.length-this.maxBytesPerFile):t;this.pending.push({kind:"append",data:n}),this.pendingAppendBytes+=n.length,this.trimPendingAppends(),this.startDrain()}reset(){return new Promise(e=>{this.pending.push({kind:"reset",done:e}),this.startDrain()})}flush(){return new Promise(e=>{this.pending.push({kind:"flush",done:e}),this.startDrain()})}readTail(e){return new Promise(t=>{this.pending.push({kind:"read",tailBytes:e,done:t}),this.startDrain()})}trimPendingAppends(){for(;this.pendingAppendBytes>this.maxBytesPerFile;){const e=this.pending.findIndex(e=>"append"===e.kind);if(-1===e)return;const[t]=this.pending.splice(e,1);if("append"===t.kind){this.pendingAppendBytes-=t.data.length;const n=this.pending[e-1];"dropped"===n?.kind?n.bytes+=t.data.length:this.pending.splice(e,0,{kind:"dropped",bytes:t.data.length})}}}startDrain(){this.draining||(this.draining=!0,this.drain())}async drain(){try{for(;this.pending.length>0;){const e=this.pending.shift();"append"===e.kind?(this.pendingAppendBytes-=e.data.length,await this.appendNow(e.data)):"dropped"===e.kind?await this.appendNow(Buffer.from(`\n[Tempo output journal dropped ${e.bytes} bytes to stay memory-bounded]\n`)):"reset"===e.kind?(await this.resetNow(),e.done()):"flush"===e.kind?e.done():e.done(await readRotatingLogTail(this.filePath,e.tailBytes))}}finally{this.draining=!1,this.pending.length>0&&this.startDrain()}}async appendNow(e){try{const t=e.length>this.maxBytesPerFile?e.subarray(e.length-this.maxBytesPerFile):e;if(await this.initializeCurrentSize(),this.currentSizeBytes+t.length>this.maxBytesPerFile&&!await this.rotateNow())return;await lo(this.filePath,t),this.currentSizeBytes=(this.currentSizeBytes??0)+t.length}catch{this.currentSizeBytes=null}}async initializeCurrentSize(){if(null===this.currentSizeBytes){await uo(yo(this.filePath),{recursive:!0});try{const e=await fo(this.filePath);if(e.size<=this.maxBytesPerFile)return void(this.currentSizeBytes=e.size);const t=await readFileTail(this.filePath,this.maxBytesPerFile);await go(this.filePath,t),this.currentSizeBytes=t.length}catch(e){if(isNodeError(e)&&"ENOENT"===e.code)return void(this.currentSizeBytes=0);throw e}}}async rotateNow(){try{await mo(this.priorFilePath,{force:!0})}catch{}try{return await ho(this.filePath,this.priorFilePath),this.currentSizeBytes=0,!0}catch{try{return await mo(this.filePath,{force:!0}),this.currentSizeBytes=0,!0}catch{return this.currentSizeBytes=null,!1}}}async resetNow(){try{await uo(yo(this.filePath),{recursive:!0})}catch{}const[e]=await Promise.allSettled([mo(this.filePath,{force:!0}),mo(this.priorFilePath,{force:!0})]);this.currentSizeBytes="fulfilled"===e.status?0:null}};async function readRotatingLogTail(e,t){try{return await readRotatingLogTailOnce(e,t)}catch{try{return await readRotatingLogTailOnce(e,t)}catch{return{content:null,totalSizeBytes:null,updatedAt:null}}}}async function readRotatingLogTailOnce(e,t){const n=Number.isFinite(t)?Math.max(0,Math.floor(t)):Number.MAX_SAFE_INTEGER,r=[`${e}.1`,e],s=[];for(const e of r)try{const t=await fo(e);t.isFile()&&s.push({path:e,size:t.size,mtimeMs:t.mtimeMs})}catch{}if(0===s.length)return{content:null,totalSizeBytes:null,updatedAt:null};let i=Math.min(n,s.reduce((e,t)=>e+t.size,0));const a=[];for(const e of[...s].reverse()){if(0===i)break;const t=Math.min(i,e.size);a.unshift(await readFileTail(e.path,t)),i-=t}return{content:Buffer.concat(a).toString("utf-8"),totalSizeBytes:s.reduce((e,t)=>e+t.size,0),updatedAt:Math.max(...s.map(e=>e.mtimeMs))}}async function readFileTail(e,t){if(t<=0)return Buffer.alloc(0);const n=await fo(e),r=Math.min(t,n.size),s=Buffer.alloc(r),i=await po(e,"r");try{return await i.read(s,0,r,n.size-r),s}finally{await i.close()}}function isNodeError(e){return e instanceof Error&&"code"in e}var Eo="devserver-watchdog.cjs",To='// Generated by Tempo — do not edit.\n// Ties the canvas devserver\'s lifetime to the Tempo app: the app holds this\n// process\'s stdin open; when the app dies (cleanly or not) the OS closes the\n// pipe, and the watchdog kills the devserver tree so no orphan is left\n// holding Next.js\'s per-directory dev lock.\n"use strict";\nconst { spawn, spawnSync } = require("node:child_process");\n\nconst command = process.argv[2];\nif (!command) {\n process.stderr.write("devserver-watchdog: missing command argument\\n");\n process.exit(64);\n}\n\nconst childEnv = { ...process.env };\nconst childRunAsNode = childEnv.TEMPO_WATCHDOG_CHILD_ELECTRON_RUN_AS_NODE;\ndelete childEnv.TEMPO_WATCHDOG_CHILD_ELECTRON_RUN_AS_NODE;\nif (childRunAsNode === "__TEMPO_UNSET__") {\n delete childEnv.ELECTRON_RUN_AS_NODE;\n} else if (childRunAsNode !== undefined) {\n childEnv.ELECTRON_RUN_AS_NODE = childRunAsNode;\n}\n\nconst child = spawn(command, {\n shell: true,\n detached: process.platform !== "win32",\n windowsHide: true,\n stdio: ["ignore", "inherit", "inherit"],\n env: childEnv,\n});\n\n// Tell the supervisor which process is the real managed process-group root.\n// The watchdog itself is only a lifetime relay; persisting its pid would make\n// the next app instance unable to prove that the port listener belongs to the\n// tree Tempo launched. IPC is intentionally optional so the generated script\n// remains independently runnable in focused watchdog tests.\nif (typeof process.send === "function") {\n process.send({ type: "tempo-watchdog-child", pid: child.pid ?? null });\n}\n\nlet killed = false;\nfunction killTree() {\n if (killed || child.pid == null) return;\n killed = true;\n if (process.platform === "win32") {\n spawnSync("taskkill", ["/pid", String(child.pid), "/t", "/f"], {\n stdio: "ignore",\n windowsHide: true,\n });\n } else {\n try { process.kill(-child.pid, "SIGKILL"); } catch {}\n try { process.kill(child.pid, "SIGKILL"); } catch {}\n }\n}\n\nchild.on("exit", (code) => {\n // Forward the devserver\'s exit code verbatim (full DWORD range on\n // Windows) so the supervisor\'s crash classification sees the real code.\n process.exit(code === null ? 1 : code);\n});\n\n// The death signal: stdin EOF means the Tempo app is gone.\nprocess.stdin.resume();\nconst onParentGone = () => {\n killTree();\n process.exit(0);\n};\nprocess.stdin.on("end", onParentGone);\nprocess.stdin.on("close", onParentGone);\nprocess.stdin.on("error", onParentGone);\n\n// Graceful teardown paths (the supervisor\'s stop / signal flows) must also\n// take the tree down, not just the watchdog.\nfor (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {\n process.on(signal, onParentGone);\n}\n';import{spawn as wo}from"child_process";function appendTail(e,t,n){return`${e}${String(t)}`.slice(-n)}function runAbortableShellCommand(e){const t=e.maxOutputBytes??4e3;return e.signal?.aborted?Promise.resolve({exitCode:null,stdout:"",stderr:"",output:"",aborted:!0,timedOut:!1,spawnError:null}):new Promise(n=>{let r,s,i="",a="",o="",c=!1,l=!1,d=!1,u=!0,p=null,h=null;try{s=wo(e.command,{cwd:e.cwd,shell:!0,detached:"win32"!==process.platform,stdio:["ignore","pipe","pipe"],windowsHide:!0,env:e.env})}catch(e){return void n({exitCode:null,stdout:i,stderr:a,output:o,aborted:!1,timedOut:!1,spawnError:e instanceof Error?e:new Error(String(e))})}let m=null;const finishIfComplete=()=>{!d&&void 0!==r&&u&&(d=!0,p&&clearTimeout(p),h&&clearTimeout(h),e.signal?.removeEventListener("abort",onAbort),n({exitCode:r,stdout:i,stderr:a,output:o,aborted:c,timedOut:l,spawnError:m}))},terminateTree=e=>{if(c||l||void 0!==r)return;c="abort"===e,l="timeout"===e,h&&clearTimeout(h),u=!1;const t=s.pid;if(null==t||"win32"===process.platform)if(null!=t){const e=wo("taskkill",["/PID",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0});e.on("error",()=>{try{s.kill("SIGKILL")}catch{}u=!0,finishIfComplete()}),e.on("close",()=>{u=!0,finishIfComplete()})}else{try{s.kill("SIGKILL")}catch{}u=!0}else{try{process.kill(-t,"SIGTERM")}catch{try{s.kill("SIGTERM")}catch{}}p=setTimeout(()=>{try{process.kill(-t,"SIGKILL")}catch{try{s.kill("SIGKILL")}catch{}}u=!0,finishIfComplete()},1e3)}},onAbort=()=>terminateTree("abort");e.signal?.addEventListener("abort",onAbort,{once:!0}),e.signal?.aborted&&onAbort();const resetIdleTimer=()=>{h&&clearTimeout(h),c||l||void 0!==r||!e.idleTimeoutMs||(h=setTimeout(()=>terminateTree("timeout"),e.idleTimeoutMs))},forwardOutput=n=>{if(!d&&0!==String(n).length){o=appendTail(o,n,t),resetIdleTimer();try{e.onOutput?.(String(n))}catch{}}};resetIdleTimer(),s.stdout?.on("data",e=>{i=appendTail(i,e,t),forwardOutput(e)}),s.stderr?.on("data",e=>{a=appendTail(a,e,t),forwardOutput(e)}),s.on("error",e=>{m=e}),s.on("close",e=>{h&&clearTimeout(h),r=e,finishIfComplete()})})}var So=/\x1b\[[0-9;]*m/g;async function resolveHttpUrlSource(e){if("string"==typeof e.source)return e.substitutePort(e.source,e.port);const t=new AbortController,onAbort=()=>t.abort();e.signal?.addEventListener("abort",onAbort,{once:!0});const n=setTimeout(()=>t.abort(),e.timeoutMs);let r;try{r=await runAbortableShellCommand({command:e.substitutePort(e.source.command,e.port),cwd:e.cwd,env:e.env,signal:t.signal,maxOutputBytes:4e3})}finally{clearTimeout(n),e.signal?.removeEventListener("abort",onAbort)}if(r.aborted){if(e.signal?.aborted)throw new Error(`${e.label}.command was aborted`);throw new Error(`${e.label}.command timed out after ${e.timeoutMs}ms`)}if(r.spawnError)throw new Error(`${e.label}.command could not start: ${r.spawnError.message}`);if(0!==r.exitCode){const t=r.stderr.trim();throw new Error(`${e.label}.command exited with code ${r.exitCode??"unknown"}${t?`: ${t}`:""}`)}const s=r.stdout.replace(So,"").trim();let i;try{i=new URL(s)}catch{throw invalidOutputError(e.label)}if("http:"!==i.protocol&&"https:"!==i.protocol||s.includes("\n")||s.includes("\r"))throw invalidOutputError(e.label);return s}function invalidOutputError(e){return new Error(`${e}.command must print exactly one valid HTTP(S) URL to stdout`)}import{existsSync as bo}from"fs";import Ao from"path";var _o="nuxt-vite-node-XXXXXX/nuxt-vite-node-4194304-1792620713060.sock",ko=["nuxt.config.ts","nuxt.config.js","nuxt.config.mjs","nuxt.config.cjs"];function nuxtSocketTmpdirEnv(e=process.env,t=process.platform){if("win32"===t)return{};const n="linux"===t?108:104,r=e.TMPDIR||e.TMP||e.TEMP||"/tmp",s=Ao.posix.join(r,_o);return Buffer.byteLength(s)<=n?{}:{TMPDIR:"/tmp"}}function isNuxtAppStart(e,t){return!!/\bnux[ti]\b/.test(e)||ko.some(e=>bo(Ao.join(t,e)))}import{cp as Io,lstat as Co,mkdtemp as Ro,rename as Po,mkdir as No,readFile as Oo,readdir as Do,realpath as Lo,rm as Mo,symlink as xo,writeFile as Fo}from"fs/promises";import Bo from"path";import{createHash as Ho}from"crypto";var Uo="TEMPO_MONOREPO_SDK_SOURCE",jo="local-tempo-sdk.json",$o=new Map;function tempoSdkDevCommandEnv(){return"local-prebuilt"===process.env[Uo]?{pnpm_config_verify_deps_before_run:"false"}:{}}async function hasTempoSdkDevSource(e){return null!==await realpathIfPresent(Bo.join(e,".tempo",jo))}async function realpathIfPresent(e){try{return await Lo(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return null;throw e}}async function isTempoSdkRoot(e){try{const t=JSON.parse(await Oo(Bo.join(e,"package.json"),"utf8"));return"tempo-sdk"===t.name}catch{return!1}}async function discoverLocalSdkRoot(e){for(let t=Bo.resolve(e);;t=Bo.dirname(t)){const e=Bo.join(t,"tempo-modules","tempo-sdk");if(await isTempoSdkRoot(e))return e;if(Bo.dirname(t)===t)return null}}async function assertLocalSdkPrebuilt(e){const t=["dist/index.js","dist/canvas/index.js"],n=(await Promise.all(t.map(async t=>({relativePath:t,present:null!==await realpathIfPresent(Bo.join(e,t))})))).filter(({present:e})=>!e).map(({relativePath:e})=>e);if(0!==n.length)throw new Error(`Local prebuilt tempo-sdk is missing ${n.join(", ")} under ${e}. Build tempo-sdk before starting the Canvas host.`)}var Go=".tempo-prebuilt-source.json";async function snapshotRevision(e,t,n){const r=Ho("sha256").update(t);async function visit(t){for(const n of(await Do(t,{withFileTypes:!0})).sort((e,t)=>e.name.localeCompare(t.name))){const s=Bo.join(t,n.name);r.update(Bo.relative(e,s)),n.isDirectory()?await visit(s):r.update(await Oo(s))}}for(const t of n){const n=Bo.join(e,t);r.update(t),(await Co(n)).isDirectory()?await visit(n):r.update(await Oo(n))}return r.digest("hex")}async function materializeSdk(e,t){const n=await Oo(Bo.join(e,"package.json"),"utf8"),r=JSON.parse(n),s=r.files??["dist"];if(s.some(e=>Bo.isAbsolute(e)||e.split(/[\\/]/).includes("..")||/[*?{}[\]!]/.test(e)))throw new Error("Local tempo-sdk package.json files must be literal paths inside the SDK checkout.");const i={};for(const t of Object.keys({...r.dependencies,...r.optionalDependencies}).sort()){const n=await realpathIfPresent(Bo.join(e,"node_modules",t));if(n)i[t]=n;else if(!(t in(r.optionalDependencies??{})))throw new Error(`Local tempo-sdk dependency ${t} is missing. Install dependencies in the Tempo checkout before launching it.`)}const a=JSON.stringify({format:2,localSdkRoot:e,revision:await snapshotRevision(e,n,s),dependencies:i}),o=await Co(t).catch(()=>null);if(!o?.isSymbolicLink()&&await Oo(Bo.join(t,Go),"utf8").catch(()=>null)===a){const e=await Promise.all(Object.entries(i).map(async([e,n])=>await realpathIfPresent(Bo.join(t,"node_modules",e))===n));if(e.every(Boolean))return}await No(Bo.dirname(t),{recursive:!0});const c=await Ro(Bo.join(Bo.dirname(t),".tempo-sdk-"));try{for(const t of s)await No(Bo.dirname(Bo.join(c,t)),{recursive:!0}),await Io(Bo.join(e,t),Bo.join(c,t),{recursive:!0});await Fo(Bo.join(c,"package.json"),n);for(const[e,t]of Object.entries(i)){const n=Bo.join(c,"node_modules",e);await No(Bo.dirname(n),{recursive:!0}),await xo(t,n,"win32"===process.platform?"junction":"dir")}await Fo(Bo.join(c,Go),a),await Mo(t,{force:!0,recursive:!0}),await Po(c,t)}finally{await Mo(c,{force:!0,recursive:!0})}}async function sdkBuildFingerprint(e){const t=Ho("sha256").update("snapshot-format-2"),n=await Oo(Bo.join(e,"package.json"),"utf8");t.update(n);const r=JSON.parse(n);for(const n of Object.keys({...r.dependencies,...r.optionalDependencies}).sort())t.update(n).update("\0"),t.update(await realpathIfPresent(Bo.join(e,"node_modules",n))??"missing").update("\0");async function visit(n){const r=await Do(Bo.join(e,n),{withFileTypes:!0});r.sort((e,t)=>e.name.localeCompare(t.name));for(const s of r){const r=Bo.join(n,s.name);s.isDirectory()?await visit(r):s.isFile()&&!/\.(?:map|d\.[cm]?ts)$/.test(s.name)&&(t.update(r).update("\0"),t.update(await Oo(Bo.join(e,r))).update("\0"))}}return await visit("dist"),t.digest("hex")}async function invalidateSdkPrebundle(e){await Mo(Bo.join(e,"node_modules",".vite"),{recursive:!0,force:!0})}async function prepareTempoSdkDevSource(e,t={}){const n=Bo.resolve(e),r=($o.get(n)??Promise.resolve()).catch(()=>{}).then(()=>prepareTempoSdkDevSourceOnce(n,t));$o.set(n,r);try{return await r}finally{$o.get(n)===r&&$o.delete(n)}}async function prepareTempoSdkDevSourceOnce(e,t){const n=process.env[Uo];if("local"===n)throw new Error(`${Uo}=local is no longer supported because Canvas host startup must not rebuild the SDK used by the running renderer. Build it before Electron starts and use local-prebuilt.`);const r=t.mode??("local-prebuilt"===n?n:"published"),s=Bo.join(e,"node_modules","tempo-sdk"),i=Bo.join(e,".tempo",jo),a=await Oo(i,"utf8").then(e=>JSON.parse(e)).catch(()=>null);if("local-prebuilt"===r){const n=t.localSdkRoot??await discoverLocalSdkRoot(t.discoveryStart??process.cwd());if(!n||!await isTempoSdkRoot(n))throw new Error(`Local tempo-sdk development is enabled via ${Uo}=local-prebuilt, but tempo-modules/tempo-sdk could not be found from the Tempo client checkout.`);await assertLocalSdkPrebuilt(n);const r=await Lo(n),o=await sdkBuildFingerprint(n),c=await Oo(Bo.join(s,Go),"utf8").catch(()=>null);return c&&a?.localSdkRoot===r&&a?.buildFingerprint===o||await invalidateSdkPrebundle(e),await materializeSdk(r,s),await No(Bo.dirname(i),{recursive:!0}),await Fo(i,`${JSON.stringify({localSdkRoot:r,buildFingerprint:o},null,2)}\n`),{source:"local",localSdkRoot:r}}if(!a)return{source:"published",removedLocalLink:!1};let o=!1;if("string"==typeof a.localSdkRoot){const[e,t]=await Promise.all([realpathIfPresent(s),realpathIfPresent(a.localSdkRoot)]),n=await Co(s).catch(()=>null);(null!==await Oo(Bo.join(s,Go),"utf8").catch(()=>null)||e===t||null===e&&n?.isSymbolicLink())&&(await Mo(s,{force:!0,recursive:!0}),o=!0)}return await invalidateSdkPrebundle(e),await Mo(i,{force:!0}),{source:"published",removedLocalLink:o}}var qo="app-devserver.json",Wo="app-devserver.log",Vo=4194304,Ko={min:4e4,max:6e4},Yo=3e4,zo=18e4,Jo=5e3,Qo=6e5,Xo="127.0.0.1",Zo=7,ec=/\x1b\[[0-9;]*m/g,tc=/https?:\/\/[^\s"'`<>]+/gi,nc=new Set(["127.0.0.1","localhost","::1","[::1]","0.0.0.0","::"]),rc=class _AppDevServer{constructor(e){this.status={phase:"idle",port:null,url:null,error:null},this.child=null,this.launcherFinished=!1,this.commandEnv=null,this.urlHealthProbeTimer=null,this.urlHealthProbeUrl=null,this.urlHealthProbeConsecutiveFailures=0,this.urlHealthProbeInFlight=!1,this.outputEpoch=0,this.recentOutput=[],this.lastOutputAt=0,this.startPromise=null,this.stopPromise=null,this.stateFileChain=Promise.resolve(),this.intentionalStop=!1,this.detectedBaseUrl=null,this.pendingLockConflict=null,this.listeners=[],this.outputListeners=[],this.exitListeners=[],this.outputBroadcastTimer=null,this.hasParentDeathWatchdog=!1,this.options={command:e.command,stop:e.stop,url:e.url,cwd:Oa.resolve(e.cwd),workspaceRoot:Oa.resolve(e.workspaceRoot),urlScrapeTimeoutMs:resolveUrlScrapeTimeout(e.urlScrapeTimeoutMs),httpReadyTimeoutMs:resolveHttpReadyTimeout(e.httpReadyTimeoutMs),httpReadyAbsoluteCapMs:e.httpReadyAbsoluteCapMs??Qo,urlCommandTimeoutMs:e.urlCommandTimeoutMs??3e4,urlHealthProbeIntervalMs:e.urlHealthProbeIntervalMs??5e3,urlHealthFailuresToDemote:e.urlHealthFailuresToDemote??3,portRange:e.portRange??Ko,ownership:e.ownership},this.outputLog=new vo({filePath:this.getLogFilePath(),maxBytesPerFile:Vo})}static{this.MAX_RECENT_LINES=30}static{this.OUTPUT_BROADCAST_DEBOUNCE_MS=500}getStatus(){return{...this.status,livenessSource:"running"===this.status.phase?this.launcherFinished?"probe":"child":null,recentOutputTail:this.recentOutput.join("").slice(-2e3)}}readOutputLogTail(e){return this.outputLog.readTail(e)}async ensurePort(){return null==this.status.port||"starting"!==this.status.phase&&"running"!==this.status.phase?await this.allocatePort():this.status.port}async reconcilePersistedProcess(){const e=await this.readPersistedState();if(!e)return"nothing_to_reconcile";const t=await this.classifyPersistedProcessOwnership(e);if("reapable"!==t)return t;const n=[[e.pid,e.pidStartedAt,"shell"],[e.serverPid,e.serverPidStartedAt,"server"]],r=n.some(([e,t])=>null!=e&&null!=t);if(!r)return"nothing_to_reconcile";if(null!=e.pid&&await pidStartIdentityMatches(e.pid,e.pidStartedAt)){const t=await reapOwnedProcessGroup(e.pid);devLog("app-devserver:registry-orphan-group-reap",{pid:e.pid,port:e.port,outcome:t,workspaceRoot:this.options.workspaceRoot})}if(null!=e.serverPid&&await pidStartIdentityMatches(e.serverPid,e.serverPidStartedAt)){const t=await reapConflictingDevServer(e.serverPid);devLog("app-devserver:registry-orphan-server-reap",{serverPid:e.serverPid,port:e.port,outcome:t,workspaceRoot:this.options.workspaceRoot})}for(const[e,t]of n)if(null!=e&&await pidStartIdentityMatches(e,t))return"orphan_cleanup_failed";if(!await isPortFree(e.port)){const t=await findPortListenerPid(e.port);if(null==t||null==e.serverPidStartedAt)return"foreign_process";if(t===e.serverPid&&await pidStartIdentityMatches(t,e.serverPidStartedAt))return"orphan_cleanup_failed"}return await this.persistChildPid(null),await this.persistServerPid(null),"orphan_reaped"}onStatusChange(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e)}}onOutput(e){return this.outputListeners.push(e),()=>{this.outputListeners=this.outputListeners.filter(t=>t!==e)}}onExit(e){return this.exitListeners.push(e),()=>{this.exitListeners=this.exitListeners.filter(t=>t!==e)}}async start(e){return sc(e),"running"===this.status.phase&&this.status.url?{ok:!0,url:this.status.url,error:null}:this.startPromise?await ac(this.startPromise,e):(this.stopPromise&&await this.stopPromise.catch(()=>{}),this.startPromise=(async()=>(this.child&&await this.killChild(),await this.runStartCycle(0,e)))().finally(()=>{this.startPromise=null}),this.startPromise)}async stop(){if("idle"!==this.status.phase&&"stopped"!==this.status.phase)return this.stopPromise||(this.stopPromise=this.runStopCycle().finally(()=>{this.stopPromise=null})),this.stopPromise}forceKill(){this.intentionalStop=!0,this.stopUrlHealthProbe(),this.outputEpoch+=1,this.clearOutputBroadcastTimer();const e=this.child;if(!e)return;const t=e.pid;if(t){try{if("win32"!==process.platform){if(this.hasParentDeathWatchdog){try{e.stdin?.destroy()}catch{}try{return process.kill(-t,"SIGTERM"),void(this.child=null)}catch{}}try{process.kill(-t,"SIGKILL")}catch{e.kill("SIGKILL")}}else Pa("taskkill",["/pid",String(t),"/T","/F"],{windowsHide:!0,timeout:3e3})}catch{}this.child=null}}async resolveBundledNodeBinDirForStart(){const e=getBundledNodeBinDir();if(!e)return null;const t=await probeNodeVersion(removeDirFromPathEnv({...process.env},e));return shouldUseBundledNode({systemNodeVersion:t,requireFloor:!1,floorOk:null!=t})?(devLog("app-devserver:bundled_node_activated",{cwd:this.options.cwd,systemNodeVersion:t,binDir:e}),e):null}async runStartCycle(e=0,t){sc(t);const n=++this.outputEpoch;this.setStatus({phase:"starting",error:null}),this.intentionalStop=!1,this.launcherFinished=!1,this.commandEnv=null,this.stopUrlHealthProbe(),this.detectedBaseUrl=null,this.recentOutput=[];let r=!1;const s=findPowerShellSyntax(this.options.command);if(s){const e=`The app dev command was rejected before spawn: it contains PowerShell-only syntax (${s}), which the shell Tempo runs commands with (cmd.exe on Windows) cannot parse — nothing was started. Rewrite "apps[0].start" in tempo.config.json as a single plain cross-platform command — use \${APP_PORT} only if it needs Tempo's allocated helper port — and if the app lives in a subdirectory set "appDir" instead of cd/pushd-ing inside the command (chaining with \`&&\` is fine; cmd supports it).`;return devLog("app-devserver:shell-dialect-rejected",{command:this.options.command,construct:s}),this.setStatus({phase:"error",error:e,url:null}),{ok:!1,url:null,error:e}}const i=this.options.stop?findPowerShellSyntax(this.options.stop):null;if(i){const e=`The app stop command was rejected before spawn: it contains PowerShell-only syntax (${i}). Rewrite "apps[0].stop" as one plain cross-platform command.`;return this.setStatus({phase:"error",error:e,url:null}),{ok:!1,url:null,error:e}}const a="object"==typeof this.options.url?this.options.url.command:null,o=a?findPowerShellSyntax(a):null;if(o){const e=`The app URL command was rejected before spawn: it contains PowerShell-only syntax (${o}). Rewrite "apps[0].url.command" as one plain cross-platform command.`;return this.setStatus({phase:"error",error:e,url:null}),{ok:!1,url:null,error:e}}await this.truncateLogFile(),sc(t);let removeAbortListener=()=>{};try{const s=this.pendingLockConflict;null!=s&&0===e&&(this.pendingLockConflict=null,Date.now()-s.at<=Xa&&await this.reapLockConflictHolder(s.conflict,e)),sc(t);const i=await this.resolveBundledNodeBinDirForStart();sc(t);const a=await this.allocatePort();sc(t),this.setStatus({port:a});const o=extractLeadingEnvAssignments(this.substitutePort(this.options.command,a)),c=o.command,l=buildAppCommandEnv(a);isNuxtAppStart(c,this.options.cwd)&&Object.assign(l,nuxtSocketTmpdirEnv(l)),Object.assign(l,o.env),Object.assign(l,tempoSdkRuntimeEnvironment(l,this.options.cwd)),this.commandEnv=l,devLog("app-devserver:spawn",{command:c,configuredUrl:this.options.url??null,liftedEnvKeys:Object.keys(o.env),cwd:this.options.cwd,port:a});const d=i?applyBundledNodeEnv(l,i):l,u=await this.ensureParentDeathWatchdog();sc(t),this.hasParentDeathWatchdog=null!==u,this.child=u?Ra(process.execPath,[u,c],{cwd:this.options.cwd,detached:"win32"!==process.platform,stdio:["pipe","pipe","pipe","ipc"],windowsHide:!0,env:{...d,TEMPO_WATCHDOG_CHILD_ELECTRON_RUN_AS_NODE:d.ELECTRON_RUN_AS_NODE??"__TEMPO_UNSET__",ELECTRON_RUN_AS_NODE:"1"}}):Ra(c,{cwd:this.options.cwd,shell:!0,detached:"win32"!==process.platform,stdio:["ignore","pipe","pipe"],windowsHide:!0,env:d}),r=!0,this.wireProcessEvents(n);const onAbort=()=>{this.killChild().catch(()=>{})};t?.addEventListener("abort",onAbort,{once:!0}),removeAbortListener=()=>t?.removeEventListener("abort",onAbort),t?.aborted&&onAbort();const p=u?await waitForWatchdogChildPid(this.child):this.child.pid??null;sc(t),await this.persistChildPid(p);const h=await this.waitForReady(a,t),m=h.url;if(!m){if("error"===this.status.phase){const n=e<2?parseDevServerLockConflict(this.recentOutput.join("")):null;if(null!=n&&await this.reapLockConflictHolder(n,e))return removeAbortListener(),removeAbortListener=()=>{},await this.runStartCycle(e+1,t);const s=this.status.error,i=await this.cleanupFailedLaunch(a,r),o=i?`${s??"App dev server failed to start."}\n\nCleanup also failed: ${i}`:s;return this.setStatus({phase:"error",error:o,url:null}),{ok:!1,url:null,error:o}}const n=h.timeoutError??"App dev server did not become reachable in time.",s=await this.cleanupFailedLaunch(a,r),i=s?`${n}\n\nCleanup also failed: ${s}`:n;return this.setStatus({phase:"error",error:i,url:null}),{ok:!1,url:null,error:i}}sc(t),this.setStatus({phase:"running",url:m,error:null}),this.launcherFinished&&this.startUrlHealthProbe(m);const f=await findPortListenerPid(a);sc(t);const g=await this.readPersistedState();sc(t);const y=g?.pid??this.child?.pid??null,v=null!=f&&null!=y&&await pidBelongsToSpawnedTree(y,f)?f:null;return await this.persistServerPid(v),sc(t),devLog("app-devserver:server-pid-resolved",{port:a,serverPid:f,ownedServerPid:v,shellPid:y}),{ok:!0,url:m,error:null}}catch(e){const t=e instanceof Error?e.message:String(e),n=await this.cleanupFailedLaunch(this.status.port,r),s=n?`${t}\n\nCleanup also failed: ${n}`:t;return this.setStatus({phase:"error",error:s}),{ok:!1,url:null,error:s}}finally{removeAbortListener()}}async cleanupFailedLaunch(e,t){if(this.stopUrlHealthProbe(),!t)return this.commandEnv=null,null;let n=null;if(this.options.stop&&null!=e){const t=await this.runBoundedCommand(this.options.stop,e,1e4);devLog("app-devserver:failed-launch-stop-command",{command:this.options.stop,exitCode:t.exitCode,aborted:t.aborted,spawnError:t.spawnError?.message??null,stderr:t.stderr.slice(-1e3),workspaceRoot:this.options.workspaceRoot}),n=describeShellCommandFailure(t)}try{await this.killChild()}catch(e){return[n,e instanceof Error?e.message:String(e)].filter(Boolean).join("\n")}return this.launcherFinished=!1,this.commandEnv=null,n}async runStopCycle(){this.intentionalStop=!0,this.stopUrlHealthProbe(),this.clearOutputBroadcastTimer();const e=this.status.port;if(this.options.stop&&null!=e){const t=await this.runBoundedCommand(this.options.stop,e,1e4);devLog("app-devserver:stop-command",{command:this.options.stop,exitCode:t.exitCode,aborted:t.aborted,spawnError:t.spawnError?.message??null,stderr:t.stderr.slice(-1e3),workspaceRoot:this.options.workspaceRoot})}await this.killChild(),this.outputEpoch+=1,await this.outputLog.flush(),await this.persistChildPid(null),await this.persistServerPid(null),this.launcherFinished=!1,this.commandEnv=null,this.setStatus({phase:"stopped",url:null,error:null})}async reapLockConflictHolder(e,t){const n=await this.readPersistedState(),r=n?[[n.pid,n.pidStartedAt],[n.serverPid,n.serverPidStartedAt]]:[],s=(await Promise.all(r.map(async([t,n])=>t===e.pid&&await pidStartIdentityMatches(t,n)))).some(Boolean);if(!s){const n=null==e.port?null:await findPortListenerPid(e.port);return devLog("app-devserver:dev-lock-unowned",{pid:e.pid,holderPort:e.port,listenerPid:n,attempt:t,workspaceRoot:this.options.workspaceRoot}),!1}const i=await reapConflictingDevServer(e.pid);return devLog("app-devserver:dev-lock-reap",{pid:e.pid,holderPort:e.port,outcome:i,attempt:t,workspaceRoot:this.options.workspaceRoot}),null!=e.port&&await waitForPortFree(e.port,2500),!0}wireProcessEvents(e){const t=this.child;if(!t)return;const onData=n=>{if(e!==this.outputEpoch)return;const r=String(n);this.lastOutputAt=Date.now(),this.recentOutput.push(r),this.recentOutput.length>_AppDevServer.MAX_RECENT_LINES&&this.recentOutput.shift(),this.outputLog.append(r);for(const e of this.outputListeners)try{e(r)}catch{}if(this.scheduleOutputBroadcast(),!this.detectedBaseUrl){const e=extractServerUrl(r);e&&(this.detectedBaseUrl=e,devLog("app-devserver:url_detected",{pid:t.pid??null,baseUrl:e}))}};t.stdout?.on("data",onData),t.stderr?.on("data",onData),t.on("error",e=>{devLog("app-devserver:spawn_error",{pid:t.pid??null,message:e.message})}),t.on("exit",(n,r)=>{const s="running"===this.status.phase;if(devLog("app-devserver:exit",{pid:t.pid??null,code:n,signal:r,intentional:this.intentionalStop}),e!==this.outputEpoch||this.child!==t)return;this.child=null,this.persistChildPid(null);const i=!this.intentionalStop&&0===n&&null==r,a=i&&null!=this.options.stop&&("starting"===this.status.phase||"running"===this.status.phase);if(a&&this.options.stop)return this.launcherFinished=!0,"running"===this.status.phase&&this.status.url&&this.startUrlHealthProbe(this.status.url),void devLog("app-devserver:launcher-finished",{pid:t.pid??null,afterReady:"running"===this.status.phase,workspaceRoot:this.options.workspaceRoot});if(!this.intentionalStop&&"stopped"!==this.status.phase){const e="running"===this.status.phase?parseDevServerLockConflict(this.recentOutput.join("")):null;null!=e&&(this.pendingLockConflict={conflict:e,at:Date.now()},devLog("app-devserver:dev-lock-post-ready-conflict",{pid:e.pid,holderPort:e.port,workspaceRoot:this.options.workspaceRoot}));const t=this.recentOutput.join("").slice(-500),a=t?classifyDevServerOutput(t):null,o=i&&"starting"===this.status.phase?'The app start command exited successfully before the configured URL became ready. Add a matching non-empty "apps[0].stop" command so Tempo has teardown authority for the external server.':`App dev server exited unexpectedly (code ${n??"null"}, signal ${r??"null"}).${t?`\n\n${t}`:""}${a?`\n\nHint: ${a.hint}`:""}`;if(this.setStatus({phase:"error",error:o,url:null}),s)for(const e of[...this.exitListeners])try{e({code:n,signal:r,error:o})}catch{}}})}async waitForReady(e,t){const n=await this.resolveConfiguredUrl(e,t);if(!n){const e=Date.now()+this.options.urlScrapeTimeoutMs;for(;!this.detectedBaseUrl&&Date.now()<e;){if(sc(t),!this.hasLivenessAuthority())return{url:null};await ic(120,t)}}const r=n??this.detectedBaseUrl??`http://${Xo}:${e}`,s=rewriteToPublicHost(r,e,null===n),i=Date.now();let a=i;for(;;){if(sc(t),!this.hasLivenessAuthority())return{url:null};const e=await probeHttpOnce(s,Jo,t);if(sc(t),"reachable"===e)return{url:s};const n=Date.now();"held"!==e&&"starting"!==e||(a=n),this.lastOutputAt>a&&(a=this.lastOutputAt);const r=n-i,o=r>=this.options.httpReadyAbsoluteCapMs,c=n-a>=this.options.httpReadyTimeoutMs;if(o||c)return{url:null,timeoutError:describeReadinessTimeout(s,e,r)};await ic(httpProbeInterval(r),t)}}hasLivenessAuthority(){return this.launcherFinished||null!==this.child}async resolveConfiguredUrl(e,t){const n=this.options.url;if(!n)return null;"object"==typeof n&&this.options.stop&&await this.waitForLauncherHandoff(t);try{return await resolveHttpUrlSource({source:n,label:"apps[0].url",cwd:this.options.cwd,env:this.commandEnv??buildAppCommandEnv(e),port:e,timeoutMs:this.options.urlCommandTimeoutMs,signal:t,substitutePort:substituteAppPort})}catch(e){throw sc(t),e}}async waitForLauncherHandoff(e){const t=Date.now()+Qo;for(;!this.launcherFinished;){if(sc(e),!this.child)throw new Error(this.status.error??"The app start command stopped before URL resolution could run.");if(Date.now()>=t)throw new Error("Timed out waiting for the app start command to hand off before running apps[0].url.command");await ic(120,e)}}async runBoundedCommand(e,t,n,r,s=this.options.cwd){const i=new AbortController,onAbort=()=>i.abort();r?.addEventListener("abort",onAbort,{once:!0});const a=setTimeout(()=>i.abort(),n);try{return await runAbortableShellCommand({command:substituteAppPort(e,t),cwd:s,env:this.commandEnv??buildAppCommandEnv(t),signal:i.signal,maxOutputBytes:4e3})}finally{clearTimeout(a),r?.removeEventListener("abort",onAbort)}}startUrlHealthProbe(e){this.stopUrlHealthProbe(),this.urlHealthProbeUrl=e,this.urlHealthProbeTimer=setInterval(()=>{this.runUrlHealthProbeTick()},this.options.urlHealthProbeIntervalMs),this.urlHealthProbeTimer.unref?.()}stopUrlHealthProbe(){this.urlHealthProbeTimer&&clearInterval(this.urlHealthProbeTimer),this.urlHealthProbeTimer=null,this.urlHealthProbeUrl=null,this.urlHealthProbeConsecutiveFailures=0,this.urlHealthProbeInFlight=!1}async runUrlHealthProbeTick(){if(this.urlHealthProbeInFlight)return;const e=this.urlHealthProbeUrl;if(e&&!this.intentionalStop){this.urlHealthProbeInFlight=!0;try{const t=await probeHttpOnce(e,1500);if(this.urlHealthProbeUrl!==e||this.intentionalStop)return;if("refused"!==t)return void(this.urlHealthProbeConsecutiveFailures=0);if(!this.launcherFinished)return;if(this.urlHealthProbeConsecutiveFailures+=1,this.urlHealthProbeConsecutiveFailures<this.options.urlHealthFailuresToDemote)return;const n=`App dev server URL became unreachable after launcher handoff: ${e}`;this.launcherFinished=!1,this.stopUrlHealthProbe(),this.setStatus({phase:"error",url:null,error:n});for(const e of[...this.exitListeners])try{e({code:null,signal:null,error:n})}catch{}}finally{this.urlHealthProbeInFlight=!1}}}async killChild(){const e=this.child;if(!e)return;if(null!==e.exitCode||null!==e.signalCode)return void(this.child=null);const t=e.pid;if(!t)return void(this.child=null);try{if("win32"!==process.platform)try{process.kill(-t,"SIGTERM")}catch{e.kill("SIGTERM")}else await killWindowsProcessTree(t)}catch{}const n=await waitForChildExit(e,5e3);if(!n){try{if("win32"!==process.platform)try{process.kill(-t,"SIGKILL")}catch{e.kill("SIGKILL")}else await killWindowsProcessTree(t),e.kill("SIGKILL")}catch{}if(!await waitForChildExit(e,2e3))throw new Error(`App dev server process ${t} survived termination. Retry cleanup before starting a replacement.`)}this.child===e&&(this.child=null)}async ensureParentDeathWatchdog(){if("0"===process.env.TEMPO_DEVSERVER_WATCHDOG)return null;const e=Oa.join(this.options.workspaceRoot,".tempo",`app-${Eo}`);try{return await Aa(Oa.dirname(e),{recursive:!0}),await atomicWriteText(e,To),e}catch(t){return devLog("app-devserver:watchdog-write-failed",{watchdogPath:e,error:t instanceof Error?t.message:String(t)}),null}}substitutePort(e,t){return substituteAppPort(e,t)}scheduleOutputBroadcast(){this.outputBroadcastTimer||(this.outputBroadcastTimer=setTimeout(()=>{this.outputBroadcastTimer=null,"starting"===this.status.phase&&this.setStatus({})},_AppDevServer.OUTPUT_BROADCAST_DEBOUNCE_MS))}clearOutputBroadcastTimer(){this.outputBroadcastTimer&&(clearTimeout(this.outputBroadcastTimer),this.outputBroadcastTimer=null)}async allocatePort(){const e=await this.readPersistedState();if(e){if(await isPortFree(e.port))return e.port;const t=await this.mayReapPersistedProcess(e);if(t&&null!=e.pid&&await pidStartIdentityMatches(e.pid,e.pidStartedAt)){const t=await reapOwnedProcessGroup(e.pid);if(devLog("app-devserver:orphan-reap",{pid:e.pid,port:e.port,outcome:t,workspaceRoot:this.options.workspaceRoot}),await waitForPortFree(e.port,2e3))return e.port}if(t&&null!=e.serverPid){const t=await findPortListenerPid(e.port);if(null!=t&&t===e.serverPid&&await pidStartIdentityMatches(t,e.serverPidStartedAt)){const t=await reapConflictingDevServer(e.serverPid);if(devLog("app-devserver:orphan-server-pid-reap",{serverPid:e.serverPid,port:e.port,outcome:t,workspaceRoot:this.options.workspaceRoot}),await waitForPortFree(e.port,2e3))return e.port}else devLog("app-devserver:orphan-server-pid-mismatch",{serverPid:e.serverPid,listenerPid:t,port:e.port,workspaceRoot:this.options.workspaceRoot})}devLog("app-devserver:persisted-port-occupied",{port:e.port,workspaceRoot:this.options.workspaceRoot})}const t=await findFreePort(this.options.portRange);return await this.writePersistedState({version:Zo,port:t,allocatedAt:Date.now(),pid:null,pidStartedAt:null,serverPid:null,serverPidStartedAt:null,...this.persistedOwnership()}),t}async persistChildPid(e){const t=null==e?null:await readPidStartIdentity(e);await this.runExclusiveStateFileOp(async()=>{const n=await this.readPersistedState();n?await this.writePersistedStateUnlocked({version:Zo,port:n.port,allocatedAt:n.allocatedAt,pid:e,pidStartedAt:t,serverPid:n.serverPid,serverPidStartedAt:n.serverPidStartedAt,...this.persistedOwnership(n)}):devLog("app-devserver:persist-pid-skipped-no-state",{pid:e,workspaceRoot:this.options.workspaceRoot})})}async persistServerPid(e){const t=null==e?null:await readPidStartIdentity(e);await this.runExclusiveStateFileOp(async()=>{const n=await this.readPersistedState();n?await this.writePersistedStateUnlocked({version:Zo,port:n.port,allocatedAt:n.allocatedAt,pid:n.pid,pidStartedAt:n.pidStartedAt,serverPid:e,serverPidStartedAt:t,...this.persistedOwnership(n)}):devLog("app-devserver:persist-server-pid-skipped-no-state",{serverPid:e,workspaceRoot:this.options.workspaceRoot})})}getStateFilePath(){return Oa.join(this.options.workspaceRoot,".tempo",qo)}persistedOwnership(e){const t=this.options.ownership;return t||{ownerId:e?.ownerId??null,managerPid:e?.managerPid??null,managerStartedAt:e?.managerStartedAt??null}}async mayReapPersistedProcess(e){return"reapable"===await this.classifyPersistedProcessOwnership(e)}async classifyPersistedProcessOwnership(e){const t=this.options.ownership;return t?e.ownerId!==t.ownerId||null==e.managerPid||null==e.managerStartedAt?"foreign_process":e.managerPid===t.managerPid&&e.managerStartedAt===t.managerStartedAt?"reapable":await pidStartIdentityMatches(e.managerPid,e.managerStartedAt)?"live_sibling":"reapable":"reapable"}async readPersistedState(){try{const e=await _a(this.getStateFilePath(),"utf-8"),t=JSON.parse(e);if(t&&"object"==typeof t&&"number"==typeof t.port&&Number.isInteger(t.port)&&t.port>0&&t.port<65536)return{version:"number"==typeof t.version?t.version:0,port:t.port,allocatedAt:"number"==typeof t.allocatedAt?t.allocatedAt:0,pid:"number"==typeof t.pid&&Number.isInteger(t.pid)?t.pid:null,pidStartedAt:"string"==typeof t.pidStartedAt?t.pidStartedAt:null,serverPid:"number"==typeof t.serverPid&&Number.isInteger(t.serverPid)?t.serverPid:null,serverPidStartedAt:"string"==typeof t.serverPidStartedAt?t.serverPidStartedAt:null,ownerId:"string"==typeof t.ownerId?t.ownerId:null,managerPid:"number"==typeof t.managerPid&&Number.isInteger(t.managerPid)?t.managerPid:null,managerStartedAt:"string"==typeof t.managerStartedAt?t.managerStartedAt:null}}catch{}return null}async writePersistedState(e){await this.runExclusiveStateFileOp(()=>this.writePersistedStateUnlocked(e))}async writePersistedStateUnlocked(e){const t=this.getStateFilePath();try{await Aa(Oa.dirname(t),{recursive:!0});const n=`${t}.${process.pid}.tmp`;await Ia(n,`${JSON.stringify(e,null,2)}\n`,"utf-8"),await ka(n,t)}catch(e){devLog("app-devserver:persist-failed",{file:t,error:e instanceof Error?e.message:String(e)})}}runExclusiveStateFileOp(e){const t=this.stateFileChain.then(e,e);return this.stateFileChain=t.catch(()=>{}),t}getLogFilePath(){return Oa.join(this.options.workspaceRoot,".tempo",Wo)}async truncateLogFile(){await this.outputLog.reset()}setStatus(e){this.status={...this.status,...e};const t=this.getStatus();for(const e of this.listeners)try{e(t)}catch{}}};function extractServerUrl(e){const t=e.replace(ec,""),n=t.match(tc);if(!n)return null;for(const e of n){const t=e.replace(/[),.;]+$/,"");try{const e=new URL(t);if(nc.has(e.hostname.toLowerCase()))return t}catch{}}return null}function rewriteToPublicHost(e,t,n=!0){try{const r=new URL(e);"0.0.0.0"!==r.hostname&&"::"!==r.hostname||(r.hostname=Xo),n&&!r.port&&(r.port=String(t));const s=r.pathname.replace(/\/+$/,"");return`${r.origin}${s}${r.search}`}catch{return`http://${Xo}:${t}`}}async function probeHttpOnce(e,t,n){const r=new AbortController,s=setTimeout(()=>r.abort(),t),onAbort=()=>r.abort();n?.addEventListener("abort",onAbort,{once:!0}),n?.aborted&&onAbort();try{const t=await fetch(e,{signal:r.signal});return await(t.body?.cancel().catch(()=>{})),503===t.status?"starting":t.status>0?"reachable":"refused"}catch{return r.signal.aborted?"held":"refused"}finally{clearTimeout(s),n?.removeEventListener("abort",onAbort)}}function describeReadinessTimeout(e,t,n){if("starting"!==t)return"App dev server did not become reachable in time.";const r=Math.round(n/1e3);return`App dev server at ${e} was still answering 503 Service Unavailable after ${r}s: it kept reporting that it was starting and never became ready.`}function httpProbeInterval(e){return e<2e4?500:e<12e4?5e3:1e4}function sleep2(e){return new Promise(t=>setTimeout(t,e))}var{throwIfAborted:sc,sleep:ic,race:ac}=abortableWait("App devserver launch was cancelled");function parseEnvMs(e){if(!e)return null;const t=Number(e);return!Number.isFinite(t)||t<=0?null:t}function resolveUrlScrapeTimeout(e){const t=parseEnvMs(process.env.TEMPO_APP_DEVSERVER_URL_SCRAPE_TIMEOUT_MS);return null!==t?t:void 0!==e?e:Yo}function resolveHttpReadyTimeout(e){const t=parseEnvMs(process.env.TEMPO_APP_DEVSERVER_HTTP_READY_TIMEOUT_MS);return null!==t?t:void 0!==e?e:zo}function waitForChildExit(e,t){return null!==e.exitCode||null!==e.signalCode?Promise.resolve(!0):new Promise(n=>{const r=setTimeout(()=>n(!1),t);e.once("exit",()=>{clearTimeout(r),n(!0)})})}function waitForWatchdogChildPid(e,t=2e3){return new Promise(n=>{let r=!1;const finish=t=>{r||(r=!0,clearTimeout(s),e.off("message",onMessage),e.off("exit",onExit),n(t))},onMessage=e=>{"object"==typeof e&&null!==e&&"type"in e&&"tempo-watchdog-child"===e.type&&"pid"in e&&finish("number"==typeof e.pid?e.pid:null)},onExit=()=>finish(null),s=setTimeout(()=>finish(null),t);e.on("message",onMessage),e.once("exit",onExit)})}function substituteAppPort(e,t){return e.replace(/\$\{(?:APP_PORT|PORT)\}/g,String(t))}function buildAppCommandEnv(e){const t={...process.env,APP_PORT:String(e),PORT:String(e),TEMPO_APP_PORT:String(e),TEMPO:"true",ASTRO_DEV_BACKGROUND:process.env.ASTRO_DEV_BACKGROUND??"0",ASTRO_PREVIEW_BACKGROUND:process.env.ASTRO_PREVIEW_BACKGROUND??"0"};for(const e of Object.keys(t)){const n=e.toLowerCase();(n.startsWith("npm_")||n.startsWith("pnpm_")||"INIT_CWD"===e||"NODE_PATH"===e)&&delete t[e]}return Object.assign(t,tempoSdkDevCommandEnv()),t}function describeShellCommandFailure(e){if(e.aborted)return"the app stop command timed out";if(e.spawnError)return`the app stop command could not start: ${e.spawnError.message}`;if(0===e.exitCode)return null;const t=e.stderr.trim();return`the app stop command exited with code ${e.exitCode??"unknown"}${t?`: ${t}`:""}`}async function findFreePort(e){const t=50;for(let n=0;n<t;n++){const r=await new Promise(e=>{const t=Na.createServer();t.once("error",()=>e(null)),t.listen(0,()=>{const n=t.address();t.close(()=>{e(n&&"object"==typeof n?n.port:null)})})});if(null!=r){if(r>=e.min&&r<=e.max)return r;if(n===t-1)return r}}throw new Error("Could not allocate a free TCP port for the app dev server.")}async function isPortFree(e){return await new Promise(t=>{const n=Na.createServer();n.once("error",()=>t(!1)),n.listen(e,()=>{n.close(()=>t(!0))})})}async function waitForPortFree(e,t){const n=Date.now()+t;for(;Date.now()<n;){if(await isPortFree(e))return!0;await sleep2(150)}return await isPortFree(e)}var oc=Da(Ca);async function readPidStartIdentity(e){try{if("win32"===process.platform){const{stdout:t}=await oc("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command",`$target = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${e}'; if ($null -ne $target) { [Console]::Out.Write($target.CreationDate.ToUniversalTime().Ticks) }`],{windowsHide:!0,timeout:2e3});return t.trim()||null}const{stdout:t}=await oc("ps",["-p",String(e),"-o","lstart="],{windowsHide:!0,timeout:2e3});return t.trim()||null}catch{return null}}async function pidBelongsToSpawnedTree(e,t){if(e===t)return!0;try{if("win32"===process.platform){const{stdout:n}=await oc("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command",`$rootPid = ${e}; $currentPid = ${t}; while ($currentPid -gt 0 -and $currentPid -ne $rootPid) { $target = Get-CimInstance -ClassName Win32_Process -Filter "ProcessId = $currentPid"; if ($null -eq $target) { break }; $currentPid = [int]$target.ParentProcessId }; if ($currentPid -eq $rootPid) { [Console]::Out.Write('owned') }`],{windowsHide:!0,timeout:2e3});return"owned"===n.trim()}const{stdout:n}=await oc("ps",["-p",String(t),"-o","pgid="],{windowsHide:!0,timeout:2e3});return Number(n.trim())===e}catch{return!1}}async function pidStartIdentityMatches(e,t){return!!t&&await readPidStartIdentity(e)===t}async function killWindowsProcessTree(e){try{await oc("taskkill",["/pid",String(e),"/T","/F"],{windowsHide:!0})}catch{}}async function reapOwnedProcessGroup(e){if("win32"===process.platform){const t=signalPid(e,0);return t?(await killWindowsProcessTree(e),await waitForPidExit(e,2e3)?"killed":(signalPid(e,"SIGKILL"),await waitForPidExit(e,1e3)?"killed":"survived")):"dead"}return signalProcessGroup(e,0)?(signalProcessGroup(e,"SIGTERM"),await waitForProcessGroupExit(e,2500)?"terminated":(signalProcessGroup(e,"SIGKILL"),await waitForProcessGroupExit(e,2e3)?"killed":"survived")):"dead"}function signalProcessGroup(e,t){try{return process.kill(-e,t),!0}catch{return!1}}async function waitForProcessGroupExit(e,t){const n=Date.now()+t;for(;Date.now()<n;){if(!signalProcessGroup(e,0))return!0;await sleep2(100)}return!signalProcessGroup(e,0)}async function reapConflictingDevServer(e){if("win32"===process.platform){const t=signalPid(e,0);return t?(await killWindowsProcessTree(e),await waitForPidExit(e,2e3)?"killed":(signalPid(e,"SIGKILL"),await waitForPidExit(e,1e3)?"killed":"survived")):"dead"}return signalPid(e,0)?(signalPid(e,"SIGTERM"),await waitForPidExit(e,2500)?"terminated":(signalPid(e,"SIGKILL"),await waitForPidExit(e,2e3)?"killed":"survived")):"dead"}function signalPid(e,t){try{return process.kill(e,t),!0}catch(e){return"EPERM"===e?.code}}async function waitForPidExit(e,t){const n=Date.now()+t;for(;Date.now()<n;){if(!signalPid(e,0))return!0;await sleep2(100)}return!signalPid(e,0)}var cc=3e5,lc=/\b(?:ETIMEDOUT|ESOCKETTIMEDOUT|ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ENETUNREACH|EHOSTUNREACH|ERR_SOCKET_TIMEOUT|UND_ERR_CONNECT_TIMEOUT|UND_ERR_SOCKET)\b/,dc=/\b(?:CERT_HAS_EXPIRED|CERT_NOT_YET_VALID|SELF_SIGNED_CERT_IN_CHAIN|DEPTH_ZERO_SELF_SIGNED_CERT|UNABLE_TO_VERIFY_LEAF_SIGNATURE|UNABLE_TO_GET_ISSUER_CERT_LOCALLY|ERR_TLS_CERT_ALTNAME_INVALID)\b/;function describeInstallConnectivity(e){const t=e.replace(/\u001b\[[0-9;]*m/g,"").split(/\r?\n/).filter(e=>!/\b(?:warn|warning)\s+deprecated\b/i.test(e)).join("\n"),n=[...t.matchAll(/npm (?:error|ERR!) code\s+(\w+)|\bERR_PNPM_(\w+)/g)].at(-1),r=n?.[1]??n?.[2],s="META_FETCH_FAIL"===n?.[2]?t.slice(n.index):r??t;if(r&&"META_FETCH_FAIL"!==r&&!lc.test(r)&&!dc.test(r))return null;const i=s.match(dc)?.[0];if(i)return{code:i,hint:"Check your proxy or registry certificate trust, then retry."};const a=s.match(lc)?.[0];return a?{code:a,hint:"Check your internet connection, VPN, or proxy, then retry."}:null}function tempoSdkIdentitySatisfiesCanvasHost(e){return"string"==typeof e.sdkVersion&&null===tempoSdkRuntimeCompatibilityError({version:e.sdkVersion,tempoRuntimeContract:e.tempoRuntimeContract})}var uc='/* THIS FILE IS AUTO-GENERATED BY TEMPO. DO NOT EDIT. */\n/*\n * CanvasHost Metro (Expo) recovery adapter.\n *\n * Expo serves its web dev bundle with Metro LAZY BUNDLING on, which keeps\n * every `import()`-reachable module out of the bundle until a separate\n * request asks for it. The generated host wrapper registers each canvas as\n * `lazy(() => import(...))`, so a canvas demand-registered while this\n * document is already live arrives as a Fast Refresh swap of the wrapper\n * that references a canvas module this client never received:\n * `Requiring unknown module "N"`. `CanvasImportBoundary` catches it, so the\n * storyboard just stays blank — permanently, because the wrapper DID update,\n * so the runtime advertises the canvas in `canvasPaths`, the component\n * pool\'s staleness check is satisfied, and nothing ever reloads the document\n * that a full page load would rebuild the bundle for. See TEM-1410.\n *\n * The repair is one document reload, and the ONLY question is when it is\n * safe to issue. The wrapper stamps a generation counter on every\n * evaluation: 1 on a cold document load, 2+ once Fast Refresh has swapped\n * it. That single bit is what separates the two failure shapes:\n *\n * - Generation 1 (COLD): the canvas module was in the graph when the\n * bundle was built, so a load failure here is the canvas genuinely\n * being broken — an unresolvable import, a module that throws at\n * evaluation. A reload would rebuild the same broken bundle, so this\n * adapter deliberately does NOTHING. The failure stays scoped to its\n * own canvas through the SDK\'s import boundary and every sibling canvas\n * keeps rendering. This is the isolation invariant `buildTempoHostWrapper`\n * exists to protect; do not "fix" a cold failure by reloading.\n *\n * - Generation 2+ (HOT): the wrapper was swapped after this bundle was\n * built, so a load failure is the lazy-bundling gap above — the module\n * is missing from THIS client, not broken. Exactly one reload rebuilds\n * the bundle with it included.\n *\n * Termination is structural, not a counter: a reload produces a fresh\n * document at generation 1, where this adapter is inert by construction. A\n * genuinely broken canvas therefore costs at most one reload and then stays\n * an isolated, boundary-scoped failure — there is no reload loop to bound.\n *\n * Deliberately NOT used here: ESM import metadata (Metro bundles web as a\n * classic script and does not transform it, so a module referencing it throws\n * on load — the same hazard the sidecar\'s metro config disables package\n * exports to avoid; the equality test pins its absence), Metro/React-Refresh\n * internals, module paths, cycle payloads, or owner identity. The adapter\n * reads one global integer and one product fact off the shared feed.\n *\n * This module installs itself exactly once per document: the generated host\n * wrapper imports it for side effects only, so wrapper re-evaluation under\n * Fast Refresh reuses the cached module instead of stacking listeners.\n */\n\ntype CanvasHostRecoveryEvent = {\n type: "module-load-failure" | "module-update-dropped";\n /** Failed module path. Diagnostic only — this adapter never matches on it. */\n path: string;\n message?: string;\n};\n\ntype CanvasHostRecoveryFeed = {\n publish(event: CanvasHostRecoveryEvent): void;\n subscribe(listener: (event: CanvasHostRecoveryEvent) => void): () => void;\n};\n\n// Mirror of tempo-sdk\'s create-if-absent feed bootstrap: whichever side\n// evaluates first creates the bus, the other reuses it, so evaluation order\n// between the SDK and this generated module never matters.\nfunction getCanvasHostRecoveryFeed(): CanvasHostRecoveryFeed {\n const globals = globalThis as typeof globalThis & {\n __tempoCanvasHostRecoveryFeed?: CanvasHostRecoveryFeed;\n };\n if (!globals.__tempoCanvasHostRecoveryFeed) {\n const listeners = new Set<(event: CanvasHostRecoveryEvent) => void>();\n globals.__tempoCanvasHostRecoveryFeed = {\n publish(event) {\n for (const listener of Array.from(listeners)) listener(event);\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n }\n return globals.__tempoCanvasHostRecoveryFeed;\n}\n\n/** Global the generated host wrapper increments on every evaluation. 1 is a\n * cold document load; 2+ means Fast Refresh swapped the wrapper. */\nexport const WRAPPER_GENERATION_KEY = "__tempoCanvasHostWrapperGeneration";\n\nfunction readWrapperGeneration(): number {\n const value = (globalThis as Record<string, unknown>)[WRAPPER_GENERATION_KEY];\n return typeof value === "number" && Number.isFinite(value) ? value : 0;\n}\n\n/** How long the reload decision waits after a failure, so a burst of\n * per-canvas failures from one wrapper swap collapses into a single reload\n * instead of racing each other. */\nconst RELOAD_DECISION_GRACE_MS = 100;\n\nexport type CanvasHostMetroRecoveryOptions = {\n /** Test seam; defaults to reloading this document. */\n reload?: () => void;\n /** Test seam; defaults to the shared in-document recovery feed. */\n feed?: CanvasHostRecoveryFeed;\n /** Test seam; defaults to the wrapper-stamped global. */\n readGeneration?: () => number;\n};\n\nexport function installCanvasHostMetroRecovery(\n options: CanvasHostMetroRecoveryOptions = {},\n): () => void {\n const feed = options.feed ?? getCanvasHostRecoveryFeed();\n const readGeneration = options.readGeneration ?? readWrapperGeneration;\n const reload =\n options.reload ??\n (() => {\n window.location.reload();\n });\n\n let reloadTimer: ReturnType<typeof setTimeout> | null = null;\n let reloadIssued = false;\n let feedEventsSeen = 0;\n let coldFailuresIgnored = 0;\n let installed = true;\n\n // Always-current diagnostic mirror (the getters close over the adapter\'s\n // live variables). Read by e2e suites and bug-report tooling via frame\n // evaluation; never consumed by the adapter itself.\n (\n globalThis as typeof globalThis & {\n __tempoCanvasHostRecoveryDebug?: unknown;\n }\n ).__tempoCanvasHostRecoveryDebug = {\n adapter: "metro",\n get installed() {\n return installed;\n },\n get wrapperGeneration() {\n return readGeneration();\n },\n get reloadIssued() {\n return reloadIssued;\n },\n get feedEventsSeen() {\n return feedEventsSeen;\n },\n get coldFailuresIgnored() {\n return coldFailuresIgnored;\n },\n };\n\n const unsubscribe = feed.subscribe((event) => {\n feedEventsSeen += 1;\n // "module-update-dropped" is Vite vocabulary (a dropped hot update whose\n // module fetch failed); Metro never publishes it. Ignore rather than\n // treat an unrecognized flavor as a reload trigger.\n if (event.type !== "module-load-failure") return;\n if (reloadIssued || reloadTimer !== null) return;\n // Cold failure: the module was in the bundle and genuinely failed. A\n // reload rebuilds the same failure and would take every sibling canvas\n // down with it. Leave it to the import boundary.\n if (readGeneration() <= 1) {\n coldFailuresIgnored += 1;\n return;\n }\n reloadTimer = setTimeout(() => {\n reloadTimer = null;\n if (reloadIssued) return;\n reloadIssued = true;\n reload();\n }, RELOAD_DECISION_GRACE_MS);\n });\n\n return () => {\n installed = false;\n unsubscribe();\n if (reloadTimer !== null) {\n clearTimeout(reloadTimer);\n reloadTimer = null;\n }\n };\n}\n\n// Self-install: this generated module is imported for side effects by the\n// host wrapper. Guarded so a Node test import of the template stays side-\n// effect free.\nif (typeof window !== "undefined") {\n installCanvasHostMetroRecovery();\n}\n',pc='/* THIS FILE IS AUTO-GENERATED BY TEMPO. DO NOT EDIT. */\n/*\n * CanvasHost Vite recovery adapter.\n *\n * Vite and React own ordinary module propagation and Fast Refresh. This\n * adapter closes exactly one verified hole class — a module this document\n * needs failed to load and Vite will not converge it in place — and the\n * repair action is always a document reload. Two failure flavors arrive as\n * product facts over the in-document recovery feed shared with tempo-sdk,\n * and they differ in what a later HMR cycle can prove:\n *\n * - "module-load-failure": convergence in place is impossible. A\n * dependency\'s top-level evaluation threw (the throw prevented\n * plugin-react\'s accept footer from registering, so even a successful\n * re-fetch of the repaired module updates nothing), or a canvas\'s\n * cold-start import rejected. The first LATER cycle (a user edit that\n * plausibly repairs the code) triggers at most one reload — a\n * successful retry of the module is deliberately NOT trusted as\n * recovery, because with the accepts lost it heals nothing.\n *\n * - "module-update-dropped": Vite dropped a hot update whose module\n * fetch failed (accept callbacks ran with `undefined`; the update is\n * never retried by Vite itself). Here later lifecycle traffic carries a\n * real verdict, read from Vite\'s own payloads: a cycle that RETRIED\n * the dropped path resolves it (on success Vite just healed it in\n * place — during active editing the same file is usually re-saved\n * within the next beat, and reloading would be pure churn; on failure\n * the fresh event re-arms right behind the cycle), a PRUNE of the path\n * resolves it (the module left the graph, so its staleness is moot),\n * and a cycle that did neither can never heal it, proving the\n * staleness permanent: trigger at most one reload. The reload decision\n * itself waits one short beat, because Vite delivers a delete burst as\n * an importer update followed by the prune in a separate message.\n *\n * No reload is issued while this document holds a live compile error (a\n * Vite error overlay, or a `vite:error` since the current update began): a\n * reload would cold-import the module that no longer compiles and fail every\n * canvas in the document. The latch stays armed, and the next update that\n * completes without one decides again.\n *\n * A reload creates a fresh document with a fresh adapter — if code is still\n * broken, the new document re-latches independently and waits for another\n * edit. Which canvases show which problems stays owner-scoped in the SDK\n * problem tracker; the adapter never models owners.\n *\n * It deliberately contains no importer traversal, source hashes, polling,\n * deadlines, or transaction receipts; the only path matching is the exact\n * identity between a dropped update\'s module path and Vite\'s own payload\n * paths. A clean error feed or a completed Vite update is never treated as\n * success for the load-failure flavor.\n *\n * This module installs itself exactly once per document: the generated host\n * wrapper imports it for side effects only, so wrapper re-evaluation under\n * HMR reuses the cached module instead of stacking listeners. If Tempo\n * rewrites this managed file, Vite re-evaluates it and the previous\n * instance\'s `hot.dispose` teardown removes its listeners first.\n */\n\ntype CanvasHostRecoveryEvent = {\n type: "module-load-failure" | "module-update-dropped";\n /** Failed module path. Diagnostic for load failures; for dropped updates\n * it is matched against Vite update payload paths, so it must be the\n * exact accepted-module path Vite reported. */\n path: string;\n message?: string;\n};\n\ntype CanvasHostRecoveryFeed = {\n publish(event: CanvasHostRecoveryEvent): void;\n subscribe(listener: (event: CanvasHostRecoveryEvent) => void): () => void;\n};\n\n// Mirror of tempo-sdk\'s create-if-absent feed bootstrap: whichever side\n// evaluates first creates the bus, the other reuses it, so evaluation order\n// between the SDK and this generated module never matters.\nfunction getCanvasHostRecoveryFeed(): CanvasHostRecoveryFeed {\n const globals = globalThis as typeof globalThis & {\n __tempoCanvasHostRecoveryFeed?: CanvasHostRecoveryFeed;\n };\n if (!globals.__tempoCanvasHostRecoveryFeed) {\n const listeners = new Set<(event: CanvasHostRecoveryEvent) => void>();\n globals.__tempoCanvasHostRecoveryFeed = {\n publish(event) {\n for (const listener of Array.from(listeners)) listener(event);\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n }\n return globals.__tempoCanvasHostRecoveryFeed;\n}\n\ntype RenderErrorRecoveryBeatBus = {\n emit(): void;\n subscribe(listener: () => void): () => void;\n};\n\n// Mirror of tempo-sdk\'s create-if-absent render-error-recovery beat bus.\n// Emitting on each completed Vite update announces "new code may have\n// arrived" to errored storyboard boundaries, which retry immediately instead\n// of waiting out their backoff timer. The SDK cannot observe Vite itself:\n// its built bundle is force-resolved into Expo\'s Metro web bundle, where a\n// literal `import.meta` is a whole-document parse error (TEM-1409), so this\n// adapter — the only party that owns `import.meta.hot` — is the beat\'s\n// producer.\nfunction getRenderErrorRecoveryBeatBus(): RenderErrorRecoveryBeatBus {\n const globals = globalThis as typeof globalThis & {\n __tempoRenderErrorRecoveryBeatBus?: RenderErrorRecoveryBeatBus;\n };\n if (!globals.__tempoRenderErrorRecoveryBeatBus) {\n const listeners = new Set<() => void>();\n globals.__tempoRenderErrorRecoveryBeatBus = {\n emit() {\n for (const listener of Array.from(listeners)) listener();\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n }\n return globals.__tempoRenderErrorRecoveryBeatBus;\n}\n\ntype ViteHotLike = {\n on?: (event: string, callback: (payload?: unknown) => void) => void;\n off?: (event: string, callback: (payload?: unknown) => void) => void;\n dispose?: (callback: (data: unknown) => void) => void;\n};\n\n/** Module paths a Vite update payload touched: both the changed path and the\n * accepting boundary, since dropped-update events name the accepted module. */\nfunction readUpdatePayloadPaths(payload: unknown): Set<string> {\n const paths = new Set<string>();\n const updates = (payload as { updates?: unknown })?.updates;\n if (!Array.isArray(updates)) return paths;\n for (const update of updates) {\n const path = (update as { path?: unknown })?.path;\n if (typeof path === "string") paths.add(path);\n const acceptedPath = (update as { acceptedPath?: unknown })?.acceptedPath;\n if (typeof acceptedPath === "string") paths.add(acceptedPath);\n }\n return paths;\n}\n\n/** How long a reload decision waits for trailing same-burst messages (a\n * delete\'s prune follows its importer update in a separate ws message)\n * before committing. Resolution during the wait cancels the reload. */\nconst RELOAD_DECISION_GRACE_MS = 100;\n\nexport type CanvasHostViteRecoveryOptions = {\n hot: ViteHotLike | undefined;\n /** Test seam; defaults to reloading this document. */\n reload?: () => void;\n /** Test seam; defaults to the shared in-document recovery feed. */\n feed?: CanvasHostRecoveryFeed;\n};\n\nexport function installCanvasHostViteRecovery(\n options: CanvasHostViteRecoveryOptions,\n): () => void {\n const hot = options.hot;\n // Production builds and non-Vite documents have no HMR lifecycle to\n // observe, and therefore no missed-accept hole to repair.\n if (!hot || typeof hot.on !== "function") return () => {};\n const feed = options.feed ?? getCanvasHostRecoveryFeed();\n const reload =\n options.reload ??\n (() => {\n window.location.reload();\n });\n\n let hmrCycle = 0;\n // A cold-start failure is naturally recorded at cycle 0. Later failures\n // never advance the latch: the earliest unresolved failure decides when a\n // subsequent edit counts as a repair attempt.\n let documentFailedAtCycle: number | null = null;\n let unconvergeableFailure = false;\n const droppedUpdatePaths = new Set<string>();\n let reloadTimer: ReturnType<typeof setTimeout> | null = null;\n let reloadIssued = false;\n let feedEventsSeen = 0;\n let installed = true;\n // A compile error is live from Vite\'s `vite:error` (and its overlay) until\n // the next update begins, when Vite clears the overlay as well.\n let viteErrorSinceUpdate = false;\n const compileErrorLive = (): boolean =>\n viteErrorSinceUpdate ||\n (typeof document !== "undefined" &&\n document.querySelector("vite-error-overlay") !== null);\n\n // Always-current diagnostic mirror of the latch state (the getters close\n // over the adapter\'s live variables). Read by e2e suites and bug-report\n // tooling via frame evaluation; never consumed by the adapter itself.\n (\n globalThis as typeof globalThis & {\n __tempoCanvasHostRecoveryDebug?: unknown;\n }\n ).__tempoCanvasHostRecoveryDebug = {\n get installed() {\n return installed;\n },\n get hmrCycle() {\n return hmrCycle;\n },\n get documentFailedAtCycle() {\n return documentFailedAtCycle;\n },\n get unconvergeableFailure() {\n return unconvergeableFailure;\n },\n get droppedUpdatePaths() {\n return Array.from(droppedUpdatePaths);\n },\n get reloadIssued() {\n return reloadIssued;\n },\n get feedEventsSeen() {\n return feedEventsSeen;\n },\n get compileErrorLive() {\n return compileErrorLive();\n },\n };\n\n const latchArmed = (): boolean =>\n unconvergeableFailure || droppedUpdatePaths.size > 0;\n\n // Every dropped path resolved (retried or pruned) with no load failure on\n // record: the document converged without us; stand down entirely.\n const settleIfResolved = (): void => {\n if (latchArmed()) return;\n documentFailedAtCycle = null;\n if (reloadTimer !== null) {\n clearTimeout(reloadTimer);\n reloadTimer = null;\n }\n };\n\n const unsubscribe = feed.subscribe((event) => {\n feedEventsSeen += 1;\n if (event.type === "module-load-failure") {\n unconvergeableFailure = true;\n } else if (event.type === "module-update-dropped") {\n droppedUpdatePaths.add(event.path);\n } else {\n return;\n }\n if (documentFailedAtCycle === null) documentFailedAtCycle = hmrCycle;\n });\n\n const onBeforeUpdate = (): void => {\n hmrCycle += 1;\n viteErrorSinceUpdate = false;\n };\n const onViteError = (): void => {\n viteErrorSinceUpdate = true;\n };\n // afterUpdate is only the trigger for a later repair attempt — never\n // evidence that anything recovered. A same-cycle failure (the failing\n // update itself) must not trigger the reload; only a later cycle may.\n const onAfterUpdate = (payload?: unknown): void => {\n // Unconditional: every completed update is a "new code" beat for the\n // SDK\'s errored boundaries, independent of this adapter\'s reload latch.\n getRenderErrorRecoveryBeatBus().emit();\n if (documentFailedAtCycle === null) return;\n if (hmrCycle <= documentFailedAtCycle) return;\n if (reloadIssued) return;\n // A retried dropped path leaves the latch: Vite either healed it in\n // place, or the retry\'s own failure event re-arms right behind this\n // cycle. Load failures never resolve this way, and a dropped path this\n // later cycle did NOT retry proves an unconvergeable document — after\n // one beat of grace for the burst\'s trailing prune message.\n if (!unconvergeableFailure) {\n for (const path of readUpdatePayloadPaths(payload)) {\n droppedUpdatePaths.delete(path);\n }\n settleIfResolved();\n if (documentFailedAtCycle === null) return;\n }\n if (reloadTimer !== null) return;\n reloadTimer = setTimeout(() => {\n reloadTimer = null;\n if (!latchArmed() || reloadIssued) return;\n // Deferred, not dropped: the latch stays armed for the next update.\n if (compileErrorLive()) return;\n reloadIssued = true;\n reload();\n }, RELOAD_DECISION_GRACE_MS);\n };\n // A pruned module left the graph: its dropped update can no longer matter.\n const onBeforePrune = (payload?: unknown): void => {\n const paths = (payload as { paths?: unknown })?.paths;\n if (!Array.isArray(paths)) return;\n for (const path of paths) {\n if (typeof path === "string") droppedUpdatePaths.delete(path);\n }\n if (!unconvergeableFailure) settleIfResolved();\n };\n\n hot.on("vite:beforeUpdate", onBeforeUpdate);\n hot.on("vite:afterUpdate", onAfterUpdate);\n hot.on("vite:beforePrune", onBeforePrune);\n hot.on("vite:error", onViteError);\n\n return () => {\n installed = false;\n unsubscribe();\n if (reloadTimer !== null) {\n clearTimeout(reloadTimer);\n reloadTimer = null;\n }\n hot.off?.("vite:beforeUpdate", onBeforeUpdate);\n hot.off?.("vite:afterUpdate", onAfterUpdate);\n hot.off?.("vite:beforePrune", onBeforePrune);\n hot.off?.("vite:error", onViteError);\n };\n}\n\n// Self-install: this generated module is imported for side effects by the\n// host wrapper. `import.meta.hot` is undefined in production builds and in\n// Node test imports of the template, so both stay side-effect free.\nconst selfHot = (import.meta as { hot?: ViteHotLike }).hot;\nif (selfHot) {\n const uninstall = installCanvasHostViteRecovery({ hot: selfHot });\n selfHot.dispose?.(() => {\n uninstall();\n });\n}\n',hc="host-entry.tsx",mc="nuxt-board-environment.ts",fc='/* THIS FILE IS AUTO-GENERATED BY TEMPO. DO NOT EDIT. */\n/*\n * Nuxt sidecar host entry.\n *\n * The sidecar\'s TempoHostMount.vue calls mountTempoHost from onMounted with\n * the div it renders on the /tempo-host page, and calls the returned function\n * from onBeforeUnmount. The canvas host is a React tree inside that Vue page.\n * Vue storyboards get their Nuxt app context from the board environment,\n * configured here before the first board can prepare.\n */\nimport { createRoot } from "react-dom/client";\nimport { configureVueStoryboards } from "tempo-sdk/canvas/vue";\nimport { nuxtBoardEnvironment } from "./nuxt-board-environment";\nimport TempoHost from "./tempo-host";\n\n// Nuxt\'s pages and layouts plugins each warn once per Nuxt app that never\n// renders <NuxtPage /> or (when the app has layouts/) <NuxtLayout />. Every\n// board is its own Nuxt app rendering one component, never a page or a layout,\n// so both warnings fire for each board and say nothing about the user\'s app.\n// Nuxt 4 reports them as NUXT_E4011 and NUXT_E4007; Nuxt 3 prints the text\n// without a code.\nconst UNUSED_PAGE_OR_LAYOUT_WARNING_PREFIXES = [\n "[NUXT_E4011]",\n "[NUXT_E4007]",\n "[nuxt] Your project has pages but `<NuxtPage />` has not been detected",\n "[nuxt] Your project has layouts but `<NuxtLayout />` has not been detected",\n];\nconst UNUSED_PAGE_OR_LAYOUT_FILTER_KEY =\n "__tempoNuxtUnusedPageOrLayoutWarningFilter";\n\nfunction isUnusedPageOrLayoutWarning(args: unknown[]): boolean {\n const message = args[0];\n if (typeof message !== "string") return false;\n return UNUSED_PAGE_OR_LAYOUT_WARNING_PREFIXES.some((prefix) =>\n message.startsWith(prefix),\n );\n}\n\n// Installed once per document. Vite re-evaluates this module on HMR, and a\n// second wrapper would hide the first one\'s console.warn behind another frame.\nfunction filterUnusedPageOrLayoutWarnings(): void {\n const globals = globalThis as Record<string, unknown>;\n if (globals[UNUSED_PAGE_OR_LAYOUT_FILTER_KEY]) return;\n globals[UNUSED_PAGE_OR_LAYOUT_FILTER_KEY] = true;\n const warn = console.warn;\n console.warn = (...args: unknown[]) => {\n if (isUnusedPageOrLayoutWarning(args)) return;\n warn.apply(console, args);\n };\n}\n\nexport function mountTempoHost(element: HTMLElement): () => void {\n filterUnusedPageOrLayoutWarnings();\n configureVueStoryboards(nuxtBoardEnvironment);\n const root = createRoot(element);\n root.render(<TempoHost />);\n return () => root.unmount();\n}\n',gc="/* THIS FILE IS AUTO-GENERATED BY TEMPO. DO NOT EDIT. */\n/*\n * One Nuxt app context per Vue storyboard (the @storybook-vue/nuxt recipe).\n *\n * A board's component expects what a Nuxt page gets: the app's plugins\n * applied (provides such as $greet, pinia, i18n, and the router behind\n * <NuxtLink>), runtime config, and a useState store of its own. This file\n * runs inside the sidecar's Nuxt build, the only place `#build/plugins`\n * resolves, so the Tempo devserver generates it instead of tempo-sdk\n * shipping it.\n *\n * A board's Nuxt app goes with the board: tempo-sdk's VueStoryboard calls\n * `teardown` once the board's Vue app is unmounted or abandoned, and asks\n * which plugins are still running when a board's setup misses its deadline.\n */\nimport type {\n VueApp,\n VueStoryboardContext,\n VueStoryboardEnvironment,\n} from \"tempo-sdk/canvas/vue\";\nimport { getNuxtAppCtx } from \"#app/nuxt\";\n// Nuxt resolves #build/plugins to the client plugin list at build time and\n// ships no type declaration for it. Nuxt's own app entry imports it the same way.\n// @ts-ignore\nimport plugins from \"#build/plugins\";\n// tempo-sdk/nuxt's build template: each client plugin's source file, keyed by\n// the plugin, to name one whose setup never finishes.\n// @ts-ignore\nimport pluginSources from \"#build/tempo-board-plugin-sources.mjs\";\nimport { applyPlugins, createNuxtApp } from \"nuxt/app\";\n\ntype NuxtApp = ReturnType<typeof createNuxtApp>;\ntype NuxtPlugin = ((nuxtApp: NuxtApp) => unknown) & { _name?: string };\n\n/** What one board's Nuxt app holds outside its Vue app. */\ninterface NuxtBoard {\n nuxtApp: NuxtApp | null;\n /** Plugins whose setup started and has not settled, by source file. */\n runningPlugins: Set<string>;\n /** The step after the plugins, while it runs. */\n runningStep: string | null;\n /** Removes each global listener the board's code added. */\n releases: Array<() => void>;\n tornDown: boolean;\n}\n\nconst boards = new WeakMap<VueApp, NuxtBoard>();\n\nasync function setupNuxtBoard(\n app: VueApp,\n context: VueStoryboardContext,\n): Promise<void> {\n const board: NuxtBoard = {\n nuxtApp: null,\n runningPlugins: new Set(),\n runningStep: null,\n releases: [],\n tornDown: false,\n };\n boards.set(app, board);\n // Keyed on the render id (canvas path plus storyboard id), not the authored\n // storyboard id: two canvases in one document may both declare a \"Card\"\n // board, and a shared key would hand the later board the earlier one's app.\n const nuxtApp = recordingGlobalListeners(board, () =>\n createNuxtApp({ vueApp: app, id: `tempo-board-${context.renderId}` }),\n );\n board.nuxtApp = nuxtApp;\n // Nuxt runs every plugin, and the plugins' later context-bound work,\n // through runWithContext, so this is where the board's code runs.\n const runWithContext = nuxtApp.runWithContext;\n nuxtApp.runWithContext = <T extends () => unknown>(fn: T) => {\n const result = recordingGlobalListeners(board, () => runWithContext(fn));\n // A plugin still running after teardown (its board missed the setup\n // deadline) has just rebound the context through callWithNuxt, and may\n // have added listeners: release them again.\n if (board.tornDown) releaseBoard(board);\n return result as ReturnType<T>;\n };\n // Bind the board under its own id, never the default one. The default\n // context belongs to the /tempo-host page's own Nuxt app; replacing it would\n // point that page's composables at whichever board was prepared last.\n getNuxtAppCtx(nuxtApp._id).set(nuxtApp, true);\n await applyPlugins(\n nuxtApp,\n (plugins as NuxtPlugin[]).map((plugin) => trackedPlugin(plugin, board)),\n );\n board.runningStep = \"Nuxt's app:created hooks are\";\n await nuxtApp.hooks.callHook(\"app:created\", app);\n board.runningStep = \"Nuxt's app:beforeMount hooks are\";\n await nuxtApp.hooks.callHook(\"app:beforeMount\", app);\n board.runningStep = null;\n}\n\n/** Removes what the board bound outside its Vue app, which VueStoryboard\n * has unmounted by now (or never mounted). Without it every remount leaked a\n * whole Nuxt app through its context binding and its listeners. */\nfunction teardownNuxtBoard(app: VueApp): void {\n const board = boards.get(app);\n if (!board || board.tornDown) return;\n board.tornDown = true;\n releaseBoard(board);\n}\n\nfunction describePendingNuxtBoardSetup(app: VueApp): string | undefined {\n const board = boards.get(app);\n if (!board) return undefined;\n const running = [...board.runningPlugins];\n if (running.length === 1) {\n return `the Nuxt plugin ${running[0]} is still running`;\n }\n if (running.length > 1) {\n return `the Nuxt plugins ${running.join(\", \")} are still running`;\n }\n return board.runningStep ? `${board.runningStep} still running` : undefined;\n}\n\nexport const nuxtBoardEnvironment: VueStoryboardEnvironment = {\n setup: setupNuxtBoard,\n teardown: teardownNuxtBoard,\n describePendingSetup: describePendingNuxtBoardSetup,\n};\n\n/** The board's global listeners, its effect scope (the watchers its plugins\n * created) and its context binding. */\nfunction releaseBoard(board: NuxtBoard): void {\n for (const release of board.releases.splice(0)) release();\n const nuxtApp = board.nuxtApp;\n if (!nuxtApp) return;\n nuxtApp._scope.stop();\n // Only this board's own binding: a remount prepares the next app under the\n // same id before the old one is torn down.\n const nuxtAppContext = getNuxtAppCtx(nuxtApp._id);\n if (nuxtAppContext.tryUse() === nuxtApp) nuxtAppContext.unset();\n}\n\n/** `plugin`, noting while its setup runs so a board stuck in setup can name\n * it. Nuxt reads a plugin's metadata (hooks, parallel, dependsOn) off the\n * function itself, so the wrapper carries it over. */\nfunction trackedPlugin(plugin: NuxtPlugin, board: NuxtBoard): NuxtPlugin {\n const source: string =\n pluginSources.get(plugin) ?? plugin._name ?? \"(unnamed plugin)\";\n const tracked = (nuxtApp: NuxtApp) => {\n board.runningPlugins.add(source);\n const settled = () => {\n board.runningPlugins.delete(source);\n };\n try {\n const result = plugin(nuxtApp);\n const isAsync =\n typeof (result as PromiseLike<unknown> | null)?.then === \"function\";\n if (isAsync) return Promise.resolve(result).finally(settled);\n settled();\n return result;\n } catch (error) {\n settled();\n throw error;\n }\n };\n return Object.assign(tracked, plugin);\n}\n\n/** The board whose synchronous code is running right now, if any. */\nlet recordingBoard: NuxtBoard | null = null;\n\n/**\n * Runs `run`, recording against `board` every event listener and Vite HMR\n * handler it adds before it returns, so teardown can remove them. JavaScript\n * runs one synchronous stretch at a time, so what a stretch adds is the\n * board's own: createNuxtApp's chunk-error listener, the dev error overlay's\n * window and HMR handlers (its `nuxt:dev:error:clear` handler reloads the\n * whole page for an app that had an error), the router's history listeners.\n * What a plugin adds after an `await`, outside runWithContext, is not seen.\n */\nfunction recordingGlobalListeners<T>(board: NuxtBoard, run: () => T): T {\n const outerBoard = recordingBoard;\n recordingBoard = board;\n // A nested stretch (a plugin calling runWithContext) is already recorded.\n const restore = outerBoard ? null : installListenerRecorders();\n try {\n return run();\n } finally {\n recordingBoard = outerBoard;\n restore?.();\n }\n}\n\ninterface ViteHotContext {\n on(event: string, handler: (...args: unknown[]) => void): void;\n off?(event: string, handler: (...args: unknown[]) => void): void;\n}\n\n/** Patches listener registration for one stretch; returns the undo. */\nfunction installListenerRecorders(): () => void {\n const eventTarget = EventTarget.prototype;\n const addEventListener = eventTarget.addEventListener;\n eventTarget.addEventListener = function (\n this: EventTarget,\n type: string,\n listener: EventListenerOrEventListenerObject | null,\n options?: AddEventListenerOptions | boolean,\n ) {\n addEventListener.call(this, type, listener, options);\n if (!recordingBoard || !listener) return;\n recordingBoard.releases.push(() =>\n this.removeEventListener(type, listener, options),\n );\n };\n // Every module's import.meta.hot shares one prototype per document.\n const hotContext = (import.meta as { hot?: ViteHotContext }).hot;\n const hot: ViteHotContext | null = hotContext\n ? Object.getPrototypeOf(hotContext)\n : null;\n const on = hot?.on;\n if (hot && on) {\n hot.on = function (\n this: ViteHotContext,\n event: string,\n handler: (...args: unknown[]) => void,\n ) {\n on.call(this, event, handler);\n recordingBoard?.releases.push(() => this.off?.(event, handler));\n };\n }\n return () => {\n eventTarget.addEventListener = addEventListener;\n if (hot && on) hot.on = on;\n };\n}\n";import{fileURLToPath as yc,pathToFileURL as vc}from"url";import{spawn as Ec}from"child_process";import{createHash as Tc}from"crypto";import{constants as wc}from"fs";import{access as Sc,readdir as bc,readFile as Ac,realpath as _c,stat as kc}from"fs/promises";import{createServer as Ic,request as Cc}from"http";import{connect as Rc,createServer as Pc}from"net";import Nc from"path";import{pipeline as Oc}from"stream";import{StringDecoder as Dc}from"string_decoder";var Lc={versionTimeoutMs:2e4,startTimeoutMs:3e5,bootstrapTimeoutMs:15e3,reloadTimeoutMs:6e4,stopGraceMs:5e3,killGraceMs:3e3,sourceDebounceMs:150},Mc=50,xc={lines:30,chars:4e3,lineChars:400,stallMs:6e4},Fc=new Set(["app-error","daemon-error","stderr"]);function selectFlutterRecentOutput(e){const t=e.limits??xc,n=recentOutputReason(e,t.stallMs);if(null===n||0===e.tail.length)return null;const r=[];let s=0;for(const{text:n}of[...e.tail].reverse()){if(r.length===t.lines)break;const e=n.length>t.lineChars?`${n.slice(0,t.lineChars-1)}…`:n,i=e.length+(r.length>0?1:0);if(s+i>t.chars)break;r.unshift(e),s+=i}return{reason:n,lines:r,omitted:e.tail.length-r.length}}function recentOutputReason(e,t){const{status:n,statusSince:r,tail:s,now:i}=e;if("failed"===n.state)return"failed";if("starting"===n.state){const e=Math.max(r,s.at(-1)?.at??0);return i-e>=t?"stalled":null}if("ready"===n.state){const e=s.some(e=>e.at>=r&&Fc.has(e.source));return e?"errors_since_ready":null}return null}var Bc=class{constructor(e){this.currentStatus={state:"stopped"},this.statusListeners=new Set,this.startPromise=null,this.gatePromise=null,this.stopRequested=!1,this.binary=null,this.daemon=null,this.spawnCount=0,this.readyCount=0,this.launchedPackageGraph=null,this.compiledSourceStamps=new Map,this.attemptedSourceStamps=new Map,this.previewKeys=[],this.lastReload=null,this.outputTail=[],this.statusSince=Date.now(),this.observedSdkMissingLine=null,this.observedPortInUse=!1,this.localSourceDirectories=[],this.previewProblems=[],this.resolutionRevision=0,this.resolutionSignature="",this.sourceDebounceTimer=null,this.pendingSourcePaths=new Set,this.sourceSyncPromise=null,this.reloadChain=Promise.resolve(),this.gate=new Vc(()=>this.gateRoute(),new Map([[Gc,()=>({statusCode:200,body:this.gateStatus()})],[qc,e=>readSourceLineTable({tempoRoot:this.options.hostRoot??this.options.tempoRoot,packageDirs:this.options.packages.map(e=>e.dir),file:e.get("file")})]])),this.loggedOnce=new Set,this.options={...e,projectRoot:canonicalPathAllowMissing(e.projectRoot),packages:e.packages.map(e=>({...e,dir:canonicalPathAllowMissing(e.dir)}))},this.timing={...Lc,...e.timing},this.env=e.env??process.env,this.hostDir=Nc.join(e.tempoRoot,ri),this.url=`http://127.0.0.1:${e.port}`}status(){return this.currentStatus}onStatusChange(e){return this.statusListeners.add(e),notifyStatusListener(e,this.currentStatus),()=>{this.statusListeners.delete(e)}}snapshot(){return{status:this.currentStatus,url:this.url,flutterRunUrl:this.daemon?loopbackUrl(this.daemon.port):null,spawn:this.spawnCount,packages:this.options.packages.map(e=>({...e,dir:toPosix2(Nc.relative(this.options.projectRoot,e.dir))||"."})),previewProblems:this.previewProblems,resolutionRevision:this.resolutionRevision,hostDir:this.hostDir,flutterBinary:this.binary?.path??null,flutterVersion:this.binary?.version??null,pid:this.daemon?.pid??null,appId:this.daemon?.appId??null,previewKeys:[...this.previewKeys],lastReload:this.lastReload,recentOutputTail:this.tailText()}}openGate(){return this.gatePromise??=this.gate.listen(this.options.port)}start(){return this.startPromise||(this.startPromise=this.performStart()),this.startPromise}async stop(){this.stopRequested=!0,this.cancelPendingSourceSync(),await this.gate.close(),await(this.daemon?.stop(this.timing.stopGraceMs,this.timing.killGraceMs)),await this.sourceSyncPromise,this.setStatus({state:"stopped"})}forceKill(){this.stopRequested=!0,this.cancelPendingSourceSync(),this.gate.close(),this.daemon?.forceKill(),this.setStatus({state:"stopped"})}reload(e){const t=this.reloadChain.then(()=>this.performReload(e));return this.reloadChain=t.catch(()=>{}),t}async performStart(){this.setStatus({state:"starting",message:null});try{await this.openGate()}catch(e){if(this.stopRequested)return;const t=e instanceof Error?e.message:String(e),n=new xs(`Could not listen on ${this.url} (${t}).`,"");throw await this.fail(n),n}this.stopRequested?await this.gate.close():0!==this.options.packages.length?await this.startEngine():this.setStatus({state:"failed",error:{code:"flutter_previews_unresolved",message:"No Flutter preview resolves yet. Fix the reported preview paths or functions."}})}async startEngine(){let e;try{e=await resolveFlutterBinary(this.env,this.timing.versionTimeoutMs,[...this.options.packages.map(e=>e.dir),this.options.projectRoot])}catch(e){if(this.stopRequested)return;const t=this.toTypedError(e);throw await this.fail(t),t}this.binary=e,devLog("flutter:sdk_resolved",{binary:e.path,version:e.version}),this.stopRequested||await this.bringUp(e)}async bringUp(e){this.setStatus({state:"starting",message:null});try{this.launchedPackageGraph=await readPackageGraphFingerprint(this.sourceDirectories(),this.options.projectRoot);const t=(await Promise.all(this.sourceDirectories().map(e=>listDartFiles(Nc.join(e,"lib"))))).flat().map(e=>Nc.relative(this.options.projectRoot,e)),n=await this.readSourceStamps(t);this.attemptedSourceStamps=n,await this.regenerateHost(),await this.runUntilStarted(e),this.rememberCompiled(n);try{const e=Nc.join(this.hostDir,".dart_tool","package_config.json"),t=JSON.parse(await Ac(e,"utf8"));this.localSourceDirectories=t.packages.flatMap(t=>{const n=new URL(t.rootUri,vc(e));if("file:"!==n.protocol)return[];const r=yc(n);return isInsideDirectory(this.options.projectRoot,r)&&!isInsideDirectory(canonicalPathAllowMissing(this.hostDir),r)?[r.replace(/[\\/]$/,"")]:[]})}catch{this.localSourceDirectories=[]}if(this.stopRequested)return;this.setStatus({state:"ready",readyCount:++this.readyCount}),devLog("flutter:ready",{url:this.url,appId:this.daemon?.appId}),this.flushSourceChanges()}catch(e){if(this.stopRequested)return;const t=this.toTypedError(e);throw await this.fail(t),t}}async relaunch(e){const t=this.binary;if(!t||this.stopRequested)return;devLog("flutter:relaunch",{reason:e}),this.setStatus({state:"starting",message:null});const n=this.daemon;this.daemon=null,await(n?.stop(this.timing.stopGraceMs,this.timing.killGraceMs)),await this.startEngine().catch(e=>this.fail(this.toTypedError(e)))}async runUntilStarted(e){let t=!1,n=!1;for(;;){const r=await this.launchDaemon(e);if("started"===r.kind||"stopped"===r.kind)return;if("port-in-use"===r.kind&&!t){t=!0,devLog("flutter:run_retry",{reason:"port-in-use"});continue}const s="exited-before-start"===r.kind||"port-in-use"===r.kind;if(!s||n)throw r.error;n=!0,devLog("flutter:run_retry",{message:r.error.message})}}async launchDaemon(e){const t=await this.ensureWatchdogScript();if(this.stopRequested)return{kind:"stopped"};this.observedSdkMissingLine=null,this.observedPortInUse=!1,this.outputTail.length=0;const n=await allocateLoopbackPort();if(this.stopRequested)return{kind:"stopped"};const r=new Uc({binary:e,cwd:this.hostDir,port:n,env:this.env,watchdogScriptPath:t,onLine:(e,t)=>this.recordOutput(e,t),onProgress:e=>{"starting"===this.currentStatus.state&&e&&this.setStatus({state:"starting",message:e})}});this.daemon=r,this.spawnCount+=1,devLog("flutter:spawned",{spawn:this.spawnCount,pid:r.pid,port:this.options.port,runPort:n,watchdog:null!==t});const s=await raceWithTimeout(Promise.race([r.started.then(()=>"started"),r.exited.then(()=>"exited")]),this.timing.startTimeoutMs);if(this.stopRequested)return{kind:"stopped"};if("exited"===s){const e=r.exitInfo();return{kind:this.observedPortInUse?"port-in-use":"exited-before-start",error:this.observedSdkMissingLine?new Ls(`running it printed "${this.observedSdkMissingLine}".`):new xs(`flutter run exited (${describeExit(e)}) before the Flutter app started.`,this.tailText())}}if("timeout"===s)return await r.stop(this.timing.stopGraceMs,this.timing.killGraceMs),{kind:"timed-out",error:new xs(`flutter run did not report app.started within ${Math.round(this.timing.startTimeoutMs/1e3)} s.`,this.tailText())};const i=loopbackUrl(n),a=await waitForBootstrap(i,this.timing.bootstrapTimeoutMs,()=>r.isRunning()&&!this.stopRequested);return this.stopRequested?{kind:"stopped"}:a?(r.exited.then(e=>this.onDaemonExitAfterStart(r,e)),{kind:"started"}):(await r.stop(this.timing.stopGraceMs,this.timing.killGraceMs),{kind:"not-serving",error:new xs(`flutter run reported app.started but ${i}/flutter_bootstrap.js never answered 200.`,this.tailText())})}onDaemonExitAfterStart(e,t){this.daemon!==e||this.stopRequested||this.fail(new xs(`flutter run exited (${describeExit(t)}) after the Flutter app had started.`,this.tailText()))}async fail(e){this.setStatus({state:"failed",error:{code:e.code,message:e.message}}),devLog("flutter:failed",{code:e.code,message:e.message}),this.flushSourceChanges()}toTypedError(e){if(e instanceof Ts)return e;const t=e instanceof Error?e.message:String(e);return new xs(t,this.tailText())}gateRoute(){const e=this.currentStatus;if("failed"===e.state)return{kind:"failed",...e.error};const t=this.daemon,n="ready"===e.state||"reloading"===e.state;return n&&t?.isRunning()?{kind:"forward",port:t.port}:"starting"===e.state?{kind:"starting",message:e.message??"Starting Flutter"}:{kind:"starting",message:Wc}}gateStatus(){const e=this.currentStatus;return{status:"stopped"===e.state?"starting":e.state,spawn:this.spawnCount,readyCount:this.readyCount,previewProblems:this.previewProblems,resolutionRevision:this.resolutionRevision,error:"failed"===e.state?e.error.code:null,message:"starting"===e.state?e.message:"failed"===e.state?e.error.message:null}}async regenerateHost(){const e=await ensureFlutterHost({tempoRoot:this.options.tempoRoot,packages:this.options.packages,hostRoot:this.options.hostRoot,flutterSdkRoot:this.binary?.sdkRoot??null});"bundled"!==e.roboto&&this.logOnce(`roboto:${e.roboto}`,"flutter:roboto_not_bundled",{reason:e.roboto,sdkRoot:this.binary?.sdkRoot??null}),this.previewKeys=e.previews.map(e=>e.key),e.writtenFiles.length>0&&devLog("flutter:host_written",{files:e.writtenFiles.map(e=>toPosix2(Nc.relative(this.hostDir,e))),previewKeys:this.previewKeys});for(const t of e.userOwnedFiles)this.logOnce(`user-owned:${t}`,"flutter:host_file_user_owned",{file:t});for(const t of e.skipped)this.logOnce(`skipped:${t.file}#${t.name??t.line}:${t.reason}`,"flutter:preview_skipped",{...t});return{previewsChanged:e.previewsChanged}}sourceDirectories(){return[...new Set([...this.options.packages.map(e=>e.dir),...this.localSourceDirectories])]}async updatePreviews(e,t){if(this.stopRequested)return;const n=JSON.stringify({packages:e.packages.map(e=>[e.dir,e.name]),problems:e.problems,boards:e.boards}),r=JSON.stringify(this.options.packages)!==JSON.stringify(e.packages.map(({dir:e,name:t})=>({dir:e,name:t})));if(this.options.packages=e.packages.map(({dir:e,name:t})=>({dir:e,name:t})),n!==this.resolutionSignature&&(this.resolutionSignature=n,this.previewProblems=e.problems,this.resolutionRevision++),this.startPromise&&0!==this.options.packages.length){if(!this.binary&&"failed"===this.currentStatus.state)return this.setStatus({state:"starting",message:null}),void this.startEngine().catch(e=>this.fail(this.toTypedError(e)));r&&this.compiledSourceStamps.clear(),this.sourceFilesChanged(r?[...t,"pubspec.yaml"]:t)}}sourceFilesChanged(e){if(!this.stopRequested){for(const t of e)this.pendingSourcePaths.add(t);this.sourceDebounceTimer&&clearTimeout(this.sourceDebounceTimer),this.sourceDebounceTimer=setTimeout(()=>{this.sourceDebounceTimer=null,this.flushSourceChanges()},this.timing.sourceDebounceMs),this.sourceDebounceTimer.unref?.()}}cancelPendingSourceSync(){this.sourceDebounceTimer&&clearTimeout(this.sourceDebounceTimer),this.sourceDebounceTimer=null,this.pendingSourcePaths.clear()}flushSourceChanges(){if(this.sourceSyncPromise)return this.sourceSyncPromise;const e=this.performSourceSync();return this.sourceSyncPromise=e,e.then(()=>{this.sourceSyncPromise===e&&(this.sourceSyncPromise=null)},()=>{this.sourceSyncPromise===e&&(this.sourceSyncPromise=null)}),e}async performSourceSync(){for(;this.pendingSourcePaths.size>0&&!this.stopRequested;){const e=this.currentStatus.state;if("failed"===e){const e=[...this.pendingSourcePaths];this.pendingSourcePaths.clear();const t=await this.readSourceStamps(e),n=await readPackageGraphFingerprint(this.sourceDirectories(),this.options.projectRoot);if(n===this.launchedPackageGraph&&e.every(e=>(this.attemptedSourceStamps.get(e)??"missing")===t.get(e)))continue;await this.relaunch("source-change-after-failure"),"ready"===this.status().state&&this.rememberCompiled(t);continue}if("ready"!==e)break;const t=[...this.pendingSourcePaths];this.pendingSourcePaths.clear(),await this.applySourceChanges(t)}}async applySourceChanges(e){e=(await Promise.all(e.map(async e=>{const t=Nc.join(this.options.projectRoot,e);return/(^|[/\\])\.fvm([/\\]|$)/.test(e)?[e]:(await kc(t).catch(()=>null))?.isDirectory()?[e,...(await listDartFiles(t)).map(e=>Nc.relative(this.options.projectRoot,e))]:[e]}))).flat();const t=await this.readSourceStamps(e),n=e.filter(e=>!this.isCompiledAsIs(e,t.get(e)??null));if(0===n.length)return void devLog("flutter:sources_already_compiled",{reported:e});const r=n.some(e=>isPackageGraphFile(e)||!e.endsWith(".dart")),s=r&&await readPackageGraphFingerprint(this.sourceDirectories(),this.options.projectRoot)!==this.launchedPackageGraph;r&&!s&&devLog("flutter:package_graph_unchanged",{changed:n});const i=n.some(e=>e.endsWith(".dart"));let a;try{({previewsChanged:a}=await this.regenerateHost())}catch(e){return void devLog("flutter:host_regenerate_failed",{message:e instanceof Error?e.message:String(e)})}const o=chooseSourceChangeAction({packageGraphChanged:s,previewsChanged:a,sourcesChanged:i});if("none"===o)return;if("relaunch"===o)return await this.relaunch("package-graph-changed"),void("ready"===this.status().state&&this.rememberCompiled(t));const c=await this.reload(o),l="hot"===o&&c.rejected,d=l?await this.reload("restart"):c;d.ok&&this.rememberCompiled(t)}async readSourceStamps(e){const t=new Map;for(const n of e){const e=Nc.join(this.options.projectRoot,n);t.set(n,await sourceStampOf(e))}return t}isCompiledAsIs(e,t){const n=this.compiledSourceStamps.get(e);return null!==t&&n===t}rememberCompiled(e){for(const[t,n]of e)null!==n&&this.compiledSourceStamps.set(t,n)}async performReload(e){const t=Date.now(),n=this.daemon,r=n?.appId??null;if(this.stopRequested||!n||!r||"ready"!==this.currentStatus.state)return this.recordReload({kind:e,ok:!1,rejected:!1,code:null,message:`Flutter is ${this.currentStatus.state}; nothing to reload.`,durationMs:0,at:t});this.setStatus({state:"reloading",kind:e});const s=await n.request("app.restart",{appId:r,fullRestart:"restart"===e,reason:"save",pause:!1},this.timing.reloadTimeoutMs);return"reloading"===this.status().state&&this.setStatus({state:"ready",readyCount:++this.readyCount}),this.recordReload({kind:e,...describeRestartResponse(s),durationMs:Date.now()-t,at:Date.now()})}recordReload(e){return this.lastReload=e,devLog("flutter:reload",{...e}),e}recordOutput(e,t){const n=e.trimEnd();if(!n)return;this.outputTail.push({text:n,source:t,at:Date.now()}),this.outputTail.length>Mc&&this.outputTail.shift(),devLog("flutter:output",{source:t,line:n.slice(0,1e3)});const r=classifyDevServerOutput(n);"flutter_sdk_missing"===r?.errorCode&&(this.observedSdkMissingLine=r.line),"port-in-use"===r?.class&&(this.observedPortInUse=!0)}tailText(){return this.outputTail.map(e=>e.text).join("\n")}recentOutput(e=Date.now()){return selectFlutterRecentOutput({status:this.currentStatus,statusSince:this.statusSince,tail:this.outputTail,now:e})}setStatus(e){const t=!sameFlutterStatus(this.currentStatus,e);if(this.currentStatus=e,t){this.statusSince=Date.now();for(const t of[...this.statusListeners])notifyStatusListener(t,e)}}logOnce(e,t,n){this.loggedOnce.has(e)||(this.loggedOnce.add(e),devLog(t,n))}async ensureWatchdogScript(){if("0"===this.env.TEMPO_DEVSERVER_WATCHDOG)return null;const e=Nc.join(this.options.tempoRoot,".tempo",jc);try{const t=await readTextFileOptional2(e);return t!==$c&&await atomicWriteText2(e,$c),e}catch(t){return devLog("flutter:watchdog_write_failed",{scriptPath:e,message:t instanceof Error?t.message:String(t)}),null}}};function sameFlutterStatus(e,t){return e.state===t.state&&("starting"===e.state&&"starting"===t.state?e.message===t.message:"reloading"===e.state&&"reloading"===t.state?e.kind===t.kind:"failed"===e.state&&"failed"===t.state?e.error.code===t.error.code&&e.error.message===t.error.message:"ready"!==e.state||"ready"!==t.state||e.readyCount===t.readyCount)}function notifyStatusListener(e,t){try{e(t)}catch(e){devLog("flutter:status_listener_failed",{message:e instanceof Error?e.message:String(e)})}}function chooseSourceChangeAction(e){return e.packageGraphChanged?"relaunch":e.previewsChanged?"restart":e.sourcesChanged?"hot":"none"}async function readPackageGraphFingerprint(e,t){const n=Tc("sha256"),r=new Set;for(const n of[...e,...await flutterWorkspaceDirectories(e)])for(let e=n;(isInsideDirectory(t,e)||e===t)&&(r.add(e),e!==t&&Nc.dirname(e)!==e);e=Nc.dirname(e));for(const e of[...r].sort()){n.update(e);for(const t of["pubspec.yaml","pubspec_overrides.yaml",".fvmrc",".fvm/fvm_config.json"]){const r=await readTextFileOptional2(Nc.join(e,t));n.update(`${t}\0${r??"\0missing"}\0`)}n.update(await _c(Nc.join(e,".fvm","flutter_sdk")).catch(()=>"missing-sdk"))}return n.digest("hex")}var Hc=new Set(["pubspec.yaml","pubspec_overrides.yaml",".fvmrc","fvm_config.json","flutter_sdk"]);function isPackageGraphFile(e){return Hc.has(Nc.posix.basename(e))}async function sourceStampOf(e){const t=await kc(e,{bigint:!0}).catch(()=>null);return null===t?"missing":t.isFile()?`${t.size}:${t.mtimeNs}`:null}function describeRestartResponse(e){if("timed-out"===e.kind)return{ok:!1,rejected:!1,code:null,message:"app.restart timed out"};if("exited"===e.kind)return{ok:!1,rejected:!1,code:null,message:"flutter run exited"};if(void 0!==e.error)return{ok:!1,rejected:!0,code:null,message:stringify(e.error)};const t=e.result,n="number"==typeof t?.code?t.code:null,r="string"==typeof t?.message?t.message:"";return{ok:0===n,rejected:null!==n&&0!==n,code:n,message:r}}async function resolveFlutterBinary(e,t=Lc.versionTimeoutMs,n=[]){const r=(await locateFlutterBinary(e,n)).path,s="win32"===process.platform&&/\.(bat|cmd)$/i.test(r),i=await runCommandWithTimeout(r,["--version","--machine"],{env:childEnv(e),useShell:s,timeoutMs:t});if(i.timedOut)throw new Ls(`\`${r} --version --machine\` did not answer within ${Math.round(t/1e3)} s. A fresh SDK downloads its Dart SDK on first use, and another flutter command can hold the SDK lock; run \`flutter --version\` in a terminal once. Output: ${lastLines(i.output,5)||"(none)"}`);if(0!==i.exitCode)throw new Ls(`\`${r} --version --machine\` failed (${i.spawnError??`exit ${i.exitCode}`}): ${lastLines(i.output,5)||"(no output)"}.`);const a=parseFlutterVersionJson(i.output);return{path:r,version:a.version,useShell:s,sdkRoot:a.sdkRoot}}async function locateFlutterBinary(e,t=[]){const n=e.TEMPO_FLUTTER_BIN?.trim();if(n)return{path:await checkFlutterOverride(n),source:"TEMPO_FLUTTER_BIN"};const r=t.at(-1),s=[];for(const e of t.length>1?t.slice(0,-1):t){let t=e;for(;;){const readPin=async(e,n)=>{const r=await readTextFileOptional2(Nc.join(t,e));if(null===r)return null;try{const e=JSON.parse(r)[n];return"string"==typeof e?e:null}catch{throw new Ls(`Invalid Flutter SDK pin at ${Nc.join(t,e)}. Fix its JSON before starting previews.`)}},e=await readPin(".fvmrc","flutter")??await readPin(".fvm/fvm_config.json","flutterSdkVersion"),n=await findProjectPinnedFlutter([t]);if(e||n){s.push({dir:t,pin:e,binary:n,version:n?await readFlutterSdkVersion(n):null,identity:n?await flutterSdkIdentity(n):`pin:${e}`});break}if(!r||t===r||Nc.dirname(t)===t)break;t=Nc.dirname(t)}}const i=new Set(s.map(e=>e.identity));if(i.size>1)throw new Ts("flutter_sdk_conflict",`Flutter packages require different SDKs: ${s.map(e=>`${e.dir}: ${e.pin??e.version??"unknown"}`).join(", ")}. Align their pins or explicitly set TEMPO_FLUTTER_BIN.`);if(s.some(e=>e.pin&&!e.binary))throw new Ls(`Install the pinned Flutter SDK for ${s.filter(e=>!e.binary).map(e=>`${e.dir} (${e.pin})`).join(", ")}.`);const a=s.find(e=>e.binary)?.binary;return a?{path:a,source:"fvm"}:{path:await findFlutterOnPath(e),source:"PATH"}}async function readFlutterSdkVersion(e){try{const t=await _c(e),n=Nc.join(Nc.dirname(t),"cache","flutter.version.json"),r=JSON.parse(await Ac(n,"utf-8")),s=r.frameworkVersion??r.flutterVersion;return"string"==typeof s&&s.trim()?s.trim():null}catch{return null}}async function flutterSdkIdentity(e){const t=await _c(e);try{const e=JSON.parse(await Ac(Nc.join(Nc.dirname(t),"cache","flutter.version.json"),"utf8")),n=e.frameworkVersion??e.flutterVersion;if("string"==typeof n)return`${n}:${e.frameworkRevision??""}`}catch{}return t}async function checkFlutterOverride(e){const t=Nc.resolve(e),n=await kc(t).catch(()=>null);if(!n?.isFile())throw new Ls(`TEMPO_FLUTTER_BIN is set to ${t}, which does not exist.`);if(!await isExecutable(t))throw new Ls(`TEMPO_FLUTTER_BIN is set to ${t}, which is not executable.`);return t}async function findProjectPinnedFlutter(e){const t="win32"===process.platform?"flutter.bat":"flutter";for(const n of new Set(e)){const e=Nc.join(n,".fvm","flutter_sdk","bin",t),r=await kc(e).catch(()=>null);if(r?.isFile()&&await isExecutable(e))return e}return null}async function findFlutterOnPath(e){const t=Object.keys(e).find(e=>"path"===e.toLowerCase())??"PATH",n=(e[t]??"").split(Nc.delimiter).filter(e=>e.length>0),r="win32"===process.platform?["flutter.bat","flutter.exe","flutter"]:["flutter"];for(const e of n)for(const t of r){const n=Nc.join(e,t),r=await kc(n).catch(()=>null);if(r?.isFile()&&await isExecutable(n))return n}throw new Ls("`flutter` is not on PATH.")}async function isExecutable(e){if("win32"===process.platform)return!0;try{return await Sc(e,wc.X_OK),!0}catch{return!1}}function parseFlutterVersionJson(e){const t=e.indexOf("{"),n=e.lastIndexOf("}");if(-1===t||n<=t)return{version:null,sdkRoot:null};try{const r=JSON.parse(e.slice(t,n+1)),s=r.flutterVersion??r.frameworkVersion;return{version:"string"==typeof s?s:null,sdkRoot:"string"==typeof r.flutterRoot&&r.flutterRoot?r.flutterRoot:null}}catch{return{version:null,sdkRoot:null}}}async function runCommandWithTimeout(e,t,n){return await new Promise(r=>{let s="",i=!1;const a=Ec(n.useShell?quoteForCmd(e):e,t,{env:n.env,shell:n.useShell,stdio:["ignore","pipe","pipe"],windowsHide:!0}),finish=e=>{i||(i=!0,clearTimeout(o),r({...e,output:s}))},o=setTimeout(()=>{a.kill("SIGKILL"),finish({exitCode:null,timedOut:!0,spawnError:null})},n.timeoutMs);a.stdout?.on("data",e=>{s+=String(e)}),a.stderr?.on("data",e=>{s+=String(e)}),a.on("error",e=>finish({exitCode:null,timedOut:!1,spawnError:e.message})),a.on("exit",e=>finish({exitCode:e,timedOut:!1,spawnError:null}))})}var Uc=class{constructor(e){this.appId=null,this.resolveStarted=()=>{},this.exit=null,this.nextRequestId=1,this.pendingRequests=new Map,this.stdoutDecoder=new Dc("utf8"),this.stderrDecoder=new Dc("utf8"),this.stdoutRemainder="",this.stderrRemainder="",this.onLine=e.onLine,this.onProgress=e.onProgress,this.port=e.port,this.usesWatchdog=null!==e.watchdogScriptPath,this.started=new Promise(e=>{this.resolveStarted=e});const t=["run","-d","web-server","--machine",`--web-port=${e.port}`,"--web-hostname=127.0.0.1"];this.child=spawnFlutter(e,t);let resolveExited=()=>{};this.exited=new Promise(e=>{resolveExited=e});const onExit=e=>{if(this.exit)return;this.exit=e;for(const e of this.pendingRequests.values())e({kind:"exited"});this.pendingRequests.clear();const t=new Promise(e=>{this.child.once("close",()=>e()),setTimeout(e,1e3).unref?.()});t.then(()=>{this.flushTrailingOutput(),resolveExited(e)})};this.child.on("exit",(e,t)=>onExit({code:e,signal:t})),this.child.on("error",e=>{this.onLine(`failed to spawn flutter: ${e.message}`,"spawn"),onExit({code:null,signal:null})}),this.child.stdin?.on("error",()=>{}),this.child.stdout?.on("data",e=>this.onStdout(this.stdoutDecoder.write(e))),this.child.stderr?.on("data",e=>this.onStderr(this.stderrDecoder.write(e)))}get pid(){return this.child.pid??null}isRunning(){return null===this.exit}exitInfo(){return this.exit??{code:null,signal:null}}request(e,t,n){if(!this.isRunning()||!this.child.stdin?.writable)return Promise.resolve({kind:"exited"});const r=this.nextRequestId;return this.nextRequestId+=1,new Promise(s=>{const i=setTimeout(()=>{this.pendingRequests.delete(r),s({kind:"timed-out"})},n);this.pendingRequests.set(r,e=>{clearTimeout(i),s(e)}),this.child.stdin?.write(`${JSON.stringify([{id:r,method:e,params:t}])}\n`)})}async stop(e,t){this.isRunning()&&(this.appId&&(this.request("app.stop",{appId:this.appId},e),await this.waitForExit(e))||(this.signal("SIGTERM"),await this.waitForExit(t)||(this.signal("SIGKILL"),await this.waitForExit(t))))}forceKill(){if(this.isRunning())if(this.usesWatchdog){try{this.child.stdin?.destroy()}catch{}this.signal("SIGTERM")}else this.signal("SIGKILL")}async waitForExit(e){const t=await raceWithTimeout(this.exited,e);return"timeout"!==t}signal(e){const t=this.child.pid;if(t){if("win32"===process.platform){const n=["/pid",String(t),"/t"];"SIGKILL"===e&&n.push("/f");try{Ec("taskkill",n,{stdio:"ignore",windowsHide:!0}).on("error",()=>{})}catch{}return}try{process.kill(-t,e)}catch{try{this.child.kill(e)}catch{}}}}onStdout(e){const t=(this.stdoutRemainder+e).split(/\r?\n/);this.stdoutRemainder=t.pop()??"";for(const e of t)this.onStdoutLine(e)}onStderr(e){const t=(this.stderrRemainder+e).split(/\r?\n/);this.stderrRemainder=t.pop()??"";for(const e of t)this.onLine(e,"stderr")}flushTrailingOutput(){const e=this.stdoutRemainder+this.stdoutDecoder.end(),t=this.stderrRemainder+this.stderrDecoder.end();this.stdoutRemainder="",this.stderrRemainder="",e&&this.onStdoutLine(e),t&&this.onLine(t,"stderr")}onStdoutLine(e){const t=parseDaemonLine(e);if(null!==t)for(const e of t)this.onMessage(e);else this.onLine(e,"stdout")}onMessage(e){if("string"==typeof e.event)return void this.onEvent(e.event,e.params??{});if("number"!=typeof e.id)return;const t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),t({kind:"answered",result:e.result,error:e.error}))}onEvent(e,t){"app.start"!==e||"string"!=typeof t.appId?"app.started"!==e?"app.progress"!==e?"app.log"!==e||"string"!=typeof t.log?"daemon.logMessage"===e&&"string"==typeof t.message&&this.onLine(t.message,`daemon-${String(t.level??"log")}`):this.onLine(t.log,!0===t.error?"app-error":"app"):this.onProgress("string"==typeof t.message?t.message:null):this.resolveStarted():this.appId=t.appId}};function parseDaemonLine(e){const t=e.trim();if(!t.startsWith("[{")||!t.endsWith("}]"))return null;try{const e=JSON.parse(t);return Array.isArray(e)?e.filter(e=>null!==e&&"object"==typeof e):null}catch{return null}}function spawnFlutter(e,t){const n=e.binary.useShell?quoteForCmd(e.binary.path):e.binary.path,r="win32"!==process.platform;if(e.watchdogScriptPath){const s=JSON.stringify({command:n,args:t,shell:e.binary.useShell});return Ec(process.execPath,[e.watchdogScriptPath,s],{cwd:e.cwd,detached:r,stdio:["pipe","pipe","pipe"],windowsHide:!0,env:{...e.env,ELECTRON_RUN_AS_NODE:"1"}})}return Ec(n,t,{cwd:e.cwd,detached:r,shell:e.binary.useShell,stdio:["pipe","pipe","pipe"],windowsHide:!0,env:childEnv(e.env)})}function childEnv(e){const{ELECTRON_RUN_AS_NODE:t,...n}=e;return n}function quoteForCmd(e){return/\s/.test(e)?`"${e}"`:e}var jc="flutter-watchdog.cjs",$c='// Generated by Tempo — do not edit.\n// Relays daemon commands to `flutter run --machine` and kills it when the\n// Tempo app\'s end of this process\'s stdin closes: flutter run itself keeps\n// running after its parent dies.\n"use strict";\nconst { spawn, spawnSync } = require("node:child_process");\n\nconst launch = JSON.parse(process.argv[2]);\nconst env = { ...process.env };\ndelete env.ELECTRON_RUN_AS_NODE;\n\nconst child = spawn(launch.command, launch.args, {\n shell: launch.shell === true,\n detached: process.platform !== "win32",\n windowsHide: true,\n stdio: ["pipe", "inherit", "inherit"],\n env,\n});\n\nlet killed = false;\nfunction killTree() {\n if (killed || child.pid == null) return;\n killed = true;\n if (process.platform === "win32") {\n spawnSync("taskkill", ["/pid", String(child.pid), "/t", "/f"], {\n stdio: "ignore",\n windowsHide: true,\n });\n } else {\n try { process.kill(-child.pid, "SIGKILL"); } catch {}\n try { process.kill(child.pid, "SIGKILL"); } catch {}\n }\n}\n\nchild.on("error", (error) => {\n process.stderr.write("flutter-watchdog: " + error.message + "\\n");\n process.exit(127);\n});\nchild.on("exit", (code) => process.exit(code === null ? 1 : code));\nchild.stdin.on("error", () => {});\n\nprocess.stdin.on("data", (chunk) => child.stdin.write(chunk));\nconst onParentGone = () => {\n killTree();\n process.exit(0);\n};\nprocess.stdin.on("end", onParentGone);\nprocess.stdin.on("close", onParentGone);\nprocess.stdin.on("error", onParentGone);\nfor (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {\n process.on(signal, onParentGone);\n}\n',Gc="/__tempo_flutter_status",qc="/__tempo_flutter_source",Wc="flutter run is not answering; retry shortly.",Vc=class{constructor(e,t){this.server=null,this.upstreamRequests=new Set,this.upgradedSockets=new Set,this.route=e,this.endpoints=t}async listen(e){const t=Ic((e,t)=>{try{this.onRequest(e,t)}catch(n){answerGateError(e,t,n)}});t.on("upgrade",(e,t,n)=>{try{this.onUpgrade(e,t,n)}catch(n){logGateError(e,n),t.destroy()}}),t.on("clientError",(e,t)=>t.destroy()),await new Promise((n,r)=>{t.once("error",r),t.listen(e,"127.0.0.1",()=>{t.off("error",r),n()})}),t.unref(),this.server=t}async close(){const e=this.server;this.server=null;for(const e of this.upstreamRequests)e.destroy();this.upstreamRequests.clear();for(const e of this.upgradedSockets)e.destroy();if(this.upgradedSockets.clear(),!e)return;const t=new Promise(t=>e.close(()=>t()));e.closeAllConnections(),await t}onRequest(e,t){const{pathname:n,query:r}=splitRequestUrl(e.url),s=this.endpoints.get(n);if(s)return e.resume(),void Promise.resolve().then(()=>s(r)).then(e=>answerJson(t,e.statusCode,e.body),n=>answerGateError(e,t,n));const i=this.route();if("forward"===i.kind)return void this.forwardRequest(e,t,i.port);e.resume();const a="failed"===i.kind?i.code:"flutter_starting";answerJson(t,503,{error:a,message:i.message})}onUpgrade(e,t,n){const r=this.route(),s=this.endpoints.has(splitRequestUrl(e.url).pathname);"forward"!==r.kind||s?t.destroy():this.forwardUpgrade(e,t,n,r.port)}forwardRequest(e,t,n){const r=Cc({hostname:"127.0.0.1",port:n,method:e.method,path:e.url??"/",headers:{...endToEndHeaders(e.headers),host:`127.0.0.1:${n}`},agent:!1},n=>{try{const e=endToEndHeaders(n.headers),r=n.statusCode??502,s=n.statusMessage;s?t.writeHead(r,s,e):t.writeHead(r,e),Oc(n,t,()=>{})}catch(r){n.destroy(),answerGateError(e,t,r)}});this.upstreamRequests.add(r),r.on("close",()=>this.upstreamRequests.delete(r)),r.on("error",()=>{t.headersSent||t.destroyed?t.destroy():answerJson(t,503,{error:"flutter_starting",message:Wc})}),t.on("close",()=>{t.writableFinished||r.destroy()}),e.pipe(r)}forwardUpgrade(e,t,n,r){const s=Rc({host:"127.0.0.1",port:r},()=>{s.write(upgradeRequestHead(e,`127.0.0.1:${r}`)),n.length>0&&s.write(n),s.pipe(t),t.pipe(s)});for(const e of[t,s])this.upgradedSockets.add(e),e.on("close",()=>this.upgradedSockets.delete(e));s.on("error",()=>t.destroy()),s.on("close",()=>t.destroy()),t.on("error",()=>s.destroy()),t.on("close",()=>s.destroy())}};function splitRequestUrl(e){const t=e??"/",n=t.indexOf("?");return-1===n?{pathname:t,query:new URLSearchParams}:{pathname:t.slice(0,n),query:new URLSearchParams(t.slice(n+1))}}async function readSourceLineTable(e){const{file:t}=e,notFound=e=>({statusCode:404,body:{error:"flutter_source_not_found",message:e}});if(!t||Nc.isAbsolute(t))return notFound("Pass the file as ?file=<path relative to the canvas host root>.");let n,r;try{const s=await _c(e.tempoRoot);n=await _c(Nc.resolve(s,t)),r=await Promise.all(e.packageDirs.map(e=>_c(e)))}catch{return notFound(`${t} does not exist.`)}if(!r.some(e=>isInsideDirectory(e,n)))return notFound(`${t} is not inside the Flutter app directory.`);try{const e=await kc(n);if(!e.isFile())return notFound(`${t} is not a file.`);const r=await Ac(n,"utf-8");return{statusCode:200,body:{file:t,modifiedTs:Math.trunc(e.mtimeMs),lineStarts:lineStartsOf(r)}}}catch{return notFound(`${t} could not be read.`)}}function lineStartsOf(e){const t=[0];for(let n=0;n<e.length;n+=1){const r=e.charCodeAt(n),s=13===r&&10!==e.charCodeAt(n+1);(10===r||s)&&t.push(n+1)}return t}function isInsideDirectory(e,t){const n=Nc.relative(e,t),r=".."===n||n.startsWith(`..${Nc.sep}`);return""!==n&&!r&&!Nc.isAbsolute(n)}function answerGateError(e,t,n){logGateError(e,n),e.resume(),t.headersSent||t.destroyed?t.destroy():answerJson(t,500,{error:"flutter_gate_error",message:n instanceof Error?n.message:String(n)})}function logGateError(e,t){devLog("flutter:gate_error",{method:e.method,path:e.url,message:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0})}function answerJson(e,t,n){e.writeHead(t,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),e.end(JSON.stringify(n))}function upgradeRequestHead(e,t){const n=[`${e.method??"GET"} ${e.url??"/"} HTTP/${e.httpVersion}`];for(let r=0;r<e.rawHeaders.length;r+=2){const s=e.rawHeaders[r]??"",i="host"===s.toLowerCase()?t:e.rawHeaders[r+1];n.push(`${s}: ${i}`)}return`${n.join("\r\n")}\r\n\r\n`}var Kc=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","proxy-connection","te","trailer","transfer-encoding","upgrade"]);function endToEndHeaders(e){const t={};for(const[n,r]of Object.entries(e))void 0===r||Kc.has(n)||(t[n]=r);return t}async function allocateLoopbackPort(){return await new Promise((e,t)=>{const n=Pc();n.unref(),n.on("error",t),n.listen(0,"127.0.0.1",()=>{const r=n.address(),s="object"==typeof r&&r?r.port:0;n.close(()=>s>0?e(s):t(new Error("Could not reserve a loopback port for flutter run")))})})}function loopbackUrl(e){return`http://127.0.0.1:${e}`}async function waitForBootstrap(e,t,n){const r=Date.now()+t;for(;Date.now()<r&&n();){try{const t=await fetch(`${e}/flutter_bootstrap.js`,{signal:AbortSignal.timeout(2e3)});if(await t.arrayBuffer().catch(()=>{}),200===t.status)return!0}catch{}await new Promise(e=>setTimeout(e,250))}return!1}async function raceWithTimeout(e,t){let n=null;const r=new Promise(e=>{n=setTimeout(()=>e("timeout"),t)});try{return await Promise.race([e,r])}finally{n&&clearTimeout(n)}}function describeExit(e){return e.signal?`signal ${e.signal}`:`code ${e.code??"unknown"}`}function lastLines(e,t){return e.trim().split(/\r?\n/).slice(-t).join(" | ")}function stringify(e){return"string"==typeof e?e:JSON.stringify(e)}function toPosix2(e){return e.split(Nc.sep).join("/")}var Yc=class{constructor(){this.outputHint=null,this.supervisorHint=null}current(){return this.supervisorHint??this.outputHint}recordOutput(e){this.outputHint=e}recordSupervisor(e){this.supervisorHint=e}clearSupervisor(e){return this.supervisorHint?.class===e&&(this.supervisorHint=null,!0)}},zc=p(Pe(),1);import{access as Jc,readdir as Qc,readFile as Xc,realpath as Zc}from"fs/promises";import el from"path";import tl from"picomatch";var nl={bun:"bun install",pnpm:"pnpm install --no-frozen-lockfile",yarn:"yarn install",npm:"npm install"};async function fileExists(e){try{return await Jc(e),!0}catch{return!1}}function parsePackageManagerField(e){if("string"!=typeof e)return null;const[t,n]=e.split("@"),r=t?.trim();if("bun"!==r&&"pnpm"!==r&&"yarn"!==r&&"npm"!==r)return null;const s=n?.split("+")[0]?.trim();return s?{pm:r,pmVersion:s}:{pm:r}}async function readPackageManagerFromPackageJson(e){try{const t=JSON.parse(await Xc(e,"utf-8"));return parsePackageManagerField(t.packageManager)}catch{return null}}var rl=[{file:"bun.lock",pm:"bun"},{file:"bun.lockb",pm:"bun"},{file:"pnpm-lock.yaml",pm:"pnpm"},{file:"yarn.lock",pm:"yarn"},{file:"pnpm-workspace.yaml",pm:"pnpm"},{file:"package-lock.json",pm:"npm"}];async function detectPackageManagerMarkerInDir(e){const t=await readPackageManagerFromPackageJson(el.join(e,"package.json"));if(t)return t;for(const t of rl)if(await fileExists(el.join(e,t.file)))return{pm:t.pm};return null}async function detectOwningPackageManager(e){const t=el.resolve(e);if(!await fileExists(el.join(t,"package.json")))return null;const{pin:n}=await findOwningInstall(t);return{...n,installCmd:nl[n.pm]}}async function findOwningInstall(e){const t=el.resolve(e);for(let e=t;;e=el.dirname(e)){const n=await detectPackageManagerMarkerInDir(e);if(!n){if(el.dirname(e)===e)break;continue}const r="pnpm"===n.pm&&e!==t;return r&&await isOutsideAncestorPnpmWorkspace(t)?{dir:t,pin:n}:{dir:e,pin:n}}return{dir:t,pin:{pm:"npm"}}}async function isOutsideAncestorPnpmWorkspace(e){const t=el.resolve(e);for(let e=t;;e=el.dirname(e)){const n=el.join(e,"pnpm-workspace.yaml");if(await fileExists(n)){if(e===t)return!1;const r=el.relative(e,t).split(el.sep).join("/");return!await pnpmWorkspaceListsPackage(n,r)}if(el.dirname(e)===e)return!1}}async function pnpmWorkspaceListsPackage(e,t){let n;try{n=(0,zc.parse)(await Xc(e,"utf-8"))}catch{return!0}const r=n?.packages;return!!Array.isArray(r)&&workspacePatternsMatch(normalizeWorkspacePatterns(r),t)}function normalizeWorkspacePatterns(e){return e.filter(e=>"string"==typeof e).map(e=>e.replace(/^(!?)\.\//,"$1").replace(/\/+$/,""))}function workspacePatternsMatch(e,t){const n=e.filter(e=>!e.startsWith("!")),r=e.filter(e=>e.startsWith("!")).map(e=>e.slice(1)),s=n.length>0&&tl(n)(t),i=r.length>0&&tl(r)(t);return s&&!i}async function readWorkspacePatterns(e){const t=el.join(e,"pnpm-workspace.yaml");if(await fileExists(t))try{const e=(0,zc.parse)(await Xc(t,"utf-8"));return Array.isArray(e?.packages)?normalizeWorkspacePatterns(e.packages):[]}catch{return null}try{const t=JSON.parse(await Xc(el.join(e,"package.json"),"utf-8")),n=t.workspaces,r=Array.isArray(n)?n:n?.packages;return Array.isArray(r)?normalizeWorkspacePatterns(r):null}catch{return null}}async function installsSeparatelyFromRoot(e,t){const n=el.resolve(e),r=el.resolve(t);if(r===n)return!1;if(!await fileExists(el.join(r,"package.json")))return!1;if(!await fileExists(el.join(n,"package.json")))return!0;const s=el.relative(n,r).split(el.sep).join("/");if(s.startsWith("../"))return!0;const i=await readWorkspacePatterns(n);return null===i||!workspacePatternsMatch(i,s)}async function pnpmHoistDirOf(e){let t;try{t=await Zc(e)}catch{return null}const n=t.split(el.sep),r=n.lastIndexOf(".pnpm");if(-1===r)return null;const s=el.join(n.slice(0,r+1).join(el.sep),"node_modules");return await fileExists(s)?s:null}import{access as sl,readFile as il,readdir as al,realpath as ol}from"fs/promises";import cl from"path";function parseTriple(e){const t=e.trim().replace(/^v/i,"").match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?$/);if(!t?.[1])return null;const n=Number.parseInt(t[1],10),r=void 0!==t[2]?Number.parseInt(t[2],10):0,s=void 0!==t[3]?Number.parseInt(t[3],10):0;if(![n,r,s].every(Number.isFinite))return null;const i=void 0!==t[3]?3:void 0!==t[2]?2:1;return{major:n,minor:r,patch:s,precision:i}}function compareTriples(e,t){return e.major!==t.major?e.major-t.major:e.minor!==t.minor?e.minor-t.minor:e.patch-t.patch}function nodeRangeSatisfied(e,t){const n=parseTriple(e);if(!n)return null;const r=t.split("||").map(e=>e.trim()).filter(e=>e.length>0);if(0===r.length)return null;let s=!1;for(const e of r){const t=clauseSatisfied(n,e);if(null!==t&&(s=!0,t))return!0}return!s&&null}function clauseSatisfied(e,t){const n=t.split(/\s+/).filter(e=>e.length>0),r=[];for(let e=0;e<n.length;e+=1){const t=n[e];/^(>=|<=|>|<|=|\^|~)$/.test(t)&&e+1<n.length?(r.push(t+n[e+1]),e+=1):r.push(t)}if(0===r.length)return null;for(const t of r){const n=comparatorSatisfied(e,t);if(null===n)return null;if(!n)return!1}return!0}function comparatorSatisfied(e,t){if("*"===t||"x"===t.toLowerCase())return!0;const n=t.match(/^(>=|<=|>|<|=|\^|~)(.+)$/),r=n?.[1]??"",s=(n?.[2]??t).trim(),i=s.match(/^v?(\d+)(?:\.(\d+))?\.(?:x|X|\*)$/);if(i&&(""===r||"="===r)){const t=Number.parseInt(i[1],10);return void 0!==i[2]?e.major===t&&e.minor===Number.parseInt(i[2],10):e.major===t}const a=parseTriple(s);if(!a)return null;switch(r){case">=":return compareTriples(e,a)>=0;case">":{const t=1===a.precision?{major:a.major+1,minor:0,patch:0}:2===a.precision?{major:a.major,minor:a.minor+1,patch:0}:{major:a.major,minor:a.minor,patch:a.patch};return 3===a.precision?compareTriples(e,t)>0:compareTriples(e,t)>=0}case"<=":return compareTriples(truncateTo(e,a.precision),a)<=0;case"<":return compareTriples(e,a)<0;case"^":return!(compareTriples(e,a)<0)&&(a.major>0?e.major===a.major:a.minor>0?0===e.major&&e.minor===a.minor:0===e.major&&0===e.minor&&e.patch===a.patch);case"~":return!(compareTriples(e,a)<0)&&(a.precision>=2?e.major===a.major&&e.minor===a.minor:e.major===a.major);case"=":case"":return 1===a.precision?e.major===a.major:2===a.precision?e.major===a.major&&e.minor===a.minor:0===compareTriples(e,a);default:return null}}function truncateTo(e,t){return 1===t?{major:e.major,minor:0,patch:0}:2===t?{major:e.major,minor:e.minor,patch:0}:e}function matchesVersionFileSpec(e,t){const n=parseTriple(t),r=parseTriple(e);return n&&r?1===n.precision?r.major===n.major:2===n.precision?r.major===n.major&&r.minor===n.minor:0===compareTriples(r,n):null}var ll=["bun.lock","bun.lockb","pnpm-lock.yaml","yarn.lock","package-lock.json"];async function pathExists(e){try{return await sl(e),!0}catch{return!1}}async function readProjectNodeRequirement(e){const t=[];let n=null;const r=new Set,collectUpToBoundary=async e=>{for(let s=cl.resolve(e);;s=cl.dirname(s)){if(!r.has(s)){r.add(s);const e=await il(cl.join(s,"package.json"),"utf-8").then(e=>JSON.parse(e)).catch(()=>null),i=e?.engines?.node;if("string"==typeof i&&i.trim()&&"*"!==i.trim()&&t.push({range:i.trim(),dir:s}),null===n)for(const e of[".nvmrc",".node-version"]){const t=await il(cl.join(s,e),"utf-8").catch(()=>null),r=t?.trim();if(r){n=r;break}}}const e=await pathExists(cl.join(s,".git"))||(await Promise.all(ll.map(e=>pathExists(cl.join(s,e))))).some(Boolean);if(e||cl.dirname(s)===s)break}};await collectUpToBoundary(e);const s=await readTempoHostAppRoot(cl.resolve(e));return null!==s&&await collectUpToBoundary(s),{engines:t,versionFileSpec:n}}async function readTempoHostAppRoot(e){const t=await il(cl.join(e,"tempo.config.json"),"utf-8").then(e=>JSON.parse(e)).catch(()=>null);if(null===t||"object"!=typeof t)return null;const n=cl.dirname(e),r=Array.isArray(t.apps)?t.apps[0]?.appDir:t.appDir,s="string"==typeof r&&""!==r.trim();return s?cl.resolve(n,r):n}var dl="^20.19.0 || >=22.12.0",ul=["@nuxt/cli","@nuxt/vite-builder"];async function readHostNodeFloor(e){const t=await il(cl.join(e,"package.json"),"utf-8").then(e=>JSON.parse(e)).catch(()=>null),n={...t?.devDependencies,...t?.dependencies},r=[],s="string"==typeof n.vite?Number(/(\d+)/.exec(n.vite)?.[1]):Number.NaN;s>=7&&r.push(dl),void 0!==n.nuxt&&r.push(...await readInstalledNuxtNodeRanges(e));const i=r.filter(e=>null!==nodeRangeSatisfied("0.0.0",e));return 0===i.length?null:{requirement:i.join(" and "),accepts:e=>i.every(t=>!0===nodeRangeSatisfied(e,t))}}async function readInstalledNuxtNodeRanges(e){const t=await readTempoHostAppRoot(cl.resolve(e)),n=await findInstalledPackageDir(e,"nuxt")??(null===t?null:await findInstalledPackageDir(t,"nuxt"));if(null===n)return[];const r=await Promise.all(ul.map(e=>findInstalledPackageDir(n,e))),s=[];for(const e of[n,...r]){if(null===e)continue;const t=await il(cl.join(e,"package.json"),"utf-8").then(e=>JSON.parse(e)).catch(()=>null),n=t?.engines?.node;"string"==typeof n&&n.trim()&&"*"!==n.trim()&&s.push(n.trim())}return s}async function findInstalledPackageDir(e,t){for(let n=cl.resolve(e);;n=cl.dirname(n)){const e=cl.join(n,"node_modules",t);if(await pathExists(cl.join(e,"package.json")))return await ol(e);if(cl.dirname(n)===n)return null}}async function discoverVersionManagerNodes(e){const{env:t,homeDir:n,platform:r}=e,s=[],collect=async(e,t,n)=>{const i=await al(e).catch(()=>[]);for(const a of i){const i=parseTriple(a);if(!i||3!==i.precision)continue;const o="bin-subdir"===n?cl.join(e,a,"bin"):cl.join(e,a),c=cl.join(o,"win32"===r?"node.exe":"node");await pathExists(c)&&s.push({version:`${i.major}.${i.minor}.${i.patch}`,binDir:o,source:t})}};if("win32"!==r){const e=t.NVM_DIR?.trim()||cl.join(n,".nvm");await collect(cl.join(e,"versions","node"),"nvm","bin-subdir");const r=t.NODENV_ROOT?.trim()||cl.join(n,".nodenv");await collect(cl.join(r,"versions"),"nodenv","bin-subdir")}return t.NVM_HOME?.trim()&&await collect(t.NVM_HOME.trim(),"nvm-windows","flat"),s.sort((e,t)=>{const n=parseTriple(e.version),r=parseTriple(t.version);return n&&r?compareTriples(r,n):0})}function usableRanges(e){return e.engines.map(e=>e.range).filter(e=>null!==nodeRangeSatisfied("0.0.0",e))}function versionSatisfiesRequirement(e,t){return usableRanges(t).every(t=>!0===nodeRangeSatisfied(e,t))}function selectNodeOverride(e){const t=usableRanges(e.requirement);if(0===t.length)return{kind:"none",reason:"no-constraint"};if(null!==e.currentVersion&&versionSatisfiesRequirement(e.currentVersion,e.requirement))return{kind:"none",reason:"current-satisfies"};const n=e.candidates.filter(t=>versionSatisfiesRequirement(t.version,e.requirement)&&e.floorOk(t.version)),r=e.requirement.versionFileSpec,s=r?n.filter(e=>!0===matchesVersionFileSpec(e.version,r)):[],i=s[0]??n[0];return i?{kind:"override",candidate:i}:{kind:"unsatisfied",requirement:t.join(" and "),currentVersion:e.currentVersion}}function buildUnsatisfiedNodeHint(e){const t=e.requirement.match(/(\d+)/)?.[1],n=t?` (e.g. \`nvm install ${t}\`)`:"",r=e.currentVersion?`your default is ${e.currentVersion}`:"no usable Node was found on PATH";return`This project requires Node ${e.requirement} (package.json engines.node) and ${r}; Tempo checked nvm and nodenv and found no installed version that satisfies it. Install one${n}, then choose Retry.`}import{access as pl,readFile as hl}from"fs/promises";import ml from"path";var fl=[{file:"bun.lock",pm:"bun"},{file:"bun.lockb",pm:"bun"},{file:"pnpm-lock.yaml",pm:"pnpm"},{file:"yarn.lock",pm:"yarn"},{file:"pnpm-workspace.yaml",pm:"pnpm"},{file:"package-lock.json",pm:"npm"}];async function fileExists2(e){try{return await pl(e),!0}catch{return!1}}function parsePackageManagerField2(e){if("string"!=typeof e)return null;const t=e.split("@")[0]?.trim();return"bun"===t||"pnpm"===t||"yarn"===t||"npm"===t?t:null}function isYarnBerryLockfile(e){return/^__metadata:/m.test(e)}function buildCommands(e,t,n,r,s){switch(t){case"pnpm":{const t=r?` --config.cacheDir=${r}`:"",n=s?" --ignore-workspace":"";return{updateCommand:`pnpm update tempo-sdk@${e}${n}${t}`,remediationCommand:`pnpm update tempo-sdk@${e}${n}${t}`}}case"bun":return{syncLockfileCommand:"bun install --lockfile-only --no-cache",updateCommand:`bun update tempo-sdk@${e} --no-cache`,remediationCommand:`bun update tempo-sdk@${e} --no-cache`};case"yarn":return n?{updateCommand:`yarn up tempo-sdk@${e}`,remediationCommand:`yarn up tempo-sdk@${e}`}:{updateCommand:`yarn upgrade tempo-sdk@${e}`,remediationCommand:`yarn upgrade tempo-sdk@${e}`,syncLockfileCommand:"yarn install --ignore-scripts --non-interactive"};case"npm":return{updateCommand:`npm update tempo-sdk --prefer-online --tag=${e}`,remediationCommand:`npm update tempo-sdk --prefer-online --tag=${e}`}}}async function resolveTempoSdkUpgradePlan(e,t={}){const n=ml.resolve(e),r=await hl(ml.join(n,"package.json"),"utf-8").then(e=>JSON.parse(e)).catch(()=>null),s=parsePackageManagerField2(r?.packageManager),i=wi,a=await findInstallOwner(n),o=s??a?.pm??"npm",c=null!==a&&a.dir!==n,l="pnpm"===o&&await fileExists2(ml.join(n,"pnpm-workspace.yaml"));return{packageManager:o,cwd:n,governedByAncestorWorkspace:c,tag:i,...buildCommands(i,o,void 0!==a?.yarnLockContents&&isYarnBerryLockfile(a.yarnLockContents),t.metadataCacheDir??null,!c&&!l)}}async function findInstallOwner(e){for(let t=e;;t=ml.dirname(t)){for(const n of fl){const r=ml.join(t,n.file);if(!await fileExists2(r))continue;const s="pnpm"===n.pm&&ml.resolve(t)!==ml.resolve(e);return s&&await isOutsideAncestorPnpmWorkspace(e)?{dir:ml.resolve(e),pm:"pnpm",marker:"pnpm-lock.yaml"}:{dir:t,pm:n.pm,marker:n.file,..."yarn"===n.pm?{yarnLockContents:await hl(r,"utf-8").catch(()=>"")}:{}}}if(ml.dirname(t)===t)return null}}import{readFile as gl,unlink as yl}from"fs/promises";import vl from"path";var El=p(Pe(),1),Tl=["dependencies","devDependencies","optionalDependencies"];function parseManagedLockfile(e){if("pnpm"===e.packageManager){const t=(0,El.parse)(e.source),n=e.importer||".",r=t?.importers?.[n]??("."===n?t:null);return r?Object.fromEntries(Tl.map(e=>[e,Object.fromEntries(Object.entries(r[e]??{}).map(([e,t])=>[e,"object"==typeof t&&null!==t?t.specifier:r.specifiers?.[e]]).sort(([e],[t])=>e.localeCompare(t)))])):null}if("npm"===e.packageManager){const t=e.importer,n=JSON.parse(e.source).packages?.[t];return n?Object.fromEntries(Tl.map(e=>[e,Object.fromEntries(Object.entries(n[e]??{}).sort(([e],[t])=>e.localeCompare(t)))])):null}return null}var wl=".tempo/pending-dependency-migration.json",Sl=new Map,bl=abortableWait("Dependency migration was cancelled");async function exclusive(e,t,n){for(;Sl.has(e);)await bl.race(Sl.get(e).catch(()=>{}),n);bl.throwIfAborted(n);const r=t();Sl.set(e,r);try{return await r}finally{Sl.get(e)===r&&Sl.delete(e)}}var Al=["dependencies","devDependencies","optionalDependencies"];function dependencies(e){const t=null===e?{}:JSON.parse(e);return Object.fromEntries(Al.map(e=>[e,Object.fromEntries(Object.entries(t[e]??{}).sort(([e],[t])=>e.localeCompare(t)))]))}async function readOptional3(e){try{return await gl(e,"utf8")}catch(e){if("ENOENT"===e.code)return null;throw e}}async function readPending(e){const t=await readOptional3(vl.join(e,wl));if(null===t)return{};const n=JSON.parse(t);if(1!==n.version||!n.packages||"object"!=typeof n.packages||Array.isArray(n.packages))throw new $s("Unrecognized pending dependency migration. Check .tempo/pending-dependency-migration.json before retrying.");return n.packages}async function writePending(e,t){await atomicWriteText(vl.join(e,wl),`${JSON.stringify({version:1,packages:t},null,2)}\n`)}async function writeManagedDependencyManifest(e,t,n,r){await exclusive(vl.resolve(e),async()=>{if(await readOptional3(t)!==n)throw new $s(`Package changed while Tempo was preparing it: ${t}. Retry setup.`);const s=dependencies(r);if(JSON.stringify(dependencies(n))!==JSON.stringify(s)){const n=await readPending(e);n[vl.relative(e,t)]=s,await writePending(e,n)}await atomicWriteText(t,r)})}async function migrateTempoSdkPins(e,t){const n=await readOptional3(e);if(null===n)return[];JSON.parse(n);const r=[...n.matchAll(/"(?:[^"\\]|\\.)*"|[{}[\]:,]/g)],s=[];let i=0,a=!1;for(let e=0;e<r.length;e++){const t=r[e][0];if(1===i&&t.startsWith('"')&&":"===r[e+1]?.[0]&&"{"===r[e+2]?.[0]&&(a=["dependencies","devDependencies"].includes(JSON.parse(t))),a&&2===i&&t.startsWith('"')&&"tempo-sdk"===JSON.parse(t)&&":"===r[e+1]?.[0]){const t=r[e+2];if(t?.[0].startsWith('"')){const e=JSON.parse(t[0]),n=managedTempoSdkSpec(e);e!==n&&s.push({start:t.index,end:t.index+t[0].length,spec:e,managed:n})}}"{"!==t&&"["!==t||i++,"}"!==t&&"]"!==t||(i--,1===i&&(a=!1))}if(0===s.length)return[];let o=n;for(const e of[...s].reverse())o=o.slice(0,e.start)+JSON.stringify(e.managed)+o.slice(e.end);return await writeManagedDependencyManifest(t,e,n,o),s.map(({spec:e})=>e)}async function prepareYarnClassicSdkMigration(e){await exclusive(vl.resolve(e.tempoRoot),async()=>{const t=vl.join(e.packageRoot,"package.json"),n=await readOptional3(t);if(null===n)return;const r=dependencies(n),s=[r.dependencies["tempo-sdk"],r.devDependencies["tempo-sdk"]],i=s.some(e=>"string"==typeof e&&managedTempoSdkSpec(e)!==e),a=await readPending(e.tempoRoot),o=vl.relative(e.tempoRoot,t),c=a[o];if(!(i||c&&s.includes("latest")))return;const l=await resolveTempoSdkUpgradePlan(e.packageRoot);if("yarn"!==l.packageManager||!l.syncLockfileCommand)return;const d=await findInstallOwner(e.packageRoot),u=d?await readOptional3(vl.join(d.dir,"yarn.lock")):null,p=(u??"").split("\n").filter(e=>/^\S.*:$/.test(e)).flatMap(e=>e.slice(0,-1).split(/,\s*/)).map(e=>e.replace(/^"|"$/g,"")).filter(e=>e.startsWith("tempo-sdk@")).map(e=>e.slice(10)),h=p.some(e=>managedTempoSdkSpec(e)!==e)&&!p.includes("latest"),m=void 0!==c&&s.includes("latest")&&h;if(i||m){if(c&&JSON.stringify(r)!==JSON.stringify(c))throw new $s(`Dependencies changed during Tempo's migration: ${t}. Update this package's lockfile with your package manager, then retry.`);m?await e.finishPendingInstall():await e.update(),c&&(delete a[o],await writePending(e.tempoRoot,a))}},e.signal)}async function managedLockfilePlan(e){const t=await resolveTempoSdkUpgradePlan(e),n=await findInstallOwner(e),r=n?.pm===t.packageManager?n.dir:e,s="pnpm"===t.packageManager?"pnpm-lock.yaml":"npm"===t.packageManager?"package-lock.json":"yarn"===t.packageManager?"yarn.lock":"bun.lockb"===n?.marker?"bun.lockb":"bun.lock",i=t.updateCommand.includes(" --ignore-workspace")?" --ignore-workspace":"",a="pnpm"===t.packageManager?`pnpm install --lockfile-only --no-frozen-lockfile --ignore-scripts${i}`:"npm"===t.packageManager?"npm install --package-lock-only --ignore-scripts":"bun"===t.packageManager?"bun install --lockfile-only --ignore-scripts":t.updateCommand.startsWith("yarn up ")?"YARN_ENABLE_IMMUTABLE_INSTALLS=false yarn install --mode=update-lockfile":null;return{directory:r,lockfile:vl.join(r,s),command:a,packageManager:t.packageManager}}async function lockedDependencies(e,t){const n=await managedLockfilePlan(e),r=await readOptional3(n.lockfile);return null===r?null:await(t??parseManagedLockfile)({packageManager:n.packageManager,source:r,importer:vl.relative(n.directory,e).split(vl.sep).join("/")})}async function prepareManagedDependencyMigration(e){const t=vl.resolve(e.tempoRoot);await exclusive(t,async()=>{e.signal?.throwIfAborted();const n=await readPending(t),r=new Set;for(const[s,i]of Object.entries(n)){const n=vl.resolve(t,s),a=vl.relative(e.projectRoot,n);if(a.startsWith(`..${vl.sep}`)||vl.isAbsolute(a))throw new $s("Pending dependency migration points outside this project.");const o=await readOptional3(n);if(null!==o){if(JSON.stringify(dependencies(o))!==JSON.stringify(i)){if(JSON.stringify(await lockedDependencies(vl.dirname(n),e.parseManagedLockfile))===JSON.stringify(dependencies(o)))continue;throw new $s(`Dependencies changed during Tempo's migration: ${n}. Update this package's lockfile with your package manager, then retry.`)}r.add(vl.dirname(n))}}if(r.size||Object.keys(n).length){if(r.size&&e.updateSdk)await e.updateSdk();else{const t=new Set;for(const n of r){e.signal?.throwIfAborted();const r=await managedLockfilePlan(n);if(!t.has(r.lockfile)){if(!r.command){if(!1===e.strictInstall)continue;throw new $s("Yarn Classic cannot prepare a lockfile without installing packages. Configure scripts.updateSdk to migrate this environment before its frozen install.")}await e.runCommand(r.command,n,e.signal,r.packageManager),t.add(r.lockfile)}}}e.signal?.throwIfAborted(),await yl(vl.join(t,wl)).catch(e=>{if("ENOENT"!==e.code)throw e})}},e.signal)}var _l=".next/tempo",kl=".tempo-cache-v1",Il="next-dist-claims",Cl=6e4,Rl=3,Pl=6048e5,{error:Nl,throwIfAborted:Ol,sleep:Dl,race:Ll}=abortableWait("Canvas devserver launch was cancelled");function waitForInstallBarrier(e,t){return Ll(e.then(()=>{},()=>{}),t)}var Ml=new Map;async function runExclusiveProjectInstall(e,t,n){const r=Ji.resolve(e),s=Ml.get(r);let i;const a=new Promise(e=>{i=e}),o=s?s.then(()=>a):a;Ml.set(r,o);try{return s&&await waitForInstallBarrier(s,t),await n()}finally{i(),o.then(()=>{Ml.get(r)===o&&Ml.delete(r)})}}function createSuffixedTempoNextDistDir(){const e=`${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`;return`${_l}-${e}`}var xl="/tempo-host",Fl="designs",Bl="tempo",Hl="devserver-process.json",Ul="recent-exits.json",jl="next-host-last-run.json",$l=/GET\s+\/tempo-host\S*\s+200\b/,Gl=2e3,ql=["component-host.tsx","component-registry.ts","canvas-manifest.tsx"],Wl="canvas-host-recovery.ts",Vl="__tempoCanvasHostWrapperGeneration";function canvasHostRecoverySourceFor(e){return"vite"===e||"nuxt"===e?pc:"expo"===e?uc:null}function frameworkManagedTempoFiles(e){const t="nuxt"===e;return[{fileName:Wl,content:canvasHostRecoverySourceFor(e)},{fileName:hc,content:t?fc:null},{fileName:mc,content:t?gc:null}]}var Kl="tempo-host.tsx",Yl=[Kl,Wl,hc,mc,Ys,...ql];function resolveManagedWatchBackend(e=process.platform,t=process.env.TEMPO_WATCHER_BACKEND,n=process.env.TEMPO_WATCHER_ISOLATION){return"native"===t||"polling"===t?t:"win32"===e?"1"===n?"native":"polling":"native"}var zl=resolveManagedWatchBackend(),Jl={diagnosticKind:"devserver-managed",ignore:["node_modules/**","**/node_modules/**",".git/**","**/.git/**","dist/**","**/dist/**","build/**","**/build/**",".next/**","**/.next/**",".dart_tool/**","**/.dart_tool/**"],debounceMs:50,coalesce:!0,autoRecover:!0,backend:zl,onError:e=>{devLog("managed-file-watcher:error",{message:e.message})}};function resolveRuntimePaths(e){const t=Ji.resolve(e),n=Ji.dirname(t),r=Ji.basename(n)===Bl?Ji.dirname(n):n;let s=Fl;try{const e=JSON.parse(Fi.readFileSync(t,"utf-8"));e.paths&&"string"==typeof e.paths.canvases&&e.paths.canvases.trim().length>0&&(s=e.paths.canvases.trim())}catch{}return{projectRoot:r,tempoRoot:n,pagesDir:Ji.resolve(n,s)}}function isManagedDevServerPath(e,t){const n=toPosixPath(e),r=Ji.join(t.tempoRoot,".tempo"),s=[t.tempoConfigPath,t.pagesDir,...Yl.map(e=>Ji.join(r,e))].map(e=>toPosixPath(Ji.relative(t.projectRoot,e))).filter(e=>e.length>0&&!e.startsWith("../"));return s.some(e=>n===e||n.startsWith(`${e}/`)||e.startsWith(`${n}/`))}var Ql=3221225786;function isWindowsTeardownExitCode(e){return e===Ql||e===(0|Ql)}function hostIdentityFrameworkFor(e){return"next"===e?"nextjs":"nuxt"===e?"nuxt":"expo"===e?"expo":"vite"}var Xl=class _TempoHostProcess{constructor(e){this.terminationPromise=null,this.detectedBaseUrl=null,this.lockConflictObserved=!1,this.publicUrl=null,this.stopped=!1,this.launcherFinished=!1,this.launcherHandoff=null,this.readinessConfirmed=!1,this.launcherStopRequired=!1,this.terminalExitNotified=!1,this.intentionalStop=!1,this.lastExitCrashed=!1,this.resolveReady=null,this.rejectReady=null,this.exitListeners=[],this.outputListeners=[],this.recentOutput=[],this.lastClientErrorLine=null,this.spawnedAt=Date.now(),this.lastOutputAt=0,this.hints=new Yc,this.hintListeners=[],this.buildErrorOutstanding=!1,this.partialOutputLines={stdout:"",stderr:""},this.explicitTempoHostUrl=e.explicitTempoHostUrl,this.tempoHostUrlSource=e.tempoHostUrlSource,this.injectedPort=e.injectedPort,this.launchSignal=e.launchSignal,this.tempoHostUrlIsHardcoded=e.tempoHostUrlIsHardcoded??!1,this.expectedProjectRoot=e.expectedProjectRoot,this.expectedIdentity=e.expectedIdentity??null,this.sdkRemedy=e.sdkRemedy??null,this.missingRootDepsProjectRoot=e.missingRootDepsProjectRoot??null,this.commandCwd=e.cwd,this.stopCommand=e.stopCommand??null,this.onLauncherHandoff=e.onLauncherHandoff??null,this.onBuildErrorOutstandingChange=e.onBuildErrorOutstandingChange??null,this.hasParentDeathWatchdog=null!=e.watchdogScriptPath;const t=extractLeadingEnvAssignments(e.command);devLog("process:spawn",{command:e.command,liftedEnvKeys:Object.keys(t.env),cwd:e.cwd,explicitTempoHostUrl:e.explicitTempoHostUrl,extraEnvKeys:e.extraEnv?Object.keys(e.extraEnv):[],watchdog:null!=e.watchdogScriptPath}),this.commandEnv={...buildManagedCommandEnv({projectNode:e.projectNode??null}),...e.extraEnv,...t.env},Object.assign(this.commandEnv,tempoSdkRuntimeEnvironment(this.commandEnv,e.cwd)),this.child=spawnManagedLongRunningCommand({command:t.command,cwd:e.cwd,env:this.commandEnv,watchdogScriptPath:e.watchdogScriptPath??null}),devLog("process:spawned",{pid:this.child.pid??null}),this.readySignal=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}),this.readySignal.catch(()=>{});const n=createDevServerOutputClassifier(),onOutput=(e,t)=>{this.lastOutputAt=Date.now();const r=String(e);this.recentOutput.push(r),this.recentOutput.length>_TempoHostProcess.MAX_RECENT_LINES&&this.recentOutput.shift(),this.notifyOutputListeners(r),this.logClientConsoleErrors(r);const s=n(r);let i=s;"module-not-found"===s?.class&&this.missingRootDepsProjectRoot&&(i={...s,errorCode:"root_deps_missing",hint:new Vs(this.missingRootDepsProjectRoot).message}),"tempo-sdk-outdated"===s?.class&&this.sdkRemedy&&(i={...s,hint:new Gs({...this.sdkRemedy,missingImport:s.metadata?.missingTempoSdkImport??null}).message}),i&&this.recordHint(i),this.trackBuildErrorOutstanding(t,r);const{ownOutput:a,conflictStarted:o}=splitOutputAtDevServerLockConflict(r),c=this.lockConflictObserved?null:extractServerUrl2(a);this.lockConflictObserved||=o,c&&!this.detectedBaseUrl&&(this.detectedBaseUrl=c,this.publicUrl=buildTempoHostUrl(c),devLog("process:url_detected",{pid:this.child.pid??null,baseUrl:c,publicUrl:this.publicUrl})),(this.publicUrl||this.detectedBaseUrl)&&this.resolveReady&&(this.resolveReady(),this.resolveReady=null,this.rejectReady=null)};this.child.stdout?.on("data",e=>onOutput(e,"stdout")),this.child.stderr?.on("data",e=>onOutput(e,"stderr")),this.child.stdout?.on("end",()=>this.trackBuildErrorOutstanding("stdout","\n")),this.child.stderr?.on("end",()=>this.trackBuildErrorOutstanding("stderr","\n")),this.child.on("error",e=>{if(devLog("process:spawn_error",{pid:this.child.pid??null,message:e.message,recentOutputTail:this.recentOutput.slice(-10).join("").slice(-2e3)}),this.rejectReady){const t=this.recentOutput.join("").trim(),n=t?`\n\nProcess output:\n${t}`:"";this.rejectReady(new Fs(`Failed to start Tempo host dev server: ${e.message}${n}${this.hintSuffix()}`)),this.resolveReady=null,this.rejectReady=null}}),this.child.on("exit",async(e,t)=>{this.stopped=!0;const n=!this.intentionalStop&&!this.readinessConfirmed&&0===e&&null==t;if(n&&this.stopCommand)return this.launcherHandoff=(async()=>{try{await(this.onLauncherHandoff?.())}catch(e){throw this.launcherHandoff=null,e}this.launcherFinished=!0})(),await this.launcherHandoff,this.lastExitCrashed=!1,devLog("process:launcher_finished",{pid:this.child.pid??null,explicitTempoHostUrl:this.explicitTempoHostUrl}),this.resolveReady&&(this.resolveReady(),this.resolveReady=null,this.rejectReady=null),void this.notifyExitListeners(e,t,"launcher-finished",!1);if(this.lastExitCrashed=!this.intentionalStop&&!isWindowsTeardownExitCode(e)&&(0!==e||null!=t||this.readinessConfirmed),n&&(this.launcherStopRequired=!0),devLog("process:exit",{pid:this.child.pid??null,code:e,signal:t,beforeReady:null!=this.rejectReady,recentOutputTail:this.recentOutput.slice(-10).join("").slice(-2e3)}),this.rejectReady){if(n)return this.rejectReady(new Bs),this.resolveReady=null,this.rejectReady=null,void this.notifyExitListeners(e,t,"process-exit");const r=t?`signal ${t}`:`code ${e??"unknown"}`,s=this.recentOutput.join("").trim(),i=s?`\n\nProcess output:\n${s}`:"";this.rejectReady(new Hs(`Tempo host dev server exited before readiness (${r})${i}${this.hintSuffix()}`)),this.resolveReady=null,this.rejectReady=null}this.notifyExitListeners(e??null,t??null,"process-exit")})}static{this.MAX_RECENT_LINES=30}onExit(e){if(this.launcherFinished&&!this.terminalExitNotified)return this.exitListeners.push(e),void e(0,null,!1,"launcher-finished",!1);this.stopped?e(null,null,this.lastExitCrashed,"process-exit",this.intentionalStop):this.exitListeners.push(e)}onOutput(e){this.outputListeners.push(e)}onHint(e){this.hintListeners.push(e);const t=this.hints.current();if(t)try{e(t)}catch{}}getLastHint(){return this.hints.current()}recordHint(e){this.hints.recordOutput(e),this.logHint(e),this.notifyHintListeners(this.hints.current())}trackBuildErrorOutstanding(e,t){const n=(this.partialOutputLines[e]+t).split(/\r?\n/);this.partialOutputLines[e]=(n.pop()??"").slice(0,Gl);let r=-1,s=-1;for(let e=0;e<n.length;e+=1){const t=n[e].replace(/\x1b\[[0-9;]*m/g,"");$l.test(t)?r=e:"compile-error"===classifyDevServerOutput(t)?.class&&(s=e)}if(s<0&&r<0)return;const i=s>r;i!==this.buildErrorOutstanding&&(this.buildErrorOutstanding=i,this.onBuildErrorOutstandingChange?.(i))}recordSupervisorHint(e){this.hints.recordSupervisor(e),this.logHint(e),this.notifyHintListeners(e)}clearSupervisorHint(e){this.hints.clearSupervisor(e)&&(devLog("process:hint_cleared",{pid:this.child.pid??null,class:e}),this.notifyHintListeners(this.hints.current()))}logHint(e){devLog("process:hint",{pid:this.child.pid??null,class:e.class,hint:e.hint,line:e.line})}notifyHintListeners(e){for(const t of this.hintListeners)try{t(e)}catch{}}getLivenessSource(){return this.launcherFinished?"probe":"child"}hintSuffix(){const e=this.hints.current();return e?`\n\nHint: ${e.hint}`:""}getPid(){return this.child.pid??null}getRecentOutputTail(){return this.recentOutput.join("").slice(-4e3)}hasBecomeReady(){return this.readinessConfirmed}isAlive(){if(this.stopped)return!1;const e=this.child.pid;return!(!e||e<=1)&&isPidAlive(e)}hasLivenessAuthority(){return this.launcherFinished||this.isAlive()}reportProbeBackedDeath(){this.launcherFinished&&!this.terminalExitNotified&&(this.lastExitCrashed=!0,this.notifyExitListeners(null,null,"probe-death"))}reportObservedChildDeath(){this.stopped||this.terminalExitNotified||(this.stopped=!0,this.lastExitCrashed=!this.intentionalStop,this.notifyExitListeners(null,null,"process-exit"))}didLastExitCrash(){return this.lastExitCrashed}getPublicUrl(){return this.publicUrl}notifyOutputListeners(e){for(const t of this.outputListeners)t(e)}logClientConsoleErrors(e){for(const t of e.split("\n")){if(!t.includes("[console.error]"))continue;const e=t.replace(/\u001b\[[0-9;]*m/g,"").replace(/^\d{1,2}:\d{2}:\d{2} [AP]M /,"").slice(0,600);e!==this.lastClientErrorLine&&(this.lastClientErrorLine=e,devLog("process:client_console_error",{pid:this.child.pid??null,line:e}))}}async waitUntilReady(e=12e3,t=Date.now()){const n="number"==typeof e?null:e,r="number"==typeof e?e:e.responderBudgetMs;if(this.launcherStopRequired){const e=new Bs;return{ok:!1,timedOut:!1,crashed:!1,errorCode:e.code,url:this.publicUrl??this.explicitTempoHostUrl,pid:this.child.pid??null,message:e.message}}if(await(this.launcherHandoff?.catch(()=>{})),this.stopped&&!this.launcherFinished)return{ok:!1,timedOut:!1,crashed:this.lastExitCrashed,url:this.publicUrl,pid:this.child.pid??null,message:"Dev server process has already stopped"};try{"object"==typeof this.tempoHostUrlSource&&null!==this.tempoHostUrlSource?(this.stopCommand&&await this.waitForLauncherHandoff(r),this.explicitTempoHostUrl=await resolveHttpUrlSource({source:this.tempoHostUrlSource,label:"urls.tempoHost",cwd:this.commandCwd,env:this.commandEnv,port:this.injectedPort,timeoutMs:3e4,signal:this.launchSignal,substitutePort:substituteAppPort})):this.tempoHostUrlIsHardcoded||(n?await this.waitForReadyOutputWithinBudget(n,t):await withTimeout(this.readySignal,r,"Timed out waiting for dev-server output"))}catch(e){Ol(this.launchSignal);const t=e instanceof Bs,n=this.lastExitCrashed;return{ok:!1,timedOut:!n&&!t,crashed:n,errorCode:t?e.code:void 0,url:this.publicUrl,pid:this.child.pid??null,message:e instanceof Error?e.message:String(e)}}if(this.launcherStopRequired){const e=new Bs;return{ok:!1,timedOut:!1,crashed:!1,errorCode:e.code,url:this.publicUrl??this.explicitTempoHostUrl,pid:this.child.pid??null,message:e.message}}const s=[this.detectedBaseUrl?buildTempoHostUrl(this.detectedBaseUrl):null,this.explicitTempoHostUrl].filter((e,t,n)=>!!e&&n.indexOf(e)===t);if(0===s.length)return{ok:!1,timedOut:!1,url:null,pid:this.child.pid??null,message:"Tempo host did not report a usable server URL"};const i=expandLoopbackHostVariants(s),isAlive=()=>!this.stopped||this.launcherFinished||null!==this.launcherHandoff,a=Date.now(),o=n?await waitForFirstHttpReachableWithinBudget(i,n,this.expectedProjectRoot,this.expectedIdentity,isAlive,()=>this.readinessExpiry(n,t,s[0]??null)):{...await waitForFirstHttpReachable(i,r,this.expectedProjectRoot,this.expectedIdentity,isAlive),responderVerdict:!0,expiry:null},c=this.launcherHandoff;await(c?.catch(()=>{}));const l=c&&!this.launcherFinished?null:o.url;if(!l){const e=this.lastExitCrashed,t=!e&&!this.stopped&&!o.sawResponder,r=!e&&this.hasLivenessAuthority()&&o.responderVerdict,i=r&&o.sawResponder&&!o.identityFailure,c=r&&o.identityFailure;let l="Tempo host URL did not become reachable in time";if(e?l="Dev server exited before its URL became reachable":o.expiry&&(l=o.expiry.message),i){const e=s[0]??"";l=`A server is answering at ${e}, but it isn't this workspace's Tempo canvas host — the app responded without the Tempo host document. The Tempo host wiring in this app is likely missing, stale, or intercepted (for Next.js: the scaffolded /tempo-host route, or a custom middleware/proxy handling the path). Re-running Tempo's canvas setup regenerates the wiring.`}if(c&&(l=this.sdkRemedy?new Gs(this.sdkRemedy).message:"The Tempo host answered, but it did not prove the current served host contract. Ensure TEMPO=true is forwarded to the dev server, install the newest tempo-sdk, restart the configured host if it is externally managed, then choose Retry."),t){const e=s[0]??"";let t="127.0.0.1";try{t=new URL(e).host}catch{}const r=Date.now()-a,i=await tcpConnectOnce(e,800);l=i?n?describeUnansweredConnection(t,r,n,o.expiry):`The dev server is running, but HTTP requests to it on ${t} are being blocked — a firewall or antivirus may be filtering local (loopback) connections on this machine.`:`The dev server is running, but Tempo can't connect to it on ${t} — a firewall or antivirus may be blocking local (loopback) connections on this machine.`}return{ok:!1,timedOut:!e,crashed:e,probeBlocked:t,wrongResponder:i,identityFailure:c,errorCode:c?"canvas_host_sdk_incompatible":void 0,url:s[0]??null,pid:this.child.pid??null,message:l}}return this.detectedBaseUrl=stripTempoHostRoute(l),this.publicUrl=l,this.readinessConfirmed=!0,{ok:!0,timedOut:!1,url:l,pid:this.child.pid??null}}readinessExpiry(e,t,n){const r=Date.now();if(r-this.lastSignOfLifeAt()>=e.stallMs)return{reason:"stall",message:describeStartStall(e,n)};if(r-t>=e.absoluteCapMs){const r=this.spawnedAt>t;return{reason:"cap",message:describeStartCap(e,n,r)}}return null}lastSignOfLifeAt(){return Math.max(this.spawnedAt,this.lastOutputAt)}waitForReadyOutputWithinBudget(e,t){return new Promise((n,r)=>{let s=null;const check=()=>{const n=this.readinessExpiry(e,t,null);if(n)return void r(new Error(n.message));const i=Math.min(this.lastSignOfLifeAt()+e.stallMs,t+e.absoluteCapMs);s=setTimeout(check,Math.max(1,i-Date.now()))};this.readySignal.then(()=>{s&&clearTimeout(s),n()},e=>{s&&clearTimeout(s),r(e)}),check()})}async waitForLauncherHandoff(e){const t=Date.now()+Math.max(e,3e4);for(;!this.launcherFinished;){if(Ol(this.launchSignal),this.stopped){if(await this.readySignal,this.launcherFinished)return;throw new Error("The canvas start command stopped before urls.tempoHost.command could run.")}if(Date.now()>=t)throw new Error("Timed out waiting for the canvas start command to hand off before running urls.tempoHost.command");await Dl(120,this.launchSignal)}}async terminate(){if(this.intentionalStop=!0,this.terminationPromise)return await this.terminationPromise;const e=this.performTermination();this.terminationPromise=e;try{await e}finally{this.terminationPromise===e&&(this.terminationPromise=null)}}async stop(){await this.terminate()}async performTermination(){if(this.stopCommand){const e=await runBoundedShellCommand({command:this.stopCommand,cwd:this.commandCwd,env:this.commandEnv,timeoutMs:1e4});devLog("process:stop_command",{command:this.stopCommand,...e})}if(this.stopped)this.launcherFinished&&(this.lastExitCrashed=!1,this.notifyExitListeners(0,null,"process-exit"));else{const e=this.child.pid;if(e){const t=await terminateManagedLongRunningProcess(this.child,{gracefulShutdownMs:3e3,forcedShutdownMs:2e3});if(!t)throw new Error(`Canvas devserver process tree rooted at pid ${e} survived termination`);this.stopped=!0}else this.stopped=!0,this.notifyExitListeners(null,null,"process-exit")}const e=this.publicUrl;if(e&&!await waitForHttpUnreachable(e,5e3))throw new Error(`Canvas devserver is still reachable at ${e} after stop`)}forceKill(){this.intentionalStop=!0,forceKillManagedLongRunningProcess(this.child,this.hasParentDeathWatchdog)}notifyExitListeners(e,t,n,r=!0){if(0===this.exitListeners.length)return;const s=[...this.exitListeners];r&&(this.exitListeners=[],this.terminalExitNotified=!0);for(const r of s)try{r(e,t,this.lastExitCrashed,n,this.intentionalStop)}catch{}}},Zl=null;function parsePersistedDevserverOwner(e){if("object"!=typeof e||null===e)return null;const t=e,n=t.managerPid;return"number"!=typeof n||!Number.isInteger(n)||n<=1?null:{appInstanceId:"string"==typeof t.appInstanceId?t.appInstanceId:null,managerPid:n,startedAt:"number"==typeof t.startedAt?t.startedAt:null,portWasTempoAllocated:!0===t.portWasTempoAllocated,launchPid:"number"==typeof t.launchPid&&Number.isInteger(t.launchPid)&&t.launchPid>1?t.launchPid:null,launchProcessStartedAt:"string"==typeof t.launchProcessStartedAt?t.launchProcessStartedAt:null,launchPort:"number"==typeof t.launchPort&&Number.isInteger(t.launchPort)&&t.launchPort>0&&t.launchPort<65536?t.launchPort:null,stopCommand:"string"==typeof t.stopCommand&&t.stopCommand.length>0?t.stopCommand:null}}var ed=class _TempoDevServer{constructor(e){this.preparedSdkUpgrade=null,this.activeHostIdentity=null,this.idleProcessStatus="stopped",this.initializePromise=null,this.projectNodeOverride=null,this.reconcileQueue=[],this.reconcileWorkerRunning=!1,this.reconcileRetryCount=0,this.reconcileRetryTimer=null,this.disposed=!1,this.urlHealthProbeTimer=null,this.urlHealthProbeUrl=null,this.devserverReadyAt=null,this.devserverLaunchPid=null,this.devserverLaunchProcessStartedAt=null,this.devserverLaunchPort=null,this.devserverStopCommand=null,this.devserverPortWasTempoAllocated=!1,this.devserverExternalRuntimePending=!1,this.managedReconciliation=createReconciliationQueue(async()=>{this.disposed||await this.repair()},{onError:e=>{this.state.lastError=String(e)}}),this.managedFileWatchers=[],this.managedWatchVersion=0,this.managedFileWatcherStopPromise=null,this.repairDebounceTimer=null,this.convergenceDriftStreak=0,this.convergenceRetryTimer=null,this.managedRewriteThrash=new Map,this.activeHostProcess=null,this.hostStartGeneration=0,this.flutterDevServer=null,this.flutterHostActive=!1,this.flutterReferenceFiles=[],this.flutterResolveChain=Promise.resolve(),this.flutterBoardKeys=new Map,this.flutterStatusListeners=new Set,this.restartHostForFlutter=null,this.flutterChangedPaths=new Set,this.flutterReconciliation=createReconciliationQueue(async()=>{const e=[...this.flutterChangedPaths];this.flutterChangedPaths.clear(),await this.reconcileFlutterPreviews(e)},{minIntervalMs:150,onError:e=>devLog("flutter:reconcile_failed",{message:String(e)})}),this.urlHealthProbeConsecutiveFailures=0,this.urlHealthProbeGeneration=0,this.urlHealthProbeInFlight=null,this.hostConnectionListeners=new Set,this.hostConnectionStatus=null,this.nextDistDir=null,this.nextDistDirClaim=null,this.nextHostRunWrite=Promise.resolve(),this.installFailure=null;const t=resolveRuntimePaths(e.tempoConfigPath);this.config={...e,scripts:{...e.scripts}},this.projectRoot=t.projectRoot,this.appRoot=e.appDir?Ji.resolve(t.projectRoot,e.appDir):t.projectRoot,this.tempoRoot=t.tempoRoot,this.pagesDir=t.pagesDir,this.commandCwd=t.tempoRoot,this.processMarkerPath=Ji.join(t.tempoRoot,".tempo",Hl),this.state={setupStatus:"uninitialized",reconcileStatus:"idle",initialized:!1,generation:0,lastError:null,dependenciesInstalled:!1,devserverUrl:null,urlUnreachableSince:null,recentReconciles:[],recentStartAttempts:[],recentExits:[]},this.registry=new zs(this.projectRoot,this.tempoRoot,this.pagesDir)}static{this.URL_HEALTH_PROBE_INTERVAL_MS=5e3}static{this.URL_HEALTH_FAILURES_TO_DEMOTE=3}static{this.REPAIR_DEBOUNCE_MS=100}static{this.RECONCILE_RETRY_DELAYS=[500,1e3,2e3,5e3]}static{this.CONVERGENCE_BACKOFF_DELAYS=[0,250,1e3,5e3,3e4]}static{this.MANAGED_REWRITE_THRASH_THRESHOLD=5}static{this.MANAGED_REWRITE_THRASH_WINDOW_MS=1e4}static{this.MANAGED_REWRITE_BACKOFF_MS=3e4}static{this.RECONCILE_ACTIVITY_LIMIT=50}static{this.START_ATTEMPT_LIMIT=30}static{this.RECENT_EXITS_LIMIT=30}publishHostConnection(e){this.hostConnectionStatus=e;for(const t of this.hostConnectionListeners)try{t(e)}catch{}}getConfig(){return{...this.config,scripts:{...this.config.scripts}}}activeHostHasLivenessAuthority(){const e=this.activeHostProcess;return!!e&&("function"==typeof e.hasLivenessAuthority?e.hasLivenessAuthority():e.isAlive())}activeHostLivenessSource(){const e=this.activeHostProcess;return e?"function"==typeof e.getLivenessSource?e.getLivenessSource():"child":null}currentProcessStatus(){return this.activeHostHasLivenessAuthority()?this.state.devserverUrl?"running":"starting":this.idleProcessStatus}getState(){return{...this.state,processStatus:this.currentProcessStatus(),livenessSource:this.activeHostLivenessSource(),recentReconciles:this.state.recentReconciles.map(e=>({...e})),recentStartAttempts:this.state.recentStartAttempts.map(e=>({...e})),recentExits:this.state.recentExits.map(e=>({...e})),recentOutputTail:this.activeHostProcess?.getRecentOutputTail()??null,...this.flutterDevServer?{flutter:this.flutterDevServer.snapshot()}:{}}}recordHostExit(e){this.state.recentExits.push(e);const t=this.state.recentExits.length-_TempoDevServer.RECENT_EXITS_LIMIT;t>0&&this.state.recentExits.splice(0,t),this.persistRecentExits()}recentExitsFilePath(){return Ji.join(this.tempoRoot,".tempo",Ul)}async persistRecentExits(){try{await Hi(Ji.dirname(this.recentExitsFilePath()),{recursive:!0}),await atomicWriteText2(this.recentExitsFilePath(),JSON.stringify(this.state.recentExits))}catch{}}async loadRecentExitsFromDisk(){const e=await readJsonFile(this.recentExitsFilePath());if(!Array.isArray(e))return;const t=e.filter(e=>!!e&&"object"==typeof e&&"number"==typeof e.at);this.state.recentExits=[...t,...this.state.recentExits].slice(-_TempoDevServer.RECENT_EXITS_LIMIT)}recordReconcileActivity(e){this.state.recentReconciles.push(e);const t=this.state.recentReconciles.length-_TempoDevServer.RECONCILE_ACTIVITY_LIMIT;t>0&&this.state.recentReconciles.splice(0,t)}recordStartAttempt(e){this.state.recentStartAttempts.push(e);const t=this.state.recentStartAttempts.length-_TempoDevServer.START_ATTEMPT_LIMIT;t>0&&this.state.recentStartAttempts.splice(0,t)}async initialize(){if(this.initializePromise)return await this.initializePromise;this.initializePromise=this.performInitialize();try{return await this.initializePromise}finally{this.initializePromise=null}}async reconcile(e,t=!1){return await this.enqueueReconcile(e,t)}async startDevServer(e){const t=devTimer("supervisor:start_dev_server",{projectRoot:this.projectRoot,tempoRoot:this.tempoRoot,commandCwd:this.commandCwd,installScript:this.config.scripts.install,updateSdkScript:this.config.scripts.updateSdk,startScript:this.config.scripts.start,forceInstall:e?.forceInstall??!1,rerunInstall:e?.rerunInstall??!1,dependenciesInstalled:this.state.dependenciesInstalled});if(!this.state.initialized)throw t.done({ok:!1,reason:"not_initialized"}),new $s("TempoDevServer.startDevServer() requires initialize() first");Ol(e?.signal);const n=++this.hostStartGeneration,r=findPowerShellSyntax(this.config.scripts.start);if(r)throw t.done({ok:!1,reason:"start_shell_dialect_mismatch"}),new Ds(this.config.scripts.start,describePowerShellRejection(r));const s=null!==this.config.tempoHostUrl&&"object"==typeof this.config.tempoHostUrl?this.config.tempoHostUrl.command:null,i=s?findPowerShellSyntax(s):null;if(s&&i)throw t.done({ok:!1,reason:"tempo_host_url_shell_dialect_mismatch"}),new Ds(s,`urls.tempoHost.command contains PowerShell-only syntax (${i}); use one plain cross-platform command`);let a;this.idleProcessStatus="starting",await this.ensureFlutterDevServerStarted();let o=null,c=null;const l=[],d=[],u=[];let p=!1;const attachProcessListeners=e=>{e.onExit((t,n,r,s,i)=>{if(p&&i)return;if("launcher-finished"===s){devLog("supervisor:launcher_finished",{pid:e.getPid()});for(const e of u)e(t,n,r,s,i);return}a===e&&(this.recordHostExit({at:Date.now(),code:t,signal:n,crashed:e.didLastExitCrash(),livenessSource:e.getLivenessSource(),afterReady:e.hasBecomeReady(),port:portFromReadyUrl(e.getPublicUrl()),outputTail:e.getRecentOutputTail()}),this.releaseNextDistDirClaim());const o=this.activeHostProcess===e;if(o&&(this.activeHostProcess=null),a===e){this.removeProcessMarkerForPid(e.getPid()).catch(()=>{}),o&&(this.devserverExternalRuntimePending=!1,this.state.devserverUrl=null,this.state.urlUnreachableSince=null,this.idleProcessStatus="exited",this.stopUrlHealthProbe(),this.persistStatus().catch(()=>{}));for(const e of u)e(t,n,r,s,i)}});for(const t of l)e.onOutput(t);for(const t of d)e.onHint(t)},currentSdkRemedy=()=>c?{managedUpgradeAttempted:c.attempted,remediationCommand:c.plan.remediationCommand,remediationDirectory:c.plan.cwd,upgradeError:c.error??null,projectNodeHint:getProjectNodeUnsatisfiedHint(this.commandCwd)}:null,h=new Set,spawnProcess=async t=>{Ol(e?.signal);const r=await this.buildStartCommandForAttempt(t,h);h.add(r.injectedPort),Ol(e?.signal);const s=await this.readExpectedHostIdentity(),i=await this.isNuxtTempoHost()?nuxtSocketTmpdirEnv():{},c=await this.nuxtSidecarNodePathEnv(),l=await this.ensureDevserverWatchdogScript();if(Ol(e?.signal),this.hostStartGeneration!==n)throw Nl();let d=null;if(this.nextDistDir&&(d=await this.beginNextHostRun(this.nextDistDir),Ol(e?.signal),this.hostStartGeneration!==n))throw Nl();const u=this.config.scripts.stop?substituteAppPort(this.config.scripts.stop,r.injectedPort):null;let p;this.devserverStopCommand=u,this.devserverLaunchPort=r.injectedPort,this.devserverPortWasTempoAllocated=r.portWasTempoAllocated,this.devserverExternalRuntimePending=!1,p=new Xl({cwd:this.commandCwd,command:r.command,explicitTempoHostUrl:r.tempoHostUrl,tempoHostUrlSource:this.config.tempoHostUrl,injectedPort:r.injectedPort,launchSignal:e?.signal,tempoHostUrlIsHardcoded:"string"==typeof this.config.tempoHostUrl&&!this.config.tempoHostUrl.includes("${PORT}"),expectedProjectRoot:this.projectRoot,expectedIdentity:s,sdkRemedy:currentSdkRemedy(),missingRootDepsProjectRoot:o,stopCommand:u,onLauncherHandoff:async()=>{this.activeHostProcess===p&&(this.devserverExternalRuntimePending=!0,await this.persistStatus())},onBuildErrorOutstandingChange:e=>{d&&this.activeHostProcess===p&&this.writeNextHostRun({...d,buildErrorOutstanding:e})},extraEnv:{...i,...c,...r.env,TEMPO_CANVAS_HOST_ROOT:this.tempoRoot,TEMPO_CANVAS_SOURCE_ROOT:this.pagesDir,TEMPO_WORKSPACE_NONCE:s.workspaceNonce,...this.nextDistDir?{TEMPO_NEXT_DIST_DIR:this.nextDistDir}:{},...this.flutterDevServer?{TEMPO_FLUTTER_URL:this.flutterDevServer.url}:{}},watchdogScriptPath:l,projectNode:toProjectNodeEnvOption(this.projectNodeOverride)}),a=p,this.activeHostIdentity=s,this.activeHostProcess=p,this.devserverLaunchPid=p.getPid(),this.devserverLaunchProcessStartedAt=this.devserverLaunchPid?await readProcessStartedAt(this.devserverLaunchPid):null,attachProcessListeners(p);try{e?.onProcessSpawned?.()}catch(e){devLog("supervisor:on_process_spawned_threw",{pid:p.getPid(),error:e instanceof Error?e.message:String(e)})}if(await this.writeProcessMarker(p.getPid()).catch(()=>{}),e?.signal?.aborted)throw await p.terminate(),Nl();return p};try{if(await this.prepareManagedDependencies({signal:e?.signal,onOutput:e?.onInstallOutput,onInstallStart:e?.onInstallStart}),this.state.dependenciesInstalled){const[e,t]=await Promise.all([this.tempoInstallReady(),this.appSideInstallReady()]);e&&t||(devLog("supervisor:dependencies_stale",{projectRoot:this.projectRoot,tempoRoot:this.tempoRoot,rootInstallReady:t,tempoInstallReady:e}),this.state.dependenciesInstalled=!1,await this.persistStatus().catch(()=>{}))}await this.selectNodeRuntimeForStart(),Ol(e?.signal),(e?.forceInstall||e?.rerunInstall||!this.state.dependenciesInstalled)&&await this.installDependenciesForStart(e?.forceInstall?"clean":e?.rerunInstall?"rerun":"if-needed",e?.signal,e?.onInstallOutput,e?.onInstallStart),Ol(e?.signal),o=await this.declaredDepsPresentOrNotRequired(this.projectRoot,!1)?null:this.projectRoot,await this.selectNextDistDir();const t=[...new Set([this.projectRoot,this.tempoRoot])];let n,r=!1;const s=this.preparedSdkUpgrade;if(this.preparedSdkUpgrade=null,c=s??await ensureTempoSdkChannelSpec(this.commandCwd,e?.signal,{updateCommand:this.config.scripts.updateSdk,runCommand:async(s,i,a)=>{e?.onInstallStart?.("sdk-update");const o=this.config.scripts.updateSdk?.trim()||(await resolveTempoSdkUpgradePlan(i)).governedByAncestorWorkspace?t:[this.tempoRoot];n=new Map,this.state.dependenciesInstalled=!1,await this.persistStatus();for(const e of o)null!==await readInstallCompletionMarker(e)&&n.set(e,await pathExists2(Ji.join(e,"node_modules",nd))),await invalidateInstallCompletionMarkers(e);await runShellCommand(s,i,a,e?.onInstallOutput,this.projectRoot,await this.nuxtSidecarNodePathEnv()),r=!0}}),Ol(e?.signal),this.projectRoot!==this.commandCwd&&await prepareAppTempoSdkDevSource(this.projectRoot,e?.signal),!n||!r&&c.error)n||await Promise.all(t.map(refreshInstallCompletionMarkers));else{for(const[e,t]of n)await writeInstallCompletionMarker(e),t&&await writeExternalLayoutInstallMarker(e);this.state.dependenciesInstalled=!0,await this.persistStatus()}a=await spawnProcess(0)}catch(e){throw await this.stopFlutterDevServer(),this.idleProcessStatus="error",this.state.lastError=e instanceof Error?e.message:String(e),t.done({ok:!1,reason:"preflight_or_spawn_failed",message:e instanceof Error?e.message:String(e)}),e}const m=this;this.restartHostForFlutter=async()=>{if(!m.disposed&&m.flutterHostActive&&!p){p=!0;try{m.stopUrlHealthProbe();const e=a.getPid();if(await a.terminate(),await m.removeProcessMarkerForPid(e).catch(()=>{}),m.disposed||!m.flutterHostActive)return;a=await spawnProcess(0);const t=await a.waitUntilReady();t.ok&&t.url?(m.state.devserverUrl=t.url,await m.persistStatus(),m.startUrlHealthProbe(t.url)):(m.idleProcessStatus="error",m.state.lastError=t.message??"Canvas host could not restart for Flutter",await a.terminate(),await m.persistStatus())}finally{p=!1}}};let f=!1;const assertReadinessOwnership=()=>{if(Ol(e?.signal),f||m.hostStartGeneration!==n)throw Nl()},stopActiveProcess=async()=>{f=!0,m.stopUrlHealthProbe(),await Promise.all([a.terminate(),m.stopFlutterDevServer()]),await m.releaseNextDistDirClaim(),await m.removeProcessMarkerForPid(a.getPid()).catch(()=>{}),m.idleProcessStatus="stopped"};return{onExit(e){u.push(e),"probe"===a.getLivenessSource()&&e(0,null,!1,"launcher-finished",!1)},onOutput(e){l.push(e),a.onOutput(e)},onHint(e){d.push(e),a.onHint(e)},onConnectionStatus(e){const current=t=>{m.activeHostProcess===a&&e(t)};return m.hostConnectionListeners.add(current),m.hostConnectionStatus&&current(m.hostConnectionStatus),()=>{m.hostConnectionListeners.delete(current)}},onFlutterStatus(e){m.flutterStatusListeners.add(e);const t=m.flutterDevServer?.status();return t&&e(t),()=>{m.flutterStatusListeners.delete(e)}},getFlutterRecentOutput:()=>m.flutterDevServer?.recentOutput()??null,getFlutterPreviewDiagnostics:()=>{const e=m.flutterDevServer?.snapshot();return e?{previewProblems:e.previewProblems,resolutionRevision:e.resolutionRevision,packages:e.packages}:null},getLastHint:()=>a.getLastHint(),getLivenessSource:()=>a.getLivenessSource(),async stop(){await stopActiveProcess()},async terminate(){await stopActiveProcess()},forceKill(){f=!0,m.flutterHostActive=!1,m.restartHostForFlutter=null,m.flutterChangedPaths.clear(),m.stopUrlHealthProbe(),a.forceKill(),m.flutterDevServer?.forceKill(),m.flutterDevServer=null,m.releaseNextDistDirClaim(),m.removeProcessMarkerForPid(a.getPid()).catch(()=>{}),m.idleProcessStatus="stopped"},async waitUntilReady(e){const n="object"==typeof e?e:void 0,r=Date.now(),capSpent=e=>Date.now()-r>=e.absoluteCapMs,owned=async e=>{const t=await e;return assertReadinessOwnership(),t};assertReadinessOwnership();let s=await owned(a.waitUntilReady(e,r));m.recordStartAttempt({at:Date.now(),kind:"initial",attempt:0,port:portFromReadyUrl(s.url),livenessSource:a.getLivenessSource(),nextDistDir:m.nextDistDir??void 0,readyBudget:n,...mapResultToAttemptOutcome(s)});let i=0,o=0,c=0;for(let t=1;t<=3;t+=1){const l=shouldRetryPortCollision(s,a),d=!l&&!s.ok&&!0===s.crashed,u=a.getRecentOutputTail(),p=d&&0===o&&m.nextDistDir===_l&&null!==parseDevServerLockConflict(u),h=d&&"node-version-unsupported"===a.getLastHint()?.class,f=h&&0===c&&shouldRetryWithBundledNode({command:m.config.scripts.start,hintClass:a.getLastHint()?.class??null,bundledNodeAvailable:null!==getBundledNodeBinDir(),bundledNodeAlreadyActive:isBundledNodeActivated()}),g=d&&!h&&!p&&0===i;if(!(l||p||f||g))break;if(n&&capSpent(n)){devLog("supervisor:retry_skipped_cap_spent",{attempt:t,absoluteCapMs:n.absoluteCapMs,elapsedMs:Date.now()-r}),s={ok:!1,timedOut:!0,crashed:!1,url:s.url,pid:s.pid,message:describeRetrySkippedAtCap(n)};break}if(p)o+=1;else if(f){c+=1,setBundledNodeActivated(!0);const e=await owned(resolveProjectNodeOverrideForDir(m.tempoRoot));m.projectNodeOverride=e,devLog("supervisor:node_toolchain_retry",{command:m.config.scripts.start,bundledNodeBinDir:getBundledNodeBinDir()})}else g&&(i+=1);if(m.stopUrlHealthProbe(),await owned(a.terminate()),await owned(m.removeProcessMarkerForPid(a.getPid()).catch(()=>{})),p){const e=await owned(m.selectSuffixedNextDistDir());m.nextDistDir=e,devLog("supervisor:next_dist_dir_suffixed",{distDir:m.nextDistDir,reason:"observed-live-lock",tempoRoot:m.tempoRoot})}const y=await spawnProcess(t);try{assertReadinessOwnership()}catch(e){throw await y.terminate(),e}a=y,s=await owned(a.waitUntilReady(e,r)),m.recordStartAttempt({at:Date.now(),kind:l?"port-retry":p?"lock-sidestep-retry":f?"node-toolchain-retry":"crash-retry",attempt:t,port:portFromReadyUrl(s.url),livenessSource:a.getLivenessSource(),nextDistDir:m.nextDistDir??void 0,readyBudget:n,...mapResultToAttemptOutcome(s)})}if(s.ok&&s.url){m.state.devserverUrl=s.url,m.state.urlUnreachableSince=null,m.devserverReadyAt=Date.now(),m.devserverExternalRuntimePending=!1;const e=a.getPid();if(e){const t=new Set(await owned(resolveDescendantPids(e).catch(()=>[]))),n=portFromReadyUrl(s.url);if(null!=n){const e=await owned(findPortListenerPid(n).catch(()=>null));if(null!=e&&t.has(e)){m.devserverLaunchPid=e;const t=await owned(readProcessStartedAt(e));m.devserverLaunchProcessStartedAt=t}}await owned(m.writeProcessMarker(e,[...t]).catch(()=>{}))}await owned(m.persistStatus()),m.startUrlHealthProbe(s.url),t.done({ok:!0,url:s.url,pid:s.pid})}else{m.stopUrlHealthProbe(),await owned(a.terminate()),await owned(m.removeProcessMarkerForPid(a.getPid()).catch(()=>{})),m.idleProcessStatus="error";const e=parseDevServerLockConflict(a.getRecentOutputTail());if(e){const t="nuxt"===e.framework?`Another Nuxt dev server (PID ${e.pid}) is running in this worktree's Tempo canvas folder and holds Nuxt's dev lock. Close the other Tempo session or terminal running \`nuxt dev\` there, then retry.`:`Another dev server (PID ${e.pid}) is holding the selected Tempo canvas build directory. Close the other Tempo session for this worktree, then retry.`;s={...s,message:t}}const n=a.getLastHint();if(n?.errorCode){const e="node-version-unsupported"===n.class?new Is(extractObservedNodeVersion(a.getRecentOutputTail())??"unknown or missing","Node.js 20.19+ or 22.12+ for Vite 7+").message:n.hint;s={...s,errorCode:n.errorCode,message:e}}m.state.lastError=s.message??"Canvas dev server failed to become ready",await owned(m.persistStatus().catch(()=>{})),t.done({ok:!1,reason:"not_ready",timedOut:s.timedOut,url:s.url,pid:s.pid,message:s.message})}return s}}}async prepareManagedDependencies(e={}){if(protectedRootFor(this.projectRoot)||protectedRootFor(this.tempoRoot))return;const updateSdk=async(t=this.commandCwd)=>{this.state.dependenciesInstalled=!1,await this.persistStatus(),await Promise.all([...new Set([this.projectRoot,this.tempoRoot])].map(invalidateInstallCompletionMarkers));const n=await ensureTempoSdkChannelSpec(t,e.signal,{updateCommand:this.config.scripts.updateSdk,runCommand:async(t,n,r)=>(e.onInstallStart?.("sdk-update"),runShellCommand(t,n,r,e.onOutput,this.projectRoot,await this.nuxtSidecarNodePathEnv()))});if(n.error)throw new bs(n.plan.updateCommand,null,n.error);!n.attempted&&this.config.scripts.updateSdk&&(e.onInstallStart?.(),await runShellCommand(this.config.scripts.updateSdk,t,e.signal,e.onOutput,this.projectRoot,await this.nuxtSidecarNodePathEnv())),t===this.commandCwd&&(this.preparedSdkUpgrade=n)},t=[];for(const e of new Set([this.commandCwd,this.projectRoot,this.appRoot])){const n="local-prebuilt"===process.env[Uo]||await hasTempoSdkDevSource(e);n||t.push(e)}let n=!1;for(const r of t)await prepareYarnClassicSdkMigration({packageRoot:r,tempoRoot:this.tempoRoot,signal:e.signal,update:async()=>{this.config.scripts.updateSdk?.trim()?(n||await updateSdk(),n=!0):await updateSdk(r)},finishPendingInstall:async()=>{const t=this.config.scripts.updateSdk?.trim();t&&"yarn upgrade tempo-sdk@latest"!==t?await updateSdk():(e.onInstallStart?.("sdk-update"),await runShellCommand(await buildSafeInstallCommand({pm:"yarn",installCmd:"yarn install --ignore-scripts --non-interactive"},r),r,e.signal,e.onOutput,this.projectRoot,await this.nuxtSidecarNodePathEnv()))}});for(const e of t)await migrateTempoSdkPins(Ji.join(e,"package.json"),this.tempoRoot);await prepareManagedDependencyMigration({projectRoot:this.projectRoot,tempoRoot:this.tempoRoot,parseManagedLockfile:this.config.parseManagedLockfile,strictInstall:/--frozen-lockfile|--immutable|\bnpm\s+ci\b/.test(this.config.scripts.install),signal:e.signal,runCommand:async(t,n,r,s)=>(e.onInstallStart?.(),e.onOutput?.("Updating Tempo dependency lockfile...\n"),runShellCommand(await buildSafeInstallCommand({pm:s,installCmd:t},n),n,r,e.onOutput,this.projectRoot,await this.nuxtSidecarNodePathEnv())),...this.config.scripts.updateSdk?.trim()?{updateSdk:()=>updateSdk()}:{}})}async installDependenciesForStart(e,t,n,r,s=()=>this.buildInstallSteps(e),i,a){const o=a??await installInputs([this.projectRoot]),c=devTimer("supervisor:install",{tempoRoot:this.tempoRoot,commandCwd:this.commandCwd,command:this.config.scripts.install});try{const installWork=async()=>{Ol(t);const e=await s();if(0!==e.length){for(const t of e)"custom tempo install"!==t.label&&await assertTempoSdkInstallRuntime(t.cwd,process.env.TEMPO_SDK_RUNTIME_PATH);r?.(),this.state.dependenciesInstalled=!1,await this.persistStatus();try{for(const r of e)Ol(t),await runInstallStep(r,t,n,this.projectRoot,await this.nuxtSidecarNodePathEnv(),i)}catch(r){if(Ol(t),!e.some(e=>"custom tempo install"===e.label)||!missingInstallEnvironment(r))throw r;const s=await this.buildInstallSteps("if-needed",!1);if(!s.length)throw r;console.warn("[tempo-devserver] The configured installer needs unavailable local tooling; trying a local dependency install for this launch.");for(const e of s)Ol(t),await assertTempoSdkInstallRuntime(e.cwd,process.env.TEMPO_SDK_RUNTIME_PATH),await runInstallStep(e,t,n,this.projectRoot,await this.nuxtSidecarNodePathEnv())}}};await runExclusiveProjectInstall(this.projectRoot,t,installWork),Ol(t),this.state.dependenciesInstalled=!0,await this.persistStatus(),this.installFailure=null,c.done({ok:!0})}catch(e){if(c.done({ok:!1,message:e instanceof Error?e.message:String(e)}),!t?.aborted){const t=this.installFailure,n=null!==t&&[...o].every(([e,n])=>!t.inputs.has(e)||t.inputs.get(e)===n);this.installFailure={count:n?t.count+1:1,error:e,inputs:new Map([...n?t.inputs:[],...o])}}throw e}}async buildInstallSteps(e,t=!0){const n="if-needed"!==e,r=this.config.scripts.install.trim();if(t&&!looksLikeGeneratedInstallScript(r,Ji.relative(this.projectRoot,this.appRoot).split(Ji.sep).join("/"))){if(!n&&await this.packageRootInstallReady(this.projectRoot)&&await installCompletedForCurrentDeps(this.tempoRoot)&&await this.tempoInstallReady())return devLog("supervisor:custom_install_skipped_premat",{projectRoot:this.projectRoot,tempoRoot:this.tempoRoot}),[];const e=findPowerShellSyntax(r);if(e)throw new Os(r,describePowerShellRejection(e));return filterProtectedInstallSteps([{cwd:this.commandCwd,command:r,label:"custom tempo install",markerRoots:[this.projectRoot,this.tempoRoot],externalLayoutMarkerRoots:[this.projectRoot,this.tempoRoot]}])}const s=this.projectRoot!==this.tempoRoot,[i,a]=await Promise.all([detectOwningPackageManager(this.projectRoot),s?detectOwningPackageManager(this.tempoRoot):null]),o=[];i&&(!s&&n||!await this.packageRootInstallReady(this.projectRoot))&&o.push({cwd:this.projectRoot,command:await buildSafeInstallCommand(i,this.projectRoot),label:"project root install",markerRoots:[this.projectRoot]});const c=await this.separateAppInstallRoot(),l=c?await detectOwningPackageManager(c):null;if(c&&l&&!await this.packageRootInstallReady(c)){const e=await buildSafeInstallCommand(l,c),t="pnpm"===l.pm&&await isOutsideAncestorPnpmWorkspace(c);o.push({cwd:c,command:t?`${e} --ignore-workspace`:e,label:"app folder install",markerRoots:[c]})}if(a&&(n||!await this.tempoInstallReady())){const t=await buildSafeInstallCommand(a,this.tempoRoot),n="pnpm"===a.pm&&await isOutsideAncestorPnpmWorkspace(this.tempoRoot);o.push({cwd:this.tempoRoot,command:n?`${t} --ignore-workspace`:t,label:"tempo sidecar install",cleanBeforeInstall:"clean"===e||await installWasInterrupted(this.tempoRoot),markerRoots:[this.tempoRoot]})}return!t||i||a||o.push({cwd:this.commandCwd,command:r,label:"fallback tempo install",markerRoots:[this.projectRoot,this.tempoRoot],externalLayoutMarkerRoots:[this.projectRoot,this.tempoRoot]}),filterProtectedInstallSteps(o)}async selectNodeRuntimeForStart(){const e=await readHostNodeFloor(this.tempoRoot),t=null!==e,n=await resolveManagedNodeVersion({skipBundledNode:!0}),r=null!=n&&!0===e?.accepts(n),s=getBundledNodeBinDir();if(s&&shouldUseBundledNode({systemNodeVersion:n,requireFloor:t,floorOk:r})&&(setBundledNodeActivated(!0),devLog("supervisor:bundled_node_activated",{tempoRoot:this.tempoRoot,systemNodeVersion:n,requireFloor:t,binDir:s})),this.projectNodeOverride=await resolveProjectNodeOverrideForDir(this.tempoRoot),!e)return;const i=this.projectNodeOverride?.version??(isBundledNodeActivated()?await resolveManagedNodeVersion():n);i&&e.accepts(i)||devLog("supervisor:node_runtime_prediction_unmet",{tempoRoot:this.tempoRoot,effectiveNodeVersion:i,requirement:e.requirement})}async buildStartCommandForAttempt(e,t){const n=portFromConfiguredTempoHostUrl(this.config.tempoHostUrl),r=!this.config.scripts.start.includes("${PORT}")&&canInjectDevServerPort(this.config.scripts.start),s=r?await this.resolveStartFramework():"vite",i=n??await getAvailableLocalPort(t),a=buildManagedStartPlan({command:this.config.scripts.start,tempoHostUrl:this.config.tempoHostUrl,port:i,framework:s});return devLog("supervisor:start_port_selected",{attempt:e,port:i,framework:s,pinnedByTempoHostUrl:null!==n,exportsPort:void 0!==a.env.PORT}),a}async resolveStartFramework(){return await this.isNextTempoHost()?"next":await this.isNuxtTempoHost()?"nuxt":await this.isExpoTempoHost()?"expo":"vite"}async readExpectedHostIdentity(){return{workspaceNonce:await ensureTempoWorkspaceNonce(this.tempoRoot),framework:hostIdentityFrameworkFor(await this.resolveStartFramework())}}async isExpoTempoHost(){if(isExpoStartCommand(this.config.scripts.start))return!0;const e=await readJsonFile(Ji.join(this.tempoRoot,"package.json"));return Boolean(e?.dependencies?.expo??e?.devDependencies?.expo)}async tempoInstallReady(){const e=Ji.join(this.tempoRoot,"package.json");let t,n;try{t=await $i(e,"utf-8")}catch{return!0}try{n=JSON.parse(t)}catch{return!0}const r=new Set;for(const e of[n.dependencies,n.devDependencies])if(e&&"object"==typeof e&&!Array.isArray(e))for(const t of Object.keys(e))t.length>0&&r.add(t);if(0===r.size)return!0;if(await externalLayoutInstallCompleted(this.tempoRoot))return!0;if(await hasPnpLoader(this.tempoRoot))return await installCompletedForCurrentDeps(this.tempoRoot);for(const e of r){const t=Ji.join(this.tempoRoot,"node_modules",e);try{await Bi(t)}catch{return!1}}return await installCompletedForCurrentDeps(this.tempoRoot)}async appSideInstallReady(){if(!await this.packageRootInstallReady(this.projectRoot))return!1;const e=await this.separateAppInstallRoot();return null===e||await this.packageRootInstallReady(e)}async separateAppInstallRoot(){if(!looksLikeGeneratedInstallScript(this.config.scripts.install,Ji.relative(this.projectRoot,this.appRoot).split(Ji.sep).join("/")))return null;if(this.appRoot===this.projectRoot||this.appRoot===this.tempoRoot)return null;const e=await installsSeparatelyFromRoot(this.projectRoot,this.appRoot);return e?this.appRoot:null}async packageRootInstallReady(e){return await installCompletedForCurrentDeps(e)&&await this.declaredDepsPresentOrNotRequired(e)}async declaredDepsPresentOrNotRequired(e,t=!0){const n=Ji.join(e,"package.json"),r=await readJsonFile(n);if(!r)return!0;const s=new Set([...Object.keys(r.dependencies??{}),...Object.keys(r.devDependencies??{})]);if(0===s.size)return!0;if(await hasPnpLoader(e)||t&&await externalLayoutInstallCompleted(e))return!0;for(const t of s)try{await Bi(Ji.join(e,"node_modules",t))}catch{return!1}return!0}async selectNextDistDir(){if(await this.releaseNextDistDirClaim(),this.nextDistDir=null,!await this.isNextTempoHost())return;this.nextDistDir=_l;const e=[...this.state.recentExits].reverse().find(e=>!0===e.afterReady&&Date.now()-e.at<=Cl&&null!==parseDevServerLockConflict(e.outputTail));e&&(this.nextDistDir=await this.selectSuffixedNextDistDir(),devLog("supervisor:next_dist_dir_suffixed",{distDir:this.nextDistDir,reason:"fresh-post-ready-lock-exit",exitAt:e.at,tempoRoot:this.tempoRoot}))}nextHostLastRunPath(){return Ji.join(this.tempoRoot,".tempo",jl)}writeNextHostRun(e){const t=this.nextHostLastRunPath();return this.nextHostRunWrite=this.nextHostRunWrite.then(async()=>{try{await Hi(Ji.dirname(t),{recursive:!0}),await atomicWriteText2(t,JSON.stringify(e))}catch(n){devLog("supervisor:next_host_run_write_failed",{filePath:t,buildErrorOutstanding:e.buildErrorOutstanding,error:n instanceof Error?n.message:String(n)})}}),this.nextHostRunWrite}async beginNextHostRun(e){await this.nextHostRunWrite;const t=await readJsonFile(this.nextHostLastRunPath());if(!0===t?.buildErrorOutstanding){const n=Ji.join(this.nextDistCachePath(e),"dev","cache");try{await Gi(n,{recursive:!0,force:!0}),devLog("supervisor:next_cache_cleared",{distDir:e,cacheDir:n,reason:"previous-run-ended-with-build-error-outstanding",previousRunDistDir:t.distDir??null,previousRunStartedAt:t.startedAt??null})}catch(t){devLog("supervisor:next_cache_clear_failed",{distDir:e,cacheDir:n,error:t instanceof Error?t.message:String(t)})}}const n={distDir:e,startedAt:Date.now(),buildErrorOutstanding:!1};return await this.writeNextHostRun(n),n}nextDistClaimsDir(){return Ji.join(this.tempoRoot,".tempo",Il)}nextDistCachePath(e){return Ji.resolve(this.commandCwd,e)}nextDistClaimPath(e){return Ji.join(this.nextDistClaimsDir(),`${Ji.basename(e)}.json`)}async tryClaimNextDistDir(e){const t=this.nextDistCachePath(e),n=this.nextDistClaimPath(e);await Hi(t,{recursive:!0}),await Wi(Ji.join(t,kl),"1\n",{flag:"a"}),await Hi(Ji.dirname(n),{recursive:!0});const r=xi(),s=await readProcessStartedAt(process.pid),i=`${JSON.stringify({token:r,managerPid:process.pid,processStartedAt:s,claimedAt:Date.now(),distDir:e})}\n`;for(let t=0;t<2;t+=1)try{return await Wi(n,i,{encoding:"utf-8",flag:"wx"}),this.nextDistDirClaim={distDir:e,claimPath:n,token:r},!0}catch(e){if("EEXIST"!==e.code)throw e;const t=await readJsonFile(n),r="number"==typeof t?.managerPid?t.managerPid:null,s="string"==typeof t?.processStartedAt?t.processStartedAt:null,i=null!=r&&isPidAlive(r),a=i?await readProcessStartedAt(r):null,o=i&&(null==s||a===s);if(o)return!1;await Gi(n,{force:!0})}return!1}async selectSuffixedNextDistDir(){await this.releaseNextDistDirClaim();const e=Ji.join(this.commandCwd,".next"),t=await ji(e,{withFileTypes:!0}).catch(()=>[]),n=[];for(const r of t){if(!r.isDirectory()||!/^tempo-[a-z0-9]+$/i.test(r.name))continue;const t=Ji.join(e,r.name);try{await Bi(Ji.join(t,kl));const e=await qi(t);n.push({distDir:`.next/${r.name}`,mtimeMs:e.mtimeMs})}catch{}}n.sort((e,t)=>t.mtimeMs-e.mtimeMs);for(const e of n)if(await this.tryClaimNextDistDir(e.distDir))return await this.sweepNextDistDirs(),e.distDir;for(;;){const e=createSuffixedTempoNextDistDir();if(await this.tryClaimNextDistDir(e))return await this.sweepNextDistDirs(),e}}async releaseNextDistDirClaim(){const e=this.nextDistDirClaim;if(this.nextDistDirClaim=null,!e)return;const t=await readJsonFile(e.claimPath);t?.token===e.token&&await Gi(e.claimPath,{force:!0}).catch(()=>{}),await this.sweepNextDistDirs()}async sweepNextDistDirs(){const e=Ji.join(this.commandCwd,".next"),t=await ji(e,{withFileTypes:!0}).catch(()=>[]),n=Date.now(),r=[];for(const s of t){if(!s.isDirectory())continue;const t=Ji.join(e,s.name);if(/^tempo-sidestep-/i.test(s.name)){const e=await qi(t).catch(()=>null);e&&n-e.mtimeMs>Pl&&await Gi(t,{recursive:!0,force:!0}).catch(()=>{});continue}if(!/^tempo-[a-z0-9]+$/i.test(s.name))continue;try{await Bi(Ji.join(t,kl))}catch{const e=await qi(t).catch(()=>null);e&&n-e.mtimeMs>Pl&&await Gi(t,{recursive:!0,force:!0}).catch(()=>{});continue}try{await Bi(this.nextDistClaimPath(`.next/${s.name}`));continue}catch{}const i=await qi(t).catch(()=>null);i&&r.push({path:t,mtimeMs:i.mtimeMs})}r.sort((e,t)=>t.mtimeMs-e.mtimeMs),await Promise.all(r.slice(Rl).map(e=>Gi(e.path,{recursive:!0,force:!0}).catch(()=>{})))}async ensureFlutterDevServerStarted(){this.flutterHostActive=!0,await this.reconcileFlutterPreviews([])}reconcileFlutterPreviews(e){const t=this.flutterResolveChain.then(()=>this.performFlutterReconcile(e));return this.flutterResolveChain=t.catch(()=>{}),t}async performFlutterReconcile(e){if(this.disposed||!this.flutterHostActive)return;const t=await scanFlutterBoards(this.pagesDir,this.tempoRoot);if(!t.length&&!this.flutterDevServer)return;const n=await resolveFlutterPreviews(t,this.projectRoot,this.tempoRoot);if(this.disposed||!this.flutterHostActive)return;const r=new Map(n.boards.map(e=>[`${e.canvasFile}#${e.storyboardId}`,e.key])),s=[...r].some(([e,t])=>this.flutterBoardKeys.has(e)&&this.flutterBoardKeys.get(e)!==t);this.flutterBoardKeys=r,this.flutterReferenceFiles=n.boards.flatMap(e=>{try{return[canonicalPathAllowMissing(Ji.resolve(Ji.dirname(e.canvasFile),e.preview.split("#")[0]))]}catch{return[Ji.resolve(Ji.dirname(e.canvasFile),e.preview.split("#")[0])]}});const i=this.flutterDevServer?.sourceDirectories()??n.packages.map(e=>e.dir),a=e.filter(e=>{let t=Ji.resolve(this.projectRoot,e);try{t=canonicalPathAllowMissing(t)}catch{}return i.some(e=>t===e||t.startsWith(e+Ji.sep))||/(?:^|[/\\])(?:pubspec(?:_overrides)?\.yaml|\.fvmrc|fvm_config\.json|flutter_sdk)$/.test(e)});let o=!1;if(this.flutterDevServer)await this.flutterDevServer.updatePreviews(n,a);else{const e=await getAvailableLocalPort();if(this.disposed||!this.flutterHostActive)return;const t=new Bc({tempoRoot:this.tempoRoot,projectRoot:this.projectRoot,packages:n.packages.map(({dir:e,name:t})=>({dir:e,name:t})),port:e,watchBackend:zl});if(this.flutterDevServer=t,t.onStatusChange(e=>{for(const t of this.flutterStatusListeners)t(e)}),await t.updatePreviews(n,[]),this.disposed||!this.flutterHostActive)return;if(await t.openGate(),this.disposed||!this.flutterHostActive)return void await t.stop();t.start().catch(()=>{}),o=!0}(o||s)&&this.restartHostForFlutter&&await this.restartHostForFlutter()}noteFlutterFiles(e){if(this.disposed||!this.flutterHostActive)return;const t=e.filter(e=>{const t=e.relativePath.replace(/\\/g,"/");if(/(^|\/)(?:node_modules|\.git|\.dart_tool|build|\.flutter-host)(\/|$)/.test(t))return!1;let n=e.path;try{n=canonicalPathAllowMissing(n)}catch{}const r=canonicalPathAllowMissing(this.pagesDir);return t.endsWith(".canvas.tsx")||"file"!==e.kind&&(n===r||n.startsWith(r+Ji.sep)||r.startsWith(n+Ji.sep))||null!==this.flutterDevServer&&(t.endsWith(".dart")||/(^|\/)(?:pubspec(?:_overrides)?\.yaml|\.fvmrc|fvm_config\.json|flutter_sdk)$/.test(t)||"file"!==e.kind&&(this.flutterDevServer.sourceDirectories().some(e=>n===e||n.startsWith(e+Ji.sep)||e.startsWith(n+Ji.sep))||this.flutterReferenceFiles.some(e=>e===n||e.startsWith(n+Ji.sep))))});if(t.length){for(const e of t)this.flutterChangedPaths.add(e.relativePath);this.flutterReconciliation.invalidate()}}async stopFlutterDevServer(){this.flutterHostActive=!1,this.restartHostForFlutter=null,this.flutterChangedPaths.clear();const e=this.flutterDevServer;this.flutterDevServer=null,await(e?.stop().catch(e=>{devLog("flutter:stop_failed",{message:e instanceof Error?e.message:String(e)})}))}async ensureDevserverWatchdogScript(){const e="0"!==process.env.TEMPO_DEVSERVER_WATCHDOG;if(!e)return null;const t=Ji.join(this.tempoRoot,".tempo",Eo);try{return await Hi(Ji.dirname(t),{recursive:!0}),await atomicWriteText2(t,To),t}catch{return devLog("supervisor:watchdog_write_failed",{watchdogPath:t}),null}}async nuxtSidecarNodePathEnv(){if(!await this.isNuxtTempoHost())return{};const e=await pnpmHoistDirOf(Ji.join(this.appRoot,"node_modules","nuxt"));return e?{NODE_PATH:e}:{}}async isNuxtTempoHost(){if(/\bnuxt(?:\s+dev|\s|$)/.test(this.config.scripts.start))return!0;for(const e of["nuxt.config.ts","nuxt.config.js","nuxt.config.mjs"])try{return await Bi(Ji.join(this.tempoRoot,e)),!0}catch{}const e=await readJsonFile(Ji.join(this.tempoRoot,"package.json"));return Boolean(e?.dependencies?.nuxt??e?.devDependencies?.nuxt)}async isNextTempoHost(){if(/\bnext(?:\s+dev|\s|$)/.test(this.config.scripts.start))return!0;const e=["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"];for(const t of e)try{return await Bi(Ji.join(this.tempoRoot,t)),!0}catch{}const t=await readJsonFile(Ji.join(this.tempoRoot,"package.json"));return Boolean(t?.dependencies?.next??t?.devDependencies?.next)}async writeProcessMarker(e,t=[]){if(!e)return;const n=await this.resolveStartFramework();"next"!==n&&"nuxt"!==n||(await Hi(Ji.dirname(this.processMarkerPath),{recursive:!0}),await Wi(this.processMarkerPath,`${JSON.stringify({framework:hostIdentityFrameworkFor(n),owner:"tempo",pid:e,workerPids:t,cwd:this.commandCwd,command:this.config.scripts.start,startedAt:(new Date).toISOString()},null,2)}\n`,"utf-8"))}async removeProcessMarkerForPid(e){if(!e)return;const t=await readTempoProcessMarker(this.processMarkerPath);t&&t.pid!==e||await Gi(this.processMarkerPath,{force:!0})}async ensureCanvasRegistered(e){const t=await this.registry.ensureReactCanvasHostEntry(e);t&&await this.enqueueReconcile("ensure-canvas-registered",!1)}async listRegisteredCanvases(){const e=await scanCanvasFiles(this.pagesDir);return e.map(e=>toPosixPath(Ji.relative(this.projectRoot,e)))}async getRequestedCanvasPaths(){return await this.registry.getRequestedCanvasPaths()}async dispose(){this.disposed=!0,this.hostConnectionListeners.clear(),this.managedReconciliation.dispose(),this.flutterReconciliation.dispose(),this.restartHostForFlutter=null,this.registry.dispose(),this.stopUrlHealthProbe(),await this.stopFlutterDevServer(),await this.stopManagedFileWatchers(),await this.releaseNextDistDirClaim(),null!==this.repairDebounceTimer&&(clearTimeout(this.repairDebounceTimer),this.repairDebounceTimer=null),null!==this.reconcileRetryTimer&&(clearTimeout(this.reconcileRetryTimer),this.reconcileRetryTimer=null),null!==this.convergenceRetryTimer&&(clearTimeout(this.convergenceRetryTimer),this.convergenceRetryTimer=null);for(const e of this.reconcileQueue.splice(0))e.reject(new js)}startUrlHealthProbe(e){this.stopUrlHealthProbe(),this.disposed||(this.urlHealthProbeUrl=e,this.urlHealthProbeConsecutiveFailures=0,this.urlHealthProbeGeneration+=1,this.urlHealthProbeTimer=setInterval(()=>{this.runUrlHealthProbeTick()},_TempoDevServer.URL_HEALTH_PROBE_INTERVAL_MS),"function"==typeof this.urlHealthProbeTimer.unref&&this.urlHealthProbeTimer.unref())}stopUrlHealthProbe(){null!==this.urlHealthProbeTimer&&(clearInterval(this.urlHealthProbeTimer),this.urlHealthProbeTimer=null),this.urlHealthProbeUrl=null,this.urlHealthProbeConsecutiveFailures=0,this.hostConnectionStatus=null,this.urlHealthProbeGeneration+=1}async runUrlHealthProbeTick(){const e=this.urlHealthProbeUrl,t=this.urlHealthProbeGeneration;if(e&&!this.disposed&&this.urlHealthProbeInFlight!==t){this.urlHealthProbeInFlight=t;try{await this.performUrlHealthProbeTick(e,t)}finally{this.urlHealthProbeInFlight===t&&(this.urlHealthProbeInFlight=null)}}}async performUrlHealthProbeTick(e,t){const n=await probeHostHealth(e,1500,this.projectRoot,this.activeHostIdentity);if(this.urlHealthProbeGeneration!==t)return;if("ok"===n.outcome)return null!==this.state.urlUnreachableSince&&devLog("supervisor:url_probe_recovered",{url:e}),"probe"===this.activeHostLivenessSource()&&this.publishHostConnection({state:"connected",unreachableSince:null}),this.state.urlUnreachableSince=null,this.urlHealthProbeConsecutiveFailures=0,void this.activeHostProcess?.clearSupervisorHint("host-unresponsive");if(this.activeHostProcess?.isAlive())return this.state.urlUnreachableSince??=Date.now(),this.urlHealthProbeConsecutiveFailures+=1,devLog("supervisor:url_probe_failed_host_alive",{url:e,consecutiveFailures:this.urlHealthProbeConsecutiveFailures,unreachableSince:this.state.urlUnreachableSince}),void(this.urlHealthProbeConsecutiveFailures===_TempoDevServer.URL_HEALTH_FAILURES_TO_DEMOTE&&this.activeHostProcess.recordSupervisorHint(buildHostUnresponsiveHint(e,this.state.urlUnreachableSince)));const r="probe"===this.activeHostLivenessSource();if(r){this.urlHealthProbeConsecutiveFailures+=1,this.state.urlUnreachableSince??=Date.now(),devLog("supervisor:url_probe_failed_probe_backed",{url:e,consecutiveFailures:this.urlHealthProbeConsecutiveFailures,requiredFailures:_TempoDevServer.URL_HEALTH_FAILURES_TO_DEMOTE,unreachableSince:this.state.urlUnreachableSince});const r=null!==this.activeHostIdentity&&("wrong-responder"===n.outcome||"verified-incompatible"===n.outcome);if(this.publishHostConnection({state:r?"incompatible":"unreachable",unreachableSince:this.state.urlUnreachableSince}),this.urlHealthProbeConsecutiveFailures<_TempoDevServer.URL_HEALTH_FAILURES_TO_DEMOTE)return;if(!r)return;const s=this.activeHostProcess;if(s?.reportProbeBackedDeath(),this.urlHealthProbeGeneration!==t)return;return this.state.devserverUrl===e&&(this.state.devserverUrl=null,this.state.urlUnreachableSince=null,this.idleProcessStatus="exited",this.activeHostProcess===s&&(this.activeHostProcess=null),await this.persistStatus().catch(()=>{})),void this.stopUrlHealthProbe()}this.activeHostProcess?.reportObservedChildDeath(),this.state.devserverUrl=null,this.state.urlUnreachableSince=null,this.idleProcessStatus="exited",this.stopUrlHealthProbe(),await this.persistStatus().catch(()=>{})}async performInitialize(){this.state.setupStatus="initializing";const e=devTimer("supervisor:initialize",{projectRoot:this.projectRoot,tempoRoot:this.tempoRoot,pagesDir:this.pagesDir});try{await Hi(this.tempoRoot,{recursive:!0});const{staleDevserverUrl:t,staleDevserverOwner:n}=await this.hydrateStatusFromDisk(),r=await this.reconcilePersistedDevserverUrl(t,n);await this.loadRecentExitsFromDisk();const s=!this.state.initialized,i=this.activeHostHasLivenessAuthority();s&&!i&&await this.registry.resetStaleRequestedCanvases();const a=await this.enqueueReconcile("initialize",!i);return this.state.initialized=!0,this.state.setupStatus="ready",await this.startManagedFileWatchers(),e.done({ok:!0,changedFilesCount:a.changedFiles.length,generation:a.generation}),{changedFiles:a.changedFiles,generation:a.generation,initialized:!0,persistedDevserverReconciliation:r}}catch(t){throw this.state.setupStatus="error",this.state.lastError=t instanceof Error?t.message:String(t),e.done({ok:!1,message:t instanceof Error?t.message:String(t)}),t}}async repair(){if(this.disposed)throw new js;const e={managedRepaired:[],urlInvalidated:!1,generation:this.state.generation};await this.assertConfigFilePresent();const t=await this.enqueueReconcile("repair",!1);if(e.managedRepaired.push(...t.changedFiles),e.generation=t.generation,this.state.devserverUrl){const t=await probeUrlOnce(this.state.devserverUrl,1500,this.projectRoot,this.activeHostIdentity),n="probe"===this.activeHostLivenessSource();t||this.activeHostProcess?.isAlive()||n||(this.state.devserverUrl=null,this.state.urlUnreachableSince=null,this.idleProcessStatus="exited",this.stopUrlHealthProbe(),e.urlInvalidated=!0,await this.persistStatus().catch(()=>{}))}return e}async assertConfigFilePresent(){try{return void await Bi(this.config.tempoConfigPath)}catch{throw new ws(this.projectRoot)}}async startManagedFileWatchers(){if(this.disposed)return;const e=this.stopManagedFileWatchers(),t=this.managedWatchVersion;if(await e,!this.disposed&&t===this.managedWatchVersion)try{const e=await watch(this.projectRoot,e=>{this.disposed||t!==this.managedWatchVersion||(this.noteFlutterFiles(e),e.some(e=>this.isManagedWatcherEvent(e))&&this.scheduleManagedRepair())},{...Jl,onInterruption:()=>{this.disposed||t!==this.managedWatchVersion||(this.managedReconciliation.invalidate(),this.flutterReconciliation.invalidate())}});if(this.disposed||t!==this.managedWatchVersion)return void await e.unsubscribe();this.managedFileWatchers.push(e),this.flutterReconciliation.invalidate()}catch(e){devLog("managed-file-watcher:start_failed",{root:this.projectRoot,message:e instanceof Error?e.message:String(e)})}}async stopManagedFileWatchers(){if(++this.managedWatchVersion,this.managedFileWatcherStopPromise)return void await this.managedFileWatcherStopPromise;const e=this.managedFileWatchers.splice(0);this.managedFileWatcherStopPromise=Promise.all(e.map(e=>e.unsubscribe().catch(e=>{devLog("managed-file-watcher:unsubscribe_failed",{message:e instanceof Error?e.message:String(e)})}))).then(()=>{});try{await this.managedFileWatcherStopPromise}finally{this.managedFileWatcherStopPromise=null}}isManagedWatcherEvent(e){return isManagedDevServerPath(e.relativePath,{projectRoot:this.projectRoot,tempoRoot:this.tempoRoot,tempoConfigPath:this.config.tempoConfigPath,pagesDir:this.pagesDir})}scheduleManagedRepair(){this.disposed||(this.managedReconciliation.getDiagnostics().pending?this.managedReconciliation.invalidate():(null!==this.repairDebounceTimer&&clearTimeout(this.repairDebounceTimer),this.repairDebounceTimer=setTimeout(()=>{this.repairDebounceTimer=null,this.repair().catch(e=>{this.state.lastError=e instanceof Error?e.message:String(e)})},_TempoDevServer.REPAIR_DEBOUNCE_MS),"function"==typeof this.repairDebounceTimer.unref&&this.repairDebounceTimer.unref()))}enqueueReconcile(e,t){return this.disposed?Promise.reject(new js):(devLog("reconcile:enqueued",{reason:e,force:t,queueDepthBefore:this.reconcileQueue.length,workerRunning:this.reconcileWorkerRunning,generation:this.state.generation}),new Promise((n,r)=>{this.reconcileQueue.push({reason:e,force:t,resolve:n,reject:r}),this.processReconcileQueue()}))}async processReconcileQueue(){if(!this.reconcileWorkerRunning&&!this.disposed){for(this.reconcileWorkerRunning=!0;this.reconcileQueue.length>0&&!this.disposed;){const e=this.reconcileQueue.splice(0),t=e.some(e=>e.force);try{const n=await this.performReconcile(e[0].reason,t);this.reconcileRetryCount=0;for(const t of e)t.resolve(n)}catch(t){this.state.reconcileStatus="error",this.state.lastError=t instanceof Error?t.message:String(t);for(const n of e)n.reject(t);this.scheduleRecoveryReconcile()}}this.state.initialized&&this.scheduleConvergenceCheck(),this.reconcileWorkerRunning=!1}}scheduleRecoveryReconcile(){if(this.disposed||null!==this.reconcileRetryTimer||this.managedReconciliation.getDiagnostics().pending)return;if(this.reconcileRetryCount>=_TempoDevServer.RECONCILE_RETRY_DELAYS.length)return void console.error(`[TempoDevServer] Reconcile failed after ${this.reconcileRetryCount} retries`);const e=_TempoDevServer.RECONCILE_RETRY_DELAYS[this.reconcileRetryCount];this.reconcileRetryCount+=1,this.reconcileRetryTimer=setTimeout(()=>{this.reconcileRetryTimer=null,this.enqueueReconcile("recovery-retry",!1).catch(()=>{})},e)}scheduleConvergenceCheck(){this.disposed||null===this.convergenceRetryTimer&&(async()=>{try{if(this.disposed)return;if(await this.hasManagedFileDrift()){if(this.disposed)return;const e=_TempoDevServer.CONVERGENCE_BACKOFF_DELAYS[Math.min(this.convergenceDriftStreak,_TempoDevServer.CONVERGENCE_BACKOFF_DELAYS.length-1)];this.convergenceDriftStreak+=1;const enqueueCorrection=()=>{this.convergenceRetryTimer=null,this.disposed||this.enqueueReconcile("drift-correction",!1).then(e=>{e.changedFiles.length>0&&(this.convergenceDriftStreak=0)}).catch(()=>{})};0===e?enqueueCorrection():this.convergenceRetryTimer=setTimeout(enqueueCorrection,e)}else this.convergenceDriftStreak=0}catch{}})()}async hasManagedFileDrift(){const e=Ji.join(this.tempoRoot,".tempo"),t=await this.registry.collectReactCanvasHostEntries(),n=await this.resolveStartFramework(),r=Ji.join(e,Kl),s=buildTempoHostWrapper(t,{startFramework:n});if(await readTextFileOptional2(r)!==s)return!0;for(const{fileName:t,content:r}of frameworkManagedTempoFiles(n)){const n=Ji.join(e,t);if(await readTextFileOptional2(n)!==r)return!0}for(const t of ql)if(null!==await readTextFileOptional2(Ji.join(e,t)))return!0;return!1}async performReconcile(e,t){this.state.reconcileStatus="reconciling";const n=devTimer("reconcile",{reason:e,force:t,generationBefore:this.state.generation}),r=[];try{r.push(...await this.reconcileGeneratedFiles(t));const s=r.length>0;s&&(this.state.generation+=1),this.state.reconcileStatus="idle";const i=r.map(e=>Ji.basename(e));return this.recordReconcileActivity({at:Date.now(),reason:e,force:t,generationBumped:s,changedFiles:i,generation:this.state.generation}),n.done({outcome:"ok",generation:this.state.generation,generationBumped:s,changedFileCount:r.length,changedFiles:i}),{changedFiles:r,generation:this.state.generation,reason:e}}catch(r){const s=r instanceof Error?r.message:String(r);throw this.recordReconcileActivity({at:Date.now(),reason:e,force:t,generationBumped:!1,changedFiles:[],generation:this.state.generation,error:s}),n.done({outcome:"error",generation:this.state.generation,error:s}),r}}shouldRewriteManagedFile(e,t,n){if(t)return this.managedRewriteThrash.delete(e),!0;const r=this.managedRewriteThrash.get(e);return!r||(n!==r.lastContent||Date.now()>=r.backoffUntil)}noteManagedFileRewrite(e,t,n){if(t)return;const r=Date.now(),s=this.managedRewriteThrash.get(e),i=void 0!==s&&n===s.lastContent&&(s.backoffUntil>0&&r<=s.backoffUntil+_TempoDevServer.MANAGED_REWRITE_THRASH_WINDOW_MS||r-s.lastRewriteAt<=_TempoDevServer.MANAGED_REWRITE_THRASH_WINDOW_MS),a=i?s.consecutiveRewrites+1:1,o=a>=_TempoDevServer.MANAGED_REWRITE_THRASH_THRESHOLD;this.managedRewriteThrash.set(e,{consecutiveRewrites:a,lastRewriteAt:r,backoffUntil:o?r+_TempoDevServer.MANAGED_REWRITE_BACKOFF_MS:0,lastContent:n}),o&&devLog("reconcile:managed_rewrite_backoff",{file:Ji.basename(e),consecutiveRewrites:a,backoffMs:_TempoDevServer.MANAGED_REWRITE_BACKOFF_MS})}noteManagedFileConverged(e){const t=this.managedRewriteThrash.get(e);if(!t)return;const n=Date.now();n>=t.backoffUntil&&n-t.lastRewriteAt>_TempoDevServer.MANAGED_REWRITE_THRASH_WINDOW_MS&&this.managedRewriteThrash.delete(e)}async reconcileGeneratedFiles(e){const t=[],n=Ji.join(this.tempoRoot,".tempo"),r=Ji.join(n,Kl),s=await this.registry.collectReactCanvasHostEntries(),i=await this.resolveStartFramework(),a=await readTextFileOptional2(r),o=buildTempoHostWrapper(s,{startFramework:i});a!==o?this.shouldRewriteManagedFile(r,e,o)&&(await atomicWriteText2(r,o),t.push(r),this.noteManagedFileRewrite(r,e,o)):this.noteManagedFileConverged(r);for(const{fileName:r,content:s}of frameworkManagedTempoFiles(i)){const i=Ji.join(n,r),a=await readTextFileOptional2(i);a!==s?this.shouldRewriteManagedFile(i,e,s)&&(null===s?await Gi(i,{force:!0}):await atomicWriteText2(i,s),t.push(i),this.noteManagedFileRewrite(i,e,s)):this.noteManagedFileConverged(i)}for(const r of ql){const s=Ji.join(n,r);null!==await readTextFileOptional2(s)?this.shouldRewriteManagedFile(s,e,null)&&(await Gi(s,{force:!0}),t.push(s),this.noteManagedFileRewrite(s,e,null)):this.noteManagedFileConverged(s)}return t}getStatusFilePath(){return Ji.join(this.tempoRoot,".tempo","status.json")}async hydrateStatusFromDisk(){const e=await readTextFileOptional2(this.getStatusFilePath());if(!e)return this.state.dependenciesInstalled=!1,{staleDevserverUrl:null,staleDevserverOwner:null};try{const t=JSON.parse(e);return this.state.dependenciesInstalled=!0===t.dependenciesInstalled,{staleDevserverUrl:"string"==typeof t.devserverUrl?t.devserverUrl:null,staleDevserverOwner:parsePersistedDevserverOwner(t.devserverOwner)}}catch{return this.state.dependenciesInstalled=!1,{staleDevserverUrl:null,staleDevserverOwner:null}}}async reconcilePersistedDevserverUrl(e,t){if(!e){if(!t)return"nothing_to_reconcile";if(isPidAlive(t.managerPid))return"live_sibling";const e=null!==Zl&&t.appInstanceId===Zl;return e?await this.purgeOwnedOrphanDevserver(null,t):"foreign_process"}if(e===this.state.devserverUrl)return"current_runtime";const n=null!==t&&null!==Zl&&t.appInstanceId===Zl;if(n)return isPidAlive(t.managerPid)?(devLog("supervisor:owned_live_sibling",{url:e,markerPid:t.managerPid}),"live_sibling"):await this.purgeOwnedOrphanDevserver(e,t);const r=await probeTempoHost(e,1500,this.projectRoot,await this.readExpectedHostIdentity());return"ok"===r?(devLog("supervisor:stale_url_live_sibling",{url:e}),"live_sibling"):"unreachable"===r?(devLog("supervisor:stale_url_cleared",{url:e,reason:"unreachable"}),await this.persistStatus(),"orphan_absent"):(devLog("supervisor:stale_url_foreign_left_alone",{url:e}),await this.persistStatus(),"foreign_process")}async purgeOwnedOrphanDevserver(e,t){const n=t.launchPort??(e?portFromReadyUrl(e):null);let r=!1,s=!1;if(t.stopCommand){const i=await runBoundedShellCommand({command:t.stopCommand,cwd:this.commandCwd,env:{...buildManagedCommandEnv(),...null!==n?{TEMPO_PORT:String(n),PORT:String(n)}:{}},timeoutMs:1e4});r=!0,s=i.ok,devLog("supervisor:owned_orphan_stop_command",{url:e,command:t.stopCommand,...i})}const i=null!==n?await findPortListenerPid(n):null;let a=!1;if(t.portWasTempoAllocated&&null!==i&&i===t.launchPid&&null!==t.launchProcessStartedAt){const e=await readProcessStartedAt(i);a=e===t.launchProcessStartedAt}const o=null!==i&&i>1&&i!==process.pid&&a;o&&null!==i&&await terminateProcessTreeByPid(i,3e3,2e3);const c=e?await probeTempoHost(e,1500,this.projectRoot,await this.readExpectedHostIdentity()):null,l=null!==t.launchPid&&null!==t.launchProcessStartedAt&&await readProcessStartedAt(t.launchPid)===t.launchProcessStartedAt,d=!l&&(e?"ok"!==c:s);return devLog("supervisor:owned_orphan_purge_result",{url:e,markerPid:t.managerPid,listenerPid:i,stopCommandRan:r,listenerIdentityMatches:a,listenerSignalled:o,finalOutcome:c,launchIdentityStillAlive:l,reconciled:d}),d&&await this.persistStatus(),d?"orphan_reaped":"orphan_cleanup_failed"}async persistStatus(){const e={dependenciesInstalled:this.state.dependenciesInstalled};this.state.devserverUrl&&(e.devserverUrl=this.state.devserverUrl),(this.state.devserverUrl||this.devserverExternalRuntimePending)&&(e.devserverOwner={appInstanceId:Zl,managerPid:process.pid,startedAt:this.devserverReadyAt??Date.now(),portWasTempoAllocated:this.devserverPortWasTempoAllocated,launchPid:this.devserverLaunchPid,launchProcessStartedAt:this.devserverLaunchProcessStartedAt,launchPort:this.devserverLaunchPort,stopCommand:this.devserverStopCommand});const t=this.getStatusFilePath(),n=`${JSON.stringify(e,null,2)}\n`;try{await writeStatusTextBestEffort(t,n)}catch(e){devLog("status:persist_failed",{statusPath:t,message:e instanceof Error?e.message:String(e)})}}};function buildTempoHostWrapper(e=[],t={}){const n=e.length>0,r="vite"===t.startFramework||"nuxt"===t.startFramework,s=e.map(({importPath:e,importSpecifier:t})=>` {\n canvasPath: ${JSON.stringify(e)},\n load: () => import(${JSON.stringify(t)}),\n },`).join("\n"),i=n?`const canvasModules = [\n${s}\n];\n`:"",a=n?" canvasModules={canvasModules}":"",o=canvasHostRecoverySourceFor(t.startFramework)?'import "./canvas-host-recovery";\n':"",c=`const tempoHostGlobals = globalThis as any;\ntempoHostGlobals.${Vl} =\n (tempoHostGlobals.${Vl} ?? 0) + 1;\n`;return`/* THIS FILE IS AUTO-GENERATED. DO NOT EDIT. */\n${r?"// tempo-incremental-canvas-registration\n":""}import { CanvasHost } from "tempo-sdk/canvas";\n${o}\n${c}${i}\nexport default function TempoHost() {\n return (\n <CanvasHost${a}${r?" incremental":""}>\n </CanvasHost>\n );\n}\n`}function installCompletionMarkerPath(e){return Ji.join(e,"node_modules",".tempo-install-complete")}function installInProgressMarkerPath(e){return Ji.join(e,"node_modules",".tempo-install-in-progress")}async function installWasInterrupted(e){return await pathExists2(installInProgressMarkerPath(e))}var td="tempo-install-complete-v3",nd=".tempo-external-install-complete";async function installInputs(e){return new Map(await Promise.all([...new Set(e.map(e=>Ji.resolve(e)))].map(async e=>[e,await computeInstallCompletionKey(e)])))}async function computeInstallCompletionKey(e){const t=Ji.join(e,"package.json"),n=await readTextFileOptional2(t);if(null==n)return null;let r=n;try{const e=JSON.parse(n);r={packageManager:e.packageManager??null,dependencies:e.dependencies??null,devDependencies:e.devDependencies??null,optionalDependencies:e.optionalDependencies??null,peerDependencies:e.peerDependencies??null,overrides:e.overrides??null,resolutions:e.resolutions??null,pnpm:e.pnpm??null}}catch{}const s=["pnpm-lock.yaml","package-lock.json","npm-shrinkwrap.json","yarn.lock","bun.lock","bun.lockb"];let i=Ji.resolve(e),a=null;for(;;){for(const t of s)try{a={path:Ji.relative(e,Ji.join(i,t)),content:await $i(Ji.join(i,t))};break}catch{}if(a)break;const t=Ji.dirname(i);if(t===i)break;i=t}const o=Mi("sha256");return o.update(JSON.stringify(r)),o.update("\0"),o.update(a?.path??"no-lockfile"),o.update("\0"),a&&o.update(a.content),o.update(`\0${process.platform}\0${process.arch}\0${process.versions.modules}`),`${td}:${o.digest("hex")}`}async function readInstallCompletionMarker(e){return await readTextFileOptional2(installCompletionMarkerPath(e))}async function installCompletedForCurrentDeps(e){const t=await readInstallCompletionMarker(e);if(null===t)return!await pathExists2(Ji.join(e,"package.json"));const n=await computeInstallCompletionKey(e);return null==n||t===n}async function writeInstallCompletionMarker(e){const t=await computeInstallCompletionKey(e);if(null!=t)try{await Hi(Ji.join(e,"node_modules"),{recursive:!0}),await Wi(installCompletionMarkerPath(e),t,"utf-8")}catch(t){console.warn(`[tempo-devserver] failed to write install-completion marker at ${e}:`,t)}}async function externalLayoutInstallCompleted(e){const t=await readTextFileOptional2(Ji.join(e,"node_modules",nd));return null!==t&&t===await computeInstallCompletionKey(e)}async function invalidateInstallCompletionMarkers(e){await Promise.all([Gi(installCompletionMarkerPath(e),{force:!0}),Gi(Ji.join(e,"node_modules",nd),{force:!0})])}async function writeExternalLayoutInstallMarker(e){const t=await computeInstallCompletionKey(e);null!=t&&(await Hi(Ji.join(e,"node_modules"),{recursive:!0}),await Wi(Ji.join(e,"node_modules",nd),t,"utf-8"))}async function refreshInstallCompletionMarkers(e){const t=await readInstallCompletionMarker(e);null!==t&&t!==await computeInstallCompletionKey(e)&&(await writeInstallCompletionMarker(e),await pathExists2(Ji.join(e,"node_modules",nd))&&await writeExternalLayoutInstallMarker(e))}async function pathExists2(e){try{return await Bi(e),!0}catch{return!1}}async function hasPnpLoader(e){return await pathExists2(Ji.join(e,".pnp.cjs"))||await pathExists2(Ji.join(e,".pnp.js"))}async function nodeModulesHasMeaningfulEntries(e){try{const t=await ji(Ji.join(e,"node_modules"));return t.some(e=>!e.startsWith("."))}catch{return!1}}function looksLikeGeneratedInstallScript(e,t){const n=e.trim();if("npm install && npm install --prefix .."===n)return!0;const r="(?:npm\\s+(?:install|ci)|pnpm\\s+install(?:\\s+--(?:no-)?frozen-lockfile)?|yarn\\s+install(?:\\s+--immutable)?|bun\\s+install)",s="[\\w@-][\\w@.-]*(?:/[\\w@-][\\w@.-]*)*",i="(?:\\.\\./)+tempo";if(new RegExp(`^${r}$`).test(n)||new RegExp(`^cd \\.\\. && ${r} && cd tempo && ${r}$`).test(n))return!0;if(!t)return!1;const a=new RegExp(`^cd \\.\\./(${s}) && ${r} && cd (${i}) && ${r}$`).exec(n)??new RegExp(`^cd \\.\\. && ${r} && cd (${s}) && ${r} && cd (${i}) && ${r}$`).exec(n);return null!==a&&a[1]===t&&a[2]===`${"../".repeat(t.split("/").length)}tempo`}async function commandAvailable(e){return await new Promise(t=>{const n=Li(`${e} --version`,{shell:!0,stdio:"ignore",windowsHide:!0,env:buildManagedCommandEnv()});n.on("error",()=>t(!1)),n.on("exit",e=>t(0===e))})}async function resolvePackageManagerCommand(e,t){if(await commandAvailable(e))return e;if(("pnpm"===e||"yarn"===e)&&await commandAvailable("corepack"))return`corepack ${e}`;throw new ks(e,t)}function protectedRootFor(e){const t=process.env.TEMPO_DEVSERVER_PROTECTED_ROOTS;if(!t)return null;const n=t.split(Ji.delimiter).map(e=>e.trim()).filter(e=>e.length>0).map(e=>Ji.resolve(e));if(0===n.length)return null;const r=Ji.resolve(e);for(const e of n){const t=Ji.relative(e,r);if(""===t||!t.startsWith("..")&&!Ji.isAbsolute(t))return e}return null}function filterProtectedInstallSteps(e){return e.filter(e=>{const t=protectedRootFor(e.cwd);return!t||(devLog("supervisor:install_step_skipped_protected",{cwd:e.cwd,protectedRoot:t,label:e.label,command:e.command}),!1)})}async function buildSafeInstallCommand(e,t){const n=await resolvePackageManagerCommand(e.pm,t),r=extractLeadingEnvAssignments(e.installCmd),s=r.command.replace(/^[^\s]+/,"");return e.installCmd.replace(r.command,`${n}${s}`)}function extractObservedNodeVersion(e){return/(?:Node(?:\.js)?(?: version)?|node)\s+v?(\d+\.\d+(?:\.\d+)?)/i.exec(e)?.[1]??null}async function resolveManagedNodeVersion(e={}){return await probeNodeVersion(buildManagedCommandEnv({skipBundledNode:e.skipBundledNode}))}var rd=new Map,sd=new Map;function toProjectNodeEnvOption(e){return e?{binDir:e.binDir,bundled:e.bundled,nodenvVersion:"nodenv"===e.source?e.version:null}:null}function getProjectNodeUnsatisfiedHint(e){const t=sd.get(Ji.resolve(e));return t?buildUnsatisfiedNodeHint(t):null}async function resolveProjectNodeOverrideForDir(e){const t=Ji.resolve(e),n=`${t}|bundled:${isBundledNodeActivated()}`,r=rd.get(n);if(r){const e=await r;if(null===e)return null;if(await Bi(e.binDir).then(()=>!0,()=>!1))return e;rd.delete(n)}const s=(async()=>{const e=await readProjectNodeRequirement(t);if(0===e.engines.length)return sd.delete(t),null;const r=await readHostNodeFloor(t),s=r?r.accepts:()=>!0,i=await resolveManagedNodeVersion(),a=selectNodeOverride({currentVersion:i,requirement:e,candidates:await discoverVersionManagerNodes({env:process.env,homeDir:zi.homedir(),platform:process.platform}),floorOk:s});if("none"===a.kind)return sd.delete(t),null;if("override"===a.kind)return sd.delete(t),devLog("supervisor:project_node_override",{cwd:t,currentVersion:i,chosenVersion:a.candidate.version,source:a.candidate.source,binDir:a.candidate.binDir,engines:e.engines,versionFileSpec:e.versionFileSpec}),{...a.candidate,bundled:!1};const o=getBundledNodeBinDir(),c=o?await probeNodeVersion(applyBundledNodeEnv(buildManagedCommandEnv({skipBundledNode:!0}),o)):null;return o&&c&&versionSatisfiesRequirement(c,e)&&s(c)?(sd.delete(t),devLog("supervisor:project_node_override",{cwd:t,currentVersion:i,chosenVersion:c,source:"bundled",binDir:o,engines:e.engines,versionFileSpec:e.versionFileSpec}),{binDir:o,version:c,source:"bundled",bundled:!0}):(sd.set(t,{requirement:a.requirement,currentVersion:a.currentVersion}),devLog("supervisor:project_node_unsatisfied",{cwd:t,currentVersion:i,requirement:a.requirement,bundledVersion:c}),rd.delete(n),null)})().catch(e=>(rd.delete(n),devLog("supervisor:project_node_resolution_failed",{cwd:t,message:e instanceof Error?e.message:String(e)}),null));return rd.set(n,s),await s}async function getAvailableLocalPort(e=new Set){return await new Promise((t,n)=>{const r=Ki();r.unref(),r.on("error",n),r.listen(0,"127.0.0.1",()=>{const s=r.address(),i=s&&"object"==typeof s?s.port:null;i&&e.has(i)?getAvailableLocalPort(e).then(e=>r.close(()=>t(e)),e=>r.close(()=>n(e))):r.close(()=>{i?t(i):n(new Error("Could not allocate a local port"))})})})}function portFromConfiguredTempoHostUrl(e){if(!e||"string"!=typeof e||e.includes("${PORT}"))return null;try{const t=new URL(e);if(t.port)return Number(t.port)}catch{}return null}function buildManagedStartPlan(e){const t=e.command.includes("${PORT}"),n=portFromConfiguredTempoHostUrl(e.tempoHostUrl),r="string"==typeof e.tempoHostUrl&&e.tempoHostUrl.includes("${PORT}"),s=canInjectDevServerPort(e.command),i=t?substituteAppPort(e.command,e.port):s?injectDevServerPort(e.command,e.port,e.framework):e.command,a="string"==typeof e.tempoHostUrl?substituteAppPort(e.tempoHostUrl,e.port):null,o=t||r||s||null!==e.tempoHostUrl;return{command:i,tempoHostUrl:a,injectedPort:e.port,portWasTempoAllocated:null===n,env:{TEMPO_PORT:String(e.port),...o?{PORT:String(e.port)}:{}}}}function isExpoStartCommand(e){return/\bexpo\s+start\b/.test(e)}function canInjectDevServerPort(e){return/\b(?:npm|pnpm|bun)\s+(?:run\s+)?dev\b/.test(e)||/\byarn\s+dev\b/.test(e)||isDirectDevServerCommand(e)}function isDirectDevServerCommand(e){return/\bnext\s+dev\b/.test(e)||/\bnux[ti]\s+dev\b/.test(e)||/\bvite\b/.test(e)||isExpoStartCommand(e)}function shouldRetryWithBundledNode(e){return"node-version-unsupported"===e.hintClass&&canInjectDevServerPort(e.command)&&e.bundledNodeAvailable&&!e.bundledNodeAlreadyActive}function injectDevServerPort(e,t,n){const r="next"===n?`-H 127.0.0.1 -p ${t}`:"expo"===n?`--host localhost --port ${t}`:`--host 127.0.0.1 --port ${t}`;return isDirectDevServerCommand(e)||e.includes(" -- ")?`${e} ${r}`:`${e} -- ${r}`}function shouldRetryPortCollision(e,t){return!e.ok&&("port-in-use"===t.getLastHint()?.class||/EADDRINUSE|address already in use/i.test(e.message??""))}function mapResultToAttemptOutcome(e){const t=(e.url??e.message??"").slice(0,200);if(e.ok&&e.url)return{outcome:"ready",exitCode:null,signal:null,detail:t};if(e.crashed){const n=/\(code (\d+)\)/i.exec(e.message??""),r=/\(signal ([A-Z0-9]+)\)/i.exec(e.message??"");return{outcome:"crashed",exitCode:n?Number(n[1]):null,signal:r?r[1]:null,detail:t}}return e.probeBlocked?{outcome:"probe-blocked",exitCode:null,signal:null,detail:t}:e.wrongResponder?{outcome:"wrong-responder",exitCode:null,signal:null,detail:t}:e.timedOut?{outcome:"timed-out",exitCode:null,signal:null,detail:t}:{outcome:"not-ready",exitCode:null,signal:null,detail:t}}function portFromReadyUrl(e){if(!e)return null;const t=/:(\d+)(?:\/|$)/.exec(e);return t?Number(t[1]):null}var id="unlink|rename|rmdir|copyfile",ad=new RegExp(`(?:EPERM|EACCES|EBUSY)[\\s\\S]{0,400}?(?:${id})|(?:${id})[\\s\\S]{0,400}?(?:EPERM|EACCES|EBUSY)|operation not permitted|permission denied|resource busy or locked`,"i");function classifyInterruptedInstallOutput(e){return/\bTAR_ENTRY_ERROR\b/.test(e)?"concurrent-install":/\bENOTEMPTY\b/.test(e)?"inconsistent-tree":null}function classifyInstallFailure(e,t){if(isShellParseAbortOutput(t))return new Os(e,t);if(/ERESOLVE|unable to resolve dependency tree|could not resolve/i.test(t))return new Ps(e,t);const n=classifyInterruptedInstallOutput(t);if(n)return new Ns(e,t,n);if(/\bEBUSY\b|resource busy or locked/i.test(t))return new Rs(e,t);if(ad.test(t))return new Cs(e,t);const r=describeInstallConnectivity(t);return r?new As(e,t,r):null}function isIgnoredBuildScriptsOnlyFailure(e){return/ERR_PNPM_IGNORED_BUILDS/.test(e)}var od=[1e3,3e3,6e3];async function runInstallCommandWithLockRetry(e,t,n=runShellCommand,r=od,s,i){for(let a=0;;a+=1){Ol(s);try{return void await n(e,t,s)}catch(t){if(t instanceof _s)throw t;const n=t instanceof Error?t.message:String(t),o=r[a];if(void 0===o||!isTransientFsLockOutput(n))throw t;devLog("supervisor:install_lock_retry",{command:e,attempt:a,delay:o}),0===a&&await(i?.()),await Dl(o,s)}}}async function runInstallStep(e,t,n,r=e.cwd,s={},i){Ol(t),await Promise.all([...new Set([...e.markerRoots??[],...e.externalLayoutMarkerRoots??[]])].map(invalidateInstallCompletionMarkers)),Ol(t),e.cleanBeforeInstall&&(await Gi(Ji.join(e.cwd,"node_modules"),{recursive:!0,force:!0}).catch(t=>{console.warn(`[tempo-devserver] ${e.label}: failed to clean node_modules before install:`,t)}),Ol(t)),await Promise.all((e.markerRoots??[]).map(writeInstallInProgressMarker));try{await runInstallCommandWithLockRetry(e.command,e.cwd,(e,t,i)=>runShellCommand(e,t,i,n,r,s),od,t,i)}catch(n){if(Ol(t),n instanceof _s)throw n;const r=n instanceof Error?n.message:String(n);if(isIgnoredBuildScriptsOnlyFailure(r)&&await nodeModulesHasMeaningfulEntries(e.cwd))return console.warn(`[tempo-devserver] ${e.label}: pnpm skipped dependency build scripts (ERR_PNPM_IGNORED_BUILDS) but node_modules is populated — treating as a successful install.`),void await recordInstallStepCompleted(e);throw classifyInstallFailure(e.command,r)??n}Ol(t),await recordInstallStepCompleted(e)}async function recordInstallStepCompleted(e){await Promise.all((e.markerRoots??[]).map(e=>Gi(installInProgressMarkerPath(e),{force:!0}))),await Promise.all((e.markerRoots??[]).map(writeInstallCompletionMarker)),await Promise.all((e.externalLayoutMarkerRoots??[]).map(writeExternalLayoutInstallMarker))}async function writeInstallInProgressMarker(e){try{await Hi(Ji.join(e,"node_modules"),{recursive:!0}),await Wi(installInProgressMarkerPath(e),"","utf-8")}catch(t){console.warn(`[tempo-devserver] failed to write install-in-progress marker at ${e}:`,t)}}async function sleepForStatusRetry(e){await new Promise(t=>setTimeout(t,e))}async function writeStatusTextBestEffort(e,t){await Hi(Ji.dirname(e),{recursive:!0});const n=[25,75,150];let r=null;for(let s=0;s<=n.length;s+=1)try{return void await atomicWriteText2(e,t)}catch(e){r=e,s<n.length&&await sleepForStatusRetry(n[s])}try{return void await Wi(e,t,"utf-8")}catch(e){throw e??r}}function augmentManagedPath(e){if("win32"!==process.platform)return e;const t=[process.env.ProgramFiles?Ji.join(process.env.ProgramFiles,"nodejs"):null,process.env.APPDATA?Ji.join(process.env.APPDATA,"npm"):null,process.env.LOCALAPPDATA?Ji.join(process.env.LOCALAPPDATA,"pnpm"):null,process.env.USERPROFILE?Ji.join(process.env.USERPROFILE,".bun","bin"):null,process.env.USERPROFILE?Ji.join(process.env.USERPROFILE,".volta","bin"):null].filter(e=>Boolean(e)),n=Object.keys(e).find(e=>"path"===e.toLowerCase()),r=n?e[n]:e.PATH,s=[...t,r].filter(Boolean).join(Ji.delimiter);return{...e,[n??"PATH"]:s}}function buildManagedCommandEnv(e={}){const t={...process.env,NODE_ENV:"development",TEMPO:"true",BROWSER:"none",COREPACK_INTEGRITY_KEYS:"0"};e.forInstall&&(t.CI="1");const n=augmentManagedPath(t);for(const e of Object.keys(n)){const t=e.toLowerCase(),r="npm_config_registry"===t||"pnpm_config_registry"===t;r||(t.startsWith("npm_")||t.startsWith("pnpm_")||"INIT_CWD"===e||"NODE_PATH"===e)&&delete n[e]}Object.assign(n,tempoSdkDevCommandEnv());const r=getBundledNodeBinDir();if(e.skipBundledNode)return r?removeDirFromPathEnv(n,r):n;const s=isBundledNodeActivated()?applyBundledNodeEnv(n,r):n;if(e.projectNode){const t=e.projectNode.bundled?applyBundledNodeEnv(s,e.projectNode.binDir):prependDirToPathEnv(s,e.projectNode.binDir);return e.projectNode.nodenvVersion?{...t,NODENV_VERSION:e.projectNode.nodenvVersion}:t}return s}function spawnManagedLongRunningCommand(e){return e.watchdogScriptPath?Li(process.execPath,[e.watchdogScriptPath,e.command],{cwd:e.cwd,detached:"win32"!==process.platform,stdio:["pipe","pipe","pipe"],windowsHide:!0,env:{...e.env,TEMPO_WATCHDOG_CHILD_ELECTRON_RUN_AS_NODE:e.env.ELECTRON_RUN_AS_NODE??"__TEMPO_UNSET__",ELECTRON_RUN_AS_NODE:"1"}}):Li(e.command,{cwd:e.cwd,shell:!0,detached:"win32"!==process.platform,stdio:["ignore","pipe","pipe"],windowsHide:!0,env:e.env})}async function runTaskkill(e,t){return await new Promise(n=>{const r=["/pid",String(e),"/t"];t&&r.push("/f");const s=Li("taskkill",r,{stdio:"ignore",windowsHide:!0});s.on("error",()=>{n(null)}),s.on("exit",e=>{n(e)})})}function parsePidList(e,t){const n=new Set;for(const r of e.split(/\s+/)){const e=Number(r.trim());Number.isInteger(e)&&e>0&&e!==t&&n.add(e)}return[...n]}async function runProcessQuery(e,t){return"win32"===process.platform?"":await new Promise(n=>{let r=!1;const finish=e=>{r||(r=!0,n(e))};try{const n=Li(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0});let r="";n.stdout?.on("data",e=>{r+=String(e)}),n.on("error",()=>finish("")),n.on("exit",()=>finish(r)),setTimeout(()=>{try{n.kill("SIGKILL")}catch{}finish(r)},2500)}catch{finish("")}})}async function readProcessStartedAt(e){return await readPidStartIdentity(e)}async function resolveDescendantPids(e){if("win32"===process.platform)return[];const t=new Set,n=[e];let r=0;for(;n.length>0&&r<256;){r+=1;const e=n.shift();if(null==e)break;const s=await runProcessQuery("pgrep",["-P",String(e)]);for(const e of parsePidList(s,process.pid))t.has(e)||(t.add(e),n.push(e))}return t.delete(e),[...t]}async function killProcessTreeByPid(e){if(!isPidAlive(e))return null;if("win32"===process.platform){const t=await runTaskkill(e,!0);if(!await waitForPidGone(e,1500)){devLog("supervisor:taskkill_survivor_direct_kill",{pid:e});try{process.kill(e,"SIGKILL")}catch{}}return t}try{return process.kill(-e,"SIGKILL"),null}catch{}try{process.kill(e,"SIGKILL")}catch{}return null}async function terminateProcessTreeByPid(e,t,n){if(isPidAlive(e)){if("win32"===process.platform)return await killProcessTreeByPid(e),void await waitForPidGone(e,n);try{process.kill(-e,"SIGTERM")}catch{try{process.kill(e,"SIGTERM")}catch{}}await waitForPidGone(e,t)||(await killProcessTreeByPid(e),await waitForPidGone(e,n))}}async function signalManagedLongRunningProcess(e,t){const n=e.pid;if(n)if("win32"!==process.platform){try{return void process.kill(-n,t)}catch{}try{e.kill(t)}catch{}}else await runTaskkill(n,"SIGKILL"===t)}function forceKillManagedLongRunningProcess(e,t){const n=e.pid;if(n&&null===e.exitCode&&null===e.signalCode)if("win32"!==process.platform){if(t){try{e.stdin?.destroy()}catch{}try{return void process.kill(-n,"SIGTERM")}catch{}}try{return void process.kill(-n,"SIGKILL")}catch{}try{e.kill("SIGKILL")}catch{}}else try{const e=Li("taskkill",["/pid",String(n),"/t","/f"],{stdio:"ignore",windowsHide:!0,detached:!0});e.unref()}catch{}}async function terminateManagedLongRunningProcess(e,t){const n=e.pid;if(!n)return!0;const r=[n,...await resolveDescendantPids(n).catch(()=>[])];if(!r.some(isPidAlive))return!0;if(await signalManagedLongRunningProcess(e,"SIGTERM"),await waitForProcessTreePidsGone(r,t.gracefulShutdownMs))return!0;if(await signalManagedLongRunningProcess(e,"SIGKILL"),"win32"===process.platform)for(const e of r)if(isPidAlive(e))try{process.kill(e,"SIGKILL")}catch{}return await waitForProcessTreePidsGone(r,t.forcedShutdownMs)}async function waitForProcessTreePidsGone(e,t){const n=Date.now();for(;Date.now()-n<t;){if(!e.some(isPidAlive))return!0;await new Promise(e=>setTimeout(e,50))}return!e.some(isPidAlive)}function isPidAlive(e){try{return process.kill(e,0),!0}catch(e){return"EPERM"===e?.code}}async function waitForPidGone(e,t){const n=Date.now();for(;Date.now()-n<t;){if(!isPidAlive(e))return!0;await new Promise(e=>setTimeout(e,50))}return!isPidAlive(e)}async function runBoundedShellCommand(e){const t=extractLeadingEnvAssignments(e.command);return await new Promise(n=>{let r=!1,s="";const recordOutput=e=>{s=`${s}${e.toString()}`.slice(-4e3)},finish=e=>{r||(r=!0,clearTimeout(a),n(e))};let i;try{i=Li(t.command,{cwd:e.cwd,shell:!0,stdio:["ignore","pipe","pipe"],windowsHide:!0,detached:"win32"!==process.platform,env:{...e.env,...t.env}})}catch{return n({ok:!1,timedOut:!1,exitCode:null,output:s})}i.stdout?.on("data",recordOutput),i.stderr?.on("data",recordOutput);const a=setTimeout(()=>{forceKillManagedLongRunningProcess(i,!1),finish({ok:!1,timedOut:!0,exitCode:i.exitCode,output:s})},e.timeoutMs);i.on("error",()=>finish({ok:!1,timedOut:!1,exitCode:null,output:s})),i.on("exit",e=>finish({ok:0===e,timedOut:!1,exitCode:e,output:s}))})}async function runShellCommand(e,t,n,r,s=t,i={}){Ol(n);const a=toProjectNodeEnvOption(await resolveProjectNodeOverrideForDir(t)),o=extractLeadingEnvAssignments(e),c={...process.env,...o.env},l=await readInstallRegistryEnv(t,s,c),d={...l,...buildManagedCommandEnv({forInstall:!0,projectNode:a}),...i,...o.env},u=await readPackageManagerConfigEnv(t,{...c,...d}),p=await runAbortableShellCommand({command:o.command,cwd:t,signal:n,env:{...d,...u},onOutput:r,idleTimeoutMs:cc});if(p.aborted)throw Nl();if(p.timedOut)throw new _s(e,p.output);if(p.spawnError)throw p.spawnError;if(0===p.exitCode)return;const h=p.output.trim();throw new bs(e,p.exitCode,h)}async function prepareAppTempoSdkDevSource(e,t,n={}){if(Ol(t),protectedRootFor(e))return;if("local-prebuilt"!==process.env[Uo]&&!await hasTempoSdkDevSource(e))return;const r=await readTextFileOptional2(Ji.join(e,"package.json"));if(!r)return;const s=JSON.parse(r),i=[s.dependencies?.["tempo-sdk"],s.devDependencies?.["tempo-sdk"]].filter(e=>"string"==typeof e);if(!i.length||i.some(isPinnedTempoSdkSpec))return;const a=Ji.join(e,".tempo",jo),o=await readTextFileOptional2(a);try{const r=await ensureTempoSdkChannelSpec(e,t,n);if(r.error)throw new bs(r.plan.updateCommand,null,r.error);Ol(t)}catch(e){throw null!==o&&await Wi(a,o),e}}function configuredNpmRegistry(){const e=process.env.npm_config_registry?.trim()||process.env.NPM_CONFIG_REGISTRY?.trim()||"https://registry.npmjs.org";return e.replace(/\/+$/,"")}async function ensureTempoSdkChannelSpec(e,t,n={}){Ol(t);const r=n.updateCommand?.trim(),s=n.runCommand??runShellCommand,i=r?null:await Ui(Ji.join(zi.tmpdir(),"tempo-sdk-meta-")).catch(()=>null),cleanupMetadataCache=async()=>{i&&await Gi(i,{recursive:!0,force:!0}).catch(()=>{})},a=await resolveTempoSdkUpgradePlan(e,{...i?{metadataCacheDir:i}:{}}).catch(async e=>{throw await cleanupMetadataCache(),e}),o=r?{...a,updateCommand:r,remediationCommand:r}:a;if(t?.aborted)throw await cleanupMetadataCache(),Nl();const c=protectedRootFor(e);if(c)return devLog("supervisor:sdk_spec_skipped_protected",{cwd:e,protectedRoot:c}),await cleanupMetadataCache(),{attempted:!1,plan:o};const l=await prepareTempoSdkDevSource(e).catch(async e=>{throw await cleanupMetadataCache(),e});if(t?.aborted)throw await cleanupMetadataCache(),Nl();if("local"===l.source)return devLog("supervisor:sdk_source_local",{cwd:e,localSdkRoot:l.localSdkRoot}),await cleanupMetadataCache(),{attempted:!1,plan:o};l.removedLocalLink&&devLog("supervisor:sdk_source_restoring_published",{cwd:e});let d=!1,u=!1;try{const i=Ji.join(e,"package.json"),ensureChannelSpec=async(e=!0)=>{const t=await $i(i,"utf-8").catch(()=>null);if(!t)return!1;const n=JSON.parse(t),r=n.dependencies&&"object"==typeof n.dependencies&&!Array.isArray(n.dependencies)?n.dependencies:void 0,s=n.devDependencies&&"object"==typeof n.devDependencies&&!Array.isArray(n.devDependencies)?n.devDependencies:void 0;let a;void 0!==r?.["tempo-sdk"]?a=r:void 0!==s?.["tempo-sdk"]?a=s:(n.devDependencies=s??{},a=n.devDependencies);const c=a["tempo-sdk"];return"string"==typeof c&&isPinnedTempoSdkSpec(c)?"pinned-local":c!==o.tag&&(!e||(a["tempo-sdk"]=o.tag,await Wi(i,`${JSON.stringify(n,null,2)}\n`),!0))},a=await ensureChannelSpec(!1);if("pinned-local"===a)return devLog("supervisor:sdk_spec_pinned_local",{cwd:e}),{attempted:!1,plan:o};const c=!("yarn"===o.packageManager&&void 0!==o.syncLockfileCommand);if(r){const e=findPowerShellSyntax(r);if(e)throw new Os(r,describePowerShellRejection(e));c&&await ensureChannelSpec(),d=!0,await s(o.updateCommand,o.cwd,t),Ol(t);const n=await ensureChannelSpec();return!0===n&&o.syncLockfileCommand&&(await s(o.syncLockfileCommand,o.cwd,t),Ol(t)),{attempted:!0,plan:o}}const l=Ji.join(e,"node_modules"),p=Ji.join(l,"tempo-sdk","package.json"),[h,m]=await Promise.all([$i(p,"utf-8").catch(()=>null),fetch(`${configuredNpmRegistry()}/tempo-sdk/${o.tag}`,{signal:t?AbortSignal.any([t,AbortSignal.timeout(3e3)]):AbortSignal.timeout(3e3)}).catch(()=>null)]);if(Ol(t),!m?.ok)return{attempted:!1,error:`could not reach the npm registry to resolve the tempo-sdk@${o.tag} (${m?`HTTP ${m.status}`:"network error/timeout"})`,plan:o};const f=await m.json(),g=f.version;if(!g)return{attempted:!1,error:`the npm registry returned no version for tempo-sdk@${o.tag}`,plan:o};const y=await tempoSdkRuntimeProvisioningError(f,n.runtimePath??process.env.TEMPO_SDK_RUNTIME_PATH);if(y)return{attempted:!1,error:y,plan:o};const v=h?JSON.parse(h).version:null;if(!a&&v===g)return{attempted:!0,error:`installed tempo-sdk ${v} is already the newest published version`,plan:o};c&&await ensureChannelSpec(),d=!0;try{await s(o.updateCommand,o.cwd,t)}catch(e){const t=e instanceof Error?e.message:String(e);if(!isIgnoredBuildScriptsOnlyFailure(t)||!await nodeModulesHasMeaningfulEntries(o.cwd))throw e;u=!0,console.warn("[tempo-devserver] tempo-sdk update skipped dependency build scripts (ERR_PNPM_IGNORED_BUILDS); verifying the installed SDK version.")}Ol(t);const E=await ensureChannelSpec();!0===E&&o.syncLockfileCommand&&(await s(o.syncLockfileCommand,o.cwd,t),Ol(t));const T=await $i(p,"utf-8").catch(()=>null),w=T?JSON.parse(T).version:null;if(w!==g){const e=u?"linked dependencies, then reported ERR_PNPM_IGNORED_BUILDS, but tempo-sdk is still":"reported success but tempo-sdk is still";throw new Error(`\`${o.updateCommand}\` ${e} ${w??"not installed"} (registry ${o.tag} is ${g}). This is usually a stale ${o.packageManager} registry metadata cache.`)}return{attempted:!0,plan:o}}catch(e){const t=e instanceof Error?e.message:String(e);return devLog("supervisor:sdk_upgrade_failed",{cwd:o.cwd,command:o.updateCommand,packageManager:o.packageManager,updateCommandStarted:d,message:t}),{attempted:d,error:t,plan:o}}finally{await cleanupMetadataCache()}}async function readJsonFile(e){try{return JSON.parse(await $i(e,"utf-8"))}catch{return null}}async function readTempoProcessMarker(e){const t=await readJsonFile(e);if("tempo"===t?.owner&&"number"==typeof t.pid&&Number.isInteger(t.pid)&&t.pid>0){const e=Array.isArray(t.workerPids)?t.workerPids.filter(e=>"number"==typeof e&&Number.isInteger(e)&&e>0):[];return{pid:t.pid,workerPids:e}}return null}var cd=new Set(["127.0.0.1","localhost","::1","[::1]","0.0.0.0","::"]);function normalizeServerUrl(e){try{const t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol)return null;"0.0.0.0"!==t.hostname&&"::"!==t.hostname||(t.hostname="127.0.0.1");const n=t.pathname.replace(/\/+$/,"");return`${t.origin}${"/"===n?"":n}`}catch{return null}}function extractServerUrl2(e){const t=e.replace(/\x1b\[[0-9;]*m/g,""),n=t.match(/https?:\/\/[^\s"'`<>]+/gi);if(!n||0===n.length)return null;for(const e of n){const t=e.replace(/[),.;]+$/,""),n=normalizeServerUrl(t);if(n)try{const e=new URL(n);if(cd.has(e.hostname.toLowerCase()))return n}catch{}}return null}function buildTempoHostUrl(e){const t=normalizeServerUrl(e);if(!t)return`${e.replace(/\/+$/,"")}${xl}`;const n=new URL(t);return n.pathname===xl||n.pathname.startsWith(`${xl}/`)?t:`${n.origin}${xl}`}function stripTempoHostRoute(e){const t=normalizeServerUrl(e);if(!t)return e.replace(/\/tempo-host\/?$/,"")||e;const n=new URL(t);return n.pathname===xl||n.pathname.startsWith(`${xl}/`)?n.origin:t}function isTempoHostDocument(e){return e.includes("tempo-project-root")||/<title>\s*tempo-host\s*<\/title>/i.test(e)}var ld=/<meta\b[^>]*\bname=["']tempo-project-root["'][^>]*\bcontent=["']([^"']*)["']/i;function readAdvertisedProjectRoot(e){const t=ld.exec(e);return t?t[1]:null}function advertisedRootBelongsToWorkspace(e,t){const norm=e=>{try{return Fi.realpathSync(e)}catch{return Ji.resolve(e)}},n=norm(e),r=norm(t);if(n===r)return!0;const s=n.endsWith(Ji.sep)?n:`${n}${Ji.sep}`,i=r.endsWith(Ji.sep)?r:`${r}${Ji.sep}`;return n.startsWith(i)||r.startsWith(s)}var dd=65536;async function readBoundedFetchBody(e){if(!e.body)return"";const t=e.body.getReader(),n=new TextDecoder;let r=dd,s="";try{for(;r>0;){const{done:e,value:i}=await t.read();if(e)break;const a=i.subarray(0,r);if(r-=a.length,s+=n.decode(a,{stream:r>0}),a.length<i.length)break}return s+=n.decode(),s}finally{0===r&&await t.cancel().catch(()=>{})}}async function fetchBodyTextViaFetch(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),t);try{const t=await fetch(e,{signal:n.signal,headers:{accept:"text/html"}}),r=await readBoundedFetchBody(t);return{status:t.status,body:r}}catch{return null}finally{clearTimeout(r)}}function fetchBodyTextViaNodeHttp(e,t){let n;try{n=new URL(e)}catch{return Promise.resolve(null)}return"http:"!==n.protocol?Promise.resolve(null):new Promise(e=>{let r;const finish=t=>{clearTimeout(r),e(t)},s=Vi(n,{headers:{accept:"text/html"}},e=>{const t=[];let n=0;e.on("data",e=>{if(n>=dd)return;const r=dd-n,s=e.subarray(0,r);t.push(s),n+=s.length}),e.on("end",()=>finish({status:e.statusCode??0,body:Buffer.concat(t).toString("utf-8")})),e.on("error",()=>finish(null))});r=setTimeout(()=>{s.destroy(),finish(null)},t),s.on("error",()=>finish(null)),s.end()})}var ud=[];function firstNonNullResponse(e){return 0===e.length?Promise.resolve(null):new Promise(t=>{let n=e.length,r=!1;for(const s of e)s.then(e=>e,()=>null).then(e=>{n-=1,r||(null!==e?(r=!0,t(e)):0===n&&t(null))})})}async function fetchProbeResponse(e,t){const n=[fetchBodyTextViaFetch,fetchBodyTextViaNodeHttp,...ud];return withTimeout(firstNonNullResponse(n.map(n=>n(e,t).catch(()=>null))),t,"Host probe response timeout").catch(()=>null)}async function probeTempoHost(e,t,n,r){const s=await fetchProbeResponse(e,t),i=s?.body??null,a=null!==i&&isTempoHostDocument(i);let o=!1;if(null!==i&&n){const e=readAdvertisedProjectRoot(i);e&&!advertisedRootBelongsToWorkspace(e,n)&&(o=!0,devLog("probe:project_root_diagnostic_mismatch",{advertised:e,expectedProjectRoot:n}))}if(!r&&o)return"wrong-responder";if(!r)return"identity-incompatible";const{outcome:c}=await probeTempoIdentityEndpoint(e,t,r);return"ok"===c?"ok":"verified-incompatible"===c?"identity-incompatible":"wrong-responder"===c?"wrong-responder":a&&"identity-incompatible"===c?"identity-incompatible":null!==i?"wrong-responder":"unreachable"}async function probeTempoIdentityEndpoint(e,t,n){const r=performance.now();let s=null;const observed=e=>({outcome:e,status:s,elapsedMs:Math.round(performance.now()-r)});let i;try{i=`${new URL(e).origin}/__tempo/identity`}catch{return observed("unreachable")}const a=await fetchProbeResponse(i,t);if(s=a?.status??null,null===a)return observed("unreachable");if(a.status<200||a.status>=300)return observed("identity-incompatible");let o;try{o=JSON.parse(a.body)}catch{return observed("identity-incompatible")}return!0!==o.tempoHost?observed("identity-incompatible"):n?o.workspaceNonce!==n.workspaceNonce?observed("wrong-responder"):"number"!=typeof o.contractVersion||o.contractVersion<1||!0!==o.pluginActive||o.framework!==n.framework||"string"!=typeof o.sdkVersion||!tempoSdkIdentitySatisfiesCanvasHost(o)?observed("verified-incompatible"):observed("ok"):observed("identity-incompatible")}async function waitForHttpReachable(e,t,n,r){const s=Date.now();let i=!1,a=!1;for(;Date.now()-s<t;){const t=await probeTempoHost(e,1200,n,r);if("ok"===t)return{reachable:!0,sawResponder:!0,identityFailure:!1};"unreachable"!==t&&(i=!0),a||="identity-incompatible"===t,await sleep3(120)}return{reachable:!1,sawResponder:i,identityFailure:a}}async function waitForFirstHttpReachable(e,t,n,r,s){const i=Date.now();let a=!1,o=!1;for(;Date.now()-i<t;){for(const t of e){const e=await waitForHttpReachable(t,250,n,r);if(a=a||e.sawResponder,o=o||e.identityFailure,e.reachable)return{url:t,sawResponder:a,identityFailure:!1}}if(s&&!s())return{url:null,sawResponder:a,identityFailure:o};await sleep3(120)}return{url:null,sawResponder:a,identityFailure:o}}async function waitForFirstHttpReachableWithinBudget(e,t,n,r,s,i){let a=!1,o=null,c=!1;const notReady=e=>({url:null,sawResponder:a,identityFailure:e.responderVerdict&&c,...e});for(;;){const l=Date.now();let d=!1,u=!1;for(const t of e){const e=await waitForHttpReachable(t,250,n,r);if(e.reachable)return{url:t,sawResponder:!0,identityFailure:!1,responderVerdict:!1,expiry:null};d||=e.sawResponder,u||=e.identityFailure}if(a||=d,d){if(o??=l,c||=u,Date.now()-o>=t.responderBudgetMs)return notReady({responderVerdict:!0,expiry:null})}else o=null,c=!1;if(!s())return notReady({responderVerdict:!1,expiry:null});const p=i();if(p)return notReady({responderVerdict:!1,expiry:p});await sleep3(120)}}function formatSeconds(e){return String(Number((e/1e3).toFixed(1)))}function raiseStartStallAdvice(e){return`raise timeouts.startStallSeconds in tempo/tempo.config.json (in effect: ${formatSeconds(e.stallMs)})`}function describeStartStall(e,t){const n=t?`did not answer as this workspace's Tempo host at ${t}`:"never printed its URL";return`The canvas host printed no output for ${formatSeconds(e.stallMs)}s and ${n}, so Tempo stopped it. If this project's first build legitimately takes longer, ${raiseStartStallAdvice(e)}.`}function describeStartCap(e,t,n){const r=t?` at ${t}`:"",s=formatSeconds(e.absoluteCapMs),i=n?`was restarted during this start and was still printing output, but had not become ready${r} after ${s}s, Tempo's limit for one start including restarts`:`was still printing output but had not become ready${r} after ${s}s, Tempo's limit for one start`;return`The canvas host ${i}, so Tempo stopped it. ${startCapAdvice(e)}`}function describeRetrySkippedAtCap(e){return`The canvas host failed before it became ready, and this start had already used Tempo's ${formatSeconds(e.absoluteCapMs)}s limit for one start, so Tempo did not start it again. ${startCapAdvice(e)}`}function startCapAdvice(e){return`The limit grows with timeouts.startStallSeconds; if this project's first build legitimately takes longer, ${raiseStartStallAdvice(e)}.`}function describeUnansweredConnection(e,t,n,r){let s="";return"stall"===r?.reason?s=`, and printed no output for the last ${formatSeconds(n.stallMs)}s`:"cap"===r?.reason&&(s=`, reaching Tempo's ${formatSeconds(n.absoluteCapMs)}s limit for one start`),`The canvas host on ${e} accepted the connection but did not answer HTTP for ${formatSeconds(t)}s${s}. It may still be busy with its first build: if this project's first build legitimately takes longer, ${raiseStartStallAdvice(n)}. Otherwise something on this machine is filtering local (loopback) HTTP, such as a firewall or antivirus.`}async function tcpConnectOnce(e,t){let n,r;try{const t=new URL(e);n=t.hostname,r=Number(t.port)||("https:"===t.protocol?443:80)}catch{return!1}return await new Promise(e=>{const s=Yi({host:n,port:r}),finish=t=>{s.destroy(),e(t)};s.setTimeout(t,()=>finish(!1)),s.once("connect",()=>finish(!0)),s.once("error",()=>finish(!1))})}function expandLoopbackHostVariants(e){const t=[];for(const n of e)try{const e=new URL(n);if("127.0.0.1"===e.hostname)e.hostname="localhost";else{if("localhost"!==e.hostname)continue;e.hostname="127.0.0.1"}t.push(e.toString())}catch{}const n=[...e,...t];return n.filter((e,t)=>n.indexOf(e)===t)}async function waitForHttpUnreachable(e,t){const n=Date.now();for(;Date.now()-n<t;){try{const t=new AbortController,n=setTimeout(()=>t.abort(),1e3);await fetch(e,{signal:t.signal}),clearTimeout(n)}catch{return!0}await sleep3(120)}return!1}async function probeUrlOnce(e,t,n,r){return"ok"===(await probeHostHealth(e,t,n,r)).outcome}async function probeHostHealth(e,t,n,r){const s=performance.now(),i=r?await probeTempoIdentityEndpoint(e,t,r):{outcome:await probeTempoHost(e,t,n),status:null,elapsedMs:Math.round(performance.now()-s)};return"ok"!==i.outcome&&devLog("supervisor:url_probe_failed",{url:e,probe:r?"identity":"document",timeoutMs:t,...i}),i}async function withTimeout(e,t,n){return await new Promise((r,s)=>{const i=setTimeout(()=>{s(new Error(n))},t);e.then(e=>{clearTimeout(i),r(e)}).catch(e=>{clearTimeout(i),s(e)})})}function sleep3(e){return new Promise(t=>{setTimeout(t,e)})}import{randomUUID as pd}from"crypto";import{readFile as hd}from"fs/promises";import md from"path";import{readdir as fd,readFile as gd,stat as yd}from"fs/promises";import vd from"path";async function readTextFileOptional3(e){try{return await gd(e,"utf-8")}catch(e){if("ENOENT"===e.code)return null;throw e}}async function pathIsDirectory(e){try{return(await yd(e)).isDirectory()}catch{return!1}}async function readJsonObjectOptional(e){const t=await readTextFileOptional3(e);if(null===t)return null;try{const e=JSON.parse(t);return!e||"object"!=typeof e||Array.isArray(e)?null:e}catch{return null}}var Ed=["next","vite","@vitejs/plugin-react","expo","react-scripts","@remix-run/dev","@sveltejs/kit","nuxt"];function collectDependencyNames(e){const t=new Set;for(const n of["dependencies","devDependencies"]){const r=e[n];if(r&&"object"==typeof r&&!Array.isArray(r))for(const e of Object.keys(r))t.add(e)}return t}async function isAppPackageDir(e){const t=await readJsonObjectOptional(vd.join(e,"package.json"));if(!t)return!1;const n=collectDependencyNames(t);return Ed.some(e=>n.has(e))}async function findAppPackageSubdirs(e){let t;try{t=await fd(e.projectRoot,{withFileTypes:!0})}catch{return[]}const n=vd.resolve(e.tempoRoot),r=[];for(const s of t){if(!s.isDirectory())continue;if("node_modules"===s.name||s.name.startsWith("."))continue;const t=vd.join(e.projectRoot,s.name);vd.resolve(t)!==n&&(await isAppPackageDir(t)&&r.push(t))}return r}function multipleAppDirectoriesWarning(e,t){return`Found multiple app directories (${t.map(t=>toPosixRelativePath(e.projectRoot,t)).join(", ")}); set "apps[0].appDir" in tempo/tempo.config.json to pick one. Using the project root.`}async function resolveAppRoot(e){if(e.appDir&&"."!==e.appDir){const t=vd.resolve(e.projectRoot,e.appDir);return await pathIsDirectory(t)?{appRoot:t,warning:null}:{appRoot:e.projectRoot,warning:`tempo.config.json "appDir" ("${e.appDir}") is not a directory under the project root; using the project root.`}}if(await isAppPackageDir(e.projectRoot))return{appRoot:e.projectRoot,warning:null};const t=await findAppPackageSubdirs(e);return 1===t.length?{appRoot:t[0],warning:null}:t.length>1?{appRoot:e.projectRoot,warning:multipleAppDirectoriesWarning(e,t)}:{appRoot:e.projectRoot,warning:null}}function toPosixRelativePath(e,t){const n=vd.relative(e,t);return""===n?".":n.replace(/\\/g,"/")}import{readFileSync as Td}from"fs";import{access as wd,mkdir as Sd,readFile as bd,rm as Ad,writeFile as _d}from"fs/promises";import kd from"path";import Id from"path";var Cd="./designs";import Rd from"path";var Pd=["react","svelte","vue","astro","flutter"],Nd=10,Od=3600,Dd="tempo.config.json",Ld="tempo";async function pathExists3(e){try{return await wd(e),!0}catch{return!1}}function isObjectRecord(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function toPosixPath2(e){return e.replace(/\\/g,"/")}function assertNonEmptyScript(e,t){if("string"!=typeof t||0===t.trim().length)throw new Error(`tempo.config.json field "${e}" must be a non-empty string`);return t.trim()}function validateAppStart(e,t="scripts.appStart"){if(null==e)return;if("string"!=typeof e||0===e.trim().length)throw new Error(`tempo.config.json field "${t}" must be a non-empty string when set`);const n=e.trim();return n}function validateHttpUrlString(e,t){const n=e.trim();let r;try{r=new URL(n.replace(/\$\{(?:APP_PORT|PORT)\}/g,"5173"))}catch{throw new Error(`tempo.config.json field "${t}" must be a valid URL`)}if("http:"!==r.protocol&&"https:"!==r.protocol)throw new Error(`tempo.config.json field "${t}" must use the "http:" or "https:" protocol`);return n}function validateHttpUrlSource(e,t){if(null==e)return;if("string"==typeof e){if(0===e.trim().length)throw new Error(`tempo.config.json field "${t}" must be a non-empty string when set`);return validateHttpUrlString(e,t)}if(!isObjectRecord(e))throw new Error(`tempo.config.json field "${t}" must be an HTTP(S) URL string or an object with a non-empty "command"`);const n=Object.keys(e);if(1!==n.length||"command"!==n[0]||"string"!=typeof e.command||0===e.command.trim().length)throw new Error(`tempo.config.json field "${t}" command source must be exactly { "command": "<non-empty command>" }`);return{command:e.command.trim()}}function validateOptionalScript(e,t){if(null!=t){if("string"!=typeof t||0===t.trim().length)throw new Error(`tempo.config.json field "${e}" must be a non-empty string when set`);return t.trim()}}function validateUrls(e){if(void 0===e)return;if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('tempo.config.json field "urls" must be an object');const t=e;if(void 0!==t.tempoHost){const e=validateHttpUrlSource(t.tempoHost,"urls.tempoHost");return void 0===e?void 0:{tempoHost:e}}}function validatePaths(e){if(void 0===e)return;if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('tempo.config.json field "paths" must be an object');const t=e,n={};if(void 0!==t.canvases){if("string"!=typeof t.canvases||0===t.canvases.trim().length)throw new Error('tempo.config.json field "paths.canvases" must be a non-empty string');n.canvases=toPosixPath2(t.canvases.trim())}return Object.keys(n).length>0?n:void 0}function validateTimeoutSeconds(e,t){if(void 0!==e){if("number"!=typeof e||!Number.isInteger(e)||e<Nd||e>Od)throw new Error(`tempo.config.json field "${t}" must be an integer number of seconds between ${Nd} and ${Od} (got ${JSON.stringify(e)})`);return e}}function validateTimeouts(e){if(void 0===e)return;if(!isObjectRecord(e))throw new Error('tempo.config.json field "timeouts" must be an object');const t=validateTimeoutSeconds(e.startNoticeSeconds,"timeouts.startNoticeSeconds"),n=validateTimeoutSeconds(e.startStallSeconds,"timeouts.startStallSeconds");if(void 0!==t&&void 0!==n&&t>n)throw new Error(`tempo.config.json field "timeouts.startNoticeSeconds" (${t}) must be less than or equal to "timeouts.startStallSeconds" (${n})`);const r={...void 0!==t?{startNoticeSeconds:t}:{},...void 0!==n?{startStallSeconds:n}:{}};return Object.keys(r).length>0?r:void 0}function validateAppDir(e,t="appDir"){if(null==e)return;if("string"!=typeof e)throw new Error(`tempo.config.json field "${t}" must be a string`);const n=e.trim();if(0===n.length)return;const r=toPosixPath2(n);if(r.startsWith("/")||r.startsWith("../")||".."===r)throw new Error(`tempo.config.json field "${t}" must be a relative path inside the project root`);return r}function validateUiFramework(e,t){if(null!=e){if("string"!=typeof e||0===e.trim().length){const e=Pd.map(e=>`"${e}"`);throw new Error(`tempo.config.json field "${t}" must be a framework name such as ${e.join(", ")}`)}return e}}function validateApps(e){if(null==e)return;if(!Array.isArray(e))throw new Error('tempo.config.json field "apps" must be an array');if(0===e.length)throw new Error('tempo.config.json field "apps" must contain at least one entry when set (omit the field for the single-app default)');const t=new Set;return e.map((n,r)=>{const s=validateAppEntry(n,r);if(void 0===s.appDir&&e.length>1)throw new Error(`tempo.config.json field "apps[${r}].appDir" is required when "apps" has more than one entry`);if(void 0!==s.appDir){if(t.has(s.appDir))throw new Error(`tempo.config.json field "apps" contains duplicate appDir "${s.appDir}"`);t.add(s.appDir)}return s})}function validateAppEntry(e,t){if(!isObjectRecord(e))throw new Error(`tempo.config.json field "apps[${t}]" must be an object`);const n=validateAppDir(e.appDir,`apps[${t}].appDir`),r=validateHttpUrlSource(e.url,`apps[${t}].url`),s=validateAppStart(e.start,`apps[${t}].start`),i=validateAppStart(e.stop,`apps[${t}].stop`),a=validateAppStart(e.appStart,`apps[${t}].appStart`);if(void 0!==s&&void 0!==a&&s!==a)throw new Error(`tempo.config.json fields "apps[${t}].start" and legacy "apps[${t}].appStart" disagree — make them match or drop "appStart"`);const o=s??a;if(void 0!==r&&void 0===o)throw new Error(`tempo.config.json field "apps[${t}].url" requires "apps[${t}].start"`);if(void 0!==i&&void 0===o)throw new Error(`tempo.config.json field "apps[${t}].stop" requires "apps[${t}].start"`);const c=validateUiFramework(e.uiFramework,`apps[${t}].uiFramework`);if(void 0===n&&void 0===o&&void 0===i&&void 0===r&&void 0===c)throw new Error(`tempo.config.json field "apps[${t}]" must set "appDir", "start", "stop", "url", and/or "uiFramework" — an empty entry encodes nothing`);return{...void 0!==n?{appDir:n}:{},...void 0!==o?{start:o}:{},...void 0!==i?{stop:i}:{},...void 0!==r?{url:r}:{},...void 0!==c?{uiFramework:c}:{}}}function validateSetupScript(e){if(null==e)return;if("string"!=typeof e)throw new Error('tempo.config.json field "setupScript" must be a string');const t=e.trim();return t.length>0?t:void 0}function validateRunScripts(e){if(null!=e){if(!Array.isArray(e))throw new Error('tempo.config.json field "runScripts" must be an array');return e.map((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))throw new Error(`tempo.config.json field "runScripts[${t}]" must be an object`);const n=e;if("string"!=typeof n.name||0===n.name.trim().length)throw new Error(`tempo.config.json field "runScripts[${t}].name" must be a non-empty string`);if("string"!=typeof n.command||0===n.command.trim().length)throw new Error(`tempo.config.json field "runScripts[${t}].command" must be a non-empty string`);return{name:n.name.trim(),command:n.command.trim()}})}}function validateTempoConfigFile(e){if(!isObjectRecord(e))throw new Error("tempo.config.json must contain a top-level object");const t=e,n=t.scripts;if(!n||"object"!=typeof n||Array.isArray(n))throw new Error('tempo.config.json field "scripts" must be an object');const r=validatePaths(t.paths),s=validateUrls(t.urls),i=validateAppDir(t.appDir),a=validateApps(t.apps),o=validateTimeouts(t.timeouts),c=validateSetupScript(t.setupScript),l=validateRunScripts(t.runScripts),d=validateAppStart(n.appStart,"scripts.appStart"),u=validateOptionalScript("scripts.stop",n.stop),p=validateOptionalScript("scripts.updateSdk",n.updateSdk);if(a){const e=a[0];if(void 0!==i&&i!==e.appDir)throw new Error(`tempo.config.json fields "appDir" ("${i}") and "apps[0].appDir" ("${e.appDir}") disagree — apps[0] is the active app; make them match or drop the legacy "appDir"`);if(void 0!==d&&d!==e.start)throw new Error('tempo.config.json fields "scripts.appStart" and "apps[0].start" disagree — apps[0] is the active app; make them match or drop the legacy "scripts.appStart"')}let h;a?h=a:void 0===i&&void 0===d||(h=[{...void 0!==i?{appDir:i}:{},...void 0!==d?{start:d}:{}}]);const m=h?h[0].appDir:void 0,f=h?h[0].start:void 0;return{...r?{paths:r}:{},...s?{urls:s}:{},...void 0!==m?{appDir:m}:{},...h?{apps:h}:{},scripts:{install:assertNonEmptyScript("scripts.install",n.install),start:assertNonEmptyScript("scripts.start",n.start),...void 0!==u?{stop:u}:{},...void 0!==p?{updateSdk:p}:{},...void 0!==f?{appStart:f}:{}},...o?{timeouts:o}:{},...void 0!==c?{setupScript:c}:{},...l&&l.length>0?{runScripts:l}:{}}}async function findTempoConfigPath(e){const t=kd.join(e,Dd),n=kd.join(e,Ld,Dd),r=await pathExists3(t),s=await pathExists3(n);return s?n:r&&!await isForeignRootConfig(t)?t:null}async function isForeignRootConfig(e){let t;try{t=JSON.parse(await bd(e,"utf-8"))}catch{return!1}return isObjectRecord(t)&&!("scripts"in t)}async function parseConfigAt(e){let t,n;try{t=await bd(e,"utf-8")}catch(t){throw new Ss(e,`could not read: ${t instanceof Error?t.message:String(t)}`)}try{n=JSON.parse(t)}catch(t){throw new Ss(e,t instanceof Error?t.message:String(t))}try{return validateTempoConfigFile(n)}catch(t){if(t instanceof Ss)throw t;throw new Ss(e,t instanceof Error?t.message:String(t))}}async function resolveTempoConfig(e){const t=kd.resolve(e),n=await findTempoConfigPath(t);if(!n)throw new ws(t);const r=await parseConfigAt(n),s=kd.dirname(n),i=kd.relative(t,s),a=""===i?".":`./${toPosixPath2(i)}`,o=kd.resolve(s,r.paths?.canvases??Cd);let c;if(r.apps&&r.apps.length>0)c=r.apps.map(e=>({appDir:e.appDir,start:e.start??null,stop:e.stop??null,url:e.url??null,appStart:e.start??null,...e.uiFramework?{uiFramework:e.uiFramework}:{}}));else{const e=r.scripts.appStart??null;c=[{...void 0!==r.appDir?{appDir:r.appDir}:{},start:e,stop:null,url:null,appStart:e}]}const l=c[0];return{projectRoot:t,tempoConfigPath:n,appDir:l.appDir,...l.uiFramework?{uiFramework:l.uiFramework}:{},rootRel:a,tempoRoot:s,pagesDir:o,packageJsonPath:kd.join(s,"package.json"),viteConfigPath:kd.join(s,"vite.config.ts"),tsconfigPath:kd.join(s,"tsconfig.json"),tempoHostUrl:r.urls?.tempoHost??null,appUrl:l.url,scripts:{install:r.scripts.install,...r.scripts.updateSdk?{updateSdk:r.scripts.updateSdk}:{},start:r.scripts.start,stop:r.scripts.stop??null,appStart:l.appStart,appStop:l.stop},apps:c,timeouts:{startNoticeSeconds:r.timeouts?.startNoticeSeconds??null,startStallSeconds:r.timeouts?.startStallSeconds??null}}}function createSharedAppRuntime(e,t){const n=new AbortController;let r,s,i=!1;const acquire=async()=>{const s=await resolveTempoConfig(e),{appRoot:a}=await resolveAppRoot(s),o=await ensureTempoWorkspaceNonce(s.tempoRoot),accepts=async e=>{try{const t=await fetch(new URL("__tempo/identity",e.replace(/\/?$/,"/")),{signal:AbortSignal.any([n.signal,AbortSignal.timeout(5e3)])}),r=await t.json(),s=t.ok&&!0===r.tempoHost&&!0===r.pluginActive&&r.workspaceNonce===o&&"astro"===r.framework&&1===r.capabilities?.astroComponents;if(!s)return!1;if(!tempoSdkIdentitySatisfiesCanvasHost(r)){const e=await resolveTempoSdkUpgradePlan(a);throw new Gs({managedUpgradeAttempted:!1,remediationCommand:e.remediationCommand,remediationDirectory:e.cwd})}return!0}catch(e){if(e instanceof Gs)throw e;return!1}};let c={};try{c=JSON.parse(await hd(md.join(e,".tempo/app-devserver.json"),"utf8"))}catch{}const l="string"==typeof s.appUrl?s.appUrl:void 0,d=!l||l.includes("${")&&!c.port?c.port?`http://127.0.0.1:${c.port}`:void 0:substituteAppPort(l,c.port??0);if(d){if(await accepts(d))return d;let e=!1;try{await fetch(d,{signal:AbortSignal.any([n.signal,AbortSignal.timeout(1500)])}),e=!0}catch{}if(e)throw new Error("The configured app URL belongs to a running server without this workspace's Astro preview capability; restart that app with Tempo instrumentation")}if(i)throw new Error("Capture runtime is disposed");if(!s.scripts.appStart)throw new Error("Astro component capture requires apps[0].start in tempo/tempo.config.json");r=new rc({cwd:a,workspaceRoot:md.join(s.tempoRoot,".tempo/capture-app",pd()),command:s.scripts.appStart,...s.scripts.appStop?{stop:s.scripts.appStop}:{},...s.appUrl?{url:s.appUrl}:{}}),r.onOutput(t);const u=await r.start(n.signal);if(!u.ok||!u.url)throw new Error(u.error??"App server failed to start for Astro capture");if(!await accepts(u.url))throw new Error("App server lacks the Astro component preview capability; enable tempoAstro() from tempo-sdk/astro");return u.url};return{getAppUrl:()=>i?Promise.reject(new Error("Capture runtime is disposed")):(s??=acquire().catch(async e=>{throw await(r?.stop()),e}),s),async dispose(){i=!0,n.abort(),await(s?.catch(()=>{})),await(r?.stop())}}}var Md=new Map;function createCaptureAppRuntime(e,t=()=>{}){const n=md.resolve(e);let r,s=!1,i=!1;return{getAppUrl(){if(i)return Promise.reject(new Error("Capture runtime is disposed"));if(!s){if(r=Md.get(n),!r){const e=new Set;r={runtime:createSharedAppRuntime(n,t=>{for(const n of e)n(t)}),refs:0,logs:e},Md.set(n,r)}s=!0,r.refs++,r.logs.add(t)}return r.runtime.getAppUrl()},async dispose(){i||(i=!0,s&&(r.logs.delete(t),0===--r.refs&&(Md.get(n)===r&&Md.delete(n),await r.runtime.dispose())))}}}async function readTempoDevserverConfig(e){const t=JSON.parse(await yr(e,"utf-8"));if(!t.scripts?.install||!t.scripts?.start)throw new Error(`tempo.config.json at ${e} must declare scripts.install and scripts.start`);const n=t.scripts.updateSdk;if(null!=n&&("string"!=typeof n||0===n.trim().length))throw new Error(`tempo.config.json at ${e}: scripts.updateSdk must be a non-empty string when provided`);return{scripts:{install:t.scripts.install,start:t.scripts.start,stop:t.scripts.stop??null,..."string"==typeof n?{updateSdk:n.trim()}:{}},tempoHostUrl:t.urls?.tempoHost??null}}function projectRootForTempoDir(e){const t=vr.resolve(e);return"tempo"===vr.basename(t)?vr.dirname(t):t}async function resolveCanvasHostLayout(e){const t=vr.resolve(e.repoRoot),n=e.tempoDir?[vr.join(vr.resolve(e.tempoDir),"tempo.config.json")]:[vr.join(t,"tempo","tempo.config.json"),vr.join(t,"tempo.config.json")];for(const e of n){let t;try{t=JSON.parse(await yr(e,"utf-8"))}catch{continue}if("object"!=typeof t||null===t||!("scripts"in t))continue;const n=vr.dirname(e),r=t.paths,s="string"==typeof r?.canvases&&r.canvases.trim().length>0?r.canvases.trim().split("\\").join("/"):"designs";return{tempoDir:n,projectRoot:projectRootForTempoDir(n),pagesDir:vr.resolve(n,s),configPath:e}}const r=e.tempoDir?vr.resolve(e.tempoDir):vr.join(t,"tempo");return{tempoDir:r,projectRoot:projectRootForTempoDir(r),pagesDir:vr.join(r,"designs"),configPath:null}}function resolveTempoDir(e){if(e.tempoConfigPath)return vr.dirname(e.tempoConfigPath);if(e.tempoDir)return e.tempoDir;if(e.repoRoot)return vr.join(e.repoRoot,"tempo");throw new Error("startDevserverSession needs one of tempoDir, repoRoot, or tempoConfigPath")}async function awaitCanvasRegistration(e){const t=e.log??(()=>{}),n=e.maxAttempts??21,r=e.retryDelayMs??250;for(let s=0;;s+=1){const i=await fetch(`${e.origin}/__tempo/canvas-host-registration`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({canvasPath:e.hostCanvasPath})}).catch(()=>null);if(!i)throw new Error(`registration barrier unreachable at ${e.origin}`);if(!i.headers.get("x-tempo-canvas-host-registration"))return void t("registration barrier not supported by host framework — skipping");if(i.ok)return;if(s>=n-1)throw new Error(`canvas ${e.hostCanvasPath} never registered into the host (last status ${i.status})`);await e.reRegister(),await new Promise(e=>setTimeout(e,r))}}var xd=/optimized dependencies changed|new dependencies optimized|Re-optimizing dependencies|Forced re-optimization|Failed to run dependency scan|could not be resolved|\(imported by |Skipping dependency pre-bundling|page reload|full-reload|server restarted|\[tempo\] (?:re-emitting|recovered)|hmr update|hmr invalidate/i,Fd=/Failed to run dependency scan/i,Bd=/\x1b\[[0-9;]*[A-Za-z]/g;function cleanDevserverLine(e){return e.replace(Bd,"").trim()}function createDevserverLineSplitter(){let e="";return{push(t){const n=(e+t).split(/\r?\n/);return e=n.pop()??"",n.map(cleanDevserverLine).filter(e=>e.length>0)},flush(){const t=cleanDevserverLine(e);return e="",t.length>0?[t]:[]}}}function isDevserverReloadSignal(e){return xd.test(e)}function formatDevserverReloadSignal(e){const t=cleanDevserverLine(e);return isDevserverReloadSignal(t)?Fd.test(t)?`⚠ devserver: ${t} — dependency pre-bundling is OFF for this session; every dependency will be discovered at runtime and each discovery wave full-reloads every capture page`:`devserver: ${t}`:null}async function startDevserverSession(e){const t=e.log??(()=>{}),n=resolveTempoDir(e),r=e.tempoConfigPath??vr.join(n,"tempo.config.json"),s=await readTempoDevserverConfig(r),i=e.hostCanvasPaths??[],a=new ed({tempoConfigPath:r,tempoHostUrl:s.tempoHostUrl,scripts:s.scripts});await a.initialize();const o=projectRootForTempoDir(n);for(const e of i)await a.ensureCanvasRegistered(vr.join(o,e));const c=await a.startDevServer(),l=e.onOutput,d=l?createDevserverLineSplitter():null,forwardOutput=e=>{if(l)for(const n of e)try{l(n)}catch(e){t(`devserver output listener threw: ${e instanceof Error?e.message:String(e)}`)}};d&&c.onOutput(e=>forwardOutput(d.push(String(e))));const u=await c.waitUntilReady(e.readyTimeoutMs??12e4);if(!u.ok||!u.url)throw await c.stop().catch(()=>{}),await a.dispose(),forwardOutput(d?.flush()??[]),new Error(`tempobook devserver failed to become ready: ${u.message??(u.timedOut?"timeout":"unknown")}`);const p=u.url,h=new URL(p).origin;t(`devserver ready at ${p}`);const registerCanvas=async e=>{await a.ensureCanvasRegistered(vr.join(o,e)),await awaitCanvasRegistration({origin:h,hostCanvasPath:e,reRegister:()=>a.ensureCanvasRegistered(vr.join(o,e)),log:t})};for(const e of i)await awaitCanvasRegistration({origin:h,hostCanvasPath:e,reRegister:()=>a.ensureCanvasRegistered(vr.join(o,e)),log:t});const m=createCaptureAppRuntime(o,t);return{getAppUrl:m.getAppUrl,origin:h,hostUrl:p,projectRoot:o,tempoDir:n,registerCanvas,dispose:async()=>{try{await m.dispose()}finally{await c.stop().catch(()=>{}),await a.dispose(),forwardOutput(d?.flush()??[])}}}}import{createHash as Hd}from"crypto";import{access as Ud,readFile as jd}from"fs/promises";import $d from"path";function ignoredStoryboardArea(e,t,n){const r=e.map(({x:e,y:r,w:s,h:i})=>({left:Math.max(0,e),top:Math.max(0,r),right:Math.min(t,e+s),bottom:Math.min(n,r+i)})).filter(({left:e,top:t,right:n,bottom:r})=>n>e&&r>t),s=[...new Set(r.flatMap(({left:e,right:t})=>[e,t]))].sort((e,t)=>e-t);let i=0;for(let e=1;e<s.length;e++){const t=s[e-1],n=s[e],a=r.filter(e=>e.left<n&&e.right>t).sort((e,t)=>e.top-t.top);let o=0,c=0;for(const e of a)o+=Math.max(0,e.bottom-Math.max(c,e.top)),c=Math.max(c,e.bottom);i+=(n-t)*o}return i}function toPosixPath3(e){return e.split($d.sep).join("/")}async function enumerateCanvasStoryboards(e){const t=e.pagesDir??$d.join(e.tempoDir,"designs"),n=projectRootForTempoDir(e.tempoDir),r=await scanCanvasFiles(t),s=[],i=[],a=[],o=[];let c=0;for(const t of r){const r=await jd(t,"utf-8"),l=parseCanvasFile(t,r),d=l.errors.filter(e=>"structural"===e.kind),u=l.imports.some(e=>"tempo-sdk/canvas"===e.source||e.source.endsWith("/tempo-sdk/canvas"))||l.misimportedSdkCanvasImports.length>0,p=!u&&d.length>0&&d.every(e=>e.message===Qr);if(p)continue;const h=d.filter(e=>e.newerSdkStoryboard),m=d.filter(e=>!e.newerSdkStoryboard);if(m.length>0){i.push(...d.map(e=>({filePath:t,message:e.message})));continue}for(const e of h){const{component:n,storyboardKey:r,vrt:s}=e.newerSdkStoryboard;c+=1,o.push({filePath:t,component:n,...r?{storyboardId:r}:{},vrt:s})}const f=l.errors.filter(e=>"degraded"===e.kind&&e.message.includes(" vrt"));if(f.length>0){a.push(...f.map(e=>({filePath:t,message:e.message})));continue}const g=toPosixPath3($d.relative(e.tempoDir,$d.dirname(t))),y=toPosixPath3($d.relative(n,t));for(const e of l.storyboards)c+=1,"route"!==e.kind&&("html"!==e.kind||e.filepath?s.push({..."astro"===componentFrameworkForStoryboard(e)?{source:{kind:"astro",canvasPath:l.canvasPath??toPosixPath3($d.relative(n,$d.dirname(t))),revision:Hd("sha256").update(r).digest("hex")}}:"html"===e.kind?{source:{kind:"html",filepath:$d.resolve($d.dirname(t),e.filepath)}}:{},filePath:t,canvasPath:g,hostCanvasPath:y,storyboardId:e.storyboardKey,name:e.displayName,layout:{x:e.layout.x,y:e.layout.y,width:e.layout.width,height:e.layout.height},vrt:e.vrt}):e.vrt&&a.push({filePath:t,message:`HTML storyboard "${e.storyboardKey}" requires a literal local filepath for headless capture.`}))}return{storyboards:s,totalStoryboards:c,totalCanvases:r.length,structuralErrors:i,vrtConfigErrors:a,newerSdkStoryboards:o}}async function enumerateTrackedStoryboards(e){try{await Ud(e.tempoDir)}catch{return{tracked:[],paused:[],totalStoryboards:0,totalCanvases:0,errors:[],newerSdkStoryboards:[]}}const t=await enumerateCanvasStoryboards(e),n=[],r=[],s=[...t.structuralErrors,...t.vrtConfigErrors];for(const e of t.storyboards){if(!e.vrt)continue;const t={...e.source?{source:e.source}:{},canvasPath:e.canvasPath,hostCanvasPath:e.hostCanvasPath,storyboardId:e.storyboardId,name:e.name,layout:e.layout,threshold:e.vrt.threshold,ignore:e.vrt.ignore},{width:i,height:a}=t.layout,o=void 0!==i&&void 0!==a;if(o){const t=ignoredStoryboardArea(e.vrt.ignore??[],i,a);if(t>=.9*i*a){s.push({filePath:e.filePath,message:`<Storyboard id="${e.storyboardId}"> vrt.ignore masks ≥90% of the board — untrack it instead`});continue}}e.vrt.skip?r.push(t):n.push(t)}return{tracked:n,paused:r,totalStoryboards:t.totalStoryboards,totalCanvases:t.totalCanvases,errors:s,newerSdkStoryboards:t.newerSdkStoryboards}}function percentile(e,t){if(0===e.length)return 0;const n=Math.min(e.length-1,Math.ceil(t/100*e.length)-1);return e[Math.max(0,n)]}function summarize(e){const t=[...e].sort((e,t)=>e-t);return{count:t.length,totalMs:t.reduce((e,t)=>e+t,0),p50Ms:percentile(t,50),p95Ms:percentile(t,95),maxMs:t[t.length-1]??0}}var Gd=class{constructor(){this.phases=[],this.perBoard={}}async phase(e,t){const n=Date.now();try{return await t()}finally{this.phases.push({name:e,ms:Date.now()-n})}}recordBoard(e,t,n="ms"){const r=this.perBoard[e]??={unit:n,values:[]};if(r.unit!==n)throw new Error(`Timing metric ${JSON.stringify(e)} changed unit from ${r.unit} to ${n}`);r.values.push(t)}toJSON(){return{phases:this.phases,perBoard:Object.fromEntries(Object.entries(this.perBoard).map(([e,{unit:t,values:n}])=>[e,{...summarize(n),unit:t}]))}}format(){const e=["── timing ──────────────────────────────"];for(const{name:t,ms:n}of this.phases)e.push(`${t.padEnd(28)} ${(n/1e3).toFixed(1)}s`);const t=Object.entries(this.perBoard);if(t.length>0){e.push("── per storyboard ──────────────────────"),e.push(`${"metric".padEnd(28)}${"count".padStart(6)}${"total".padStart(10)}${"p50".padStart(8)}${"p95".padStart(8)}${"max".padStart(8)}`);for(const[n,{unit:r,values:s}]of t){const t=summarize(s),i="ms"===r?`${(t.totalMs/1e3).toFixed(1)}s`:String(t.totalMs),formatValue=e=>"ms"===r?`${Math.round(e)}ms`:String(Math.round(e));e.push(`${n.padEnd(28)}${String(t.count).padStart(6)}${i.padStart(10)}${formatValue(t.p50Ms).padStart(8)}${formatValue(t.p95Ms).padStart(8)}${formatValue(t.maxMs).padStart(8)}`)}}return e.join("\n")}};import{readFile as qd}from"fs/promises";import{resolve as Wd}from"path";var Vd={node:{core:["index","expo-babel-plugin","flutter-preview-path","nextjs-loader","assets/parser","canvas/parser"],vue:["vue"],svelte:["svelte"],astro:["astro","astro/runtime"],nuxt:["nuxt"]}};async function provisionCaptureRuntime(e){const t=process.env.TEMPO_SDK_RUNTIME_PATH||e,n=await qd(Wd(t,"runtime.json"),"utf8").then(e=>{const t=JSON.parse(e),n=Object.values(Vd.node).flat().filter(e=>!Object.prototype.hasOwnProperty.call(t.node??{},e));return n.length?`The private Tempo SDK runtime is missing entries: ${n.join(", ")}`:null}).catch(()=>null),r=n??await tempoSdkRuntimeProvisioningError({tempoRuntimeContract:1},t);if(r)throw new Error(`${t}: ${r}`);process.env.TEMPO_SDK_RUNTIME_PATH=t}var Kd=We;async function enumerateTrackedStoryboards2(e){return await enumerateTrackedStoryboards(e)}function scaleIgnoreRegionsToDevicePx(e){return e?.map(e=>({x:e.x*gt,y:e.y*gt,w:e.w*gt,h:e.h*gt}))}function routeMissingHint(e){return 404===e?" — the target deployment has no /visual-review routes yet (they arrive with the next release's Convex deploy); expected-red until then":""}var Yd=class extends Error{constructor(e,t){super(e),this.name="VisualReviewHttpError",this.status=t}},zd=class{constructor(e,t){this.lastCredentialKind="secret",this.baseUrl=e,this.credential="function"==typeof t?t:async()=>t}async authHeader(){const e=await this.credential();return this.lastCredentialKind=e.kind,"oidc"!==e.kind?{"x-visual-review-secret":e.value}:e.repoKey?{"x-visual-review-oidc":e.value,"x-visual-review-repo-key":e.repoKey}:{"x-visual-review-oidc":e.value}}async request(e,t){const n=await a(`${this.baseUrl}${e}`,async()=>({...t,headers:{...await this.authHeader(),...t.headers??{}}}),`ingest ${t.method??"GET"}`,async e=>{if(503!==e.status)return!0;const t=await this.errorReason(e);return!t||"jwks_unavailable"===t});if(503===n.status){const e=await this.errorReason(n);if("jwks_unavailable"===e)throw new Yd("visual-review ingest could not verify the OIDC token: GitHub's JWKS endpoint is unreachable from the deployment (transient — retry the job)",n.status);if("visual_review_unconfigured"===e)throw new Yd("visual-review ingest is unconfigured on the target deployment (set VISUAL_REVIEW_UPLOAD_SECRET, or its OIDC producer credential)",n.status);throw new Yd(`visual-review ingest unavailable: ${e??"HTTP 503"}`,n.status)}if(401===n.status)throw new Yd("oidc"===this.lastCredentialKind?"visual-review ingest OIDC token rejected (unregistered repo, wrong audience, or expired)":"visual-review ingest secret rejected (note: production rejects the shared secret — CI must send an OIDC token)",n.status);return n}async errorReason(e){try{const t=await e.json();return t.reason??t.error}catch{return}}async negotiate(e){if(0===e.length)return[];const t=await this.request("/visual-review/negotiate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hashes:e})});if(!t.ok)throw new Error(`negotiate failed: ${t.status}${routeMissingHint(t.status)}`);const{missing:n}=await t.json();return n}async uploadBlob(e,t,n){const r=await this.request(`/visual-review/blob?hash=${e}&w=${n.width}&h=${n.height}`,{method:"POST",body:t});if(!r.ok)throw new Error(`blob upload failed for ${e.slice(0,12)}: ${r.status} ${await r.text()}`)}async uploadBlobs(e){let t,n=0;if(await Promise.all(Array.from({length:Math.min(8,e.length)},async()=>{for(;!t;){const r=e[n++];if(!r)return;try{await this.uploadBlob(r.hash,r.bytes,r)}catch(e){t??={error:e}}}})),t)throw t.error}async claimBaseline(e){try{const t=await this.request("/visual-review/baseline/claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(404===t.status)return{status:"unsupported"};if(429===t.status||t.status>=500)return{status:"unsupported",reason:`claim service returned ${t.status}`};if(!t.ok)throw new Yd(`baseline claim failed: ${t.status} ${await t.text()}${routeMissingHint(t.status)}`,t.status);return await t.json()}catch(e){if(e instanceof Yd&&e.status>=400&&e.status<500&&429!==e.status)throw e;return{status:"unsupported",reason:e instanceof Error?e.message:String(e)}}}async renewBaselineClaim(e){const t=await this.request("/visual-review/baseline/heartbeat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Yd(`baseline claim heartbeat failed: ${t.status} ${await t.text()}`,t.status);return await t.json()}async failBaselineClaim(e){const t=await this.request("/visual-review/baseline/fail",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`baseline claim release failed: ${t.status} ${await t.text()}`);return await t.json()}async baselineManifest(e,t,n){const r=new URLSearchParams({repo:e,sha:t,env:n}),s=await this.request(`/visual-review/baseline/manifest?${r}`,{method:"GET"});if(!s.ok)throw new Error(`baseline manifest fetch failed: ${s.status} ${await s.text()}`);return await s.json()}async finalize(e){const t=await this.request("/visual-review/finalize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repoKey:e.repoKey,githubRepo:e.githubRepo,headSha:e.headSha,branch:e.branch,trigger:e.trigger,prNumber:e.prNumber,baseCandidates:e.baseCandidates,envFingerprint:e.envFingerprint,expected:e.expected,snapshots:e.snapshots.map(e=>"content-unavailable"===e.status?{...e,status:"render-error",error:`content-unavailable: ${e.error??"External content did not become ready"}`}:e),baselineClaimToken:e.baselineClaimToken,scm:e.scm})});if(!t.ok)throw new Error(`finalize failed: ${t.status} ${await t.text()}${routeMissingHint(t.status)}`);return await t.json()}};import{dirname as Jd,resolve as Qd}from"path";import{fileURLToPath as Xd}from"url";async function provisionSdkRuntime(){const e=Xd(import.meta.url),t=e.endsWith(".ts")?Qd(Jd(e),"../../tempo-sdk-runtime/dist"):Qd(Jd(e),"sdk-runtime");try{await provisionCaptureRuntime(t)}catch(e){throw new Error(`Tempo VRT SDK runtime is unavailable. Reinstall @tempo-ai/visual-review or provide a compatible TEMPO_SDK_RUNTIME_PATH. ${e instanceof Error?e.message:String(e)}`)}}async function startDevserverSession2(e){return await provisionSdkRuntime(),startDevserverSession(e)}async function startCaptureSession2(e){return await provisionSdkRuntime(),startCaptureSession(e)}function inferRepoRoot(){try{return Ne("git",["rev-parse","--show-toplevel"],{encoding:"utf-8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}).toString().trim()}catch{return process.cwd()}}function parseArgs(e){const t=i(),n={repoRoot:inferRepoRoot(),tempoDir:"",tempoDirExplicit:!1,upload:t.isCi&&"manual"!==t.trigger,trigger:t.trigger,baseDepth:50,prNumber:t.prNumber,headSha:t.headSha,branch:t.branch,githubRepo:"bitbucket"===t.provider?void 0:t.repoFullName,repoKey:t.repoKey,parallel:6,ci:t};for(let t=0;t<e.length;t+=1){const r=e[t],next=()=>{t+=1;const n=e[t];if(void 0===n)throw new Error(`${r} needs a value`);return n};switch(r){case"capture":break;case"--repo-root":n.repoRoot=He.resolve(next());break;case"--tempo-dir":n.tempoDir=He.resolve(next()),n.tempoDirExplicit=!0;break;case"--out":n.out=He.resolve(next());break;case"--upload":n.upload=!0;break;case"--no-upload":n.upload=!1;break;case"--url":n.url=next();break;case"--trigger":n.trigger=next();break;case"--pr":n.prNumber=Number(next());break;case"--head":n.headSha=next();break;case"--branch":n.branch=next();break;case"--base":n.baseSha=next();break;case"--base-depth":n.baseDepth=Number(next());break;case"--github-repo":n.githubRepo=next();break;case"--repo-key":n.repoKey=next();break;case"--parallel":n.parallel=Number(next());break;case"--settle-timeout":n.settleTimeoutMs=Number(next());break;case"--baseline-claim-token":n.baselineClaimToken=next();break;case"--expected-env-fingerprint":n.expectedEnvFingerprint=next();break;default:throw new Error(`unknown flag ${r}`)}}if(n.tempoDir||(n.tempoDir=He.join(n.repoRoot,"tempo")),!["pr","main","manual"].includes(n.trigger))throw new Error(`--trigger must be pr|main|manual, got ${n.trigger}`);return n}function inferPrBase(e){if("pr"!==e.trigger||e.baseSha)return;const t=e.ci.baseRef;if(t&&"bitbucket"===e.ci.provider)try{git(e.repoRoot,"fetch","--no-tags","origin",`+refs/heads/${t}:refs/remotes/origin/${t}`)}catch{}if(t)try{e.baseSha=git(e.repoRoot,"merge-base",`origin/${t}`,e.headSha??"HEAD")}catch{}e.baseSha??=e.ci.baseSha}function git(e,...t){return Ne("git",t,{cwd:e,encoding:"utf-8",windowsHide:!0}).toString().trim()}function deriveRepoKey(e){if(e.repoKey)return e.repoKey.toLowerCase();if(e.githubRepo)return`github.com/${e.githubRepo}`.toLowerCase();const t=git(e.repoRoot,"remote","get-url","origin"),n=t.match(/^[\w.-]+@([\w.-]+):([\w./-]+?)(?:\.git)?$/)??t.match(/^[\w+.-]+:\/\/(?:[^@]+@)?([\w.-]+)\/([\w./-]+?)(?:\.git)?$/);if(!n)throw new Error(`cannot derive repo key from remote "${t}"`);return`${n[1]}/${n[2]}`.toLowerCase()}var key=e=>`${e.canvasPath}#${e.storyboardId}`;function pngDimensions(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{width:t.getUint32(16),height:t.getUint32(20)}}function manifestSize(e,t){if(void 0!==e.width&&void 0!==e.height)return{width:e.width,height:e.height};if(!t?.pngBytes)return{...Kd};const n=pngDimensions(t.pngBytes);return{width:n.width/gt,height:n.height/gt}}var Zd=12e5,eu=5e3,tu=3e4,nu=500;async function detectEnvFingerprint(){const{chromium:e}=await(import("playwright")),t=await e.launch();try{return buildEnvFingerprint({os:process.platform,browserVersion:t.version()}).fingerprint}finally{await t.close().catch(()=>{})}}async function resolveOrClaimBaseline(e){const t=e.now??Date.now,n=t()+(e.waitTimeoutMs??Zd);for(;;){const r=await e.ingest.claimBaseline({repoKey:e.repoKey,commitSha:e.commitSha,envFingerprint:e.envFingerprint,ownerToken:e.ownerToken});if("capturing"!==r.status)return r;if(t()>=n)throw new Error(`timed out waiting for baseline ${r.commitSha.slice(0,12)}`);e.log(`baseline ${r.commitSha.slice(0,12)} is being captured; waiting`);const s=Math.max(nu,r.leaseExpiresAt-t()+nu);await(e.sleep??(e=>new Promise(t=>setTimeout(t,e))))(Math.min(e.pollIntervalMs??eu,s))}}function startClaimHeartbeat(e){let t=!1,n=!1,r=null,s=e.leaseExpiresAt,i=null;const schedule=()=>{if(n||r)return;const e=s-Date.now(),t=Math.max(nu,Math.min(tu,Math.floor(e/3)));i=setTimeout(renew,t),i.unref()},renew=()=>{t||r||(t=!0,e.ingest.renewBaselineClaim(e.claim).then(e=>{s=e.leaseExpiresAt}).catch(t=>{const n=t instanceof Error?t.message:String(t);t instanceof Yd&&409===t.status?r=new Error(`lost baseline claim for ${e.claim.commitSha.slice(0,12)}`):Date.now()>=s?r=new Error(`baseline claim expired for ${e.claim.commitSha.slice(0,12)} after heartbeat failures`):e.log(`baseline claim heartbeat failed transiently: ${n}`)}).finally(()=>{t=!1,schedule()}))};return schedule(),{stop:()=>{n=!0,i&&clearTimeout(i)},assertOwned:()=>{if(r)throw r}}}function explicitTempoDirRelative(e){if(!e.tempoDirExplicit)return;const t=He.relative(e.repoRoot,e.tempoDir);return t.startsWith("..")||He.isAbsolute(t)?void 0:t}function buildBaselineCaptureArgs(e){const t=["capture","--repo-root",e.worktreeRoot,"--upload","--trigger","main","--head",e.commitSha,"--branch",`on-demand/${e.commitSha.slice(0,12)}`,"--parallel",String(e.parallel),"--baseline-claim-token",e.claimToken,"--expected-env-fingerprint",e.envFingerprint];return e.url&&t.push("--url",e.url),e.githubRepo&&t.push("--github-repo",e.githubRepo),void 0!==e.tempoDirRelative&&t.push("--tempo-dir",He.join(e.worktreeRoot,e.tempoDirRelative||".")),e.repoKey&&t.push("--repo-key",e.repoKey),void 0!==e.settleTimeoutMs&&t.push("--settle-timeout",String(e.settleTimeoutMs)),t}async function runBaselineCaptureInWorktree(e){const t=await Me(He.join(process.env.RUNNER_TEMP||Be(),"tempo-vrt-baseline-")),n=He.join(t,"repo");try{e.log(`capturing missing baseline ${e.commitSha.slice(0,12)} on demand`),Ne("git",["worktree","add","--detach",n,e.commitSha],{cwd:e.args.repoRoot,stdio:"inherit",windowsHide:!0});const t=process.argv[1];if(!t)throw new Error("cannot locate the visual-review CLI entrypoint");const r=[t,...buildBaselineCaptureArgs({worktreeRoot:n,commitSha:e.commitSha,parallel:e.args.parallel,claimToken:e.claimToken,envFingerprint:e.envFingerprint,url:e.args.url,githubRepo:e.args.githubRepo,repoKey:e.args.repoKey,settleTimeoutMs:e.args.settleTimeoutMs,tempoDirRelative:explicitTempoDirRelative(e.args)})];await new Promise((e,t)=>{const n=Oe(process.execPath,r,{cwd:process.cwd(),env:{...process.env,GITHUB_OUTPUT:""},stdio:"inherit",windowsHide:!0});n.once("error",t),n.once("exit",(n,r)=>{0===n?e():t(new Error(`baseline capture exited ${n??`from signal ${r??"unknown"}`}`))})})}finally{try{Ne("git",["worktree","remove","--force",n],{cwd:e.args.repoRoot,stdio:"ignore",windowsHide:!0})}catch{}await xe(t,{recursive:!0,force:!0})}}async function main(e=process.argv.slice(2)){const i=parseArgs(e);inferPrBase(i);const a=new Gd,log=e=>console.log(`[visual-review] ${e}`),d=i.headSha??git(i.repoRoot,"rev-parse","HEAD"),u=i.branch||git(i.repoRoot,"branch","--show-current")||"detached";if(i.upload&&void 0===i.baselineClaimToken&&"pr"===i.trigger&&"bitbucket"===i.ci.provider&&void 0!==i.prNumber&&await s(d))return log("no-visual-change declaration present — posted success and skipped capture"),l({declared:"no-visual-change"}),await n({repoFullName:i.ci.repoFullName,prNumber:i.prNumber,body:t(),log}).catch(e=>log(`sticky comment failed: ${e instanceof Error?e.message:e}`)),0;const p=i.baseSha?git(i.repoRoot,"rev-list","--first-parent",`--max-count=${i.baseDepth}`,i.baseSha).split("\n").filter(Boolean):[];if("pr"===i.trigger&&0===p.length)throw new Error("--trigger pr requires --base <merge-base sha>");const h=await resolveCanvasHostLayout({repoRoot:i.repoRoot,tempoDir:i.tempoDirExplicit?i.tempoDir:void 0});i.tempoDir=h.tempoDir;const m=h.pagesDir,f=await a.phase("enumerate",()=>enumerateTrackedStoryboards2({tempoDir:i.tempoDir,pagesDir:m}));if(f.errors.length>0){for(const e of f.errors)console.error(`[visual-review] parse error: ${e.filePath}: ${e.message}`);return 1}for(const e of f.newerSdkStoryboards){const t=e.storyboardId?` id="${e.storyboardId}"`:"",n=e.vrt?"tracked ":"";console.warn(`[visual-review] skipped ${n}<${e.component}${t}> in ${e.filePath}: its storyboard component needs a newer @tempo-ai/visual-review. The canvas's other storyboards are captured.`)}log(`${f.tracked.length} tracked storyboard(s) of ${f.totalStoryboards} across ${f.totalCanvases} canvases`+(f.paused.length>0?` (${f.paused.length} paused via skip)`:""));const g=i.upload&&new zd(i.url??process.env.VISUAL_REVIEW_INGEST_URL??r,c()),y=deriveRepoKey(i);let v="",E=null,T=null,w=0,S=null,b=null;const A=process.env.VISUAL_REVIEW_CAPTURE_OWNER_TOKEN??("bitbucket"===i.ci.provider?o().captureOwnerToken:void 0),_=void 0===i.baselineClaimToken;let k=!1;const releaseCurrentClaims=async e=>{if(!g)return;const t=[E,T];A&&!t.some(e=>e?.commitSha===d&&e.ownerToken===A)&&t.push({repoKey:y,commitSha:d,ownerToken:A}),await Promise.all(t.filter(e=>null!==e).map(async t=>{await g.failBaselineClaim({...t,error:e}).catch(e=>{log(`failed to release baseline claim for ${t.commitSha.slice(0,12)}: ${e instanceof Error?e.message:e}`)})}))},terminate=e=>{k||(k=!0,S?.stop(),releaseCurrentClaims(`capture interrupted by ${e}`).finally(()=>process.exit("SIGTERM"===e?143:130)))},onSigint=()=>terminate("SIGINT"),onSigterm=()=>terminate("SIGTERM");g&&(process.once("SIGINT",onSigint),process.once("SIGTERM",onSigterm));try{if(g&&("pr"===i.trigger||"main"===i.trigger)){if(v=await a.phase("environment-fingerprint",()=>detectEnvFingerprint()),i.expectedEnvFingerprint&&i.expectedEnvFingerprint!==v)throw new Error(`baseline capture environment changed: expected ${i.expectedEnvFingerprint}, got ${v}`);const e=i.baselineClaimToken??process.env.VISUAL_REVIEW_CAPTURE_OWNER_TOKEN??De();if("main"===i.trigger){const t=await resolveOrClaimBaseline({ingest:g,repoKey:y,commitSha:d,envFingerprint:v,ownerToken:e,log});if("ready"===t.status)return log(`baseline ${t.commitSha.slice(0,12)} is already ready`),0;"claimed"===t.status?(E={repoKey:y,commitSha:t.commitSha,envFingerprint:v,ownerToken:e},w=t.leaseExpiresAt):log(`baseline claims unavailable${"unsupported"===t.status&&t.reason?` (${t.reason})`:""}; continuing without a lease`)}else{let t=await g.claimBaseline({repoKey:y,commitSha:d,envFingerprint:v,ownerToken:e});"capturing"===t.status&&(t=await resolveOrClaimBaseline({ingest:g,repoKey:y,commitSha:d,envFingerprint:v,ownerToken:e,log})),"claimed"===t.status?(E={repoKey:y,commitSha:d,envFingerprint:v,ownerToken:e},w=t.leaseExpiresAt):"ready"===t.status?(log(`reusing existing capture for PR head ${d.slice(0,12)}`),b=await g.baselineManifest(y,d,v)):log(`baseline claims unavailable${"unsupported"===t.status&&t.reason?` (${t.reason})`:""}; using legacy PR capture`)}if(E&&(S=startClaimHeartbeat({ingest:g,claim:E,leaseExpiresAt:w,log})),"pr"===i.trigger){const t=p[0];if(!t)throw new Error("--trigger pr requires --base <merge-base sha>");const n=await resolveOrClaimBaseline({ingest:g,repoKey:y,commitSha:t,envFingerprint:v,ownerToken:e,log});if("claimed"===n.status){T={repoKey:y,commitSha:n.commitSha,envFingerprint:v,ownerToken:e};try{await runBaselineCaptureInWorktree({args:i,commitSha:n.commitSha,envFingerprint:v,claimToken:e,log})}catch(e){throw await g.failBaselineClaim({...T,error:e instanceof Error?e.message:String(e)}).catch(()=>{}),T=null,e}T=null,E?.commitSha===n.commitSha&&(S?.stop(),S=null,E=null)}else"ready"===n.status?log(`using baseline ${n.commitSha.slice(0,12)}`):log(`on-demand baselines unavailable${"unsupported"===n.status&&n.reason?` (${n.reason})`:""}; using nearest stored baseline`)}}let e=[];if(g&&0===f.tracked.length&&!v&&(v=await detectEnvFingerprint()),f.tracked.length>0&&!b){const t=await a.phase("devserver-boot",()=>startDevserverSession2({tempoDir:i.tempoDir,hostCanvasPaths:[...new Set(f.tracked.map(e=>e.hostCanvasPath))],log,onOutput:e=>{const t=formatDevserverReloadSignal(e);t&&log(t)}}));try{const n=await startCaptureSession2({hostUrl:t.hostUrl,getAppUrl:t.getAppUrl,parallelPages:i.parallel,timing:a,settleTimeoutMs:i.settleTimeoutMs,log});try{if(v&&n.envFingerprint!==v)throw new Error(`capture environment changed after claiming baseline: expected ${v}, got ${n.envFingerprint}`);v=n.envFingerprint,e=await a.phase("capture",()=>n.captureBoards(f.tracked))}finally{await n.dispose()}}finally{await a.phase("devserver-shutdown",()=>t.dispose())}}const t={repoKey:y,githubRepo:i.githubRepo,..."bitbucket"===i.ci.provider&&i.ci.repoFullName?{scm:{provider:"bitbucket",fullName:i.ci.repoFullName}}:{},headSha:d,branch:u,trigger:i.trigger,prNumber:i.prNumber,baseCandidates:p,baselineClaimToken:E?.ownerToken??i.baselineClaimToken,envFingerprint:v,expected:b?.expected??[...f.tracked.map(t=>({canvasPath:t.canvasPath,storyboardId:t.storyboardId,name:t.name,...t.layout,...manifestSize(t.layout,e.find(e=>key(e)===key(t))),threshold:t.threshold,ignore:scaleIgnoreRegionsToDevicePx(t.ignore)})),...f.paused.map(e=>({canvasPath:e.canvasPath,storyboardId:e.storyboardId,name:e.name,...e.layout,...manifestSize(e.layout,void 0),skip:!0}))],snapshots:b?.snapshots??e.map(e=>({canvasPath:e.canvasPath,storyboardId:e.storyboardId,pngHash:e.pngHash,htmlHash:e.htmlHash,status:e.status,error:e.error}))},n=e.filter(e=>"ok"!==e.status);if(n.length>0)for(const e of n)log(`⚠ ${key(e)}: ${e.status}${e.error?` — ${e.error}`:""}`);if(i.out){const n=i.out;await a.phase("write-out",async()=>{await Le(n,{recursive:!0});for(const t of e){if(!t.pngBytes)continue;const e=`${key(t).replace(/[^\w.-]+/g,"_")}.png`;await Fe(He.join(n,e),t.pngBytes)}await Fe(He.join(n,"manifest.json"),JSON.stringify(t,null,2))})}let r=null;if(g){S?.assertOwned();const n=new Map;for(const t of e){f.tracked.find(e=>key(e)===key(t));t.pngHash&&t.pngBytes&&n.set(t.pngHash,{bytes:t.pngBytes,...pngDimensions(t.pngBytes)}),t.htmlHash&&t.htmlBytes&&n.set(t.htmlHash,{bytes:t.htmlBytes,width:0,height:0})}const s=await a.phase("negotiate",()=>g.negotiate([...n.keys()]));log(`uploading ${s.length} of ${n.size} blob(s)`),await a.phase("upload",async()=>{await g.uploadBlobs(s.map(e=>{const t=n.get(e);if(!t)throw new Error(`negotiate returned unknown hash ${e}`);return{hash:e,...t}}))}),r=await a.phase("finalize",()=>g.finalize(t)),log(`run ${r.state}${r.deduped?" (deduped)":""}`),log(`report: ${r.reportUrl}`),log(`status: ${r.statusUrl}`),i.out&&await Fe(He.join(i.out,"run.json"),JSON.stringify(r,null,2)),"bitbucket"===i.ci.provider&&_&&l({reportKey:r.reportKey,reportUrl:r.reportUrl,statusUrl:r.statusUrl}),process.env.GITHUB_OUTPUT&&await Fe(process.env.GITHUB_OUTPUT,`report_key=${r.reportKey}\nreport_url=${r.reportUrl}\nstatus_url=${r.statusUrl}\n`,{flag:"a"})}return console.log(a.format()),0}catch(e){throw await releaseCurrentClaims(e instanceof Error?e.message:String(e)),e}finally{S?.stop(),process.removeListener("SIGINT",onSigint),process.removeListener("SIGTERM",onSigterm)}}var ru=void 0!==process.argv[1]&&(process.argv[1].endsWith("cli.ts")||process.argv[1].endsWith("cli.js"));ru&&main().then(e=>{process.exit(e)}).catch(e=>{console.error(`[visual-review] ${e instanceof Error?e.message:e}`),process.exit(1)});export{at as FROZEN_EPOCH_MS,buildFreezeInitScript,ot as FREEZE_MOTION_CSS,mt as KIT_VERSION,ft as FONTS_BUNDLE_VERSION,gt as DEVICE_SCALE_FACTOR,buildEnvFingerprint,yt as CHROMIUM_LAUNCH_ARGS,settlePage,storyboardRenderId,sha256Hex,looksBlank,percentile,summarize,Gd as TimingReport,enumerateTrackedStoryboards2 as enumerateTrackedStoryboards,scaleIgnoreRegionsToDevicePx,Yd as VisualReviewHttpError,zd as VisualReviewIngestClient,startDevserverSession2 as startDevserverSession,startCaptureSession2 as startCaptureSession,resolveOrClaimBaseline,explicitTempoDirRelative,buildBaselineCaptureArgs,main};