vsn 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1864 -716
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +194 -53
- package/dist/index.d.ts +194 -53
- package/dist/index.js +1859 -714
- package/dist/index.js.map +1 -1
- package/dist/index.min.js +8 -8
- package/dist/index.min.js.map +1 -1
- package/dist/plugins/microdata.d.ts +481 -0
- package/dist/plugins/microdata.js +178 -0
- package/dist/plugins/microdata.js.map +1 -0
- package/dist/plugins/microdata.min.js +2 -0
- package/dist/plugins/microdata.min.js.map +1 -0
- package/package.json +2 -1
package/dist/index.min.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
2
|
-
`;)this.next()}readBlockComment(){for(this.next(),this.next();!this.eof();){if(this.peek()==="*"&&this.peek(1)==="/"){this.next(),this.next();return}this.next()}}readIdentifier(){let
|
|
3
|
-
`?(this.line+=1,this.column=1):this.column+=1,
|
|
4
|
-
`||e==="\r"}isAlpha(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}isDigit(e){return e>="0"&&e<="9"}isAlphaNumeric(e){return this.isAlpha(e)||this.isDigit(e)}};var u=class{constructor(e){this.type=e}async prepare(e){}async evaluate(e){}};async function pe(p,e){let t=p.scope;if(!t||!t.createChild)return e.evaluate(p);let s=p.scope;p.scope=t.createChild();try{return await e.evaluate(p)}finally{p.scope=s}}var j=class extends u{constructor(t,s=[]){super("Program");this.behaviors=t;this.uses=s}},G=class extends u{constructor(t,s,r={},i={}){super("Use");this.name=t;this.alias=s;this.flags=r;this.flagArgs=i}},y=class extends u{constructor(t){super("Block");this.statements=t}async evaluate(t){for(let s of this.statements){if(t.returning)break;s&&typeof s.evaluate=="function"&&await s.evaluate(t)}}},K=class extends u{constructor(t){super("Selector");this.selectorText=t}},C=class extends u{constructor(t,s){super("Behavior");this.selector=t;this.body=s}},Q=class extends u{constructor(t,s,r){super("StateEntry");this.name=t;this.value=s;this.important=r}},_=class extends u{constructor(t){super("StateBlock");this.entries=t}},b=class extends u{constructor(t,s,r,i=[]){super("OnBlock");this.eventName=t;this.args=s;this.body=r;this.modifiers=i}},B=class extends u{constructor(t,s,r="="){super("Assignment");this.target=t;this.value=s;this.operator=r}async evaluate(t){if(!t.scope||!t.scope.setPath)return;let s=await this.value.evaluate(t);if(this.operator!=="=")return this.applyCompoundAssignment(t,s);if(this.target instanceof m&&this.target.name.startsWith("root.")&&t.rootScope){let r=this.target.name.slice(5);return t.rootScope.setPath?.(`self.${r}`,s),s}return this.assignTarget(t,this.target,s),s}applyCompoundAssignment(t,s){if(!t.scope||!t.scope.setPath)return;if(!(this.target instanceof m))throw new Error("Compound assignment requires a simple identifier");let r=this.target.name.startsWith("root."),i=r&&t.rootScope?t.rootScope:t.scope,n=r?this.target.name.slice(5):this.target.name,a=r?`self.${n}`:n,o=i?.getPath?i.getPath(a):void 0,c;return this.operator==="+="?c=o+s:this.operator==="-="?c=o-s:this.operator==="*="?c=o*s:c=o/s,i?.setPath?.(a,c),c}assignTarget(t,s,r){if(!(!t.scope||!t.scope.setPath)){if(s instanceof m){t.scope.setPath(s.name,r);return}if(s instanceof H){let i=Array.isArray(r)?r:[],n=0;for(let a of s.elements){if(a instanceof M){t.scope.setPath(a.target.name,i.slice(n));return}if(a===null){n+=1;continue}this.assignTarget(t,a,i[n]),n+=1}return}if(s instanceof I){let i=r&&typeof r=="object"?r:{},n=new Set;for(let a of s.entries){if("rest"in a){let o={};for(let c of Object.keys(i))n.has(c)||(o[c]=i[c]);t.scope.setPath(a.rest.name,o);continue}n.add(a.key),this.assignTarget(t,a.target,i[a.key])}return}}}},D=class extends u{constructor(t){super("Return");this.value=t}async evaluate(t){return t.returning||(t.returnValue=this.value?await this.value.evaluate(t):void 0,t.returning=!0),t.returnValue}},Z=class extends u{constructor(t,s,r){super("If");this.test=t;this.consequent=s;this.alternate=r}async evaluate(t){if(await this.test.evaluate(t))return pe(t,this.consequent);if(this.alternate)return pe(t,this.alternate)}},J=class extends u{constructor(t,s){super("While");this.test=t;this.body=s}async evaluate(t){let s=t.scope;t.scope?.createChild&&(t.scope=t.scope.createChild());try{for(;await this.test.evaluate(t)&&(await this.body.evaluate(t),!t.returning););}finally{t.scope=s}}},Y=class extends u{constructor(t,s,r,i){super("For");this.init=t;this.test=s;this.update=r;this.body=i}async evaluate(t){this.init&&await this.init.evaluate(t);let s=t.scope,r=t.scope;for(t.scope?.createChild&&(r=t.scope.createChild());(!this.test||await this.test.evaluate(t))&&(t.scope=r,await this.body.evaluate(t),!t.returning);)t.scope=s,this.update&&await this.update.evaluate(t);t.scope=s}},X=class extends u{constructor(t,s,r){super("Try");this.body=t;this.errorName=s;this.handler=r}async evaluate(t){try{return await pe(t,this.body)}catch(s){if(t.returning)return t.returnValue;let r=t.scope,i=t.scope;t.scope?.createChild&&(i=t.scope.createChild()),t.scope=i;let n=t.scope,a;n&&(a=n.getPath(this.errorName),n.setPath&&n.setPath(`self.${this.errorName}`,s)),await this.handler.evaluate(t),n&&n.setPath&&i===r&&n.setPath(this.errorName,a),t.scope=r}}},L=class extends u{constructor(t,s,r,i=!1){super("FunctionDeclaration");this.name=t;this.params=s;this.body=r;this.isAsync=i}},S=class extends u{constructor(t,s,r=!1){super("FunctionExpression");this.params=t;this.body=s;this.isAsync=r}async evaluate(t){let s=t.scope,r=t.globals,i=t.element;return async(...n)=>{let a=s?.createChild?s.createChild():s,o={scope:a,rootScope:t.rootScope,...r?{globals:r}:{},...i?{element:i}:{},returnValue:void 0,returning:!1};if(a){let c=new Map;await this.applyParams(a,c,o,n),await this.body.evaluate(o),a===s&&this.restoreParams(a,c)}else await this.body.evaluate(o);return o.returnValue}}async applyParams(t,s,r,i){if(!t||!t.setPath)return;let n=0;for(let a of this.params){let o=a.name;if(!o)continue;if(s.set(o,t.getPath(o)),a.rest){t.setPath(`self.${o}`,i.slice(n)),n=i.length;continue}let c=i[n];c===void 0&&a.defaultValue&&(c=await a.defaultValue.evaluate(r)),t.setPath(`self.${o}`,c),n+=1}}restoreParams(t,s){if(!(!t||!t.setPath))for(let r of this.params){let i=r.name;i&&t.setPath(i,s.get(i))}}},F=class extends u{constructor(t,s,r,i,n){super("Declaration");this.target=t;this.operator=s;this.value=r;this.flags=i;this.flagArgs=n}},m=class extends u{constructor(t){super("Identifier");this.name=t}async evaluate(t){if(this.name.startsWith("root.")&&t.rootScope){let s=this.name.slice(5);return t.rootScope.getPath(`self.${s}`)}if(t.scope){let s=t.scope.getPath(this.name),r=this.name.split(".")[0];if(this.name.startsWith("parent.")||this.name.startsWith("root.")||this.name.startsWith("self.")||s!==void 0||r&&t.scope.hasKey?.(r))return s}return t.globals?t.globals[this.name]:void 0}},R=class extends u{constructor(t){super("SpreadElement");this.value=t}},M=class extends u{constructor(t){super("RestElement");this.target=t}},H=class extends u{constructor(t){super("ArrayPattern");this.elements=t}},I=class extends u{constructor(t){super("ObjectPattern");this.entries=t}},k=class extends u{constructor(t){super("Literal");this.value=t}async evaluate(){return this.value}},ee=class extends u{constructor(t){super("TemplateExpression");this.parts=t}async evaluate(t){let s="";for(let r of this.parts){let i=await r.evaluate(t);s+=i==null?"":String(i)}return s}},O=class extends u{constructor(t,s){super("UnaryExpression");this.operator=t;this.argument=s}async evaluate(t){let s=await this.argument.evaluate(t);return this.operator==="!"?!s:this.operator==="-"?-s:s}},v=class extends u{constructor(t,s,r){super("BinaryExpression");this.operator=t;this.left=s;this.right=r}async evaluate(t){if(this.operator==="&&")return await this.left.evaluate(t)&&await this.right.evaluate(t);if(this.operator==="||")return await this.left.evaluate(t)||await this.right.evaluate(t);if(this.operator==="??")return await this.left.evaluate(t)??await this.right.evaluate(t);let s=await this.left.evaluate(t),r=await this.right.evaluate(t);if(this.operator==="+")return s+r;if(this.operator==="-")return s-r;if(this.operator==="*")return s*r;if(this.operator==="/")return s/r;if(this.operator==="%")return s%r;if(this.operator==="==")return s==r;if(this.operator==="!=")return s!=r;if(this.operator==="===")return s===r;if(this.operator==="!==")return s!==r;if(this.operator==="<")return s<r;if(this.operator===">")return s>r;if(this.operator==="<=")return s<=r;if(this.operator===">=")return s>=r}},te=class extends u{constructor(t,s,r){super("TernaryExpression");this.test=t;this.consequent=s;this.alternate=r}async evaluate(t){return await this.test.evaluate(t)?this.consequent.evaluate(t):this.alternate.evaluate(t)}},N=class p extends u{constructor(t,s,r=!1){super("MemberExpression");this.target=t;this.property=s;this.optional=r}async evaluate(t){return(await this.resolve(t))?.value}async resolve(t){let s=this.getIdentifierPath();if(s){let i=this.resolveFromScope(t,s);if(i)return i;let n=this.resolveFromGlobals(t,s);if(n)return n}let r=await this.target.evaluate(t);return r==null?{value:void 0,target:r,optional:this.optional}:{value:r[this.property],target:r,optional:this.optional}}getIdentifierPath(){let t=this.getTargetIdentifierPath();return t?{path:`${t.path}.${this.property}`,root:t.root}:void 0}getTargetIdentifierPath(){if(this.target instanceof m){let t=this.target.name,s=t.split(".")[0];return s?{path:t,root:s}:void 0}if(this.target instanceof p)return this.target.getIdentifierPath()}resolveFromScope(t,s){if(!t.scope)return;if(s.path.startsWith("root.")&&t.rootScope){let o=s.path.slice(5),c=t.rootScope.getPath(`self.${o}`),h=o.split(".").slice(0,-1).join("."),f=h?t.rootScope.getPath(`self.${h}`):t.rootScope;return{value:c,target:f,optional:this.optional}}let r=t.scope.getPath(s.path);if(!(s.path.startsWith("parent.")||s.path.startsWith("root.")||s.path.startsWith("self."))&&r===void 0&&!t.scope.hasKey?.(s.root))return;let n=this.getTargetPath(s.path),a=n?t.scope.getPath(n):void 0;return{value:r,target:a,optional:this.optional}}resolveFromGlobals(t,s){let r=t.globals??{};if(!s.root||!(s.root in r))return;let i=r[s.root],n,a=s.path.split(".");for(let o=1;o<a.length;o+=1){n=i;let c=a[o];if(!c)return{value:void 0,target:n,optional:this.optional};i=i?.[c]}return{value:i,target:n,optional:this.optional}}getTargetPath(t){let s=t.split(".");if(!(s.length<=1))return s.slice(0,-1).join(".")}},w=class extends u{constructor(t,s){super("CallExpression");this.callee=t;this.args=s}async evaluate(t){let s=await this.resolveCallee(t),r=s?.fn??await this.callee.evaluate(t);if(typeof r!="function")return;let i=[];for(let n of this.args)i.push(await n.evaluate(t));return r.apply(s?.thisArg,i)}async resolveCallee(t){if(this.callee instanceof N){let c=await this.callee.resolve(t);return c?{fn:c.value,thisArg:c.target}:void 0}if(!(this.callee instanceof m))return;let s=this.callee.name,r=t.globals??{},i=s.split("."),n=i[0];if(!n||!(n in r)){if(i.length>1&&t.scope){let c=i.slice(0,-1).join("."),h=i[i.length-1];if(!h)return;let f=t.scope.getPath(c);return f==null?void 0:{fn:f?.[h],thisArg:f}}return}let a=r[n],o;for(let c=1;c<i.length;c+=1){o=a;let h=i[c];if(!h)return;a=a?.[h]}return{fn:a,thisArg:o}}},se=class extends u{constructor(t){super("ArrayExpression");this.elements=t}async evaluate(t){let s=[];for(let r of this.elements){if(r instanceof R){let i=await r.value.evaluate(t);if(i==null)continue;if(typeof i[Symbol.iterator]=="function")for(let a of i)s.push(a);else s.push(i);continue}s.push(await r.evaluate(t))}return s}},re=class extends u{constructor(t){super("ObjectExpression");this.entries=t}async evaluate(t){let s={};for(let r of this.entries){if("spread"in r){let i=await r.spread.evaluate(t);i!=null&&Object.assign(s,i);continue}if("computed"in r&&r.computed){let i=await r.keyExpr.evaluate(t);s[String(i)]=await r.value.evaluate(t)}else s[r.key]=await r.value.evaluate(t)}return s}},ie=class extends u{constructor(t,s){super("IndexExpression");this.target=t;this.index=s}async evaluate(t){let s=await this.target.evaluate(t);if(s==null)return;let r=await this.index.evaluate(t);if(r!=null)return s[r]}},x=class extends u{constructor(t,s){super("Directive");this.kind=t;this.name=s}async evaluate(t){let s=t.element;if(!s)return`${this.kind}:${this.name}`;if(this.kind==="attr")return this.name==="value"&&(s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement)?s.value:this.name==="checked"&&s instanceof HTMLInputElement?s.checked:this.name==="html"&&s instanceof HTMLElement?s.innerHTML:s.getAttribute(this.name)??void 0;if(this.kind==="style"&&s instanceof HTMLElement)return s.style.getPropertyValue(this.name)??void 0}},U=class extends u{constructor(t){super("AwaitExpression");this.argument=t}async evaluate(t){return await await this.argument.evaluate(t)}},ne=class extends u{constructor(t,s){super("Query");this.direction=t;this.selector=s}async evaluate(t){let s=this.selector.trim();if(!s)return[];if(this.direction==="ancestor"){let i=[],n=t.element?.parentElement;for(;n;)n.matches(s)&&i.push(n),n=n.parentElement;return i}let r=this.direction==="descendant"?t.element??(typeof document<"u"?document:void 0):typeof document<"u"?document:void 0;return!r||!("querySelectorAll"in r)?[]:Array.from(r.querySelectorAll(s))}};var ae=class{constructor(e){this.tokens=e}index=0;peek(e=0){return this.tokens[this.index+e]??null}next(){let e=this.tokens[this.index++];if(!e)throw new Error("Unexpected end of input");return e}eof(){return this.index>=this.tokens.length}match(e){return this.peek()?.type===e?(this.next(),!0):!1}expect(e){let t=this.next();if(t.type!==e)throw new Error(`Expected ${e} but got ${t.type}`);return t}skipWhitespace(){for(;this.peek()?.type==="Whitespace";)this.next()}peekNonWhitespace(e=0){let t=0;for(let s=this.index;s<this.tokens.length;s++){let r=this.tokens[s];if(r.type!=="Whitespace"){if(t===e)return r;t+=1}}return null}};var A=class p{stream;source;customFlags;allowImplicitSemicolon=!1;awaitStack=[];constructor(e,t){this.source=e,this.customFlags=t?.customFlags??new Set;let s=new T(e);this.stream=new ae(s.tokenize())}static parseInline(e){return new p(`{${e}}`).parseInlineBlock()}parseProgram(){return this.wrapErrors(()=>{let e=[],t=[];for(this.stream.skipWhitespace();!this.stream.eof();){let s=this.stream.peek();if(!s)break;s.type==="Use"?t.push(this.parseUseStatement()):e.push(this.parseBehavior()),this.stream.skipWhitespace()}return new j(e,t)})}parseInlineBlock(){return this.wrapErrors(()=>(this.stream.skipWhitespace(),this.allowImplicitSemicolon=!0,this.parseBlock({allowDeclarations:!1})))}parseBehavior(){return this.wrapErrors(()=>{this.stream.skipWhitespace(),this.stream.expect("Behavior");let e=this.parseSelector(),t=this.parseBlock({allowDeclarations:!0});return new C(e,t)})}parseSelector(){let e="",t=!1;for(;;){let s=this.stream.peek();if(!s||s.type==="LBrace")break;if(s.type==="Whitespace"){this.stream.next(),t&&e[e.length-1]!==" "&&(e+=" ");continue}t=!0,e+=this.stream.next().value}if(!e.trim())throw new Error("Behavior selector is required");return new K(e.trim())}parseUseStatement(){return this.wrapErrors(()=>{this.stream.expect("Use"),this.stream.skipWhitespace();let e=this.parseIdentifierPath();this.stream.skipWhitespace();let t=e,s=this.stream.peek();s?.type==="Identifier"&&s.value==="as"&&(this.stream.next(),this.stream.skipWhitespace(),t=this.stream.expect("Identifier").value);let{flags:r,flagArgs:i}=this.parseUseFlags();return this.stream.skipWhitespace(),this.stream.expect("Semicolon"),new G(e,t,r,i)})}parseUseFlags(){let e={},t={};for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="Bang";){this.stream.next();let s=this.stream.expect("Identifier").value;if(s!=="wait")throw new Error(`Unknown flag ${s}`);if(e.wait=!0,this.stream.peek()?.type==="LParen"){this.stream.next(),this.stream.skipWhitespace();let r=this.stream.expect("Number"),i=Number(r.value),n;if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next(),this.stream.skipWhitespace();let a=this.stream.expect("Number");n=Number(a.value),this.stream.skipWhitespace()}this.stream.expect("RParen"),t.wait={timeoutMs:i,...n!==void 0?{intervalMs:n}:{}}}}return{flags:e,flagArgs:t}}wrapErrors(e){try{return e()}catch(t){throw t instanceof Error&&!/\(line\s+\d+, column\s+\d+\)/i.test(t.message)?new Error(this.formatError(t.message)):t}}formatError(e){let t=this.stream.peek()??this.stream.peekNonWhitespace(0);if(!t)return`Parse error: ${e}`;let s=t.start.line,r=t.start.column,i=this.getLineSnippet(s,r);return`Parse error (line ${s}, column ${r}): ${e}
|
|
5
|
-
${i}`}getLineSnippet(e
|
|
6
|
-
${i}`}parseBlock(e){let t=e?.allowDeclarations??!1;this.stream.skipWhitespace(),this.stream.expect("LBrace");let s=[],r=t,i=!1,n=!1,a=!1;for(;;){this.stream.skipWhitespace();let o=this.stream.peek();if(!o)throw new Error("Unterminated block");if(o.type==="RBrace"){this.stream.next();break}if(t&&o.type==="Behavior"&&(a=!0),t&&a&&o.type!=="Behavior")throw new Error("Nested behaviors must appear after construct, function, and on blocks");if(t&&this.isFunctionDeclarationStart()){i||(n=!0),s.push(this.parseFunctionDeclaration());continue}if(t&&this.isFunctionExpressionAssignmentStart()){if(!r)throw new Error("Declarations must appear before blocks");s.push(this.parseAssignment());continue}if(this.isDeclarationStart()){if(!t)throw new Error("Declarations are only allowed at the behavior root");if(!r)throw new Error("Declarations must appear before blocks");s.push(this.parseDeclaration())}else{if(r&&(r=!1),t&&o.type==="On"&&!i&&(n=!0),t&&o.type==="Construct"){if(n)throw new Error("Construct blocks must appear before functions and on blocks");i=!0}s.push(this.parseStatement())}}return new y(s)}parseStatement(e){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)throw new Error("Unexpected end of input");let s=e?.allowBlocks??!0,r=e?.allowReturn??!1;if(t.type==="Return"){if(!r)throw new Error("Return is only allowed inside functions");return this.parseReturnStatement()}if(s&&t.type==="On")return this.parseOnBlock();if(s&&t.type==="If")return this.parseIfBlock();if(s&&t.type==="For")return this.parseForBlock();if(s&&t.type==="While")return this.parseWhileBlock();if(s&&t.type==="Try")return this.parseTryBlock();if(s&&t.type==="Construct")return this.parseConstructBlock();if(s&&t.type==="Destruct")return this.parseDestructBlock();if(s&&t.type==="Behavior")return this.parseBehavior();if(this.isAwaitAllowed()&&t.type==="Identifier"&&t.value==="await")return this.parseExpressionStatement();if(this.isAssignmentStart())return this.parseAssignment();if(this.isExpressionStatementStart())return this.parseExpressionStatement();throw new Error(`Unexpected token ${t.type}`)}parseStateBlock(){this.stream.expect("State"),this.stream.skipWhitespace(),this.stream.expect("LBrace");let e=[];for(;;){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)throw new Error("Unterminated state block");if(t.type==="RBrace"){this.stream.next();break}let s=this.stream.expect("Identifier");this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace();let r=this.parseExpression();this.stream.skipWhitespace();let i=!1;if(this.stream.peek()?.type==="Bang"){this.stream.next(),this.stream.skipWhitespace();let n=this.stream.next();if(n.type==="Identifier"&&n.value==="important")i=!0;else throw new Error("Expected 'important' after '!'")}this.stream.skipWhitespace(),this.stream.expect("Semicolon"),e.push(new Q(s.value,r,i))}return new _(e)}parseOnBlock(){this.stream.expect("On"),this.stream.skipWhitespace();let e=this.parseIdentifierPath();this.stream.skipWhitespace(),this.stream.expect("LParen");let t=[];for(;;){this.stream.skipWhitespace();let i=this.stream.peek();if(!i)throw new Error("Unterminated on() arguments");if(i.type==="RParen"){this.stream.next();break}if(i.type==="Identifier"){t.push(this.stream.next().value),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"&&this.stream.next();continue}throw new Error(`Unexpected token in on() args: ${i.type}`)}let s=this.parseOnModifiers(),r=this.parseBlock({allowDeclarations:!1});return new b(e,t,r,s)}parseOnModifiers(){let e=[];for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="Bang";){this.stream.next();let t=this.stream.expect("Identifier").value;e.push(t)}return e}parseAssignment(){let e=this.parseAssignmentTarget();this.stream.skipWhitespace();let t=this.parseAssignmentOperator();this.stream.skipWhitespace();let s=this.parseExpression();return this.consumeStatementTerminator(),new B(e,s,t)}parseExpression(){return this.parsePipeExpression()}parsePipeExpression(){let e=this.parseTernaryExpression();for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="Pipe";){this.stream.next(),this.stream.skipWhitespace();let t=!1,s=this.stream.peek();this.isAwaitAllowed()&&s?.type==="Identifier"&&s.value==="await"&&(this.stream.next(),this.stream.skipWhitespace(),t=!0);let r=this.parseCallExpression(),i=this.buildPipeCall(e,r);e=t?new U(i):i}return e}buildPipeCall(e,t){if(t instanceof w)return new w(t.callee,[e,...t.args]);if(t instanceof m||t instanceof N)return new w(t,[e]);throw new Error("Pipe operator requires a function call")}parseTernaryExpression(){let e=this.parseNullishExpression();if(this.stream.skipWhitespace(),this.stream.peek()?.type!=="Question")return e;this.stream.next(),this.stream.skipWhitespace();let t=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace();let s=this.parseExpression();return new te(e,t,s)}parseNullishExpression(){let e=this.parseLogicalOrExpression();for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="NullishCoalesce";){this.stream.next(),this.stream.skipWhitespace();let t=this.parseLogicalOrExpression();e=new v("??",e,t)}return e}parseLogicalOrExpression(){let e=this.parseLogicalAndExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="Or")break;this.stream.skipWhitespace(),this.stream.next(),this.stream.skipWhitespace();let s=this.parseLogicalAndExpression();this.stream.skipWhitespace(),e=new v("||",e,s)}return e}parseLogicalAndExpression(){let e=this.parseEqualityExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="And")break;this.stream.skipWhitespace(),this.stream.next(),this.stream.skipWhitespace();let s=this.parseEqualityExpression();this.stream.skipWhitespace(),e=new v("&&",e,s)}return e}parseEqualityExpression(){let e=this.parseComparisonExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="DoubleEquals"&&t.type!=="NotEquals"&&t.type!=="TripleEquals"&&t.type!=="StrictNotEquals")break;this.stream.skipWhitespace();let s=this.stream.next();this.stream.skipWhitespace();let r=this.parseComparisonExpression();this.stream.skipWhitespace();let i="==";s.type==="NotEquals"?i="!=":s.type==="TripleEquals"?i="===":s.type==="StrictNotEquals"&&(i="!=="),e=new v(i,e,r)}return e}parseComparisonExpression(){let e=this.parseAdditiveExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="Less"&&t.type!=="Greater"&&t.type!=="LessEqual"&&t.type!=="GreaterEqual")break;this.stream.skipWhitespace();let s=this.stream.next();this.stream.skipWhitespace();let r=this.parseAdditiveExpression();this.stream.skipWhitespace();let i="<";s.type==="Greater"?i=">":s.type==="LessEqual"?i="<=":s.type==="GreaterEqual"&&(i=">="),e=new v(i,e,r)}return e}parseMultiplicativeExpression(){let e=this.parseUnaryExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="Star"&&t.type!=="Slash"&&t.type!=="Percent")break;this.stream.skipWhitespace();let s=this.stream.next();this.stream.skipWhitespace();let r=this.parseUnaryExpression();this.stream.skipWhitespace();let i="*";s.type==="Slash"?i="/":s.type==="Percent"&&(i="%"),e=new v(i,e,r)}return e}parseAdditiveExpression(){let e=this.parseMultiplicativeExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="Plus"&&t.type!=="Minus")break;this.stream.skipWhitespace();let s=this.stream.next();this.stream.skipWhitespace();let r=this.parseMultiplicativeExpression();this.stream.skipWhitespace(),e=new v(s.type==="Plus"?"+":"-",e,r)}return e}parseUnaryExpression(){this.stream.skipWhitespace();let e=this.stream.peek();if(!e)throw new Error("Expected expression");if(e.type==="Bang"){this.stream.next();let t=this.parseUnaryExpression();return new O("!",t)}if(e.type==="Minus"){this.stream.next();let t=this.parseUnaryExpression();return new O("-",t)}if(this.isAwaitAllowed()&&e.type==="Identifier"&&e.value==="await"){this.stream.next();let t=this.parseUnaryExpression();return new U(t)}return this.parseCallExpression()}parseCallExpression(){let e=this.parsePrimaryExpression();for(;;){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)break;if(t.type==="LParen"){this.stream.next();let s=[];for(;;){this.stream.skipWhitespace();let r=this.stream.peek();if(!r)throw new Error("Unterminated call expression");if(r.type==="RParen"){this.stream.next();break}if(s.push(this.parseExpression()),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RParen"){this.stream.next();break}throw new Error("Expected ',' or ')' in call arguments")}e=new w(e,s);continue}if(t.type==="OptionalChain"){this.stream.next(),this.stream.skipWhitespace();let s=this.stream.peek();if(!s)throw new Error("Expected property or call after ?.");if(s.type==="LParen"){this.stream.next();let r=[];for(;;){this.stream.skipWhitespace();let i=this.stream.peek();if(!i)throw new Error("Unterminated call expression");if(i.type==="RParen"){this.stream.next();break}if(r.push(this.parseExpression()),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RParen"){this.stream.next();break}throw new Error("Expected ',' or ')' in call arguments")}e=new w(e,r);continue}if(s.type==="Identifier"){let r=this.stream.next();e=new N(e,r.value,!0);continue}throw new Error("Expected property or call after ?.")}if(t.type==="Dot"){this.stream.next();let s=this.stream.expect("Identifier");e=new N(e,s.value);continue}if(t.type==="LBracket"){this.stream.next(),this.stream.skipWhitespace();let s=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RBracket"),e=new ie(e,s);continue}break}return e}parsePrimaryExpression(){this.stream.skipWhitespace();let e=this.stream.peek();if(!e)throw new Error("Expected expression");if(e.type==="At"||e.type==="Dollar"){let t=e.type==="At"?"attr":"style";this.stream.next();let s=this.stream.expect("Identifier");return new x(t,s.value)}if(e.type==="Question")return this.parseQueryExpression();if(e.type==="LBracket")return this.parseArrayExpression();if(e.type==="LBrace")return this.parseObjectExpression();if(e.type==="LParen"){if(this.isArrowFunctionStart())return this.parseArrowFunctionExpression();this.stream.next();let t=this.parseExpression();return this.stream.skipWhitespace(),this.stream.expect("RParen"),t}if(e.type==="Identifier")return this.isAsyncToken(e)&&this.isAsyncArrowFunctionStart()?(this.stream.next(),this.stream.skipWhitespace(),this.parseArrowFunctionExpression(!0)):new m(this.stream.next().value);if(e.type==="Boolean")return new k(this.stream.next().value==="true");if(e.type==="Null")return this.stream.next(),new k(null);if(e.type==="Number")return new k(Number(this.stream.next().value));if(e.type==="String")return new k(this.stream.next().value);if(e.type==="Template")return this.parseTemplateExpression();throw new Error(`Unsupported expression token ${e.type}`)}parseArrayExpression(){this.stream.expect("LBracket");let e=[];for(;;){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)throw new Error("Unterminated array literal");if(t.type==="RBracket"){this.stream.next();break}if(t.type==="Ellipsis"){this.stream.next(),this.stream.skipWhitespace();let s=this.parseExpression();e.push(new R(s))}else e.push(this.parseExpression());if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="RBracket"){this.stream.next();break}continue}if(this.stream.peek()?.type==="RBracket"){this.stream.next();break}throw new Error("Expected ',' or ']' in array literal")}return new se(e)}parseTemplateExpression(){let e=[];for(;;){let t=this.stream.peek();if(!t)throw new Error("Unterminated template literal");if(t.type!=="Template")throw new Error("Expected template literal");let s=this.stream.next().value;s&&e.push(new k(s));let r=this.stream.peek();if(!r||r.type!=="Dollar")break;this.stream.next(),this.stream.expect("LBrace"),this.stream.skipWhitespace();let i=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RBrace"),e.push(i)}return new ee(e)}parseObjectExpression(){this.stream.expect("LBrace");let e=[];for(;;){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)throw new Error("Unterminated object literal");if(t.type==="RBrace"){this.stream.next();break}let s,r;if(t.type==="Ellipsis")this.stream.next(),this.stream.skipWhitespace(),r={spread:this.parseExpression()};else if(t.type==="LBracket"){this.stream.next(),this.stream.skipWhitespace();let i=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RBracket"),this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace(),s=this.parseExpression(),r={keyExpr:i,value:s,computed:!0}}else if(t.type==="Identifier"){let i=this.stream.next().value;this.stream.skipWhitespace(),this.stream.peek()?.type==="Colon"?(this.stream.next(),this.stream.skipWhitespace(),s=this.parseExpression()):s=new m(i),r={key:i,value:s}}else if(t.type==="String"){let i=this.stream.next().value;this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace(),s=this.parseExpression(),r={key:i,value:s}}else throw new Error(`Unexpected token in object literal: ${t.type}`);if(!r)throw new Error("Invalid object literal entry");if(e.push(r),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="RBrace"){this.stream.next();break}continue}if(this.stream.peek()?.type==="RBrace"){this.stream.next();break}throw new Error("Expected ',' or '}' in object literal")}return new re(e)}consumeStatementTerminator(){this.stream.skipWhitespace();let e=this.stream.peek();if(e?.type==="Semicolon"){this.stream.next();return}this.allowImplicitSemicolon&&e?.type==="RBrace"||this.stream.expect("Semicolon")}parseFunctionBlockWithAwait(e){this.stream.expect("LBrace");let t=[];this.awaitStack.push(e);try{for(;;){this.stream.skipWhitespace();let s=this.stream.peek();if(!s)throw new Error("Unterminated function block");if(s.type==="RBrace"){this.stream.next();break}t.push(this.parseStatement({allowBlocks:!1,allowReturn:!0}))}}finally{this.awaitStack.pop()}return new y(t)}isAsyncToken(e){return e?.type==="Identifier"&&e.value==="async"}isAwaitAllowed(){return this.awaitStack.length===0?!1:this.awaitStack[this.awaitStack.length-1]===!0}parseArrowExpressionBody(e){this.awaitStack.push(e);try{let t=this.parseExpression();return new y([new D(t)])}finally{this.awaitStack.pop()}}parseAssignmentTarget(){let e=this.stream.peek();if(!e)throw new Error("Expected assignment target");if(e.type==="At"||e.type==="Dollar"){let t=e.type==="At"?"attr":"style";this.stream.next();let s=this.stream.expect("Identifier");return new x(t,s.value)}if(e.type==="LBracket")return this.parseArrayPattern();if(e.type==="LBrace")return this.parseObjectPattern();if(e.type==="Identifier")return new m(this.parseIdentifierPath());throw new Error(`Invalid assignment target ${e.type}`)}parseArrayPattern(){this.stream.expect("LBracket");let e=[],t=!1;for(;;){this.stream.skipWhitespace();let s=this.stream.peek();if(!s)throw new Error("Unterminated array pattern");if(s.type==="RBracket"){this.stream.next();break}if(s.type==="Comma"){this.stream.next(),e.push(null);continue}if(s.type==="Ellipsis"){if(t)throw new Error("Array patterns can only include one rest element");this.stream.next(),this.stream.skipWhitespace();let r=this.stream.expect("Identifier");e.push(new M(new m(r.value))),t=!0}else if(s.type==="LBracket")e.push(this.parseArrayPattern());else if(s.type==="LBrace")e.push(this.parseObjectPattern());else if(s.type==="Identifier")e.push(new m(this.parseIdentifierPath()));else throw new Error(`Unexpected token in array pattern: ${s.type}`);if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RBracket"){this.stream.next();break}throw new Error("Expected ',' or ']' in array pattern")}if(t&&!(e[e.length-1]instanceof M))throw new Error("Rest element must be last in array pattern");return new H(e)}parseObjectPattern(){this.stream.expect("LBrace");let e=[],t;for(;;){this.stream.skipWhitespace();let r=this.stream.peek();if(!r)throw new Error("Unterminated object pattern");if(r.type==="RBrace"){this.stream.next();break}if(r.type==="Ellipsis"){if(t)throw new Error("Object patterns can only include one rest element");this.stream.next(),this.stream.skipWhitespace();let i=this.stream.expect("Identifier");if(t=new m(i.value),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"&&(this.stream.next(),this.stream.skipWhitespace()),this.stream.peek()?.type!=="RBrace")throw new Error("Rest element must be last in object pattern");this.stream.next();break}else if(r.type==="Identifier"||r.type==="String"){let n=this.stream.next().value;this.stream.skipWhitespace();let a;if(this.stream.peek()?.type==="Colon"){this.stream.next(),this.stream.skipWhitespace();let o=this.stream.peek();if(!o)throw new Error("Expected object pattern target");if(o.type==="LBracket")a=this.parseArrayPattern();else if(o.type==="LBrace")a=this.parseObjectPattern();else if(o.type==="Identifier")a=new m(this.parseIdentifierPath());else throw new Error(`Unexpected token in object pattern: ${o.type}`)}else a=new m(n);e.push({key:n,target:a})}else throw new Error(`Unexpected token in object pattern: ${r.type}`);if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="RBrace"){this.stream.next();break}continue}if(this.stream.peek()?.type==="RBrace"){this.stream.next();break}throw new Error("Expected ',' or '}' in object pattern")}let s=t?[...e,{rest:t}]:e;return t&&e.length===0?new I([{rest:t}]):new I(s)}parseDeclaration(){let e=this.parseDeclarationTarget();this.stream.skipWhitespace();let t=this.parseDeclarationOperator();this.stream.skipWhitespace();let s=this.parseExpression(),{flags:r,flagArgs:i}=this.parseFlags();return this.stream.skipWhitespace(),this.stream.expect("Semicolon"),new F(e,t,s,r,i)}parseDeclarationTarget(){let e=this.stream.peek();if(!e)throw new Error("Expected declaration target");if(e.type==="At"||e.type==="Dollar"){let t=e.type==="At"?"attr":"style";this.stream.next();let s=this.stream.expect("Identifier");return new x(t,s.value)}if(e.type==="Identifier")return new m(this.stream.next().value);throw new Error(`Invalid declaration target ${e.type}`)}parseDeclarationOperator(){this.stream.expect("Colon");let e=this.stream.peek();return e?e.type==="Equals"?(this.stream.next(),":="):e.type==="Less"?(this.stream.next(),":<"):e.type==="Greater"?(this.stream.next(),":>"):":":":"}parseFlags(){let e={},t={};for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="Bang";){this.stream.next();let s=this.stream.expect("Identifier").value;if(s==="important")e.important=!0;else if(s==="trusted")e.trusted=!0;else if(s==="debounce")if(e.debounce=!0,this.stream.peek()?.type==="LParen"){this.stream.next(),this.stream.skipWhitespace();let r=this.stream.expect("Number");t.debounce=Number(r.value),this.stream.skipWhitespace(),this.stream.expect("RParen")}else t.debounce=200;else if(this.customFlags.has(s)){e[s]=!0;let r=this.parseCustomFlagArg();r!==void 0&&(t[s]=r)}else throw new Error(`Unknown flag ${s}`)}return{flags:e,flagArgs:t}}parseCustomFlagArg(){if(this.stream.peek()?.type!=="LParen")return;this.stream.next(),this.stream.skipWhitespace();let e=this.stream.peek();if(!e)throw new Error("Unterminated flag arguments");let t;if(e.type==="Number")t=Number(this.stream.next().value);else if(e.type==="String")t=this.stream.next().value;else if(e.type==="Boolean")t=this.stream.next().value==="true";else if(e.type==="Identifier")t=this.stream.next().value;else throw new Error(`Unsupported flag argument ${e.type}`);return this.stream.skipWhitespace(),this.stream.expect("RParen"),t}isDeclarationStart(){let e=this.stream.peekNonWhitespace(0);if(!e)return!1;if(e.type==="Identifier")return this.stream.peekNonWhitespace(1)?.type==="Colon";if(e.type==="At"||e.type==="Dollar"){let t=this.stream.peekNonWhitespace(1),s=this.stream.peekNonWhitespace(2);return t?.type==="Identifier"&&s?.type==="Colon"}return!1}isAssignmentStart(){let e=this.stream.peekNonWhitespace(0);if(!e)return!1;if(e.type==="Identifier"){let t=1;for(;this.stream.peekNonWhitespace(t)?.type==="Dot"&&this.stream.peekNonWhitespace(t+1)?.type==="Identifier";)t+=2;return this.isAssignmentOperatorStart(t)}if(e.type==="At"||e.type==="Dollar"){let t=this.stream.peekNonWhitespace(1),s=this.stream.peekNonWhitespace(2);return t?.type==="Identifier"&&this.isAssignmentOperatorStart(2)}if(e.type==="LBrace"||e.type==="LBracket"){let t=[],s=0;for(;;){let r=this.stream.peekNonWhitespace(s);if(!r)return!1;if(r.type==="LBrace"||r.type==="LBracket")t.push(r.type);else if((r.type==="RBrace"||r.type==="RBracket")&&(t.pop(),t.length===0))return this.isAssignmentOperatorStart(s+1);s+=1}}return!1}isAssignmentOperatorStart(e){let t=this.stream.peekNonWhitespace(e);return t?t.type==="Equals"?!0:t.type==="Plus"||t.type==="Minus"||t.type==="Star"||t.type==="Slash"?this.stream.peekNonWhitespace(e+1)?.type==="Equals":!1:!1}isCallStart(){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="Identifier")return!1;let t=1;for(;this.stream.peekNonWhitespace(t)?.type==="Dot"&&this.stream.peekNonWhitespace(t+1)?.type==="Identifier";)t+=2;return this.stream.peekNonWhitespace(t)?.type==="LParen"}isExpressionStatementStart(){let e=this.stream.peekNonWhitespace(0);return e?e.type==="Identifier"?!0:e.type==="Number"||e.type==="String"||e.type==="Boolean"||e.type==="Null"||e.type==="LParen"||e.type==="LBracket"||e.type==="LBrace"||e.type==="At"||e.type==="Dollar"||e.type==="Question"||e.type==="Bang"||e.type==="Minus":!1}isFunctionDeclarationStart(){let e=this.stream.peekNonWhitespace(0);if(!e)return!1;let t=0;if(this.isAsyncToken(e)){let r=this.stream.peekNonWhitespace(1);if(!r||r.type!=="Identifier")return!1;t=1}else if(e.type!=="Identifier")return!1;if(t+=1,this.stream.peekNonWhitespace(t)?.type!=="LParen")return!1;t+=1;let s=1;for(;;){let r=this.stream.peekNonWhitespace(t);if(!r)return!1;if(r.type==="LParen")s+=1;else if(r.type==="RParen"&&(s-=1,s===0)){t+=1;break}t+=1}return this.stream.peekNonWhitespace(t)?.type==="LBrace"}isArrowFunctionStart(){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="LParen")return!1;let t=1,s=1;for(;;){let r=this.stream.peekNonWhitespace(t);if(!r)return!1;if(r.type==="LParen")s+=1;else if(r.type==="RParen"&&(s-=1,s===0)){t+=1;break}t+=1}return this.stream.peekNonWhitespace(t)?.type==="Arrow"}isAsyncArrowFunctionStart(){let e=this.stream.peekNonWhitespace(0);if(!this.isAsyncToken(e)||this.stream.peekNonWhitespace(1)?.type!=="LParen")return!1;let t=2,s=1;for(;;){let r=this.stream.peekNonWhitespace(t);if(!r)return!1;if(r.type==="LParen")s+=1;else if(r.type==="RParen"&&(s-=1,s===0)){t+=1;break}t+=1}return this.stream.peekNonWhitespace(t)?.type==="Arrow"}isFunctionExpressionAssignmentStart(){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="Identifier"||this.stream.peekNonWhitespace(1)?.type!=="Equals")return!1;let t=2;if(this.isAsyncToken(this.stream.peekNonWhitespace(t))&&(t+=1),this.stream.peekNonWhitespace(t)?.type!=="LParen")return!1;t+=1;let s=1;for(;;){let r=this.stream.peekNonWhitespace(t);if(!r)return!1;if(r.type==="LParen")s+=1;else if(r.type==="RParen"&&(s-=1,s===0)){t+=1;break}t+=1}return this.stream.peekNonWhitespace(t)?.type==="Arrow"}parseExpressionStatement(){let e=this.parseExpression();return this.consumeStatementTerminator(),e}parseIfBlock(){this.stream.expect("If"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let e=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RParen");let t=this.parseBlock({allowDeclarations:!1});this.stream.skipWhitespace();let s;if(this.stream.peek()?.type==="Else")if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="If"){let r=this.parseIfBlock();s=new y([r])}else s=this.parseBlock({allowDeclarations:!1});return new Z(e,t,s)}parseWhileBlock(){this.stream.expect("While"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let e=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RParen");let t=this.parseBlock({allowDeclarations:!1});return new J(e,t)}parseForBlock(){this.stream.expect("For"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let e;this.stream.peek()?.type!=="Semicolon"&&(e=this.parseForClause()),this.stream.skipWhitespace(),this.stream.expect("Semicolon"),this.stream.skipWhitespace();let t;this.stream.peek()?.type!=="Semicolon"&&(t=this.parseExpression()),this.stream.skipWhitespace(),this.stream.expect("Semicolon"),this.stream.skipWhitespace();let s;this.stream.peek()?.type!=="RParen"&&(s=this.parseForClause()),this.stream.skipWhitespace(),this.stream.expect("RParen");let r=this.parseBlock({allowDeclarations:!1});return new Y(e,t,s,r)}parseForClause(){return this.isAssignmentStart()?this.parseAssignmentExpression():this.parseExpression()}parseAssignmentExpression(){let e=this.parseAssignmentTarget();this.stream.skipWhitespace();let t=this.parseAssignmentOperator();this.stream.skipWhitespace();let s=this.parseExpression();return new B(e,s,t)}parseAssignmentOperator(){let e=this.stream.peek();if(!e)throw new Error("Expected assignment operator");if(e.type==="Equals")return this.stream.next(),"=";if(e.type==="Plus"||e.type==="Minus"||e.type==="Star"||e.type==="Slash"){let t=this.stream.next();return this.stream.expect("Equals"),t.type==="Plus"?"+=":t.type==="Minus"?"-=":t.type==="Star"?"*=":"/="}throw new Error("Expected assignment operator")}parseTryBlock(){this.stream.expect("Try");let e=this.parseBlock({allowDeclarations:!1});this.stream.skipWhitespace(),this.stream.expect("Catch"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let t=this.stream.expect("Identifier").value;this.stream.skipWhitespace(),this.stream.expect("RParen");let s=this.parseBlock({allowDeclarations:!1});return new X(e,t,s)}parseConstructBlock(){this.stream.expect("Construct");let e=this.parseBlock({allowDeclarations:!1});return e.type="Construct",e}parseDestructBlock(){this.stream.expect("Destruct");let e=this.parseBlock({allowDeclarations:!1});return e.type="Destruct",e}parseQueryExpression(){this.stream.expect("Question");let e="self";this.stream.peek()?.type==="Greater"?(this.stream.next(),e="descendant"):this.stream.peek()?.type==="Less"&&(this.stream.next(),e="ancestor"),this.stream.skipWhitespace(),this.stream.expect("LParen");let t=this.readSelectorUntil("RParen");return new ne(e,t)}parseFunctionDeclaration(){let e=!1,t=this.stream.peekNonWhitespace(0);this.isAsyncToken(t)&&(this.stream.next(),this.stream.skipWhitespace(),e=!0);let s=this.stream.expect("Identifier").value;this.stream.skipWhitespace();let r=this.parseFunctionParams();this.stream.skipWhitespace();let i=this.parseFunctionBlockWithAwait(e);return new L(s,r,i,e)}parseFunctionBlock(){return this.parseFunctionBlockWithAwait(!1)}parseReturnStatement(){if(this.stream.expect("Return"),this.stream.skipWhitespace(),this.stream.peek()?.type==="Semicolon")return this.stream.next(),new D;let e=this.parseExpression();return this.stream.skipWhitespace(),this.stream.expect("Semicolon"),new D(e)}parseArrowFunctionExpression(e=!1){let t=this.parseFunctionParams();if(this.stream.skipWhitespace(),this.stream.expect("Arrow"),this.stream.skipWhitespace(),this.stream.peek()?.type==="LBrace"){let r=this.parseFunctionBlockWithAwait(e);return new S(t,r,e)}let s=this.parseArrowExpressionBody(e);return new S(t,s,e)}parseFunctionParams(){this.stream.expect("LParen");let e=[],t=!1;for(;;){this.stream.skipWhitespace();let s=this.stream.peek();if(!s)throw new Error("Unterminated function parameters");if(s.type==="RParen"){this.stream.next();break}if(s.type==="Ellipsis"){if(t)throw new Error("Function parameters can only include one rest parameter");this.stream.next(),this.stream.skipWhitespace();let n=this.stream.expect("Identifier").value;if(e.push({name:n,rest:!0}),t=!0,this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma")throw new Error("Rest parameter must be last in function parameters");this.stream.expect("RParen");break}let r=this.stream.expect("Identifier").value;this.stream.skipWhitespace();let i;if(this.stream.peek()?.type==="Equals"&&(this.stream.next(),this.stream.skipWhitespace(),i=this.parseExpression()),e.push(i?{name:r,defaultValue:i}:{name:r}),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RParen"){this.stream.next();break}throw new Error("Expected ',' or ')' in function parameters")}return e}readSelectorUntil(e){let t="",s=!1;for(;;){let r=this.stream.peek();if(!r)throw new Error("Unterminated selector");if(r.type===e){this.stream.next();break}if(r.type==="Whitespace"){this.stream.next(),s&&t[t.length-1]!==" "&&(t+=" ");continue}s=!0,t+=this.stream.next().value}return t.trim()}parseIdentifierPath(){let e=this.stream.expect("Identifier").value;for(;this.stream.peek()?.type==="Dot";){this.stream.next();let t=this.stream.expect("Identifier").value;e=`${e}.${t}`}return e}};var $=class p{constructor(e){this.parent=e;this.root=e?e.root:this}data=new Map;root;listeners=new Map;anyListeners=new Set;createChild(){return new p(this)}get(e){return this.getPath(e)}set(e,t){this.setPath(e,t)}hasKey(e){let s=e.split(".")[0];return s?this.data.has(s):!1}getPath(e){let t=e.startsWith("parent.")||e.startsWith("root.")||e.startsWith("self."),{targetScope:s,targetPath:r}=this.resolveScope(e);if(!s||!r)return;let i=this.getLocalPathValue(s,r);if(t||i!==void 0)return i;let n=s.parent;for(;n;){let a=this.getLocalPathValue(n,r);if(a!==void 0)return a;n=n.parent}}setPath(e,t){let s=e.startsWith("parent.")||e.startsWith("root.")||e.startsWith("self."),{targetScope:r,targetPath:i}=this.resolveScope(e);if(!r||!i)return;let n=s?r:this.findNearestScopeWithKey(r,i)??r,a=i.split("."),o=a[0];if(!o)return;if(a.length===1){n.data.set(o,t),n.emitChange(i);return}let c=n.data.get(o);(c==null||typeof c!="object")&&(c={},n.data.set(o,c));let h=c;for(let d=1;d<a.length-1;d+=1){let g=a[d];if(!g)return;(h[g]==null||typeof h[g]!="object")&&(h[g]={}),h=h[g]}let f=a[a.length-1];f&&(h[f]=t,n.emitChange(i))}on(e,t){let s=e.trim();if(!s)return;let r=this.listeners.get(s)??new Set;r.add(t),this.listeners.set(s,r)}off(e,t){let s=e.trim(),r=this.listeners.get(s);r&&(r.delete(t),r.size===0&&this.listeners.delete(s))}onAny(e){this.anyListeners.add(e)}offAny(e){this.anyListeners.delete(e)}emitChange(e){let t=e.trim();if(!t)return;this.listeners.get(t)?.forEach(r=>r());let s=t.split(".")[0];s&&s!==t&&this.listeners.get(s)?.forEach(r=>r()),this.anyListeners.forEach(r=>r())}resolveScope(e){let t=this,s=e;for(;s.startsWith("parent.");)t=t?.parent,s=s.slice(7);for(s.startsWith("root.")&&(t=t?.root,s=s.slice(5));s.startsWith("self.");)t=t??this,s=s.slice(5);return{targetScope:t,targetPath:s}}getLocalPathValue(e,t){let s=t.split("."),r=s[0];if(!r)return;let i=e.data.get(r);for(let n=1;n<s.length;n+=1){if(i==null)return;let a=s[n];if(!a)return;i=i[a]}return i}findNearestScopeWithKey(e,t){let s=t.split(".")[0];if(!s)return;let r=e;for(;r;){if(r.data.has(s))return r;r=r.parent}}};function Ee(p){return p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement?p.value:p.textContent??""}function ke(p,e){if(p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement){p.value=e,p.setAttribute("value",e);return}if(p instanceof HTMLSelectElement){p.value=e;return}p instanceof HTMLElement&&p.querySelector("*")||(p.textContent=e)}function oe(p,e,t){let s=e.trim();if(!s)return;let r=Ee(p);t.set(s,r)}function ce(p,e,t){let s=e.trim();if(!s)return;let r=t.get(s);r!=null&&ke(p,String(r))}function ge(p,e){let t=p.trim();return t?!!e.get(t):!1}function le(p,e,t){p.style.display=ge(e,t)?"":"none"}function he(p,e,t){p.style.display=ge(e,t)?"":"none"}function we(p){return p.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"")}function W(p,e,t,s){let r=e.trim();if(!r)return;let i=t.get(r),n=i==null?"":String(i);p.innerHTML=s?n:we(n)}async function ye(p,e,t,s){if(!globalThis.fetch)throw new Error("fetch is not available");let r=await globalThis.fetch(e.url);if(!r||!r.ok)return;let i=await r.text(),n=be(p,e.targetSelector);if(!n){p.dispatchEvent(new CustomEvent("vsn:targetError",{detail:{selector:e.targetSelector}}));return}if(e.swap==="outer"){let a=document.createElement("div");W(a,"__html",{get:()=>i},e.trusted);let o=a.firstElementChild;o&&n.parentNode&&(n.parentNode.replaceChild(o,n),s?.(o));return}W(n,"__html",{get:()=>i},e.trusted),s?.(n)}function be(p,e){return e?p.ownerDocument.querySelector(e):p}function P(p,e){let t;return(...s)=>{t&&clearTimeout(t),t=setTimeout(()=>{t=void 0,p(...s)},e)}}var q=class p{static activeEngines=new WeakMap;scopes=new WeakMap;bindBindings=new WeakMap;ifBindings=new WeakMap;showBindings=new WeakMap;htmlBindings=new WeakMap;getBindings=new WeakMap;eachBindings=new WeakMap;lifecycleBindings=new WeakMap;behaviorRegistry=[];behaviorBindings=new WeakMap;behaviorListeners=new WeakMap;behaviorId=0;codeCache=new Map;behaviorCache=new Map;observer;observerRoot;attributeHandlers=[];globals={};importantFlags=new WeakMap;inlineDeclarations=new WeakMap;flagHandlers=new Map;pendingAdded=new Set;pendingRemoved=new Set;pendingUpdated=new Set;observerFlush;ignoredAdded=new WeakMap;diagnostics;logger;pendingUses=[];constructor(e={}){this.diagnostics=e.diagnostics??!1,this.logger=e.logger??console,this.registerGlobal("console",console),this.registerGlobal("list",{async map(t,s){if(!Array.isArray(t)||typeof s!="function")return[];let r=[];for(let i=0;i<t.length;i+=1)r.push(await s(t[i],i));return r},async filter(t,s){if(!Array.isArray(t)||typeof s!="function")return[];let r=[];for(let i=0;i<t.length;i+=1)await s(t[i],i)&&r.push(t[i]);return r},async reduce(t,s,r){if(!Array.isArray(t)||typeof s!="function")return r;let i=arguments.length>2,n=i?r:t[0],a=i?0:1;for(let o=a;o<t.length;o+=1)n=await s(n,t[o],o);return n}}),this.registerDefaultAttributeHandlers()}async mount(e){let t=e.ownerDocument,s=p.activeEngines.get(t);s&&s!==this&&s.disconnectObserver(),p.activeEngines.set(t,this);let r=[e,...Array.from(e.querySelectorAll("*"))];for(let i of r){if(!this.hasVsnAttributes(i))continue;let n=this.findParentScope(i);this.getScope(i,n),this.attachAttributes(i),this.runConstruct(i)}await this.applyBehaviors(e),this.attachObserver(e)}unmount(e){this.runDestruct(e),this.disconnectObserver()}registerBehaviors(e){let t=new A(e,{customFlags:new Set(this.flagHandlers.keys())}).parseProgram();for(let s of t.uses){if(s.flags?.wait){this.pendingUses.push(this.waitForUseGlobal(s));continue}let r=this.resolveGlobalPath(s.name);if(r===void 0){console.warn(`vsn: global '${s.name}' not found`);continue}this.registerGlobal(s.alias,r)}for(let s of t.behaviors)this.collectBehavior(s)}registerGlobal(e,t){this.globals[e]=t}registerGlobals(e){Object.assign(this.globals,e)}registerFlag(e,t={}){if(new Set(["important","trusted","debounce"]).has(e))throw new Error(`Flag '${e}' is reserved`);this.flagHandlers.set(e,t)}getRegistryStats(){return{behaviorCount:this.behaviorRegistry.length,behaviorCacheSize:this.behaviorCache.size}}registerAttributeHandler(e){this.attributeHandlers.push(e)}resolveGlobalPath(e){let t=e.split("."),s=t[0];if(!s)return;let r=globalThis[s];for(let i=1;i<t.length;i+=1){let n=t[i];if(!n)return;r=r?.[n]}return r}async waitForUses(){for(;this.pendingUses.length>0;){let e=this.pendingUses;this.pendingUses=[],await Promise.all(e)}}waitForUseGlobal(e){let t=e.flagArgs?.wait??{},s=t.timeoutMs??1e4,r=t.intervalMs??100,i=1e3,n=this.resolveGlobalPath(e.name);return n!==void 0?(this.registerGlobal(e.alias,n),Promise.resolve()):s<=0?(this.emitUseError(e.name,new Error(`vsn: global '${e.name}' not found`)),Promise.resolve()):new Promise(a=>{let o=0,c=r,h=()=>{let f=this.resolveGlobalPath(e.name);if(f!==void 0){this.registerGlobal(e.alias,f),a();return}if(o>=s){this.emitUseError(e.name,new Error(`vsn: global '${e.name}' not found`)),a();return}let d=Math.min(c,s-o);setTimeout(()=>{o+=d,c=Math.min(c*2,i),h()},d)};h()})}getScope(e,t){let s=this.scopes.get(e);if(s)return s;let r=new $(t??this.findParentScope(e));return this.scopes.set(e,r),r}evaluate(e){let t=this.getScope(e),s=this.bindBindings.get(e);s&&(s.direction==="from"||s.direction==="both")&&ce(e,s.expr,t);let r=this.ifBindings.get(e);r&&e instanceof HTMLElement&&le(e,r,t);let i=this.showBindings.get(e);i&&e instanceof HTMLElement&&he(e,i,t);let n=this.htmlBindings.get(e);n&&e instanceof HTMLElement&&(W(e,n.expr,t,n.trusted),n.trusted&&this.handleTrustedHtml(e))}attachObserver(e){this.observer||(this.observerRoot=e,this.observerFlush=P(()=>this.flushObserverQueue(),10),this.observer=new MutationObserver(t=>{for(let s of t){s.type==="attributes"&&s.target instanceof Element&&this.pendingUpdated.add(s.target);for(let r of Array.from(s.addedNodes))if(r&&r.nodeType===1){let i=r;if(this.ignoredAdded.has(i)){this.ignoredAdded.delete(i);continue}this.pendingAdded.add(i)}for(let r of Array.from(s.removedNodes))r&&r.nodeType===1&&this.pendingRemoved.add(r)}this.observerFlush?.()}),this.observer.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class"]}))}disconnectObserver(){this.observer?.disconnect(),this.observer=void 0,this.observerRoot=void 0,this.pendingAdded.clear(),this.pendingRemoved.clear(),this.pendingUpdated.clear()}flushObserverQueue(){let e=Array.from(this.pendingRemoved);this.pendingRemoved.clear();for(let r of e)this.handleRemovedNode(r);let t=Array.from(this.pendingUpdated);this.pendingUpdated.clear();for(let r of t)this.handleUpdatedNode(r);let s=Array.from(this.pendingAdded);this.pendingAdded.clear();for(let r of s)this.handleAddedNode(r)}handleRemovedNode(e){this.lifecycleBindings.has(e)&&this.runDestruct(e),this.behaviorBindings.has(e)&&this.runBehaviorDestruct(e);for(let t of Array.from(e.querySelectorAll("*")))this.lifecycleBindings.has(t)&&this.runDestruct(t),this.behaviorBindings.has(t)&&this.runBehaviorDestruct(t)}handleAddedNode(e){let t=[e,...Array.from(e.querySelectorAll("*"))];for(let s of t){if(!this.hasVsnAttributes(s))continue;let r=this.findParentScope(s);this.getScope(s,r),this.attachAttributes(s),this.runConstruct(s)}this.applyBehaviors(e)}handleUpdatedNode(e){let t=[e,...Array.from(e.querySelectorAll("*"))];for(let s of t)this.reapplyBehaviorsForElement(s)}async applyBehaviors(e){if(await this.waitForUses(),this.behaviorRegistry.length===0)return;let t=[e,...Array.from(e.querySelectorAll("*"))];for(let s of t)await this.reapplyBehaviorsForElement(s)}async reapplyBehaviorsForElement(e){if(this.behaviorRegistry.length===0)return;let t=this.behaviorBindings.get(e)??new Set,s=this.getScope(e),r=this.behaviorRegistry.filter(n=>e.matches(n.selector)).sort((n,a)=>n.specificity!==a.specificity?n.specificity-a.specificity:n.order-a.order);for(let n of r)t.has(n.id)||await this.applyBehaviorForElement(n,e,s,t);let i=new Set(r.map(n=>n.id));for(let n of this.behaviorRegistry)t.has(n.id)&&!i.has(n.id)&&this.unbindBehaviorForElement(n,e,s,t);this.behaviorBindings.set(e,t)}async applyBehaviorForElement(e,t,s,r){r.add(e.id);let i=this.getBehaviorRootScope(t,e);this.applyBehaviorFunctions(t,s,e.functions,i),await this.applyBehaviorDeclarations(t,s,e.declarations,i),e.construct&&await this.safeExecuteBlock(e.construct,s,t,i);for(let n of e.onBlocks)this.attachBehaviorOnHandler(t,n.event,n.body,n.modifiers,n.args,e.id,i);this.logDiagnostic("bind",t,e)}unbindBehaviorForElement(e,t,s,r){if(r.delete(e.id),e.destruct){let a=this.getBehaviorRootScope(t,e);this.safeExecuteBlock(e.destruct,s,t,a)}let i=this.behaviorListeners.get(t),n=i?.get(e.id);if(n){for(let a of n)a.target.removeEventListener(a.event,a.handler,a.options);i?.delete(e.id)}this.logDiagnostic("unbind",t,e)}runBehaviorDestruct(e){let t=this.behaviorBindings.get(e);if(!t)return;let s=this.getScope(e);for(let r of this.behaviorRegistry){if(!t.has(r.id)||!r.destruct)continue;let i=this.getBehaviorRootScope(e,r);this.safeExecuteBlock(r.destruct,s,e,i)}}attachAttributes(e){let t=this.getScope(e);for(let s of e.getAttributeNames()){if(!s.startsWith("vsn-"))continue;let r=e.getAttribute(s)??"";for(let i of this.attributeHandlers){if(!i.match(s))continue;if(i.handle(e,s,r,t)!==!1)break}}}setLifecycle(e,t){let s=this.lifecycleBindings.get(e)??{};this.lifecycleBindings.set(e,{...s,...t})}runConstruct(e){let t=this.lifecycleBindings.get(e);if(!t?.construct)return;let s=this.getScope(e);this.safeExecute(t.construct,s,e)}runDestruct(e){let t=this.lifecycleBindings.get(e);if(!t?.destruct)return;let s=this.getScope(e);this.safeExecute(t.destruct,s,e)}parseEachExpression(e){let[t,s]=e.split(/\s+as\s+/);if(!t||!s)return null;let r=t.trim(),i=s.split(",").map(o=>o.trim()).filter(Boolean);if(!r||i.length===0)return null;let n=i[0]??"",a=i[1];return{listExpr:r,itemName:n,...a?{indexName:a}:{}}}renderEach(e){let t=this.eachBindings.get(e);if(!t||!(e instanceof HTMLTemplateElement))return;let s=e.parentElement;if(!s)return;for(let a of t.rendered)this.handleRemovedNode(a),a.parentNode&&a.parentNode.removeChild(a);t.rendered=[];let r=this.getScope(e),i=r.get(t.listExpr);if(!Array.isArray(i))return;let n=[];i.forEach((a,o)=>{let c=e.content.cloneNode(!0),h=Array.from(c.children),f=new $(r);f.setPath(`self.${t.itemName}`,a),t.indexName&&f.setPath(`self.${t.indexName}`,o);for(let d of h)this.getScope(d,f);s.insertBefore(c,e);for(let d of h){this.ignoredAdded.set(d,!0),n.push(d),this.handleAddedNode(d),this.evaluate(d);for(let g of Array.from(d.querySelectorAll("*")))this.evaluate(g)}}),t.rendered=n}attachBindInputHandler(e,t){if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement))return;let s=()=>{let r=this.getScope(e);oe(e,t,r)};e.addEventListener("input",s),e.addEventListener("change",s)}parseBindDirection(e){return e.includes(":from")?"from":e.includes(":to")?"to":"both"}hasVsnAttributes(e){return e.getAttributeNames().some(t=>t.startsWith("vsn-"))}markInlineDeclaration(e,t){let s=this.inlineDeclarations.get(e)??new Set;s.add(t),this.inlineDeclarations.set(e,s)}isInlineDeclaration(e,t){let s=this.inlineDeclarations.get(e);return s?s.has(t):!1}findParentScope(e){let t=e.parentElement;for(;t;){let s=this.scopes.get(t);if(s)return s;t=t.parentElement}}watch(e,t,s){let r=t.trim();if(!r)return;let i=r.split(".")[0];if(!i)return;let n=e;for(;n&&!n.hasKey(i);)n=n.parent;if(n){n.on(r,s);return}let a=e;for(;a;)a.on(r,s),a=a.parent}watchWithDebounce(e,t,s,r){r?this.watch(e,t,P(s,r)):this.watch(e,t,s)}watchAllScopes(e,t,s){let r=s?P(t,s):t,i=e;for(;i;)i.onAny(r),i=i.parent}parseOnAttribute(e,t){if(!e.startsWith("vsn-on:"))return null;let s=e.slice(7),[r,...i]=s.split("!");if(!r)return null;let n=this.parseEventDescriptor(r);if(!n.event)return null;let a,o=[];for(let f of i){if(f.startsWith("debounce")){let d=f.match(/debounce\((\d+)\)/);a=d?Number(d[1]):200;continue}o.push(f)}let c=[...o,...n.modifiers];return{event:n.event,code:t,...a!==void 0?{debounceMs:a}:{},...c.length>0?{modifiers:c}:{},...n.keyModifiers.length>0?{keyModifiers:n.keyModifiers}:{}}}parseEventDescriptor(e){let t=e.split(".").map(a=>a.trim()).filter(Boolean),s=t.shift()??"",r=[],i=[],n=new Set(["outside","self"]);for(let a of t)n.has(a)?r.push(a):i.push(a);return{event:s,keyModifiers:i,modifiers:r}}matchesKeyModifiers(e,t){if(!t||t.length===0)return!0;if(!(e instanceof KeyboardEvent))return!1;let s={shift:e.shiftKey,ctrl:e.ctrlKey,control:e.ctrlKey,alt:e.altKey,meta:e.metaKey},r={esc:"escape",escape:"escape",enter:"enter",tab:"tab",space:"space",spacebar:"space",up:"arrowup",down:"arrowdown",left:"arrowleft",right:"arrowright",arrowup:"arrowup",arrowdown:"arrowdown",arrowleft:"arrowleft",arrowright:"arrowright",delete:"delete",backspace:"backspace"},i=e.key?.toLowerCase()??"";i===" "&&(i="space");for(let n of t){let a=n.toLowerCase();if(a in s){if(!s[a])return!1;continue}let o=r[a]??a;if(i!==o)return!1}return!0}matchesTargetModifiers(e,t,s){if(!s||s.length===0)return!0;let r=t?.target;return!r||!(r instanceof Node)?!s.includes("self")&&!s.includes("outside"):!(s.includes("self")&&r!==e||s.includes("outside")&&e.contains(r))}describeElement(e){let t=e.tagName.toLowerCase(),s=e.id?`#${e.id}`:"",r=e.classList.length>0?`.${Array.from(e.classList).join(".")}`:"";return`${t}${s}${r}`}logDiagnostic(e,t,s){!this.diagnostics||!this.logger.info||this.logger.info(`vsn:${e}`,{element:this.describeElement(t),selector:s.selector,behaviorId:s.id})}emitError(e,t){let s=this.describeElement(e);this.logger.warn?.("vsn:error",{error:t,selector:s}),e.dispatchEvent(new CustomEvent("vsn:error",{detail:{error:t,selector:s},bubbles:!0}))}emitUseError(e,t){let s=`use:${e}`;this.logger.warn?.("vsn:error",{error:t,selector:s});let r=globalThis.document;r&&typeof r.dispatchEvent=="function"&&r.dispatchEvent(new CustomEvent("vsn:error",{detail:{error:t,selector:s},bubbles:!0}))}attachOnHandler(e,t){let s=this.getListenerOptions(t.modifiers),r=t.modifiers?.includes("outside")?e.ownerDocument:e,i,n=async a=>{if(!e.isConnected){r.removeEventListener(t.event,i,s);return}if(!this.matchesKeyModifiers(a,t.keyModifiers)||!this.matchesTargetModifiers(e,a,t.modifiers))return;this.applyEventModifiers(a,t.modifiers);let o=this.getScope(e);try{await this.execute(t.code,o,e),this.evaluate(e)}catch(c){this.emitError(e,c)}};i=t.debounceMs?P(n,t.debounceMs):n,r.addEventListener(t.event,i,s)}attachBehaviorOnHandler(e,t,s,r,i,n,a){let o=this.parseEventDescriptor(t),c=r?[...r,...o.modifiers]:o.modifiers.length>0?[...o.modifiers]:void 0,h=c?.includes("outside")?e.ownerDocument:e,f=async z=>{if(!this.matchesKeyModifiers(z,o.keyModifiers)||!this.matchesTargetModifiers(e,z,c))return;this.applyEventModifiers(z,c);let V=this.getScope(e),fe=new Map;if(i&&i.length>0){let E=i[0];E&&(fe.set(E,V.getPath(E)),V.setPath(E,z))}let de=!1;try{await this.executeBlock(s,V,e,a)}catch(E){de=!0,this.emitError(e,E)}finally{for(let[E,ve]of fe.entries())V.setPath(E,ve)}de||this.evaluate(e)},d=this.getListenerOptions(c);h.addEventListener(o.event,f,d);let g=this.behaviorListeners.get(e)??new Map,ue=g.get(n)??[];ue.push({target:h,event:o.event,handler:f,options:d}),g.set(n,ue),this.behaviorListeners.set(e,g)}attachGetHandler(e,t=!1){let s=async()=>{let r=this.getBindings.get(e);if(r)try{await ye(e,r,this.getScope(e),i=>{r.trusted&&this.handleTrustedHtml(i)})}catch(i){console.warn("vsn:getError",i),e.dispatchEvent(new CustomEvent("vsn:getError",{detail:{error:i},bubbles:!0}))}};e.addEventListener("click",r=>{r.target===e&&s()}),t&&Promise.resolve().then(s)}applyEventModifiers(e,t){if(!(!e||!t||t.length===0))for(let s of t)s==="prevent"?e.preventDefault():s==="stop"&&e.stopPropagation()}getListenerOptions(e){if(!e||e.length===0)return;let t={};return e.includes("once")&&(t.once=!0),e.includes("passive")&&(t.passive=!0),e.includes("capture")&&(t.capture=!0),Object.keys(t).length>0?t:void 0}async execute(e,t,s,r){let i=this.codeCache.get(e);i||(i=A.parseInline(e),this.codeCache.set(e,i));let n={scope:t,rootScope:r,globals:this.globals,...s?{element:s}:{}};await i.evaluate(n)}async executeBlock(e,t,s,r){let i={scope:t,rootScope:r,globals:this.globals,...s?{element:s}:{}};await e.evaluate(i)}async safeExecute(e,t,s,r){try{await this.execute(e,t,s,r)}catch(i){s&&this.emitError(s,i)}}async safeExecuteBlock(e,t,s,r){try{await this.executeBlock(e,t,s,r)}catch(i){s&&this.emitError(s,i)}}collectBehavior(e,t,s){let r=t?`${t} ${e.selector.selectorText}`:e.selector.selectorText,i=s??t??e.selector.selectorText,n=this.getCachedBehavior(e);this.behaviorRegistry.push({id:this.behaviorId+=1,selector:r,rootSelector:i,specificity:this.computeSpecificity(r),order:this.behaviorRegistry.length,...n}),this.collectNestedBehaviors(e.body,r,i)}collectNestedBehaviors(e,t,s){for(let r of e.statements){if(r instanceof C){this.collectBehavior(r,t,s);continue}if(r instanceof b){this.collectNestedBehaviors(r.body,t,s);continue}r instanceof y&&this.collectNestedBehaviors(r,t,s)}}computeSpecificity(e){let t=e.match(/#[\w-]+/g)?.length??0,s=e.match(/\.[\w-]+/g)?.length??0,r=e.match(/\[[^\]]+\]/g)?.length??0,i=e.match(/:[\w-]+/g)?.length??0,n=e.match(/(^|[\s>+~])([a-zA-Z][\w-]*)/g)?.length??0;return t*100+(s+r+i)*10+n}getBehaviorRootScope(e,t){let s=e.closest(t.rootSelector)??e;return this.getScope(s)}getImportantKey(e){if(e.target instanceof m)return`state:${e.target.name}`;if(e.target instanceof x)return`${e.target.kind}:${e.target.name}`}isImportant(e,t){let s=this.importantFlags.get(e);return s?s.has(t):!1}markImportant(e,t){let s=this.importantFlags.get(e)??new Set;s.add(t),this.importantFlags.set(e,s)}extractLifecycle(e){let t,s;for(let r of e.statements)r instanceof y&&(r.type==="Construct"?t=r:r.type==="Destruct"&&(s=r));return{...t?{construct:t}:{},...s?{destruct:s}:{}}}extractOnBlocks(e){let t=[];for(let s of e.statements)s instanceof b&&t.push({event:s.eventName,body:s.body,modifiers:s.modifiers,args:s.args});return t}extractDeclarations(e){let t=[];for(let s of e.statements)s instanceof F&&t.push(s);return t}extractFunctionDeclarations(e){let t=[];for(let s of e.statements){if(s instanceof L){t.push({name:s.name,params:s.params,body:s.body});continue}s instanceof B&&s.target instanceof m&&s.value instanceof S&&t.push({name:s.target.name,params:s.value.params,body:s.value.body})}return t}getCachedBehavior(e){let t=this.hashBehavior(e),s=this.behaviorCache.get(t);if(s)return s;let r=this.extractLifecycle(e.body),i={onBlocks:this.extractOnBlocks(e.body),declarations:this.extractDeclarations(e.body),functions:this.extractFunctionDeclarations(e.body),...r};return this.behaviorCache.set(t,i),i}hashBehavior(e){let t=this.normalizeNode(e),s=JSON.stringify(t);return this.hashString(s)}normalizeNode(e){if(!e||typeof e!="object")return e;let t=e.type??"Unknown";return t==="Behavior"?{type:t,selector:e.selector?.selectorText??"",body:this.normalizeNode(e.body)}:t==="Selector"?{type:t,selectorText:e.selectorText??""}:t==="Block"||t==="Construct"||t==="Destruct"?{type:t,statements:Array.isArray(e.statements)?e.statements.map(s=>this.normalizeNode(s)):[]}:t==="OnBlock"?{type:t,eventName:e.eventName??"",args:Array.isArray(e.args)?e.args:[],body:this.normalizeNode(e.body)}:t==="Declaration"?{type:t,target:this.normalizeNode(e.target),operator:e.operator??"",value:this.normalizeNode(e.value),flags:e.flags??{},flagArgs:e.flagArgs??{}}:t==="Assignment"?{type:t,target:this.normalizeNode(e.target),value:this.normalizeNode(e.value)}:t==="StateBlock"?{type:t,entries:Array.isArray(e.entries)?e.entries.map(s=>this.normalizeNode(s)):[]}:t==="StateEntry"?{type:t,name:e.name??"",value:this.normalizeNode(e.value),important:!!e.important}:t==="FunctionDeclaration"?{type:t,name:e.name??"",params:Array.isArray(e.params)?e.params.map(s=>({name:s?.name??"",rest:!!s?.rest,defaultValue:this.normalizeNode(s?.defaultValue??null)})):[],body:this.normalizeNode(e.body),isAsync:!!e.isAsync}:t==="FunctionExpression"?{type:t,params:Array.isArray(e.params)?e.params.map(s=>({name:s?.name??"",rest:!!s?.rest,defaultValue:this.normalizeNode(s?.defaultValue??null)})):[],body:this.normalizeNode(e.body),isAsync:!!e.isAsync}:t==="Return"?{type:t,value:this.normalizeNode(e.value??null)}:t==="If"?{type:t,test:this.normalizeNode(e.test),consequent:this.normalizeNode(e.consequent),alternate:this.normalizeNode(e.alternate??null)}:t==="While"?{type:t,test:this.normalizeNode(e.test),body:this.normalizeNode(e.body)}:t==="For"?{type:t,init:this.normalizeNode(e.init??null),test:this.normalizeNode(e.test??null),update:this.normalizeNode(e.update??null),body:this.normalizeNode(e.body)}:t==="Try"?{type:t,errorName:e.errorName??"",body:this.normalizeNode(e.body),handler:this.normalizeNode(e.handler)}:t==="Identifier"?{type:t,name:e.name??""}:t==="Literal"?{type:t,value:e.value}:t==="TemplateExpression"?{type:t,parts:Array.isArray(e.parts)?e.parts.map(s=>this.normalizeNode(s)):[]}:t==="UnaryExpression"?{type:t,operator:e.operator??"",argument:this.normalizeNode(e.argument)}:t==="BinaryExpression"?{type:t,operator:e.operator??"",left:this.normalizeNode(e.left),right:this.normalizeNode(e.right)}:t==="TernaryExpression"?{type:t,test:this.normalizeNode(e.test),consequent:this.normalizeNode(e.consequent),alternate:this.normalizeNode(e.alternate)}:t==="MemberExpression"?{type:t,target:this.normalizeNode(e.target),property:e.property??"",optional:!!e.optional}:t==="CallExpression"?{type:t,callee:this.normalizeNode(e.callee),args:Array.isArray(e.args)?e.args.map(s=>this.normalizeNode(s)):[]}:t==="AwaitExpression"?{type:t,argument:this.normalizeNode(e.argument)}:t==="Directive"?{type:t,kind:e.kind??"",name:e.name??""}:t==="Query"?{type:t,direction:e.direction??"",selector:e.selector??""}:t==="ArrayExpression"?{type:t,elements:Array.isArray(e.elements)?e.elements.map(s=>this.normalizeNode(s)):[]}:t==="ObjectExpression"?{type:t,entries:Array.isArray(e.entries)?e.entries.map(s=>({key:s?.key??"",computed:!!s?.computed,keyExpr:s?.keyExpr?this.normalizeNode(s.keyExpr):null,value:this.normalizeNode(s?.value)})):[]}:t==="IndexExpression"?{type:t,target:this.normalizeNode(e.target),index:this.normalizeNode(e.index)}:{type:t}}hashString(e){let t=5381;for(let s=0;s<e.length;s+=1)t=(t<<5)+t+e.charCodeAt(s),t|=0;return(t>>>0).toString(16)}applyBehaviorFunctions(e,t,s,r){for(let i of s)this.applyBehaviorFunction(e,t,i,r)}applyBehaviorFunction(e,t,s,r){let i=t.getPath(s.name);if(i!==void 0&&typeof i!="function")throw new Error(`Cannot override non-function '${s.name}' with a function`);let n=async(...a)=>{let o=t.createChild?t.createChild():t,c={scope:o,rootScope:r??o,globals:this.globals,element:e,returnValue:void 0,returning:!1},h=new Map;return await this.applyFunctionParams(o,s.params,h,c,a),await s.body.evaluate(c),o===t&&this.restoreFunctionParams(o,s.params,h),c.returnValue};t.setPath(s.name,n)}async applyFunctionParams(e,t,s,r,i){let n=0;for(let a of t){let o=a.name;if(!o)continue;if(s.set(o,e.getPath(o)),a.rest){e.setPath(`self.${o}`,i.slice(n)),n=i.length;continue}let c=i[n];c===void 0&&a.defaultValue&&(c=await a.defaultValue.evaluate(r)),e.setPath(`self.${o}`,c),n+=1}}restoreFunctionParams(e,t,s){for(let r of t){let i=r.name;i&&e.setPath(i,s.get(i))}}async applyBehaviorDeclarations(e,t,s,r){for(let i of s)await this.applyBehaviorDeclaration(e,t,i,r)}async applyBehaviorDeclaration(e,t,s,r){let i={scope:t,rootScope:r,element:e},n=s.operator,a=s.flags.debounce?s.flagArgs.debounce??200:void 0,o=this.getImportantKey(s);if(!s.flags.important&&o&&this.isImportant(e,o)||o&&this.isInlineDeclaration(e,o))return;if(this.applyCustomFlags(e,t,s),s.target instanceof m){let d=await s.value.evaluate(i);t.setPath(s.target.name,d),s.flags.important&&o&&this.markImportant(e,o);return}if(!(s.target instanceof x))return;let c=s.target,h=s.value instanceof m?s.value.name:void 0;if(n===":>"){h&&this.applyDirectiveToScope(e,c,h,t,a,r),s.flags.important&&o&&this.markImportant(e,o);return}if(n===":="&&h&&this.applyDirectiveToScope(e,c,h,t,a,r),!h){let d=await s.value.evaluate(i);this.setDirectiveValue(e,c,d,s.flags.trusted),(n===":<"||n===":=")&&this.applyDirectiveFromExpression(e,c,s.value,t,s.flags.trusted,a,r),s.flags.important&&o&&this.markImportant(e,o);return}let f=n===":<"||n===":=";this.applyDirectiveFromScope(e,c,h,t,s.flags.trusted,a,f,r),s.flags.important&&o&&this.markImportant(e,o)}applyCustomFlags(e,t,s){if(this.flagHandlers.size!==0)for(let[r,i]of this.flagHandlers)s.flags[r]&&i.onApply?.({name:r,args:s.flagArgs[r],element:e,scope:t,declaration:s})}applyDirectiveFromScope(e,t,s,r,i,n,a=!0,o){if(t.kind==="attr"&&t.name==="html"&&e instanceof HTMLElement){let h=()=>{let f=s.startsWith("root.")&&o,d=f?o:r,g=f?`self.${s.slice(5)}`:s;W(e,g,d,!!i)};if(h(),i&&this.handleTrustedHtml(e),a){let f=s.startsWith("root.")&&o,d=f?o:r,g=f?s.slice(5):s;this.watchWithDebounce(d,g,h,n)}return}let c=()=>{let h=s.startsWith("root.")&&o,f=h?o:r,d=h?`self.${s.slice(5)}`:s,g=f.get(d);g!=null&&this.setDirectiveValue(e,t,g,i)};if(c(),a){let h=s.startsWith("root.")&&o,f=h?o:r,d=h?s.slice(5):s;this.watchWithDebounce(f,d,c,n)}}applyDirectiveFromExpression(e,t,s,r,i,n,a){let o=async()=>{let c={scope:r,rootScope:a,element:e},h=await s.evaluate(c);this.setDirectiveValue(e,t,h,i)};o(),this.watchAllScopes(r,()=>{o()},n)}applyDirectiveToScope(e,t,s,r,i,n){let a=s.startsWith("root.")&&n,o=a?n:r,c=a?`self.${s.slice(5)}`:s;if(t.kind==="attr"&&t.name==="value"){this.applyValueBindingToScope(e,c,i,o);return}if(t.kind==="attr"&&t.name==="checked"){this.applyCheckedBindingToScope(e,c,i,o);return}let h=this.getDirectiveValue(e,t);h!=null&&o.set(c,h)}applyCheckedBindingToScope(e,t,s,r){if(!(e instanceof HTMLInputElement))return;let i=()=>{(r??this.getScope(e)).set(t,e.checked)},n=s?P(i,s):i;n(),e.addEventListener("change",n),e.addEventListener("input",n)}applyValueBindingToScope(e,t,s,r){if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement))return;let i=()=>{let a=r??this.getScope(e);oe(e,t,a)},n=s?P(i,s):i;n(),e.addEventListener("input",n),e.addEventListener("change",n)}setDirectiveValue(e,t,s,r){if(t.kind==="attr"&&t.name==="html"&&e instanceof HTMLElement){let i=s==null?"":String(s);e.innerHTML=r?i:i.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),r&&this.handleTrustedHtml(e);return}if(t.kind==="attr"){if(t.name==="value"){if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){e.value=s==null?"":String(s),e.setAttribute("value",e.value);return}if(e instanceof HTMLSelectElement){e.value=s==null?"":String(s);return}}if(t.name==="checked"&&e instanceof HTMLInputElement){let i=s===!0||s==="true"||s===1||s==="1";e.checked=i,i?e.setAttribute("checked",""):e.removeAttribute("checked");return}e.setAttribute(t.name,s==null?"":String(s));return}t.kind==="style"&&e instanceof HTMLElement&&e.style.setProperty(t.name,s==null?"":String(s))}getDirectiveValue(e,t){if(t.kind==="attr")return t.name==="value"&&(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)?e.value:t.name==="checked"&&e instanceof HTMLInputElement?e.checked:e.getAttribute(t.name)??void 0;if(t.kind==="style"&&e instanceof HTMLElement)return e.style.getPropertyValue(t.name)??void 0}handleTrustedHtml(e){let t=Array.from(e.querySelectorAll('script[type="text/vsn"]'));if(t.length===0)return;let s=t.map(r=>r.textContent??"").join(`
|
|
7
|
-
`);
|
|
8
|
-
`);
|
|
1
|
+
var be=(u=>(u.Whitespace="Whitespace",u.Identifier="Identifier",u.Number="Number",u.String="String",u.Template="Template",u.Boolean="Boolean",u.Null="Null",u.Behavior="Behavior",u.Use="Use",u.State="State",u.On="On",u.Construct="Construct",u.Destruct="Destruct",u.Return="Return",u.If="If",u.Else="Else",u.For="For",u.While="While",u.Try="Try",u.Catch="Catch",u.Assert="Assert",u.Break="Break",u.Continue="Continue",u.LBrace="LBrace",u.RBrace="RBrace",u.LParen="LParen",u.RParen="RParen",u.LBracket="LBracket",u.RBracket="RBracket",u.Colon="Colon",u.Semicolon="Semicolon",u.Comma="Comma",u.Ellipsis="Ellipsis",u.Dot="Dot",u.Hash="Hash",u.Greater="Greater",u.Less="Less",u.Plus="Plus",u.PlusPlus="PlusPlus",u.Minus="Minus",u.MinusMinus="MinusMinus",u.Tilde="Tilde",u.Star="Star",u.Slash="Slash",u.Percent="Percent",u.Equals="Equals",u.Arrow="Arrow",u.DoubleEquals="DoubleEquals",u.TripleEquals="TripleEquals",u.NotEquals="NotEquals",u.StrictNotEquals="StrictNotEquals",u.LessEqual="LessEqual",u.GreaterEqual="GreaterEqual",u.And="And",u.Or="Or",u.Pipe="Pipe",u.NullishCoalesce="NullishCoalesce",u.OptionalChain="OptionalChain",u.Bang="Bang",u.At="At",u.Dollar="Dollar",u.Question="Question",u))(be||{});var Se={behavior:"Behavior",use:"Use",state:"State",on:"On",construct:"Construct",destruct:"Destruct",return:"Return",if:"If",else:"Else",for:"For",while:"While",try:"Try",catch:"Catch",assert:"Assert",break:"Break",continue:"Continue",true:"Boolean",false:"Boolean",null:"Null"},q=class{constructor(t){this.input=t}index=0;line=1;column=1;pendingTokens=[];templateMode=!1;templateExpressionMode=!1;templateBraceDepth=0;tokenize(){let t=[];for(;!this.eof();){if(this.pendingTokens.length>0){let s=this.pendingTokens.shift();if(s){t.push(s),this.trackTemplateBrace(s);continue}}if(this.templateMode){let s=this.readTemplateChunk();t.push(s);continue}let e=this.peek();if(this.isWhitespace(e)){t.push(this.readWhitespace());continue}if(e==="`"){this.next(),this.templateMode=!0;continue}if(e==="/"&&this.peek(1)==="/"){this.readLineComment();continue}if(e==="/"&&this.peek(1)==="*"){this.readBlockComment();continue}if(this.isAlpha(e)||e==="_"){t.push(this.readIdentifier());continue}if(this.isDigit(e)||e==="-"&&this.isDigit(this.peek(1))){t.push(this.readNumber());continue}if(e==='"'||e==="'"){t.push(this.readString());continue}let r=this.readPunctuator();if(r){t.push(r),this.trackTemplateBrace(r);continue}throw new Error(`Unexpected character '${e}' at ${this.line}:${this.column}`)}return t}readWhitespace(){let t=this.position(),e="";for(;!this.eof()&&this.isWhitespace(this.peek());)e+=this.next();return this.token("Whitespace",e,t)}readLineComment(){for(this.next(),this.next();!this.eof()&&this.peek()!==`
|
|
2
|
+
`;)this.next()}readBlockComment(){for(this.next(),this.next();!this.eof();){if(this.peek()==="*"&&this.peek(1)==="/"){this.next(),this.next();return}this.next()}}readIdentifier(){let t=this.position(),e="";for(;!this.eof();){let s=this.peek();if(this.isAlphaNumeric(s)||s==="_"){e+=this.next();continue}if(s==="-"){if(this.peek(1)==="-")break;e+=this.next();continue}break}let r=Se[e];return r?this.token(r,e,t):this.token("Identifier",e,t)}readNumber(){let t=this.position(),e="";for(this.peek()==="-"&&(e+=this.next());!this.eof()&&this.isDigit(this.peek());)e+=this.next();if(this.peek()===".")for(e+=this.next();!this.eof()&&this.isDigit(this.peek());)e+=this.next();return this.token("Number",e,t)}readString(){let t=this.next(),e=this.position(),r="";for(;!this.eof();){let s=this.next();if(s==="\\"){let i=this.next();r+=i;continue}if(s===t)return this.token("String",r,e);r+=s}throw new Error(`Unterminated string at ${e.line}:${e.column}`)}readTemplateChunk(){let t=this.position(),e="";for(;!this.eof();){let r=this.peek();if(r==="`")return this.next(),this.templateMode=!1,this.token("Template",e,t);if(r==="$"&&this.peek(1)==="{"){let s=this.position();this.next();let i=this.position();return this.next(),this.templateMode=!1,this.templateExpressionMode=!0,this.templateBraceDepth=0,this.pendingTokens.push(this.token("Dollar","$",s)),this.pendingTokens.push(this.token("LBrace","{",i)),this.token("Template",e,t)}if(r==="\\"){this.next();let s=this.next();e+=s;continue}e+=this.next()}throw new Error(`Unterminated template literal at ${t.line}:${t.column}`)}readPunctuator(){let t=this.position(),e=this.peek(),r=this.peek(1);if(e==="="&&r==="="&&this.peek(2)==="=")return this.next(),this.next(),this.next(),this.token("TripleEquals","===",t);if(e==="="&&r==="=")return this.next(),this.next(),this.token("DoubleEquals","==",t);if(e==="="&&r===">")return this.next(),this.next(),this.token("Arrow","=>",t);if(e==="!"&&r==="="&&this.peek(2)==="=")return this.next(),this.next(),this.next(),this.token("StrictNotEquals","!==",t);if(e==="!"&&r==="=")return this.next(),this.next(),this.token("NotEquals","!=",t);if(e==="<"&&r==="=")return this.next(),this.next(),this.token("LessEqual","<=",t);if(e===">"&&r==="=")return this.next(),this.next(),this.token("GreaterEqual",">=",t);if(e==="&"&&r==="&")return this.next(),this.next(),this.token("And","&&",t);if(e==="|"&&r==="|")return this.next(),this.next(),this.token("Or","||",t);if(e==="?"&&r==="?")return this.next(),this.next(),this.token("NullishCoalesce","??",t);if(e==="?"&&r===".")return this.next(),this.next(),this.token("OptionalChain","?.",t);if(e==="|"&&r===">")return this.next(),this.next(),this.token("Pipe","|>",t);if(e==="+"&&r==="+")return this.next(),this.next(),this.token("PlusPlus","++",t);if(e==="-"&&r==="-")return this.next(),this.next(),this.token("MinusMinus","--",t);if(e==="."&&r==="."&&this.peek(2)===".")return this.next(),this.next(),this.next(),this.token("Ellipsis","...",t);let i={"{":"LBrace","}":"RBrace","(":"LParen",")":"RParen","[":"LBracket","]":"RBracket",":":"Colon",";":"Semicolon",",":"Comma",".":"Dot","#":"Hash",">":"Greater","<":"Less","+":"Plus","-":"Minus","~":"Tilde","*":"Star","/":"Slash","%":"Percent","=":"Equals","!":"Bang","@":"At",$:"Dollar","?":"Question"}[e];return i?(this.next(),this.token(i,e,t)):null}trackTemplateBrace(t){this.templateExpressionMode&&(t.type==="LBrace"?this.templateBraceDepth+=1:t.type==="RBrace"&&(this.templateBraceDepth-=1,this.templateBraceDepth<=0&&(this.templateExpressionMode=!1,this.templateMode=!0)))}token(t,e,r){return{type:t,value:e,start:r,end:this.position()}}position(){return{index:this.index,line:this.line,column:this.column}}peek(t=0){return this.input[this.index+t]??""}next(){let t=this.input[this.index++]??"";return t===`
|
|
3
|
+
`?(this.line+=1,this.column=1):this.column+=1,t}eof(){return this.index>=this.input.length}isWhitespace(t){return t===" "||t===" "||t===`
|
|
4
|
+
`||t==="\r"}isAlpha(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"}isDigit(t){return t>="0"&&t<="9"}isAlphaNumeric(t){return this.isAlpha(t)||this.isDigit(t)}};var m=class{constructor(t){this.type=t}async prepare(t){}evaluate(t){}};function G(p){return!!p&&typeof p.then=="function"}function d(p,t){return G(p)?p.then(t):t(p)}function ge(p,t){let e=p.scope;if(!e||!e.createChild)return t.evaluate(p);let r=p.scope;p.scope=e.createChild();try{return t.evaluate(p)}finally{p.scope=r}}var Z=class extends m{constructor(e,r=[]){super("Program");this.behaviors=e;this.uses=r}},J=class extends m{constructor(e,r,s={},i={}){super("Use");this.name=e;this.alias=r;this.flags=s;this.flagArgs=i}},E=class extends m{constructor(e){super("Block");this.statements=e}evaluate(e){let r=0,s=()=>{for(;r<this.statements.length&&!(e.returning||e.breaking||e.continuing);){let i=this.statements[r];if(r+=1,i&&typeof i.evaluate=="function"){let n=i.evaluate(e);if(G(n))return n.then(()=>s())}}};return s()}},Y=class extends m{constructor(e){super("Selector");this.selectorText=e}},M=class extends m{constructor(e,r,s={},i={}){super("Behavior");this.selector=e;this.body=r;this.flags=s;this.flagArgs=i}},C=class extends m{constructor(e,r,s,i={},n={}){super("OnBlock");this.eventName=e;this.args=r;this.body=s;this.flags=i;this.flagArgs=n}},N=class extends m{constructor(e,r,s="=",i=!1){super("Assignment");this.target=e;this.value=r;this.operator=s;this.prefix=i}evaluate(e){if(!e.scope||!e.scope.setPath)return;if(this.operator==="++"||this.operator==="--")return this.applyIncrement(e);let r=this.value.evaluate(e);return d(r,s=>{if(this.operator!=="=")return this.applyCompoundAssignment(e,s);if(this.target instanceof y&&this.target.name.startsWith("root.")&&e.rootScope){let i=this.target.name.slice(5);return e.rootScope.setPath?.(`self.${i}`,s),s}if(this.target instanceof v||this.target instanceof w){let i=this.resolveAssignmentTarget(e);return d(i,n=>n?.scope?.setPath?(n.scope.setPath(n.path,s),s):(this.assignTarget(e,this.target,s),s))}return this.assignTarget(e,this.target,s),s})}applyCompoundAssignment(e,r){if(!e.scope||!e.scope.setPath)return;let s=this.resolveAssignmentTarget(e);return d(s,i=>{if(!i)throw new Error("Compound assignment requires a simple identifier or member path");let{scope:n,path:a}=i,o=n?.getPath?n.getPath(a):void 0,c;return this.operator==="+="?c=o+r:this.operator==="-="?c=o-r:this.operator==="*="?c=o*r:c=o/r,n?.setPath?.(a,c),c})}applyIncrement(e){if(!e.scope||!e.scope.setPath)return;let r=this.resolveAssignmentTarget(e);return d(r,s=>{if(!s)throw new Error("Increment/decrement requires a simple identifier or member path");let{scope:i,path:n}=s,a=i?.getPath?i.getPath(n):void 0,o=typeof a=="number"?a:Number(a),c=this.operator==="++"?1:-1,l=(Number.isNaN(o)?0:o)+c;return i?.setPath?.(n,l),this.prefix?l:o})}resolveAssignmentTarget(e){if(this.target instanceof y){let r=this.target.name.startsWith("root."),s=r?this.target.name.slice(5):this.target.name;return r?e.rootScope?{scope:e.rootScope,path:`self.${s}`}:{scope:e.scope,path:`root.${s}`}:{scope:e.scope,path:s}}if(this.target instanceof v){let r=this.target.getIdentifierPath();if(r){let n=r.path,a=n.startsWith("root."),o=a?n.slice(5):n;return a?e.rootScope?{scope:e.rootScope,path:`self.${o}`}:{scope:e.scope,path:`root.${o}`}:{scope:e.scope,path:o}}let s=this.target,i=this.resolveTargetPath(e,s.target);return d(i,n=>{if(!n)return null;let a=`${n}.${s.property}`,o=a.startsWith("root."),c=o?a.slice(5):a;return o?e.rootScope?{scope:e.rootScope,path:`self.${c}`}:{scope:e.scope,path:`root.${c}`}:{scope:e.scope,path:c}})}if(this.target instanceof w){let r=this.resolveIndexPath(e,this.target);return d(r,s=>{if(!s)return null;let i=s.startsWith("root."),n=i?s.slice(5):s;return i?e.rootScope?{scope:e.rootScope,path:`self.${n}`}:{scope:e.scope,path:`root.${n}`}:{scope:e.scope,path:n}})}return null}resolveIndexPath(e,r){let s=this.resolveTargetPath(e,r.target);return d(s,i=>{if(!i)return null;let n=r.index.evaluate(e);return d(n,a=>a==null?null:`${i}.${a}`)})}resolveTargetPath(e,r){return r instanceof y?r.name:r instanceof v?r.getIdentifierPath()?.path??null:r instanceof w?this.resolveIndexPath(e,r):null}assignTarget(e,r,s){if(!(!e.scope||!e.scope.setPath)){if(r instanceof x){this.assignDirectiveTarget(e,r,s);return}if(r instanceof y){e.scope.setPath(r.name,s);return}if(r instanceof V){let i=Array.isArray(s)?s:[],n=0;for(let a of r.elements){if(a instanceof H){e.scope.setPath(a.target.name,i.slice(n));return}if(a===null){n+=1;continue}this.assignTarget(e,a,i[n]),n+=1}return}if(r instanceof O){let i=s&&typeof s=="object"?s:{},n=new Set;for(let a of r.entries){if("rest"in a){let o={};for(let c of Object.keys(i))n.has(c)||(o[c]=i[c]);e.scope.setPath(a.rest.name,o);continue}n.add(a.key),this.assignTarget(e,a.target,i[a.key])}return}}}assignDirectiveTarget(e,r,s){let i=e.element;if(i){if(r.kind==="attr"){if(r.name==="value"){if(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement){i.value=s==null?"":String(s),i.setAttribute("value",i.value);return}if(i instanceof HTMLSelectElement){i.value=s==null?"":String(s);return}}if(r.name==="checked"&&i instanceof HTMLInputElement){let n=s===!0||s==="true"||s===1||s==="1";i.checked=n,n?i.setAttribute("checked",""):i.removeAttribute("checked");return}if(r.name==="html"&&i instanceof HTMLElement){i.innerHTML=s==null?"":String(s);return}i.setAttribute(r.name,s==null?"":String(s));return}r.kind==="style"&&i instanceof HTMLElement&&i.style.setProperty(r.name,s==null?"":String(s))}}},L=class extends m{constructor(e){super("Return");this.value=e}evaluate(e){if(e.returning)return e.returnValue;let r=this.value?this.value.evaluate(e):void 0;return d(r,s=>(e.returnValue=s,e.returning=!0,e.returnValue))}},X=class extends m{constructor(){super("Break")}evaluate(t){t.breaking=!0}},ee=class extends m{constructor(){super("Continue")}evaluate(t){t.continuing=!0}},ye=class extends Error{constructor(t="Assertion failed"){super(t),this.name="AssertError"}},te=class extends m{constructor(e){super("Assert");this.test=e}evaluate(e){let r=this.test.evaluate(e);return d(r,s=>{if(!s)throw new ye;return s})}},re=class extends m{constructor(e,r,s){super("If");this.test=e;this.consequent=r;this.alternate=s}evaluate(e){let r=this.test.evaluate(e);return d(r,s=>{if(s)return ge(e,this.consequent);if(this.alternate)return ge(e,this.alternate)})}},se=class extends m{constructor(e,r){super("While");this.test=e;this.body=r}evaluate(e){let r=e.scope;e.scope?.createChild&&(e.scope=e.scope.createChild());let s=()=>{let n=this.test.evaluate(e);return d(n,a=>{if(!a||e.returning)return;let o=this.body.evaluate(e);return d(o,()=>{if(e.breaking){e.breaking=!1;return}return e.continuing&&(e.continuing=!1),s()})})},i=s();return G(i)?i.finally(()=>{e.scope=r}):(e.scope=r,i)}},ie=class extends m{constructor(e,r,s,i){super("ForEach");this.target=e;this.iterable=r;this.kind=s;this.body=i}evaluate(e){let r=this.iterable.evaluate(e);return d(r,s=>{let i=this.getEntries(s),n=e.scope,a=e.scope;e.scope?.createChild&&(a=e.scope.createChild());let o=0,c=()=>{if(o>=i.length||e.returning){e.scope=n;return}let l=i[o];o+=1,e.scope=a,e.scope?.setPath?.(this.target.name,l);let h=this.body.evaluate(e);return d(h,()=>{if(e.breaking){e.breaking=!1,e.scope=n;return}return e.continuing&&(e.continuing=!1),e.scope=n,c()})};return c()})}getEntries(e){return e==null?[]:this.kind==="in"?typeof e=="object"?Object.keys(e):[]:typeof e=="string"||typeof e[Symbol.iterator]=="function"?Array.from(e):typeof e=="object"?Object.values(e):[]}},ne=class extends m{constructor(e,r,s,i){super("For");this.init=e;this.test=r;this.update=s;this.body=i}evaluate(e){let r=this.init?this.init.evaluate(e):void 0,s=()=>{let i=e.scope,n=e.scope;e.scope?.createChild&&(n=e.scope.createChild());let a=()=>{let o=this.test?this.test.evaluate(e):!0;return d(o,c=>{if(!c||e.returning){e.scope=i;return}e.scope=n;let l=this.body.evaluate(e);return d(l,()=>{if(e.returning){e.scope=i;return}if(e.breaking){e.breaking=!1,e.scope=i;return}e.scope=i,e.continuing&&(e.continuing=!1);let h=this.update?this.update.evaluate(e):void 0;return d(h,()=>a())})})};return a()};return d(r,()=>s())}},ae=class extends m{constructor(e,r,s){super("Try");this.body=e;this.errorName=r;this.handler=s}evaluate(e){let r=s=>{if(e.returning)return e.returnValue;let i=e.scope,n=e.scope;e.scope?.createChild&&(n=e.scope.createChild()),e.scope=n;let a=e.scope,o;a&&(o=a.getPath(this.errorName),a.setPath&&a.setPath(`self.${this.errorName}`,s));let c=this.handler.evaluate(e);return d(c,()=>{a&&a.setPath&&n===i&&a.setPath(this.errorName,o),e.scope=i})};try{let s=ge(e,this.body);return G(s)?s.catch(i=>r(i)):s}catch(s){return r(s)}}},I=class extends m{constructor(e,r,s,i=!1){super("FunctionDeclaration");this.name=e;this.params=r;this.body=s;this.isAsync=i}},W=class extends m{constructor(e,r,s=!1){super("FunctionExpression");this.params=e;this.body=r;this.isAsync=s}evaluate(e){let r=e.scope,s=e.globals,i=e.element;return this.isAsync?(...n)=>{let a=r?.createChild?r.createChild():r,o={scope:a,rootScope:e.rootScope,...s?{globals:s}:{},...i?{element:i}:{},returnValue:void 0,returning:!1,breaking:!1,continuing:!1},c=new Map,l=a?this.applyParams(a,c,o,n):void 0,h=d(l,()=>this.body.evaluate(o)),f=d(h,()=>o.returnValue);return Promise.resolve(f).finally(()=>{a&&a===r&&this.restoreParams(a,c)})}:(...n)=>{let a=r?.createChild?r.createChild():r,o={scope:a,rootScope:e.rootScope,...s?{globals:s}:{},...i?{element:i}:{},returnValue:void 0,returning:!1,breaking:!1,continuing:!1},c=new Map,l=a?this.applyParams(a,c,o,n):void 0,h=d(l,()=>this.body.evaluate(o)),f=d(h,()=>o.returnValue);return G(f)?f.finally(()=>{a&&a===r&&this.restoreParams(a,c)}):(a&&a===r&&this.restoreParams(a,c),f)}}applyParams(e,r,s,i){if(!e)return;let n=e.setPath?.bind(e);if(!n)return;let a=this.params,o=(c,l)=>{for(let h=c;h<a.length;h+=1){let f=a[h],g=f.name;if(!g)continue;if(r.set(g,e.getPath(g)),f.rest){n(`self.${g}`,i.slice(l));return}let k=i[l];if(k===void 0&&f.defaultValue){let $=f.defaultValue.evaluate(s);return d($,U=>(n(`self.${g}`,U),o(h+1,l+1)))}n(`self.${g}`,k),l+=1}};return o(0,0)}restoreParams(e,r){if(!e)return;let s=e.setPath?.bind(e);if(s)for(let i of this.params){let n=i.name;n&&s(n,r.get(n))}}},R=class extends m{constructor(e,r,s,i,n){super("Declaration");this.target=e;this.operator=r;this.value=s;this.flags=i;this.flagArgs=n}},y=class extends m{constructor(e){super("Identifier");this.name=e}evaluate(e){if(this.name.startsWith("root.")&&e.rootScope){let r=this.name.slice(5);return e.rootScope.getPath(`self.${r}`)}if(e.scope){let r=e.scope.getPath(this.name),s=this.name.split(".")[0];if(this.name.startsWith("parent.")||this.name.startsWith("root.")||this.name.startsWith("self.")||r!==void 0||s&&e.scope.hasKey?.(s))return r}return e.globals?e.globals[this.name]:void 0}},j=class extends m{constructor(e){super("SpreadElement");this.value=e}},H=class extends m{constructor(e){super("RestElement");this.target=e}},V=class extends m{constructor(e){super("ArrayPattern");this.elements=e}},O=class extends m{constructor(e){super("ObjectPattern");this.entries=e}},B=class extends m{constructor(e){super("Literal");this.value=e}evaluate(){return this.value}},oe=class extends m{constructor(e){super("TemplateExpression");this.parts=e}evaluate(e){let r="",s=0,i=()=>{for(;s<this.parts.length;){let n=this.parts[s];s+=1;let a=n.evaluate(e);return d(a,o=>(r+=o==null?"":String(o),i()))}return r};return i()}},z=class extends m{constructor(e,r){super("UnaryExpression");this.operator=e;this.argument=r}evaluate(e){let r=this.argument.evaluate(e);return d(r,s=>this.operator==="!"?!s:this.operator==="-"?-s:s)}},b=class extends m{constructor(e,r,s){super("BinaryExpression");this.operator=e;this.left=r;this.right=s}evaluate(e){let r=this.left.evaluate(e);return d(r,s=>{if(this.operator==="&&")return s&&this.right.evaluate(e);if(this.operator==="||")return s||this.right.evaluate(e);if(this.operator==="??")return s??this.right.evaluate(e);let i=this.right.evaluate(e);return d(i,n=>{if(this.operator==="+")return s+n;if(this.operator==="-")return s-n;if(this.operator==="*")return s*n;if(this.operator==="/")return s/n;if(this.operator==="%")return s%n;if(this.operator==="==")return s==n;if(this.operator==="!=")return s!=n;if(this.operator==="===")return s===n;if(this.operator==="!==")return s!==n;if(this.operator==="<")return s<n;if(this.operator===">")return s>n;if(this.operator==="<=")return s<=n;if(this.operator===">=")return s>=n})})}},ce=class extends m{constructor(e,r,s){super("TernaryExpression");this.test=e;this.consequent=r;this.alternate=s}evaluate(e){let r=this.test.evaluate(e);return d(r,s=>s?this.consequent.evaluate(e):this.alternate.evaluate(e))}},v=class p extends m{constructor(e,r,s=!1){super("MemberExpression");this.target=e;this.property=r;this.optional=s}evaluate(e){let r=this.resolve(e);return d(r,s=>s?.value)}resolve(e){let r=this.getIdentifierPath();if(r){let i=this.resolveFromScope(e,r);if(i)return i;let n=this.resolveFromGlobals(e,r);if(n)return n}let s=this.target.evaluate(e);return d(s,i=>i==null?{value:void 0,target:i,optional:this.optional}:{value:i[this.property],target:i,optional:this.optional})}getIdentifierPath(){let e=this.getTargetIdentifierPath();return e?{path:`${e.path}.${this.property}`,root:e.root}:void 0}getTargetIdentifierPath(){if(this.target instanceof y){let e=this.target.name,r=e.split(".")[0];return r?{path:e,root:r}:void 0}if(this.target instanceof p)return this.target.getIdentifierPath()}resolveFromScope(e,r){if(!e.scope)return;if(r.path.startsWith("root.")&&e.rootScope){let o=r.path.slice(5),c=e.rootScope.getPath(`self.${o}`),l=o.split(".").slice(0,-1).join("."),h=l?e.rootScope.getPath(`self.${l}`):e.rootScope;return{value:c,target:h,optional:this.optional}}let s=e.scope.getPath(r.path);if(!(r.path.startsWith("parent.")||r.path.startsWith("root.")||r.path.startsWith("self."))&&s===void 0&&!e.scope.hasKey?.(r.root))return;let n=this.getTargetPath(r.path),a=n?e.scope.getPath(n):void 0;return{value:s,target:a,optional:this.optional}}resolveFromGlobals(e,r){let s=e.globals??{};if(!r.root||!(r.root in s))return;let i=s[r.root],n,a=r.path.split(".");for(let o=1;o<a.length;o+=1){n=i;let c=a[o];if(!c)return{value:void 0,target:n,optional:this.optional};i=i?.[c]}return{value:i,target:n,optional:this.optional}}getTargetPath(e){let r=e.split(".");if(!(r.length<=1))return r.slice(0,-1).join(".")}},S=class extends m{constructor(e,r){super("CallExpression");this.callee=e;this.args=r}evaluate(e){let r=this.resolveCallee(e);return d(r,s=>{let i=s?.fn??this.callee.evaluate(e);return d(i,n=>{if(typeof n!="function")return;let a=[],o=c=>{for(let l=c;l<this.args.length;l+=1){let f=this.args[l].evaluate(e);return d(f,g=>(a.push(g),o(l+1)))}return n.apply(s?.thisArg,a)};return o(0)})})}resolveCallee(e){if(this.callee instanceof v){let c=this.callee.resolve(e);return d(c,l=>{if(l)return{fn:l.value,thisArg:l.target}})}if(!(this.callee instanceof y))return;let r=this.callee.name,s=e.globals??{},i=r.split("."),n=i[0];if(!n||!(n in s)){if(i.length>1&&e.scope){let c=i.slice(0,-1).join("."),l=i[i.length-1];if(!l)return;let h=e.scope.getPath(c);return h==null?void 0:{fn:h?.[l],thisArg:h}}return}let a=s[n],o;for(let c=1;c<i.length;c+=1){o=a;let l=i[c];if(!l)return;a=a?.[l]}return{fn:a,thisArg:o}}},pe=class extends m{constructor(e){super("ArrayExpression");this.elements=e}evaluate(e){let r=[],s=n=>{if(n==null)return;if(typeof n[Symbol.iterator]=="function")for(let o of n)r.push(o);else r.push(n)},i=n=>{for(let a=n;a<this.elements.length;a+=1){let o=this.elements[a];if(o instanceof j){let l=o.value.evaluate(e);return d(l,h=>(s(h),i(a+1)))}let c=o.evaluate(e);return d(c,l=>(r.push(l),i(a+1)))}return r};return i(0)}},le=class extends m{constructor(e){super("ObjectExpression");this.entries=e}evaluate(e){let r={},s=i=>{for(let n=i;n<this.entries.length;n+=1){let a=this.entries[n];if("spread"in a){let c=a.spread.evaluate(e);return d(c,l=>(l!=null&&Object.assign(r,l),s(n+1)))}if("computed"in a&&a.computed){let c=a.keyExpr.evaluate(e);return d(c,l=>{let h=a.value.evaluate(e);return d(h,f=>(r[String(l)]=f,s(n+1)))})}let o=a.value.evaluate(e);return d(o,c=>(r[a.key]=c,s(n+1)))}return r};return s(0)}},w=class extends m{constructor(e,r){super("IndexExpression");this.target=e;this.index=r}evaluate(e){let r=this.target.evaluate(e);return d(r,s=>{if(s==null)return;let i=this.index.evaluate(e);return d(i,n=>{if(n==null)return;let a=this.normalizeIndexKey(s,n);return s[a]})})}normalizeIndexKey(e,r){if(Array.isArray(e)&&typeof r=="string"&&r.trim()!==""){let s=Number(r);if(!Number.isNaN(s))return s}return r}},x=class extends m{constructor(e,r){super("Directive");this.kind=e;this.name=r}evaluate(e){let r=e.element;if(!r)return`${this.kind}:${this.name}`;if(this.kind==="attr")return this.name==="value"&&(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement)?r.value:this.name==="text"&&r instanceof HTMLElement?r.innerText:this.name==="content"&&r instanceof HTMLElement?r.textContent??"":this.name==="checked"&&r instanceof HTMLInputElement?r.checked:this.name==="html"&&r instanceof HTMLElement?r.innerHTML:r.getAttribute(this.name)??void 0;if(this.kind==="style"&&r instanceof HTMLElement)return r.style.getPropertyValue(this.name)??void 0}},K=class extends m{constructor(e){super("AwaitExpression");this.argument=e}evaluate(e){let r=this.argument.evaluate(e);return Promise.resolve(r)}},he=class extends m{constructor(e,r){super("Query");this.direction=e;this.selector=r}evaluate(e){let r=this.selector.trim();if(!r)return[];if(this.direction==="ancestor"){let i=[],n=e.element?.parentElement;for(;n;)n.matches(r)&&i.push(n),n=n.parentElement;return i}let s=this.direction==="descendant"?e.element??(typeof document<"u"?document:void 0):typeof document<"u"?document:void 0;return!s||!("querySelectorAll"in s)?[]:Array.from(s.querySelectorAll(r))}};var ue=class{constructor(t){this.tokens=t}index=0;peek(t=0){return this.tokens[this.index+t]??null}next(){let t=this.tokens[this.index++];if(!t)throw new Error("Unexpected end of input");return t}eof(){return this.index>=this.tokens.length}match(t){return this.peek()?.type===t?(this.next(),!0):!1}expect(t){let e=this.next();if(e.type!==t)throw new Error(`Expected ${t} but got ${e.type}`);return e}skipWhitespace(){for(;this.peek()?.type==="Whitespace";)this.next()}peekNonWhitespace(t=0){let e=0;for(let r=this.index;r<this.tokens.length;r++){let s=this.tokens[r];if(s&&s.type!=="Whitespace"){if(e===t)return s;e+=1}}return null}indexAfterDelimited(t,e,r=0){let s=this.peekNonWhitespace(r);if(!s||s.type!==t)return null;let i=r+1,n=1;for(;;){let a=this.peekNonWhitespace(i);if(!a)return null;if(a.type===t)n+=1;else if(a.type===e&&(n-=1,n===0))return i+1;i+=1}}};var D=class p{stream;source;customFlags;behaviorFlags;allowImplicitSemicolon=!1;awaitStack=[];functionDepth=0;constructor(t,e){this.source=t,this.customFlags=e?.customFlags??new Set(["important","trusted","debounce"]),this.behaviorFlags=e?.behaviorFlags??new Set;let r=new q(t);this.stream=new ue(r.tokenize())}static parseInline(t){return new p(`{${t}}`).parseInlineBlock()}parseProgram(){return this.wrapErrors(()=>{let t=[],e=[];for(this.stream.skipWhitespace();!this.stream.eof();){let r=this.stream.peek();if(!r)break;r.type==="Use"?e.push(this.parseUseStatement()):t.push(this.parseBehavior()),this.stream.skipWhitespace()}return new Z(t,e)})}parseInlineBlock(){return this.wrapErrors(()=>(this.stream.skipWhitespace(),this.allowImplicitSemicolon=!0,this.parseBlock({allowDeclarations:!1})))}parseBehavior(){return this.wrapErrors(()=>{this.stream.skipWhitespace(),this.stream.expect("Behavior");let t=this.parseSelector(),{flags:e,flagArgs:r}=this.parseBehaviorFlags(),s=this.parseBlock({allowDeclarations:!0});return new M(t,s,e,r)})}parseSelector(){let t="",e=!1;for(;;){let r=this.stream.peek();if(!r||r.type==="LBrace"||r.type==="Bang")break;if(r.type==="Whitespace"){this.stream.next(),e&&t[t.length-1]!==" "&&(t+=" ");continue}e=!0,t+=this.stream.next().value}if(!t.trim())throw new Error("Behavior selector is required");return new Y(t.trim())}parseBehaviorFlags(){let t=this.parseFlags(this.behaviorFlags,"behavior modifier");return{flags:t.flags,flagArgs:t.flagArgs}}parseUseStatement(){return this.wrapErrors(()=>{this.stream.expect("Use"),this.stream.skipWhitespace();let t=this.parseIdentifierPath();this.stream.skipWhitespace();let e=t,r=this.stream.peek();r?.type==="Identifier"&&r.value==="as"&&(this.stream.next(),this.stream.skipWhitespace(),e=this.stream.expect("Identifier").value);let{flags:s,flagArgs:i}=this.parseUseFlags();return this.stream.skipWhitespace(),this.stream.expect("Semicolon"),new J(t,e,s,i)})}parseUseFlags(){let t={},e={};for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="Bang";){this.stream.next();let r=this.stream.expect("Identifier").value;if(r!=="wait")throw new Error(`Unknown flag ${r}`);if(t.wait=!0,this.stream.peek()?.type==="LParen"){this.stream.next(),this.stream.skipWhitespace();let s=this.stream.expect("Number"),i=Number(s.value),n;if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next(),this.stream.skipWhitespace();let a=this.stream.expect("Number");n=Number(a.value),this.stream.skipWhitespace()}this.stream.expect("RParen"),e.wait={timeoutMs:i,...n!==void 0?{intervalMs:n}:{}}}}return{flags:t,flagArgs:e}}wrapErrors(t){try{return t()}catch(e){throw e instanceof Error&&!/\(line\s+\d+, column\s+\d+\)/i.test(e.message)?new Error(this.formatError(e.message)):e}}formatError(t){let e=this.stream.peek()??this.stream.peekNonWhitespace(0);if(!e)return`Parse error: ${t}`;let r=e.start.line,s=e.start.column,i=this.getLineSnippet(r,s);return`Parse error (line ${r}, column ${s}): ${t}
|
|
5
|
+
${i}`}getLineSnippet(t,e){let s=this.source.split(/\r?\n/)[t-1]??"",i=`${" ".repeat(Math.max(e-1,0))}^`;return`${s}
|
|
6
|
+
${i}`}parseBlock(t){let e=t?.allowDeclarations??!1,r=t?.allowReturn??this.functionDepth>0;this.stream.skipWhitespace(),this.stream.expect("LBrace");let s=[],i=e,n=!1,a=!1,o=!1;for(;;){this.stream.skipWhitespace();let c=this.stream.peek();if(!c)throw new Error("Unterminated block");if(c.type==="RBrace"){this.stream.next();break}if(e&&c.type==="Behavior"&&(o=!0),e&&o&&c.type!=="Behavior")throw new Error("Nested behaviors must appear after construct, function, and on blocks");if(e&&this.isFunctionDeclarationStart()){n||(a=!0),s.push(this.parseFunctionDeclaration());continue}if(e&&this.isFunctionExpressionAssignmentStart()){if(!i)throw new Error("Declarations must appear before blocks");s.push(this.parseAssignment());continue}if(this.isDeclarationStart()){if(!e)throw new Error("Declarations are only allowed at the behavior root");if(!i)throw new Error("Declarations must appear before blocks");s.push(this.parseDeclaration())}else{if(i&&(i=!1),e&&c.type==="On"&&!n&&(a=!0),e&&c.type==="Construct"){if(a)throw new Error("Construct blocks must appear before functions and on blocks");n=!0}s.push(this.parseStatement({allowReturn:r}))}}return new E(s)}parseStatement(t){this.stream.skipWhitespace();let e=this.stream.peek();if(!e)throw new Error("Unexpected end of input");let r=t?.allowBlocks??!0,s=t?.allowReturn??!1;if(e.type==="Return"){if(!s)throw new Error("Return is only allowed inside functions");return this.parseReturnStatement()}if(e.type==="Assert")return this.parseAssertStatement();if(e.type==="Break")return this.parseBreakStatement();if(e.type==="Continue")return this.parseContinueStatement();if(r&&e.type==="On")return this.parseOnBlock();if(r&&e.type==="If")return this.parseIfBlock();if(r&&e.type==="For")return this.parseForBlock();if(r&&e.type==="While")return this.parseWhileBlock();if(r&&e.type==="Try")return this.parseTryBlock();if(r&&e.type==="Construct")return this.parseConstructBlock();if(r&&e.type==="Destruct")return this.parseDestructBlock();if(r&&e.type==="Behavior")return this.parseBehavior();if(this.isAwaitAllowed()&&e.type==="Identifier"&&e.value==="await")return this.parseExpressionStatement();if(this.isAssignmentStart())return this.parseAssignment();if(this.isExpressionStatementStart())return this.parseExpressionStatement();throw new Error(`Unexpected token ${e.type}`)}parseOnBlock(){this.stream.expect("On"),this.stream.skipWhitespace();let t=this.parseIdentifierPath();this.stream.skipWhitespace(),this.stream.expect("LParen");let e=[];for(;;){this.stream.skipWhitespace();let n=this.stream.peek();if(!n)throw new Error("Unterminated on() arguments");if(n.type==="RParen"){this.stream.next();break}if(n.type==="Identifier"){e.push(this.stream.next().value),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"&&this.stream.next();continue}throw new Error(`Unexpected token in on() args: ${n.type}`)}let{flags:r,flagArgs:s}=this.parseFlags(this.customFlags,"flag"),i=this.parseBlock({allowDeclarations:!1});return new C(t,e,i,r,s)}parseAssignment(){let t=this.parseAssignmentTarget();this.stream.skipWhitespace();let e=this.parseAssignmentOperator();this.stream.skipWhitespace();let r=this.parseExpression();return this.consumeStatementTerminator(),new N(t,r,e)}parseExpression(){return this.parsePipeExpression()}parsePipeExpression(){let t=this.parseTernaryExpression();for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="Pipe";){this.stream.next(),this.stream.skipWhitespace();let e=!1,r=this.stream.peek();this.isAwaitAllowed()&&r?.type==="Identifier"&&r.value==="await"&&(this.stream.next(),this.stream.skipWhitespace(),e=!0);let s=this.parseCallExpression(),i=this.buildPipeCall(t,s);t=e?new K(i):i}return t}buildPipeCall(t,e){if(e instanceof S)return new S(e.callee,[t,...e.args]);if(e instanceof y||e instanceof v)return new S(e,[t]);throw new Error("Pipe operator requires a function call")}parseTernaryExpression(){let t=this.parseNullishExpression();if(this.stream.skipWhitespace(),this.stream.peek()?.type!=="Question")return t;this.stream.next(),this.stream.skipWhitespace();let e=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace();let r=this.parseExpression();return new ce(t,e,r)}parseNullishExpression(){let t=this.parseLogicalOrExpression();for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="NullishCoalesce";){this.stream.next(),this.stream.skipWhitespace();let e=this.parseLogicalOrExpression();t=new b("??",t,e)}return t}parseLogicalOrExpression(){let t=this.parseLogicalAndExpression();for(this.stream.skipWhitespace();;){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="Or")break;this.stream.skipWhitespace(),this.stream.next(),this.stream.skipWhitespace();let r=this.parseLogicalAndExpression();this.stream.skipWhitespace(),t=new b("||",t,r)}return t}parseLogicalAndExpression(){let t=this.parseEqualityExpression();for(this.stream.skipWhitespace();;){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="And")break;this.stream.skipWhitespace(),this.stream.next(),this.stream.skipWhitespace();let r=this.parseEqualityExpression();this.stream.skipWhitespace(),t=new b("&&",t,r)}return t}parseEqualityExpression(){let t=this.parseComparisonExpression();for(this.stream.skipWhitespace();;){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="DoubleEquals"&&e.type!=="NotEquals"&&e.type!=="TripleEquals"&&e.type!=="StrictNotEquals")break;this.stream.skipWhitespace();let r=this.stream.next();this.stream.skipWhitespace();let s=this.parseComparisonExpression();this.stream.skipWhitespace();let i="==";r.type==="NotEquals"?i="!=":r.type==="TripleEquals"?i="===":r.type==="StrictNotEquals"&&(i="!=="),t=new b(i,t,s)}return t}parseComparisonExpression(){let t=this.parseAdditiveExpression();for(this.stream.skipWhitespace();;){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="Less"&&e.type!=="Greater"&&e.type!=="LessEqual"&&e.type!=="GreaterEqual")break;this.stream.skipWhitespace();let r=this.stream.next();this.stream.skipWhitespace();let s=this.parseAdditiveExpression();this.stream.skipWhitespace();let i="<";r.type==="Greater"?i=">":r.type==="LessEqual"?i="<=":r.type==="GreaterEqual"&&(i=">="),t=new b(i,t,s)}return t}parseMultiplicativeExpression(){let t=this.parseUnaryExpression();for(this.stream.skipWhitespace();;){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="Star"&&e.type!=="Slash"&&e.type!=="Percent")break;this.stream.skipWhitespace();let r=this.stream.next();this.stream.skipWhitespace();let s=this.parseUnaryExpression();this.stream.skipWhitespace();let i="*";r.type==="Slash"?i="/":r.type==="Percent"&&(i="%"),t=new b(i,t,s)}return t}parseAdditiveExpression(){let t=this.parseMultiplicativeExpression();for(this.stream.skipWhitespace();;){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="Plus"&&e.type!=="Minus")break;this.stream.skipWhitespace();let r=this.stream.next();this.stream.skipWhitespace();let s=this.parseMultiplicativeExpression();this.stream.skipWhitespace(),t=new b(r.type==="Plus"?"+":"-",t,s)}return t}parseUnaryExpression(){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)throw new Error("Expected expression");if(t.type==="PlusPlus"||t.type==="MinusMinus"){this.stream.next();let e=this.parseUnaryExpression();return this.createIncrementNode(t,e,!0)}if(t.type==="Bang"){this.stream.next();let e=this.parseUnaryExpression();return new z("!",e)}if(t.type==="Minus"){this.stream.next();let e=this.parseUnaryExpression();return new z("-",e)}if(this.isAwaitAllowed()&&t.type==="Identifier"&&t.value==="await"){this.stream.next();let e=this.parseUnaryExpression();return new K(e)}return this.parsePostfixExpression()}parsePostfixExpression(){let t=this.parseCallExpression();for(;;){this.stream.skipWhitespace();let e=this.stream.peek();if(!e)break;if(e.type==="PlusPlus"||e.type==="MinusMinus"){this.stream.next(),t=this.createIncrementNode(e,t,!1);continue}break}return t}createIncrementNode(t,e,r){if(!(e instanceof y)&&!(e instanceof v)&&!(e instanceof w)&&!(e instanceof x))throw new Error("Increment/decrement requires a mutable target");let s=t.type==="PlusPlus"?"++":"--";return new N(e,new B(1),s,r)}parseCallExpression(){let t=this.parsePrimaryExpression();for(;;){this.stream.skipWhitespace();let e=this.stream.peek();if(!e)break;if(e.type==="LParen"){this.stream.next();let r=[];for(;;){this.stream.skipWhitespace();let s=this.stream.peek();if(!s)throw new Error("Unterminated call expression");if(s.type==="RParen"){this.stream.next();break}if(r.push(this.parseExpression()),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RParen"){this.stream.next();break}throw new Error("Expected ',' or ')' in call arguments")}t=new S(t,r);continue}if(e.type==="OptionalChain"){this.stream.next(),this.stream.skipWhitespace();let r=this.stream.peek();if(!r)throw new Error("Expected property or call after ?.");if(r.type==="LParen"){this.stream.next();let s=[];for(;;){this.stream.skipWhitespace();let i=this.stream.peek();if(!i)throw new Error("Unterminated call expression");if(i.type==="RParen"){this.stream.next();break}if(s.push(this.parseExpression()),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RParen"){this.stream.next();break}throw new Error("Expected ',' or ')' in call arguments")}t=new S(t,s);continue}if(r.type==="Identifier"){let s=this.stream.next();t=new v(t,s.value,!0);continue}throw new Error("Expected property or call after ?.")}if(e.type==="Dot"){this.stream.next();let r=this.stream.expect("Identifier");t=new v(t,r.value);continue}if(e.type==="LBracket"){this.stream.next(),this.stream.skipWhitespace();let r=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RBracket"),t=new w(t,r);continue}break}return t}parsePrimaryExpression(){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)throw new Error("Expected expression");if(t.type==="At"||t.type==="Dollar"){let e=t.type==="At"?"attr":"style";this.stream.next();let r=this.stream.expect("Identifier");return new x(e,r.value)}if(t.type==="Question")return this.parseQueryExpression();if(t.type==="LBracket")return this.parseArrayExpression();if(t.type==="LBrace")return this.parseObjectExpression();if(t.type==="LParen"){if(this.isArrowFunctionStart())return this.parseArrowFunctionExpression();this.stream.next();let e=this.parseExpression();return this.stream.skipWhitespace(),this.stream.expect("RParen"),e}if(t.type==="Identifier")return this.isAsyncToken(t)&&this.isAsyncArrowFunctionStart()?(this.stream.next(),this.stream.skipWhitespace(),this.parseArrowFunctionExpression(!0)):new y(this.stream.next().value);if(t.type==="Boolean")return new B(this.stream.next().value==="true");if(t.type==="Null")return this.stream.next(),new B(null);if(t.type==="Number")return new B(Number(this.stream.next().value));if(t.type==="String")return new B(this.stream.next().value);if(t.type==="Template")return this.parseTemplateExpression();throw new Error(`Unsupported expression token ${t.type}`)}parseArrayExpression(){this.stream.expect("LBracket");let t=[];for(;;){this.stream.skipWhitespace();let e=this.stream.peek();if(!e)throw new Error("Unterminated array literal");if(e.type==="RBracket"){this.stream.next();break}if(e.type==="Ellipsis"){this.stream.next(),this.stream.skipWhitespace();let r=this.parseExpression();t.push(new j(r))}else t.push(this.parseExpression());if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="RBracket"){this.stream.next();break}continue}if(this.stream.peek()?.type==="RBracket"){this.stream.next();break}throw new Error("Expected ',' or ']' in array literal")}return new pe(t)}parseTemplateExpression(){let t=[];for(;;){let e=this.stream.peek();if(!e)throw new Error("Unterminated template literal");if(e.type!=="Template")throw new Error("Expected template literal");let r=this.stream.next().value;r&&t.push(new B(r));let s=this.stream.peek();if(!s||s.type!=="Dollar")break;this.stream.next(),this.stream.expect("LBrace"),this.stream.skipWhitespace();let i=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RBrace"),t.push(i)}return new oe(t)}parseObjectExpression(){this.stream.expect("LBrace");let t=[];for(;;){this.stream.skipWhitespace();let e=this.stream.peek();if(!e)throw new Error("Unterminated object literal");if(e.type==="RBrace"){this.stream.next();break}let r,s;if(e.type==="Ellipsis")this.stream.next(),this.stream.skipWhitespace(),s={spread:this.parseExpression()};else if(e.type==="LBracket"){this.stream.next(),this.stream.skipWhitespace();let i=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RBracket"),this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace(),r=this.parseExpression(),s={keyExpr:i,value:r,computed:!0}}else if(e.type==="Identifier"){let i=this.stream.next().value;this.stream.skipWhitespace(),this.stream.peek()?.type==="Colon"?(this.stream.next(),this.stream.skipWhitespace(),r=this.parseExpression()):r=new y(i),s={key:i,value:r}}else if(e.type==="String"){let i=this.stream.next().value;this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace(),r=this.parseExpression(),s={key:i,value:r}}else throw new Error(`Unexpected token in object literal: ${e.type}`);if(!s)throw new Error("Invalid object literal entry");if(t.push(s),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="RBrace"){this.stream.next();break}continue}if(this.stream.peek()?.type==="RBrace"){this.stream.next();break}throw new Error("Expected ',' or '}' in object literal")}return new le(t)}consumeStatementTerminator(){this.stream.skipWhitespace();let t=this.stream.peek();if(t?.type==="Semicolon"){this.stream.next();return}this.allowImplicitSemicolon&&t?.type==="RBrace"||this.stream.expect("Semicolon")}parseFunctionBlockWithAwait(t){this.stream.expect("LBrace");let e=[];this.awaitStack.push(t),this.functionDepth+=1;try{for(;;){this.stream.skipWhitespace();let r=this.stream.peek();if(!r)throw new Error("Unterminated function block");if(r.type==="RBrace"){this.stream.next();break}e.push(this.parseStatement({allowBlocks:!0,allowReturn:!0}))}}finally{this.functionDepth-=1,this.awaitStack.pop()}return new E(e)}isAsyncToken(t){return t?.type==="Identifier"&&t.value==="async"}isAwaitAllowed(){return this.awaitStack.length===0?!1:this.awaitStack[this.awaitStack.length-1]===!0}parseArrowExpressionBody(t){this.awaitStack.push(t);try{let e=this.parseExpression();return new E([new L(e)])}finally{this.awaitStack.pop()}}parseAssignmentTarget(){let t=this.stream.peek();if(!t)throw new Error("Expected assignment target");if(t.type==="At"||t.type==="Dollar"){let e=t.type==="At"?"attr":"style";this.stream.next();let r=this.stream.expect("Identifier");return new x(e,r.value)}if(t.type==="LBracket")return this.parseArrayPattern();if(t.type==="LBrace")return this.parseObjectPattern();if(t.type==="Identifier"){let e=this.parseCallExpression();if(e instanceof S)throw new Error("Invalid assignment target CallExpression");if(e instanceof y||e instanceof v||e instanceof w)return e;throw new Error("Invalid assignment target")}throw new Error(`Invalid assignment target ${t.type}`)}parseArrayPattern(){this.stream.expect("LBracket");let t=[],e=!1;for(;;){this.stream.skipWhitespace();let r=this.stream.peek();if(!r)throw new Error("Unterminated array pattern");if(r.type==="RBracket"){this.stream.next();break}if(r.type==="Comma"){this.stream.next(),t.push(null);continue}if(r.type==="Ellipsis"){if(e)throw new Error("Array patterns can only include one rest element");this.stream.next(),this.stream.skipWhitespace();let s=this.stream.expect("Identifier");t.push(new H(new y(s.value))),e=!0}else if(r.type==="LBracket")t.push(this.parseArrayPattern());else if(r.type==="LBrace")t.push(this.parseObjectPattern());else if(r.type==="Identifier")t.push(new y(this.parseIdentifierPath()));else throw new Error(`Unexpected token in array pattern: ${r.type}`);if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RBracket"){this.stream.next();break}throw new Error("Expected ',' or ']' in array pattern")}if(e&&!(t[t.length-1]instanceof H))throw new Error("Rest element must be last in array pattern");return new V(t)}parseObjectPattern(){this.stream.expect("LBrace");let t=[],e;for(;;){this.stream.skipWhitespace();let s=this.stream.peek();if(!s)throw new Error("Unterminated object pattern");if(s.type==="RBrace"){this.stream.next();break}if(s.type==="Ellipsis"){if(e)throw new Error("Object patterns can only include one rest element");this.stream.next(),this.stream.skipWhitespace();let i=this.stream.expect("Identifier");if(e=new y(i.value),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"&&(this.stream.next(),this.stream.skipWhitespace()),this.stream.peek()?.type!=="RBrace")throw new Error("Rest element must be last in object pattern");this.stream.next();break}else if(s.type==="Identifier"||s.type==="String"){let n=this.stream.next().value;this.stream.skipWhitespace();let a;if(this.stream.peek()?.type==="Colon"){this.stream.next(),this.stream.skipWhitespace();let o=this.stream.peek();if(!o)throw new Error("Expected object pattern target");if(o.type==="LBracket")a=this.parseArrayPattern();else if(o.type==="LBrace")a=this.parseObjectPattern();else if(o.type==="Identifier")a=new y(this.parseIdentifierPath());else throw new Error(`Unexpected token in object pattern: ${o.type}`)}else a=new y(n);t.push({key:n,target:a})}else throw new Error(`Unexpected token in object pattern: ${s.type}`);if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="RBrace"){this.stream.next();break}continue}if(this.stream.peek()?.type==="RBrace"){this.stream.next();break}throw new Error("Expected ',' or '}' in object pattern")}let r=e?[...t,{rest:e}]:t;return e&&t.length===0?new O([{rest:e}]):new O(r)}parseDeclaration(){let t=this.parseDeclarationTarget();this.stream.skipWhitespace();let e=this.parseDeclarationOperator();this.stream.skipWhitespace();let r=this.parseExpression(),{flags:s,flagArgs:i}=this.parseFlags(this.customFlags,"flag");return this.stream.skipWhitespace(),this.stream.expect("Semicolon"),new R(t,e,r,s,i)}parseDeclarationTarget(){let t=this.stream.peek();if(!t)throw new Error("Expected declaration target");if(t.type==="At"||t.type==="Dollar"){let e=t.type==="At"?"attr":"style";this.stream.next();let r=this.stream.expect("Identifier");return new x(e,r.value)}if(t.type==="Identifier")return new y(this.stream.next().value);throw new Error(`Invalid declaration target ${t.type}`)}parseDeclarationOperator(){this.stream.expect("Colon");let t=this.stream.peek();return t?t.type==="Equals"?(this.stream.next(),":="):t.type==="Less"?(this.stream.next(),":<"):t.type==="Greater"?(this.stream.next(),":>"):":":":"}parseFlags(t,e){let r={},s={};for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="Bang";){this.stream.next();let i=this.stream.expect("Identifier").value;if(t&&!t.has(i))throw new Error(`Unknown ${e} ${i}`);r[i]=!0;let n=this.parseCustomFlagArg();n!==void 0&&(s[i]=n)}return{flags:r,flagArgs:s}}parseCustomFlagArg(){if(this.stream.peek()?.type!=="LParen")return;if(this.stream.next(),this.stream.skipWhitespace(),!this.stream.peek())throw new Error("Unterminated flag arguments");let e=this.parseCustomFlagLiteral();return this.stream.skipWhitespace(),this.stream.expect("RParen"),e}parseCustomFlagLiteral(){let t=this.stream.peek();if(!t)throw new Error("Unterminated flag arguments");if(t.type==="Number")return Number(this.stream.next().value);if(t.type==="String")return this.stream.next().value;if(t.type==="Boolean")return this.stream.next().value==="true";if(t.type==="Identifier")return this.stream.next().value;if(t.type==="LBracket")return this.parseCustomFlagArray();if(t.type==="LBrace")return this.parseCustomFlagObject();throw new Error(`Unsupported flag argument ${t.type}`)}parseCustomFlagArray(){this.stream.expect("LBracket");let t=[];for(;;){this.stream.skipWhitespace();let e=this.stream.peek();if(!e)throw new Error("Unterminated flag array");if(e.type==="RBracket"){this.stream.next();break}t.push(this.parseCustomFlagLiteral()),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"&&this.stream.next()}return t}parseCustomFlagObject(){this.stream.expect("LBrace");let t={};for(;;){this.stream.skipWhitespace();let e=this.stream.peek();if(!e)throw new Error("Unterminated flag object");if(e.type==="RBrace"){this.stream.next();break}let r;if(e.type==="Identifier"||e.type==="String")r=this.stream.next().value;else throw new Error(`Unsupported flag object key ${e.type}`);this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace(),t[r]=this.parseCustomFlagLiteral(),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"&&this.stream.next()}return t}isDeclarationStart(){let t=this.stream.peekNonWhitespace(0);if(!t)return!1;if(t.type==="Identifier")return this.stream.peekNonWhitespace(1)?.type==="Colon";if(t.type==="At"||t.type==="Dollar"){let e=this.stream.peekNonWhitespace(1),r=this.stream.peekNonWhitespace(2);return e?.type==="Identifier"&&r?.type==="Colon"}return!1}isAssignmentStart(){let t=this.stream.peekNonWhitespace(0);if(!t)return!1;if(t.type==="Identifier"){let e=1;for(;;){let r=this.stream.peekNonWhitespace(e);if(!r)return!1;if(r.type==="Dot"&&this.stream.peekNonWhitespace(e+1)?.type==="Identifier"){e+=2;continue}if(r.type==="LBracket"){let s=this.stream.indexAfterDelimited("LBracket","RBracket",e);if(s===null)return!1;e=s;continue}break}return this.isAssignmentOperatorStart(e)}if(t.type==="At"||t.type==="Dollar")return this.stream.peekNonWhitespace(1)?.type==="Identifier"&&this.isAssignmentOperatorStart(2);if(t.type==="LBrace"||t.type==="LBracket"){let e=[],r=0;for(;;){let s=this.stream.peekNonWhitespace(r);if(!s)return!1;if(s.type==="LBrace"||s.type==="LBracket")e.push(s.type);else if((s.type==="RBrace"||s.type==="RBracket")&&(e.pop(),e.length===0))return this.isAssignmentOperatorStart(r+1);r+=1}}return!1}isAssignmentOperatorStart(t){let e=this.stream.peekNonWhitespace(t);return e?e.type==="Equals"?!0:e.type==="Plus"||e.type==="Minus"||e.type==="Star"||e.type==="Slash"?this.stream.peekNonWhitespace(t+1)?.type==="Equals":!1:!1}isExpressionStatementStart(){let t=this.stream.peekNonWhitespace(0);return t?t.type==="Identifier"?!0:t.type==="Number"||t.type==="String"||t.type==="Boolean"||t.type==="Null"||t.type==="LParen"||t.type==="LBracket"||t.type==="LBrace"||t.type==="At"||t.type==="Dollar"||t.type==="Question"||t.type==="Bang"||t.type==="Minus":!1}isFunctionDeclarationStart(){let t=this.stream.peekNonWhitespace(0);if(!t)return!1;let e=0;if(this.isAsyncToken(t)){let s=this.stream.peekNonWhitespace(1);if(!s||s.type!=="Identifier")return!1;e=1}else if(t.type!=="Identifier")return!1;if(e+=1,this.stream.peekNonWhitespace(e)?.type!=="LParen")return!1;let r=this.stream.indexAfterDelimited("LParen","RParen",e);return r===null?!1:this.stream.peekNonWhitespace(r)?.type==="LBrace"}isArrowFunctionStart(){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="LParen")return!1;let e=this.stream.indexAfterDelimited("LParen","RParen",0);return e===null?!1:this.stream.peekNonWhitespace(e)?.type==="Arrow"}isAsyncArrowFunctionStart(){let t=this.stream.peekNonWhitespace(0);if(!this.isAsyncToken(t)||this.stream.peekNonWhitespace(1)?.type!=="LParen")return!1;let e=this.stream.indexAfterDelimited("LParen","RParen",1);return e===null?!1:this.stream.peekNonWhitespace(e)?.type==="Arrow"}isFunctionExpressionAssignmentStart(){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="Identifier"||this.stream.peekNonWhitespace(1)?.type!=="Equals")return!1;let e=2;if(this.isAsyncToken(this.stream.peekNonWhitespace(e))&&(e+=1),this.stream.peekNonWhitespace(e)?.type!=="LParen")return!1;let r=this.stream.indexAfterDelimited("LParen","RParen",e);return r===null?!1:this.stream.peekNonWhitespace(r)?.type==="Arrow"}parseExpressionStatement(){let t=this.parseExpression();return this.consumeStatementTerminator(),t}parseIfBlock(){this.stream.expect("If"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let t=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RParen");let e=this.parseConditionalBody();this.stream.skipWhitespace();let r;if(this.stream.peek()?.type==="Else")if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="If"){let s=this.parseIfBlock();r=new E([s])}else r=this.parseConditionalBody();return new re(t,e,r)}parseConditionalBody(){if(this.stream.skipWhitespace(),this.stream.peek()?.type==="LBrace")return this.parseBlock({allowDeclarations:!1});let t=this.parseStatement({allowBlocks:!1,allowReturn:this.functionDepth>0});return new E([t])}parseWhileBlock(){this.stream.expect("While"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let t=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RParen");let e=this.parseBlock({allowDeclarations:!1});return new se(t,e)}parseForBlock(){this.stream.expect("For"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let t=this.detectForEachKind();if(t){let n=this.parseForEachTarget();this.stream.skipWhitespace();let a=this.stream.expect("Identifier");if(a.value!==t)throw new Error(`Expected '${t}' but got '${a.value}'`);this.stream.skipWhitespace();let o=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RParen");let c=this.parseBlock({allowDeclarations:!1});return new ie(n,o,t,c)}let e;this.stream.peek()?.type!=="Semicolon"&&(e=this.parseForClause()),this.stream.skipWhitespace(),this.stream.expect("Semicolon"),this.stream.skipWhitespace();let r;this.stream.peek()?.type!=="Semicolon"&&(r=this.parseExpression()),this.stream.skipWhitespace(),this.stream.expect("Semicolon"),this.stream.skipWhitespace();let s;this.stream.peek()?.type!=="RParen"&&(s=this.parseForClause()),this.stream.skipWhitespace(),this.stream.expect("RParen");let i=this.parseBlock({allowDeclarations:!1});return new ne(e,r,s,i)}detectForEachKind(){let t=0,e=0;for(;;){let r=this.stream.peekNonWhitespace(t);if(!r)return null;if(r.type==="LParen"||r.type==="LBracket"||r.type==="LBrace")e+=1;else if(r.type==="RParen"||r.type==="RBracket"||r.type==="RBrace"){if(e===0)return null;e-=1}if(e===0){if(r.type==="Semicolon")return null;if(r.type==="Identifier"&&(r.value==="in"||r.value==="of"))return r.value}t+=1}}parseForEachTarget(){let t=this.stream.peek();if(!t)throw new Error("Expected for-each target");if(t.type!=="Identifier")throw new Error("for-in/of target must be an identifier");return new y(this.stream.next().value)}parseForClause(){return this.isAssignmentStart()?this.parseAssignmentExpression():this.parseExpression()}parseAssignmentExpression(){let t=this.parseAssignmentTarget();this.stream.skipWhitespace();let e=this.parseAssignmentOperator();this.stream.skipWhitespace();let r=this.parseExpression();return new N(t,r,e)}parseAssignmentOperator(){let t=this.stream.peek();if(!t)throw new Error("Expected assignment operator");if(t.type==="Equals")return this.stream.next(),"=";if(t.type==="Plus"||t.type==="Minus"||t.type==="Star"||t.type==="Slash"){let e=this.stream.next();return this.stream.expect("Equals"),e.type==="Plus"?"+=":e.type==="Minus"?"-=":e.type==="Star"?"*=":"/="}throw new Error("Expected assignment operator")}parseTryBlock(){this.stream.expect("Try");let t=this.parseBlock({allowDeclarations:!1});this.stream.skipWhitespace(),this.stream.expect("Catch"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let e=this.stream.expect("Identifier").value;this.stream.skipWhitespace(),this.stream.expect("RParen");let r=this.parseBlock({allowDeclarations:!1});return new ae(t,e,r)}parseConstructBlock(){this.stream.expect("Construct");let t=this.parseBlock({allowDeclarations:!1});return t.type="Construct",t}parseDestructBlock(){this.stream.expect("Destruct");let t=this.parseBlock({allowDeclarations:!1});return t.type="Destruct",t}parseQueryExpression(){this.stream.expect("Question");let t="self";this.stream.peek()?.type==="Greater"?(this.stream.next(),t="descendant"):this.stream.peek()?.type==="Less"&&(this.stream.next(),t="ancestor"),this.stream.skipWhitespace(),this.stream.expect("LParen");let e=this.readSelectorUntil("RParen");return new he(t,e)}parseFunctionDeclaration(){let t=!1,e=this.stream.peekNonWhitespace(0);this.isAsyncToken(e)&&(this.stream.next(),this.stream.skipWhitespace(),t=!0);let r=this.stream.expect("Identifier").value;this.stream.skipWhitespace();let s=this.parseFunctionParams();this.stream.skipWhitespace();let i=this.parseFunctionBlockWithAwait(t);return new I(r,s,i,t)}parseReturnStatement(){if(this.stream.expect("Return"),this.stream.skipWhitespace(),this.stream.peek()?.type==="Semicolon")return this.stream.next(),new L;let t=this.parseExpression();return this.stream.skipWhitespace(),this.stream.expect("Semicolon"),new L(t)}parseAssertStatement(){this.stream.expect("Assert"),this.stream.skipWhitespace();let t=this.parseExpression();return this.consumeStatementTerminator(),new te(t)}parseBreakStatement(){return this.stream.expect("Break"),this.consumeStatementTerminator(),new X}parseContinueStatement(){return this.stream.expect("Continue"),this.consumeStatementTerminator(),new ee}parseArrowFunctionExpression(t=!1){let e=this.parseFunctionParams();if(this.stream.skipWhitespace(),this.stream.expect("Arrow"),this.stream.skipWhitespace(),this.stream.peek()?.type==="LBrace"){let s=this.parseFunctionBlockWithAwait(t);return new W(e,s,t)}let r=this.parseArrowExpressionBody(t);return new W(e,r,t)}parseFunctionParams(){this.stream.expect("LParen");let t=[],e=!1;for(;;){this.stream.skipWhitespace();let r=this.stream.peek();if(!r)throw new Error("Unterminated function parameters");if(r.type==="RParen"){this.stream.next();break}if(r.type==="Ellipsis"){if(e)throw new Error("Function parameters can only include one rest parameter");this.stream.next(),this.stream.skipWhitespace();let n=this.stream.expect("Identifier").value;if(t.push({name:n,rest:!0}),e=!0,this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma")throw new Error("Rest parameter must be last in function parameters");this.stream.expect("RParen");break}let s=this.stream.expect("Identifier").value;this.stream.skipWhitespace();let i;if(this.stream.peek()?.type==="Equals"&&(this.stream.next(),this.stream.skipWhitespace(),i=this.parseExpression()),t.push(i?{name:s,defaultValue:i}:{name:s}),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RParen"){this.stream.next();break}throw new Error("Expected ',' or ')' in function parameters")}return t}readSelectorUntil(t){let e="",r=!1;for(;;){let s=this.stream.peek();if(!s)throw new Error("Unterminated selector");if(s.type===t){this.stream.next();break}if(s.type==="Whitespace"){this.stream.next(),r&&e[e.length-1]!==" "&&(e+=" ");continue}r=!0,e+=this.stream.next().value}return e.trim()}parseIdentifierPath(){let t=this.stream.expect("Identifier").value;for(;this.stream.peek()?.type==="Dot";){this.stream.next();let e=this.stream.expect("Identifier").value;t=`${t}.${e}`}return t}};var Q=class p{constructor(t){this.parent=t;this.root=t?t.root:this}data=new Map;root;listeners=new Map;anyListeners=new Set;isEachItem=!1;createChild(){return new p(this)}get(t){return this.getPath(t)}set(t,e){this.setPath(t,e)}hasKey(t){let r=t.split(".")[0];return r?this.data.has(r):!1}getPath(t){let e=t.startsWith("parent.")||t.startsWith("root.")||t.startsWith("self."),{targetScope:r,targetPath:s}=this.resolveScope(t);if(!r||!s)return;let i=this.getLocalPathValue(r,s);if(e||i!==void 0)return i;let n=r.parent;for(;n;){let a=this.getLocalPathValue(n,s);if(a!==void 0)return a;n=n.parent}}setPath(t,e){let r=t.startsWith("parent.")||t.startsWith("root.")||t.startsWith("self."),{targetScope:s,targetPath:i}=this.resolveScope(t);if(!s||!i)return;let n=r?s:this.findNearestScopeWithKey(s,i)??s,a=i.split("."),o=a[0];if(!o)return;if(a.length===1){n.data.set(o,e),n.emitChange(i);return}let c=n.data.get(o);(c==null||typeof c!="object")&&(c={},n.data.set(o,c));let l=c;for(let f=1;f<a.length-1;f+=1){let g=a[f];if(!g)return;(l[g]==null||typeof l[g]!="object")&&(l[g]={}),l=l[g]}let h=a[a.length-1];h&&(l[h]=e,n.emitChange(i))}on(t,e){let r=t.trim();if(!r)return;let s=this.listeners.get(r)??new Set;s.add(e),this.listeners.set(r,s)}off(t,e){let r=t.trim(),s=this.listeners.get(r);s&&(s.delete(e),s.size===0&&this.listeners.delete(r))}onAny(t){this.anyListeners.add(t)}offAny(t){this.anyListeners.delete(t)}emitChange(t){let e=t.trim();if(!e)return;this.listeners.get(e)?.forEach(s=>s());let r=e.split(".")[0];r&&r!==e&&this.listeners.get(r)?.forEach(s=>s()),this.anyListeners.forEach(s=>s())}resolveScope(t){let e=this,r=t;for(;r.startsWith("parent.");)e=e?.parent,r=r.slice(7);for(r.startsWith("root.")&&(e=e?.root,r=r.slice(5));r.startsWith("self.");)e=e??this,r=r.slice(5);return{targetScope:e,targetPath:r}}getLocalPathValue(t,e){let r=e.split("."),s=r[0];if(!s)return;let i=t.data.get(s);for(let n=1;n<r.length;n+=1){if(i==null)return;let a=r[n];if(!a)return;i=i[a]}return i}findNearestScopeWithKey(t,e){let r=e.split(".")[0];if(!r)return;let s=t;for(;s;){if(s.data.has(r))return s;s=s.parent}}};function Ae(p){return p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement?p.value:p.textContent??""}function Ne(p,t){if(p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement){p.value=t,p.setAttribute("value",t);return}if(p instanceof HTMLSelectElement){p.value=t;return}p instanceof HTMLElement&&p.querySelector("*")||(p.textContent=t)}function fe(p,t,e){let r=t.trim();if(!r)return;let s=Ae(p);e.set(r,s)}function de(p,t,e){let r=t.trim();if(!r)return;let s=e.get(r);s!=null&&Ne(p,String(s))}function we(p,t){let e=p.trim();return e?!!t.get(e):!1}function ve(p,t,e){p.style.display=we(t,e)?"":"none"}function Ee(p,t,e){p.style.display=we(t,e)?"":"none"}function Pe(p){return p.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"")}function T(p,t,e,r){let s=t.trim();if(!s)return;let i=e.get(s),n=i==null?"":String(i);p.innerHTML=r?n:Pe(n)}async function Be(p,t,e,r){if(!globalThis.fetch)throw new Error("fetch is not available");let s=await globalThis.fetch(t.url);if(!s||!s.ok)return;let i=await s.text(),n=Fe(p,t.targetSelector);if(!n){p.dispatchEvent(new CustomEvent("vsn:targetError",{detail:{selector:t.targetSelector}}));return}if(t.swap==="outer"){let a=document.createElement("div");T(a,"__html",{get:()=>i},t.trusted);let o=a.firstElementChild;o&&n.parentNode&&(n.parentNode.replaceChild(o,n),r?.(o));return}T(n,"__html",{get:()=>i},t.trusted),r?.(n)}function Fe(p,t){return t?p.ownerDocument.querySelector(t):p}function P(p,t){let e;return(...r)=>{e&&clearTimeout(e),e=setTimeout(()=>{e=void 0,p(...r)},t)}}var _=class p{static activeEngines=new WeakMap;scopes=new WeakMap;bindBindings=new WeakMap;ifBindings=new WeakMap;showBindings=new WeakMap;htmlBindings=new WeakMap;getBindings=new WeakMap;eachBindings=new WeakMap;lifecycleBindings=new WeakMap;behaviorRegistry=[];behaviorRegistryHashes=new Set;behaviorBindings=new WeakMap;behaviorListeners=new WeakMap;behaviorId=0;codeCache=new Map;behaviorCache=new Map;observer;attributeHandlers=[];globals={};importantFlags=new WeakMap;inlineDeclarations=new WeakMap;flagHandlers=new Map;behaviorModifiers=new Map;pendingAdded=new Set;pendingRemoved=new Set;pendingUpdated=new Set;observerFlush;ignoredAdded=new WeakMap;diagnostics;logger;pendingUses=[];pendingAutoBindToScope=[];scopeWatchers=new WeakMap;executionStack=[];groupProxyCache=new WeakMap;constructor(t={}){this.diagnostics=t.diagnostics??!1,this.logger=t.logger??console,this.registerGlobal("console",console),this.registerFlag("important"),this.registerFlag("trusted"),this.registerFlag("debounce",{onEventBind:({args:e})=>({debounceMs:typeof e=="number"?e:200})}),this.registerFlag("prevent",{onEventBefore:({event:e})=>{e?.preventDefault()}}),this.registerFlag("stop",{onEventBefore:({event:e})=>{e?.stopPropagation()}}),this.registerFlag("self",{onEventBefore:({event:e,element:r})=>{let s=e?.target;return s instanceof Node?s===r:!1}}),this.registerFlag("outside",{onEventBind:({element:e})=>({listenerTarget:e.ownerDocument}),onEventBefore:({event:e,element:r})=>{let s=e?.target;return s instanceof Node?!r.contains(s):!1}}),this.registerFlag("once",{onEventBind:()=>({options:{once:!0}})}),this.registerFlag("passive",{onEventBind:()=>({options:{passive:!0}})}),this.registerFlag("capture",{onEventBind:()=>({options:{capture:!0}})}),this.registerFlag("shift",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"shift")}),this.registerFlag("ctrl",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"ctrl")}),this.registerFlag("control",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"ctrl")}),this.registerFlag("alt",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"alt")}),this.registerFlag("meta",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"meta")}),this.registerFlag("enter",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"enter")}),this.registerFlag("escape",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"escape")}),this.registerFlag("esc",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"escape")}),this.registerFlag("tab",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"tab")}),this.registerFlag("space",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"space")}),this.registerFlag("up",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"arrowup")}),this.registerFlag("down",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"arrowdown")}),this.registerFlag("left",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"arrowleft")}),this.registerFlag("right",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"arrowright")}),this.registerFlag("arrowup",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"arrowup")}),this.registerFlag("arrowdown",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"arrowdown")}),this.registerFlag("arrowleft",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"arrowleft")}),this.registerFlag("arrowright",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"arrowright")}),this.registerFlag("delete",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"delete")}),this.registerFlag("backspace",{onEventBefore:({event:e})=>this.matchesKeyFlag(e,"backspace")}),this.registerGlobal("list",{async map(e,r){if(!Array.isArray(e)||typeof r!="function")return[];let s=[];for(let i=0;i<e.length;i+=1)s.push(await r(e[i],i));return s},async filter(e,r){if(!Array.isArray(e)||typeof r!="function")return[];let s=[];for(let i=0;i<e.length;i+=1)await r(e[i],i)&&s.push(e[i]);return s},async reduce(e,r,s){if(!Array.isArray(e)||typeof r!="function")return s;let i=arguments.length>2,n=i?s:e[0],a=i?0:1;for(let o=a;o<e.length;o+=1)n=await r(n,e[o],o);return n}}),this.registerDefaultAttributeHandlers(),this.registerFlag("int",{transformValue:(e,r)=>this.coerceInt(r)}),this.registerFlag("float",{transformValue:(e,r)=>this.coerceFloat(r)}),this.registerBehaviorModifier("group",{onConstruct:({args:e,scope:r,rootScope:s,behavior:i,element:n})=>{let a=typeof e=="string"?e:void 0;if(!a)return;let o=this.getGroupTargetScope(n,i,r,s),c=o.getPath?.(a),l=Array.isArray(c)?c:[],h=this.getGroupProxy(r);l.includes(h)?Array.isArray(c)||o.setPath?.(a,l):(l.push(h),o.setPath?.(a,l))},onUnbind:({args:e,scope:r,rootScope:s,behavior:i,element:n})=>{let a=typeof e=="string"?e:void 0;if(!a)return;let o=this.getGroupTargetScope(n,i,r,s),c=o.getPath?.(a);if(!Array.isArray(c))return;let l=this.getGroupProxy(r),h=c.filter(f=>f!==l);h.length!==c.length&&o.setPath?.(a,h)}})}getGroupTargetScope(t,e,r,s){let i=s??r;if(e.parentSelector){let n=t.closest(e.parentSelector);n&&(i=this.getScope(n))}return i}getGroupProxy(t){let e=this.groupProxyCache.get(t);if(e)return e;let r=new Proxy({},{get:(s,i)=>{if(typeof i!="symbol")return i==="__scope"?t:t.getPath(String(i))},set:(s,i,n)=>typeof i=="symbol"?!1:(t.setPath(String(i),n),!0),has:(s,i)=>typeof i=="symbol"?!1:t.getPath(String(i))!==void 0,getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),ownKeys:()=>[]});return this.groupProxyCache.set(t,r),r}async mount(t){let e=t.ownerDocument,r=p.activeEngines.get(e);r&&r!==this&&r.disconnectObserver(),p.activeEngines.set(e,this);let s=[t,...Array.from(t.querySelectorAll("*"))];for(let i of s){if(!this.hasVsnAttributes(i))continue;let n=this.findParentScope(i);this.getScope(i,n),this.attachAttributes(i),this.runConstruct(i)}await this.applyBehaviors(t),this.attachObserver(t)}unmount(t){this.runDestruct(t),this.disconnectObserver()}registerBehaviors(t){let e=new D(t,{customFlags:new Set(this.flagHandlers.keys()),behaviorFlags:new Set(this.behaviorModifiers.keys())}).parseProgram();for(let r of e.uses){if(r.flags?.wait){this.pendingUses.push(this.waitForUseGlobal(r));continue}let s=this.resolveGlobalPath(r.name);if(s===void 0){console.warn(`vsn: global '${r.name}' not found`);continue}this.registerGlobal(r.alias,s)}for(let r of e.behaviors)this.collectBehavior(r)}registerGlobal(t,e){this.globals[t]=e}registerGlobals(t){Object.assign(this.globals,t)}registerFlag(t,e={}){this.flagHandlers.set(t,e)}registerBehaviorModifier(t,e={}){if(new Set(["important","trusted","debounce"]).has(t))throw new Error(`Behavior modifier '${t}' is reserved`);this.behaviorModifiers.set(t,e)}getRegistryStats(){return{behaviorCount:this.behaviorRegistry.length,behaviorCacheSize:this.behaviorCache.size}}registerAttributeHandler(t){this.attributeHandlers.push(t)}resolveGlobalPath(t){let e=t.split("."),r=e[0];if(!r)return;let s=globalThis[r];for(let i=1;i<e.length;i+=1){let n=e[i];if(!n)return;s=s?.[n]}return s}async waitForUses(){for(;this.pendingUses.length>0;){let t=this.pendingUses;this.pendingUses=[],await Promise.all(t)}}waitForUseGlobal(t){let e=t.flagArgs?.wait??{},r=e.timeoutMs??1e4,s=e.intervalMs??100,i=1e3,n=this.resolveGlobalPath(t.name);return n!==void 0?(this.registerGlobal(t.alias,n),Promise.resolve()):r<=0?(this.emitUseError(t.name,new Error(`vsn: global '${t.name}' not found`)),Promise.resolve()):new Promise(a=>{let o=0,c=s,l=()=>{let h=this.resolveGlobalPath(t.name);if(h!==void 0){this.registerGlobal(t.alias,h),a();return}if(o>=r){this.emitUseError(t.name,new Error(`vsn: global '${t.name}' not found`)),a();return}let f=Math.min(c,r-o);setTimeout(()=>{o+=f,c=Math.min(c*2,i),l()},f)};l()})}getScope(t,e){let r=this.scopes.get(t);if(r)return r;let s=new Q(e??this.findParentScope(t));return this.scopes.set(t,s),s}evaluate(t){let e=this.getScope(t),r=this.bindBindings.get(t);r&&(r.direction==="from"||r.direction==="both")&&de(t,r.expr,e);let s=this.ifBindings.get(t);s&&t instanceof HTMLElement&&ve(t,s,e);let i=this.showBindings.get(t);i&&t instanceof HTMLElement&&Ee(t,i,e);let n=this.htmlBindings.get(t);n&&t instanceof HTMLElement&&(T(t,n.expr,e,n.trusted),n.trusted&&this.handleTrustedHtml(t))}attachObserver(t){this.observer||(this.observerFlush=P(()=>this.flushObserverQueue(),10),this.observer=new MutationObserver(e=>{for(let r of e){r.type==="attributes"&&r.target instanceof Element&&this.pendingUpdated.add(r.target);for(let s of Array.from(r.addedNodes))if(s&&s.nodeType===1){let i=s;if(this.ignoredAdded.has(i)){this.ignoredAdded.delete(i);continue}this.pendingAdded.add(i)}for(let s of Array.from(r.removedNodes))s&&s.nodeType===1&&this.pendingRemoved.add(s)}this.observerFlush?.()}),this.observer.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class"]}))}disconnectObserver(){this.observer?.disconnect(),this.observer=void 0,this.pendingAdded.clear(),this.pendingRemoved.clear(),this.pendingUpdated.clear()}flushObserverQueue(){let t=Array.from(this.pendingRemoved);this.pendingRemoved.clear();for(let s of t)this.handleRemovedNode(s);let e=Array.from(this.pendingUpdated);this.pendingUpdated.clear();for(let s of e)this.handleUpdatedNode(s);let r=Array.from(this.pendingAdded);this.pendingAdded.clear();for(let s of r)this.handleAddedNode(s)}handleRemovedNode(t){this.lifecycleBindings.has(t)&&this.runDestruct(t),this.behaviorBindings.has(t)&&this.runBehaviorDestruct(t),this.cleanupScopeWatchers(t),this.cleanupBehaviorListeners(t);for(let e of Array.from(t.querySelectorAll("*")))this.lifecycleBindings.has(e)&&this.runDestruct(e),this.behaviorBindings.has(e)&&this.runBehaviorDestruct(e),this.cleanupScopeWatchers(e),this.cleanupBehaviorListeners(e)}handleAddedNode(t){let e=[t,...Array.from(t.querySelectorAll("*"))];for(let r of e){if(!this.hasVsnAttributes(r))continue;let s=this.findParentScope(r);this.getScope(r,s),this.attachAttributes(r),this.runConstruct(r)}this.applyBehaviors(t)}handleUpdatedNode(t){let e=[t,...Array.from(t.querySelectorAll("*"))];for(let r of e)this.reapplyBehaviorsForElement(r)}async applyBehaviors(t){if(await this.waitForUses(),this.behaviorRegistry.length>0){let e=[t,...Array.from(t.querySelectorAll("*"))];for(let r of e)await this.reapplyBehaviorsForElement(r)}this.flushAutoBindQueue()}async reapplyBehaviorsForElement(t){if(this.behaviorRegistry.length===0)return;let e=this.behaviorBindings.get(t)??new Set,r=this.getScope(t),s=this.behaviorRegistry.filter(n=>t.matches(n.selector)).sort((n,a)=>n.specificity!==a.specificity?n.specificity-a.specificity:n.order-a.order);for(let n of s)e.has(n.id)||await this.applyBehaviorForElement(n,t,r,e);let i=new Set(s.map(n=>n.id));for(let n of this.behaviorRegistry)e.has(n.id)&&!i.has(n.id)&&this.unbindBehaviorForElement(n,t,r,e);this.behaviorBindings.set(t,e)}async applyBehaviorForElement(t,e,r,s){s.add(t.id);let i=this.getBehaviorRootScope(e,t);this.applyBehaviorFunctions(e,r,t.functions,i),await this.applyBehaviorDeclarations(e,r,t.declarations,i),await this.applyBehaviorModifierHook("onBind",t,e,r,i),t.construct&&await this.safeExecuteBlock(t.construct,r,e,i),await this.applyBehaviorModifierHook("onConstruct",t,e,r,i);for(let n of t.onBlocks)this.attachBehaviorOnHandler(e,n.event,n.body,n.flags,n.flagArgs,n.args,t.id,i);this.logDiagnostic("bind",e,t)}unbindBehaviorForElement(t,e,r,s){s.delete(t.id);let i=this.getBehaviorRootScope(e,t);t.destruct&&this.safeExecuteBlock(t.destruct,r,e,i),this.applyBehaviorModifierHook("onDestruct",t,e,r,i);let n=this.behaviorListeners.get(e),a=n?.get(t.id);if(a){for(let o of a)o.target.removeEventListener(o.event,o.handler,o.options);n?.delete(t.id)}this.applyBehaviorModifierHook("onUnbind",t,e,r,i),this.logDiagnostic("unbind",e,t)}runBehaviorDestruct(t){let e=this.behaviorBindings.get(t);if(!e)return;let r=this.getScope(t);for(let s of this.behaviorRegistry){if(!e.has(s.id)||!s.destruct&&!this.behaviorHasModifierHooks(s))continue;let i=this.getBehaviorRootScope(t,s);s.destruct&&this.safeExecuteBlock(s.destruct,r,t,i),this.applyBehaviorModifierHook("onDestruct",s,t,r,i),this.applyBehaviorModifierHook("onUnbind",s,t,r,i)}}attachAttributes(t){let e=this.getScope(t);for(let r of t.getAttributeNames()){if(!r.startsWith("vsn-"))continue;let s=t.getAttribute(r)??"";for(let i of this.attributeHandlers){if(!i.match(r))continue;if(i.handle(t,r,s,e)!==!1)break}}}setLifecycle(t,e){let r=this.lifecycleBindings.get(t)??{};this.lifecycleBindings.set(t,{...r,...e})}runConstruct(t){let e=this.lifecycleBindings.get(t);if(!e?.construct)return;let r=this.getScope(t);this.safeExecute(e.construct,r,t)}runDestruct(t){let e=this.lifecycleBindings.get(t);if(!e?.destruct)return;let r=this.getScope(t);this.safeExecute(e.destruct,r,t)}parseEachExpression(t){let[e,r]=t.split(/\s+as\s+/);if(!e||!r)return null;let s=e.trim(),i=r.split(",").map(o=>o.trim()).filter(Boolean);if(!s||i.length===0)return null;let n=i[0]??"",a=i[1];return{listExpr:s,itemName:n,...a?{indexName:a}:{}}}renderEach(t){let e=this.eachBindings.get(t);if(!e||!(t instanceof HTMLTemplateElement))return;let r=t.parentElement;if(!r)return;for(let a of e.rendered)this.handleRemovedNode(a),a.parentNode&&a.parentNode.removeChild(a);e.rendered=[];let s=this.getScope(t),i=s.get(e.listExpr);if(!Array.isArray(i))return;let n=[];i.forEach((a,o)=>{let c=t.content.cloneNode(!0),l=Array.from(c.children),h=new Q(s);h.isEachItem=!0,h.setPath(`self.${e.itemName}`,a),e.indexName&&h.setPath(`self.${e.indexName}`,o);for(let f of l)this.getScope(f,h);r.insertBefore(c,t);for(let f of l){this.ignoredAdded.set(f,!0),n.push(f),this.handleAddedNode(f),this.evaluate(f);for(let g of Array.from(f.querySelectorAll("*")))this.evaluate(g)}}),e.rendered=n}attachBindInputHandler(t,e){if(!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement))return;let r=()=>{let s=this.getScope(t);fe(t,e,s)};t.addEventListener("input",r),t.addEventListener("change",r)}parseBindDirection(t){return t.includes(":from")?"from":t.includes(":to")?"to":"auto"}resolveBindConfig(t,e,r,s){return s!=="auto"?{direction:s,seedFromScope:!1,syncToScope:s==="to"||s==="both",deferToScope:!1}:this.isInEachScope(r)?{direction:"both",seedFromScope:!1,syncToScope:!1,deferToScope:!1}:this.isFormControl(t)?this.hasScopeValue(r,e)?{direction:"both",seedFromScope:!0,syncToScope:!1,deferToScope:!1}:{direction:"both",seedFromScope:!1,syncToScope:!1,deferToScope:!0}:this.hasScopeValue(r,e)?{direction:"both",seedFromScope:!1,syncToScope:!1,deferToScope:!1}:this.hasElementValue(t)?{direction:"both",seedFromScope:!1,syncToScope:!1,deferToScope:!0}:{direction:"both",seedFromScope:!1,syncToScope:!1,deferToScope:!1}}isFormControl(t){return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement}hasScopeValue(t,e){let r=e.trim();if(!r)return!1;let s=t.get(r);return s!=null}hasElementValue(t){return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement?t.value.length>0:(t.textContent??"").trim().length>0}coerceInt(t){if(t==null||t==="")return t;let e=typeof t=="number"?t:Number.parseInt(String(t),10);return Number.isNaN(e)?t:e}coerceFloat(t){if(t==null||t==="")return t;let e=typeof t=="number"?t:Number.parseFloat(String(t));return Number.isNaN(e)?t:e}isInEachScope(t){let e=t;for(;e;){if(e.isEachItem)return!0;e=e.parent}return!1}flushAutoBindQueue(){if(this.pendingAutoBindToScope.length===0)return;let t=this.pendingAutoBindToScope;this.pendingAutoBindToScope=[];for(let e of t)e.element.isConnected&&(this.hasScopeValue(e.scope,e.expr)||this.hasElementValue(e.element)&&fe(e.element,e.expr,e.scope))}hasVsnAttributes(t){return t.getAttributeNames().some(e=>e.startsWith("vsn-"))}markInlineDeclaration(t,e){let r=this.inlineDeclarations.get(t)??new Set;r.add(e),this.inlineDeclarations.set(t,r)}isInlineDeclaration(t,e){let r=this.inlineDeclarations.get(t);return r?r.has(e):!1}findParentScope(t){let e=t.parentElement;for(;e;){let r=this.scopes.get(e);if(r)return r;e=e.parentElement}}watch(t,e,r,s){let i=e.trim();if(!i)return;let n=i.split(".")[0];if(!n)return;let a=t;for(;a&&!a.hasKey(n);)a=a.parent;if(a){a.on(i,r),s&&this.trackScopeWatcher(s,a,"path",r,i);return}let o=t;for(;o;)o.on(i,r),s&&this.trackScopeWatcher(s,o,"path",r,i),o=o.parent}watchWithDebounce(t,e,r,s,i){let n=s?P(r,s):r;this.watch(t,e,n,i)}watchAllScopes(t,e,r,s){let i=r?P(e,r):e,n=t;for(;n;)n.onAny(i),s&&this.trackScopeWatcher(s,n,"any",i),n=n.parent}trackScopeWatcher(t,e,r,s,i){let n=this.scopeWatchers.get(t)??[];n.push({scope:e,kind:r,handler:s,...i?{key:i}:{}}),this.scopeWatchers.set(t,n)}cleanupScopeWatchers(t){let e=this.scopeWatchers.get(t);if(e){for(let r of e){if(r.kind==="any"){r.scope.offAny(r.handler);continue}r.key&&r.scope.off(r.key,r.handler)}this.scopeWatchers.delete(t)}}cleanupBehaviorListeners(t){let e=this.behaviorListeners.get(t);if(e){for(let r of e.values())for(let s of r)s.target.removeEventListener(s.event,s.handler,s.options);e.clear(),this.behaviorListeners.delete(t),this.behaviorBindings.delete(t)}}parseOnAttribute(t,e){if(!t.startsWith("vsn-on:"))return null;let r=t.slice(7),[s,...i]=r.split("!");if(!s)return null;if(s.includes("."))throw new Error("vsn:on does not support dot modifiers; use !flags instead");let{flagMap:n,flagArgs:a}=this.parseInlineFlags(i);return{event:s,code:e,flags:n,flagArgs:a}}parseInlineFlags(t){let e={},r={};for(let s of t){let i=s.trim();if(!i)continue;let n=i.match(/^([a-zA-Z][\w-]*)(?:\((.+)\))?$/);if(!n)continue;let a=n[1]??"";if(a){if(!this.flagHandlers.has(a))throw new Error(`Unknown flag ${a}`);e[a]=!0,n[2]!==void 0&&(r[a]=this.parseInlineFlagArg(n[2]))}}return{flagMap:e,flagArgs:r}}parseInlineFlagArg(t){let e=t.trim();return e==="true"?!0:e==="false"?!1:/^-?\d+(\.\d+)?$/.test(e)?Number(e):e}describeElement(t){let e=t.tagName.toLowerCase(),r=t.id?`#${t.id}`:"",s=t.classList.length>0?`.${Array.from(t.classList).join(".")}`:"";return`${e}${r}${s}`}logDiagnostic(t,e,r){!this.diagnostics||!this.logger.info||this.logger.info(`vsn:${t}`,{element:this.describeElement(e),selector:r.selector,behaviorId:r.id})}emitError(t,e){let r=this.describeElement(t);this.logger.warn?.("vsn:error",{error:e,selector:r}),t.dispatchEvent(new CustomEvent("vsn:error",{detail:{error:e,selector:r},bubbles:!0}))}emitUseError(t,e){let r=`use:${t}`;this.logger.warn?.("vsn:error",{error:e,selector:r});let s=globalThis.document;s&&typeof s.dispatchEvent=="function"&&s.dispatchEvent(new CustomEvent("vsn:error",{detail:{error:e,selector:r},bubbles:!0}))}attachOnHandler(t,e){let{listenerTarget:r,options:s,debounceMs:i}=this.getEventBindingConfig(t,e.flags,e.flagArgs),n,a=async o=>{if(!t.isConnected){r.removeEventListener(e.event,n,s);return}let c=this.getScope(t);if(this.applyEventFlagBefore(t,c,e.flags,e.flagArgs,o))try{await this.execute(e.code,c,t),this.evaluate(t)}catch(l){this.emitError(t,l)}finally{this.applyEventFlagAfter(t,c,e.flags,e.flagArgs,o)}};n=i?P(a,i):a,r.addEventListener(e.event,n,s)}attachBehaviorOnHandler(t,e,r,s,i,n,a,o){if(e.includes("."))throw new Error("vsn:on does not support dot modifiers; use !flags instead");let{listenerTarget:c,options:l,debounceMs:h}=this.getEventBindingConfig(t,s,i),f=async U=>{let F=this.getScope(t);if(!this.applyEventFlagBefore(t,F,s,i,U))return;let xe=new Map;if(n&&n.length>0){let A=n[0];if(A){xe.set(A,F.getPath(A));let[me]=this.applyEventFlagArgTransforms(t,F,s,i,U);F.setPath(A,me)}}let ke=!1;try{await this.executeBlock(r,F,t,o)}catch(A){ke=!0,this.emitError(t,A)}finally{for(let[A,me]of xe.entries())F.setPath(A,me);this.applyEventFlagAfter(t,F,s,i,U)}ke||this.evaluate(t)},g=h?P(f,h):f;c.addEventListener(e,g,l);let k=this.behaviorListeners.get(t)??new Map,$=k.get(a)??[];$.push({target:c,event:e,handler:g,options:l}),k.set(a,$),this.behaviorListeners.set(t,k)}attachGetHandler(t,e=!1){let r=async()=>{let s=this.getBindings.get(t);if(s)try{await Be(t,s,this.getScope(t),i=>{s.trusted&&this.handleTrustedHtml(i)})}catch(i){console.warn("vsn:getError",i),t.dispatchEvent(new CustomEvent("vsn:getError",{detail:{error:i},bubbles:!0}))}};t.addEventListener("click",s=>{s.target===t&&r()}),e&&Promise.resolve().then(r)}getEventBindingConfig(t,e,r){let s=t,i={},n;for(let a of Object.keys(e)){let o=this.flagHandlers.get(a);if(!o?.onEventBind)continue;let c=o.onEventBind({name:a,args:r[a],element:t,scope:this.getScope(t),rootScope:void 0,event:void 0,engine:this});c&&(c.listenerTarget&&(s=c.listenerTarget),c.options&&(i={...i,...c.options}),c.debounceMs!==void 0&&(n=c.debounceMs))}return{listenerTarget:s,...Object.keys(i).length>0?{options:i}:{},...n!==void 0?{debounceMs:n}:{}}}applyEventFlagBefore(t,e,r,s,i){for(let n of Object.keys(r)){let a=this.flagHandlers.get(n);if(!a?.onEventBefore)continue;if(a.onEventBefore({name:n,args:s[n],element:t,scope:e,rootScope:void 0,event:i,engine:this})===!1)return!1}return!0}applyEventFlagAfter(t,e,r,s,i){for(let n of Object.keys(r)){let a=this.flagHandlers.get(n);a?.onEventAfter&&a.onEventAfter({name:n,args:s[n],element:t,scope:e,rootScope:void 0,event:i,engine:this})}}applyEventFlagArgTransforms(t,e,r,s,i){let n=[i];for(let a of Object.keys(r)){let o=this.flagHandlers.get(a);if(!o?.transformEventArgs)continue;let c=o.transformEventArgs({name:a,args:s[a],element:t,scope:e,rootScope:void 0,event:i,engine:this},n);Array.isArray(c)&&(n=c)}return n}matchesKeyFlag(t,e){if(!(t instanceof KeyboardEvent))return!1;let r={shift:t.shiftKey,ctrl:t.ctrlKey,alt:t.altKey,meta:t.metaKey};if(e in r)return r[e]??!1;let s={escape:"escape",esc:"escape",enter:"enter",tab:"tab",space:"space",spacebar:"space",up:"arrowup",down:"arrowdown",left:"arrowleft",right:"arrowright",arrowup:"arrowup",arrowdown:"arrowdown",arrowleft:"arrowleft",arrowright:"arrowright",delete:"delete",backspace:"backspace"},i=t.key?.toLowerCase()??"";i===" "&&(i="space");let n=s[e]??e;return i===n}async withExecutionElement(t,e){if(!t){await e();return}this.executionStack.push(t);try{await e()}finally{this.executionStack.pop()}}getCurrentElement(){return this.executionStack[this.executionStack.length-1]}async execute(t,e,r,s){let i=this.codeCache.get(t);i||(i=D.parseInline(t),this.codeCache.set(t,i)),await this.withExecutionElement(r,async()=>{let n={scope:e,rootScope:s,globals:this.globals,...r?{element:r}:{}};await i.evaluate(n)})}async executeBlock(t,e,r,s){await this.withExecutionElement(r,async()=>{let i={scope:e,rootScope:s,globals:this.globals,...r?{element:r}:{}};await t.evaluate(i)})}async safeExecute(t,e,r,s){try{await this.execute(t,e,r,s)}catch(i){r&&this.emitError(r,i)}}async safeExecuteBlock(t,e,r,s){try{await this.executeBlock(t,e,r,s)}catch(i){r&&this.emitError(r,i)}}collectBehavior(t,e,r){let s=e?`${e} ${t.selector.selectorText}`:t.selector.selectorText,i=r??e??t.selector.selectorText,n=this.hashBehavior(t),a=`${s}::${i}::${n}`;if(this.behaviorRegistryHashes.has(a))return;let o=this.getCachedBehavior(t),c={id:this.behaviorId+=1,hash:a,selector:s,rootSelector:i,specificity:this.computeSpecificity(s),order:this.behaviorRegistry.length,flags:t.flags??{},flagArgs:t.flagArgs??{},...o,...e?{parentSelector:e}:{}};this.behaviorRegistry.push(c),this.behaviorRegistryHashes.add(a),this.collectNestedBehaviors(t.body,s,i)}collectNestedBehaviors(t,e,r){for(let s of t.statements){if(s instanceof M){this.collectBehavior(s,e,r);continue}if(s instanceof C){this.collectNestedBehaviors(s.body,e,r);continue}s instanceof E&&this.collectNestedBehaviors(s,e,r)}}computeSpecificity(t){let e=t.match(/#[\w-]+/g)?.length??0,r=t.match(/\.[\w-]+/g)?.length??0,s=t.match(/\[[^\]]+\]/g)?.length??0,i=t.match(/:[\w-]+/g)?.length??0,n=t.match(/(^|[\s>+~])([a-zA-Z][\w-]*)/g)?.length??0;return e*100+(r+s+i)*10+n}getBehaviorRootScope(t,e){let r=t.closest(e.rootSelector)??t;return this.getScope(r)}getImportantKey(t){if(t.target instanceof y)return`state:${t.target.name}`;if(t.target instanceof x)return`${t.target.kind}:${t.target.name}`}isImportant(t,e){let r=this.importantFlags.get(t);return r?r.has(e):!1}markImportant(t,e){let r=this.importantFlags.get(t)??new Set;r.add(e),this.importantFlags.set(t,r)}extractLifecycle(t){let e,r;for(let s of t.statements)s instanceof E&&(s.type==="Construct"?e=s:s.type==="Destruct"&&(r=s));return{...e?{construct:e}:{},...r?{destruct:r}:{}}}extractOnBlocks(t){let e=[];for(let r of t.statements)r instanceof C&&e.push({event:r.eventName,body:r.body,flags:r.flags,flagArgs:r.flagArgs,args:r.args});return e}extractDeclarations(t){let e=[];for(let r of t.statements)r instanceof R&&e.push(r);return e}extractFunctionDeclarations(t){let e=[];for(let r of t.statements){if(r instanceof I){e.push({name:r.name,params:r.params,body:r.body});continue}r instanceof N&&r.target instanceof y&&r.value instanceof W&&e.push({name:r.target.name,params:r.value.params,body:r.value.body})}return e}getCachedBehavior(t){let e=this.hashBehavior(t),r=this.behaviorCache.get(e);if(r)return r;let s=this.extractLifecycle(t.body),i={onBlocks:this.extractOnBlocks(t.body),declarations:this.extractDeclarations(t.body),functions:this.extractFunctionDeclarations(t.body),...s};return this.behaviorCache.set(e,i),i}hashBehavior(t){let e=this.normalizeNode(t),r=JSON.stringify(e);return this.hashString(r)}normalizeNode(t){if(!t||typeof t!="object")return t;let e=t.type??"Unknown";return e==="Behavior"?{type:e,selector:t.selector?.selectorText??"",flags:t.flags??{},flagArgs:t.flagArgs??{},body:this.normalizeNode(t.body)}:e==="Selector"?{type:e,selectorText:t.selectorText??""}:e==="Block"||e==="Construct"||e==="Destruct"?{type:e,statements:Array.isArray(t.statements)?t.statements.map(r=>this.normalizeNode(r)):[]}:e==="OnBlock"?{type:e,eventName:t.eventName??"",args:Array.isArray(t.args)?t.args:[],flags:t.flags??{},flagArgs:t.flagArgs??{},body:this.normalizeNode(t.body)}:e==="Declaration"?{type:e,target:this.normalizeNode(t.target),operator:t.operator??"",value:this.normalizeNode(t.value),flags:t.flags??{},flagArgs:t.flagArgs??{}}:e==="Assignment"?{type:e,target:this.normalizeNode(t.target),value:this.normalizeNode(t.value),operator:t.operator??"",prefix:!!t.prefix}:e==="FunctionDeclaration"?{type:e,name:t.name??"",params:Array.isArray(t.params)?t.params.map(r=>({name:r?.name??"",rest:!!r?.rest,defaultValue:this.normalizeNode(r?.defaultValue??null)})):[],body:this.normalizeNode(t.body),isAsync:!!t.isAsync}:e==="FunctionExpression"?{type:e,params:Array.isArray(t.params)?t.params.map(r=>({name:r?.name??"",rest:!!r?.rest,defaultValue:this.normalizeNode(r?.defaultValue??null)})):[],body:this.normalizeNode(t.body),isAsync:!!t.isAsync}:e==="Return"?{type:e,value:this.normalizeNode(t.value??null)}:e==="Assert"?{type:e,test:this.normalizeNode(t.test)}:e==="Break"||e==="Continue"?{type:e}:e==="If"?{type:e,test:this.normalizeNode(t.test),consequent:this.normalizeNode(t.consequent),alternate:this.normalizeNode(t.alternate??null)}:e==="While"?{type:e,test:this.normalizeNode(t.test),body:this.normalizeNode(t.body)}:e==="For"?{type:e,init:this.normalizeNode(t.init??null),test:this.normalizeNode(t.test??null),update:this.normalizeNode(t.update??null),body:this.normalizeNode(t.body)}:e==="ForEach"?{type:e,kind:t.kind??"of",target:this.normalizeNode(t.target),iterable:this.normalizeNode(t.iterable),body:this.normalizeNode(t.body)}:e==="Try"?{type:e,errorName:t.errorName??"",body:this.normalizeNode(t.body),handler:this.normalizeNode(t.handler)}:e==="Identifier"?{type:e,name:t.name??""}:e==="Literal"?{type:e,value:t.value}:e==="TemplateExpression"?{type:e,parts:Array.isArray(t.parts)?t.parts.map(r=>this.normalizeNode(r)):[]}:e==="UnaryExpression"?{type:e,operator:t.operator??"",argument:this.normalizeNode(t.argument)}:e==="BinaryExpression"?{type:e,operator:t.operator??"",left:this.normalizeNode(t.left),right:this.normalizeNode(t.right)}:e==="TernaryExpression"?{type:e,test:this.normalizeNode(t.test),consequent:this.normalizeNode(t.consequent),alternate:this.normalizeNode(t.alternate)}:e==="MemberExpression"?{type:e,target:this.normalizeNode(t.target),property:t.property??"",optional:!!t.optional}:e==="CallExpression"?{type:e,callee:this.normalizeNode(t.callee),args:Array.isArray(t.args)?t.args.map(r=>this.normalizeNode(r)):[]}:e==="AwaitExpression"?{type:e,argument:this.normalizeNode(t.argument)}:e==="Directive"?{type:e,kind:t.kind??"",name:t.name??""}:e==="Query"?{type:e,direction:t.direction??"",selector:t.selector??""}:e==="ArrayExpression"?{type:e,elements:Array.isArray(t.elements)?t.elements.map(r=>this.normalizeNode(r)):[]}:e==="ObjectExpression"?{type:e,entries:Array.isArray(t.entries)?t.entries.map(r=>({key:r?.key??"",computed:!!r?.computed,keyExpr:r?.keyExpr?this.normalizeNode(r.keyExpr):null,value:this.normalizeNode(r?.value)})):[]}:e==="IndexExpression"?{type:e,target:this.normalizeNode(t.target),index:this.normalizeNode(t.index)}:{type:e}}hashString(t){let e=5381;for(let r=0;r<t.length;r+=1)e=(e<<5)+e+t.charCodeAt(r),e|=0;return(e>>>0).toString(16)}applyBehaviorFunctions(t,e,r,s){for(let i of r)this.applyBehaviorFunction(t,e,i,s)}applyBehaviorFunction(t,e,r,s){let i=e.getPath(r.name);if(i!==void 0&&typeof i!="function")throw new Error(`Cannot override non-function '${r.name}' with a function`);let n=async(...a)=>{let o=e.createChild?e.createChild():e,c={scope:o,rootScope:s??o,globals:this.globals,element:t,returnValue:void 0,returning:!1,breaking:!1,continuing:!1},l=new Map;return await this.applyFunctionParams(o,r.params,l,c,a),await r.body.evaluate(c),o===e&&this.restoreFunctionParams(o,r.params,l),c.returnValue};e.setPath(r.name,n)}async applyFunctionParams(t,e,r,s,i){let n=0;for(let a of e){let o=a.name;if(!o)continue;if(r.set(o,t.getPath(o)),a.rest){t.setPath(`self.${o}`,i.slice(n)),n=i.length;continue}let c=i[n];c===void 0&&a.defaultValue&&(c=await a.defaultValue.evaluate(s)),t.setPath(`self.${o}`,c),n+=1}}restoreFunctionParams(t,e,r){for(let s of e){let i=s.name;i&&t.setPath(i,r.get(i))}}async applyBehaviorDeclarations(t,e,r,s){for(let i of r)await this.applyBehaviorDeclaration(t,e,i,s)}async applyBehaviorDeclaration(t,e,r,s){let i={scope:e,rootScope:s,element:t},n=r.operator,a=r.flags.debounce?r.flagArgs.debounce??200:void 0,o=g=>this.applyCustomFlagTransforms(g,t,e,r),c=this.getImportantKey(r);if(!r.flags.important&&c&&this.isImportant(t,c)||c&&this.isInlineDeclaration(t,c))return;if(this.applyCustomFlags(t,e,r),r.target instanceof y){let g=await r.value.evaluate(i),k=this.applyCustomFlagTransforms(g,t,e,r);e.setPath(r.target.name,k),r.flags.important&&c&&this.markImportant(t,c);return}if(!(r.target instanceof x))return;let l=r.target,h=r.value instanceof y?r.value.name:void 0;if(n===":>"){h&&this.applyDirectiveToScope(t,l,h,e,a,s,o),r.flags.important&&c&&this.markImportant(t,c);return}if(n===":="&&h&&this.applyDirectiveToScope(t,l,h,e,a,s,o),!h){let g=await r.value.evaluate(i),k=this.applyCustomFlagTransforms(g,t,e,r);this.setDirectiveValue(t,l,k,r.flags.trusted),(n===":<"||n===":=")&&this.applyDirectiveFromExpression(t,l,r.value,e,r.flags.trusted,a,s),r.flags.important&&c&&this.markImportant(t,c);return}let f=n===":<"||n===":=";this.applyDirectiveFromScope(t,l,h,e,r.flags.trusted,a,f,s),r.flags.important&&c&&this.markImportant(t,c)}applyCustomFlags(t,e,r){if(this.flagHandlers.size!==0)for(let[s,i]of this.flagHandlers)r.flags[s]&&i.onApply?.({name:s,args:r.flagArgs[s],element:t,scope:e,declaration:r})}applyCustomFlagTransforms(t,e,r,s){if(this.flagHandlers.size===0)return t;let i=t;for(let[n,a]of this.flagHandlers)!s.flags[n]||!a.transformValue||(i=a.transformValue({name:n,args:s.flagArgs[n],element:e,scope:r,declaration:s},i));return i}async applyBehaviorModifierHook(t,e,r,s,i){if(this.behaviorModifiers.size!==0)for(let[n,a]of this.behaviorModifiers){if(!e.flags?.[n])continue;let o=a[t];o&&await o({name:n,args:e.flagArgs?.[n],element:r,scope:s,rootScope:i,behavior:e,engine:this})}}behaviorHasModifierHooks(t){if(this.behaviorModifiers.size===0)return!1;let e=t.flags??{};for(let r of Object.keys(e))if(e[r]&&this.behaviorModifiers.has(r))return!0;return!1}applyDirectiveFromScope(t,e,r,s,i,n,a=!0,o){if(e.kind==="attr"&&e.name==="html"&&t instanceof HTMLElement){let l=()=>{let h=r.startsWith("root.")&&o,f=h?o:s,g=h?`self.${r.slice(5)}`:r;T(t,g,f,!!i)};if(l(),i&&this.handleTrustedHtml(t),a){let h=r.startsWith("root.")&&o,f=h?o:s,g=h?r.slice(5):r;this.watchWithDebounce(f,g,l,n,t)}return}let c=()=>{let l=r.startsWith("root.")&&o,h=l?o:s,f=l?`self.${r.slice(5)}`:r,g=h.get(f);g!=null&&this.setDirectiveValue(t,e,g,i)};if(c(),a){let l=r.startsWith("root.")&&o,h=l?o:s,f=l?r.slice(5):r;this.watchWithDebounce(h,f,c,n,t)}}applyDirectiveFromExpression(t,e,r,s,i,n,a){let o=async()=>{let c={scope:s,rootScope:a,element:t},l=await r.evaluate(c);this.setDirectiveValue(t,e,l,i)};o(),this.watchAllScopes(s,()=>{o()},n,t)}applyDirectiveToScope(t,e,r,s,i,n,a){let o=r.startsWith("root.")&&n,c=o?n:s,l=o?`self.${r.slice(5)}`:r;if(e.kind==="attr"&&e.name==="value"){this.applyValueBindingToScope(t,l,i,c,a);return}if(e.kind==="attr"&&e.name==="checked"){this.applyCheckedBindingToScope(t,l,i,c,a);return}let h=this.getDirectiveValue(t,e);if(h!=null){let f=a?a(h):h;c.set(l,f)}}applyCheckedBindingToScope(t,e,r,s,i){if(!(t instanceof HTMLInputElement))return;let n=()=>{let o=s??this.getScope(t),c=i?i(t.checked):t.checked;o.set(e,c)},a=r?P(n,r):n;a(),t.addEventListener("change",a),t.addEventListener("input",a)}applyValueBindingToScope(t,e,r,s,i){if(!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement))return;let n=()=>{let o=s??this.getScope(t),c=t.value,l=i?i(c):c;o.set(e,l)},a=r?P(n,r):n;a(),t.addEventListener("input",a),t.addEventListener("change",a)}setDirectiveValue(t,e,r,s){if(e.kind==="attr"&&e.name==="html"&&t instanceof HTMLElement){let i=r==null?"":String(r);t.innerHTML=s?i:i.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),s&&this.handleTrustedHtml(t);return}if(e.kind==="attr"){if(e.name==="text"&&t instanceof HTMLElement){t.innerText=r==null?"":String(r);return}if(e.name==="content"&&t instanceof HTMLElement){t.textContent=r==null?"":String(r);return}if(e.name==="value"){if(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement){t.value=r==null?"":String(r),t.setAttribute("value",t.value);return}if(t instanceof HTMLSelectElement){t.value=r==null?"":String(r);return}}if(e.name==="checked"&&t instanceof HTMLInputElement){let i=r===!0||r==="true"||r===1||r==="1";t.checked=i,i?t.setAttribute("checked",""):t.removeAttribute("checked");return}t.setAttribute(e.name,r==null?"":String(r));return}e.kind==="style"&&t instanceof HTMLElement&&t.style.setProperty(e.name,r==null?"":String(r))}getDirectiveValue(t,e){if(e.kind==="attr")return e.name==="text"&&t instanceof HTMLElement?t.innerText:e.name==="content"&&t instanceof HTMLElement?t.textContent??"":e.name==="value"&&(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)?t.value:e.name==="checked"&&t instanceof HTMLInputElement?t.checked:t.getAttribute(e.name)??void 0;if(e.kind==="style"&&t instanceof HTMLElement)return t.style.getPropertyValue(e.name)??void 0}handleTrustedHtml(t){let e=Array.from(t.querySelectorAll('script[type="text/vsn"]'));if(e.length===0)return;let r=e.map(s=>s.textContent??"").join(`
|
|
7
|
+
`);r.trim()&&(this.registerBehaviors(r),this.applyBehaviors(t))}registerDefaultAttributeHandlers(){this.registerAttributeHandler({id:"vsn-bind",match:t=>t.startsWith("vsn-bind"),handle:(t,e,r,s)=>{let i=this.parseBindDirection(e),n=this.resolveBindConfig(t,r,s,i),a=n.direction,o=i==="auto";this.bindBindings.set(t,{expr:r,direction:a,auto:o}),!o&&(a==="to"||a==="both")&&this.markInlineDeclaration(t,`state:${r}`),n.seedFromScope&&de(t,r,s),n.deferToScope?this.pendingAutoBindToScope.push({element:t,expr:r,scope:s}):n.syncToScope&&fe(t,r,s),(a==="to"||a==="both")&&this.attachBindInputHandler(t,r),(a==="from"||a==="both")&&this.watch(s,r,()=>de(t,r,s),t)}}),this.registerAttributeHandler({id:"vsn-if",match:t=>t==="vsn-if",handle:(t,e,r,s)=>{this.ifBindings.set(t,r),t instanceof HTMLElement&&ve(t,r,s),this.watch(s,r,()=>this.evaluate(t),t)}}),this.registerAttributeHandler({id:"vsn-show",match:t=>t==="vsn-show",handle:(t,e,r,s)=>{this.showBindings.set(t,r),t instanceof HTMLElement&&Ee(t,r,s),this.watch(s,r,()=>this.evaluate(t),t)}}),this.registerAttributeHandler({id:"vsn-html",match:t=>t.startsWith("vsn-html"),handle:(t,e,r,s)=>{let i=e.includes("!trusted");this.htmlBindings.set(t,{expr:r,trusted:i}),this.markInlineDeclaration(t,"attr:html"),t instanceof HTMLElement&&(T(t,r,s,i),i&&this.handleTrustedHtml(t)),this.watch(s,r,()=>this.evaluate(t),t)}}),this.registerAttributeHandler({id:"vsn-each",match:t=>t==="vsn-each",handle:(t,e,r,s)=>{let i=this.parseEachExpression(r);i&&(this.eachBindings.set(t,{...i,rendered:[]}),this.renderEach(t),this.watch(s,i.listExpr,()=>this.renderEach(t),t))}}),this.registerAttributeHandler({id:"vsn-get",match:t=>t.startsWith("vsn-get"),handle:(t,e)=>{let r=e.includes("!trusted"),s=e.includes("!load"),i=t.getAttribute(e)??"",n=t.getAttribute("vsn-target")??void 0,a=t.getAttribute("vsn-swap")??"inner",o={url:i,swap:a,trusted:r,...n?{targetSelector:n}:{}};this.getBindings.set(t,o),this.attachGetHandler(t,s)}}),this.registerAttributeHandler({id:"vsn-construct",match:t=>t==="vsn-construct",handle:(t,e,r)=>{this.setLifecycle(t,{construct:r})}}),this.registerAttributeHandler({id:"vsn-destruct",match:t=>t==="vsn-destruct",handle:(t,e,r)=>{this.setLifecycle(t,{destruct:r})}}),this.registerAttributeHandler({id:"vsn-on",match:t=>t.startsWith("vsn-on:"),handle:(t,e,r)=>{let s=this.parseOnAttribute(e,r);s&&this.attachOnHandler(t,s)}})}};var Ce="0.1.0";function We(p){return new D(p).parseProgram()}typeof window<"u"&&(window.parseCFS=We);function De(p=document){if(typeof document>"u")return null;let t=new _;globalThis.VSNEngine=t;let e=typeof performance<"u"&&performance.now?performance.now():Date.now(),r=()=>{let s=p instanceof Document?p.body:p;if(s){let i=globalThis.VSNPlugins;if(i&&typeof i=="object")for(let c of Object.values(i))typeof c=="function"&&c(t);let n=Array.from(document.querySelectorAll('script[type="text/vsn"]')).map(c=>c.textContent??"").join(`
|
|
8
|
+
`);n.trim()&&t.registerBehaviors(n),t.mount(s);let a=typeof performance<"u"&&performance.now?performance.now():Date.now(),o=Math.round(a-e);console.log(`Took ${o}ms to start up VSN.js. https://www.vsnjs.com/ v${Ce}`)}};return document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>setTimeout(r,0),{once:!0}):setTimeout(r,0),t}typeof document<"u"&&document.querySelector("script[auto-mount]")&&De();export{pe as ArrayExpression,V as ArrayPattern,ye as AssertError,te as AssertNode,N as AssignmentNode,K as AwaitExpression,m as BaseNode,M as BehaviorNode,b as BinaryExpression,E as BlockNode,X as BreakNode,S as CallExpression,ee as ContinueNode,R as DeclarationNode,x as DirectiveExpression,_ as Engine,ie as ForEachNode,ne as ForNode,I as FunctionDeclarationNode,W as FunctionExpression,y as IdentifierExpression,re as IfNode,w as IndexExpression,q as Lexer,B as LiteralExpression,v as MemberExpression,le as ObjectExpression,O as ObjectPattern,C as OnBlockNode,D as Parser,Z as ProgramNode,he as QueryExpression,H as RestElement,L as ReturnNode,Y as SelectorNode,j as SpreadElement,oe as TemplateExpression,ce as TernaryExpression,be as TokenType,ae as TryNode,z as UnaryExpression,J as UseNode,Ce as VERSION,se as WhileNode,De as autoMount,We as parseCFS};
|
|
9
9
|
//# sourceMappingURL=index.min.js.map
|