snapback2 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +127 -0
  2. package/bin/snapback2.mjs +36 -0
  3. package/dist/api.d.ts +20 -0
  4. package/dist/assets.d.ts +34 -0
  5. package/dist/client-assets.d.ts +26 -0
  6. package/dist/client-offline.d.ts +94 -0
  7. package/dist/client-outbox.d.ts +58 -0
  8. package/dist/client-upload.d.ts +41 -0
  9. package/dist/client-wire.d.ts +41 -0
  10. package/dist/client.d.ts +12 -0
  11. package/dist/client.mjs +5 -0
  12. package/dist/client.mjs.map +7 -0
  13. package/dist/compiler-core.mjs +60 -0
  14. package/dist/compiler-core.mjs.map +7 -0
  15. package/dist/compiler-lib.d.ts +71 -0
  16. package/dist/compiler.mjs +5 -0
  17. package/dist/compiler.mjs.map +7 -0
  18. package/dist/drain.d.ts +33 -0
  19. package/dist/expo/files.d.ts +3 -0
  20. package/dist/expo/index.d.ts +16 -0
  21. package/dist/expo/token-store.d.ts +7 -0
  22. package/dist/expo/witness.d.ts +28 -0
  23. package/dist/expo/witness.mjs +2 -0
  24. package/dist/expo/witness.mjs.map +7 -0
  25. package/dist/expo.d.ts +4 -0
  26. package/dist/expo.mjs +9 -0
  27. package/dist/expo.mjs.map +7 -0
  28. package/dist/guide/auth.md +89 -0
  29. package/dist/guide/effects.md +52 -0
  30. package/dist/guide/families.json +446 -0
  31. package/dist/guide/grammar.md +52 -0
  32. package/dist/guide/live-query.md +27 -0
  33. package/dist/guide/offline.md +75 -0
  34. package/dist/guide/personas.md +15 -0
  35. package/dist/guide/quarry.md +297 -0
  36. package/dist/guide/testing.md +57 -0
  37. package/dist/index.d.ts +362 -0
  38. package/dist/index.mjs +2 -0
  39. package/dist/index.mjs.map +7 -0
  40. package/dist/offline-protocol.d.ts +180 -0
  41. package/dist/offline-schema.d.ts +1 -0
  42. package/dist/offline.d.ts +177 -0
  43. package/dist/react-core.d.ts +91 -0
  44. package/dist/react-core.mjs +2 -0
  45. package/dist/react-core.mjs.map +7 -0
  46. package/dist/react-native/components.d.ts +23 -0
  47. package/dist/react-native/files.d.ts +43 -0
  48. package/dist/react-native/source.d.ts +16 -0
  49. package/dist/react-native.d.ts +4 -0
  50. package/dist/react-native.mjs +2 -0
  51. package/dist/react-native.mjs.map +7 -0
  52. package/dist/react.d.ts +19 -0
  53. package/dist/react.mjs +2 -0
  54. package/dist/react.mjs.map +7 -0
  55. package/dist/sqlite-test.mjs +1720 -0
  56. package/dist/sqlite-test.mjs.map +7 -0
  57. package/dist/sse.d.ts +44 -0
  58. package/dist/store/byte-cache.d.ts +162 -0
  59. package/dist/store/canonical.d.ts +2 -0
  60. package/dist/store/indexeddb.d.ts +23 -0
  61. package/dist/store/locks.d.ts +11 -0
  62. package/dist/store/outbox.d.ts +113 -0
  63. package/dist/store/overlay-retirement.d.ts +17 -0
  64. package/dist/store/projection.d.ts +11 -0
  65. package/dist/store/range-store.d.ts +388 -0
  66. package/dist/store/sqlite-driver.conformance.d.ts +7 -0
  67. package/dist/store/sqlite-driver.d.ts +16 -0
  68. package/dist/store/sqlite-expo.d.ts +3 -0
  69. package/dist/store/sqlite.d.ts +31 -0
  70. package/dist/templates/chat/expo/App.tsx +29 -0
  71. package/dist/templates/chat/expo/app.json +11 -0
  72. package/dist/templates/chat/expo/index.js +3 -0
  73. package/dist/templates/chat/expo/shared/log.js +92 -0
  74. package/dist/templates/chat/expo/shared/log.ts +130 -0
  75. package/dist/templates/chat/expo/shared/offline.js +8 -0
  76. package/dist/templates/chat/expo/shared/offline.ts +9 -0
  77. package/dist/templates/chat/expo/src/Chat.tsx +23 -0
  78. package/dist/templates/chat/expo/src/Composer.tsx +23 -0
  79. package/dist/templates/chat/expo/src/MediaView.tsx +29 -0
  80. package/dist/templates/chat/expo/src/Witness.tsx +131 -0
  81. package/dist/templates/chat/expo/src/screens/Inbox.tsx +9 -0
  82. package/dist/templates/chat/expo/src/screens/Search.tsx +10 -0
  83. package/dist/templates/chat/expo/src/screens/Thread.tsx +22 -0
  84. package/dist/templates/chat/expo/src/witness-state.ts +68 -0
  85. package/dist/templates/chat/expo/tsconfig.json +5 -0
  86. package/dist/templates/chat/react/index.html +5 -0
  87. package/dist/templates/chat/react/shared/log.js +92 -0
  88. package/dist/templates/chat/react/shared/log.ts +130 -0
  89. package/dist/templates/chat/react/shared/offline.js +8 -0
  90. package/dist/templates/chat/react/shared/offline.ts +9 -0
  91. package/dist/templates/chat/react/src/App.tsx +36 -0
  92. package/dist/templates/chat/react/src/Composer.tsx +45 -0
  93. package/dist/templates/chat/react/src/Inbox.tsx +24 -0
  94. package/dist/templates/chat/react/src/Search.tsx +26 -0
  95. package/dist/templates/chat/react/src/Thread.tsx +126 -0
  96. package/dist/templates/chat/react/src/env.d.ts +1 -0
  97. package/dist/templates/chat/react/src/main.tsx +20 -0
  98. package/dist/templates/chat/shared/log.js +92 -0
  99. package/dist/templates/chat/shared/log.ts +130 -0
  100. package/dist/templates/chat/shared/offline.js +8 -0
  101. package/dist/templates/chat/shared/offline.ts +9 -0
  102. package/dist/templates/chat/snapback/deliveries.q +33 -0
  103. package/dist/templates/chat/snapback/delivery.ts +30 -0
  104. package/dist/templates/chat/snapback/feeds.q +14 -0
  105. package/dist/templates/chat/snapback/follows.q +11 -0
  106. package/dist/templates/chat/snapback/groups.q +40 -0
  107. package/dist/templates/chat/snapback/messages.q +32 -0
  108. package/dist/templates/chat/snapback/notifications.q +7 -0
  109. package/dist/templates/chat/snapback/posts.q +4 -0
  110. package/dist/templates/chat/snapback/profiles.q +17 -0
  111. package/dist/templates/chat/snapback/schema.q +136 -0
  112. package/dist/templates/chat/snapback/seed.ts +45 -0
  113. package/dist/templates/chat/snapback/tests/chat.test.ts +759 -0
  114. package/dist/templates/react/index.html +5 -0
  115. package/dist/templates/react/src/App.tsx +5 -0
  116. package/dist/templates/react/src/main.tsx +18 -0
  117. package/dist/templates/todos/snapback/schema.q +11 -0
  118. package/dist/templates/todos/snapback/seed.ts +10 -0
  119. package/dist/templates/todos/snapback/tests/todos.test.ts +13 -0
  120. package/dist/templates/todos/snapback/todos.q +6 -0
  121. package/dist/test-runner.mjs +8541 -0
  122. package/dist/test-runner.mjs.map +7 -0
  123. package/dist/test.d.ts +28 -0
  124. package/dist/test.mjs +8541 -0
  125. package/dist/test.mjs.map +7 -0
  126. package/dist/token-store.d.ts +3 -0
  127. package/dist/twin-hydrate.d.ts +43 -0
  128. package/dist/twin.d.ts +70 -0
  129. package/dist/types.d.ts +410 -0
  130. package/dist/witness-test.mjs +2 -0
  131. package/dist/witness-test.mjs.map +7 -0
  132. package/package.json +117 -0
@@ -0,0 +1,60 @@
1
+ import{existsSync as Rt,readFileSync as nc}from"node:fs";import{lstat as vf,mkdir as Rf,mkdtemp as Df,readdir as uc,readFile as st,realpath as tc,rename as Is,rm as Zi,writeFile as ic}from"node:fs/promises";import{basename as er,dirname as cc,isAbsolute as lc,join as Se,relative as dc,resolve as qn,sep as Ms}from"node:path";import{fileURLToPath as ci,pathToFileURL as rc}from"node:url";import ie from"typescript";import T from"typescript";import Vn from"typescript";import C from"typescript";var Fs=new Set(["query","mutation","effect","channel","table","schema","seed","emit"]);function tn(e,n=e.getSourceFile()){let t=new Map,i=new Set;for(let r of n.statements){if(!C.isImportDeclaration(r)||!C.isStringLiteral(r.moduleSpecifier)||r.moduleSpecifier.text!=="snapback2")continue;let s=r.importClause?.namedBindings;if(s&&C.isNamedImports(s))for(let o of s.elements){let a=o.propertyName?.text??o.name.text;Fs.has(a)&&t.set(o.name.text,a)}else s&&C.isNamespaceImport(s)&&i.add(s.name.text)}if(C.isIdentifier(e.expression))return t.get(e.expression.text);if(C.isPropertyAccessExpression(e.expression)&&C.isIdentifier(e.expression.expression)&&i.has(e.expression.expression.text)&&Fs.has(e.expression.name.text))return e.expression.name.text}function js(e,n){let t=e.parent;for(;t;){if(n(t))return t;t=t.parent}}function K(e,n,t){return e.slice(0,n.getStart())+t+e.slice(n.getEnd())}function ir(e,n){return n.sort((t,i)=>i.start-t.start).reduce((t,i)=>t.slice(0,i.start)+i.text+t.slice(i.end),e)}function Bs(e){let n=!1;return we(e,t=>{(C.isPostfixUnaryExpression(t)||C.isPrefixUnaryExpression(t))&&(t.operator===C.SyntaxKind.PlusPlusToken||t.operator===C.SyntaxKind.MinusMinusToken)&&(n=!0)}),n}function rr(e,n){let t=!1;return we(e,i=>{C.isCallExpression(i)&&oe(i).endsWith(n)&&(t=!0)}),t}function Lt(e,n){let t;return we(e,i=>{!t&&C.isCallExpression(i)&&oe(i).endsWith(n)&&(t=i)}),t}function ot(e,n){let t=e,i=r=>{r.getFullStart()<=n&&n<r.getEnd()&&(t=r,C.forEachChild(r,i))};return i(e),t}function qs(e,n){let t=Us(e,n),i=t?.indexOf(n)??-1;return i>0?t[i-1]:void 0}function Vs(e,n){let t=Us(e,n),i=t?.indexOf(n)??-1;return i>=0?t[i+1]:void 0}function Us(e,n){if(n.parent===e)return e.statements;if(C.isBlock(n.parent))return n.parent.statements}function we(e,n){n(e),C.forEachChild(e,t=>we(t,n))}function Pe(e){return C.canHaveModifiers(e)&&!!C.getModifiers(e)?.some(n=>n.kind===C.SyntaxKind.ExportKeyword)}function Ks(e){return!!C.canHaveModifiers(e)&&!!C.getModifiers(e)?.some(n=>n.kind===C.SyntaxKind.AsyncKeyword)}function ge(e){return C.isArrowFunction(e)||C.isFunctionExpression(e)}function Qs(e){let n=e.parent;for(;n&&!C.isSourceFile(n);){if(C.isCallExpression(n)&&tn(n)==="effect")return!0;if(C.isVariableStatement(n))return!1;n=n.parent}return!1}function N(e){let n=h(e);return C.isCallExpression(n)?n:void 0}function h(e){let n=e;for(;C.isParenthesizedExpression(n)||C.isAsExpression(n)||C.isNonNullExpression(n);)n=n.expression;return n}function ye(e){let n=h(e);if(C.isIdentifier(n))return n.text;if(!C.isPropertyAccessExpression(n))return;let t=ye(n.expression);return t?`${t}.${n.name.text}`:void 0}function oe(e){return e.expression.getText()}function di(e){return C.isPropertyAccessExpression(e)?e.name.text:void 0}function On(e){let n=h(e);if(!(!C.isNewExpression(n)||!C.isIdentifier(n.expression)))return n.expression.text==="Map"||n.expression.text==="Set"?n.expression.text:void 0}function at(e,n){return C.isIdentifier(e)&&n(e.text)}function We(e,n){return C.isPropertyAccessExpression(e)&&at(e.expression,n)}function Hs(e,n){let t=N(e);return!!t&&C.isPropertyAccessExpression(t.expression)&&at(t.expression.expression,n)&&["insert","update","upsert","delete","require","assert"].includes(t.expression.name.text)}function zs(e,n){let t=N(e);return!!t&&C.isPropertyAccessExpression(t.expression)&&at(t.expression.expression,n)&&t.expression.name.text==="insert"}function Ws(e,n){let t=N(e);return!!t&&C.isPropertyAccessExpression(t.expression)&&at(t.expression.expression,n)&&t.expression.name.text==="get"}function Pt(e){let n=h(e);if(!(!C.isBinaryExpression(n)||![C.SyntaxKind.ExclamationEqualsToken,C.SyntaxKind.ExclamationEqualsEqualsToken].includes(n.operatorToken.kind)))return C.isIdentifier(n.left)&&n.right.kind===C.SyntaxKind.NullKeyword?n.left.text:C.isIdentifier(n.right)&&n.left.kind===C.SyntaxKind.NullKeyword?n.right.text:void 0}function G(e,n){let t="temp"in e?e.temp:e,i=t.value++;return`__${n}${i}`}function Ft(e,n){return C.factory.createIdentifier(n)}function H(e){return C.isIdentifier(e)||C.isStringLiteralLike(e)||C.isNumericLiteral(e)?e.text:void 0}function $e(e,n){return e.properties.find(i=>C.isPropertyAssignment(i)&&H(i.name)===n)?.initializer}function sr(e,n){return Fe($e(e,n))}function Fe(e){return e&&C.isNumericLiteral(h(e))?Number(h(e).text):void 0}function Cn(e){let n=e.replaceAll("_","").match(/^(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:e([+-]?\d+))?$/i);if(!n)return;let t=n[1]??"0",i=n[2]??n[3]??"",r=Number(n[4]??0),s=`${t}${i}`,o=t.length+r,a=(o<=0?"0":o>=s.length?s.padEnd(o,"0"):s.slice(0,o)).replace(/^0+(?=\d)/,""),u=(o<=0?`${"0".repeat(-o)}${s}`:o>=s.length?"":s.slice(o)).replace(/0+$/,"");return{whole:a||"0",fraction:u}}function fi(e){let n=e&&h(e);return n&&C.isStringLiteralLike(n)?n.text:void 0}function bn(e){return fi(e)}function Js(e){return Fe(e)===0}function re(e){let n;return e===null?n="Null":typeof e=="boolean"?n={Bool:e}:typeof e=="number"?n={Int:e}:n={String:e},{Literal:n}}function pi(e){return new Map([[C.SyntaxKind.EqualsEqualsEqualsToken,"Eq"],[C.SyntaxKind.EqualsEqualsToken,"Eq"],[C.SyntaxKind.ExclamationEqualsEqualsToken,"Ne"],[C.SyntaxKind.ExclamationEqualsToken,"Ne"],[C.SyntaxKind.LessThanToken,"Lt"],[C.SyntaxKind.LessThanEqualsToken,"Lte"],[C.SyntaxKind.GreaterThanToken,"Gt"],[C.SyntaxKind.GreaterThanEqualsToken,"Gte"],[C.SyntaxKind.PlusToken,"Add"],[C.SyntaxKind.MinusToken,"Sub"],[C.SyntaxKind.AsteriskToken,"Mul"],[C.SyntaxKind.AmpersandAmpersandToken,"And"],[C.SyntaxKind.BarBarToken,"Or"]]).get(e)}function jt(e){return e.endsWith("ies")?`${e.slice(0,-3)}y`:e.endsWith("s")?e.slice(0,-1):e}function or(e,n){let t=h(e);if(C.isIdentifier(t))return t.text;if(C.isPropertyAccessExpression(t)){let i=h(t.expression);if(C.isIdentifier(i)&&n(i.text))return t.name.text}}function Bt(e,n,t){return`${e}/${n.getStart(t)}`}function Ye(e,n,t){return`${e}:${n.getStart(t)}:${n.getEnd()}:${n.kind}`}function mn(e){let n=mc(e.getSourceFile()),t=new Map,i=new Set,r,s,o=a=>{if(!i.has(a)){i.add(a);for(let u of a.properties){if(r||s)break;if(Vn.isSpreadAssignment(u)){let l=h(u.expression),f=Vn.isIdentifier(l)?n.get(l.text):void 0;!f||i.has(f)?r=u:o(f);continue}if(!Vn.isPropertyAssignment(u)){s=u;continue}let c=H(u.name);if(!c){s=u;continue}t.delete(c),t.set(c,{name:c,value:u.initializer,node:u})}i.delete(a)}};return o(e),{entries:[...t.values()],invalidSpread:r,invalidProperty:s}}function Gs(e,n){let t=n.expression.getText(n.getSourceFile());return K(e,n,`field: ${t}.field`)}function mc(e){let n=new Map;for(let t of e.statements)if(!(!Vn.isVariableStatement(t)||!(t.declarationList.flags&Vn.NodeFlags.Const)))for(let i of t.declarationList.declarations){if(!Vn.isIdentifier(i.name)||!i.initializer)continue;let r=h(i.initializer);Vn.isObjectLiteralExpression(r)&&n.set(i.name.text,r)}return n}var hn=class extends Error{constructor(t){super(t.message);this.diagnostic=t}};function L(e,n,t,i,r){let s=gc(e,t);return{code:n,family:yc(n),message:i,site:`${s.file}:${s.line}:${s.column}`,rule:Ys(n),rewrite:r,guide:bc(n)}}function w(e,n,t,i,r=e.source){throw new hn(L(e,n,t,i,r))}function qe(e,n,t,i,r,s,o,a){return{code:e,family:n,message:s,site:`${t}:${i}:${r}`,rule:Ys(e),rewrite:o,guide:a}}function En(e,n,t){let i=new Set,r=e.filter(u=>{let c=`${u.code}\0${u.site}\0${u.message}`;return i.has(c)?!1:(i.add(c),!0)}).sort((u,c)=>u.site.localeCompare(c.site)||u.code.localeCompare(c.code));if(r.length<=n)return r;let s=r.slice(0,n-1),o=r[n-1],a=r.slice(n-1).reduce((u,c)=>{let l=c.code==="E_DIAG_TRUNCATED"&&c.message.match(/^…and (\d+) more/);return u+(l?Number(l[1]):1)},0);return s.push({...o,code:"E_DIAG_TRUNCATED",family:"opaque",message:`\u2026and ${a} more ${t}`,rule:void 0,rewrite:`${o.rewrite}
2
+ // Fix the remaining diagnostics and run snapback2 check again.`,guide:"opaque/subset"}),s}function gc(e,n){let t=n.getStart(e.sourceFile),i=e.sourceFile.getLineAndCharacterOfPosition(t);return{file:e.fileName,start:t,end:n.getEnd(),line:i.line+1,column:i.character+1}}function yc(e){return e.startsWith("E_QUARRY_")?"quarry":e.startsWith("E_SCHEMA_")?"schema":e.startsWith("E_RULE_")?"rule":e.startsWith("E_SEED_")?"input":e.startsWith("E_EFFECT_")||e==="E_EMIT_IN_QUERY"?"effect":e.startsWith("E_ARGS_")||e==="E_DECIMAL_SCALE"||e==="E_ENUM_VARIANT"?"args":e.startsWith("E_OP_")?"op":["E_UNBOUND_SCAN","E_UNBOUND_LOOP","E_UNBOUND_COUNT","E_STRUCTURAL_COUNT","E_BOUND"].includes(e)?"bound":"opaque"}function bc(e){return e==="E_QUARRY_SYNTAX"?"quarry/grammar":e==="E_QUARRY_AMBIGUOUS"?"quarry/indexes":e==="E_QUARRY_UNSUPPORTED"?"quarry/refusals":e==="E_QUARRY_PLACEMENT"?"quarry/projects":e==="E_QUARRY_RETAIN"?"quarry/grammar":e==="E_QUARRY_ONLY"?"quarry/projects":e==="E_QUARRY_UNKNOWN"?"quarry/names":e==="E_UNBOUND_SCAN"?"bound/scan":e==="E_UNBOUND_LOOP"?"bound/loop":e==="E_UNBOUND_COUNT"||e==="E_STRUCTURAL_COUNT"?"bound/count":e==="E_BOUND"?"bound/ceiling":e==="E_AMBIENT_TIME"?"opaque/time":e==="E_PROVENANCE_AMBIGUOUS"?"opaque/provenance":e==="E_OP_MODULE_BASENAME"?"programs/module-basename":e.startsWith("E_SCHEMA_")?"schema/project":e.startsWith("E_RULE_")?"schema/rules":e.startsWith("E_SEED_")?"schema/seed":e.startsWith("E_EFFECT_")||e==="E_EMIT_IN_QUERY"?"effects/authoring":e.startsWith("E_ARGS_")||e==="E_DECIMAL_SCALE"||e==="E_ENUM_VARIANT"?"programs/types":e.startsWith("E_OP_")?"programs/operations":"opaque/subset"}function Ys(e){return{E_UNBOUND_SCAN:"every scan names take",E_UNBOUND_LOOP:"every loop has a static maximum",E_UNBOUND_COUNT:"growing populations do not expose exact counts",E_STRUCTURAL_COUNT:"rules do not leak hidden population structure",E_AMBIENT_TIME:"programs use ctx.now()",E_PROVENANCE_AMBIGUOUS:"read keys have one unambiguous origin",E_OP_MODULE_BASENAME:"module basenames are unique",E_BOUND:"the certified ceiling is finite",E_EMIT_IN_QUERY:"only mutations emit effects"}[e]}import M from"typescript";import V from"typescript";import hc from"typescript";var mi=128;function je(e,n,t,i){let r=e.recursion.active.get(n);if(e.recursion.depth>=mi||r?.has(t))return ar(e,n);e.recursion.depth+=1,r?r.add(t):e.recursion.active.set(n,new Set([t]));try{return i()}finally{let s=e.recursion.active.get(n);s?.delete(t),s?.size===0&&e.recursion.active.delete(n),e.recursion.depth-=1}}function ar(e,n){let t=hc.isExpression(n)?n:void 0,i=t?K(e.source,t,"PROVENANCE_ORIGIN_REQUIRED(/* choose one direct origin; recursive expansion was refused */)"):`${e.source}
3
+ // E_PROVENANCE_AMBIGUOUS: replace the recursive value with one direct origin.`;w(e,"E_PROVENANCE_AMBIGUOUS",n,`provenance expansion is recursive or exceeds ${mi} levels; choose one direct origin`,i)}import Me from"typescript";import ut from"typescript";function Ce(e,n){let t=N(e);if(!t||!ut.isIdentifier(t.expression))return;let i=n.helpers.get(t.expression.text);if(!i)return;n.helperStack.includes(t.expression.text)&&w(n,"E_OPAQUE",t,"recursive helper is not inlineable");let r=xc(i);r||w(n,"E_OPAQUE",i,"helper must be a single pure return expression");let s={...n,variables:new Map([...n.variables].map(([o,a])=>[o,{...a}])),substitutions:new Map(n.substitutions),helperStack:[...n.helperStack,t.expression.text],deferredCollectionMutations:new Set(n.deferredCollectionMutations),literalContext:Bt(n.literalContext,t,n.sourceFile)};return i.parameters.forEach((o,a)=>{(!ut.isIdentifier(o.name)||!t.arguments[a])&&w(n,"E_OPAQUE",o,"helper parameters must be positional identifiers");let u=Ec(t.arguments[a],n);s.substitutions.delete(o.name.text),(!ut.isIdentifier(u.expression)||u.expression.text!==o.name.text||u.environment!==n)&&s.substitutions.set(o.name.text,u)}),{expression:r,environment:s}}function Ec(e,n){let t=e,i=n,r=new Set;for(;;){let s=h(t);if(!ut.isIdentifier(s))return{expression:t,environment:i};let o=i.substitutions.get(s.text);if(!o)return{expression:t,environment:i};if(r.has(s.text)||r.size>=128)return ar(n,e);r.add(s.text),t=o.expression,i=o.environment}}function xc(e){if(e.body){if(!ut.isBlock(e.body))return e.body;if(!(e.body.statements.length!==1||!ut.isReturnStatement(e.body.statements[0])))return e.body.statements[0].expression}}import O from"typescript";var Mn="<unknown origin>";function gi(e){let n=new Set,t={bindings:new Map};for(let i of e.parameters)In(i.name,t);return e.body&&xn(e.body,t,n),n}function to(e){let n=[],t=new Map,i={bindings:new Map};for(let u of e.parameters)In(u.name,i);e.body&&Un(e.body,i,n,t);let r=new Map;for(let u of n)Xs(r,u.left,u.right,u.site),Xs(r,u.right,u.left,u.site);let s=new Map,o=new Map,a=new Set([...r.keys(),...t.keys()]);for(let u of a){let c=[u],l=new Set,f=new Set,d=new Map;for(;c.length>0;){let p=c.pop();if(!l.has(p)){l.add(p);for(let g of t.get(p)??[])d.set(g.expression.getStart(),g);for(let g of r.get(p)??[])f.add(g.site),c.push(g.other)}}f.size>0&&s.set(u,[...f]),d.size>0&&o.set(u,[...d.values()])}return{aliases:s,escapes:o}}function io(e){let n=h(e);if(O.isArrayLiteralExpression(n))return!0;if(!O.isNewExpression(n)||!On(n))return!1;let t=n.arguments?.[0];return t===void 0||O.isArrayLiteralExpression(h(t))}function kc(e,n,t,i){let r=e.collectionDeclaration?i.collectionAliasSites.get(e.collectionDeclaration)??[]:[],s=oo(e,n,i),o=[...r.map(no),...s];if(o.length>0)return Zs(i,o);let a=e.collectionDeclaration?.parent;if(a&&O.isVariableDeclaration(a)&&a.initializer)return Zs(i,[no(a.initializer)]);let u=`${t.text}Copy`,c=O.isPropertyAccessExpression(n.expression)?n.expression.name.getText(i.sourceFile):"push";return K(i.source,n,`const ${u} = [...${t.text}]; ${u}.${c}(${n.arguments.map(l=>l.getText(i.sourceFile)).join(", ")})`)}function yi(e,n,t){let i=t.variables.get(e.text),r=i.collectionDeclaration?t.collectionAliasSites.get(i.collectionDeclaration)??[]:[],s=oo(i,n,t);if(i.locallyCreatedCollection&&r.length===0&&s.length===0)return;let o=r.length>0?"aliased under another binding":s.length>0?s.some(a=>a.expression.getStart(t.sourceFile)<n.getStart(t.sourceFile))?"shared by an escape before this mutation":"shared by an escape in the same cyclic loop body":"not locally created";w(t,"E_OPAQUE",n,`collection mutation requires an unaliased local collection created from a literal or spread copy; ${e.text} is ${o}`,kc(i,n,e,t))}function ro(e){let n=e.parameters[0];if(!n||!O.isObjectBindingPattern(n.name))return{};let t={};for(let i of n.name.elements){if(!O.isIdentifier(i.name))continue;let r=i.propertyName?H(i.propertyName):i.name.text;(r==="args"||r==="ctx"||r==="db")&&(t[r]=i.name.text)}return t}function Oe(e,n,t){return so(e,n,t,new Set)}function so(e,n,t,i){if(t.variables.get(e)?.operationComposite===n)return!0;let r=t.substitutions.get(e);if(!r||i.has(e))return!1;let s=h(r.expression);return O.isIdentifier(s)?(i.add(e),so(s.text,n,r.environment,i)):!1}function xn(e,n,t){if(O.isBlock(e)){let i={parent:n,bindings:new Map};for(let r of e.statements)if(O.isVariableStatement(r))for(let s of r.declarationList.declarations)In(s.name,i);for(let r of e.statements)xn(r,i,t);return}if(O.isForOfStatement(e)){xn(e.expression,n,t);let i={parent:n,bindings:new Map};if(O.isVariableDeclarationList(e.initializer))for(let r of e.initializer.declarations)In(r.name,i);else xn(e.initializer,n,t);xn(e.statement,i,t);return}if(O.isFunctionDeclaration(e)||O.isArrowFunction(e)||O.isFunctionExpression(e)){let i={parent:n,bindings:new Map};for(let r of e.parameters)In(r.name,i);e.body&&xn(e.body,i,t);return}if(O.isVariableDeclaration(e)){e.initializer&&xn(e.initializer,n,t);return}if(O.isBinaryExpression(e)&&e.operatorToken.kind===O.SyntaxKind.EqualsToken&&O.isIdentifier(e.left)){let i=Kn(e.left.text,n);i&&t.add(i),xn(e.right,n,t);return}if((O.isPostfixUnaryExpression(e)||O.isPrefixUnaryExpression(e))&&(e.operator===O.SyntaxKind.PlusPlusToken||e.operator===O.SyntaxKind.MinusMinusToken)&&O.isIdentifier(e.operand)){let i=Kn(e.operand.text,n);i&&t.add(i);return}O.forEachChild(e,i=>xn(i,n,t))}function Un(e,n,t,i){if(O.isBlock(e)){let r={parent:n,bindings:new Map};for(let s of e.statements)if(O.isVariableStatement(s))for(let o of s.declarationList.declarations)In(o.name,r);for(let s of e.statements)Un(s,r,t,i);return}if(O.isForOfStatement(e)){Un(e.expression,n,t,i);let r={parent:n,bindings:new Map};if(O.isVariableDeclarationList(e.initializer))for(let s of e.initializer.declarations)In(s.name,r);Un(e.statement,r,t,i);return}if(!O.isFunctionLike(e)){if(O.isVariableDeclaration(e)){if(O.isIdentifier(e.name)&&e.initializer){let r=h(e.initializer),s=Kn(e.name.text,n),o=O.isIdentifier(r)?Kn(r.text,n):void 0;s&&o&&s!==o&&t.push({left:s,right:o,site:e.initializer}),Un(e.initializer,n,t,i)}return}if(O.isBinaryExpression(e)&&e.operatorToken.kind===O.SyntaxKind.EqualsToken&&O.isIdentifier(e.left)){let r=h(e.right),s=Kn(e.left.text,n),o=O.isIdentifier(r)?Kn(r.text,n):void 0;s&&o&&s!==o&&t.push({left:s,right:o,site:e.right}),Un(e.right,n,t,i);return}$c(e,n,i),O.forEachChild(e,r=>Un(r,n,t,i))}}function Xs(e,n,t,i){let r=e.get(n)??[];r.push({other:t,site:i}),e.set(n,r)}function Zs(e,n){let i=[...new Map(n.map(s=>[s.expression.getStart(e.sourceFile),s])).values()].map(s=>({start:s.expression.getStart(e.sourceFile),end:s.expression.getEnd(),text:s.replacement})).sort((s,o)=>o.start-s.start),r=e.source;for(let s of i)r=r.slice(0,s.start)+s.text+r.slice(s.end);return r}function oo(e,n,t){let i=e.collectionDeclaration;if(!i)return[];let r=n.getStart(t.sourceFile);return(t.collectionEscapeSites.get(i)??[]).filter(s=>s.expression.getStart(t.sourceFile)<r||Sc(s.expression,n,i))}function Sc(e,n,t){let i=new Set(eo(e));return eo(n).some(r=>i.has(r)&&!wc(t,r))}function eo(e){let n=[];for(let t=e;t?.parent;t=t.parent)O.isForOfStatement(t.parent)&&t.parent.statement===t&&n.push(t);return n}function wc(e,n){for(let t=e;t;t=t.parent)if(t===n)return!0;return!1}function no(e){return{expression:e,replacement:`[...${e.getText()}]`}}function $c(e,n,t){if(O.isReturnStatement(e)&&e.expression&&an(e.expression,n,t),O.isCallExpression(e))for(let i of e.arguments)O.isSpreadElement(i)||an(i,n,t);if(O.isArrayLiteralExpression(e))for(let i of e.elements)O.isSpreadElement(i)||an(i,n,t);if(O.isObjectLiteralExpression(e))for(let i of e.properties)O.isShorthandPropertyAssignment(i)?ao(i.name,n,t,`${i.name.text}: [...${i.name.text}]`):O.isPropertyAssignment(i)&&an(i.initializer,n,t);O.isConditionalExpression(e)&&(an(e.whenTrue,n,t),an(e.whenFalse,n,t)),O.isBinaryExpression(e)&&[O.SyntaxKind.AmpersandAmpersandToken,O.SyntaxKind.BarBarToken,O.SyntaxKind.QuestionQuestionToken].includes(e.operatorToken.kind)&&(an(e.left,n,t),an(e.right,n,t))}function an(e,n,t){if(!(O.isFunctionLike(e)||O.isSpreadElement(e))){if(O.isIdentifier(e)){ao(e,n,t);return}if(O.isCallExpression(e)){for(let i of e.arguments)O.isSpreadElement(i)||an(i,n,t);return}if(O.isPropertyAccessExpression(e)){an(e.expression,n,t);return}e.forEachChild(i=>{O.isExpression(i)&&an(i,n,t)})}}function ao(e,n,t,i=`[...${e.text}]`){let r=Kn(e.text,n);if(!r)return;let s=t.get(r)??[];s.some(o=>o.expression===e)||s.push({expression:e,replacement:i}),t.set(r,s)}function In(e,n){if(O.isIdentifier(e)){n.bindings.set(e.text,e);return}for(let t of e.elements)O.isBindingElement(t)&&In(t.name,n)}function Kn(e,n){for(let t=n;t;t=t.parent){let i=t.bindings.get(e);if(i)return i}}function Ie(e,n){return je(n,e,"direct origin",()=>Ac(e,n))}function Ac(e,n){let t=h(e);if(O.isPropertyAccessExpression(t)&&O.isIdentifier(t.expression)){let r=n.variables.get(t.expression.text),s=r?.operationComposite;if(s==="args"||s==="ctx"&&t.name.text==="viewer")return new Set([t.getText(n.sourceFile)]);if(r?.rowBinding)return new Set([t.getText(n.sourceFile)])}if(O.isIdentifier(t)){let r=n.variables.get(t.text);if(r?.operationComposite==="args")return new Set([t.text]);if(r?.operationComposite==="ctx")return new Set([`${t.text}.viewer`]);if(r?.operationArgument){let s=[...n.variables].find(([,o])=>o.operationComposite==="args")?.[0];return new Set([s?`${s}.${r.operationArgument}`:r.operationArgument])}return r?.provenanceAmbiguity?new Set([...r.provenanceAmbiguity.candidates??[],...r.provenanceAmbiguity.directRewrite?[r.provenanceAmbiguity.directRewrite]:[]]):r?.alternativeOrigins?co(r.alternativeOrigins,new Set):r?.immutableOrigin?Ie(r.immutableOrigin.expression,r.immutableOrigin.environment):new Set}if(O.isPropertyAccessExpression(t))return Ie(t.expression,n);if(O.isObjectLiteralExpression(t)){let r=new Set;for(let s of t.properties){let o=O.isSpreadAssignment(s)?s.expression:O.isPropertyAssignment(s)?s.initializer:O.isShorthandPropertyAssignment(s)?s.name:void 0;if(o)for(let a of Ie(o,n))r.add(a)}return r}if(O.isCallExpression(t)){let r=new Set;for(let s of t.arguments)for(let o of Ie(s,n))r.add(o);return r}if(O.isConditionalExpression(t))return new Set([...Ie(t.whenTrue,n),...Ie(t.whenFalse,n)]);let i=new Set;return t.forEachChild(r=>{if(O.isExpression(r))for(let s of Ie(r,n))i.add(s)}),i}function qt(e,n,t){if(!e.provenanceAmbiguity)return e;let i=new Set([...e.provenanceAmbiguity.candidates??[],...e.provenanceAmbiguity.directRewrite?[e.provenanceAmbiguity.directRewrite]:[],...Ie(n,t)]);return{...e,provenanceAmbiguity:un([...i])}}function uo(e,n,t){if(!e)return;let i=[...Ie(n,t)],r=new Set([...e.provenanceAmbiguity?.candidates??[],...e.provenanceAmbiguity?.directRewrite?[e.provenanceAmbiguity.directRewrite]:[],...e.immutableOrigin?Ie(e.immutableOrigin.expression,e.immutableOrigin.environment):[],...i.length>0?i:[Mn]]);e.provenanceAmbiguity=un([...r])}function un(e){let n=[...new Set(e)];return{...n.length===1&&n[0]!==Mn?{directRewrite:n[0]}:{},...n.length>0?{candidates:n}:{}}}function co(e,n){let t=new Set;for(let i of e){if("expression"in i){for(let s of Ie(i.expression,i.environment))t.add(s);continue}i.candidate&&t.add(i.candidate);let r=i.binding;if(!n.has(r)){n.add(r);for(let s of r.provenanceAmbiguity?.candidates??[])t.add(s);if(r.provenanceAmbiguity?.directRewrite&&t.add(r.provenanceAmbiguity.directRewrite),r.alternativeOrigins)for(let s of co(r.alternativeOrigins,n))t.add(s);if(r.immutableOrigin)for(let s of Ie(r.immutableOrigin.expression,r.immutableOrigin.environment))t.add(s)}}return t}function lo(e){return e.split(/[\\/]/).at(-1).replace(/\.[^.]+$/,"")}function Ve(e,n){return je(n,e,"collection elements",()=>Tc(e,n))}function Tc(e,n){let t=h(e);if(Me.isIdentifier(t)){let s=n.substitutions.get(t.text);if(s)return Ve(s.expression,s.environment);let o=n.variables.get(t.text);return o?.elementOrigins?o.elementOrigins:o?.alternativeOrigins?ur(o.alternativeOrigins):o?.rowCollection?[{binding:{provenance:"Shape",rowBinding:!0,objectFields:o.objectFields}}]:o?.max!==void 0?[fo(o,o.operationArgument)]:void 0}if(Me.isPropertyAccessExpression(t)){let s=gn(t.expression,n,t.name.text);return s.kind==="found"?ur(s.origins):void 0}if(Me.isArrayLiteralExpression(t)){let s=[],o=kn(n);for(let a of t.elements)if(Me.isSpreadElement(a)){let u=Ve(a.expression,n);if(!u)return;s.push(...u)}else s.push({expression:a,environment:o});return s}if(Me.isConditionalExpression(t)){let s=Ve(t.whenTrue,n),o=Ve(t.whenFalse,n);return s&&o?[...s,...o]:void 0}let i=N(t),r=i&&Ce(i,n);if(r)return Ve(r.expression,r.environment);if(i&&oe(i).endsWith(".scan")&&We(i.expression,s=>Oe(s,"db",n)))return[{binding:{provenance:"Shape",rowBinding:!0,objectFields:Oc(i.arguments[0],n)}}];if(i&&Me.isIdentifier(i.expression)&&i.expression.text==="mergeByIndex"){let s=i.arguments[0];return s?Ve(s,n):void 0}if(i&&Me.isIdentifier(i.expression)&&i.expression.text==="mentionTokens")return[{binding:{provenance:"Computed"}}];if(i&&Me.isPropertyAccessExpression(i.expression)){let s=i.expression.name.text,o=i.expression.expression;if(["filter","sort","slice"].includes(s))return Ve(o,n);if(s==="map"||s==="flatMap"){let a=i.arguments[0];if(!a||!Me.isArrowFunction(a)&&!Me.isFunctionExpression(a)||a.parameters.length===0||!Me.isIdentifier(a.parameters[0].name)||Me.isBlock(a.body))return;let u=kn(n);return u.variables.set(a.parameters[0].name.text,Nc(o,n)),s==="map"?[{expression:a.body,environment:kn(u)}]:Ve(a.body,u)}}}function Nc(e,n){let t=Ve(e,n);return t&&t.length>0?{provenance:"Computed",alternativeOrigins:t}:{provenance:"Computed",provenanceAmbiguity:{}}}function ur(e){let n=[];for(let t of e){if("binding"in t){let r=t.binding.elementOrigins??(t.binding.alternativeOrigins?ur(t.binding.alternativeOrigins):void 0);if(r)n.push(...r);else if(t.binding.max!==void 0||t.binding.operationArgument||t.binding.rowCollection)n.push(fo(t.binding,t.candidate));else return;continue}let i=Ve(t.expression,t.environment);if(!i)return;n.push(...i)}return n}function cr(e,n){return"binding"in e?e.binding.immutableOrigin?cr(e.binding.immutableOrigin,n):{kind:"unknown"}:gn(e.expression,e.environment,n)}function gn(e,n,t){let i=h(e);if(Me.isIdentifier(i)){let s=n.substitutions.get(i.text);if(s)return gn(s.expression,s.environment,t);let o=n.variables.get(i.text);if(o?.operationComposite==="args"){let a=n.args[t];if(!a)return{kind:"absent"};let u=typeof a!="string"&&"Optional"in a?a.Optional:a,c=typeof u!="string"&&"List"in u?u.List.max:void 0;return{kind:"found",origins:[{binding:{provenance:"Arg",operationArgument:t,...c!==void 0?{max:c,boundSource:`arg ${t} max`}:{}},candidate:`${i.text}.${t}`}],presence:typeof a!="string"&&"Optional"in a?"optional":"required"}}if(o?.operationComposite==="ctx")return t==="viewer"?{kind:"found",origins:[{binding:{provenance:"Viewer"}}],presence:"required"}:{kind:"absent"};if(o?.provenanceAmbiguity)return{kind:"unknown"};if(o?.alternativeOrigins){let a=o.alternativeOrigins.map(u=>cr(u,t));return a.some(u=>u.kind!=="found")?{kind:"unknown"}:{kind:"found",origins:a.flatMap(u=>u.kind==="found"?u.origins:[]),presence:a.some(u=>u.kind==="found"&&u.presence==="optional")?"optional":"required"}}return o?.immutableOrigin?cr(o.immutableOrigin,t):{kind:"unknown"}}if(Me.isConditionalExpression(i))return _c([gn(i.whenTrue,n,t),gn(i.whenFalse,n,t)]);if(!Me.isObjectLiteralExpression(i))return{kind:"unknown"};let r=[];for(let s of[...i.properties].reverse()){let o;if(Me.isSpreadAssignment(s)?o=gn(s.expression,n,t):Me.isShorthandPropertyAssignment(s)&&s.name.text===t?o={kind:"found",origins:[{expression:s.name,environment:kn(n)}],presence:"required"}:Me.isPropertyAssignment(s)&&H(s.name)===t&&(o={kind:"found",origins:[{expression:s.initializer,environment:kn(n)}],presence:"required"}),!(!o||o.kind==="absent")){if(o.kind==="unknown")return o;if(o.presence==="optional"){r.push(...o.origins);continue}return{kind:"found",origins:[...r,...o.origins],presence:"required"}}}return r.length>0?{kind:"found",origins:r,presence:"optional"}:{kind:"absent"}}function Ue(e){let n=new Set;for(let t of e){if("expression"in t){for(let i of Ie(t.expression,t.environment))n.add(i);continue}t.candidate&&n.add(t.candidate);for(let i of t.binding.provenanceAmbiguity?.candidates??[])n.add(i);if(t.binding.provenanceAmbiguity?.directRewrite&&n.add(t.binding.provenanceAmbiguity.directRewrite),t.binding.immutableOrigin)for(let i of Ie(t.binding.immutableOrigin.expression,t.binding.immutableOrigin.environment))n.add(i);if(t.binding.alternativeOrigins)for(let i of Ue(t.binding.alternativeOrigins))n.add(i)}return[...n]}function _c(e){if(e.some(t=>t.kind==="unknown"))return{kind:"unknown"};if(e.every(t=>t.kind==="absent"))return{kind:"absent"};if(e.some(t=>t.kind==="absent"))return{kind:"unknown"};let n=e;return{kind:"found",origins:n.flatMap(t=>t.origins),presence:n.some(t=>t.presence==="optional")?"optional":"required"}}function kn(e){return{...e,variables:new Map([...e.variables].map(([n,t])=>[n,{...t}])),substitutions:new Map(e.substitutions),helperStack:[...e.helperStack],deferredCollectionMutations:new Set(e.deferredCollectionMutations)}}function fo(e,n){let{max:t,boundSource:i,elementOrigins:r,alternativeOrigins:s,...o}=e;return{binding:o,...n?{candidate:n}:{}}}function Oc(e,n){if(!e)return;let t=ye(e)?.split(".")[0],i=t&&n.tables.get(t)?.columns;return i?[...new Set(["id",...Object.keys(i)])]:void 0}function ct(e,n){let t=ve(e,n,[],e);return t.kind!=="known"&&Lc(e,n,t.kind==="ambiguous"?t.directRewrite:void 0,t.kind==="ambiguous"?t.candidates:void 0),t.provenance}function lt(e,n){let t=ve(e,n,[],e);return t.kind==="known"?{provenance:t.provenance}:{provenance:"Computed",provenanceAmbiguity:t.kind==="ambiguous"?un(t.candidates??(t.directRewrite?[t.directRewrite]:[Mn])):{}}}function mo(e,n){let t=e.map(r=>lt(r,n)),i=t.find(r=>r.provenanceAmbiguity);return i?{provenance:"Computed",provenanceAmbiguity:{...i.provenanceAmbiguity}}:{provenance:Ei(t.map(r=>r.provenance))}}function dt(e,n){let t=Ve(e,n);if(!t||t.length===0)return{...lt(e,n),provenanceAmbiguity:{}};let i=Qn(t.map(r=>hi(r,[],e)),"required",Ue(t));return{...i.kind==="known"?{provenance:i.provenance}:{provenance:"Computed",provenanceAmbiguity:un(i.kind==="ambiguous"?i.candidates??[Mn]:Ue(t))},alternativeOrigins:t}}function bi(e,n){let t=Qn(e.map(i=>hi(i,[],n)),"required",Ue(e));return t.kind==="known"?{provenance:t.provenance}:{provenance:"Computed",provenanceAmbiguity:un(t.kind==="ambiguous"?t.candidates??Ue(e):Ue(e))}}function ve(e,n,t,i){return je(n,e,"provenance",()=>Cc(e,n,t,i))}function Cc(e,n,t,i){let r=h(e),s=V.isIdentifier(r)?n.substitutions.get(r.text):void 0;if(s)return ve(s.expression,s.environment,t,i);if(V.isIdentifier(r))return Ic(r,n,t,i);if(V.isPropertyAccessExpression(r))return ve(r.expression,n,[r.name.text,...t],i);if(V.isStringLiteralLike(r)||V.isNumericLiteral(r)||r.kind===V.SyntaxKind.NullKeyword||r.kind===V.SyntaxKind.TrueKeyword||r.kind===V.SyntaxKind.FalseKeyword)return t.length===0?Be("Const"):Ke();if(V.isObjectLiteralExpression(r))return t.length===0?vc(r,n,i):Rc(r,n,t,i);if(V.isArrayLiteralExpression(r))return t.length>0?Ke():dr(r.elements.map(a=>{let u=V.isSpreadElement(a)?a.expression:a;return ve(u,n,[],i)}));if(V.isCallExpression(r)){let a=Ce(r,n);return a?ve(a.expression,a.environment,t,i):yo(r,n)?Dc(r,n,t):t.length===0?Be("Computed"):Ke()}if(V.isConditionalExpression(r))return t.length===0?Be("Computed"):Qn([ve(r.whenTrue,n,t,i),ve(r.whenFalse,n,t,i)],"required");if(V.isTemplateExpression(r)||V.isBinaryExpression(r)||V.isNewExpression(r)||V.isPrefixUnaryExpression(r))return t.length===0?Be("Computed"):Ke();if(t.length>0)return Ke();let o=[];return r.forEachChild(a=>{V.isExpression(a)&&o.push(ve(a,n,[],i))}),dr(o)}function Ic(e,n,t,i){let r=n.variables.get(e.text);if(!r)return Ke();if(r.provenanceAmbiguity){let s=un([...r.provenanceAmbiguity.candidates??[],...r.provenanceAmbiguity.directRewrite?[r.provenanceAmbiguity.directRewrite]:[],...r.elementOrigins?Ue(r.elementOrigins):[],...r.alternativeOrigins?Ue(r.alternativeOrigins):[]]);return Ke(s.directRewrite,s.candidates)}if(r.operationComposite==="args"){if(t.length===0)return Object.keys(n.args).length===0?Be("Const"):Be("Arg");let s=n.args[t[0]];return s?{...Be("Arg"),presence:typeof s!="string"&&"Optional"in s?"optional":"required"}:Vt()}return r.operationComposite==="ctx"?t.length===0||t[0]==="viewer"?Be("Viewer"):Vt():r.alternativeOrigins?Qn(r.alternativeOrigins.map(s=>hi(s,t,i)),"required",Ue(r.alternativeOrigins)):r.rowBinding?go(r,t):r.immutableOrigin?ve(r.immutableOrigin.expression,r.immutableOrigin.environment,t,i):t.length===0||r.provenance==="Arg"||r.provenance==="Viewer"||r.provenance==="Const"?Be(r.provenance):Ke()}function hi(e,n,t){return"expression"in e?ve(e.expression,e.environment,n,t):Mc(e.binding,n,t)}function Mc(e,n,t){return e.provenanceAmbiguity?Ke(e.provenanceAmbiguity.directRewrite,e.provenanceAmbiguity.candidates):e.alternativeOrigins?Qn(e.alternativeOrigins.map(i=>hi(i,n,t)),"required",Ue(e.alternativeOrigins)):e.rowBinding?go(e,n):n.length===0?Be(e.provenance):Ke()}function vc(e,n,t){let i=[];for(let r of e.properties)V.isSpreadAssignment(r)?i.push(ve(r.expression,n,[],t)):V.isShorthandPropertyAssignment(r)?i.push(ve(r.name,n,[],t)):V.isPropertyAssignment(r)?i.push(ve(r.initializer,n,[],t)):i.push(Ke());return dr(i)}function Rc(e,n,t,i){let[r,...s]=t,o=[];for(let a of[...e.properties].reverse()){let u;if(V.isSpreadAssignment(a)){u=ve(a.expression,n,t,i);let c=gn(a.expression,n,r);c.kind==="found"&&(u=lr(u,Ue(c.origins)))}else V.isShorthandPropertyAssignment(a)&&a.name.text===r?u=lr(ve(a.name,n,s,i),[...Ie(a.name,n)]):V.isPropertyAssignment(a)&&H(a.name)===r&&(u=lr(ve(a.initializer,n,s,i),[...Ie(a.initializer,n)]));if(!(!u||u.kind==="absent")){if(u.kind==="ambiguous")return u;if(u.presence==="optional"){o.push(u);continue}return Qn([...o,u],"required")}}return o.length>0?Qn(o,"optional"):Vt()}function go(e,n){return n.length===0?Be("Shape"):e.objectFields&&!e.objectFields.includes(n[0])?Vt():n.length>1?Ke():{...Be("Shape"),presence:e.nullableRead?"optional":"required"}}function Dc(e,n,t){if(t.length===0)return Be("Shape");let i=bo(e.arguments[0],n);return i&&!i.includes(t[0])?Vt():t.length>1?Ke():{...Be("Shape"),presence:"optional"}}function dr(e){let n=e.find(i=>i.kind==="ambiguous");if(n?.kind==="ambiguous")return n;let t=e.flatMap(i=>i.kind==="known"?[i.provenance]:[]);return Be(Ei(t))}function Qn(e,n,t=[]){let i=e.filter(a=>a.kind==="known"),r=e.flatMap(a=>a.kind==="absent"?[]:a.candidates??(a.kind==="ambiguous"&&a.directRewrite?[a.directRewrite]:[])),s=[...new Set([...t,...r])];if(i.length!==e.length){let a=e.some(u=>u.kind==="absent"||u.kind==="ambiguous"&&!u.directRewrite&&(u.candidates?.length??0)===0);return Ke(void 0,a?[...new Set([...s,Mn])]:s)}let o=i[0]?.provenance;return!o||i.some(a=>a.provenance!==o)?Ke(void 0,s):{kind:"known",provenance:o,presence:n,...s.length>0?{candidates:s}:{}}}function Be(e,n){return{kind:"known",provenance:e,presence:"required",...n&&n.length>0?{candidates:n}:{}}}function Vt(){return{kind:"absent"}}function Ke(e,n){return{kind:"ambiguous",...e?{directRewrite:e}:{},...n&&n.length>0?{candidates:n}:{}}}function lr(e,n){return e.kind==="absent"||n.length===0?e:{...e,candidates:[...new Set([...e.candidates??[],...n])]}}function yo(e,n){return oe(e).endsWith(".get")&&We(e.expression,t=>Oe(t,"db",n))}function bo(e,n){if(!e)return;let i=ye(e)?.split(".")[0],r=i&&n.tables.get(i)?.columns;return r?[...new Set(["id",...Object.keys(r)])]:void 0}function Lc(e,n,t,i){let r=h(e),s=[],o=(l,f,d)=>{let p=Pc(l,n,f,d);return s.push(...p.candidates),p.replacement},a=V.isArrayLiteralExpression(r)?`[${r.elements.map(l=>{let f=V.isSpreadElement(l)?l.expression:l,d=ve(f,n,[],e);return d.kind==="known"?l.getText(n.sourceFile):d.kind==="ambiguous"&&d.directRewrite?o(f,d.directRewrite):o(f,void 0,d.kind==="ambiguous"?d.candidates:void 0)}).join(", ")}]`:o(r,t,i),u=[...new Set(s)],c=u.length>0?`; candidate direct origins: ${u.join(", ")}`:"";w(n,"E_PROVENANCE_AMBIGUOUS",e,`read key provenance is ambiguous; each key must follow one direct origin rule${c}`,K(n.source,e,a))}function Pc(e,n,t,i){let r=[...new Set([...i??[],...t?[t]:[]])];return r.length===1&&r[0]!==Mn?{replacement:r[0],candidates:r}:r.length>1?po(r):po(r.length===0?[Mn]:r)}function po(e){let n=e.length>0?e.join(" | "):"no bound direct origins";return{replacement:`(() => { throw new Error(${JSON.stringify(`E_PROVENANCE_AMBIGUOUS: choose one direct origin: ${n}`)}); })()`,candidates:e}}function Ei(e){if(e.includes("Computed"))return"Computed";let n=new Set(e.filter(t=>t!=="Const"));return n.size===0?"Const":n.size===1?[...n][0]:"Shape"}function Hn(e,n){return je(n,e,"row expression",()=>Fc(e,n))}function Fc(e,n){let t=h(e),i=V.isIdentifier(t)?n.substitutions.get(t.text):void 0;if(i)return Hn(i.expression,i.environment);if(V.isIdentifier(t))return n.variables.get(t.text)?.rowBinding===!0;let r=N(t);if(!r)return!1;let s=Ce(r,n);return s?Hn(s.expression,s.environment):yo(r,n)}function cn(e,n){return je(n,e,"row collection",()=>jc(e,n))}function jc(e,n){let t=h(e),i=V.isIdentifier(t)?n.substitutions.get(t.text):void 0;if(i)return cn(i.expression,i.environment);if(V.isIdentifier(t))return n.variables.get(t.text)?.rowCollection===!0;let r=N(t);if(!r)return!1;let s=Ce(r,n);if(s)return cn(s.expression,s.environment);if(oe(r).endsWith(".scan")&&We(r.expression,u=>Oe(u,"db",n)))return!0;if(!V.isPropertyAccessExpression(r.expression))return!1;if(["filter","sort","slice"].includes(r.expression.name.text))return cn(r.expression.expression,n);if(r.expression.name.text==="flatMap"){if(!cn(r.expression.expression,n))return!1;let u=r.arguments[0];if(!u||!V.isArrowFunction(u)&&!V.isFunctionExpression(u)||u.parameters.length===0||!V.isIdentifier(u.parameters[0].name)||V.isBlock(u.body))return!1;let c=h(u.body);if(!V.isArrayLiteralExpression(c))return!1;let l=kn(n);return l.variables.set(u.parameters[0].name.text,{provenance:"Shape",rowBinding:!0,objectFields:bo(r.expression.expression,n)}),c.elements.every(f=>!V.isSpreadElement(f)&&Hn(f,l))}if(r.expression.name.text!=="map")return!1;let o=r.arguments[0];if(!o||!V.isArrowFunction(o)&&!V.isFunctionExpression(o)||o.parameters.length===0||!V.isIdentifier(o.parameters[0].name)||V.isBlock(o.body))return!1;let a=h(o.body);return V.isIdentifier(a)&&a.text===o.parameters[0].name.text&&cn(r.expression.expression,n)}import de from"typescript";function Qe(e,n){return je(n,e,"object fields",()=>Bc(e,n))}function Bc(e,n){let t=h(e);if(de.isIdentifier(t)){let s=n.substitutions.get(t.text);if(s)return Qe(s.expression,s.environment);let o=n.variables.get(t.text);return o?.operationComposite==="args"?Object.keys(n.args):o?.operationComposite==="ctx"?["viewer"]:o?.objectFields??(o?.immutableOrigin?Qe(o.immutableOrigin.expression,o.immutableOrigin.environment):void 0)}if(de.isPropertyAccessExpression(t)){let s=zn(t.expression,t.name.text,n);return s&&Qe(s.expression,s.environment)}if(de.isObjectLiteralExpression(t)){let s=[];for(let o of t.properties){if(de.isSpreadAssignment(o)){let u=Qe(o.expression,n);if(!u)return;for(let c of u)s.includes(c)||s.push(c);continue}if(de.isShorthandPropertyAssignment(o)){s.includes(o.name.text)||s.push(o.name.text);continue}if(!de.isPropertyAssignment(o))return;let a=H(o.name);if(!a)return;s.includes(a)||s.push(a)}return s}let i=N(t),r=i&&Ce(i,n);if(r)return Qe(r.expression,r.environment);if(i&&oe(i).endsWith(".get")&&We(i.expression,s=>Oe(s,"db",n)))return xo(i.arguments[0],n);if(i&&de.isPropertyAccessExpression(i.expression)&&i.expression.name.text==="require")return Qe(i.expression.expression,n)}function zn(e,n,t){let i=h(e);if(de.isIdentifier(i)){let o=t.substitutions.get(i.text);if(o)return zn(o.expression,n,o.environment);let a=t.variables.get(i.text)?.immutableOrigin;return a&&zn(a.expression,n,a.environment)}if(de.isPropertyAccessExpression(i)){let o=zn(i.expression,i.name.text,t);return o&&zn(o.expression,n,o.environment)}if(de.isObjectLiteralExpression(i)){for(let o of[...i.properties].reverse()){if(de.isSpreadAssignment(o)){let a=Qe(o.expression,t);if(!a)return;if(a.includes(n))return zn(o.expression,n,t);continue}if(de.isShorthandPropertyAssignment(o)&&o.name.text===n)return{expression:o.name,environment:t};if(de.isPropertyAssignment(o)&&H(o.name)===n)return{expression:o.initializer,environment:t}}return}let r=N(i),s=r&&Ce(r,t);return s&&zn(s.expression,n,s.environment)}function Sn(e,n){return je(n,e,"row collection fields",()=>qc(e,n))}function qc(e,n){let t=h(e);if(de.isIdentifier(t)){let s=n.substitutions.get(t.text);if(s)return Sn(s.expression,s.environment);let o=n.variables.get(t.text);return o?.rowCollection?o.objectFields:void 0}let i=N(t);if(!i)return;let r=Ce(i,n);if(r)return Sn(r.expression,r.environment);if(oe(i).endsWith(".scan")&&We(i.expression,s=>Oe(s,"db",n)))return xo(i.arguments[0],n);if(de.isPropertyAccessExpression(i.expression)&&["filter","sort","slice"].includes(i.expression.name.text))return Sn(i.expression.expression,n);if(de.isPropertyAccessExpression(i.expression)&&i.expression.name.text==="map"){let s=i.arguments[0];if(s&&ge(s)&&s.parameters.length>0&&!de.isBlock(s.body)&&de.isIdentifier(s.parameters[0].name)){let o=h(s.body);if(de.isIdentifier(o)&&o.text===s.parameters[0].name.text)return Sn(i.expression.expression,n)}}if(de.isPropertyAccessExpression(i.expression)&&i.expression.name.text==="flatMap"&&cn(i,n))return Sn(i.expression.expression,n)}function xi(e,n){let t=h(e);if(de.isIdentifier(t)&&n.variables.get(t.text)?.nullableRead)return t.text;let i=N(t);return i&&oe(i).endsWith(".get")&&We(i.expression,r=>Oe(r,"db",n))?i.getText(n.sourceFile):void 0}function ki(e,n,t){let r=t.includes(".get(")?`const row = ${t};
4
+ db.require(row !== null, "ROW_REQUIRED");
5
+ { ...row }`:`db.require(${t} !== null, "ROW_REQUIRED");
6
+ { ...${t} }`;w(n,"E_OPAQUE",e,`nullable db.get result ${t} cannot be spread before it is required`,r)}function ho(e,n){let t=n.expression.getText(e.sourceFile);return K(e.source,n,`field: ${t}.field`)}function Eo(e,n){let t=n.expression.getText(e.sourceFile);return K(e.source,n,`${t}[0], ${t}[1]`)}function xo(e,n){if(!e)return;let t=h(e),i=de.isIdentifier(t)?t.text:de.isPropertyAccessExpression(t)&&de.isIdentifier(t.expression)?t.expression.text:void 0,r=i&&n.tables.get(i)?.columns;if(r)return[...new Set(["id",...Object.keys(r)])]}import Xe from"typescript";function fr(e,n){let t=h(e);if(!Xe.isPropertyAccessExpression(t))return;let i=h(t.expression);if(!Xe.isIdentifier(i)||n.variables.get(i.text)?.operationComposite!=="args")return;let r=n.args[t.name.text];return{name:t.name.text,...r&&typeof r!="string"&&"List"in r?{max:r.List.max}:{}}}function Ut(e,n){let t=Ae(e,n);return t===void 0?{}:{max:t,boundSource:`${e.getText()} static bound`}}function Ae(e,n){return je(n,e,"static bound",()=>Vc(e,n))}function Vc(e,n){let t=h(e);if(Xe.isIdentifier(t)){let o=n.substitutions.get(t.text);if(o)return Ae(o.expression,o.environment);let a=n.variables.get(t.text);return a?.max??(a?ko(a,Ae):void 0)}let i=fr(t,n);if(i)return i.max;if(Xe.isPropertyAccessExpression(t)){let o=gn(t.expression,n,t.name.text);if(o.kind==="found"){let a=o.origins.map(u=>So(u,Ae));if(a.every(u=>u!==void 0))return Math.max(...a)}}if(Xe.isArrayLiteralExpression(t)){let o=0;for(let a of t.elements)if(Xe.isSpreadElement(a)){let u=Ae(a.expression,n);if(u===void 0)return;o+=u}else o+=1;return o}if(Xe.isConditionalExpression(t)){let o=Ae(t.whenTrue,n),a=Ae(t.whenFalse,n);return o===void 0||a===void 0?void 0:Math.max(o,a)}if(Xe.isNewExpression(t)&&On(t)){let o=t.arguments?.[0];return o?Ae(o,n):0}let r=N(e),s=r&&Ce(r,n);if(s)return Ae(s.expression,s.environment);if(r&&oe(r).endsWith(".scan")){let o=Uc(r);if(typeof o=="number")return o}if(r&&Xe.isIdentifier(r.expression)&&r.expression.text==="mergeByIndex")return Fe(r.arguments[3]);if(r&&Xe.isIdentifier(r.expression)&&r.expression.text==="mentionTokens")return 85;if(r&&Xe.isPropertyAccessExpression(r.expression)){let o=r.expression.name.text,a=Ae(r.expression.expression,n);if(o==="map"||o==="filter"||o==="sort")return a;if(o==="slice"){let u=Fe(r.arguments[0])??0,c=Fe(r.arguments[1]);return c===void 0?a:Math.max(0,c-u)}if(o==="flatMap"&&a!==void 0){let u=r.arguments[0];if(u&&ge(u)&&!Xe.isBlock(u.body)){let c=Ae(u.body,n);if(c!==void 0)return a*c}}}}function ko(e,n){if(!e.alternativeOrigins||e.alternativeOrigins.length===0)return;let t=e.alternativeOrigins.map(i=>So(i,n));return t.every(i=>i!==void 0)?Math.max(...t):void 0}function So(e,n){return"binding"in e?e.binding.max??ko(e.binding,n):n(e.expression,e.environment)}function Uc(e){let n=e.arguments[2];if(!n||!Xe.isObjectLiteralExpression(n))return;let t=$e(n,"take");return t?Fe(t)??"arg":void 0}function Si(e,n,t){let i=e.collectionIdentity;return i?(t.collectionMutationCounts&&Kt(t.collectionMutationCounts,i,1,n),t.deferredCollectionMutations.has(i)?0:1):1}function Kt(e,n,t,i){let r=e.get(n),s=(r?.count??0)+t;e.set(n,{count:s,name:r?.name??i})}function Je(e,n){return pr(e,"max",n.max),pr(e,"boundSource",n.boundSource),pr(e,"elementOrigins",n.elementOrigins),e}function wo(e,n,t,i){let r=Ve(e,n);return{...t!==void 0?{max:t,boundSource:i}:{},...r!==void 0?{elementOrigins:r}:t===0?{elementOrigins:[]}:{}}}function wi(e,n,t,i,r){let s=e.elementOrigins??(e.max===0?[]:void 0);if(!s){let u=new Set(["unknown prior collection origin",...e.provenanceAmbiguity?.candidates??[],...e.provenanceAmbiguity?.directRewrite?[e.provenanceAmbiguity.directRewrite]:[],...Kc(e),...Ue([{expression:n,environment:t}])]);e.provenance="Computed",e.provenanceAmbiguity=un([...u]),Je(e,{});return}let o=[...s,{expression:n,environment:kn(t)}];Je(e,{...e.max!==void 0?{max:e.max+i}:{},...e.max!==void 0?{boundSource:i>0?`${n.getText(t.sourceFile)} push count`:e.boundSource}:{},elementOrigins:o});let a=r(o,n);a.provenanceAmbiguity?(e.provenance=a.provenance,e.provenanceAmbiguity=a.provenanceAmbiguity):e.provenanceAmbiguity||(e.provenance=a.provenance)}function $o(e,n,t,i,r){let s=Ve(n,t);if(!(e.collection!==void 0||e.max!==void 0||e.elementOrigins!==void 0||i!==void 0||s!==void 0))return;let a=e.elementOrigins??(e.max===0?[]:void 0);Je(e,{...e.max!==void 0&&i!==void 0?{max:Math.max(e.max,i),boundSource:r??e.boundSource}:{},...a!==void 0&&s!==void 0?{elementOrigins:[...a,...s]}:{}})}function Ao(e,n,t){if(!(e.collection!==void 0||e.max!==void 0||e.elementOrigins!==void 0||n.some(o=>o.collection!==void 0||o.max!==void 0||o.elementOrigins!==void 0)))return;let r=n.map(o=>o.max),s=n.map(o=>o.elementOrigins);Je(e,{...r.every(o=>o!==void 0)?{max:Math.max(...r),boundSource:t}:{},...s.every(o=>o!==void 0)?{elementOrigins:s.flat()}:{}})}function Kc(e){return e.immutableOrigin?Ue([e.immutableOrigin]):[]}function pr(e,n,t){n==="max"?t===void 0?delete e.max:e.max=t:n==="boundSource"?t===void 0?delete e.boundSource:e.boundSource=t:t===void 0?delete e.elementOrigins:e.elementOrigins=t}import fe from"typescript";var P={kind:"unknown"},Qc={kind:"int"},ln={kind:"string",id:!0};function be(e){return e?.kind==="string"&&e.id===!0}function Wn(e){if(e==="Int"||e==="Time")return Qc;if(e==="Bool")return{kind:"bool"};if(e==="Id")return ln;if(e==="Principal")return{kind:"principal"};if(!e||typeof e!="object"||Array.isArray(e))return P;let n=e;return n.Text?{kind:"string",max:n.Text.max}:n.Bytes?{kind:"bytes",max:n.Bytes.max}:n.Image?{kind:"asset",asset:"image",max:n.Image.max}:n.Video?{kind:"asset",asset:"video",max:n.Video.max}:n.Ref?ln:n.Json?{kind:"json",max:n.Json.max_bytes}:n.Enum?{kind:"enum",variants:[...n.Enum.variants]}:n.Decimal?{kind:"decimal",scale:n.Decimal.scale}:n.Money?{kind:"decimal",scale:n.Money.scale,currency:n.Money.currency}:"Optional"in n?{kind:"optional",of:Wn(n.Optional)}:n.List?{kind:"list",of:Wn(n.List.of),max:n.List.max}:P}function ee(e){return e?.kind==="optional"?ee(e.of):e??P}function mr(e,n){return e.kind==="decimal"&&n.kind==="decimal"&&e.scale===n.scale&&e.currency===n.currency}function Oo(e,n,t,i,r){let o=[...n.tables.values()].find(a=>a.name===t)?.indexes?.[i];return!o||r<=o.columns.length?!0:(n.diagnostics.push(L(n,"E_ARGS_TYPE",e,`scan ${n.siteBase}.${n.accessOrdinal.value} prefix supplies ${r} components but ${t}.${i} has ${o.columns.length} columns`,zc(e,n,o.columns.length))),!1)}function hr(e,n,t,i,r){if(!e)return;let s=h(e),a=[...n.tables.values()].find(R=>R.name===t)?.indexes?.[i];if(!a)return;let u=a.columns.slice(r),c=a.types.slice(r);if(u.length===0){n.diagnostics.push(L(n,"E_ARGS_CURSOR_SHAPE",s,`scan ${t}.${i} prefix names every index column, so a cursor has no position to compare; remove after/before or shorten the prefix`,Hc(e,n)));return}if(a.columns.at(-1)!=="id"&&a.unique!==!0){let R=[...a.columns.filter(D=>D!=="id"),"id"];n.diagnostics.push(L(n,"E_ARGS_CURSOR_INDEX",s,`scan ${t}.${i} uses a cursor, so the index must be a total order: end in id, or be unique`,`change ${t}.${i} to { columns: [${R.map(D=>JSON.stringify(D)).join(", ")}] }`));return}let l=Ce(s,n),f=h(l?.expression??s),d=l?.environment??n,p=yr(f,d),g=fe.isArrayLiteralExpression(f)?[...f.elements]:void 0,m=gr(f,d)||$i(p)===!1;if(u.length===1&&!g&&m){n.diagnostics.push(L(n,"E_ARGS_CURSOR_SHAPE",s,`scan ${t}.${i} cursor must be an indexable scalar for its one remaining index column`,_o(e,n,u,c)));return}let y=g?g.length===u.length:$i(p)===!0?u.length===1:$i(p)===!1?u.length===1?void 0:!1:void 0,b=Wc(e,n,t,u),S=b?K(n.source,e,b):n.source,E=b&&S!==n.source?S:_o(e,n,u,c);if(y===!1){n.diagnostics.push(L(n,"E_ARGS_CURSOR_SHAPE",s,`scan ${t}.${i} cursor has the wrong static shape: expected exactly ${u.length} cursor value(s), one per remaining index column`,E));return}let k=g??(u.length===1?[f]:void 0);if(!k||k.length!==u.length)return;let $=e.parent&&fe.isPropertyAssignment(e.parent)?H(e.parent.name)??"after":"after";k.forEach((R,D)=>{let J=yr(R,d),se=c[D];Io(J,se)===!1&&n.diagnostics.push(L(n,"E_ARGS_TYPE",R,`scan ${n.siteBase}.${n.accessOrdinal.value} ${$} cursor component ${D+1} is ${To(J)} but ${t}.${i} column ${u[D]} is ${To(se)}`,E))})}function gr(e,n,t=new Set){let i=h(e);if(t.has(i))return!1;if(t.add(i),fe.isObjectLiteralExpression(i))return!0;if(!fe.isIdentifier(i))return!1;let r=n.substitutions.get(i.text);if(r)return gr(r.expression,r.environment,t);let s=n.variables.get(i.text)?.immutableOrigin;return s?gr(s.expression,s.environment,t):!1}function Hc(e,n){let t=e.parent,i=t?.parent;return!t||!fe.isPropertyAssignment(t)||!i||!fe.isObjectLiteralExpression(i)?n.source:K(n.source,i,Co(i,n))}function zc(e,n,t){let i=h(e),r=fe.isArrayLiteralExpression(i)?`[${i.elements.slice(0,t).map(c=>c.getText(n.sourceFile)).join(", ")}]`:"[]",s=e.parent,o=s&&fe.isCallExpression(s)&&s.arguments[1]===e?s.arguments[2]:void 0,a=o&&fe.isObjectLiteralExpression(h(o))?h(o):void 0,u=[{start:e.getStart(n.sourceFile),end:e.getEnd(),value:r}];return a&&t>0&&u.push({start:a.getStart(n.sourceFile),end:a.getEnd(),value:Co(a,n)}),Mo(n.source,u)}function Co(e,n){return`{ ${e.properties.filter(i=>{if(!fe.isPropertyAssignment(i)&&!fe.isShorthandPropertyAssignment(i))return!0;let r=H(i.name);return r!=="after"&&r!=="before"}).map(i=>i.getText(n.sourceFile)).join(", ")} }`}function yr(e,n){let t=h(e);if(fe.isIdentifier(t)){let i=n.variables.get(t.text)?.immutableOrigin;if(i)return yr(i.expression,i.environment)}if(fe.isPropertyAccessExpression(t)){let i=h(t.expression);if(fe.isIdentifier(i)&&n.variables.get(i.text)?.operationComposite==="args")return Wn(n.args[t.name.text]);let r=n.expressionTypes.get(Ye(n.literalContext,i,n.sourceFile)),s=ee(r);if(s.kind==="row"){let a=[...n.tables.values()].find(u=>u.name===s.table)?.columns?.[t.name.text];if(a)return a}}return n.expressionTypes.get(Ye(n.literalContext,t,n.sourceFile))}function $i(e){if(e?.kind==="optional"||e?.kind==="row"||e?.kind==="asset")return;let n=ee(e);if(!(n.kind==="unknown"||n.kind==="json"||n.kind==="list"))return n.kind!=="object"}function Io(e,n){if(e?.kind==="optional"){let r=Io(e.of,n);return r===!1?void 0:r}let t=ee(e),i=ee(n);if(t.kind==="null")return!0;if(!(t.kind==="unknown"||t.kind==="json"||t.kind==="row"||i.kind==="unknown"))return i.kind==="json"?$i(t):be(i)||i.kind==="principal"?be(t)||t.kind==="principal":i.kind==="string"||i.kind==="enum"?t.kind==="string"&&!be(t)||t.kind==="enum":i.kind==="int"||i.kind==="decimal"?t.kind==="int"||t.kind==="decimal":i.kind==="bool"?t.kind==="bool":i.kind==="bytes"?t.kind==="bytes":!1}function To(e){let n=ee(e);return be(n)||n.kind==="principal"?"Id":n.kind==="string"||n.kind==="enum"?"String":n.kind==="int"||n.kind==="decimal"?"Int":n.kind==="bool"?"Bool":n.kind==="bytes"?"Bytes":n.kind==="null"?"Null":n.kind==="list"?"array":n.kind==="row"||n.kind==="object"?"object":"unknown"}function Wc(e,n,t,i){let r=h(e),s=c=>{let l=h(c);if(fe.isPropertyAccessExpression(l)){let f=h(l.expression);if(fe.isIdentifier(f)&&No(n.variables.get(f.text))===t)return l.expression;let d=n.expressionTypes.get(Ye(n.literalContext,f,n.sourceFile));if(ee(d).kind==="row")return l.expression}};if(fe.isArrayLiteralExpression(r)){let c=r.elements.map(s),l=c[0]?.getText(n.sourceFile);return l&&c.every(f=>f?.getText(n.sourceFile)===l)?`[${i.map(f=>`${l}.${f}`).join(", ")}]`:void 0}let o=s(r)?.getText(n.sourceFile),a=[...n.variables].find(([,c])=>c.rowBinding&&No(c)===t)?.[0],u=o??a;if(u)return`[${i.map(c=>`${u}.${c}`).join(", ")}]`;if(i.length===1&&!fe.isArrayLiteralExpression(r))return r.getText(n.sourceFile)}function No(e){return e?e.rowTable?e.rowTable:e.identityExpression?.Get?.table:void 0}function _o(e,n,t,i){let r=Jc(e),s=r?.arguments[0],o=r?.arguments[1];if(!s||!o||!fe.isObjectLiteralExpression(h(s)))return n.source;let a=h(s),c=(e.parent&&fe.isPropertyAssignment(e.parent)?H(e.parent.name):void 0)==="before"?"before":"after",l=new Set(Object.keys(n.args)),f=t.map(S=>Gc(l,`${c}${S[0]?.toUpperCase()??""}${S.slice(1)}`)),d=f.map((S,E)=>`${S}: ${br(i[E])}`).join(", "),g=`${a.getText(n.sourceFile).slice(0,-1).trimEnd()}${a.properties.length===0?" ":", "}${d} }`,m=[{start:a.getStart(n.sourceFile),end:a.getEnd(),value:g},{start:e.getStart(n.sourceFile),end:e.getEnd(),value:`[${f.map(S=>`__ARGS__.${S}`).join(", ")}]`}],y=[...n.variables].find(([,S])=>S.operationComposite==="args")?.[0],b=fe.isArrowFunction(o)||fe.isFunctionExpression(o)?o.parameters[0]?.name:void 0;if(!y&&b&&fe.isObjectBindingPattern(b)){y=Yc(n.source,"snapbackArgs");let S=b.getText(n.sourceFile);m.push({start:b.getStart(n.sourceFile),end:b.getEnd(),value:`${S.slice(0,-1).trimEnd()}${b.elements.length===0?" ":", "}args: ${y} }`})}return y?(m[1].value=m[1].value.replaceAll("__ARGS__",y),Mo(n.source,m)):n.source}function Jc(e){for(let n=e.parent;n;n=n.parent)if(fe.isCallExpression(n)&&["query","mutation"].includes(oe(n)))return n}function Gc(e,n){let t=n,i=1;for(;e.has(t);)t=`${n}${i++}`;return e.add(t),t}function Yc(e,n){let t=n,i=1;for(;new RegExp(`\\b${t}\\b`).test(e);)t=`${n}${i++}`;return t}function br(e){if(!e)return"t.json(4096)";if(be(ee(e)))return"t.id()";switch(e.kind){case"optional":return`t.optional(${br(e.of)})`;case"int":return"t.int()";case"principal":return"t.principal()";case"string":return`t.text(${e.max??4096})`;case"bytes":return`t.bytes(${e.max})`;case"asset":return`t.${e.asset}(${e.max})`;case"bool":return"t.bool()";case"enum":return`t.enum(${JSON.stringify(e.variants)})`;case"decimal":return e.currency?`t.money(${JSON.stringify(e.currency)}, ${e.scale})`:`t.decimal(${e.scale})`;case"list":return`t.list(${br(e.of)}, { max: ${e.max??64} })`;default:return"t.json(4096)"}}function Mo(e,n){let t=e;for(let i of n.sort((r,s)=>s.start-r.start))t=`${t.slice(0,i.start)}${i.value}${t.slice(i.end)}`;return t}function Ai(e){return e.slice(1).reduce((n,t)=>({Builtin:{builtin:"Concat",args:[n,t]}}),e[0])}function Xc(e,n){if(!e)return;let t=h(e),i=M.isIdentifier(t)?t.text:M.isPropertyAccessExpression(t)&&M.isIdentifier(t.expression)?t.expression.text:void 0,r=i&&n.tables.get(i)?.columns;if(r)return[...new Set(["id",...Object.keys(r)])]}function Lo(e,n){let t=h(e);return M.isIdentifier(t)&&n.variables.get(t.text)?.rowCollection?!1:Qe(e,n)!==void 0||Hn(e,n)}function xr(e,n,t){let i=M.isIdentifier(e.expression)?t.variables.get(e.expression.text)?.collection:void 0;return e.name.text==="length"&&!Lo(e.expression,t)||e.name.text==="size"&&i?{Builtin:{builtin:"Len",args:[n]}}:{Field:{base:n,name:e.name.text}}}function Po(e,n,t,i){let r=[],s=e;for(;M.isPropertyAccessChain(s);)r.unshift(s),s=s.expression;let o=t(s,n,i),a=G(n,"optionalBase"),u=G(n,"optionalValue"),c=(l,f)=>{let d=r[l],p=xr(d,f,n),g=l===r.length-1?[{Assign:{name:u,value:p}}]:(()=>{let m=G(n,"optionalStep");return[{Let:{name:m,value:p}},...c(l+1,{Variable:m})]})();return d.questionDotToken?[{If:{condition:{Binary:{op:"Ne",left:f,right:re(null)}},then_body:g,else_body:[]}}]:g};return{statements:[...o.statements,{Let:{name:a,value:o.expression}},{Let:{name:u,value:re(null)}},...c(0,{Variable:a})],expression:{Variable:u}}}function Ti(e){if("Page"in e)return"Literal"in e.Page.take?e.Page.take.Literal:e.Page.take.Arg.max;if("LiteralRange"in e)return Math.max(0,e.LiteralRange.end_exclusive-e.LiteralRange.start);if("ArgList"in e)return e.ArgList.max;if("DerivedArray"in e)return e.DerivedArray.max;let n=e.Recurse;if(n.fanout===0)return 1;if(n.fanout===1)return n.depth+1;let t=(n.fanout**(n.depth+1)-1)/(n.fanout-1);return Number.isSafeInteger(t)?t:Number.MAX_SAFE_INTEGER}function Fo(e,n){if(M.isArrowFunction(e)||M.isFunctionExpression(e)){(e.parameters.length!==1||!M.isIdentifier(e.parameters[0].name))&&w(n,"E_OPAQUE",e,"write callback must have one identifier parameter"),M.isBlock(e.body)&&w(n,"E_OPAQUE",e.body,"write callback body must be an expression");let t=Ze(n),i=e.parameters[0].name.text;return t.variables.set(i,{provenance:"Shape",rowBinding:!0}),U(e.body,t)}return U(e,n)}function Er(e,n,t,i){return je(n,e,"loop domain",()=>Zc(e,n,t,i))}function Zc(e,n,t,i){let r=Ce(e,n);if(r)return Er(r.expression,r.environment,t,i);let s=N(e);if(s&&oe(s).endsWith(".scan")){let c=vn(s.arguments[0],n);return{domain:{Page:jo(s,n,i??`${n.programName}.${c.table}`)},bindingInfo:{provenance:"Shape",objectFields:Xc(s.arguments[0],n),rowBinding:!0,rowTable:c.table}}}if(s&&M.isIdentifier(s.expression)&&s.expression.text==="range"){let c=Fe(s.arguments[0]),l=Fe(s.arguments[1]);return(c===void 0||l===void 0)&&w(n,"E_UNBOUND_LOOP",s,"literal range requires literal endpoints"),{domain:{LiteralRange:{start:c,end_exclusive:l}},bindingInfo:{provenance:"Const"}}}if(s&&M.isIdentifier(s.expression)&&s.expression.text==="mentionTokens"){let c=s.arguments[0];return c||w(n,"E_OPAQUE",s,"mentionTokens requires text"),{domain:{DerivedArray:{value:{Builtin:{builtin:"MentionTokens",args:[U(c,n)]}},max:85,bound_source:"messages.body max 256 / min whitespace mention 3"}},bindingInfo:{provenance:"Computed"}}}if(s&&M.isIdentifier(s.expression)&&s.expression.text==="recurse")return el(s,n);let o=fr(e,n);if(o?.max!==void 0)return{domain:{ArgList:{name:o.name,max:o.max}},bindingInfo:dt(e,n)};let a=o?void 0:or(e,c=>n.variables.get(c)?.operationComposite==="args");if(a){let c=n.variables.get(a);if(c?.max!==void 0)return c.operationArgument&&n.args[c.operationArgument]&&typeof n.args[c.operationArgument]!="string"?{domain:{ArgList:{name:c.operationArgument,max:c.max}},bindingInfo:dt(e,n)}:{domain:{DerivedArray:{value:{Variable:a},max:c.max,bound_source:c.boundSource??`${a} declared max`}},bindingInfo:{provenance:c.provenance,...c.provenanceAmbiguity?{provenanceAmbiguity:{...c.provenanceAmbiguity}}:{},...c.rowCollection?{rowBinding:!0,objectFields:c.objectFields}:{},...c.elementOrigins?{alternativeOrigins:c.elementOrigins}:{}}}}let u=Ae(e,n);if(u!==void 0)return{domain:{DerivedArray:{value:U(e,n),max:u,bound_source:`${e.getText(n.sourceFile)} static bound`}},bindingInfo:dt(e,n)};w(n,"E_UNBOUND_LOOP",e,"loop domain has no static cardinality")}function el(e,n){let t=e.arguments[0],i=e.arguments[1],r=e.arguments[2];(!t||!i||!ge(i)||!r||!M.isObjectLiteralExpression(r))&&w(n,"E_OPAQUE",e,"recurse requires seed, inline step, depth, and fanout");let s=sr(r,"depth"),o=sr(r,"fanout");(s===void 0||o===void 0)&&w(n,"E_UNBOUND_LOOP",r,"recurse bounds must be literals"),s>1e4&&w(n,"E_UNBOUND_LOOP",r,"recurse depth must be at most 10000"),(i.parameters.length!==1||!M.isIdentifier(i.parameters[0].name))&&w(n,"E_OPAQUE",i,"recurse step requires exactly one row parameter");let a=i.parameters[0].name.text,u=M.isBlock(i.body)&&i.body.statements.length===1&&M.isReturnStatement(i.body.statements[0])?i.body.statements[0].expression:M.isBlock(i.body)?void 0:i.body,c=u&&N(u);(!c||!oe(c).endsWith(".get")||!We(c.expression,d=>Oe(d,"db",n)))&&w(n,"E_OPAQUE",i,"recurse step must be exactly one get through the operation db binding");let l=vn(c.arguments[0],n),f=c.arguments[1];return(!f||!M.isPropertyAccessExpression(f)||!M.isIdentifier(f.expression)||f.expression.text!==a)&&w(n,"E_OPAQUE",c,"recurse step key must be a field of its bound row parameter"),{domain:{Recurse:{site:pt(n),table:l.table,index:l.index,seed:U(t,n),next_field:f.name.text,depth:s,fanout:o,provenance:"Shape"}},bindingInfo:{provenance:"Shape",rowBinding:!0,rowTable:l.table}}}function U(e,n,t){return je(n,e,"expression",()=>nl(e,n,t))}function nl(e,n,t){let i=M.isIdentifier(e)?n.substitutions.get(e.text):void 0;if(i)return U(i.expression,i.environment,t);let r=h(e);if(r!==e)return U(r,n,t);if(e.kind===M.SyntaxKind.NullKeyword)return re(null);if(e.kind===M.SyntaxKind.TrueKeyword)return re(!0);if(e.kind===M.SyntaxKind.FalseKeyword)return re(!1);if(M.isNumericLiteral(e)){let s=n.literalValues.get(Ye(n.literalContext,e,n.sourceFile)),o=Cn(e.text),a=!Number.isInteger(Number(e.text))||(o?.fraction.length??0)>0;if(a&&s===void 0){let u=Math.max(1,o?.fraction.length??0);w(n,"E_DECIMAL_SCALE",e,`fractional literal ${e.text} has no known Decimal scale`,K(n.source,e,`decimal(${e.text}, ${u})`))}return!a&&s===void 0&&o&&BigInt(o.whole)>9007199254740991n&&w(n,"E_OPAQUE",e,`integer literal ${e.text} is outside the safe integer range`,K(n.source,e,"9007199254740991")),re(s??Number(e.text))}if(M.isStringLiteralLike(e)){let s=n.expressionTypes.get(Ye(n.literalContext,e,n.sourceFile));return be(s)&&!M.isVariableDeclaration(e.parent)?{Literal:{Id:e.text}}:re(e.text)}if(M.isIdentifier(e)){let s=n.variables.get(e.text),o=n.expressionTypes.get(Ye(n.literalContext,e,n.sourceFile));return be(o)&&s?.identityExpression&&"Literal"in s.identityExpression&&typeof s.identityExpression.Literal=="object"&&s.identityExpression.Literal!==null&&"String"in s.identityExpression.Literal?{Literal:{Id:s.identityExpression.Literal.String}}:s?.operationComposite==="args"?{Object:Object.fromEntries(Object.keys(n.args).map(a=>[a,{Variable:a}]))}:s?.operationComposite==="ctx"?{Object:{viewer:{Input:"Viewer"}}}:{Variable:e.text}}if(M.isArrayLiteralExpression(e)){let s=[],o=[],a=()=>{o.length>0&&s.push({Array:o}),o=[]};for(let u of e.elements)try{M.isSpreadElement(u)?(Ae(u.expression,n)===void 0&&w(n,"E_OPAQUE",u,"array spread requires a statically bounded array; spell its elements explicitly",Eo(n,u)),a(),s.push(U(u.expression,n))):o.push(U(u,n))}catch(c){vo(n,c)}return a(),s.length===0?{Array:[]}:s.length===1?s[0]:Ai(s)}if(M.isObjectLiteralExpression(e)){let s=Object.create(null);for(let o of e.properties)try{if(M.isSpreadAssignment(o)){let u=xi(o.expression,n);u&&ki(o,n,u);let c=Qe(o.expression,n);if(c||w(n,"E_OPAQUE",o,"object spread requires a statically known object shape; spell its fields explicitly",ho(n,o)),M.isIdentifier(o.expression)&&n.variables.get(o.expression.text)?.operationComposite==="args")for(let l of c)s[l]={Variable:l};else{let l=U(o.expression,n);if("Object"in l)for(let[f,d]of Object.entries(l.Object))s[f]=d;else for(let f of c)s[f]={Field:{base:l,name:f}}}continue}if(M.isShorthandPropertyAssignment(o)){s[o.name.text]=U(o.name,n);continue}M.isPropertyAssignment(o)||w(n,"E_OPAQUE",o,"object method/property form is unsupported");let a=H(o.name);a||w(n,"E_OPAQUE",o.name,"computed object keys are unsupported"),s[a]=U(o.initializer,n,t?`${t}.${a}`:a)}catch(a){vo(n,a)}return{Object:s}}if(M.isPropertyAccessExpression(e)){if(e.questionDotToken&&w(n,"E_OPAQUE",e,"optional property access must be lowered in a statement-aware expression position"),M.isIdentifier(e.expression)){let o=n.variables.get(e.expression.text)?.operationComposite;if(o==="args")return{Variable:e.name.text};if(o==="ctx"){if(e.name.text==="viewer")return{Input:"Viewer"};if(e.name.text==="readTime")return{Input:"ReadTime"};if(e.name.text==="commitTime")return{Input:"Now"}}}if(e.name.text==="length"&&!Lo(e.expression,n))return{Builtin:{builtin:"Len",args:[U(e.expression,n)]}};let s=U(e.expression,n);return"Object"in s&&s.Object[e.name.text]?s.Object[e.name.text]:{Field:{base:s,name:e.name.text}}}if(M.isBinaryExpression(e)){let s=pi(e.operatorToken.kind);return s||w(n,"E_OPAQUE",e.operatorToken,`operator ${e.operatorToken.getText()} is outside the IR`),{Binary:{op:s,left:U(e.left,n),right:U(e.right,n)}}}if(M.isPrefixUnaryExpression(e)){if(e.operator===M.SyntaxKind.ExclamationToken)return{Unary:{op:"Not",value:U(e.operand,n)}};if(e.operator===M.SyntaxKind.MinusToken)return{Unary:{op:"Neg",value:U(e.operand,n)}}}if(M.isNoSubstitutionTemplateLiteral(e))return re(e.text);if(M.isTemplateExpression(e)){let s=[];e.head.text&&s.push(re(e.head.text));for(let o of e.templateSpans)s.push(U(o.expression,n)),o.literal.text&&s.push(re(o.literal.text));return s.length===1?Ai([re(""),s[0]]):Ai(s)}if(M.isCallExpression(e))return tl(e,n,t);w(n,"E_OPAQUE",e,`expression ${M.SyntaxKind[e.kind]} is outside the S1 IR`)}function vo(e,n){if(n instanceof hn)e.diagnostics.push(n.diagnostic);else throw n}function tl(e,n,t){let i=Ce(e,n);if(i)return U(i.expression,i.environment,t);let r=oe(e);if(r==="decimal"&&e.arguments[0])return U(e.arguments[0],n,t);let s=M.isPropertyAccessExpression(e.expression)?e.expression:void 0,o=s&&M.isIdentifier(s.expression)?n.variables.get(s.expression.text)?.operationComposite:void 0;if(o==="ctx"&&s?.name.text==="now")return{Input:n.kind==="Query"?"ReadTime":"Now"};if(o==="ctx"&&s?.name.text==="commitTime")return{Input:"Now"};if(o==="ctx"&&s?.name.text==="newId")return{Input:"NewId"};if(r.endsWith(".get")&&We(e.expression,a=>Oe(a,"db",n)))return{Get:Ro(e,n,t)};if(r.endsWith(".exists")&&We(e.expression,a=>Oe(a,"db",n)))return{Exists:Ro(e,n,t)};if(r.endsWith(".scan")&&We(e.expression,a=>Oe(a,"db",n)))return{Scan:jo(e,n,t)};if(["normalizeWordPrefix","normalizeHandle"].includes(r)&&e.arguments[0])return U(e.arguments[0],n,t);if(r==="memberOf"){let a=e.arguments[0];return a||w(n,"E_OPAQUE",e,"memberOf requires a conversation id"),{Exists:{site:pt(n),table:"memberships",index:"byConvUser",key:[U(a,n),{Input:"Viewer"}],provenance:Ei([ct(a,n),"Viewer"])}}}if(["concat","max","min","divmod","deterministicShare","mentionTokens"].includes(r)){let a={concat:"Concat",max:"Max",min:"Min",divmod:{Divmod:{remainder_sink:"lexicographic-id"}},deterministicShare:"DeterministicShare",mentionTokens:"MentionTokens"}[r],u=e.arguments.map(l=>U(l,n)),c=r==="deterministicShare"?3:r==="mentionTokens"?1:2;return(u.length<c||r!=="concat"&&r!=="max"&&r!=="min"&&u.length!==c)&&w(n,"E_OPAQUE",e,`${r} requires ${c===1?"one argument":c===2?"at least two arguments":"three arguments"}`),r==="concat"&&u.length>2?Ai(u):(r==="max"||r==="min")&&u.length>2?u.slice(1).reduce((l,f)=>({Builtin:{builtin:a,args:[l,f]}}),u[0]):{Builtin:{builtin:a,args:u}}}if(M.isPropertyAccessExpression(e.expression)){let a=e.expression.name.text,u=e.expression.expression;if(a==="count"||a==="countCapped")return{Builtin:{builtin:a==="count"?"Count":"CountCapped",args:[U(u,n,t)]}};if(a==="slice")return e.arguments.length!==2&&w(n,"E_OPAQUE",e,"slice requires start and end arguments"),{Builtin:{builtin:"Slice",args:[U(u,n),...e.arguments.map(c=>U(c,n))]}};if(a==="sort")return il(u,e.arguments[0],n)}w(n,"E_OPAQUE",e,`helper ${r} is not defined in this module or the pure builtin set`)}function il(e,n,t){return kr(U(e,t),n,t)}function kr(e,n,t){(!n||!ge(n)||n.parameters.length!==2||!M.isIdentifier(n.parameters[0].name)||!M.isIdentifier(n.parameters[1].name)||M.isBlock(n.body))&&w(t,"E_OPAQUE",n??t.sourceFile,"sort requires an inline field comparator");let i=n.body;(!M.isBinaryExpression(i)||i.operatorToken.kind!==M.SyntaxKind.MinusToken||!M.isPropertyAccessExpression(i.left)||!M.isPropertyAccessExpression(i.right))&&w(t,"E_OPAQUE",i,"sort comparator must subtract the same scalar field");let r=M.isIdentifier(i.left.expression)?i.left.expression.text:"",s=M.isIdentifier(i.right.expression)?i.right.expression.text:"",o=n.parameters[0].name.text,a=n.parameters[1].name.text;(i.left.name.text!==i.right.name.text||!(r===o&&s===a||r===a&&s===o))&&w(t,"E_OPAQUE",i,"sort comparator must subtract the same field from its two opposite parameters");let u=r===o?"Asc":"Desc";return{Builtin:{builtin:{Sort:{keys:[{field:i.left.name.text,order:u}]}},args:[e]}}}function Ro(e,n,t){let i=e.arguments[0],r=e.arguments[1];(!i||!r)&&w(n,"E_OPAQUE",e,"point read requires target and key");let s=vn(i,n);return{site:pt(n),table:s.table,index:s.index,key:Oi(r,n),provenance:ct(r,n)}}function jo(e,n,t){let i=e.arguments[0],r=e.arguments[1],s=e.arguments[2];(!i||!r||!s||!M.isObjectLiteralExpression(s))&&w(n,"E_UNBOUND_SCAN",e,"scan requires target, prefix, and options with take");let o=vn(i,n),a=$e(s,"take");a||w(n,"E_UNBOUND_SCAN",e,"scan options require take");let u,c=Fe(a);if(c!==void 0)u={Literal:c};else{let k=or(a,J=>n.variables.get(J)?.operationComposite==="args"),$=k&&n.variables.get(k)?.operationArgument,R=$&&n.args[$],D=k&&R&&typeof R!="string"&&"List"in R?R.List.max:void 0;(!$||D===void 0)&&w(n,"E_UNBOUND_SCAN",a,"take argument needs a declared max"),u={Arg:{name:$,max:D}}}let l=$e(s,"order"),f=fi(l);l&&f!=="asc"&&f!=="desc"&&w(n,"E_OPAQUE",l,'scan order must be "asc" or "desc"');let d=$e(s,"range"),p=Oi(r,n),g=$e(s,"after"),m=$e(s,"before"),y=$e(s,"opaqueCursor"),b=y?.kind===M.SyntaxKind.TrueKeyword;y&&!b&&w(n,"E_OPAQUE",y,"opaqueCursor is an internal literal true tag"),Oo(r,n,o.table,o.index,p.length)&&(b||(hr(g,n,o.table,o.index,p.length),hr(m,n,o.table,o.index,p.length)));let S=$e(s,"mergeSite"),E=fi(S);return S&&E===void 0&&w(n,"E_OPAQUE",S,"mergeSite must be a static string"),{site:pt(n),table:o.table,index:o.index,prefix:p,order:f==="desc"?"Desc":"Asc",take:u,after:ft(g,n),before:ft(m,n),range:d&&M.isObjectLiteralExpression(d)?{gt:ft($e(d,"gt"),n),gte:ft($e(d,"gte"),n),lt:ft($e(d,"lt"),n),lte:ft($e(d,"lte"),n)}:null,...b?{opaque_cursor:!0}:{},merge_site:E??null,provenance:ct(r,n)}}function vn(e,n){let t=ye(e),i=t&&n.tables.get(t);if(i)return{table:i.name,index:i.maintainedFrom?"byGroup":"byId"};let r=t?.lastIndexOf(".")??-1,s=r>0?n.tables.get(t.slice(0,r)):void 0;if(s)return{table:s.name,index:t.slice(r+1)};w(n,"E_OPAQUE",e,`static table/index reference required; ${e.getText(n.sourceFile)} does not resolve to an imported table or table.index`,K(n.source,e,"table.index"))}function Oi(e,n){let t=h(e);if(M.isArrayLiteralExpression(t))return t.elements.map(r=>U(r,n));if(M.isIdentifier(t)){let r=n.variables.get(t.text)?.identityExpression;if(r&&"Array"in r)return r.Array}let i=U(t,n);return"Array"in i?i.Array:[i]}function Ze(e){return{...e,variables:new Map([...e.variables].map(([n,t])=>[n,{...t}])),substitutions:new Map(e.substitutions),helperStack:[...e.helperStack],deferredCollectionMutations:new Set(e.deferredCollectionMutations)}}function Sr(e){return{...e,variables:new Map(e.variables),substitutions:new Map(e.substitutions),helperStack:[...e.helperStack],deferredCollectionMutations:new Set(e.deferredCollectionMutations)}}function pt(e){let n=`${e.siteBase}.${e.accessOrdinal.value}`;return e.accessOrdinal.value+=1,n}function Jn(e){e.accessOrdinal.value+=1}function Ni(e,n=new Set,t=0){if(t>=mi)return!0;if(Array.isArray(e)){if(n.has(e))return!0;n.add(e);let s=e.some(o=>Ni(o,n,t+1));return n.delete(e),s}if(!e||typeof e!="object")return!1;let i=e;if(n.has(i))return!0;n.add(i);let r=["Get","Exists","Scan"].some(s=>s in i)||Object.values(i).some(s=>Ni(s,n,t+1));return n.delete(i),r}function Bo(e,n,t,i,r,s){let o=t.arguments[0];(!o||!ge(o)||o.parameters.length<1||!M.isIdentifier(o.parameters[0].name))&&w(i,"E_OPAQUE",t,`${e} requires an inline callback with an identifier`),M.isBlock(o.body)&&w(i,"E_OPAQUE",o.body,`${e} callback must be an expression`);let a=e==="reduce"?2:1;(o.parameters.length!==a||o.parameters.some(m=>!M.isIdentifier(m.name)))&&w(i,"E_OPAQUE",o,e==="reduce"?"reduce callback requires exactly accumulator and item parameters":`${e} callback requires exactly one parameter`);let u=o.parameters[0].name.text,c=Ze(i),{statements:l,domain:f,bindingInfo:d}=_i(n,c,u,r,s);if(c.variables.set(u,d),e==="map"||e==="filter"){let m=G(i,e),y=r(o.body,c,s),b=e==="map"?[...y.statements,{Push:{target:m,value:y.expression}}]:[...y.statements,{If:{condition:y.expression,then_body:[{Push:{target:m,value:{Variable:u}}}],else_body:[]}}],S=e==="filter"?{provenance:d.provenance,...d.provenanceAmbiguity?{provenanceAmbiguity:{...d.provenanceAmbiguity}}:{}}:qt(lt(o.body,c),o.body,c),E=h(o.body),k=e==="map"&&M.isIdentifier(E)&&E.text===u,$=(e==="filter"||k)&&d.rowBinding,R=e==="filter"?Do(d):[{expression:o.body,environment:c}],D=Ut(n,i);return i.variables.set(m,Je({...S,...$?{rowCollection:!0,objectFields:d.objectFields}:{}},{...D,elementOrigins:R})),{statements:[...l,{Let:{name:m,value:{Array:[]}}},{For:{binding:u,domain:f,body:b}}],expression:{Variable:m}}}if(e==="flatMap"){let m=G(i,"flatMap"),y=G(i,"flatItem"),b=_i(o.body,c,y,r,s);return Ze(c).variables.set(y,b.bindingInfo),i.variables.set(m,Je({...b.bindingInfo,...b.bindingInfo.rowBinding?{rowCollection:!0,objectFields:b.bindingInfo.objectFields}:{}},{max:Ti(f)*Ti(b.domain),boundSource:`${t.getText(i.sourceFile)} flatMap bounds`,elementOrigins:Do(b.bindingInfo)})),{statements:[...l,{Let:{name:m,value:{Array:[]}}},{For:{binding:u,domain:f,body:[...b.statements,{For:{binding:y,domain:b.domain,body:[{Push:{target:m,value:{Variable:y}}}]}}]}}],expression:{Variable:m}}}if(e==="reduce"){let m=t.arguments[1];(!m||o.parameters.length<2||!M.isIdentifier(o.parameters[1].name))&&w(i,"E_OPAQUE",t,"reduce requires accumulator, item, and initial value");let y=o.parameters[0].name.text,b=o.parameters[1].name.text,S=Ze(i);S.variables.set(b,d);let E=G(i,"reduce");S.substitutions.set(y,{expression:Ft(i.sourceFile,E),environment:S});let k=r(o.body,S,s);return{statements:[...l,{Let:{name:E,value:U(m,i)}},{For:{binding:b,domain:f,body:[...k.statements,{Assign:{name:E,value:k.expression}}]}}],expression:{Variable:E}}}let p=G(i,"some"),g=r(o.body,c,s);return{statements:[...l,{Let:{name:p,value:re(!1)}},{For:{binding:u,domain:f,body:[...g.statements,{If:{condition:g.expression,then_body:[{Assign:{name:p,value:re(!0)}},"Break"],else_body:[]}}]}}],expression:{Variable:p}}}function _i(e,n,t,i,r){let s=h(e),o=N(s),a=o&&M.isPropertyAccessExpression(o.expression)?o.expression.name.text:void 0;if(a&&["map","flatMap","filter","sort","slice"].includes(a)){let u=i(e,n,r);if("Variable"in u.expression){let f=Er(Ft(n.sourceFile,u.expression.Variable),n,t,r);return{statements:u.statements,...f}}let c=Ae(e,n);c===void 0&&w(n,"E_UNBOUND_LOOP",e,"loop domain has no static cardinality");let l=cn(e,n);return{statements:u.statements,domain:{DerivedArray:{value:u.expression,max:c,bound_source:`${e.getText(n.sourceFile)} static bound`}},bindingInfo:l?{provenance:"Shape",rowBinding:!0,objectFields:Sn(e,n)}:dt(e,n)}}if(M.isArrayLiteralExpression(s)){let u=Ae(e,n);u===void 0&&w(n,"E_UNBOUND_LOOP",e,"loop domain has no static cardinality");let c=i(e,n,r);return{statements:c.statements,domain:{DerivedArray:{value:c.expression,max:u,bound_source:`${e.getText(n.sourceFile)} static bound`}},bindingInfo:dt(e,n)}}return{statements:[],...Er(e,n,t,r)}}function Do(e){if(e.alternativeOrigins)return e.alternativeOrigins;let{elementOrigins:n,...t}=e;return[{binding:t}]}function ft(e,n){return e?U(e,n):null}function Qt(e){let n=Ze(e),t=e.collectionMutationCounts?new Map:void 0;return n.collectionMutationCounts=t,{environment:n,outerBindings:new Map(n.variables),collectionMutationCounts:t}}function wr(e,n,t){for(let[r,s]of e.variables){let o=n.flatMap(u=>u.outerBindings.get(r)?[u.outerBindings.get(r)]:[]);if(o.length!==n.length)continue;let a=new Set(o.flatMap(u=>[...u.provenanceAmbiguity?.candidates??[],...u.provenanceAmbiguity?.directRewrite?[u.provenanceAmbiguity.directRewrite]:[]]));a.size>0&&(s.provenance="Computed",s.provenanceAmbiguity=un([...a])),Ao(s,o,`${t.getText(e.sourceFile)} branch maximum`),o.some(u=>u.nullableRead===!1)&&(s.nullableRead=!1)}if(!e.collectionMutationCounts)return;let i=new Set(n.flatMap(r=>[...r.collectionMutationCounts?.keys()??[]]));for(let r of i){let s=n.map(u=>u.collectionMutationCounts?.get(r)),o=Math.max(...s.map(u=>u?.count??0)),a=s.find(u=>u)?.name;a&&o>0&&Kt(e.collectionMutationCounts,r,o,a)}}var rl=16;function Vo(e,n,t,i,r){let s=new Set(n.deferredCollectionMutations),o=sl(n),a=ol(e,n,o,t,i,r);qo(n,o,a,s),n.deferredCollectionMutations=new Set([...s,...o.keys()]);let u=n.collectionMutationCounts;n.collectionMutationCounts=new Map;let c=r(e.statement,n);if(qo(n,o,a,s),u)for(let[l,f]of a.counts){let d=f.count*t;Number.isSafeInteger(d)||w(n,"E_UNBOUND_LOOP",e.expression,"nested collection mutation delta exceeds the static integer range"),Kt(u,l,d,f.name)}return c}function sl(e){let n=new Map;for(let[t,i]of e.variables)i.collectionIdentity&&!n.has(i.collectionIdentity)&&n.set(i.collectionIdentity,{name:t,info:i});return n}function ol(e,n,t,i,r,s){let o=new Map,a=new Map;for(let u=0;u<rl;u+=1){let c=ul(n);for(let[p,g]of t){let m=$r(c,p,g.name);if(!m)continue;let y=a.get(p);y&&al(m,y);let b=o.get(p);if(b&&!n.deferredCollectionMutations.has(p)){g.info.max===void 0&&w(n,"E_UNBOUND_LOOP",e.expression,"collection mutation has no provable pre-loop cardinality");let S=g.info.max+i*b.count;Number.isSafeInteger(S)||w(n,"E_UNBOUND_LOOP",e.expression,"collection mutation bound exceeds the static integer range"),Je(m,{max:S,boundSource:`${b.name} mutations \xD7 loop bound ${i}`,...m.elementOrigins!==void 0?{elementOrigins:m.elementOrigins}:{}})}}c.deferredCollectionMutations=new Set([...n.deferredCollectionMutations,...t.keys()]),c.collectionMutationCounts=new Map,s(e.statement,c);let l=c.diagnostics.find(p=>p.code==="E_UNBOUND_LOOP");if(l)throw new hn(l);let f=new Map([...c.collectionMutationCounts].filter(([p])=>t.has(p)));r&&f.has(r)&&w(n,"E_UNBOUND_LOOP",e.expression,"collection mutation bound depends on its own growing loop domain and has no finite static fixed point");let d=new Map;for(let[p,g]of t){let m=$r(c,p,g.name);m&&d.set(p,m)}if(ll(o,f))return{counts:f,facts:d,iterations:i};o=f,a=d}w(n,"E_UNBOUND_LOOP",e.expression,"collection mutation bound depends on a growing loop domain and has no finite static fixed point")}function al(e,n){Je(e,{...n.max!==void 0?{max:n.max}:{},...n.boundSource!==void 0?{boundSource:n.boundSource}:{},...e.elementOrigins!==void 0?{elementOrigins:e.elementOrigins}:{}})}function ul(e){let n=Ze(e);return n.accessOrdinal={value:e.accessOrdinal.value},n.temp={value:e.temp.value},n.diagnostics=[],n.recursion={depth:0,active:new Map},n.collectionMutationCounts=new Map,n}function qo(e,n,t,i){for(let[r,s]of n){if(i.has(r))continue;let o=$r(e,r,s.name),a=t.facts.get(r);if(!o||!a)continue;cl(o,a);let u=t.counts.get(r);u&&o.max!==void 0&&(o.boundSource=`${u.name} mutations \xD7 loop bound ${t.iterations}`)}}function cl(e,n){e.provenance=n.provenance,n.provenanceAmbiguity?e.provenanceAmbiguity={...n.provenanceAmbiguity,...n.provenanceAmbiguity.candidates?{candidates:[...n.provenanceAmbiguity.candidates]}:{}}:delete e.provenanceAmbiguity,Je(e,{...n.max!==void 0?{max:n.max}:{},...n.boundSource!==void 0?{boundSource:n.boundSource}:{},...n.elementOrigins!==void 0?{elementOrigins:[...n.elementOrigins]}:{}})}function $r(e,n,t){let i=e.variables.get(t);return i?.collectionIdentity===n?i:[...e.variables.values()].find(r=>r.collectionIdentity===n)}function ll(e,n){if(e.size!==n.size)return!1;for(let[t,i]of e)if(n.get(t)?.count!==i.count)return!1;return!0}import dl from"typescript";function Uo(e,n,t,i,r){let s=e.arguments[0],o=e.arguments[1],a=bn(e.arguments[2]),u=e.arguments[3],c=bn(e.arguments[4]),l=bn(e.arguments[5]);(!s||!o||!dl.isArrayLiteralExpression(h(o))||!u||!c||!l||a!=="asc"&&a!=="desc")&&w(n,"E_OPAQUE",e,"mergeByIndex requires rows, static fields, asc/desc, take, site, and table");let f=i(s,n,t),p={Builtin:{builtin:{Sort:{keys:h(o).elements.map(m=>{let y=bn(m);return y||w(n,"E_OPAQUE",m,"mergeByIndex fields must be static strings"),{field:y,order:a==="desc"?"Desc":"Asc"}})}},args:[f.expression]}},g={Builtin:{builtin:{DedupeById:{site:c,table:l}},args:[p]}};return{statements:f.statements,expression:{Builtin:{builtin:"Slice",args:[g,re(0),r(u,n)]}}}}import Ht from"typescript";function Ko(e,n,t,i){let r=On(e);r||w(n,"E_OPAQUE",e,"only Map and Set constructors are admitted");let s=e.arguments?.[0];if(!s)return{statements:[],expression:{Array:[]}};if((e.arguments?.length??0)!==1&&w(n,"E_OPAQUE",e,`${r} constructor accepts at most one bounded initializer`),r==="Set")return fl(s,n,t,i);let o=h(s);Ht.isArrayLiteralExpression(o)||w(n,"E_OPAQUE",s,"Map initializer must be a bounded array literal of [key, value] pairs");let a=[],u=G(n,"mapResult");a.push({Let:{name:u,value:{Array:[]}}});let c=0;for(let l of o.elements){let f=h(l);(!Ht.isArrayLiteralExpression(f)||f.elements.length!==2)&&w(n,"E_OPAQUE",l,"Map initializer entries must be [key, value] pairs"),wn(f.elements[0],n,"Map keys");let d=t(f.elements[0],n,i),p=t(f.elements[1],n,i);a.push(...Ar(u,d,p,c,"Map initializer bound",n)),c+=1}return{statements:a,expression:{Variable:u}}}function fl(e,n,t,i){let r=t(e,n,i),s=Ae(e,n);s===void 0&&w(n,"E_UNBOUND_LOOP",e,"Set initializer must have a static bound");let o=h(e);if(Ht.isArrayLiteralExpression(o))for(let d of o.elements)Ht.isSpreadElement(d)?wn(d.expression,n,"Set elements",!0):wn(d,n,"Set elements");else wn(e,n,"Set elements",!0);let a=G(n,"setSource"),u=G(n,"setResult"),c=G(n,"setItem"),l=G(n,"setExisting"),f=G(n,"setFound");return{statements:[...r.statements,{Let:{name:a,value:r.expression}},{Let:{name:u,value:{Array:[]}}},{For:{binding:c,domain:{DerivedArray:{value:{Variable:a},max:s,bound_source:`${e.getText(n.sourceFile)} static bound`}},body:[{Let:{name:f,value:re(!1)}},{For:{binding:l,domain:{DerivedArray:{value:{Variable:u},max:s,bound_source:"Set uniqueness bound"}},body:[{If:{condition:{Binary:{op:"SameValueZero",left:{Variable:l},right:{Variable:c}}},then_body:[{Assign:{name:f,value:re(!0)}}],else_body:[]}}]}},{If:{condition:{Unary:{op:"Not",value:{Variable:f}}},then_body:[{Push:{target:u,value:{Variable:c}}}],else_body:[]}}]}}],expression:{Variable:u}}}function Ar(e,n,t,i,r,s){let o=G(s,"authoredMapKey"),a=G(s,"authoredMapValue"),u=G(s,"mapKey"),c=G(s,"mapValue"),l=G(s,"mapUpdated"),f=G(s,"mapEntry"),d=G(s,"mapFound"),p={Object:{key:{Variable:u},value:{Variable:c}}};return[...n.statements,{Let:{name:o,value:n.expression}},...t.statements,{Let:{name:a,value:t.expression}},{Let:{name:u,value:{Variable:o}}},{Let:{name:c,value:{Variable:a}}},{Let:{name:l,value:{Array:[]}}},{Let:{name:d,value:re(!1)}},{For:{binding:f,domain:{DerivedArray:{value:{Variable:e},max:i,bound_source:r??"Map static bound"}},body:[{If:{condition:{Binary:{op:"SameValueZero",left:{Field:{base:{Variable:f},name:"key"}},right:{Variable:u}}},then_body:[{If:{condition:{Unary:{op:"Not",value:{Variable:d}}},then_body:[{Push:{target:l,value:p}}],else_body:[]}},{Assign:{name:d,value:re(!0)}}],else_body:[{Push:{target:l,value:{Variable:f}}}]}}]}},{If:{condition:{Unary:{op:"Not",value:{Variable:d}}},then_body:[{Push:{target:l,value:p}}],else_body:[]}},{Assign:{name:e,value:{Variable:l}}}]}function Ci(e,n,t,i){let r=t.variables.get(e.text);r?.max===void 0&&w(t,"E_UNBOUND_LOOP",e,`${e.text}.${i==="MapGet"?"get":"has"} needs a statically bounded collection`);let s=G(t,i==="SetHas"?"setItem":"mapEntry"),o=G(t,"collectionNeedle"),a=G(t,i==="MapGet"?"mapValue":"collectionHas"),u=i==="SetHas"?{Variable:s}:{Field:{base:{Variable:s},name:"key"}},c=i==="MapGet"?{Field:{base:{Variable:s},name:"value"}}:re(!0);return{statements:[{Let:{name:o,value:n}},{Let:{name:a,value:i==="MapGet"?re(null):re(!1)}},{For:{binding:s,domain:{DerivedArray:{value:{Variable:e.text},max:r.max,bound_source:r.boundSource??`${e.text} static bound`}},body:[{If:{condition:{Binary:{op:"SameValueZero",left:u,right:{Variable:o}}},then_body:[{Assign:{name:a,value:c}}],else_body:[]}}]}}],expression:{Variable:a}}}function wn(e,n,t,i=!1){let r=h(e);if(r.kind===Ht.SyntaxKind.NullKeyword)return;let s=n.expressionTypes.get(Ye(n.literalContext,r,n.sourceFile));i&&(s=s?.kind==="list"?s.of:void 0);let o=s&&ee(s);o&&["null","bool","int","decimal","enum","string"].includes(o.kind)||w(n,"E_OPAQUE",e,`${t} must be primitive strings, numbers, booleans, or null; object identity cannot be preserved in bounded data IR`,"select a primitive identity field before using this Map or Set operation")}function Nr(e,n,t){if(n=Qo(n,t,new Set),"Object"in n){let s=n.Object.id;return s===void 0?void 0:Ii(e,s)&&!Tr(s)}if(!("Literal"in n)||n.Literal==="Null"||typeof n.Literal!="object")return;let r=("Row"in n.Literal?n.Literal.Row:"Map"in n.Literal?n.Literal.Map:void 0)?.id;return r===void 0?void 0:Ii(e,{Literal:r})}function Qo(e,n,t){if(!("Variable"in e)||t.has(e.Variable))return e;t.add(e.Variable);let i=n(e.Variable);return i===void 0?e:Qo(i,n,t)}function Tr(e){if(Array.isArray(e))return e.some(Tr);if(!e||typeof e!="object")return!1;let n=e;return n.Input==="NewId"||Object.values(n).some(Tr)}function Ii(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((o,a)=>Ii(o,n[a]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let t=e,i=n,r=Object.keys(t).sort(),s=Object.keys(i).sort();return r.length===s.length&&r.every((o,a)=>o===s[a]&&Ii(t[o],i[o]))}import ne from"typescript";function Wo(e,n=50){let t=[],i=c=>{t.length<n&&t.push(c)},r=(c,l)=>{if(!(t.length>=n)&&!(ge(c)&&Qs(c))){if(ne.isFunctionDeclaration(c)&&c.name&&(l=c.name.text),ne.isWhileStatement(c)&&i(L(e,"E_OPAQUE",c,"while loops have no static iteration bound",bl(e.source,c))),(ne.isAwaitExpression(c)||Ks(c))&&i(L(e,"E_OPAQUE",c,"async/await is outside data programs",e.source)),ne.isCallExpression(c)){let f=oe(c);(f==="Date.now"||f==="Date"&&c.arguments.length===0)&&i(L(e,"E_AMBIENT_TIME",c,"ambient time is not replay-stable",hl(e.source,c))),["Math.random","fetch","setTimeout","eval"].includes(f)&&i(L(e,"E_OPAQUE",c,`${f} is outside the deterministic subset`,e.source)),l&&ne.isIdentifier(c.expression)&&c.expression.text===l&&i(L(e,"E_OPAQUE",c,"recursive helpers must use recurse with depth and fanout",e.source))}ne.forEachChild(c,f=>r(f,l))}};r(e.sourceFile);let s=[],o=[],a=[],u=[];we(e.sourceFile,c=>{ne.isCallExpression(c)&&oe(c).endsWith(".scan")&&o.push(c),ne.isCallExpression(c)&&["count","reduce"].includes(di(c.expression)??"")&&s.push(c),ne.isForOfStatement(c)&&a.push(c),ne.isElementAccessExpression(c)&&Js(c.argumentExpression)&&rr(c.expression,".sort")&&u.push(c)});for(let c of s){if(t.length>=n)break;let l=Lt(c.expression,".scan");l&&(Ir(l)||i(L(e,"E_UNBOUND_COUNT",c,"an exact reduction over a growing population has no static bound",ml(e.source))),_r(e,l)&&i(Ho(e,c,l)))}for(let c of u){if(t.length>=n)break;let l=Lt(c.expression,".scan");l&&_r(e,l)&&i(Ho(e,c,l))}for(let c of a){if(t.length>=n)break;let l=Lt(c.expression,".scan");l&&_r(e,l)&&Bs(c.statement)&&i(pl(e,c,l)),rr(c.expression,".split")&&!kl(c.expression)&&i(L(e,"E_UNBOUND_LOOP",c.expression,"split-derived loop cardinality is not declared",yl(e.source)))}for(let c of o){if(t.length>=n)break;Ir(c)||i(L(e,"E_UNBOUND_SCAN",c,"scan requires a literal take or an argument with a declared maximum",gl(Go(e.sourceFile,e.source))))}for(let c of El(e,n-t.length))i(c);return t}function Ho(e,n,t){let i=Jo(e,t);return L(e,"E_STRUCTURAL_COUNT",n,"reduction would expose a fact about rows hidden by a non-tautologous rule",i?K(e.source,n,i):e.source)}function pl(e,n,t){let i=Jo(e,t)??"null",r=n.getStart(e.sourceFile),s=n.getEnd(),o=qs(e.sourceFile,n),a=Vs(e.sourceFile,n);return o&&ne.isVariableStatement(o)&&a&&ne.isReturnStatement(a)&&(r=o.getStart(e.sourceFile),s=a.getEnd()),L(e,"E_STRUCTURAL_COUNT",n,"loop tally would expose a structural count through caller visibility",`${e.source.slice(0,r)}return ${i};${e.source.slice(s)}`)}function Jo(e,n){let t=n.arguments[0],i=n.arguments[1];if(!t||!i)return;let r=Mr(t,e.tables).table,s=[...e.tables.entries()].find(([,a])=>(a.maintainedFrom?e.tables.get(a.maintainedFrom):void 0)?.name===r);if(!s)return;let o=ne.isArrayLiteralExpression(i)&&i.elements.length===1?i.elements[0].getText(e.sourceFile):i.getText(e.sourceFile);return`db.get(${s[0]}, ${o})`}function Go(e,n){let t=[];return we(e,i=>{if(!ne.isCallExpression(i)||!oe(i).endsWith(".scan")||Ir(i))return;if(i.arguments.length<3){t.push({start:i.arguments.end,end:i.arguments.end,text:", { take: 50 }"});return}let r=i.arguments[2];if(r&&ne.isObjectLiteralExpression(r)){let s=r.properties.pos;t.push({start:s,end:s,text:"take: 50, "})}}),ir(n,t)}function ml(e){let n=ne.createSourceFile("rewrite.ts",e,ne.ScriptTarget.ES2022,!0);return Go(n,e).replace(/\.count\s*\(\s*\)/g,".countCapped()")}function gl(e){let n=ne.createSourceFile("rewrite-map.ts",e,ne.ScriptTarget.ES2022,!0),t=[];return we(n,i=>{if(!ne.isReturnStatement(i)||!i.expression||!ne.isCallExpression(i.expression)||!ne.isPropertyAccessExpression(i.expression.expression)||i.expression.expression.name.text!=="map")return;let r=i.expression.arguments[0];if(!r||!ge(r)||r.parameters.length!==1||!ne.isIdentifier(r.parameters[0].name)||ne.isBlock(r.body))return;let s=r.parameters[0].name.text,o=i.expression.expression.expression.getText(n),a=r.body.getText(n);t.push({start:i.getStart(n),end:i.getEnd(),text:`let mapped = []; for (const ${s} of ${o}) mapped.push(${a}); return mapped;`})}),ir(e,t)}function yl(e){return e.replace(/([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\.split\(\s*(['"]) \2\s*\)/g,"mentionTokens($1)")}function bl(e,n){if(!ne.isBinaryExpression(n.expression)||n.expression.operatorToken.kind!==ne.SyntaxKind.LessThanToken||!ne.isIdentifier(n.expression.left)||Fe(n.expression.right)===void 0)return e;let t=n.expression.left.text,i=Fe(n.expression.right),r=n.statement.getText().replace(new RegExp(`\\b${t}\\+\\+\\s*;?`),"");return K(e,n,`for (const _ of range(0, ${i})) ${r}`)}function hl(e,n){let t=K(e,n,"ctx.now()");return/\(\{[^}]*\bctx\b[^}]*\}\)\s*=>/.test(t)||(t=t.replace(/\(\{([^}]*)\}\)\s*=>/,(i,r)=>{let s=r.split(",").map(a=>a.trim()).filter(Boolean),o=s.indexOf("db");return s.splice(o>=0?o+1:0,0,"ctx"),`({ ${s.join(", ")} }) =>`})),t}function El(e,n){let t=[],i=(r,s)=>{let o=Lt(r.expression,".scan"),a=o&&o.arguments[2]&&ne.isObjectLiteralExpression(o.arguments[2])?$e(o.arguments[2],"take"):void 0,u=Fe(a),c=o?.arguments[0],l=c?xl(e.tables,Mr(c,e.tables).table):1024,f=u!==void 0&&a?[...s,{value:u,node:a,rowBytes:l}]:s,d=f.reduce((g,m)=>g*m.value,1);if(d>10240&&a&&t.length<n){let g=[...f].sort(($,R)=>R.value-$.value)[0],m=d/g.value,y=Math.max(...f.map($=>$.rowBytes)),b=Math.floor((1024*1024-2)/(y+1)),S=Math.floor(4*1024*1024/y),E=Math.min(10240,b,S),k=Math.max(1,Math.floor(E/(m+4)));t.push(L(e,"E_BOUND",r,`nested population product ${f.map($=>$.value).join(" \xD7 ")} = ${d} exceeds 10240`,K(e.source,g.node,String(k))))}let p=ne.isBlock(r.statement)?r.statement.statements:[r.statement];for(let g of p)we(g,m=>{t.length<n&&ne.isForOfStatement(m)&&m!==r&&i(m,f)})};return we(e.sourceFile,r=>{t.length<n&&ne.isForOfStatement(r)&&!js(r,ne.isForOfStatement)&&i(r,[])}),t}function xl(e,n){let t=[...e.values()].find(i=>i.name===n);return t?.columns?Object.entries(t.columns).reduce((i,[r,s])=>i+r.length+4+Or(s),10):1024}function Or(e){switch(e.kind){case"string":return e.max===void 0?144:e.max+16;case"principal":return 144;case"bytes":return e.max*2+16;case"asset":return e.asset==="image"?256:288;case"int":case"decimal":return 32;case"bool":return 16;case"json":return(e.max??1024)+16;case"enum":return Math.max(16,...e.variants.map(n=>n.length+16));case"optional":return Math.max(8,Or(e.of));case"list":return 2+(e.max??1)*(Or(e.of)+1);case"null":return 8;case"object":case"row":case"unknown":return 1024}}function _r(e,n){let t=n.arguments[0];if(!t)return!1;let i=Mr(t,e.tables),r=[...e.tables.values()].find(u=>u.name===i.table);if(!r?.private)return!1;let s=n.arguments[1]&&h(n.arguments[1]),o=r.indexes?.[i.index]?.columns;if(!s||!ne.isArrayLiteralExpression(s)||!o||r.readRule===void 0)return!0;let a=new Set(o.slice(0,s.elements.length));return[...Cr(r.readRule)].some(u=>!a.has(u))}function Cr(e,n=new Set){if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,i=t.Eq??t.Ne;Array.isArray(i)&&i.forEach(o=>zo(o,n));let r=t.Exists;r&&Array.isArray(r.key)&&r.key.forEach(o=>zo(o,n));let s=t.And??t.Or;return Array.isArray(s)&&s.forEach(o=>Cr(o,n)),t.Not!==void 0&&Cr(t.Not,n),n}function zo(e,n){e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.Field=="string"&&n.add(e.Field)}function Mr(e,n){let t=ye(e),i=t&&n.get(t);if(i)return{table:i.name,index:i.maintainedFrom?"byGroup":"byId"};let r=t?.lastIndexOf(".")??-1,s=r>0?n.get(t.slice(0,r)):void 0;return s?{table:s.name,index:t.slice(r+1)}:{table:t??h(e).getText(),index:"byId"}}function Ir(e){let n=e.arguments[2];if(!n||!ne.isObjectLiteralExpression(n))return;let t=$e(n,"take");if(t)return Fe(t)??"arg"}function kl(e){let n=e.getText();return/\.split\([^)]*\)\.slice\(\s*0\s*,\s*\d+\s*\)/.test(n)||n.includes("mentionTokens(")}import x from"typescript";var vr=512,Rr=8192;function ta(e,n){let t=new Lr(e,oe(n)==="mutation"?"Mutation":"Query",n),i=n.arguments[0]&&h(n.arguments[0]),r=Object.create(null);if(i&&x.isObjectLiteralExpression(i))for(let o of mn(i).entries)r[o.name]=ia(o.value);let s=n.arguments[1];if(s&&ge(s)){let o={variables:new Map,constants:new Map,args:r,mutableBindings:gi(s),memo:new Map,literalContext:"operation"};for(let a of s.parameters)for(let u of Yn(a.name))Ln(o,u,{type:P});for(let[a,u]of Object.entries(Nl(s)))u&&Ln(o,u,{type:P,operationComposite:a});x.isBlock(s.body)?t.statements(s.body.statements,o):t.expression(s.body,o)}return{diagnostics:t.diagnostics,literalValues:t.literalValues,expressionTypes:t.expressionTypes,analysisLimitReached:t.analysisLimitReached}}var Lr=class{constructor(n,t,i){this.module=n;this.programKind=t;this.operation=i}diagnostics=[];literalValues=new Map;expressionTypes=new Map;seen=new Set;helperStack=[];analysisVisits=0;analysisDepth=0;analysisLimitReached=!1;statements(n,t){for(let i of n)this.statement(i,t)}statement(n,t){if(x.isVariableStatement(n)){for(let i of n.declarationList.declarations){if(!i.initializer)continue;let r=this.expression(i.initializer,t),s=this.bindingTypes(i.name,i.initializer,r,t);for(let[o,a]of s){let u=ra(i.name,o),c=u!==void 0&&t.mutableBindings.has(u),l=x.isIdentifier(i.name)?this.binding(i.initializer,t,c?P:a):{type:c?P:a};Ln(t,o,l,c?void 0:i.initializer)}}return}if(x.isExpressionStatement(n)){this.expression(n.expression,t);return}if(x.isReturnStatement(n)&&n.expression){this.expression(n.expression,t);return}if(x.isIfStatement(n)){this.expression(n.expression,t);let i=Dn(t),r=Pt(n.expression);if(r){let s=i.variables.get(r);s&&(s.type=ee(s.type)),i.constants.delete(r)}this.controlled(n.thenStatement,i),n.elseStatement&&this.controlled(n.elseStatement,Dn(t));return}if(x.isForOfStatement(n)){let i=this.expression(n.expression,t),r=Dn(t);if(x.isVariableDeclarationList(n.initializer))for(let s of n.initializer.declarations)for(let o of Yn(s.name))Ln(r,o,{type:i.kind==="list"?i.of:P});this.controlled(n.statement,r);return}x.isBlock(n)&&this.statements(n.statements,Dn(t))}controlled(n,t){x.isBlock(n)?this.statements(n.statements,t):this.statement(n,t)}expression(n,t,i,r=!1){let s=h(n),o=i&&ee(i),a=`${r?"quiet":"loud"}:${JSON.stringify(o??null)}`,u=t.memo.get(s)?.get(a),c=Ye(t.literalContext,s,this.module.sourceFile);if(u)return this.expressionTypes.set(c,u),u;if(this.analysisLimitReached)return P;if(this.analysisDepth>=vr)return this.analysisLimit(s);if(this.analysisVisits>=Rr)return this.analysisLimit(s);this.analysisVisits+=1,this.analysisDepth+=1;let l;try{l=this.expressionInner(s,t,o,r)}finally{this.analysisDepth-=1}be(o)&&!$l(l)&&l.kind!=="unknown"&&l.kind!=="json"&&Mi(n)&&!(i?.kind==="optional"&&l.kind==="null")&&this.add("E_ARGS_ID_SCALAR",s,`an Id position requires an Id scalar, not ${Ol(l)}`,this.idScalarRewrite(s,t));let f=t.memo.get(s)??new Map;return f.set(a,l),t.memo.set(s,f),this.expressionTypes.set(c,l),l}expressionInner(n,t,i,r){if(x.isNumericLiteral(n))return this.numeric(n,t,i,r);if(x.isStringLiteralLike(n))return i?.kind==="enum"&&!i.variants.includes(n.text)&&this.enumVariant(n,i),i?.kind==="string"&&i.max!==void 0&&[...n.text].length>i.max&&this.add("E_ARGS_TYPE",n,`text literal has ${[...n.text].length} Unicode scalars but text(${i.max}) allows at most ${i.max}`,K(this.module.source,n,JSON.stringify([...n.text].slice(0,i.max).join("")))),i?.kind==="enum"||i?.kind==="string"&&(!be(i)||n.text.length>0)?i:{kind:"string"};if(n.kind===x.SyntaxKind.TrueKeyword||n.kind===x.SyntaxKind.FalseKeyword)return{kind:"bool"};if(n.kind===x.SyntaxKind.NullKeyword)return{kind:"null"};if(x.isIdentifier(n)){let s=i&&t.constants.get(n.text);return s&&!(be(i)&&Sl(s))?this.expression(s,t,i):t.variables.get(n.text)?.type??P}if(x.isPrefixUnaryExpression(n))return this.expression(n.operand,t,i,r);if(x.isPropertyAccessExpression(n)){let s=this.operationComposite(n.expression,t);if(s==="args")return ee(t.args[n.name.text]);if(s==="ctx"){if(n.name.text==="viewer")return{kind:"principal"};if(["readTime","commitTime"].includes(n.name.text))return{kind:"int"}}let o=this.expression(n.expression,t,void 0,!0);if(o.kind==="row")return this.table(o.table)?.columns?.[n.name.text]??P;if(o.kind==="object")return o.fields?.[n.name.text]??P;if(o.kind==="asset"){let a=_l(o.asset,n.name.text);if(a)return a;let u=o.asset==="image"?"id, width, height":"id, width, height, duration",c=`${n.expression.getText(this.module.sourceFile)}.${o.asset==="video"?"duration":"width"}`;return this.add("E_ARGS_TYPE",n,`${o.asset} asset has no field ${n.name.text}; available fields are ${u}`,K(this.module.source,n,c)),P}return(o.kind==="list"||o.kind==="string")&&n.name.text==="length"?{kind:"int"}:P}if(x.isNoSubstitutionTemplateLiteral(n))return{kind:"string"};if(x.isTemplateExpression(n)){let s=n.templateSpans.map(a=>a.expression),o=s.map(a=>this.expression(a,t));return o.some(Rn)&&be(ee(i))&&Mi(n)?(this.add("E_ARGS_ID_TEXT",n,"Id scalars cannot be interpolated into text; keep identity values structurally separate",this.idTextRewrite(n,i,s,o)),P):{kind:"string"}}if(x.isArrayLiteralExpression(n)){let s=i?.kind==="list"?i.of:void 0,o=n.elements.map(a=>this.expression(a,t,s));return{kind:"list",of:Gn(o),max:o.length}}if(x.isObjectLiteralExpression(n)){let s=i?.kind==="row"?this.table(i.table):void 0,o=Object.create(null);for(let a of n.properties){if(x.isSpreadAssignment(a)){let f=this.expression(a.expression,t);if(f.kind==="object"&&f.fields)Object.assign(o,f.fields);else for(let d of Object.keys(o))delete o[d];continue}if(x.isShorthandPropertyAssignment(a)){o[a.name.text]=this.expression(a.name,t,s?.columns?.[a.name.text]);continue}if(!x.isPropertyAssignment(a))continue;let u=H(a.name),c=u?s?.columns?.[u]:void 0,l=this.expression(a.initializer,t,c);u&&(o[u]=l)}return i??{kind:"object",fields:o}}if(x.isConditionalExpression(n)){this.expression(n.condition,t);let s=this.expression(n.whenTrue,t,i),o=this.expression(n.whenFalse,t,i);return Gn([s,o])}if(x.isBinaryExpression(n))return this.binary(n,t,i);if(x.isCallExpression(n))return this.call(n,t,i);if(x.isNewExpression(n)){for(let s of n.arguments??[])this.expression(s,t);return{kind:"object"}}if(x.isArrowFunction(n)||x.isFunctionExpression(n)){let s=Dn(t);for(let o of n.parameters)for(let a of Yn(o.name))Ln(s,a,{type:P});x.isBlock(n.body)?this.statements(n.body.statements,s):this.expression(n.body,s,i)}return i??P}analysisLimit(n){return this.analysisLimitReached||(this.analysisLimitReached=!0,this.add("E_OPAQUE",n,`type analysis is limited per operation to ${vr} nested expressions and ${Rr} contextual expression visits; reduce this operation below those bounds or split it into multiple operations (naming values inside the same operation does not reset the bounds)`,K(this.module.source,n,`__snapback2_type_analysis_limit_${vr}_depth_${Rr}_visits_per_operation__()`))),P}numeric(n,t,i,r){let s=Cl(n.text);if(i?.kind==="decimal"){if(s>i.scale)return this.add("E_DECIMAL_SCALE",n,`${s} fractional digits, scale ${i.scale}; ${mt(i)} cannot represent ${n.text}`,K(this.module.source,n,`decimal(${n.text}, ${i.scale})`)),i;let o=sa(n.text,i.scale);return o===void 0?this.add("E_DECIMAL_SCALE",n,`${n.text} at scale ${i.scale} is outside the safe integer wire range`,K(this.module.source,n,`decimal(${n.text}, ${i.scale})`)):this.literalValues.set(Ye(t.literalContext,n,this.module.sourceFile),o),i}return s===0?{kind:"int"}:(r||this.add("E_DECIMAL_SCALE",n,`fractional literal ${n.text} has ${s} fractional digits but no Decimal scale`,K(this.module.source,n,`decimal(${n.text}, ${s})`)),P)}binary(n,t,i){let r=n.operatorToken.kind;if(r===x.SyntaxKind.PlusToken){let l=Pr(n),f=l.map(d=>this.expression(d,t,void 0,!0));if(f.some(Rn))return this.add("E_ARGS_ID_TEXT",n,"Id scalars cannot be concatenated or added into text; keep identity values structurally separate",this.idTextRewrite(n,i,l,f)),P}let s=this.expression(n.left,t,void 0,!0),o=this.expression(n.right,t,void 0,!0),u=[x.SyntaxKind.EqualsEqualsToken,x.SyntaxKind.EqualsEqualsEqualsToken,x.SyntaxKind.ExclamationEqualsToken,x.SyntaxKind.ExclamationEqualsEqualsToken].includes(r)&&Rn(s)!==Rn(o);if(this.analysisLimitReached)return P;if(r===x.SyntaxKind.AsteriskToken?s.kind==="decimal"?o=this.expression(n.right,t):o.kind==="decimal"?s=this.expression(n.left,t):(s=this.expression(n.left,t),o=this.expression(n.right,t)):u?Rn(s)?o=this.expression(n.right,t,ln):s=this.expression(n.left,t,ln):s.kind==="decimal"?o=this.expression(n.right,t,s):o.kind==="decimal"?s=this.expression(n.left,t,o):s.kind==="enum"?o=this.expression(n.right,t,s):o.kind==="enum"?s=this.expression(n.left,t,o):(s=this.expression(n.left,t,i),o=this.expression(n.right,t,i)),this.analysisLimitReached)return P;if(r===x.SyntaxKind.QuestionQuestionToken)return s.kind==="enum"&&(o=this.expression(n.right,t,s)),o.kind==="enum"&&(s=this.expression(n.left,t,o)),s.kind==="string"&&(o=this.expression(n.right,t,s)),o.kind==="string"&&(s=this.expression(n.left,t,o)),s.kind==="unknown"?P:s.kind==="null"?o:s;let c=[x.SyntaxKind.LessThanToken,x.SyntaxKind.LessThanEqualsToken,x.SyntaxKind.GreaterThanToken,x.SyntaxKind.GreaterThanEqualsToken,x.SyntaxKind.EqualsEqualsToken,x.SyntaxKind.EqualsEqualsEqualsToken,x.SyntaxKind.ExclamationEqualsToken,x.SyntaxKind.ExclamationEqualsEqualsToken].includes(r);return s.kind==="enum"&&x.isStringLiteralLike(h(n.right))&&this.enumVariant(h(n.right),s),o.kind==="enum"&&x.isStringLiteralLike(h(n.left))&&this.enumVariant(h(n.left),o),s.kind==="decimal"||o.kind==="decimal"?this.decimalBinary(n,s,o,c):c?{kind:"bool"}:Gn([s,o])}decimalBinary(n,t,i,r){let s=n.operatorToken.kind,o=t.kind==="decimal"?t:i.kind==="decimal"?i:P;if(r&&(t.kind==="null"||i.kind==="null"))return{kind:"bool"};let a=Dr(n.left)||Dr(n.right),u=t.kind==="decimal"&&i.kind==="decimal"&&mr(t,i);return(r||s===x.SyntaxKind.PlusToken||s===x.SyntaxKind.MinusToken)&&(u||a)?r?{kind:"bool"}:o:s===x.SyntaxKind.AsteriskToken&&(t.kind==="decimal"&&i.kind==="int"||i.kind==="decimal"&&t.kind==="int")?o:(this.decimalMismatch(n,t,i,vl(s)),r?{kind:"bool"}:o)}call(n,t,i){let r=oe(n);if(x.isPropertyAccessExpression(n.expression)&&this.operationComposite(n.expression.expression,t)==="ctx"){if(n.expression.name.text==="newId")return ln;if(n.expression.name.text==="now")return{kind:"int"}}if(x.isIdentifier(n.expression)){let s=t.variables.has(n.expression.text)?void 0:this.module.helpers?.get(n.expression.text);if(s){if(this.helperStack.includes(n.expression.text)||this.helperStack.length>=128)return P;this.helperStack.push(n.expression.text);try{let o=Dn(t);if(o.literalContext=Bt(t.literalContext,n,this.module.sourceFile),s.parameters.forEach((a,u)=>{let c=n.arguments[u]?this.expression(n.arguments[u],t):P,l=n.arguments[u]?this.binding(n.arguments[u],t,c):{type:P};for(let f of Yn(a.name))Ln(o,f,l)}),s.body&&x.isBlock(s.body)){let a=s.body.statements.find(x.isReturnStatement)?.expression;return a?this.expression(a,o,i):P}if(s.body)return this.expression(s.body,o,i)}finally{this.helperStack.pop()}}}if(r==="decimal"&&!t.variables.has(r)){let s=n.arguments[1]&&h(n.arguments[1]),o=s&&x.isNumericLiteral(s)?Number(s.text):void 0,a=n.arguments[0],u=Number.isInteger(o)&&o>=0&&o<=12?{kind:"decimal",scale:o}:P;return!a||u.kind!=="decimal"||!Ml(a)?this.add("E_DECIMAL_SCALE",n,"decimal(value, scale) requires a numeric literal and an integer scale from 0 through 12","use decimal(9.99, 2)"):this.expression(a,t,u),u}if(x.isPropertyAccessExpression(n.expression)&&this.operationComposite(n.expression.expression,t)==="db"){let s=n.expression.name.text,o=n.arguments[0],a=o&&this.tableReference(o);if(s==="insert"||s==="update"||s==="upsert"){let u=n.arguments[s==="insert"?1:2];if(o&&this.expression(o,t),n.arguments[1]&&s!=="insert"&&this.expression(n.arguments[1],t,a?.columns?.id??ln),u&&a){let c={kind:"row",table:a.name};ge(u)?this.callback(u,t,c,c):this.expression(u,t,c)}return s==="insert"&&a?{kind:"row",table:a.name}:P}if((s==="get"||s==="scan")&&a){o&&this.expression(o,t);let u=this.indexTypes(o,a),c=n.arguments[1];if(c&&this.key(c,t,u),s==="scan"){let f=n.arguments[2];f&&this.scanOptions(f,t,u.slice(this.prefixArity(c,t)))}let l={kind:"row",table:a.name};return s==="scan"?{kind:"list",of:l}:l}}if((r==="min"||r==="max")&&!t.variables.has(r)&&n.arguments.length>0){let s=n.arguments.map(u=>this.expression(u,t,void 0,!0)),o=s.find(u=>u.kind==="decimal");o?.kind==="decimal"&&(s=n.arguments.map(u=>this.expression(u,t,o)));let a=s.every((u,c)=>mr(o??P,u)||Dr(n.arguments[c]));return o?.kind==="decimal"&&!a&&this.decimalMismatch(n,s[0]??P,s[1]??P,r),o??Gn(s)}if(r==="divmod"&&!t.variables.has(r)&&n.arguments.length===2){let s=h(n.arguments[0]);if(x.isBinaryExpression(s)&&s.operatorToken.kind===x.SyntaxKind.AsteriskToken){let u=this.expression(s.left,t,void 0,!0),c=this.expression(s.right,t,void 0,!0);if(u.kind==="decimal"&&c.kind==="decimal"){let l=n.arguments[1];this.expression(l,t,{kind:"int"}),u.currency&&c.currency&&this.add("E_DECIMAL_SCALE",s,"money multiplied by money has no currency-squared value","multiply the money value by a decimal rate or an int");let f=u.currency?c:c.currency?u:c,d=u.currency?u:c.currency?c:u,p=10**f.scale;return Il(l)!==p&&this.add("E_DECIMAL_SCALE",l,`branded multiplication must divide by 10^${f.scale} (${p}) to drop ${mt(f)}`,K(this.module.source,l,String(p))),{kind:"object",fields:{quotient:d,remainder:d}}}}let o=this.expression(n.arguments[0],t,void 0,!0);this.expression(n.arguments[1],t,{kind:"int"});let a=ee(o);return a.kind==="int"||a.kind==="decimal"?{kind:"object",fields:{quotient:a,remainder:a}}:P}if(r==="deterministicShare"&&!t.variables.has(r)&&n.arguments.length===3){let s=this.expression(n.arguments[0],t,void 0,!0);return this.expression(n.arguments[1],t),this.expression(n.arguments[2],t),s}if(r==="concat"&&!t.variables.has(r)){let s=n.arguments.map(o=>this.expression(o,t,void 0,!0));if(s.some(Rn)&&s.some(o=>ee(o).kind==="string"&&!be(ee(o)))&&be(ee(i))&&Mi(n))return this.add("E_ARGS_ID_TEXT",n,"Id scalars cannot be concatenated into text; keep identity values structurally separate",this.idTextRewrite(n,i,[...n.arguments],s)),P;if(s.length>0&&s.every(Rn))return ln;if(s.every(o=>ee(o).kind==="list")){let o=s.map(ee);return{kind:"list",of:Gn(o.map(a=>a.of))}}return s.some(o=>ee(o).kind==="string")?{kind:"string"}:Gn(s)}if(r==="String"&&!t.variables.has(r)&&n.arguments.length===1){let s=n.arguments[0],o=this.expression(s,t,void 0,!0);return Rn(o)&&be(ee(i))&&Mi(n)?(this.add("E_ARGS_ID_TEXT",n,"String(id) would erase the Id's nominal domain; keep the identity value separate",this.idTextRewrite(n,i,[s],[o])),P):{kind:"string"}}if(x.isPropertyAccessExpression(n.expression)){let s=this.expression(n.expression.expression,t),o=n.expression.name.text;if(s.kind==="list"&&["map","filter","some"].includes(o)){let a=n.arguments[0],u=a&&ge(a)?this.callback(a,t,s.of):P;return o==="map"?{kind:"list",of:u}:o==="filter"?s:{kind:"bool"}}}for(let s of n.arguments)this.expression(s,t);return i??P}callback(n,t,i,r){let s=Dn(t);for(let o of n.parameters)for(let a of Yn(o.name))Ln(s,a,{type:i});return n.body?x.isBlock(n.body)?(this.statements(n.body.statements,s),P):this.expression(n.body,s,r):P}binding(n,t,i){let r=h(n);return x.isIdentifier(r)?{...t.variables.get(r.text),type:i}:{type:i}}operationComposite(n,t){let i=h(n);return x.isIdentifier(i)?t.variables.get(i.text)?.operationComposite:void 0}tableReference(n){let t=ye(n);if(!t)return;let i=this.module.tables.get(t);if(i)return i;let r=t.lastIndexOf(".");return r>0?this.module.tables.get(t.slice(0,r)):void 0}table(n){return[...this.module.tables.values()].find(t=>t.name===n)}indexTypes(n,t){let i=n&&ye(n);if(!i)return[];let r=this.module.tables.get(i);if(r)return r.indexes?.byId?.types??[ln];let s=i.lastIndexOf(".");return s>0?t.indexes?.[i.slice(s+1)]?.types??[]:[]}key(n,t,i){let r=h(n);x.isArrayLiteralExpression(r)?r.elements.forEach((s,o)=>this.expression(s,t,i[o])):this.expression(r,t,i.length===1?i[0]:{kind:"list",of:Gn(i),max:i.length})}scanOptions(n,t,i){let r=h(n);if(!x.isObjectLiteralExpression(r)){this.expression(r,t);return}for(let s of r.properties){if(!x.isPropertyAssignment(s))continue;let o=H(s.name);if(o==="after"||o==="before"){let a=h(s.initializer);x.isArrayLiteralExpression(a)?a.elements.forEach((u,c)=>this.expression(u,t,i[c])):this.expression(a,t,i.length===1?i[0]:void 0)}else if(o==="range"){let a=h(s.initializer);if(!x.isObjectLiteralExpression(a))this.expression(a,t);else for(let u of a.properties)x.isPropertyAssignment(u)&&this.expression(u.initializer,t,i[0])}else this.expression(s.initializer,t)}}enumVariant(n,t){t.variants.includes(n.text)||this.add("E_ENUM_VARIANT",n,`${JSON.stringify(n.text)} is not an enum variant; expected ${t.variants.map(i=>JSON.stringify(i)).join(", ")}`,K(this.module.source,n,JSON.stringify(t.variants[0]??"")))}decimalMismatch(n,t,i,r){this.add("E_DECIMAL_SCALE",n,`${r} requires equal Decimal scales (or literal 0); received ${mt(t)} and ${mt(i)}`,`make both operands ${t.kind==="decimal"?mt(t):i.kind==="decimal"?mt(i):"the same Decimal<S>"}`)}idScalarRewrite(n,t){if(this.programKind==="Mutation"&&wl(n)){let u=[...t.variables].find(([,f])=>f.operationComposite==="ctx")?.[0];if(u)return K(this.module.source,n,Yo(n,`${u}.newId()`));let l=Xo(n)?.parameters[0]?.name;if(l&&x.isObjectBindingPattern(l)){let f=Zo(this.module.source,"snapbackCtx"),p=`${l.getText(this.module.sourceFile).slice(0,-1).trimEnd()}${l.elements.length===0?" ":", "}ctx: ${f} }`;return ea(this.module.source,[{start:l.getStart(this.module.sourceFile),end:l.getEnd(),value:p},{start:n.getStart(this.module.sourceFile),end:n.getEnd(),value:Yo(n,`${f}.newId()`)}])}}let i=[...t.variables].find(([,u])=>u.operationComposite==="args")?.[0],r=Al(n,i),s=this.operation.arguments[0],o=s?h(s):void 0;if(r&&o&&x.isObjectLiteralExpression(o)){let u=o.properties.find(c=>x.isPropertyAssignment(c)&&H(c.name)===r);if(u&&x.isPropertyAssignment(u))return K(this.module.source,u.initializer,"t.id()")}let a=Object.entries(t.args).find(([,u])=>be(ee(u)))?.[0];if(i&&a)return K(this.module.source,n,`${i}.${a}`);if(o&&x.isObjectLiteralExpression(o)){let u=Tl(t.args,"id"),l=`${o.getText(this.module.sourceFile).slice(0,-1).trimEnd()}${o.properties.length===0?" ":", "}${u}: t.id() }`,f=[{start:o.getStart(this.module.sourceFile),end:o.getEnd(),value:l}],d=i;if(!d){let p=Xo(n)?.parameters[0]?.name;if(p&&x.isObjectBindingPattern(p)){d=Zo(this.module.source,"snapbackArgs");let g=p.getText(this.module.sourceFile);f.push({start:p.getStart(this.module.sourceFile),end:p.getEnd(),value:`${g.slice(0,-1).trimEnd()}${p.elements.length===0?" ":", "}args: ${d} }`})}}if(d)return f.push({start:n.getStart(this.module.sourceFile),end:n.getEnd(),value:`${d}.${u}`}),ea(this.module.source,f)}return this.module.source}bindingTypes(n,t,i,r){let s=new Map,o=(a,u,c,l=r)=>{if(x.isIdentifier(a)){s.set(a.text,u?this.expression(u,l):c);return}let f=u&&h(u),d=x.isArrayBindingPattern(a)&&f?this.arrayBindingSources(f,l):void 0;a.elements.forEach((p,g)=>{if(!x.isBindingElement(p))return;let m=c.kind==="list"?c.of:P,y=d?.sources[g];o(p.name,y&&!x.isOmittedExpression(y)?y:void 0,m,d?.env??l)})};return o(n,t,i),s}arrayBindingSources(n,t){if(x.isArrayLiteralExpression(n))return{sources:n.elements,env:t};if(!x.isCallExpression(n)||!x.isIdentifier(n.expression)||t.variables.has(n.expression.text))return;let i=this.module.helpers?.get(n.expression.text),r=na(i),s=r&&h(r);if(!i||!s||!x.isArrayLiteralExpression(s))return;let o=Dn(t);return o.literalContext=Bt(t.literalContext,n,this.module.sourceFile),i.parameters.forEach((a,u)=>{let c=n.arguments[u],l=c?this.expression(c,t):P,f=c?this.binding(c,t,l):{type:P};for(let d of Yn(a.name))Ln(o,d,f)}),{sources:s.elements,env:o}}prefixArity(n,t,i=new Set){if(!n)return 0;let r=h(n);if(x.isArrayLiteralExpression(r))return r.elements.length;if(x.isIdentifier(r)){let s=`binding:${r.text}`;if(i.has(s))return 1;i.add(s);let o=t.constants.get(r.text);return o?this.prefixArity(o,t,i):1}if(x.isCallExpression(r)&&x.isIdentifier(r.expression)&&!t.variables.has(r.expression.text)){let s=`helper:${r.expression.text}`;if(i.has(s))return 1;i.add(s);let o=na(this.module.helpers?.get(r.expression.text));return o?this.prefixArity(o,t,i):1}return 1}idTextRewrite(n,t,i,r){let s=i.filter((a,u)=>be(r[u])),o;return be(ee(t))?o=s[0]?.getText(this.module.sourceFile)??JSON.stringify("replace-with-id"):["string","enum"].includes(ee(t).kind)?o=JSON.stringify("replace-with-text"):o=`[${s.map(a=>a.getText(this.module.sourceFile)).join(", ")}]`,K(this.module.source,n,o)}add(n,t,i,r){let s=`${n}:${t.getStart(this.module.sourceFile)}:${i}`;this.seen.has(s)||(this.seen.add(s),this.diagnostics.push(L(this.module,n,t,i,r)))}};function Pr(e){let n=h(e);return x.isBinaryExpression(n)&&n.operatorToken.kind===x.SyntaxKind.PlusToken?[...Pr(n.left),...Pr(n.right)]:[n]}function Sl(e){let n=h(e);return x.isArrayLiteralExpression(n)||x.isCallExpression(n)||x.isBinaryExpression(n)&&n.operatorToken.kind===x.SyntaxKind.QuestionQuestionToken}function Rn(e){let n=ee(e);return be(n)||n.kind==="principal"}function wl(e){let n=e;for(;n.parent&&!x.isFunctionLike(n.parent);){let t=n.parent;if((x.isPropertyAssignment(t)||x.isShorthandPropertyAssignment(t))&&H(t.name)==="id"){let i=t.parent,r=i.parent;return x.isObjectLiteralExpression(i)&&x.isCallExpression(r)&&r.arguments[1]===i&&x.isPropertyAccessExpression(r.expression)&&r.expression.name.text==="insert"}n=t}return!1}function Mi(e){for(let n=e;n.parent&&!x.isFunctionLike(n.parent);n=n.parent){let t=n.parent;if(!x.isPropertyAssignment(t)&&!x.isShorthandPropertyAssignment(t))continue;let i=t.parent,r=i.parent;if(!x.isObjectLiteralExpression(i)||!x.isCallExpression(r)||!x.isPropertyAccessExpression(r.expression))continue;let s=r.expression.name.text;if(s==="insert"&&r.arguments[1]===i||(s==="update"||s==="upsert")&&r.arguments[2]===i)return!0}return!1}function $l(e){let n=ee(e);return be(n)||n.kind==="principal"}function Yo(e,n){return x.isIdentifier(e)&&x.isShorthandPropertyAssignment(e.parent)?`id: ${n}`:n}function Al(e,n){let t=h(e);return n&&x.isPropertyAccessExpression(t)&&x.isIdentifier(t.expression)&&t.expression.text===n?t.name.text:void 0}function Tl(e,n){let t=n,i=1;for(;t in e;)t=`${n}${i++}`;return t}function Xo(e){for(let n=e.parent;n;n=n.parent)if(ge(n))return n}function Zo(e,n){let t=n,i=1;for(;new RegExp(`\\b${t}\\b`).test(e);)t=`${n}${i++}`;return t}function ea(e,n){let t=e;for(let i of n.sort((r,s)=>s.start-r.start))t=`${t.slice(0,i.start)}${i.value}${t.slice(i.end)}`;return t}function ia(e){let n=N(e),t=n&&(x.isIdentifier(n.expression)?n.expression.text:x.isPropertyAccessExpression(n.expression)?n.expression.name.text:void 0);if(!n)return P;if(t==="int"||t==="time")return{kind:"int"};if(t==="principal")return{kind:"principal"};if(t==="id"||t==="ref")return ln;if(t==="text"){let i=n.arguments[0]&&h(n.arguments[0]);return{kind:"string",...i&&x.isNumericLiteral(i)?{max:Number(i.text)}:{}}}if(t==="bytes"){let i=n.arguments[0]&&h(n.arguments[0]);return{kind:"bytes",max:i&&x.isNumericLiteral(i)?Number(i.text):0}}if(t==="image"||t==="video"){let i=n.arguments[0]&&h(n.arguments[0]);return{kind:"asset",asset:t,max:i&&x.isNumericLiteral(i)?Number(i.text):0}}if(t==="bool")return{kind:"bool"};if(t==="json")return{kind:"json"};if(t==="enum"){let i=n.arguments[0]&&h(n.arguments[0]);return i&&x.isArrayLiteralExpression(i)?{kind:"enum",variants:i.elements.filter(x.isStringLiteralLike).map(r=>r.text)}:P}if(t==="decimal"||t==="money"){let i=t==="decimal"?0:1,r=n.arguments[i]&&h(n.arguments[i]),s=r&&x.isNumericLiteral(r)?Number(r.text):t==="money"?2:void 0,o=t==="money"&&n.arguments[0]&&h(n.arguments[0]);return s!==void 0?{kind:"decimal",scale:s,...o&&x.isStringLiteralLike(o)?{currency:o.text}:{}}:P}if((t==="optional"||t==="list")&&n.arguments[0]){let i=ia(n.arguments[0]);return t==="optional"?{kind:"optional",of:i}:{kind:"list",of:i}}return P}function Yn(e){return x.isIdentifier(e)?[e.text]:e.elements.flatMap(n=>x.isBindingElement(n)?Yn(n.name):[])}function ra(e,n){if(x.isIdentifier(e))return e.text===n?e:void 0;for(let t of e.elements){if(!x.isBindingElement(t))continue;let i=ra(t.name,n);if(i)return i}}function na(e){if(e?.body){if(!x.isBlock(e.body))return e.body;if(!(e.body.statements.length!==1||!x.isReturnStatement(e.body.statements[0])))return e.body.statements[0].expression}}function Nl(e){let n=e.parameters[0];if(!n||!x.isObjectBindingPattern(n.name))return{};let t={};for(let i of n.name.elements){if(!x.isIdentifier(i.name))continue;let r=i.propertyName?H(i.propertyName):i.name.text;(r==="args"||r==="ctx"||r==="db")&&(t[r]=i.name.text)}return t}function Ln(e,n,t,i){e.variables.set(n,{...t}),i?e.constants.set(n,i):e.constants.delete(n)}function Dn(e){return{variables:new Map([...e.variables].map(([n,t])=>[n,{...t}])),constants:new Map(e.constants),args:e.args,mutableBindings:e.mutableBindings,memo:new Map,literalContext:e.literalContext}}function Gn(e){if(e.length===0||e.some(t=>t.kind==="unknown"))return P;let n=JSON.stringify(e[0]);return e.every(t=>JSON.stringify(t)===n)?e[0]:P}function _l(e,n){if(n==="id")return ln;if(n==="width"||n==="height"||e==="video"&&n==="duration")return{kind:"int"}}function Ol(e){return be(e)?"Id":e.kind==="list"?"an array":e.kind==="object"||e.kind==="json"?"an object":e.kind==="asset"?`${e.asset} asset`:e.kind}function Cl(e){return Cn(e)?.fraction.length??1}function sa(e,n){let t=Cn(e);if(!t||t.fraction.length>n)return;let i=BigInt(`${t.whole}${t.fraction.padEnd(n,"0")}`);return i<=BigInt(Number.MAX_SAFE_INTEGER)?Number(i):void 0}function mt(e){return e.kind==="decimal"?e.currency?`Money<${JSON.stringify(e.currency)}, ${e.scale}>`:`Decimal<${e.scale}>`:e.kind==="int"?"Int":e.kind==="enum"?"Enum":"Unknown"}function Dr(e){let n=h(e),t=x.isNumericLiteral(n)&&Cn(n.text);return!!t&&t.whole==="0"&&t.fraction===""}function Il(e){let n=h(e);return x.isNumericLiteral(n)?sa(n.text,0):void 0}function Ml(e){let n=h(e);return x.isNumericLiteral(n)||x.isPrefixUnaryExpression(n)&&n.operator===x.SyntaxKind.MinusToken&&x.isNumericLiteral(n.operand)}function vl(e){return x.tokenToString(e)??x.SyntaxKind[e]}import gt from"typescript";function Fr(e,n,t){let i=n.endsWith(".ts")?n:`${n}.ts`,r=new Map([[i,e],["bounded-lib.d.ts",t]]),s={module:gt.ModuleKind.ESNext,noEmit:!0,noLib:!0,strict:!0,target:gt.ScriptTarget.ES2022},o={fileExists:u=>r.has(u),getCanonicalFileName:u=>u,getCurrentDirectory:()=>"",getDefaultLibFileName:()=>"bounded-lib.d.ts",getNewLine:()=>`
7
+ `,getSourceFile:(u,c)=>{let l=r.get(u);return l===void 0?void 0:gt.createSourceFile(u,l,c,!0)},readFile:u=>r.get(u),useCaseSensitiveFileNames:()=>!0,writeFile:()=>{}},a=gt.createProgram([i,"bounded-lib.d.ts"],s,o);return gt.getPreEmitDiagnostics(a).filter(u=>u.file?.fileName!=="bounded-lib.d.ts")}function oa(e){return gt.flattenDiagnosticMessageText(e.messageText,`
8
+ `)}import aa from"typescript";import pe from"typescript";function B(e){if(!e)return;let n=N(e);if(!n)return;let t=tn(n);if(t)return t;let i=pe.isIdentifier(n.expression)?n.expression.text:pe.isPropertyAccessExpression(n.expression)?n.expression.name.text:void 0;return i&&["query","mutation","effect","channel","table","schema","seed","emit"].includes(i)?void 0:i}function z(e){let n=e&&h(e);return n&&pe.isObjectLiteralExpression(n)?n:void 0}function _(e,n){return $e(e,n)}function sn(e){let n=[];for(let t of e.properties)if(pe.isPropertyAssignment(t)){let i=H(t.name);i&&n.push({name:i,value:t.initializer,node:t})}else pe.isShorthandPropertyAssignment(t)&&n.push({name:t.name.text,value:t.name,node:t});return n}function q(e){let n=e&&h(e);return n&&pe.isStringLiteralLike(n)?n.text:void 0}function X(e){let n=e&&h(e);if(n&&pe.isNumericLiteral(n))return Number(n.text);if(n&&pe.isPrefixUnaryExpression(n)&&n.operator===pe.SyntaxKind.MinusToken&&pe.isNumericLiteral(n.operand))return-Number(n.operand.text)}function $n(e){let n=e&&h(e);if(n?.kind===pe.SyntaxKind.TrueKeyword)return!0;if(n?.kind===pe.SyntaxKind.FalseKeyword)return!1}function en(e){let n=e&&h(e);if(!n||!pe.isArrayLiteralExpression(n))return;let t=n.elements.map(i=>q(i));return t.every(i=>i!==void 0)?t:void 0}function rn(e,n=new Map){let t=h(e);if(t.kind===pe.SyntaxKind.NullKeyword)return null;let i=$n(t);if(i!==void 0)return i;let r=X(t);if(r!==void 0)return r;let s=q(t);if(s!==void 0)return s;if(pe.isIdentifier(t))return n.get(t.text);if(pe.isArrayLiteralExpression(t)){let o=[];for(let a of t.elements){if(pe.isSpreadElement(a))return;let u=rn(a,n);if(u===void 0)return;o.push(u)}return o}if(pe.isObjectLiteralExpression(t)){let o=Object.create(null);for(let a of t.properties){if(pe.isSpreadAssignment(a)){let l=rn(a.expression,n);if(!l||typeof l!="object"||Array.isArray(l))return;Object.assign(o,l);continue}let u=pe.isPropertyAssignment(a)?{name:H(a.name),value:a.initializer}:pe.isShorthandPropertyAssignment(a)?{name:a.name.text,value:a.name}:void 0;if(!u?.name)return;let c=rn(u.value,n);if(c===void 0)return;o[u.name]=c}return o}}function zt(e){let n=new Map;for(let t of e.statements)if(!(!pe.isVariableStatement(t)||!(t.declarationList.flags&pe.NodeFlags.Const)))for(let i of t.declarationList.declarations){if(!pe.isIdentifier(i.name)||!i.initializer)continue;let r=rn(i.initializer,n);r!==void 0&&n.set(i.name.text,r)}return n}function vi(e,n){if(n==="schema.ts"||n.endsWith("/schema.ts"))return{code:"E_SCHEMA_INVALID",family:"schema",guide:"schema/project"};let t=ua(e,aa.isVariableDeclaration),i=t?.initializer&&N(t.initializer),r=i&&B(i);if(r==="effect"){let s=ua(e,aa.isPropertyAssignment);return s&&H(s.name)==="then"?{code:"E_EFFECT_THEN_ARGS",family:"effect",guide:"effects/authoring"}:{code:"E_EFFECT_TYPE",family:"effect",guide:"effects/authoring"}}if(i&&(r==="query"||r==="mutation")){let s=i.arguments[0];if(s&&e.getStart()>=s.getStart()&&e.getEnd()<=s.getEnd())return{code:"E_ARGS_TYPE",family:"args",guide:"programs/args"}}return{code:"E_OPAQUE",family:"opaque",guide:"opaque/subset"}}function ua(e,n){let t=e;for(;t;){if(n(t))return t;t=t.parent}}import ae from"typescript";var jr={systemPrincipalId:"system",retentionPolicies:["until-revoked","delivered-history"],valueModelVersion:"i53-codepoint-bytes-v2"};var yt=Object.freeze({systemPrincipalId:jr.systemPrincipalId,retentionPolicies:jr.retentionPolicies});import bt from"typescript";var Dl="declare authority axes as Principal and align rule terms with the referenced index columns";function ca(e,n,t,i,r,s){let o=da(i);for(let[a,u]of n){let c=z(u.arguments[0]),l=c&&z(_(c,"rules")),f=o.get(a);for(let d of["read","insert","update","delete"]){let p=l&&_(l,d);p&&Jt(e,p,f,{kind:"table",effect:d},o,s)}c&&f&&Ll(e,c,a,f,o,s)}for(let[a,u]of t){let c=z(u.arguments[0]),l=r[a],f=l&&typeof l=="object"&&!Array.isArray(l)?l.args:void 0,d=f&&typeof f=="object"&&!Array.isArray(f)?{label:`channel ${a}`,columns:f}:void 0;for(let p of["publish","subscribe"]){let g=c&&_(c,p);g&&Jt(e,g,d,{kind:"other"},o,s)}}}function la(e,n,t,i){let r=n&&h(n);if(!r||!bt.isArrayLiteralExpression(r))return;let s=da(t);for(let o of r.elements){let a=z(o),u=a&&_(a,"readable");if(!u)continue;let c=q(_(a,"into"));Jt(e,u,c?s.get(c):void 0,{kind:"other"},s,i)}}function da(e){let n=new Map;for(let[t,i]of Object.entries(e)){if(!i||typeof i!="object"||Array.isArray(i))continue;let r=i,s=r.columns&&typeof r.columns=="object"&&!Array.isArray(r.columns)?r.columns:{},o=r.indexes&&typeof r.indexes=="object"&&!Array.isArray(r.indexes)?r.indexes:{};n.set(t,{label:`table ${t}`,table:t,columns:s,indexes:o})}return n}function Jt(e,n,t,i,r,s){let o=N(n),a=o&&B(o);if(!o||!a)return;if(a==="viewerIs"&&o.arguments.length===1&&o.arguments[0]){let y=q(o.arguments[0]);if(y){let b=Br(e,o.arguments[0],t,y,s);b&&!Xn(b,{kind:"principal"})&&s.push(Le(e,o.arguments[0],`${t?.label??"unknown rule subject"}.${y} is ${An(b)}; fields compared with rule.viewer must be Principal`))}return}if((a==="eq"||a==="ne")&&o.arguments.length===2){let y=o.arguments[0]&&Ri(e,o.arguments[0],t,i,s),b=o.arguments[1]&&Ri(e,o.arguments[1],t,i,s);y&&b&&!Xn(y,b)&&s.push(Le(e,o,`rule.${a} compares ${An(y)} with ${An(b)}; rule terms must have compatible scalar types`));return}if(a==="and"||a==="or"){for(let y of o.arguments)Jt(e,y,t,i,r,s);return}if(a==="not"&&o.arguments[0]){Jt(e,o.arguments[0],t,i,r,s);return}if(a!=="exists"&&a!=="created"||(a==="created"&&!(i.kind==="table"&&i.effect==="insert")&&s.push(Le(e,o,"created-row probes are valid only in table insert rules")),o.arguments.length!==3))return;let u=a,c=o.arguments[0]&&h(o.arguments[0]),l=c&&bt.isIdentifier(c)?c.text:void 0,f=q(o.arguments[1]),d=o.arguments[2]&&h(o.arguments[2]),p=l?r.get(l):void 0;if(!l||!p){s.push(Le(e,o.arguments[0]??o,`rule.${u} references unresolved table ${l??o.arguments[0]?.getText()??"<missing>"}`));return}if(!f)return;let g=f?p?.indexes[f]:void 0;if(!g){s.push(Le(e,o.arguments[1]??o,`rule.${u} references unresolved index ${l}.${f}`));return}if(!d||!bt.isArrayLiteralExpression(d))return;let m=g.columns;if(!Array.isArray(m)){s.push(Le(e,o.arguments[1]??o,`rule.${u} index ${l}.${f} has an unresolved column list`));return}d.elements.length!==m.length&&s.push(Le(e,d,`rule.${u} key for ${l}.${f} has ${d.elements.length} terms; expected ${m.length}`));for(let[y,b]of d.elements.entries()){let S=m[y];if(!S)continue;let E=Gt(p.columns[S]);if(!E){s.push(Le(e,b,`rule.${u} index ${l}.${f} references unresolved column ${S}`));continue}let k=Ri(e,b,t,i,s);!k||pa(k,E,l,S,i.kind==="table"?t?.table:void 0,b)||s.push(Le(e,b,`rule.${u} term for ${l}.${f}.${S} is ${An(k)}; expected ${An(E)}`))}}function Ll(e,n,t,i,r,s){let o=_(n,"constraints"),a=o&&h(o);if(!(!a||!bt.isArrayLiteralExpression(a)))for(let u of a.elements){let c=z(u),l=c&&_(c,"finalExistsOnInsert"),f=l&&z(l);if(!f)continue;let d=_(f,"table"),p=q(d);if(!p)continue;let g=r.get(p);if(!g){s.push(Le(e,d??l,`final-exists constraint references unknown table ${p}`));continue}let m=_(f,"index"),y=q(m);if(!y)continue;let b=g.indexes[y];if(!b){s.push(Le(e,m??l,`final-exists constraint references unknown index ${p}.${y}`));continue}let S=_(f,"key"),E=S&&h(S);if(!E||!bt.isArrayLiteralExpression(E))continue;let k=b.columns;if(!Array.isArray(k)){s.push(Le(e,m??l,`final-exists index ${p}.${y} has an unresolved column list`));continue}E.elements.length!==k.length&&s.push(Le(e,E,`final-exists key for ${p}.${y} has ${E.elements.length} terms; expected ${k.length}`));for(let[$,R]of E.elements.entries()){let D=k[$];if(!D)continue;let J=Gt(g.columns[D]);if(!J){s.push(Le(e,R,`final-exists index ${p}.${y} references unresolved column ${D}`));continue}let se=Ri(e,R,i,{kind:"other"},s);!se||Pl(se,J,t,p,D,R)||s.push(Le(e,R,`final-exists term for ${p}.${y}.${D} is ${An(se)}; expected ${An(J)}`))}}}function Ri(e,n,t,i,r){let s=h(n);if(bt.isPropertyAccessExpression(s)&&s.expression.getText()==="rule"&&s.name.text==="viewer")return{kind:"principal"};let o=N(s),a=o&&B(o);if(o&&a==="field"&&o.arguments.length===1&&o.arguments[0]){let u=q(o.arguments[0]);if(u)return Br(e,o.arguments[0],t,u,r)}if(o&&(a==="oldField"||a==="nextField")&&o.arguments.length===1&&o.arguments[0]){if(!(i.kind==="table"&&i.effect==="update")){r.push(Le(e,o,`${a==="oldField"?"old":"next"}-row fields are valid only in table update rules`));return}let u=q(o.arguments[0]);if(u)return Br(e,o.arguments[0],t,u,r)}if(o&&a==="literal"&&o.arguments.length===1&&o.arguments[0]){let u=rn(o.arguments[0]);if(u!==void 0)return fa(u)}}function Br(e,n,t,i,r){let s=Gt(t?.columns[i]);if(s)return s;r.push(Le(e,n,`rule references unknown or untyped field ${i} on ${t?.label??"its unresolved outer subject"}`))}function Gt(e){if(e==="Principal")return{kind:"principal"};if(e==="Id")return{kind:"id"};if(e==="Int")return{kind:"int"};if(e==="Bool")return{kind:"bool"};if(e==="Time")return{kind:"time"};if(e==="Scalar")return{kind:"scalar"};if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(n.Ref&&typeof n.Ref.table=="string")return{kind:"ref",table:n.Ref.table};if(n.Text)return{kind:"text"};if(n.Bytes)return{kind:"bytes"};if(n.Json)return{kind:"json"};if(n.Enum&&Array.isArray(n.Enum.variants))return{kind:"enum",variants:[...n.Enum.variants]};if(n.Decimal&&typeof n.Decimal.scale=="number")return{kind:"decimal",scale:n.Decimal.scale};if(n.Money&&typeof n.Money.currency=="string"&&typeof n.Money.scale=="number")return{kind:"money",currency:n.Money.currency,scale:n.Money.scale};if("Optional"in n){let t=Gt(n.Optional);return t?{kind:"optional",of:t}:void 0}if(n.List){let t=Gt(n.List.of??"Scalar");return t?{kind:"list",of:t}:void 0}}function fa(e){return e===null?{kind:"null-literal"}:typeof e=="boolean"?{kind:"bool-literal"}:typeof e=="number"?{kind:"int-literal"}:typeof e=="string"?{kind:"text-literal",value:e}:Array.isArray(e)?{kind:"array-literal",values:e.map(fa)}:{kind:"json-literal"}}function Xn(e,n){return Di(e,n)?!0:e.kind==="optional"?n.kind==="null-literal"||Xn(e.of,n):n.kind==="optional"?e.kind==="null-literal"||Xn(e,n.of):e.kind==="text"&&n.kind==="text-literal"||n.kind==="text"&&e.kind==="text-literal"?!0:e.kind==="enum"&&n.kind==="text-literal"?e.variants.includes(n.value):n.kind==="enum"&&e.kind==="text-literal"?n.variants.includes(e.value):["int","time"].includes(e.kind)&&n.kind==="int-literal"||["int","time"].includes(n.kind)&&e.kind==="int-literal"||["decimal","money"].includes(e.kind)&&n.kind==="int-literal"||["decimal","money"].includes(n.kind)&&e.kind==="int-literal"||e.kind==="bool"&&n.kind==="bool-literal"||n.kind==="bool"&&e.kind==="bool-literal"||e.kind==="bytes"&&n.kind==="json-literal"||n.kind==="bytes"&&e.kind==="json-literal"||e.kind==="json"&&Wt(n)||n.kind==="json"&&Wt(e)?!0:e.kind==="array-literal"&&n.kind==="array-literal"?e.values.every(Wt)&&n.values.every(Wt):e.kind==="list"&&n.kind==="array-literal"?n.values.every(t=>Xn(e.of,t)):n.kind==="list"&&e.kind==="array-literal"?e.values.every(t=>Xn(t,n.of)):!1}function Wt(e){return["null-literal","text-literal","int-literal","bool-literal","json-literal"].includes(e.kind)?!0:e.kind==="array-literal"&&e.values.every(Wt)}function pa(e,n,t,i,r,s){let o=s&&N(s);return Xn(e,n)||e.kind==="ref"&&e.table===t&&n.kind==="id"&&i==="id"||e.kind==="id"&&n.kind==="ref"&&n.table===r&&B(o)==="field"&&q(o?.arguments[0])==="id"}function Pl(e,n,t,i,r,s){if(pa(e,n,i,r))return!0;let o=n.kind==="ref"?n.table:n.kind==="optional"&&n.of.kind==="ref"?n.of.table:void 0,a=N(s);return e.kind==="id"&&o===t&&B(a)==="field"&&q(a?.arguments[0])==="id"}function Di(e,n){return e.kind!==n.kind?!1:e.kind==="ref"&&n.kind==="ref"?e.table===n.table:e.kind==="enum"&&n.kind==="enum"?JSON.stringify(e.variants)===JSON.stringify(n.variants):e.kind==="decimal"&&n.kind==="decimal"?e.scale===n.scale:e.kind==="money"&&n.kind==="money"?e.currency===n.currency&&e.scale===n.scale:e.kind==="optional"&&n.kind==="optional"||e.kind==="list"&&n.kind==="list"?Di(e.of,n.of):e.kind==="array-literal"&&n.kind==="array-literal"?e.values.length===n.values.length&&e.values.every((t,i)=>Di(t,n.values[i])):!0}function An(e){switch(e.kind){case"principal":return"Principal";case"id":return"Id";case"ref":return`Ref<${e.table}>`;case"text":return"Text";case"int":return"Int";case"bool":return"Bool";case"time":return"Time";case"bytes":return"Bytes";case"json":return"Json";case"enum":return`Enum<${e.variants.join("|")}>`;case"decimal":return`Decimal<${e.scale}>`;case"money":return`Money<${e.currency},${e.scale}>`;case"optional":return`Optional<${An(e.of)}>`;case"list":return`List<${An(e.of)}>`;case"scalar":return"Scalar";case"null-literal":return"null literal";case"text-literal":return`text literal ${JSON.stringify(e.value)}`;case"int-literal":return"integer literal";case"bool-literal":return"boolean literal";case"array-literal":return"array literal";case"json-literal":return"json literal"}}function Le(e,n,t){return L(e,"E_RULE_INVALID",n,t,Dl)}function Qr(e,n){let t=ae.createSourceFile(n,e,ae.ScriptTarget.ES2022,!0),i={sourceFile:t,source:e,fileName:n},r=[],s=new Map,o=new Map,a;for(let m of t.statements){if(ae.isExportAssignment(m)&&!m.isExportEquals){let y=N(m.expression);y&&B(y)==="schema"?a=y:r.push(v(i,"E_SCHEMA_DEFAULT_EXPORT",m,"schema.ts must default-export schema({...})"));continue}if(!(!ae.isVariableStatement(m)||!Pe(m)))for(let y of m.declarationList.declarations){if(!ae.isIdentifier(y.name)||!y.initializer)continue;let b=N(y.initializer);b&&(B(b)==="table"&&s.set(y.name.text,b),B(b)==="channel"&&o.set(y.name.text,b))}}a||r.push(v(i,"E_SCHEMA_DEFAULT_EXPORT",t,"schema.ts must default-export schema({...})"));let u=new Map;for(let m of s.keys())m.startsWith("_")&&r.push(v(i,"E_SCHEMA_RESERVED",s.get(m),`table ${m} uses the reserved _ prefix`)),u.set(m,{name:m,private:!0});let c=Object.create(null);for(let[m,y]of s){let b=Fl(i,m,y,u,r);b&&(c[m]=b.value,u.set(m,{name:m,private:b.private,columns:b.columns,indexes:b.indexes,readRule:b.readRule}))}let l=Object.create(null);for(let[m,y]of o){let b=Kl(i,y,u,r);b&&(l[m]=b)}ca(i,s,o,c,l,r);let f=a?z(a.arguments[0]):void 0;a&&!f&&r.push(v(i,"E_SCHEMA_DEFAULT_EXPORT",a,"schema() requires one object literal")),f&&(on(i,f,["auth","tables","maintains","channels"],"schema","E_SCHEMA_INVALID",r),ba(i,f,"tables",s,r),ba(i,f,"channels",o,r));let d=f?Vl(i,_(f,"maintains"),u,c,r):[];f&&la(i,_(f,"maintains"),c,r);for(let m of d){let y=m,b=u.get(y.target);b&&(b.maintainedFrom=y.source)}let p=f&&z(_(f,"auth"));p&&on(i,p,["password","guests"],"auth","E_SCHEMA_INVALID",r),f&&_(f,"auth")&&!p&&r.push(v(i,"E_SCHEMA_INVALID",_(f,"auth"),"auth must be an object"));for(let m of["password","guests"]){let y=p&&_(p,m);y&&$n(y)===void 0&&r.push(v(i,"E_SCHEMA_INVALID",y,`auth.${m} must be boolean`))}let g={password:$n(p&&_(p,"password"))??!1,guests:$n(p&&_(p,"guests"))??!1};return{schema:{tables:c,maintains:d,channels:l,auth:g,effects:[]},tables:u,channels:new Set(o.keys()),diagnostics:r}}function Fl(e,n,t,i,r){let s=z(t.arguments[0]);if(!s){r.push(v(e,"E_SCHEMA_INVALID",t,`table ${n} requires an object literal`));return}let o=z(_(s,"columns"));if(!o){r.push(v(e,"E_SCHEMA_INVALID",s,`table ${n} requires columns`));return}on(e,s,["columns","indexes","rules","constraints","retain"],`table ${n}`,"E_SCHEMA_INVALID",r),ji(e,o,`columns for ${n}`,"E_SCHEMA_INVALID",r);let a=Object.assign(Object.create(null),{id:"Id"});for(let E of sn(o)){if(E.name==="id"){r.push(v(e,"E_SCHEMA_ID_RESERVED",E.node,`column ${n}.id is implicit; remove it`));continue}let k=qr(e,E.value,i,r);k!==void 0&&(a[E.name]=k)}let u=Object.fromEntries(Object.entries(a).map(([E,k])=>[E,Wn(k)])),c=Object.assign(Object.create(null),{byId:{columns:["id"],unique:!0}}),l=z(_(s,"indexes"));if(_(s,"indexes")&&!l&&r.push(v(e,"E_SCHEMA_INVALID",_(s,"indexes"),`indexes for ${n} must be an object`)),l){ji(e,l,`indexes for ${n}`,"E_SCHEMA_INVALID",r);for(let E of sn(l)){let k=z(E.value),$=k&&en(_(k,"columns"));if(!k||!$){r.push(v(e,"E_SCHEMA_INVALID",E.node,`index ${n}.${E.name} requires columns`));continue}($.length===0||new Set($).size!==$.length)&&r.push(v(e,"E_SCHEMA_INDEX_COLUMN",E.node,`index ${n}.${E.name} columns must be non-empty and unique`)),$.length>8&&r.push(v(e,"E_SCHEMA_INDEX_COLUMN",E.node,`index ${n}.${E.name} has ${$.length} columns; indexes support at most 8`));let R=r.length;on(e,k,["columns","unique"],`index ${n}.${E.name}`,"E_SCHEMA_INDEX_OPTION",r);let D=_(k,"unique"),J=D?$n(D):!1;if(D&&J===void 0&&r.push(v(e,"E_SCHEMA_INDEX_OPTION",D,`index ${n}.${E.name} unique must be boolean`)),E.name==="byId"){($.length!==1||$[0]!=="id"||J!==!0||r.length!==R)&&r.push(v(e,"E_SCHEMA_ID_RESERVED",E.node,`index ${n}.byId is implicit as { columns: ['id'], unique: true }; remove or match it`));continue}for(let se of $)Object.hasOwn(a,se)?ka(a[se])||r.push(v(e,"E_SCHEMA_INDEX_COLUMN",E.node,`index ${n}.${E.name} column ${se} has non-indexable type ${Vr(a[se])}`)):r.push(v(e,"E_SCHEMA_INDEX_COLUMN",E.node,`index ${n}.${E.name} names unknown column ${se}`));c[E.name]={columns:$,unique:J??!1}}}let f=Object.fromEntries(Object.entries(c).map(([E,k])=>{let $=[...k.columns];return[E,{columns:$,types:$.map(R=>u[R]??P),unique:k.unique??!1}]})),d=i.get(n);d&&(d.columns=u,d.indexes=f);let p=z(_(s,"rules"));_(s,"rules")&&!p&&r.push(Fn(e,_(s,"rules"),`rules for ${n} must be an object`)),p&&on(e,p,["read","insert","update","delete"],`rules for ${n}`,"E_RULE_INVALID",r);let g=Object.create(null);for(let E of["read","insert","update","delete"]){let k=p&&_(p,E);g[E]=k?ht(e,k,i,r,u)??"Deny":"Deny"}let m=_(s,"retain"),y=m&&q(m),b=y&&yt.retentionPolicies.includes(y)?y:"until-revoked";m&&!yt.retentionPolicies.includes(y)&&r.push(v(e,"E_SCHEMA_INVALID",m,`table ${n} retain must be until-revoked or delivered-history`,'retain: "until-revoked"'));let S=ql(e,_(s,"constraints"),a,c,r);return{value:{columns:a,indexes:c,rules:g,constraints:S,retain:b},private:!Hl(g.read),columns:u,indexes:f,readRule:g.read}}function qr(e,n,t,i){let r=N(n),s=r&&B(r);if(!r||!s){let a=Fi(n);i.push(v(e,"E_SCHEMA_COLUMN",a.node,a.message,a.rewrite));return}if(s==="id"&&r.arguments.length===0)return"Id";if(s==="principal"&&r.arguments.length===0)return"Principal";if(s==="int"&&r.arguments.length===0)return"Int";if(s==="bool"&&r.arguments.length===0)return"Bool";if(s==="time"&&r.arguments.length===0)return"Time";if(s==="enum"&&r.arguments.length===1){let a=en(r.arguments[0]);if(Hr(a))return{Enum:{variants:a}}}if(s==="decimal"&&r.arguments.length===1){let a=X(r.arguments[0]);if(Et(a))return{Decimal:{scale:a}}}if(s==="money"&&(r.arguments.length===1||r.arguments.length===2)){let a=q(r.arguments[0]),u=r.arguments[1]?X(r.arguments[1]):2;if(a&&/^[A-Z]{3}$/.test(a)&&Et(u))return{Money:{currency:a,scale:u}}}if(s==="text"){let a=X(r.arguments[0]);if(r.arguments.length===1&&Pn(a))return{Text:{max:a}}}if(s==="bytes"){let a=X(r.arguments[0]);if(r.arguments.length===1&&Pn(a))return{Bytes:{max:a}}}if(s==="image"||s==="video"){let a=X(r.arguments[0]);if(r.arguments.length===1&&Pn(a))return{[s==="image"?"Image":"Video"]:{max:a}}}if(s==="json"){let a=X(r.arguments[0]);if(r.arguments.length===1&&Pn(a))return{Json:{max_bytes:a}}}if(s==="ref"&&r.arguments.length===1){let a=r.arguments[0],u=a&&ae.isIdentifier(h(a))?h(a).text:void 0;if(!u||!t.has(u)){i.push(v(e,"E_SCHEMA_UNKNOWN_TABLE",a??r,`unknown table ${u??a?.getText()??"<missing>"}`));return}return{Ref:{table:t.get(u).name}}}if(s==="optional"&&r.arguments.length===1&&r.arguments[0]){let a=qr(e,r.arguments[0],t,i);return a===void 0?void 0:{Optional:a}}if(s==="list"&&r.arguments.length===2&&r.arguments[0]){let a=qr(e,r.arguments[0],t,i);if(a===void 0)return;let u=z(r.arguments[1]),c=u&&X(_(u,"max"));if(u&&on(e,u,["max"],"list options","E_SCHEMA_INVALID",i),a!==void 0&&Pn(c))return{List:{of:a,max:c}}}let o=Fi(n);i.push(v(e,"E_SCHEMA_COLUMN",o.node,o.message,o.rewrite))}function ht(e,n,t,i,r){let s=N(n),o=s&&B(s);if(!s||!o){i.push(Fn(e,n,"rule must be a rule.* descriptor"));return}if(o==="public"&&s.arguments.length===1&&q(s.arguments[0]))return{Public:{reason:q(s.arguments[0])}};if(o==="allow"&&s.arguments.length===0)return"Allow";if(o==="deny"&&s.arguments.length===0)return"Deny";if(o==="system"&&s.arguments.length===0)return{Eq:["Viewer",{Literal:{Id:yt.systemPrincipalId}}]};if(o==="viewerIs"&&s.arguments.length===1&&q(s.arguments[0]))return{Eq:[{Field:q(s.arguments[0])},"Viewer"]};if((o==="eq"||o==="ne")&&s.arguments.length===2){let a=s.arguments[1]&&ma(s.arguments[1],r),u=s.arguments[0]&&ma(s.arguments[0],r),c=s.arguments[0]&&Li(e,s.arguments[0],i,a),l=s.arguments[1]&&Li(e,s.arguments[1],i,u);return c!==void 0&&l!==void 0?{[o==="eq"?"Eq":"Ne"]:[c,l]}:void 0}if(o==="and"||o==="or"){if(s.arguments.length===0){i.push(Fn(e,n,`rule.${o} requires at least one rule`));return}let a=s.arguments.map(u=>ht(e,u,t,i,r)).filter(u=>u!==void 0);return{[o==="and"?"And":"Or"]:a}}if(o==="not"&&s.arguments.length===1&&s.arguments[0]){let a=ht(e,s.arguments[0],t,i,r);return a===void 0?void 0:{Not:a}}if((o==="exists"||o==="created")&&s.arguments.length===3){let a=s.arguments[0],u=a&&ae.isIdentifier(h(a))?h(a).text:void 0;if(!u||!t.has(u)){i.push(v(e,"E_SCHEMA_UNKNOWN_TABLE",a??s,`unknown table ${u??"<missing>"}`));return}let c=q(s.arguments[1]),l=s.arguments[2]&&h(s.arguments[2]);if(!c||!l||!ae.isArrayLiteralExpression(l)){i.push(Fn(e,s,`rule.${o} requires table, index, and a key array`));return}let f=t.get(u).indexes?.[c]?.types,d=[],p=!1;return l.elements.forEach((g,m)=>{let y=Li(e,g,i,f?.[m]);y===void 0?p=!0:d.push(y)}),p?void 0:{[o==="exists"?"Exists":"Created"]:{table:t.get(u).name,index:c,key:d,provenance:Ql(d)}}}if(o==="exists"&&s.arguments.length===4){i.push(Fn(e,s.arguments[3],"rule.exists visibility is derived from the referenced table policy; remove the options argument"));return}i.push(Fn(e,n,`unsupported rule.${o}`))}function Li(e,n,t,i){let r=h(n);if(ae.isPropertyAccessExpression(r)&&r.expression.getText()==="rule"&&r.name.text==="viewer")return"Viewer";let s=N(r),o=s&&B(s);if(s&&o==="field"&&s.arguments.length===1&&q(s.arguments[0]))return{Field:q(s.arguments[0])};if(s&&(o==="oldField"||o==="nextField")&&s.arguments.length===1&&q(s.arguments[0]))return{[o==="oldField"?"OldField":"NextField"]:q(s.arguments[0])};if(s&&o==="literal"&&s.arguments[0]){let a=i&&ee(i);if(a?.kind==="decimal"){let l=jl(s.arguments[0],a.scale);if(l!==void 0)return{Literal:{Int:l}};if(Ea(s.arguments[0])){t.push(L(e,"E_DECIMAL_SCALE",s.arguments[0],`numeric rule literal must fit Decimal scale ${a.scale} and the safe integer range`,e.source.slice(0,s.arguments[0].getStart(e.sourceFile))+"0"+e.source.slice(s.arguments[0].getEnd())));return}}let u=Bl(s.arguments[0]);if(u){t.push(L(e,"E_DECIMAL_SCALE",u,`fractional literal ${u.text} has no Decimal target in a rule literal`,e.source.slice(0,u.getStart(e.sourceFile))+u.text.replace(".","")+e.source.slice(u.getEnd())));return}let c=rn(s.arguments[0]);if(c!==void 0){let l=Kr(c,i);if(l!==void 0)return{Literal:l};t.push(Fn(e,s.arguments[0],a?.kind==="bytes"?"Bytes rule literal must be exactly { Bytes: canonicalLowercaseBase16 }":"a { Bytes: ... } rule literal requires a Bytes schema position"));return}}t.push(Fn(e,n,"rule term must be field(), oldField(), nextField(), viewer, or literal()"))}function ma(e,n){let t=N(e);if(!t||B(t)!=="field"||t.arguments.length!==1)return;let i=q(t.arguments[0]);return i&&n&&Object.hasOwn(n,i)?n[i]:void 0}function Ea(e){let n=h(e);if(ae.isNumericLiteral(n))return{text:n.text,negative:!1};if(ae.isPrefixUnaryExpression(n)&&n.operator===ae.SyntaxKind.MinusToken&&ae.isNumericLiteral(h(n.operand)))return{text:h(n.operand).text,negative:!0}}function jl(e,n){let t=Ea(e),i=t&&Cn(t.text);if(!i||i.fraction.length>n)return;let r=BigInt(i.whole)*10n**BigInt(n)+BigInt(i.fraction.padEnd(n,"0")||"0"),s=t.negative?-r:r;return s>=-9007199254740991n&&s<=9007199254740991n?Number(s):void 0}function Bl(e){let n,t=i=>{n||(ae.isNumericLiteral(i)&&i.text.includes(".")?n=i:ae.forEachChild(i,t))};return t(e),n}function ql(e,n,t,i,r){let s=n&&h(n);if(!s)return[];if(!ae.isArrayLiteralExpression(s))return r.push(v(e,"E_SCHEMA_INVALID",s,"constraints must be an array")),[];let o=[];for(let a of s.elements){let u=z(a);if(!u){r.push(v(e,"E_SCHEMA_CONSTRAINT",a,"constraint must be an object with exactly one supported form"));continue}if(sn(u).length!==1||u.properties.length!==1){r.push(v(e,"E_SCHEMA_CONSTRAINT",a,"constraint must have exactly one of unique, cap, appendOnly, immutable, text, or finalExistsOnInsert"));continue}let l=q(_(u,"unique"));if(l){Object.hasOwn(i,l)||r.push(v(e,"E_SCHEMA_INDEX_COLUMN",a,`constraint names unknown index ${l}`)),o.push({Unique:{index:l}});continue}let f=z(_(u,"cap"));if(f){on(e,f,["by","max"],"cap constraint","E_SCHEMA_CONSTRAINT",r);let m=en(_(f,"by")),y=X(_(f,"max"));if(m&&m.length>0&&y!==void 0&&Number.isInteger(y)&&y>0){for(let b of m)Object.hasOwn(t,b)||r.push(v(e,"E_SCHEMA_CONSTRAINT",a,`cap constraint names unknown column ${b}`));o.push({Cap:{by:m,max:y}})}else r.push(v(e,"E_SCHEMA_CONSTRAINT",a,"cap constraint requires non-empty by and a positive integer max"));continue}if(_(u,"appendOnly")){$n(_(u,"appendOnly"))===!0?o.push("AppendOnly"):r.push(v(e,"E_SCHEMA_CONSTRAINT",a,"appendOnly constraint must be true"));continue}let d=en(_(u,"immutable"));if(d&&d.length>0){for(let m of d)Object.hasOwn(t,m)||r.push(v(e,"E_SCHEMA_CONSTRAINT",a,`immutable constraint names unknown column ${m}`));o.push({Immutable:{fields:d}});continue}let p=z(_(u,"text"));if(p){on(e,p,["field","min","format"],"text constraint","E_SCHEMA_CONSTRAINT",r);let m=q(_(p,"field")),y=_(p,"min")?X(_(p,"min")):0,b=_(p,"format")?q(_(p,"format")):void 0;if(!m||!(m in t)){r.push(v(e,"E_SCHEMA_CONSTRAINT",a,`text constraint names unknown column ${m??"<missing>"}`));continue}let S=xa(t[m]);if(S===void 0){r.push(v(e,"E_SCHEMA_CONSTRAINT",a,`text constraint names non-text column ${m}`));continue}if(y===void 0||!Number.isInteger(y)||y<0){r.push(v(e,"E_SCHEMA_CONSTRAINT",a,"text constraint min must be a non-negative integer"));continue}if(y>S){r.push(v(e,"E_SCHEMA_CONSTRAINT",a,`text constraint min ${y} exceeds ${m}'s maximum ${S}`));continue}if(b!==void 0&&b!=="handle"&&b!=="url"){r.push(v(e,"E_SCHEMA_CONSTRAINT",a,"text constraint format must be handle or url"));continue}if(y===0&&b===void 0){r.push(v(e,"E_SCHEMA_CONSTRAINT",a,"text constraint must declare min or format"));continue}o.push({Text:{field:m,min:y,...b===void 0?{}:{format:b}}});continue}let g=_(u,"finalExistsOnInsert");if(g){let m=z(g);if(!m){r.push(v(e,"E_SCHEMA_CONSTRAINT",g,"finalExistsOnInsert must be an object with table, index, and key",ga()));continue}on(e,m,["table","index","key"],"finalExistsOnInsert constraint","E_SCHEMA_CONSTRAINT",r);let y=q(_(m,"table")),b=q(_(m,"index")),S=_(m,"key")&&h(_(m,"key"));if(!y||!b||!S||!ae.isArrayLiteralExpression(S)){r.push(v(e,"E_SCHEMA_CONSTRAINT",m,"finalExistsOnInsert requires a static table-name string, index string, and key array",ga()));continue}let E=S.elements.map(k=>Li(e,k,r));if(E.some(k=>k===void 0))continue;o.push({FinalExistsOnInsert:{table:y,index:b,key:E}});continue}r.push(v(e,"E_SCHEMA_CONSTRAINT",a,"unknown or malformed constraint; use unique, cap, appendOnly, immutable, text, or finalExistsOnInsert"))}return o}function xa(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;return n.Text&&typeof n.Text.max=="number"?n.Text.max:"Optional"in n?xa(n.Optional):void 0}function ga(){return'{ finalExistsOnInsert: { table: "memberships", index: "byConversationPrincipalRole", key: [rule.field("id"), rule.field("creatorId"), rule.literal("admin")] } }'}function Vl(e,n,t,i,r){let s=n&&h(n);if(!s)return[];if(!ae.isArrayLiteralExpression(s))return r.push(v(e,"E_SCHEMA_INVALID",s,"maintains must be an array")),[];let o=[],a=new Map,u=[];for(let[l,f]of s.elements.entries()){let d=z(f);if(!d){r.push(v(e,"E_SCHEMA_MAINTAIN",f,"maintain must be an object"));continue}on(e,d,["count","sum","by","into","readable"],"maintain","E_SCHEMA_MAINTAIN",r);let p=q(_(d,"count")),g=z(_(d,"sum"));g&&on(e,g,["source","of"],"sum maintain","E_SCHEMA_MAINTAIN",r);let m=p??(g&&q(_(g,"source"))),y=q(_(d,"into")),b=en(_(d,"by")),S=!!p!=!!g,E=g&&q(_(g,"of"));if(!S||!m||!y||!b||b.length===0||g&&!E){r.push(v(e,"E_SCHEMA_MAINTAIN",f,"maintain requires exactly one count/sum form, non-empty by, and into"));continue}if(!t.has(m)||!t.has(y)){r.push(v(e,"E_SCHEMA_UNKNOWN_TABLE",f,"maintain names an unknown source or target table"));continue}let k=a.get(y);k!==void 0?r.push(v(e,"E_SCHEMA_MAINTAIN",f,`maintain target ${y} is owned by both maintains[${k}] and maintains[${l}]`)):a.set(y,l);let $=ya(i[m])??{},R=ya(i[y])??{},D=new Set;for(let ce of b){if(D.has(ce)){r.push(v(e,"E_SCHEMA_MAINTAIN",f,`maintain.by repeats source column ${ce}`));continue}if(D.add(ce),ce==="id"||ce==="value"){r.push(v(e,"E_SCHEMA_MAINTAIN",f,`maintain.by cannot use reserved source column ${ce}`));continue}ce in $?Ur($[ce])&&r.push(v(e,"E_SCHEMA_ASSET_MAINTAIN",f,`maintain.by cannot use asset-typed source column ${m}.${ce}`)):r.push(v(e,"E_SCHEMA_MAINTAIN",f,`maintain names unknown source column ${m}.${ce}`))}E&&(E in $?Ul($[E])||r.push(v(e,"E_SCHEMA_MAINTAIN",f,`sum maintain source column ${m}.${E} must be Int, Decimal, or Money`)):r.push(v(e,"E_SCHEMA_MAINTAIN",f,`sum maintain names unknown source column ${m}.${E}`))),R.id!=="Id"&&r.push(v(e,"E_SCHEMA_MAINTAIN",f,`maintain target ${y}.id must be the intrinsic Id column`));let J=E?$[E]:"Int";J!==void 0&&!Pi(R.value,J)&&r.push(v(e,"E_SCHEMA_MAINTAIN",f,`maintain target ${y}.value type ${Vr(R.value)} must equal source ${m}.${E??"count"} type ${Vr(J)}`));let se=new Set(["id","value"]);for(let ce of D)ce==="id"||ce==="value"||(se.add(ce),ce in $&&!Pi($[ce],R[ce])&&r.push(v(e,"E_SCHEMA_MAINTAIN",f,`maintain target ${y}.${ce} must exactly match source ${m}.${ce}`)));let he=Object.keys(R).filter(ce=>!se.has(ce));he.length>0&&r.push(v(e,"E_SCHEMA_MAINTAIN",f,`maintain target ${y} has non-aggregate columns ${he.join(", ")}`));let Dt=_(d,"readable");o.push({kind:p?"Count":{Sum:{of:E}},source:m,by:b,target:y,readable:Dt?ht(e,Dt,t,r)??null:null}),u.push({source:m,target:y,item:f})}let c=new Set(u.map(l=>l.source));for(let l of u)c.has(l.target)&&r.push(v(e,"E_SCHEMA_MAINTAIN",l.item,`maintain target ${l.target} cannot also be a maintain source`));return o}function ya(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e.columns;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Ul(e){return e==="Int"||!!e&&typeof e=="object"&&!Array.isArray(e)&&("Decimal"in e||"Money"in e)}function Vr(e){if(typeof e=="string")return e;if(!e||typeof e!="object"||Array.isArray(e))return"missing";let[n,t]=Object.entries(e)[0]??["unknown",void 0];return t===void 0?n:`${n} ${JSON.stringify(t)}`}function ka(e){if(!e||typeof e!="object"||Array.isArray(e))return!0;let n=e;return"Optional"in n?ka(n.Optional):!("List"in n||"Image"in n||"Video"in n)}function Ur(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e;return"Optional"in n?Ur(n.Optional):n.List?Ur(n.List.of):"Image"in n||"Video"in n}function Pi(e,n){if(e===n)return!0;if(!e||!n||typeof e!="object"||typeof n!="object"||Array.isArray(e)!==Array.isArray(n))return!1;if(Array.isArray(e)&&Array.isArray(n))return e.length===n.length&&e.every((o,a)=>Pi(o,n[a]));let t=e,i=n,r=Object.keys(t).sort(),s=Object.keys(i).sort();return r.length===s.length&&r.every((o,a)=>o===s[a]&&Pi(t[o],i[o]))}function Kl(e,n,t,i){let r=z(n.arguments[0]),s=r&&z(_(r,"args"));if(!r||!s){i.push(v(e,"E_SCHEMA_INVALID",n,"channel requires args, publish, subscribe, and ttlMs"));return}on(e,r,["args","publish","subscribe","ttlMs"],"channel","E_SCHEMA_INVALID",i),ji(e,s,"channel args","E_SCHEMA_INVALID",i);let o=Object.create(null),a=Object.create(null);for(let f of sn(s)){let d=Zn(f.value,t);d===void 0?i.push(v(e,"E_SCHEMA_INVALID",f.node,`invalid channel argument descriptor ${f.name}`)):(o[f.name]=d,a[f.name]=Wn(d))}let u=_(r,"publish"),c=_(r,"subscribe"),l=X(_(r,"ttlMs"));if(!u||!c||!Pn(l)){i.push(v(e,"E_SCHEMA_INVALID",r,"channel requires publish, subscribe, and ttlMs"));return}return{args:o,publish:ht(e,u,t,i,a)??"Deny",subscribe:ht(e,c,t,i,a)??"Deny",ttl_ms:l}}function Zn(e,n){let t=N(e);if(t&&B(t)==="list"){let i=z(t.arguments[1]),r=X(i&&_(i,"max")),s=i&&sn(i).every(a=>a.name==="max")&&i.properties.length===sn(i).length,o=t.arguments[0]&&Zn(t.arguments[0],n);return t.arguments.length===2&&o!==void 0&&s&&Pn(r)?{List:{of:o,max:r}}:void 0}if(t&&B(t)==="optional"&&t.arguments[0]){let i=Zn(t.arguments[0],n);return t.arguments.length===1&&i!==void 0?{Optional:i}:void 0}if(t&&B(t)==="enum"){let i=en(t.arguments[0]);return t.arguments.length===1&&Hr(i)?{Enum:{variants:i}}:void 0}if(t&&B(t)==="decimal"){let i=X(t.arguments[0]);return t.arguments.length===1&&Et(i)?{Decimal:{scale:i}}:void 0}if(t&&B(t)==="money"){let i=q(t.arguments[0]),r=t.arguments[1]?X(t.arguments[1]):2;return(t.arguments.length===1||t.arguments.length===2)&&i&&/^[A-Z]{3}$/.test(i)&&Et(r)?{Money:{currency:i,scale:r}}:void 0}if(!(!t||!wa(e)))switch(B(t)){case"cursor":return"Cursor";case"id":return"Id";case"principal":return"Principal";case"ref":{if(!n)return"Id";let i=t.arguments[0]&&ye(t.arguments[0]),r=i&&n.get(i);return r?{Ref:{table:r.name}}:void 0}case"int":return"Int";case"bool":return"Bool";case"time":return"Time";case"text":return{Text:{max:X(t.arguments[0])}};case"bytes":return{Bytes:{max:X(t.arguments[0])}};case"image":return{Image:{max:X(t.arguments[0])}};case"video":return{Video:{max:X(t.arguments[0])}};case"json":return{Json:{max_bytes:X(t.arguments[0])}};default:return}}function Sa(e){let n=N(e);if(!n)return;let t=B(n)==="list"&&z(n.arguments[1]),i=t&&X(_(t,"max"));return typeof i=="number"?{List:{max:i}}:"Scalar"}function wa(e){let n=N(e),t=n&&B(n);if(!n||!t)return!1;if(["cursor","id","principal","int","bool","time"].includes(t))return n.arguments.length===0;if(["text","bytes","image","video","json"].includes(t))return n.arguments.length===1&&Pn(X(n.arguments[0]));if(t==="ref")return n.arguments.length===1;if(t==="optional")return n.arguments.length===1&&!!n.arguments[0]&&wa(n.arguments[0]);if(t==="enum"){let i=en(n.arguments[0]);return n.arguments.length===1&&Hr(i)}if(t==="decimal")return n.arguments.length===1&&Et(X(n.arguments[0]));if(t==="money"){let i=q(n.arguments[0]),r=n.arguments[1]?X(n.arguments[1]):2;return(n.arguments.length===1||n.arguments.length===2)&&!!i&&/^[A-Z]{3}$/.test(i)&&Et(r)}return t==="list"?Zn(e)!==void 0:!1}function ba(e,n,t,i,r){let s=z(_(n,t));if(!s){i.size>0&&r.push(v(e,"E_SCHEMA_INVALID",n,`schema() must list its ${t}`));return}let o=new Set;for(let a of sn(s)){let u=h(a.value),c=ae.isIdentifier(u)?u.text:void 0;!c||!i.has(c)?r.push(v(e,"E_SCHEMA_UNKNOWN_TABLE",a.node,`${t} entry ${a.name} is not a named schema export`)):a.name!==c?r.push(v(e,"E_SCHEMA_INVALID",a.node,`${t} entry ${a.name} must use its export name ${c}`)):o.add(c)}for(let[a,u]of i)o.has(a)||r.push(v(e,"E_SCHEMA_INVALID",u,`${t} omits exported ${a}`))}function Kr(e,n){if(n?.kind==="optional"&&e===null)return"Null";let t=n&&ee(n);if(t?.kind==="bytes"){if(!e||typeof e!="object"||Array.isArray(e))return;let s=Object.entries(e);return s.length===1&&s[0][0]==="Bytes"&&typeof s[0][1]=="string"&&/^(?:[0-9a-f]{2})*$/.test(s[0][1])?{Bytes:s[0][1]}:void 0}if(e===null)return"Null";if(typeof e=="boolean")return{Bool:e};if(typeof e=="number")return{Int:e};if(typeof e=="string")return{String:e};if(Array.isArray(e)){let s=t?.kind==="list"?t.of:t?.kind==="json"?t:void 0,o=e.map(a=>Kr(a,s));return o.every(a=>a!==void 0)?{Array:o}:void 0}if(e&&typeof e=="object"&&Object.keys(e).length===1&&typeof e.Bytes=="string"&&/^(?:[0-9a-f]{2})*$/.test(e.Bytes))return t?.kind==="json"?{Map:{Bytes:{String:e.Bytes}}}:void 0;let i=t?.kind==="json"?t:void 0,r=Object.entries(e).map(([s,o])=>[s,Kr(o,i)]);return r.every(s=>s[1]!==void 0)?{Map:Object.fromEntries(r)}:void 0}function Ql(e){return e.some(n=>typeof n=="object"&&n!==null&&["Field","OldField","NextField"].some(t=>t in n))?"Shape":e.some(n=>n==="Viewer")?"Viewer":e.every(n=>typeof n=="object"&&n!==null&&"Literal"in n)?"Const":"Computed"}function Hl(e){return typeof e=="object"&&e!==null&&"Public"in e}function Et(e){return e!==void 0&&Number.isInteger(e)&&e>=0&&e<=12}function Hr(e){return!!e?.length&&e.every(n=>n.length>0)&&new Set(e).size===e.length}function Fi(e){let n=N(e),t=n&&B(n);if(n&&(t==="optional"||t==="list")&&n.arguments[0]&&Zn(n.arguments[0])===void 0)return Fi(n.arguments[0]);let i=n?.expression.getText()??"t.text",r=o=>{let a=i.lastIndexOf(".");return`${a>=0?i.slice(0,a+1):"t."}${o}`};if(t==="decimal"){let o=ha(X(n.arguments[0]));return{node:e,message:"t.decimal(scale) requires an integer scale from 0 through 12",rewrite:`${i}(${o})`}}if(t==="money"){let o=q(n.arguments[0]),a=o&&/^[A-Za-z]{3}$/.test(o)?o.toUpperCase():"USD",u=n.arguments[1]?`, ${ha(X(n.arguments[1]))}`:"";return{node:e,message:"t.money(currency, scale?) requires an uppercase ISO-4217-shaped three-letter currency and a scale from 0 through 12",rewrite:`${i}(${JSON.stringify(a)}${u})`}}if(t==="enum"){let o=[...new Set((en(n.arguments[0])??[]).filter(a=>a.length>0))];return o.length===0&&o.push("value"),{node:e,message:"t.enum(variants) requires at least one unique, non-empty string variant",rewrite:`${i}(${JSON.stringify(o)})`}}let s={id:`${i}()`,principal:`${i}()`,int:`${i}()`,bool:`${i}()`,time:`${i}()`,text:`${i}(100)`,bytes:`${i}(100)`,image:`${i}(5000000)`,video:`${i}(50000000)`,json:`${i}(1000)`,ref:`${i}(table)`,optional:`${i}(${r("text")}(100))`,list:`${i}(${r("text")}(100), { max: 10 })`};return{node:e,message:t?`t.${t} arguments do not form a valid descriptor`:"column type must be a t.* descriptor",rewrite:s[t??""]??`${r("text")}(100)`}}function $a(e){let n=N(e);if(!(!n||!zl(n)))return Fi(e)}function zl(e){let n=B(e);if(!n||!["id","principal","text","bytes","image","video","int","bool","time","ref","json","optional","list","enum","decimal","money"].includes(n)||!ae.isPropertyAccessExpression(e.expression))return;let t=e.expression.expression.getText();if(t==="t"||t.endsWith(".t"))return n;for(let i of e.getSourceFile().statements){if(!ae.isImportDeclaration(i)||!ae.isStringLiteral(i.moduleSpecifier)||i.moduleSpecifier.text!=="snapback2")continue;let r=i.importClause?.namedBindings;if(r&&ae.isNamedImports(r)&&r.elements.some(s=>(s.propertyName?.text??s.name.text)==="t"&&s.name.text===t))return n}}function ha(e){return e===void 0||!Number.isFinite(e)?2:Math.max(0,Math.min(12,Math.trunc(e)))}function Pn(e){return e!==void 0&&Number.isInteger(e)&&e>0&&e<=4294967295}function ji(e,n,t,i,r){sn(n).length!==n.properties.length&&r.push(v(e,i,n,`${t} uses an unsupported spread, method, or computed property`))}function on(e,n,t,i,r,s){ji(e,n,i,r,s);for(let o of sn(n))t.includes(o.name)||s.push(v(e,r,o.node,`${i} has unknown option ${o.name}; use ${t.join(", ")}`))}function v(e,n,t,i,r){let s=r??(n==="E_SCHEMA_ID_RESERVED"?"columns: {}":n==="E_SCHEMA_CONSTRAINT"?"{ appendOnly: true }":n==="E_SCHEMA_INDEX_OPTION"?"indexes: {}":n==="E_SCHEMA_MAINTAIN"||n==="E_SCHEMA_ASSET_MAINTAIN"?"maintains: []":Wl(t));return L(e,n,t,i,s)}function Fn(e,n,t){return L(e,"E_RULE_INVALID",n,t,"rule.deny()")}function Wl(e){let n=e;for(;n;){if(ae.isVariableDeclaration(n)&&ae.isIdentifier(n.name)){let t=n.initializer&&N(n.initializer),i=t&&B(t),r=t?.expression.getText()??i;if(i==="channel"){let s=r?.endsWith(".channel")?r.slice(0,-7):"";return`export const ${n.name.text} = ${r}({ args: {}, publish: ${s}rule.allow(), subscribe: ${s}rule.allow(), ttlMs: 4000 });`}if(i==="table")return`export const ${n.name.text.startsWith("_")?"rows":n.name.text} = ${r}({ columns: {} });`}if(ae.isExportAssignment(n))return`export default ${N(n.expression)?.expression.getText()??"schema"}({ tables: {} });`;n=n.parent}return"export default schema({ tables: {} });"}import Re from"typescript";function Aa(e){let n=e.parameters[0]?.name;if(!n||!Re.isObjectBindingPattern(n))return;let t=new Map;for(let i of n.elements){if(!Re.isIdentifier(i.name))continue;let r=i.propertyName?H(i.propertyName):i.name.text;if(r!=="args"&&r!=="ctx")continue;let s=t.get(r)??[];s.push(i),t.set(r,s)}for(let[i,r]of t)if(r.length>1)return{property:i,elements:r}}function Ta(e,n,t){let i=n.parameters[0],r=n.body;if(!i||!Re.isObjectBindingPattern(i.name)||!r)return e.source;let s=t.elements.at(-1),o=s.name.text,a=new Set(t.elements),u=`{ ${i.name.elements.filter(d=>!a.has(d)||d===s).map(d=>d.getText(e.sourceFile)).join(", ")} }`,c=t.elements.slice(0,-1).map(d=>d.name.text).filter(d=>d!==o).map(d=>`const ${d} = ${o};`).join(" "),l=[{start:i.name.getStart(e.sourceFile),end:i.name.getEnd(),text:u}];if(Re.isBlock(r)){let d=r.getStart(e.sourceFile)+1;l.push({start:d,end:d,text:` ${c}`})}else l.push({start:r.getStart(e.sourceFile),end:r.getEnd(),text:`{ ${c} return ${r.getText(e.sourceFile)}; }`});let f=e.source;for(let d of l.sort((p,g)=>g.start-p.start))f=`${f.slice(0,d.start)}${d.text}${f.slice(d.end)}`;return f}function zr(e){let n=e.parameters[0]?.name;return n&&Re.isObjectBindingPattern(n)?n.elements.find(t=>!Re.isIdentifier(t.name)):void 0}function Wr(e,n){let t=n.parameters[0],i=n.body;if(!t||!Re.isObjectBindingPattern(t.name)||!i)return e.source;let r=new Set;we(n,l=>{Re.isIdentifier(l)&&r.add(l.text)});let s=new Map,o=[];for(let l of t.name.elements){if(Re.isIdentifier(l.name))continue;let f=l.propertyName?H(l.propertyName):void 0,d=f==="args"?"packed":`${f??"composite"}Packed`,p=d;for(let m=2;r.has(p);m+=1)p=`${d}${m}`;r.add(p),s.set(l,p);let g=l.initializer?`(${p} ?? ${l.initializer.getText(e.sourceFile)})`:p;Na(l.name,g,e.sourceFile,o)}let a=[];for(let[l,f]of s){let d=l.propertyName?l.propertyName.getText(e.sourceFile):f,p=l.initializer?` = ${l.initializer.getText(e.sourceFile)}`:"";a.push({start:l.getStart(e.sourceFile),end:l.getEnd(),text:`${d}: ${f}${p}`})}let u=o.map(l=>`const ${l};`).join(" ");if(Re.isBlock(i)){let l=i.getStart(e.sourceFile)+1;a.push({start:l,end:l,text:` ${u}`})}else a.push({start:i.getStart(e.sourceFile),end:i.getEnd(),text:`{ ${u} return ${i.getText(e.sourceFile)}; }`});let c=e.source;for(let l of a.sort((f,d)=>d.start-f.start))c=`${c.slice(0,l.start)}${l.text}${c.slice(l.end)}`;return c}function Na(e,n,t,i){if(Re.isIdentifier(e)){i.push(`${e.text} = ${n}`);return}e.elements.forEach((r,s)=>{if(!Re.isBindingElement(r))return;if(r.dotDotDotToken){for(let u of _a(r.name))i.push(`${u} = __snapback2_rewrite_rest_binding_explicitly__()`);return}let o=Re.isObjectBindingPattern(e)?Jl(n,r.propertyName,r.name,t):`${n}[${s}]`;if(!o)return;let a=r.initializer?`(${o} ?? ${r.initializer.getText(t)})`:o;Na(r.name,a,t,i)})}function Jl(e,n,t,i){return n?Re.isIdentifier(n)?`${e}.${n.text}`:Re.isComputedPropertyName(n)?`${e}[${n.expression.getText(i)}]`:`${e}[${n.getText(i)}]`:Re.isIdentifier(t)?`${e}.${t.text}`:void 0}function _a(e){return Re.isIdentifier(e)?[e.text]:e.elements.flatMap(n=>Re.isBindingElement(n)?_a(n.name):[])}import Tn from"typescript";function Oa(e,n,t,i){let r=new Map(i.tables??[]),s=new Map(i.effects??[]),o=new Map;for(let a of e.statements){if(Tn.isFunctionDeclaration(a)&&a.name){o.set(a.name.text,a);continue}if(Tn.isVariableStatement(a))for(let u of a.declarationList.declarations){if(!Tn.isIdentifier(u.name)||!u.initializer)continue;let c=u.name.text,l=N(u.initializer),f=l&&tn(l,e),d=l&&Tn.isIdentifier(l.expression)&&["privateTable","maintained"].includes(l.expression.text)?l.expression.text:void 0,p=f??d;if(!l||!p){(Tn.isArrowFunction(u.initializer)||Tn.isFunctionExpression(u.initializer))&&o.set(c,u.initializer);continue}if(p==="table"||p==="privateTable"||p==="maintained"){let g=bn(l.arguments[0])??c,m=p==="maintained"&&Tn.isIdentifier(l.arguments[1])?l.arguments[1].text:void 0;r.set(c,{name:g,private:p==="privateTable",maintainedFrom:m})}else p==="effect"?s.has(c)||s.set(c,c):(Tn.isArrowFunction(u.initializer)||Tn.isFunctionExpression(u.initializer))&&o.set(c,u.initializer)}}return{sourceFile:e,source:n,fileName:t,tables:r,effects:s,helpers:o}}import Jr from"typescript";function Bi(e,n,t){let i=new Set,r=[];return n.forEach(({name:s,call:o})=>{let a=e.filter((u,c)=>{let l=u.site.match(/:(\d+):(\d+)$/);if(!l)return!1;let f=t.sourceFile.getPositionOfLineAndCharacter(Number(l[1])-1,Number(l[2])-1);return f<o.getStart(t.sourceFile)||f>o.getEnd()?!1:(i.add(c),!0)});r.push(...En(a,20,`refusals in operation ${s}`))}),e.forEach((s,o)=>{i.has(o)||r.push(s)}),r}function Ca(e){let n=new Set(["query","mutation","effect","channel","table","schema","seed","emit"]);for(let t of e.statements){if(Jr.isFunctionDeclaration(t)&&t.name&&n.has(t.name.text))return{name:t.name.text,node:t};if(Jr.isVariableStatement(t)){for(let i of t.declarationList.declarations)if(Jr.isIdentifier(i.name)&&n.has(i.name.text))return{name:i.name.text,node:i}}}}function Ia(e,n,t){!n||!t.startsWith("E_AUTH_")||w(e,"E_OP_RESERVED",n,`application refusal code ${t} uses the reserved E_AUTH_* namespace`,K(e.source,n,'"ACCESS_DENIED"'))}function Gr(e){return typeof e=="object"}function Gl(e){if(typeof e=="string")return[e,void 0];let n=Object.entries(e)[0];return n?[n[0],n[1]]:["",void 0]}function qi(e,n){if("Variable"in e)return n.get(e.Variable);if("Scan"in e&&e.Scan.opaque_cursor)return e.Scan.merge_site??e.Scan.site;if("Builtin"in e){let[t,i]=Gl(e.Builtin.builtin);if(t==="DedupeById")return i?.site;if(["Slice","Sort"].includes(t))return e.Builtin.args[0]&&qi(e.Builtin.args[0],n)}}function Yl(e,n){if("Page"in e&&e.Page.opaque_cursor)return e.Page.merge_site??e.Page.site;if("DerivedArray"in e)return qi(e.DerivedArray.value,n)}function Xl(e){return e.flatMap(n=>Gr(n)&&"Push"in n?[n.Push.target]:[])}function Zl(e){let n=new Map,t=[],i=!1,r=s=>s.some(o=>Gr(o)&&("Return"in o||"If"in o&&(r(o.If.then_body)||r(o.If.else_body))||"For"in o&&r(o.For.body)));for(let s of e.body)if(Gr(s))if("Const"in s||"Let"in s||"Assign"in s){let o="Const"in s?s.Const:"Let"in s?s.Let:s.Assign;n.set(o.name,qi(o.value,n))}else if("For"in s){r(s.For.body)&&(i=!0);let o=Yl(s.For.domain,n),a=Xl(s.For.body);o&&a.length===1&&n.set(a[0],o)}else"If"in s?(r(s.If.then_body)||r(s.If.else_body))&&(i=!0):"Return"in s&&t.push(qi(s.Return,n));return!i&&t.length===1?t[0]:void 0}function Ma(e){let n=e.kind==="Query"?Zl(e):void 0;return n?{...e,result_page_site:n}:e}function xt(e,n){if(n instanceof hn)e.push(n.diagnostic);else throw n}function va(e,n="input.ts",t,i={}){let r=T.createSourceFile(n,e,T.ScriptTarget.ES2022,!0),s=Oa(r,e,n,i),o=Wo(s,Number.MAX_SAFE_INTEGER),a=[];if(t!==void 0){let f=Fr(e,n,t);for(let d of f){let p=d.file&&d.start!==void 0?ot(d.file,d.start):r,g=vi(p,n),m=e.replace(/\bschema\s+\([^\n:]+\):/g,"schema:");o.push(L(s,g.code,p,oa(d),m))}}let u=0,c=[];for(let f of r.statements)if(!(!T.isVariableStatement(f)||!Pe(f)))for(let d of f.declarationList.declarations){if(!d.initializer)continue;let p=N(d.initializer),g=p&&tn(p,r);if(g==="effect"){u+=1;continue}if(!p||g!=="query"&&g!=="mutation")continue;u+=1;let m=i.operationPrefix?`${i.operationPrefix}.${T.isIdentifier(d.name)?d.name.text:"operation"}`:T.isIdentifier(d.name)?d.name.text:"operation";a.push({name:m,call:p});let y=p.arguments[1],b=y&&ge(y)?Aa(y):void 0;if(b&&y&&ge(y)){o.push(L(s,"E_OPAQUE",b.elements[1],`handler property ${b.property} is destructured more than once; bind it once and alias locally`,Ta(s,y,b)));continue}let S=y&&ge(y)?zr(y):void 0;if(S&&y&&ge(y)){o.push(L(s,"E_OPAQUE",S,"nested handler destructuring is not lowerable; bind each operation composite to an identifier and access its fields explicitly",Wr(s,y)));continue}let E=ta(s,p);if(o.push(...E.diagnostics),!E.analysisLimitReached&&T.isIdentifier(d.name))try{c.push(ed(s,m,d.name.text,g,p,E,o))}catch(k){xt(o,k)}}if(u===0){let f=Ca(r);o.push(L(s,"E_OP_NONE",f?.node??r,f?`module exports no query/mutation/effect; local declaration ${f.name} shadows the Snapback constructor`:"module exports no query/mutation/effect","export const operation = query({}, ({ args }) => args);"))}let l=Bi(o,a,s);return l.length>0?{ok:!1,diagnostics:En(l,50,"refusals in this module")}:{ok:!0,programs:c}}function ed(e,n,t,i,r,s,o=[]){let a=r.arguments[0],u=r.arguments[1];(!a||!T.isObjectLiteralExpression(a)||!u||!ge(u))&&w(e,"E_OPAQUE",r,"query/mutation requires an argument object and inline handler");let c=zr(u);c&&w(e,"E_OPAQUE",c,"nested handler destructuring is not lowerable; bind each operation composite to an identifier and access its fields explicitly",Wr(e,u));let l=Object.create(null),f=mn(a);f.invalidSpread&&w(e,"E_ARGS_SPREAD",f.invalidSpread,"argument object spread is not a module-level constant object; spell out every argument field",Gs(e.source,f.invalidSpread)),f.invalidProperty&&w(e,"E_ARGS_TYPE",f.invalidProperty,"argument members must use name: descriptor syntax");for(let b of f.entries){let S=b.name,E=Zn(b.value,e.tables),k=E===void 0?$a(b.value):void 0;k&&w(e,"E_ARGS_DESCRIPTOR",k.node,`invalid argument descriptor ${S}; ${k.message}`,k.rewrite);let $=E??Sa(b.value);$||w(e,"E_ARGS_TYPE",b.node,`invalid argument descriptor ${S}`),l[S]=$}let d=new Map;for(let[b,S]of Object.entries(l)){let E={provenance:"Arg",operationArgument:b};typeof S!="string"&&"List"in S&&(E.collectionIdentity={},Je(E,{max:S.List.max,boundSource:`arg ${b} max`,elementOrigins:[{binding:{provenance:"Arg",operationArgument:b},candidate:b}]})),d.set(b,E)}let p=ro(u),g=to(u);p.args&&d.set(p.args,{provenance:Object.keys(l).length===0?"Const":"Arg",operationComposite:"args",objectFields:Object.keys(l)}),p.ctx&&d.set(p.ctx,{provenance:"Viewer",operationComposite:"ctx",objectFields:["viewer"]}),p.db&&d.set(p.db,{provenance:"Const",operationComposite:"db"});let m={...e,programName:n,siteBase:`${lo(e.fileName)}.${t}`,kind:i==="query"?"Query":"Mutation",args:l,variables:d,substitutions:new Map,helperStack:[],mutableBindings:gi(u),deferredCollectionMutations:new Set,collectionAliasSites:g.aliases,collectionEscapeSites:g.escapes,accessOrdinal:{value:0},temp:{value:0},literalValues:s?.literalValues??new Map,expressionTypes:s?.expressionTypes??new Map,literalContext:"operation",diagnostics:o,recursion:{depth:0,active:new Map}},y;if(T.isBlock(u.body))y=Ui(u.body.statements,m);else if(Hs(u.body,b=>Oe(b,"db",m)))y=Vi(u.body,m);else{let b=W(u.body,m,`${n}.result`);y=[...b.statements,{Return:b.expression}]}return Ma({name:n,kind:m.kind,args:l,read_time_granularity_ms:m.kind==="Query"&&JSON.stringify(y).includes('"Input":"ReadTime"')?1:null,body:y})}function Ui(e,n){let t=[];for(let i of e)try{t.push(...Ra(i,n))}catch(r){xt(n.diagnostics,r)}return t}function Ra(e,n){if(T.isVariableStatement(e)){let t=[];for(let i of e.declarationList.declarations)try{if(i.initializer||w(n,"E_OPAQUE",i,"destructuring declarations are not yet lowerable"),T.isArrayBindingPattern(i.name)){let S=N(i.initializer);(!S||!T.isIdentifier(S.expression)||S.expression.text!=="orderedPair"||i.name.elements.length!==2||S.arguments.length!==2)&&w(n,"E_OPAQUE",i,"array destructuring is admitted only for orderedPair");let E=i.name.elements.find(J=>T.isBindingElement(J)&&J.initializer);E&&w(n,"E_OPAQUE",E,"orderedPair destructuring defaults have authored runtime semantics; normalize each input before orderedPair");let k=i.name.elements.map(J=>T.isBindingElement(J)&&T.isIdentifier(J.name)?J.name:void 0);(!k[0]||!k[1])&&w(n,"E_OPAQUE",i.name,"orderedPair bindings must be identifiers");let $=S.arguments.map(J=>W(J,n));t.push(...$.flatMap(J=>J.statements));let R=$.map((J,se)=>{let he=G(n,`ordered${se}`);return t.push({Let:{name:he,value:J.expression}}),{Variable:he}});t.push({Let:{name:k[0].text,value:{Builtin:{builtin:"Min",args:R}}}}),t.push({Let:{name:k[1].text,value:{Builtin:{builtin:"Max",args:R}}}});let D=qt(mo(S.arguments,n),i.initializer,n);for(let J of k)n.variables.set(J.text,{...D});continue}T.isIdentifier(i.name)||w(n,"E_OPAQUE",i.name,"binding pattern is unsupported");let r=i.name.text,s=W(i.initializer,n,`${n.programName}.${r}`),o=On(i.initializer),a=(e.declarationList.flags&T.NodeFlags.Const)!==0,u=!n.mutableBindings.has(i.name),c="Variable"in s.expression?n.variables.get(s.expression.Variable):void 0,l=c?.rowCollection===!0||cn(i.initializer,n),f=u?Qe(i.initializer,n)??(l?Sn(i.initializer,n):void 0):void 0,d=lt(i.initializer,n),p=qt(d,i.initializer,n),g=Ze(n),m=Ut(i.initializer,n),y=wo(i.initializer,n,m.max,m.boundSource);y.elementOrigins===void 0&&c?.elementOrigins!==void 0&&(y.elementOrigins=c.elementOrigins);let b=Je({...p,...o||y.max!==void 0||y.elementOrigins!==void 0?{collectionIdentity:{}}:{},collectionDeclaration:i.name,locallyCreatedCollection:io(i.initializer),...o?{collection:o}:{},...f?{objectFields:f}:{},...u?{identityExpression:s.expression}:{},immutableOrigin:{expression:i.initializer,environment:g},...Hn(i.initializer,n)?{rowBinding:!0}:{},...l?{rowCollection:!0}:{},...Ws(i.initializer,S=>Oe(S,"db",n))?{nullableRead:!0}:{}},y);n.variables.set(r,b),t.push(...s.statements),t.push(a&&!o?{Const:{name:r,value:s.expression}}:{Let:{name:r,value:s.expression}})}catch(r){xt(n.diagnostics,r)}return t}if(T.isExpressionStatement(e))return Vi(e.expression,n);if(T.isReturnStatement(e)){if(!e.expression)return[{Return:re(null)}];let t=W(e.expression,n,`${n.programName}.result`);return[...t.statements,{Return:t.expression}]}if(T.isIfStatement(e)){let t=W(e.expression,n),i=Qt(n),r=Qt(n),s=i.environment,o=Pt(e.expression);o&&s.variables.has(o)&&(s.variables.get(o).nullableRead=!1);let a=Yr(e.thenStatement,s),u=e.elseStatement?Yr(e.elseStatement,r.environment):[];return wr(n,[i,r],e),[...t.statements,{If:{condition:t.expression,then_body:a,else_body:u}}]}if(T.isForOfStatement(e)){(!T.isVariableDeclarationList(e.initializer)||e.initializer.declarations.length!==1||!T.isIdentifier(e.initializer.declarations[0].name))&&w(n,"E_OPAQUE",e.initializer,"for-of binding must be one identifier");let t=e.initializer.declarations[0].name.text,i=Sr(n),{statements:r,domain:s,bindingInfo:o}=_i(e.expression,i,t,W);i.variables.set(t,o);let a=Ti(s),u="DerivedArray"in s&&"Variable"in s.DerivedArray.value?i.variables.get(s.DerivedArray.value.Variable)?.collectionIdentity:void 0,c=Vo(e,i,a,u,Yr);return[...r,{For:{binding:t,domain:s,body:c}}]}if(e.kind===T.SyntaxKind.BreakStatement)return["Break"];if(e.kind===T.SyntaxKind.ContinueStatement)return["Continue"];if(T.isBlock(e))return Ui(e.statements,Sr(n));if(T.isEmptyStatement(e))return[];w(n,"E_OPAQUE",e,`statement ${T.SyntaxKind[e.kind]} is outside the subset`)}function Yr(e,n){if(T.isBlock(e))return Ui(e.statements,n);try{return Ra(e,n)}catch(t){return xt(n.diagnostics,t),[]}}function Vi(e,n){if(T.isCallExpression(e)){if(tn(e,n.sourceFile)==="emit"){n.kind==="Query"&&w(n,"E_EMIT_IN_QUERY",e,"emit is available only in mutations");let t=e.arguments[0],i=e.arguments[1];(!t||!i)&&w(n,"E_EFFECT_UNKNOWN",e,"emit requires an imported effect and a JSON payload");let r=ye(t),s=r&&n.effects.get(r);s||w(n,"E_EFFECT_UNKNOWN",t,`effect ${t.getText(n.sourceFile)} is not declared in this project`),Jn(n);let o=W(i,n,`${n.programName}.emit`);return[...o.statements,{Emit:{effect:s,payload:o.expression}}]}if(T.isPropertyAccessExpression(e.expression)){let t=e.expression.expression,i=e.expression.name.text;if(T.isIdentifier(t)&&n.variables.has(t.text)&&i==="push")return e.arguments.length===0&&w(n,"E_OPAQUE",e,"push requires at least one value"),yi(t,e,n),e.arguments.flatMap(r=>{let s=n.variables.get(t.text);wi(s,r,n,Si(s,t.text,n),bi);let o=W(r,n,`${n.programName}.${t.text}`);return[...o.statements,{Push:{target:t.text,value:o.expression}}]});if(T.isIdentifier(t)&&n.variables.get(t.text)?.collection==="Map"&&i==="set"){yi(t,e,n);let r=e.arguments[0],s=e.arguments[1];(!r||!s)&&w(n,"E_OPAQUE",e,"Map.set requires key and value"),wn(r,n,"Map keys");let o=W(r,n),a=W(s,n),u=n.variables.get(t.text),c=u.max,l=Si(u,t.text,n);return wi(u,s,n,l,bi),u.max===void 0&&c!==void 0&&(u.max=c+l,u.boundSource=`${s.getText(n.sourceFile)} Map.set bound`),[...Ar(t.text,o,a,u.max??0,u.boundSource,n)]}if(T.isIdentifier(t)&&n.variables.get(t.text)?.collection==="Set"&&i==="add"){yi(t,e,n);let r=e.arguments[0];r||w(n,"E_OPAQUE",e,"Set.add requires a value"),wn(r,n,"Set values");let s=W(r,n),o=G(n,"setValue"),a=Ci(t,{Variable:o},n,"SetHas"),u=n.variables.get(t.text),c=u.max,l=Si(u,t.text,n);return wi(u,r,n,l,bi),u.max===void 0&&c!==void 0&&(u.max=c+l,u.boundSource=`${r.getText(n.sourceFile)} Set.add bound`),[...s.statements,{Let:{name:o,value:s.expression}},...a.statements,{If:{condition:{Unary:{op:"Not",value:a.expression}},then_body:[{Push:{target:t.text,value:{Variable:o}}}],else_body:[]}}]}if(at(t,r=>Oe(r,"db",n)))return nd(i,e,n)}}if((T.isPostfixUnaryExpression(e)||T.isPrefixUnaryExpression(e))&&(e.operator===T.SyntaxKind.PlusPlusToken||e.operator===T.SyntaxKind.MinusMinusToken)&&T.isIdentifier(e.operand))return[{Assign:{name:e.operand.text,value:{Binary:{op:e.operator===T.SyntaxKind.PlusPlusToken?"Add":"Sub",left:{Variable:e.operand.text},right:re(1)}}}}];if(T.isBinaryExpression(e)&&e.operatorToken.kind===T.SyntaxKind.EqualsToken&&T.isIdentifier(e.left)){let t=n.variables.get(e.left.text);uo(t,e.right,n);let i=Ut(e.right,n);return t&&$o(t,e.right,n,i.max,i.boundSource),[{Assign:{name:e.left.text,value:U(e.right,n)}}]}if(T.isConditionalExpression(e)){let t=W(e.condition,n),i=Qt(n),r=Qt(n),s=Vi(e.whenTrue,i.environment),o=Vi(e.whenFalse,r.environment);return wr(n,[i,r],e),[...t.statements,{If:{condition:t.expression,then_body:s,else_body:o}}]}w(n,"E_OPAQUE",e,"expression statement does not lower to a data operation")}function nd(e,n,t){if(e==="require"||e==="assert"){let s=n.arguments[0];s||w(t,"E_OPAQUE",n,`${e} requires a condition`);let o=n.arguments[1],a=bn(o)??(e==="assert"?"ASSERTION_FAILED":"REQUIRE_FAILED");Ia(t,o,a);let u=W(s,t),c=Pt(s);if(c){let l=t.variables.get(c);l&&(l.nullableRead=!1)}return[...u.statements,{Require:{condition:u.expression,code:a}}]}let i=n.arguments[0],r=i&&vn(i,t).table;if(r||w(t,"E_OPAQUE",n,`${e} requires a static table`),e==="insert"){let s=n.arguments[1];s||w(t,"E_OPAQUE",n,"insert requires a row"),Jn(t);let o=W(s,t);return[...o.statements,{Insert:{table:r,row:o.expression}}]}if(e==="delete"){let s=n.arguments[1];return s||w(t,"E_OPAQUE",n,"delete requires a key"),Jn(t),[{Delete:{table:r,key:U(s,t)}}]}if(e==="update"||e==="upsert"){let s=n.arguments[1],o=n.arguments[2];if((!s||!o)&&w(t,"E_OPAQUE",n,`${e} requires key and row/patch`),T.isArrayLiteralExpression(h(s))&&w(t,"E_OPAQUE",s,`${e} with a composite identity cannot be represented by S1's scalar write key`),ge(o))return td(e,i,r,s,o,t);e==="update"&&Qe(o,t)?.includes("id")&&w(t,"E_SCHEMA_ID_RESERVED",o,"update patches cannot contain id","remove id from the update patch"),Jn(t);let a=U(s,t),u=Fo(o,t);return e==="upsert"&&Nr(a,u,c=>t.variables.get(c)?.identityExpression)===!1&&w(t,"E_SCHEMA_ID_RESERVED",o,"upsert key and row id must be one identity","const rowId = ctx.newId(); db.upsert(table, rowId, { ...row, id: rowId })"),e==="update"?[{Update:{table:r,key:a,patch:u}}]:[{Upsert:{table:r,key:a,row:u}}]}w(t,"E_OPAQUE",n,`db.${e} is not part of the S1 IR`)}function td(e,n,t,i,r,s){(r.parameters.length!==1||!T.isIdentifier(r.parameters[0].name))&&w(s,"E_OPAQUE",r,"write callback must have one identifier parameter"),T.isBlock(r.body)&&!s.source.startsWith("// GENERATED by the Snapback 2 Quarry front end from ")&&w(s,"E_OPAQUE",r.body,"write callback body must be an expression");let o=T.isBlock(r.body)?Da(r.body,s):r.body;e==="update"&&Qe(o,s)?.includes("id")&&w(s,"E_SCHEMA_ID_RESERVED",o,"update patches cannot contain id","remove id from the update patch");let a=vn(n,s);e==="upsert"&&a.index!=="byId"&&w(s,"E_OPAQUE",n,"upsert callbacks require a table primary key");let u=pt(s);Jn(s);let l=Oi(i,s)[0],f=Ni(l)?G(s,`${jt(t)}WriteKey`):void 0,d=f?{Variable:f}:l,p=G(s,`${jt(t)}Current`),g=Ze(s);g.substitutions.set(r.parameters[0].name.text,{expression:Ft(s.sourceFile,p),environment:g}),g.variables.set(p,{provenance:"Shape",rowBinding:!0});let m=T.isBlock(r.body)?id(r.body,g,`${s.programName}.${jt(t)}Write`):W(r.body,g,`${s.programName}.${jt(t)}Write`);e==="upsert"&&Nr(d,m.expression,b=>s.variables.get(b)?.identityExpression)===!1&&w(s,"E_SCHEMA_ID_RESERVED",o,"upsert key and row id must be one identity","bind the identity once and use that binding for both the upsert key and row id");let y=f?[{Let:{name:f,value:l}}]:[];return y.push({Let:{name:p,value:{Get:{site:u,table:a.table,index:a.index,key:[d],provenance:ct(i,s)}}}}),e==="update"&&y.push({Require:{condition:{Binary:{op:"Ne",left:{Variable:p},right:re(null)}},code:"NOT_FOUND"}}),y.push(...m.statements),e==="update"?y.push({Update:{table:t,key:d,patch:m.expression}}):y.push({Upsert:{table:t,key:d,row:m.expression}}),y}function Da(e,n){let t=e.statements.at(-1);return(!t||!T.isReturnStatement(t)||!t.expression)&&w(n,"E_OPAQUE",e,"write callback block must end with a returned patch expression"),t.expression}function id(e,n,t){let i=Da(e,n),r=Ui(e.statements.slice(0,-1),n),s=W(i,n,t);return{statements:[...r,...s.statements],expression:s.expression}}function W(e,n,t){let i=h(e);if(T.isConditionalExpression(i)){let r=G(n,"conditional"),s=W(i.condition,n),o=W(i.whenTrue,Ze(n),t),a=W(i.whenFalse,Ze(n),t);return{statements:[...s.statements,{Let:{name:r,value:re(null)}},{If:{condition:s.expression,then_body:[...o.statements,{Assign:{name:r,value:o.expression}}],else_body:[...a.statements,{Assign:{name:r,value:a.expression}}]}}],expression:{Variable:r}}}if(T.isBinaryExpression(i)){let r=pi(i.operatorToken.kind),s=i.operatorToken.kind===T.SyntaxKind.QuestionQuestionToken;if(!r&&!s)return{statements:[],expression:U(i,n,t)};let o=W(i.left,n,t),a=W(i.right,n,t);if(r==="And"||r==="Or"||s){let u=G(n,"logicalLeft"),c=G(n,"logicalResult"),l=s?{Binary:{op:"Eq",left:{Variable:u},right:re(null)}}:r==="And"?{Variable:u}:{Unary:{op:"Not",value:{Variable:u}}};return{statements:[...o.statements,{Let:{name:u,value:o.expression}},{Let:{name:c,value:{Variable:u}}},{If:{condition:l,then_body:[...a.statements,{Assign:{name:c,value:a.expression}}],else_body:[]}}],expression:{Variable:c}}}return{statements:[...o.statements,...a.statements],expression:{Binary:{op:r,left:o.expression,right:a.expression}}}}if(T.isPrefixUnaryExpression(i)&&(i.operator===T.SyntaxKind.ExclamationToken||i.operator===T.SyntaxKind.MinusToken)){let r=W(i.operand,n,t);return{statements:r.statements,expression:{Unary:{op:i.operator===T.SyntaxKind.ExclamationToken?"Not":"Neg",value:r.expression}}}}if(T.isPropertyAccessExpression(i)){if(T.isIdentifier(i.expression)&&n.variables.get(i.expression.text)?.operationComposite)return{statements:[],expression:U(i,n,t)};if(T.isPropertyAccessChain(i))return Po(i,n,W,t);let r=W(i.expression,n,t);return{statements:r.statements,expression:xr(i,r.expression,n)}}if(T.isObjectLiteralExpression(i)){let r=[],s=Object.create(null);for(let o of i.properties)try{if(T.isSpreadAssignment(o)){let c=xi(o.expression,n);c&&ki(o,n,c);let l=Qe(o.expression,n);if(!l){let p=o.expression.getText(n.sourceFile);w(n,"E_OPAQUE",o,"object spread requires a statically known object shape; spell its fields explicitly",K(n.source,o,`field: ${p}.field`))}if(T.isIdentifier(o.expression)&&n.variables.get(o.expression.text)?.operationComposite==="args"){for(let p of l)s[p]={Variable:p};continue}let f=W(o.expression,n,t);if(r.push(...f.statements),"Object"in f.expression){for(let[p,g]of Object.entries(f.expression.Object))s[p]=g;continue}let d=f.expression;if(l.length>1&&!("Variable"in d)){let p=G(n,"spread");r.push({Let:{name:p,value:d}}),d={Variable:p}}for(let p of l)s[p]={Field:{base:d,name:p}};continue}if(T.isShorthandPropertyAssignment(o)){s[o.name.text]=U(o.name,n);continue}T.isPropertyAssignment(o)||w(n,"E_OPAQUE",o,"object member is outside the subset");let a=H(o.name);a||w(n,"E_OPAQUE",o.name,"computed object keys are unsupported");let u=W(o.initializer,n,t?`${t}.${a}`:a);r.push(...u.statements),s[a]=u.expression}catch(a){xt(n.diagnostics,a)}return{statements:r,expression:{Object:s}}}if(T.isArrayLiteralExpression(i)){let r=[],s=[],o=[],a=()=>{o.length&&s.push({Array:o}),o=[]};for(let u of i.elements)try{if(T.isSpreadElement(u)){if(Ae(u.expression,n)===void 0){let l=u.expression.getText(n.sourceFile);w(n,"E_OPAQUE",u,"array spread requires a statically bounded array; spell its elements explicitly",K(n.source,u,`${l}[0], ${l}[1]`))}a();let c=W(u.expression,n,t);r.push(...c.statements),s.push(c.expression)}else{let c=W(u,n,t);r.push(...c.statements),o.push(c.expression)}}catch(c){xt(n.diagnostics,c)}return a(),{statements:r,expression:s.length===0?{Array:[]}:s.length===1?s[0]:La(s)}}if(T.isNewExpression(i))return Ko(i,n,W,t);if(T.isCallExpression(i)){let r=di(i.expression);if(r&&T.isPropertyAccessExpression(i.expression)&&T.isIdentifier(i.expression.expression)){let s=i.expression.expression,o=n.variables.get(s.text),a=i.arguments[0];if(o?.collection==="Map"&&(r==="get"||r==="has")&&a){wn(a,n,"Map keys");let u=W(a,n,t),c=Ci(s,u.expression,n,r==="get"?"MapGet":"MapHas");return{statements:[...u.statements,...c.statements],expression:c.expression}}if(o?.collection==="Set"&&r==="has"&&a){wn(a,n,"Set values");let u=W(a,n,t),c=Ci(s,u.expression,n,"SetHas");return{statements:[...u.statements,...c.statements],expression:c.expression}}}if(r==="slice"&&T.isPropertyAccessExpression(i.expression)){i.arguments.length!==2&&w(n,"E_OPAQUE",i,"slice requires start and end arguments");let s=W(i.expression.expression,n,t),o=i.arguments.map(a=>W(a,n));return{statements:[...s.statements,...o.flatMap(a=>a.statements)],expression:{Builtin:{builtin:"Slice",args:[s.expression,...o.map(a=>a.expression)]}}}}if(r==="sort"&&T.isPropertyAccessExpression(i.expression)){let s=W(i.expression.expression,n,t);return{statements:s.statements,expression:kr(s.expression,i.arguments[0],n)}}if(r&&["map","flatMap","filter","reduce","some"].includes(r)&&T.isPropertyAccessExpression(i.expression))return Bo(r,i.expression.expression,i,n,W,t);if(r==="require"&&T.isPropertyAccessExpression(i.expression)){let s=W(i.expression.expression,n,t),o=G(n,"required");return{statements:[...s.statements,{Let:{name:o,value:s.expression}},{Require:{condition:{Binary:{op:"Ne",left:{Variable:o},right:re(null)}},code:"REQUIRED_ROW_MISSING"}}],expression:{Variable:o}}}if(zs(i,s=>Oe(s,"db",n))){let s=i.arguments[0],o=i.arguments[1];(!s||!o)&&w(n,"E_OPAQUE",i,"insert requires table and row"),Jn(n);let a=W(o,n,t),u=G(n,"insertRow");return{statements:[...a.statements,{Let:{name:u,value:a.expression}},{Insert:{table:vn(s,n).table,row:{Variable:u}}}],expression:{Variable:u}}}if(T.isIdentifier(i.expression)&&i.expression.text==="mergeByIndex")return Uo(i,n,t,W,U);if(T.isIdentifier(i.expression)&&["top","mergeByTime","intersectById"].includes(i.expression.text))return rd(i.expression.text,i,n,t)}return{statements:[],expression:U(i,n,t)}}function La(e){return e.slice(1).reduce((n,t)=>({Builtin:{builtin:"Concat",args:[n,t]}}),e[0])}function rd(e,n,t,i){let r=e==="top"?n.arguments[1]:n.arguments[0];r||w(t,"E_OPAQUE",n,`${e} requires a bounded collection`);let s=W(r,t,i),o=s.expression;if(e==="mergeByTime"){let u="Array"in o?o.Array:[o];o=u.length===0?{Array:[]}:La(u)}e!=="intersectById"&&(o={Builtin:{builtin:{Sort:{keys:[{field:"at",order:"Desc"}]}},args:[o]}});let a=e==="top"?n.arguments[0]:n.arguments[1];return a&&(o={Builtin:{builtin:"Slice",args:[o,re(0),U(a,t)]}}),{statements:s.statements,expression:o}}import F from"typescript";function Fa(e){let n=new Map;for(let t of e)for(let i of t.sourceFile.statements)if(!(!F.isVariableStatement(i)||!Pe(i)))for(let r of i.declarationList.declarations){if(!F.isIdentifier(r.name)||!r.initializer)continue;let s=N(r.initializer);if(s&&B(s)==="effect"){let o=`${t.moduleName}.${r.name.text}`;n.set(o,{module:t,exportName:r.name.text,call:s})}}return n}function ja(e,n){let t=new Map;for(let[i,r]of n)r.module.moduleName===e.moduleName&&t.set(r.exportName,i);for(let i of e.sourceFile.statements){if(!F.isImportDeclaration(i)||!F.isStringLiteral(i.moduleSpecifier)||!i.moduleSpecifier.text.startsWith("."))continue;let r=Xr(i.moduleSpecifier.text),s=i.importClause?.namedBindings;if(s){if(F.isNamespaceImport(s)){for(let[o,a]of n)a.module.moduleName===r&&t.set(`${s.name.text}.${a.exportName}`,o);continue}for(let o of s.elements){let a=o.propertyName?.text??o.name.text,u=`${r}.${a}`;n.has(u)&&t.set(o.name.text,u)}}}return t}function Ba(e,n){let t=[],i=[];for(let[r,s]of[...e].sort(([o],[a])=>o.localeCompare(a))){let o=sd(r,s.module,s.call,n,i);o&&t.push(o)}return{effects:t,diagnostics:i}}function sd(e,n,t,i,r){let s=z(t.arguments[0]),o=s&&en(_(s,"grants"));if(!s||!o||o.length===0||o.some(m=>!pd(m))){r.push(kt(n,"E_EFFECT_GRANT",t,"grants must be a non-empty list of https:// or http://127.0.0.1 origins"));return}let a=_(s,"run"),u=a&&h(a);if(!u||!F.isArrowFunction(u)&&!F.isFunctionExpression(u)){r.push(kt(n,"E_EFFECT_CLOSURE",s,"effect run must be an arrow or function expression"));return}let c=od(n,u);c&&r.push(c);let l=null,f=_(s,"then");if(f){let m=dd(n,f,i);!m||m.kind!=="mutation"||!fd(m.call)?r.push(kt(n,"E_EFFECT_THEN_ARGS",f,"then must name a mutation with outboxId, effect, and result arguments matching run's result")):l=m.name}if(c||f&&l===null)return;let d=F.transpileModule(`(${u.getText(n.sourceFile)})`,{compilerOptions:{target:F.ScriptTarget.ES2020,module:F.ModuleKind.None,removeComments:!0}}).outputText.trim().replace(/;$/,""),p=[...zt(n.sourceFile)].map(([m,y])=>`const ${m} = ${JSON.stringify(y)};`).join(" "),g=p?`(() => { ${p} return ${d}; })()`:d;return{name:e,grants:o,source:g,then:l}}function od(e,n){let t=[...n.parameters,n.body],i;for(let c of t)we(c,l=>{i||(F.isCallExpression(l)&&F.isIdentifier(l.expression)&&l.expression.text==="require"&&(i=l),F.isCallExpression(l)&&l.expression.kind===F.SyntaxKind.ImportKeyword&&(i=l))});if(i)return kt(e,"E_EFFECT_IMPORT",i,"effect run cannot import or require modules");let r=[];for(let c of n.parameters)Yt(c.name,n,r);we(n.body,c=>{if(F.isVariableDeclaration(c)&&Yt(c.name,Pa(c,n),r),qa(c)){for(let l of c.parameters)Yt(l.name,c,r);(F.isFunctionDeclaration(c)||F.isFunctionExpression(c))&&c.name&&r.push({name:c.name.text,owner:F.isFunctionDeclaration(c)?Pa(c,n):c})}F.isCatchClause(c)&&c.variableDeclaration&&Yt(c.variableDeclaration.name,c,r)});let s=zt(e.sourceFile),o=new Set([...s.keys(),"fetch","meta","console","JSON","Math","Date","URL","TextEncoder","TextDecoder","btoa","atob","setTimeout","Promise","Error","crypto","undefined","NaN","Infinity"]),a;for(let c of t)we(c,l=>{a||!F.isIdentifier(l)||!cd(l)||!o.has(l.text)&&!r.some(f=>f.name===l.text&&ud(l,f.owner))&&(a=l)});if(!a)return;let u=ad(e.sourceFile,a.text,s);return u?kt(e,"E_EFFECT_CLOSURE",u,`effect JSON constant spread ${u.expression.getText(e.sourceFile)} is not statically JSON`):kt(e,"E_EFFECT_CLOSURE",a,`effect run closes over non-JSON value ${a.text}`)}function qa(e){return F.isFunctionDeclaration(e)||F.isFunctionExpression(e)||F.isArrowFunction(e)||F.isMethodDeclaration(e)}function ad(e,n,t){let i;for(let r of e.statements){if(!F.isVariableStatement(r)||!(r.declarationList.flags&F.NodeFlags.Const))continue;let s=r.declarationList.declarations.find(o=>F.isIdentifier(o.name)&&o.name.text===n);s?.initializer&&we(s.initializer,o=>{if(i||!F.isSpreadAssignment(o))return;let a=rn(o.expression,t);(!a||typeof a!="object"||Array.isArray(a))&&(i=o)})}return i}function Yt(e,n,t){if(F.isIdentifier(e))t.push({name:e.text,owner:n});else for(let i of e.elements)F.isBindingElement(i)&&Yt(i.name,n,t)}function Pa(e,n){let t=e.parent;for(;t&&t!==n;){if(F.isBlock(t)||qa(t)||F.isCatchClause(t))return t;t=t.parent}return n}function ud(e,n){let t=e;for(;t;){if(t===n)return!0;t=t.parent}return!1}function cd(e){let n=e.parent;return F.isPropertyAccessExpression(n)&&n.name===e||F.isPropertyAssignment(n)&&n.name===e&&n.initializer!==e||F.isMethodDeclaration(n)&&n.name===e||F.isPropertySignature(n)||F.isTypeReferenceNode(n)||F.isTypeParameterDeclaration(n)||F.isBindingElement(n)&&(n.name===e||n.propertyName===e)||F.isVariableDeclaration(n)&&n.name===e||F.isParameter(n)&&n.name===e||F.isFunctionDeclaration(n)&&n.name===e?!1:!ld(e)}function ld(e){let n=e.parent;for(;n;){if(F.isTypeNode(n))return!0;if(F.isExpression(n)||F.isStatement(n))return!1;n=n.parent}return!1}function dd(e,n,t){let i=ye(n);if(!i)return;let r=i.includes(".")?void 0:t.get(`${e.moduleName}.${i}`);if(r)return r;for(let s of e.sourceFile.statements){if(!F.isImportDeclaration(s)||!F.isStringLiteral(s.moduleSpecifier)||!s.moduleSpecifier.text.startsWith("."))continue;let o=s.importClause?.namedBindings;if(!o)continue;if(F.isNamespaceImport(o)){let c=`${o.name.text}.`;if(i.startsWith(c)&&!i.slice(c.length).includes("."))return t.get(`${Xr(s.moduleSpecifier.text)}.${i.slice(c.length)}`);continue}let a=o.elements.find(c=>c.name.text===i);if(!a)continue;let u=a.propertyName?.text??a.name.text;return t.get(`${Xr(s.moduleSpecifier.text)}.${u}`)}}function fd(e){let n=z(e.arguments[0]);if(!n)return!1;let t=mn(n).entries;if(t.map(r=>r.name).sort().join(",")!=="effect,outboxId,result")return!1;let i=new Map(t.map(r=>[r.name,B(r.value)]));return["id","text"].includes(i.get("outboxId")??"")&&i.get("effect")==="text"&&i.has("result")}function pd(e){try{let n=new URL(e);return n.origin!==e||n.username||n.password?!1:n.protocol==="https:"||n.protocol==="http:"&&n.hostname==="127.0.0.1"}catch{return!1}}function Xr(e){return(e.split("/").filter(Boolean).at(-1)??e).replace(/\.[cm]?[jt]s$/,"")}function kt(e,n,t,i){let r=t;for(;r&&!F.isVariableDeclaration(r);)r=r.parent;let s=r&&F.isVariableDeclaration(r)&&F.isIdentifier(r.name)?r.name.text:"effectName",a=(r&&F.isVariableDeclaration(r)&&r.initializer?N(r.initializer):void 0)?.expression.getText(e.sourceFile)??"effect",u=`export const ${s} = ${a}({ grants: ["https://api.example.com"], run: async (_payload: null) => null });`;return L(e,n,t,i,u)}import{basename as Nn}from"node:path";var xe=class extends Error{diagnostic;constructor(n,t,i="E_QUARRY_UNKNOWN",r="fix the named Quarry declaration",s=md(i)){let o=n.expandedFrom,a=o?`${t} (from a named shape used at ${o.file}:${o.line}:${o.col})`:t;super(a),this.diagnostic={...n,code:i,message:a,rewrite:r,guide:s}}};function I(e,n,t){throw new xe(e,n,"E_QUARRY_UNKNOWN",t??"fix the named Quarry declaration")}function Y(e,n,t="fix this Quarry declaration and rerun snapback2 check"){throw new xe(e,n,"E_QUARRY_SYNTAX",t)}function Ge(e,n,t){throw new xe(e,`${n} is not part of the Snapback 2 platform`,"E_QUARRY_UNSUPPORTED",t)}function Va(e,n,t){throw new xe(e,n,"E_QUARRY_AMBIGUOUS",t)}function Q(e,n,t){throw new xe(e,n,"E_QUARRY_TYPE",t)}function Xt(e,n){throw new xe(e,n,"E_QUARRY_RETAIN","retain until-revoked -- alternatively: retain delivered-history")}function md(e){return e==="E_QUARRY_SYNTAX"?"quarry/grammar":e==="E_QUARRY_AMBIGUOUS"?"quarry/indexes":e==="E_QUARRY_UNSUPPORTED"?"quarry/refusals":e==="E_QUARRY_PLACEMENT"?"quarry/projects":e==="E_QUARRY_TYPE"?"quarry/types":e==="E_QUARRY_RETAIN"?"quarry/grammar":"quarry/names"}function Ha(e){let n=new Map;for(let t of e)for(let i of t.tables){n.has(i.name)&&I(i.site,`duplicate table ${i.name}`);let r=new Map;for(let u of i.columns)u.name==="id"&&I(u.site,`table ${i.name} gets id implicitly; remove the id column`),r.has(u.name)&&I(u.site,`duplicate column ${i.name}.${u.name}`),r.set(u.name,u.type);let s=[{name:"byId",columns:["id"],unique:!0,site:i.site},...i.indexes],o=new Set;for(let u of s){o.has(u.name)&&I(u.site,`duplicate index ${i.name}.${u.name}; name one ordering explicitly`),o.add(u.name),u.columns.length===0&&I(u.site,`index ${i.name}.${u.name} needs at least one column`),new Set(u.columns).size!==u.columns.length&&I(u.site,`index ${i.name}.${u.name} repeats a column`);for(let c of u.columns)c!=="id"&&!r.has(c)&&I(u.site,`index ${i.name}.${u.name} names unknown column ${c}`)}let a=new Set;for(let u of i.rules)a.has(u.effect)&&I(u.site,`duplicate ${u.effect} rule on ${i.name}`),a.add(u.effect);n.set(i.name,{declaration:i,columns:r,indexes:s})}for(let t of n.values())for(let i of t.declaration.columns)Zr(i.type,n,i.site);for(let t of e){let i=new Set;for(let s of t.channels)i.has(s.name)&&I(s.site,`duplicate channel ${s.name}`),i.add(s.name),Ua(s.args,n);let r=new Set;for(let s of t.programs)r.has(s.name)&&I(s.site,`duplicate operation ${s.name}`),r.add(s.name),Ua(s.args,n)}return n}function Ua(e,n){let t=new Set;for(let i of e)t.has(i.name)&&I(i.site,`duplicate argument ${i.name}`),t.add(i.name),Zr(i.type,n,i.site)}function Zr(e,n,t){e.kind==="text"&&e.max<1&&I(t,"text bounds must be positive"),e.kind==="text"&&e.min!==void 0&&(e.min<0||e.min>e.max)&&I(t,"text minimum must be between zero and its maximum"),(e.kind==="json"||e.kind==="bytes")&&e.max<1&&I(t,`${e.kind} bounds must be positive`),(e.kind==="image"||e.kind==="video")&&(!Number.isInteger(e.max)||e.max<1||e.max>4294967295)&&I(t,`${e.kind} byte bounds must be positive integers no larger than 4294967295`),e.kind==="enum"&&(e.variants.length===0||new Set(e.variants).size!==e.variants.length)&&I(t,"enum variants must be non-empty and unique"),e.kind==="ref"&&!n.has(e.table)&&I(t,`reference names unknown table ${e.table}`),e.kind==="list"&&(e.max<1&&I(t,"list bounds must be positive"),Zr(e.item,n,t))}function za(e){return[...e.values()].map(n=>n.declaration)}function et(e,n,t,i,r,s,o){let a=e.get(n);if(a||I(o,`unknown table ${n}`),r){let f=a.indexes.find(d=>d.name===r);return f||I(o,`table ${n} has no index ${r}`),Ka(a.declaration,f,t,i,s,o),f}let u=t.some(f=>f.column!==void 0);u&&t.some(f=>f.column===void 0)&&I(o,"an index key cannot mix named and positional parts");let c=a.indexes.filter(f=>i==="range"&&f.name==="byId"||i==="point"&&(!f.unique||f.columns.length!==t.length)||(i==="range"||i==="exists")&&f.columns.length<t.length?!1:u?t.every((d,p)=>f.columns[p]===d.column):t.every((d,p)=>Ga(s(d.value),Ja(a.declaration,f.columns[p]))));if(i==="point"&&t.length===1&&!u){let f=s(t[0].value);f?.kind==="ref"&&(f.table===n||f.table==="")?c=c.filter(d=>d.name==="byId"):c.some(d=>d.name!=="byId")&&(c=c.filter(d=>d.name!=="byId"))}if(i!=="range"){let f=c.filter(d=>d.columns.length===t.length);f.length>0&&(c=f)}if(c.length===0){let f=t.map(d=>d.column??"?").join(", ");I(o,`no ${i==="point"?"unique index":"ordering"} on ${n} matches [${f}]; name the columns/index or add one`)}c.length>1&&Va(o,`index selection for ${n}[...] is ambiguous (${c.map(f=>f.name).join(", ")}); name it with by <index>`,`${n}[${t.map(f=>f.value.kind==="name"?f.value.name:"key").join(", ")}] by ${c[0].name}`);let l=c[0];return Ka(a.declaration,l,t,i,s,o),l}function Ka(e,n,t,i,r,s){i==="point"&&(!n.unique||n.columns.length!==t.length)&&I(s,`${e.name}.${n.name} is not a complete unique key`),(i==="range"||i==="exists")&&n.columns.length<t.length&&I(s,`${e.name}.${n.name} has no ${t.length}-column prefix`);for(let[o,a]of t.entries()){let u=n.columns[o];a.column&&u!==a.column&&I(a.site,`${e.name}.${n.name} expects ${u} at key position ${o+1}`);let c=r(a.value),l=Ja(e,u);l.kind==="int"&&Wa(a.value)&&Q(a.value.site,"int positions take integer literals","use an integer literal for this int index key"),c&&!Ga(c,l)&&I(a.value.site,`${e.name}.${n.name} expects ${Qa(l)} for ${u}, got ${Qa(c)}`)}}function Wa(e){return e.kind==="unary"&&e.op==="-"?Wa(e.value):e.kind==="literal"&&typeof e.value=="number"&&e.numericText?.includes(".")===!0}function Ja(e,n){return n==="id"?{kind:"ref",table:e.name,optional:!1}:e.columns.find(t=>t.name===n)?.type??{kind:"int",optional:!1}}function Ga(e,n){return e?n.kind==="ref"?e.kind==="id"?!0:e.kind==="ref"&&(e.table===""||e.table===n.table):n.kind==="id"?e.kind==="ref"||e.kind==="id":n.kind==="principal"?e.kind==="principal":n.kind==="enum"&&e.kind==="text"?!0:n.kind==="decimal"?e.kind==="decimal"&&e.scale===n.scale:n.kind==="money"?e.kind==="money"&&e.currency===n.currency&&e.scale===n.scale:e.kind===n.kind:!0}function Qa(e){return e.kind==="ref"?`reference to ${e.table}`:e.kind==="list"?"list":e.kind==="decimal"?`decimal ${e.scale}`:e.kind==="money"?`money ${e.currency} ${e.scale}`:e.kind}var es=8;function Xa(e){let n=[];return{documents:e.map(i=>{let r=new Map;for(let a of i.shapes)r.has(a.name)?n.push(new xe(a.site,`duplicate shape ${a.name}`,"E_QUARRY_UNKNOWN",`rename shape ${a.name} or remove this declaration`).diagnostic):r.set(a.name,a);if(n.length>0)return i;let s=new ns(r);for(let a of i.shapes)try{s.instantiate(a.name,a.site,1,[])}catch(u){n.push(Ya(u))}let o=[];for(let a of i.programs)try{o.push({...a,body:a.body.map(u=>s.statement(u))})}catch(u){n.push(Ya(u)),o.push(a)}return{...i,programs:o}}),diagnostics:gd(n)}}var ns=class{constructor(n){this.definitions=n}instantiate(n,t,i,r){let s=this.definitions.get(n);if(!s)throw new xe(t,`unknown shape ${n}`,"E_QUARRY_UNKNOWN",`define shape ${n} = { * } in this operation module`);if(r.includes(n))throw new xe(s.site,`shape cycle ${[...r,n].join(" -> ")} is not supported; shape ${n} was used at ${ts(t)}`,"E_QUARRY_UNSUPPORTED",`remove the recursive ${n} shape use`);if(i>es)throw new xe(s.site,`shape expansion exceeds depth ${es}; shape ${n} was used at ${ts(t)}`,"E_QUARRY_UNSUPPORTED",`inline or split the projection so it expands through at most ${es} named shapes`);return this.fields(s.fields,t,i,[...r,n],!0)}statement(n){if(n.kind==="bind"||n.kind==="expr"||n.kind==="return")return{...n,value:this.expression(n.value)};if(n.kind==="require")return{...n,condition:this.expression(n.condition)};if(n.kind==="emit")return{...n,payload:this.expression(n.payload)};if(n.kind==="if")return{...n,condition:this.expression(n.condition),thenBody:n.thenBody.map(i=>this.statement(i)),elseBody:n.elseBody.map(i=>this.statement(i))};if(n.kind==="for")return{...n,domain:this.expression(n.domain),body:n.body.map(i=>this.statement(i))};let t=this.expression(n.read);return{...n,read:t,someBody:n.someBody.map(i=>this.statement(i)),noneBody:n.noneBody.map(i=>this.statement(i))}}expression(n,t,i=0,r=[]){let s=o=>this.expression(o,t,i,r);if(n.kind==="shapeUse"){let o=t??n.site;return{kind:"shape",base:s(n.base),fields:this.instantiate(n.name,o,i+1,r),authoredName:n.name,site:this.site(n.site,t)}}if(n.kind==="shape"){let o=n.fields.some(a=>a.kind==="namedSpread")?structuredClone(n.fields):n.authoredFields;return{...n,base:s(n.base),fields:this.fields(n.fields,t??n.site,i,r,!!t),...o?{authoredFields:o}:{},site:this.site(n.site,t)}}return n.kind==="unary"||n.kind==="assert"?{...n,value:s(n.value),site:this.site(n.site,t)}:n.kind==="binary"?{...n,left:s(n.left),right:s(n.right),site:this.site(n.site,t)}:n.kind==="member"?{...n,base:s(n.base),site:this.site(n.site,t)}:n.kind==="call"?{...n,args:n.args.map(s),site:this.site(n.site,t)}:n.kind==="array"?{...n,items:n.items.map(s),site:this.site(n.site,t)}:n.kind==="object"?{...n,fields:n.fields.map(o=>({...o,value:o.value&&s(o.value),site:this.site(o.site,t)})),site:this.site(n.site,t)}:n.kind==="read"?{...n,keys:n.keys.map(o=>({...o,value:s(o.value),site:this.site(o.site,t)})),range:n.range&&{...n.range,cursor:n.range.cursor&&s(n.range.cursor),where:n.range.where&&{...n.range.where,predicate:s(n.range.where.predicate),site:this.site(n.range.where.site,t)},site:this.site(n.range.site,t)},site:this.site(n.site,t)}:n.kind==="merge"?{...n,cursor:n.cursor&&s(n.cursor),lanes:n.lanes.map(o=>({...o,prefix:o.prefix.map(s),loop:o.loop&&{...o.loop,domain:s(o.loop.domain)},site:this.site(o.site,t)})),site:this.site(n.site,t)}:n.kind==="exists"||n.kind==="created"?{...n,read:s(n.read),site:this.site(n.site,t)}:n.kind==="aggregate"?{...n,keys:n.keys.map(o=>({...o,value:s(o.value),site:this.site(o.site,t)})),site:this.site(n.site,t)}:n.kind==="walk"?{...n,seed:s(n.seed),site:this.site(n.site,t)}:n.kind==="write"?{...n,keys:n.keys.map(o=>({...o,value:s(o.value),site:this.site(o.site,t)})),fields:n.fields.map(o=>({...o,value:o.value&&s(o.value),site:this.site(o.site,t)})),site:this.site(n.site,t)}:{...n,site:this.site(n.site,t)}}fields(n,t,i,r,s){return n.flatMap(o=>{if(o.kind==="namedSpread")return this.instantiate(o.name,t,i+1,r);let a=this.site(o.site,s?t:void 0);return o.kind==="field"?[{...o,value:this.expression(o.value,s?t:void 0,i,r),site:a}]:[{...o,site:a}]})}site(n,t){return t?{file:n.file,line:n.line,col:n.col,expandedFrom:t.expandedFrom??t}:n}};function Ya(e){if(e instanceof xe)return e.diagnostic;throw e}function ts(e){return`${e.file}:${e.line}:${e.col}`}function gd(e){let n=new Set;return e.filter(t=>{let i=`${ts(t)}\0${t.code}\0${t.message}`;return n.has(i)?!1:(n.add(i),!0)})}var yd=new Set(["<-","->","<=",">=","!=","??"]),bd=new Set(":(),[]{}.?!#+-~*/%=<>"),hd=["until-revoked","delivered-history"];function Za(e,n){let t=[],i=[],r=(u,c)=>i.push({...u,code:"E_QUARRY_SYNTAX",message:c,rewrite:"fix this Quarry line and rerun snapback2 check",guide:"quarry/grammar"}),s=[0],o=0,a=n.replace(/\r\n?/g,`
9
+ `).split(`
10
+ `);for(let u=0;u<a.length;u+=1){let c=a[u],l=u+1;if(/^\s*--/.test(c)||/^\s*$/.test(c))continue;let f=c.match(/^[ \t]*/)?.[0]??"";f.includes(" ")&&r({file:e,line:l,col:1},"tabs are not valid indentation; use spaces");let d=f.length;if(o===0){let g=s.at(-1);if(d>g)s.push(d),t.push(Zt(e,l,1,"indent","<indent>"));else if(d<g){for(;d<s.at(-1);)s.pop(),t.push(Zt(e,l,1,"dedent","<dedent>"));d!==s.at(-1)&&r({file:e,line:l,col:1},"indentation does not match an enclosing block")}}let p=!1;for(;d<c.length;){let g=c[d];if(g===" "||g===" "){d+=1;continue}if(g==="-"&&c[d+1]==="-")break;let m={file:e,line:l,col:d+1},y=c.slice(d,d+2);if(yd.has(y)){t.push({...m,kind:"symbol",value:y}),d+=2,p=!0;continue}if(g==="'"||g==='"'){let b=g,S="";d+=1;let E=!1;for(;d<c.length;){let k=c[d];if(k===b){d+=1,E=!0;break}if(k==="\\"){let $=c[d+1];if($===void 0)break;S+=$==="n"?`
11
+ `:$==="t"?" ":$,d+=2}else S+=k,d+=1}E||r(m,"unterminated string literal"),t.push({...m,kind:"string",value:S}),p=!0;continue}if(/[0-9]/.test(g)){let b=c.slice(d).match(/^\d+(?:\.\d+)?/)[0];t.push({...m,kind:"number",value:b}),d+=b.length,p=!0;continue}if(/[A-Za-z_]/.test(g)){let b=t.at(-1),S=b?.line===l&&b.value==="retain",E=hd.find(R=>c.startsWith(R,d)&&!/[A-Za-z0-9_-]/.test(c[d+R.length]??""));E&&!S&&r(m,`${E} is a retention policy and is valid only after retain`);let $=(S?E:void 0)??c.slice(d).match(/^[A-Za-z_][A-Za-z0-9_]*/)[0];t.push({...m,kind:"word",value:$}),d+=$.length,p=!0;continue}if(bd.has(g)){t.push({...m,kind:"symbol",value:g}),"([{".includes(g)&&(o+=1),")]}".includes(g)&&(o-=1),o<0&&(r(m,`unexpected ${g}`),o=0),d+=1,p=!0;continue}r(m,`unexpected character ${JSON.stringify(g)}`),d+=1}p&&o===0&&t.push(Zt(e,l,c.length+1,"newline","<newline>"))}for(o!==0&&r({file:e,line:a.length,col:1},"unclosed grouping delimiter");s.length>1;)s.pop(),t.push(Zt(e,a.length,1,"dedent","<dedent>"));return t.push(Zt(e,a.length,1,"eof","<eof>")),{tokens:t,diagnostics:i}}function Zt(e,n,t,i,r){return{file:e,line:n,col:t,kind:i,value:r}}function eu(e,n){if(e.kind!=="binary"||e.op!=="!="||e.right.kind!=="literal"||e.right.value!==null)return;let t=e.left;if(t.kind==="name"){let s=n.get(t.name);if(!s)return;let o=s.narrowedType??s.type;"optional"in o&&o.optional?s.narrowedType={...o,optional:!1}:"nullable"in o&&o.nullable&&(s.narrowedType={...o,nullable:!1});return}if(t.kind!=="member"||t.base.kind!=="name")return;let i=n.get(t.base.name),r=i?.narrowedType??i?.type;!i||r?.kind!=="row"||(i.narrowedFields=new Set(i.narrowedFields),i.narrowedFields.add(t.name))}function tu(e,n,t){let i=e.find(u=>u.tables.length>0)?.tables[0]?.site??{file:t,line:1,col:1},r=[Z(os(t),i)];r.push(Z('import { channel, rule, schema, table, t } from "snapback2";',i),"");for(let u of za(n))r.push(...Ed(u,n),"");let s=e.flatMap(u=>u.channels);for(let u of s)r.push(...kd(u,n),"");let o=e.find(u=>u.identity)?.identity??{password:!1,guests:!1},a=e.flatMap(u=>u.maintains);if(r.push(Z("export default schema({",i)),r.push(Z(` auth: { password: ${o.password}, guests: ${o.guests} },`,i)),r.push(Z(` tables: { ${[...n.keys()].join(", ")} },`,i)),a.length>0){r.push(Z(" maintains: [",a[0].site));for(let u of a)r.push(Z(` ${Sd(u,n)},`,u.site));r.push(Z(" ],",a.at(-1).site))}return r.push(Z(` channels: { ${s.map(u=>u.name).join(", ")} },`,i)),r.push(Z("});",i)),`${r.join(`
12
+ `)}
13
+ `}function Ed(e,n){let t=[Z(`export var ${e.name} = table({`,e.site)];t.push(Z(" columns: {",e.site));for(let s of e.columns)t.push(Z(` ${ss(s.name)}: ${ni(s.type)},`,s.site));if(t.push(Z(" },",e.site)),t.push(Z(` retain: ${JSON.stringify(e.retain?.policy??"until-revoked")},`,e.retain?.site??e.site)),e.indexes.length>0){t.push(Z(" indexes: {",e.site));for(let s of e.indexes)t.push(Z(` ${ss(s.name)}: { columns: [${s.columns.map(o=>JSON.stringify(o)).join(", ")}]${s.unique?", unique: true":""} },`,s.site));t.push(Z(" },",e.site))}let i=[];e.public&&i.push(Z(` read: rule.public(${JSON.stringify(e.public.reason)}),`,e.public.site));for(let s of e.rules)s.effect==="read"&&e.public&&I(s.site,`table ${e.name} cannot combine public with an explicit read rule`),i.push(Z(` ${s.effect}: ${iu(s,n,e)},`,s.site));i.length>0&&t.push(Z(" rules: {",e.site),...i,Z(" },",e.site));let r=xd(e,n);return r.length>0&&t.push(Z(" constraints: [",e.site),...r,Z(" ],",e.site)),t.push(Z("});",e.site)),t}function xd(e,n){let t=[];for(let i of e.indexes.filter(r=>r.unique))t.push(Z(` { unique: ${JSON.stringify(i.name)} },`,i.site));for(let i of e.immutable)t.push(Z(` { immutable: [${i.columns.map(r=>JSON.stringify(r)).join(", ")}] },`,i.site));for(let i of e.columns)if(i.type.kind==="text"&&(i.type.min!==void 0||i.type.format)){let r=[`field: ${JSON.stringify(i.name)}`];i.type.min!==void 0&&r.push(`min: ${i.type.min}`),i.type.format&&r.push(`format: ${JSON.stringify(i.type.format)}`),t.push(Z(` { text: { ${r.join(", ")} } },`,i.site))}for(let i of e.finalExists){let r=i.value.read,s={names:new Set,focal:!0,effect:"insert",table:e},o=et(n,r.table,r.keys,"exists",r.index,u=>Qi(u,s),r.site),a=r.keys.map(u=>Ki(u.value,s).code).join(", ");t.push(Z(` { finalExistsOnInsert: { table: ${JSON.stringify(r.table)}, index: ${JSON.stringify(o.name)}, key: [${a}] } },`,i.site))}return t}function kd(e,n){let t={names:new Set(e.args.map(i=>i.name)),args:new Map(e.args.map(i=>[i.name,i.type]))};return[Z(`export const ${e.name} = channel({`,e.site),Z(` args: { ${e.args.map(i=>`${ss(i.name)}: ${ni(i.type)}`).join(", ")} },`,e.site),Z(` publish: ${ei(e.publish,n,t)},`,e.publish.site),Z(` subscribe: ${ei(e.subscribe,n,t)},`,e.subscribe.site),Z(` ttlMs: ${e.ttlSeconds*1e3},`,e.site),Z("});",e.site)]}function Sd(e,n){let t=e.aggregate==="count"?`count: ${JSON.stringify(e.source)}`:`sum: { source: ${JSON.stringify(e.source)}, of: ${JSON.stringify(e.column)} }`,i=e.readable?`, readable: ${iu(e.readable,n,n.get(e.name)?.declaration)}`:"";return`{ ${t}, by: [${e.by.map(r=>JSON.stringify(r)).join(", ")}], into: ${JSON.stringify(e.name)}${i} }`}function iu(e,n,t){let i={names:new Set(e.bindings),focal:e.bindings.length===0,effect:e.effect,table:t};return e.effect==="update"&&e.bindings.length===2&&([i.old,i.next]=e.bindings),ei(e.value,n,i)}function ei(e,n,t){if(e.kind==="name"){if(e.name==="allow")return"rule.allow()";if(e.name==="deny")return"rule.deny()";if(e.name==="system")return"rule.system()";if(e.name==="public")return'rule.public("Quarry public rule")';I(e.site,`rule expression ${e.name} is not allow, deny, public, system, or a supported predicate`)}if(e.kind==="unary"&&e.op==="not")return`rule.not(${ei(e.value,n,t)})`;if(e.kind==="binary"&&(e.op==="and"||e.op==="or"))return`rule.${e.op}(${rs(e,e.op).map(i=>ei(i,n,t)).join(", ")})`;if(e.kind==="binary"&&(e.op==="="||e.op==="!=")){let i=Qi(e.left,t),r=Qi(e.right,t);(i?.kind==="int"&&is(e.right)||r?.kind==="int"&&is(e.left))&&Q(e.site,"int positions take integer literals","use an integer literal in the int comparison"),i&&r&&!wd(i,r)&&!nu(i,e.right)&&!nu(r,e.left)&&I(e.site,`cannot compare nominal ${i.kind} with ${r.kind}; fields compared with viewer must be principal`);let s=Ki(e.left,t),o=Ki(e.right,t);return e.op==="="&&s.kind==="field"&&o.code==="rule.viewer"&&s.method==="field"?`rule.viewerIs(${JSON.stringify(s.field)})`:e.op==="="&&o.kind==="field"&&s.code==="rule.viewer"&&o.method==="field"?`rule.viewerIs(${JSON.stringify(o.field)})`:`rule.${e.op==="="?"eq":"ne"}(${s.code}, ${o.code})`}if(e.kind==="exists"||e.kind==="created"){let i=et(n,e.read.table,e.read.keys,"exists",e.read.index,s=>Qi(s,t),e.site),r=e.read.keys.map(s=>Ki(s.value,t).code).join(", ");return`rule.${e.kind}(${e.read.table}, ${JSON.stringify(i.name)}, [${r}])`}(e.kind==="member"||e.kind==="read")&&I(e.site,"rules cannot follow point reads or nested field chains; use a direct .field or exists/created probe"),e.kind==="binary"&&["<","<=",">",">="].includes(e.op)&&I(e.site,`the platform rule vocabulary has eq/ne but not ${e.op}; move the bounded comparison into a mutation require`),I(e.site,`rule expression cannot be represented by the Snapback 2 platform${t.effect?` for ${t.effect}`:""}`)}function Ki(e,n){if(e.kind==="name"&&e.name==="viewer")return{code:"rule.viewer",kind:"other"};if(e.kind==="literal")return{code:`rule.literal(${$d(e)})`,kind:"other"};if(e.kind==="member"&&e.base.kind==="focal"&&n.focal)return n.table&&e.name!=="id"&&!n.table.columns.some(t=>t.name===e.name)&&I(e.site,`table ${n.table.name} has no rule field ${e.name}`),{code:`rule.field(${JSON.stringify(e.name)})`,kind:"field",field:e.name,method:"field"};if(e.kind==="member"&&e.base.kind==="name"&&n.names.has(e.base.name)){n.table&&e.name!=="id"&&!n.table.columns.some(i=>i.name===e.name)&&I(e.site,`table ${n.table.name} has no rule field ${e.name}`);let t=e.base.name===n.old?"oldField":e.base.name===n.next?"nextField":"field";return{code:`rule.${t}(${JSON.stringify(e.name)})`,kind:"field",field:e.name,method:t}}if(e.kind==="name"&&n.names.has(e.name))return{code:`rule.field(${JSON.stringify(e.name)})`,kind:"field",field:e.name,method:"field"};e.kind==="member"&&I(e.site,"rule terms cannot follow nested field chains; use a direct .field or exists/created probe"),I(e.site,"rule terms may only be viewer, literals, channel arguments, or direct .fields of the ruled row")}function Qi(e,n){if(e.kind==="name"&&e.name==="viewer")return{kind:"principal",optional:!1};if(e.kind==="literal"){if(typeof e.value=="string")return{kind:"text",max:Math.max(1,e.value.length),optional:!1};if(typeof e.value=="number")return{kind:"int",optional:!1};if(typeof e.value=="boolean")return{kind:"bool",optional:!1}}if(e.kind==="member"&&e.base.kind==="focal"&&n.focal)return e.name==="id"&&n.table?{kind:"ref",table:n.table.name,optional:!1}:n.table?.columns.find(t=>t.name===e.name)?.type;if(e.kind==="member"&&e.base.kind==="name"&&n.names.has(e.base.name))return e.name==="id"&&n.table?{kind:"ref",table:n.table.name,optional:!1}:n.table?.columns.find(t=>t.name===e.name)?.type;if(e.kind==="name"&&n.names.has(e.name))return n.args?.get(e.name)}function wd(e,n){return e.kind==="principal"||n.kind==="principal"?e.kind==="principal"&&n.kind==="principal":e.kind==="ref"||e.kind==="id"?n.kind==="ref"||n.kind==="id":n.kind==="ref"||n.kind==="id"?!1:e.kind==="enum"&&n.kind==="text"||e.kind==="text"&&n.kind==="enum"?!0:e.kind==="decimal"||n.kind==="decimal"?e.kind==="decimal"&&n.kind==="decimal"&&e.scale===n.scale:e.kind==="money"||n.kind==="money"?e.kind==="money"&&n.kind==="money"&&e.currency===n.currency&&e.scale===n.scale:e.kind===n.kind}function nu(e,n){return(e.kind==="decimal"||e.kind==="money")&&ru(n)}function ru(e){return e.kind==="literal"&&typeof e.value=="number"||e.kind==="unary"&&e.op==="-"&&ru(e.value)}function is(e){return e.kind==="unary"&&e.op==="-"?is(e.value):e.kind==="literal"&&typeof e.value=="number"&&e.numericText?.includes(".")===!0}function $d(e){return typeof e.value=="number"?e.numericText??JSON.stringify(e.value):JSON.stringify(e.value)}function rs(e,n){return e.kind==="binary"&&e.op===n?[...rs(e.left,n),...rs(e.right,n)]:[e]}function ni(e){let n;return e.kind==="cursor"?n="t.cursor()":e.kind==="text"?n=`t.text(${e.max})`:e.kind==="id"?n="t.id()":e.kind==="principal"?n="t.principal()":e.kind==="int"?n="t.int()":e.kind==="decimal"?n=`t.decimal(${e.scale})`:e.kind==="money"?n=e.explicitScale?`t.money(${JSON.stringify(e.currency)}, ${e.scale})`:`t.money(${JSON.stringify(e.currency)})`:e.kind==="time"?n="t.time()":e.kind==="bool"?n="t.bool()":e.kind==="json"?n=`t.json(${e.max})`:e.kind==="bytes"?n=`t.bytes(${e.max})`:e.kind==="image"?n=`t.image(${e.max})`:e.kind==="video"?n=`t.video(${e.max})`:e.kind==="enum"?n=`t.enum([${e.variants.map(t=>JSON.stringify(t)).join(", ")}])`:e.kind==="ref"?n=`t.ref(${e.table})`:n=`t.list(${ni({...e.item,optional:!1})}, { max: ${e.max} })`,e.optional?`t.optional(${n})`:n}function os(e){return`// GENERATED by the Snapback 2 Quarry front end from ${e}`}function Ad(e,n,t=1){return`// q:${e}:${n}:${t}`}function as(e){return Ad(e.file,e.line,e.col)}function Z(e,n){return`${e} ${as(n)}`}function ss(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}var us=class{lines=[];indent=0;lastSite;constructor(n){this.lastSite=n}raw(n="",t){t&&(this.lastSite=t),this.lines.push(n?`${" ".repeat(this.indent)}${n} ${as(t??this.lastSite)}`:"")}statement(n,t){this.raw(n,t)}nested(n){this.indent+=1,n(),this.indent-=1}},cs=class e{constructor(n,t,i){this.catalog=n;this.program=t;this.effects=i;for(let r of t.args)this.bindings.set(r.name,{code:`args.${r.name}`,type:r.type})}bindings=new Map;focal;inlineComparisons=!1;clone(){let n=new e(this.catalog,this.program,this.effects);n.bindings.clear();for(let[t,i]of this.bindings)n.bindings.set(t,{...i,narrowedFields:i.narrowedFields&&new Set(i.narrowedFields)});return n.focal=this.focal&&{...this.focal},n.inlineComparisons=this.inlineComparisons,n}};function ys(e,n,t,i=[]){let r=e[0]?.site??i[0]?.site??{file:t,line:1,col:1},s=new us(r);s.raw(os(t),r),s.statement('import { deterministicShare, divmod, emit, max, mergeByIndex, mentionTokens, min, mutation, query, range, recurse, t } from "snapback2";',{file:t,line:1,col:1}),n.size>0&&s.statement(`import { ${[...n.keys()].join(", ")} } from "./schema";`,{file:t,line:1,col:1});for(let o of i)s.statement(`import { ${o.name} } from "./${o.module}";`,o.site);s.raw(),s.statement("function orderedPair(left: any, right: any): [any, any] { return [left, right]; }",{file:t,line:1,col:1}),s.raw();for(let o of e)Td(o,n,s,new Set(i.map(a=>a.name))),s.raw();return`${s.lines.join(`
14
+ `).trimEnd()}
15
+ `}function Td(e,n,t,i){let r=new cs(n,e,i),s=e.args.map(o=>`${Tt(o.name)}: ${ni(o.type)}`).join(", ");t.raw(`export const ${e.name} = ${e.kind}({ ${s} }, ({ db, ctx, args }) => {`,e.site),t.nested(()=>St(e.body,r,t,{kind:"return"})),t.statement("});",e.site)}function St(e,n,t,i,r=!1){if(e.length===0){i?.kind==="return"?t.statement("return null;",n.program.site):i?.kind==="assign"&&t.statement(`${i.name} = null;`,n.program.site);return}for(let[s,o]of e.entries()){let a=s===e.length-1;Nd(o,n,t,a?i:void 0,a&&r)}}function Nd(e,n,t,i,r=!1){if(e.kind==="bind"){if(e.names.length>1){(e.names.length!==2||e.value.kind!=="call"||e.value.name!=="sorted"||e.value.args.length!==2)&&I(e.site,"tuple bindings are supported only as (a, b) = sorted(a, b)");let s=ue(e.value.args[0],n,t),o=ue(e.value.args[1],n,t);t.statement(`const [${e.names.join(", ")}] = orderedPair(${s.code}, ${o.code});`,e.site),n.bindings.set(e.names[0],{code:e.names[0],type:s.type}),n.bindings.set(e.names[1],{code:e.names[1],type:o.type})}else{let s=ue(e.value,n,t);s.effectOnly&&I(e.site,"update/upsert/delete do not yield a value; bind a following point read instead");let o=e.names[0];t.statement(`const ${o} = ${s.code};`,e.site),n.bindings.set(o,{code:o,type:s.type})}ti(i,t,e.site);return}if(e.kind==="require"){let s=ue(e.condition,n,t);ri(e.condition,s.type,"require"),t.statement(`db.require(${s.code}, ${JSON.stringify(e.code)});`,e.site),ti(i,t,e.site);return}if(e.kind==="return"){let s=ue(e.value,n,t);t.statement(`return ${s.effectOnly?"null":s.code};`,e.site);return}if(e.kind==="emit"){n.effects.has(e.effect)||I(e.site,`unknown effect ${e.effect}; declare effect ${e.effect} from <module>`);let s=ue(e.payload,n,t);t.statement(`emit(${e.effect}, ${s.code});`,e.site),ti(i,t,e.site);return}if(e.kind==="expr"){let s=ue(e.value,n,t);if(i){let o=s.effectOnly?"null":s.code;if(i.kind==="return")t.statement(`return ${o};`,e.site);else if(e.value.kind==="write"&&e.value.op==="insert"){let a=me("inserted",e.site);t.statement(`const ${a} = ${o};`,e.site),t.statement(`${i.name} = ${a};`,e.site)}else t.statement(`${i.name} = ${o};`,e.site)}else r&&!s.effectOnly?e.value.kind==="write"&&e.value.op==="insert"?t.statement(`${s.code};`,e.site):t.statement(`const ${me("discard",e.site)} = ${s.code};`,e.site):s.effectOnly||((e.value.kind!=="write"||e.value.op!=="insert")&&I(e.site,"a non-final expression must be a write; bind it if its value is needed"),t.statement(`${s.code};`,e.site));return}if(e.kind==="if"){let s=ue(e.condition,n,t);ri(e.condition,s.type,"if"),t.raw(`if (${s.code}) {`,e.site),t.nested(()=>{let o=n.clone();eu(e.condition,o.bindings),St(e.thenBody,o,t,i)}),e.elseBody.length>0?(t.raw("} else {",e.site),t.nested(()=>St(e.elseBody,n.clone(),t,i))):i&&(t.raw("} else {",e.site),t.nested(()=>ti(i,t,e.site))),t.statement("}",e.site);return}if(e.kind==="for"){let s=ue(e.domain,n,t),o=s.type.kind==="page"?{kind:"row",table:s.type.table,nullable:!1}:s.type.kind==="sequence"||s.type.kind==="list"?s.type.item:{kind:"unknown"};s.type.kind!=="page"&&s.type.kind!=="sequence"&&s.type.kind!=="list"&&s.type.kind!=="unknown"&&I(e.domain.site,"for domains must be a page, capped list argument, range, tokens result, or literal list"),t.raw(`for (const ${e.name} of ${s.code}) {`,e.site),t.nested(()=>{let a=n.clone();a.bindings.set(e.name,{code:e.name,type:o}),St(e.body,a,t)}),t.statement("}",e.site),ti(i,t,e.site);return}_d(e,n,t,i)}function _d(e,n,t,i){let r=wt(e.read,n,t),s=me("match",e.site);t.statement(`const ${s} = ${r.code};`,e.site);let o=i===void 0,a=i,u;i?.kind==="return"&&(u=me("matchResult",e.site),t.statement(`let ${u}: any = null;`,e.site),a={kind:"assign",name:u}),t.raw(`if (${s} !== null) {`,e.site),t.nested(()=>{let c=n.clone();c.bindings.set(e.someName,{code:e.someName,type:{kind:"row",table:e.read.table,nullable:!1}}),t.statement(`const ${e.someName} = ${s};`,e.site),St(e.someBody,c,t,a,o)}),t.raw("} else {",e.site),t.nested(()=>St(e.noneBody,n.clone(),t,a,o)),t.statement("}",e.site),u&&t.statement(`return ${u};`,e.site)}function ti(e,n,t){e&&(e.kind==="return"?n.statement("return null;",t):n.statement(`${e.name} = null;`,t))}function ue(e,n,t){if(e.kind==="literal")return{code:Vd(e),type:bu(e)};if(e.kind==="name")return Od(e.name,e.site,n);if(e.kind==="focal")return n.focal||I(e.site,". is available only inside a shape or write patch"),n.focal;if(e.kind==="array"){let i=e.items.map(s=>ue(s,n,t)),r=i[0]?.type??{kind:"unknown"};return{code:`[${i.map(s=>s.code).join(", ")}]`,type:{kind:"list",item:Fd(r),max:i.length,optional:!1}}}if(e.kind==="object"){let i=new Map;return{code:`{ ${e.fields.map(s=>{let o=ue(s.value??{kind:"name",name:s.name,site:s.site},n,t);return i.set(s.name,o.type),`${Tt(s.name)}: ${o.code}`}).join(", ")} }`,type:{kind:"object",fields:i,nullable:!1}}}if(e.kind==="unary"){let i=ue(e.value,n,t);return e.op==="not"&&ri(e.value,i.type,"not"),e.op==="-"&&!gs(i.type)&&(["int","decimal","money"].includes(i.type.kind)&&"optional"in i.type&&i.type.optional?Q(e.site,"negation requires a present int, decimal, or money value","require presence first: -(value!) or -(value ?? 0)"):Q(e.site,"negation requires an int, decimal, or money value","negate an int, decimal, or money value")),{code:`${e.op==="not"?"!":"-"}(${i.code})`,type:e.op==="not"?$t():i.type}}if(e.kind==="binary")return Cd(e,n,t);if(e.kind==="member")return lu(e,n,t);if(e.kind==="call")return Id(e,n,t);if(e.kind==="read")return wt(e,n,t);if(e.kind==="merge")return Md(e,n,t);if(e.kind==="exists")return{code:wt(e.read,n,t,!0).code,type:$t()};if(e.kind==="created"&&I(e.site,"created is valid only in an insert table rule"),e.kind==="aggregate"){let i=wt({kind:"read",table:e.table,keys:e.keys,site:e.site},n,t),r=n.catalog.get(e.table)?.columns.get("value");r||I(e.site,`#${e.table}[...] requires a maintained target with a value column`);let s=me("agg",e.site);return t.statement(`const ${s} = ${i.code}?.value ?? 0;`,e.site),{code:s,type:{...r,optional:!1}}}if(e.kind==="assert"){let i=ue(e.value,n,t),r=me("required",e.site);return t.statement(`const ${r} = ${i.code};`,e.site),t.statement(`db.require(${r} !== null, ${JSON.stringify(e.code)});`,e.site),{code:`${r}!`,type:Eu(i.type)}}if(e.kind==="shapeUse"&&I(e.site,`shape ${e.name} was not expanded`),e.kind==="shape")return vd(e,n,t);if(e.kind==="walk"){let i=n.catalog.get(e.table);i||I(e.site,`unknown table ${e.table}`);let r=i.columns.get(e.column);(r?.kind!=="ref"||r.table!==e.table)&&I(e.site,`walk ${e.table} up .${e.column} requires a self-reference column`);let s=ue(e.seed,n,t),o=me("walk",e.site),a=me("ancestor",e.site);return t.statement(`const ${o}: any[] = [];`,e.site),t.raw(`for (const ${a} of recurse(${s.code}, (current) => db.get(${e.table}, current.${e.column}), { depth: ${e.depth}, fanout: 1 })) {`),t.nested(()=>t.statement(`${o}.push(${a});`,e.site)),t.statement("}",e.site),{code:o,type:{kind:"sequence",item:{kind:"row",table:e.table,nullable:!1},max:e.depth+1}}}return Rd(e,n,t)}function Od(e,n,t){let i=t.bindings.get(e);if(i)return{...i,type:i.narrowedType??i.type};if(e==="viewer")return{code:"ctx.viewer",type:{kind:"principal",optional:!1}};if(e==="now")return{code:"ctx.now()",type:{kind:"time",optional:!1}};if(e==="commit")return{code:"ctx.commitTime",type:{kind:"time",optional:!1}};if(e==="new")return{code:"ctx.newId()",type:{kind:"id",optional:!1}};I(n,`unknown name ${e}`)}function Cd(e,n,t){let i=ue(e.left,n,t),r=ue(e.right,n,t);if(e.op==="and"||e.op==="or")return ri(e.left,i.type,e.op),ri(e.right,r.type,e.op),{code:`(${i.code} ${e.op==="and"?"&&":"||"} ${r.code})`,type:$t()};if(e.op==="??")return{code:`(${i.code} ?? ${r.code})`,type:Eu(i.type)};let s=e.op==="="?"===":e.op==="!="?"!==":e.op;if(["=","!=","<","<=",">",">="].includes(e.op)){if((e.op==="="||e.op==="!=")&&e.right.kind==="literal"&&e.right.value===null)return{code:`(${i.code} ${e.op==="="?"==":"!="} null)`,type:$t()};uu(e,i.type,r.type);let a=dn(i.type)??dn(r.type),u=a===i.type?r:i,c=a===i.type?e.right:e.left;if(a&&!dn(u.type)&&!si(c)&&Q(e.site,`cannot compare nominal ${fn(a)} with ${nn(u.type)}`,`compare ${nt(a===i.type?e.left:e.right)} with the same ${fn(a)} type`),!a&&pn(i.type)&&pn(r.type)&&!xu(i.type,r.type)&&I(e.site,`cannot compare nominal ${i.type.kind} with ${r.type.kind}; use a principal value only with viewer`),["<","<=",">",">="].includes(e.op)&&(ms(i.type)||ms(r.type))){let l=au(e.left,i.type),f=au(e.right,r.type);Q(e.site,`ordered comparison ${e.op} requires present operands`,`${l} ${e.op} ${f}`)}return{code:`(${i.code} ${s} ${r.code})`,type:$t()}}uu(e,i.type,r.type);let o=dn(i.type)??dn(r.type);if(o&&(e.op==="/"||e.op==="%")){let a=e.op==="/"?"quotient":"remainder";Q(e.site,`${fn(o)} does not admit ${e.op}`,`use divmod(${nt(e.left)}, ${nt(e.right)}).${a}`)}if(o&&(e.op==="+"||e.op==="-")){let a=o===i.type?r:i,u=o===i.type?e.right:e.left;return!dn(a.type)&&!si(u)&&Q(e.site,`${e.op} requires matching ${fn(o)} values`,`use two matching ${fn(o)} values`),{code:`(${i.code} ${e.op} ${r.code})`,type:o}}if(o&&e.op==="*"){let a=dn(i.type),u=dn(r.type);if(a&&u){a.kind==="money"&&u.kind==="money"&&Q(e.site,"money multiplied by money has no currency-squared value in Quarry","multiply the money value by a decimal rate or an int");let f=a.kind==="money"?u:u.kind==="money"?a:u,d=a.kind==="money"?a:u.kind==="money"?u:a,p=10**f.scale;return{code:`divmod((${i.code} * ${r.code}), ${p}).quotient`,type:d}}let c=o===i.type?r:i,l=o===i.type?e.right:e.left;return!dn(c.type)&&(c.type.kind!=="int"||jn(l))&&Q(e.site,`${fn(o)} multiplication requires an int operand or a decimal-typed rate; a bare fractional literal has no scale`,"use an int operand or declare the rate as a decimal S argument or column"),{code:`(${i.code} * ${r.code})`,type:o}}return{code:`(${i.code} ${e.op} ${r.code})`,type:i.type}}function lu(e,n,t){let i=e.base.kind==="name"?n.bindings.get(e.base.name):void 0,r=ue(e.base,n,t);if(hu(r.type)){let s=r.type;s.table||I(e.site,`cannot auto-dereference ${e.name} because the reference target is not known; use a typed table ref`);let o=me("deref",e.site);if(s.optional){let a=me("derefKey",e.site);t.statement(`const ${a} = ${r.code} ?? null;`,e.site),t.statement(`let ${o}: any = null;`,e.site),t.raw(`if (${a} !== null) {`),t.nested(()=>t.statement(`${o} = db.get(${s.table}, ${a});`,e.site)),t.statement("}",e.site)}else t.statement(`const ${o} = db.get(${s.table}, ${r.code});`,e.site);r={code:o,type:{kind:"row",table:s.table,nullable:!0}}}if(r.type.kind==="image"||r.type.kind==="video"){let s=r.type.kind==="image"?["id","width","height"]:["id","width","height","duration"];s.includes(e.name)||Q(e.site,`${r.type.kind} asset has no field ${e.name}; available fields are ${s.join(", ")}`,`${nt(e.base)}.${r.type.kind==="video"?"duration":"width"}`);let o=e.name==="id"?{kind:"id",optional:r.type.optional}:{kind:"int",optional:r.type.optional};return{code:`${r.code}${r.type.optional?"?.":"."}${e.name}`,type:o}}if(r.type.kind==="row"){let s=n.catalog.get(r.type.table),o=e.name==="id"?{kind:"ref",table:r.type.table,optional:!1}:s?.columns.get(e.name);o||I(e.site,`table ${r.type.table} has no column ${e.name}`);let a=i?.narrowedFields?.has(e.name)??!1;return{code:`${r.code}${r.type.nullable?"?.":"."}${e.name}`,type:{...o,optional:a?!1:o.optional||r.type.nullable}}}if(r.type.kind==="object"){let s=r.type.fields.get(e.name);return s||I(e.site,`shaped object has no field ${e.name}`),{code:`${r.code}${r.type.nullable?"?.":"."}${e.name}`,type:r.type.nullable?jd(s):s}}if(r.type.kind==="json")return{code:`(${r.code} as any)?.${e.name}`,type:{kind:"unknown"}};if(r.type.kind==="unknown")return{code:`${r.code}?.${e.name}`,type:{kind:"unknown"}};I(e.site,`cannot select .${e.name} from ${r.type.kind}`)}function Id(e,n,t){e.name==="sorted"&&I(e.site,"sorted(a, b) must be consumed by a two-name binding: (lo, hi) = sorted(a, b)");let i=e.name==="tokens"?"mentionTokens":e.name;["tokens","range","min","max","count","divmod","share"].includes(e.name)||Ge(e.site,`user function or recursion (${e.name})`,"use a Quarry builtin or inline one bounded expression");let r=e.args.map(s=>ue(s,n,t));if(e.name==="divmod"){r.length!==2&&Q(e.site,`divmod(a, b) requires exactly 2 arguments; received ${r.length}`,"use divmod(amount, integerDivisor)");let s=r[0],o=r[1];gs(s.type)||Q(e.args[0].site,`divmod's first argument must be int, decimal, or money; received ${nn(s.type)}`,"use an int, decimal, or money numerator"),(o.type.kind!=="int"||jn(e.args[1]))&&Q(e.args[1].site,"divmod's divisor must be an int","use an integer expression or integer literal as the divisor");let a=s.type;return{code:`divmod(${s.code}, ${o.code})`,type:{kind:"object",fields:new Map([["quotient",a],["remainder",a]]),nullable:!1}}}if(e.name==="share"){r.length!==3&&Q(e.site,`share(amount, recipients, recipient) requires exactly 3 arguments; received ${r.length}`,"use share(amount, recipients, recipient)");let s=r[0],o=r[1],a=r[2];gs(s.type)||Q(e.args[0].site,`share's amount must be int, decimal, or money; received ${nn(s.type)}`,"use an int, decimal, or money amount");let u=Bd(o.type);return u||Q(e.args[1].site,`share recipients must be a bounded list or page; received ${nn(o.type)}`,"use a bounded [T] <=N argument or bounded page-derived list"),qd(u,a.type)||Q(e.args[2].site,`share recipient type ${nn(a.type)} does not match recipient-list item type ${nn(u)}`,"use a recipient with the same nominal type as the recipients list items"),{code:`deterministicShare(${s.code}, ${o.code}, ${a.code})`,type:s.type}}if(e.name==="count")return(r.length!==1||!["list","page","sequence"].includes(r[0].type.kind))&&I(e.site,"count(x) requires one bounded list or page"),{code:`${r[0].code}.length`,type:{kind:"int",optional:!1}};if(e.name==="tokens")return{code:`${i}(${r.map(s=>s.code).join(", ")})`,type:{kind:"list",item:{kind:"text",max:4096,optional:!1},max:64,optional:!1}};if(e.name==="range"){r.length!==2&&I(e.site,"range(a, b) requires two arguments");for(let u of e.args)jn(u)&&Q(u.site,"int positions take integer literals",`replace ${oi(u)} with an integer literal`);let s=cu(e.args[0]),o=cu(e.args[1]),a=s===void 0||o===void 0?1e3:Math.max(0,o-s);return{code:`range(${r.map(u=>u.code).join(", ")})`,type:{kind:"list",item:{kind:"int",optional:!1},max:a,optional:!1}}}if(e.name==="min"||e.name==="max"){let s=r.map(a=>dn(a.type)).find(a=>a!==void 0);if(s)return r.forEach((a,u)=>{!dn(a.type)&&!si(e.args[u])&&Q(e.args[u].site,`${e.name} requires matching ${fn(s)} values`,`use matching ${fn(s)} values`)}),{code:`${i}(${r.map(a=>a.code).join(", ")})`,type:s};let o=e.args.find(jn);o&&r.some(a=>a.type.kind==="int")&&Q(o.site,"int positions take integer literals",`replace ${oi(o)} with an integer literal`)}return{code:`${i}(${r.map(s=>s.code).join(", ")})`,type:r[0]?.type??{kind:"int",optional:!1}}}function wt(e,n,t,i=!1){n.catalog.has(e.table)||I(e.site,`unknown table ${e.table}`);let r=e.range?"range":i?"exists":"point",s=et(n.catalog,e.table,e.keys,r,e.index,c=>At(c,n),e.site),o=e.keys.map(c=>Hi(ue(c.value,n,t))),a=s.name==="byId"?e.table:`${e.table}.${s.name}`;if(e.range){let c=s.columns.slice(e.keys.length);if(e.range.cursor&&c.length===0){let{cursor:p,cursorKind:g,...m}=e.range;Q(e.range.cursor.site,`scan ${e.table}.${s.name} prefix names every index column, so a cursor has no position to compare; remove after or shorten the prefix`,te({...e,range:m}))}if(e.range.cursor&&s.columns.at(-1)!=="id"&&!s.unique){let p=[...s.columns.filter(g=>g!=="id"),"id"];Q(s.site,`cursor at ${Ud(e.range.cursor.site)} uses \`${e.table}.${s.name}\`, which is not a total order (it neither ends in id nor is unique)`,`by ${s.name}: ${p.join(", ")}`)}let l=e.range.cursor&&ue(e.range.cursor,n,t);l&&l.type.kind!=="cursor"&&Q(e.range.cursor.site,`after expects a cursor value, got ${nn(l.type)}`,"declare c: cursor ? and pass after c");let f=[`order: ${JSON.stringify(e.range.order)}`,`take: ${e.range.take}`];return l&&f.push(`after: ${l.code}`,"opaqueCursor: true"),e.range.mergeSite&&f.push(`mergeSite: ${JSON.stringify(e.range.mergeSite)}`),{code:`db.scan(${a}, [${o.map(p=>p.code).join(", ")}], { ${f.join(", ")} })`,type:{kind:"page",table:e.table}}}let u=s.name==="byId"&&o.length===1?o[0].code:`[${o.map(c=>c.code).join(", ")}]`;return i?{code:`db.exists(${a}, ${u})`,type:$t()}:{code:`db.get(${a}, ${u})`,type:{kind:"row",table:e.table,nullable:!0}}}function Md(e,n,t){let i=n.catalog.get(e.table);i||I(e.site,`unknown table ${e.table}`);let r=i.indexes.find(d=>d.name===e.index);if(r||I(e.site,`table ${e.table} has no index ${e.index}`),r.columns.at(-1)!=="id"){let d=[...r.columns.filter(p=>p!=="id"),"id"];Q(r.site,`pageable merge ${e.table}.${r.name} must end in intrinsic id`,`by ${r.name}: ${d.join(", ")}`)}let s=e.cursor&&ue(e.cursor,n,t);if(s&&s.type.kind!=="cursor"&&Q(e.cursor.site,`merge after expects a cursor value, got ${nn(s.type)}`,"declare c: cursor ? and pass after c"),new Set(e.lanes.map(d=>d.prefix.length)).size!==1){let d=e.lanes.find(p=>p.prefix.length!==e.lanes[0].prefix.length)??e.lanes[0];Q(d.site,"merge lanes must have equal-width index prefixes",`use ${e.lanes[0].prefix.length} prefix key(s) in this lane`)}let a=e.lanes[0].prefix.length;a>=r.columns.length&&Q(e.lanes[0].site,`merge lane prefixes must leave at least one ${e.table}.${r.name} suffix column`,"drop the last prefix key from every lane");let u=new Map;e.lanes.forEach((d,p)=>{let g=d.prefix.map(te).join("\0");u.has(g)&&Q(d.site,"merge lanes have structurally identical prefixes","drop this duplicate lane"),u.set(g,p);let m=n.clone();d.loop&&m.bindings.set(d.loop.name,{code:d.loop.name,type:{kind:"row",table:d.loop.domain.table,nullable:!1}}),d.prefix.forEach((y,b)=>{let S=At(y,m),E=r.columns[b],k=E==="id"?{kind:"ref",table:e.table,optional:!1}:i.columns.get(E);S&&k&&!xu(S,k)&&Q(d.site,`merge lane key ${b+1} is ${nn(S)}; ${e.table}.${r.name}.${E} is ${nn(k)}`,`use a ${nn(k)} expression in this lane position`)}),et(n.catalog,e.table,d.prefix.map(y=>({value:y,site:y.site})),"range",e.index,y=>At(y,m),d.site)});let c=`${e.site.file}:${e.site.line}:${e.site.col}`,l=me("mergeUnion",e.site);t.statement(`const ${l}: Array<(typeof ${e.table})["__row"]> = [];`,e.site);for(let d of e.lanes){let p=m=>{let y=wt({kind:"read",table:e.table,keys:d.prefix.map(S=>({value:S,site:S.site})),index:e.index,range:{order:e.order,take:e.take,cursor:e.cursor,cursorKind:e.cursorKind,mergeSite:c,site:d.site},site:d.site},m,t),b=me("mergeRow",d.site);t.raw(`for (const ${b} of ${y.code}) {`,d.site),t.nested(()=>t.statement(`${l}.push(${b});`,d.site)),t.statement("}",d.site)};if(!d.loop){p(n);continue}let g=wt(d.loop.domain,n,t);t.raw(`for (const ${d.loop.name} of ${g.code}) {`,d.site),t.nested(()=>{let m=n.clone();m.bindings.set(d.loop.name,{code:d.loop.name,type:{kind:"row",table:d.loop.domain.table,nullable:!1}}),p(m)}),t.statement("}",d.site)}let f=r.columns.slice(a);return{code:`mergeByIndex(${l}, ${JSON.stringify(f)}, ${JSON.stringify(e.order)}, ${e.take}, ${JSON.stringify(c)}, ${JSON.stringify(e.table)})`,type:{kind:"page",table:e.table}}}function vd(e,n,t){let i=ue(e.base,n,t);if(hu(i.type)){let u=i.type;u.table||I(e.site,"shape auto-dereference needs a typed table reference");let c=me("shapeRef",e.site);if(u.optional){let l=me("shapeRefKey",e.site);t.statement(`const ${l} = ${i.code} ?? null;`,e.site),t.statement(`let ${c}: any = null;`,e.site),t.raw(`if (${l} !== null) {`),t.nested(()=>t.statement(`${c} = db.get(${u.table}, ${l});`,e.site)),t.statement("}",e.site)}else t.statement(`const ${c} = db.get(${u.table}, ${i.code});`,e.site);i={code:c,type:{kind:"row",table:u.table,nullable:!0}}}if(i.type.kind==="page")return su(i,e.fields,e.site,n,t,i.type.table);if(i.type.kind==="sequence"&&i.type.item.kind==="row")return su(i,e.fields,e.site,n,t,i.type.item.table);i.type.kind!=="row"&&I(e.site,"shapes may focus only a row, reference, or page");let r=i.type,s=me("row",e.site);t.statement(`const ${s} = ${i.code};`,e.site);let o=me("shape",e.site),a={kind:"object",fields:new Map,nullable:!1};if(r.nullable)t.statement(`let ${o}: any = null;`,e.site),t.raw(`if (${s} !== null) {`),t.nested(()=>{let[u,c]=ls(e.fields,{code:s,type:{...r,nullable:!1}},n,t);a=c,t.statement(`${o} = ${u};`,e.site)}),t.statement("}",e.site);else{let[u,c]=ls(e.fields,{code:s,type:r},n,t);a=c,t.statement(`const ${o} = ${u};`,e.site)}return{code:o,type:{...a,nullable:r.nullable}}}function su(e,n,t,i,r,s){let o=me("page",t),a=me("rows",t),u=me("row",t),c={kind:"object",fields:new Map,nullable:!1};return r.statement(`const ${o} = ${e.code};`,t),r.statement(`const ${a}: any[] = [];`,t),r.raw(`for (const ${u} of ${o}) {`),r.nested(()=>{let[l,f]=ls(n,{code:u,type:{kind:"row",table:s,nullable:!1}},i,r);c=f,r.statement(`${a}.push(${l});`,t)}),r.statement("}",t),{code:a,type:{kind:"sequence",item:c,max:1e3}}}function ls(e,n,t,i){let r=t.focal;t.focal=n;try{let s=[],o=new Map;for(let a of e)if(a.kind==="spread"){s.push(`...${n.code}`),n.type.kind!=="row"&&I(a.site,"shape spread requires a row"),o.set("id",{kind:"ref",table:n.type.table,optional:!1});for(let[u,c]of t.catalog.get(n.type.table)?.columns??[])o.set(u,c)}else if(a.kind==="bare"){let u=lu({kind:"member",base:{kind:"focal",site:a.site},name:a.name,site:a.site},t,i);s.push(`${Tt(a.name)}: ${u.code}`),o.set(a.name,u.type)}else if(a.kind==="namedSpread")I(a.site,`shape ${a.name} was not expanded`);else{let u=ue(a.value,t,i);s.push(`${Tt(a.name)}: ${u.code}`),o.set(a.name,u.type)}return[`{ ${s.join(", ")} }`,{kind:"object",fields:o,nullable:!1}]}finally{t.focal=r}}function Rd(e,n,t){let i=n.catalog.get(e.table);if(i||I(e.site,`unknown table ${e.table}`),e.op==="insert"){let d=ds(e.fields,n,t,i.columns);return e.fields.some(p=>p.name==="id")||d.unshift("id: ctx.newId()"),{code:`db.insert(${e.table}, { ${d.join(", ")} })`,type:{kind:"row",table:e.table,nullable:!1}}}let r=et(n.catalog,e.table,e.keys,"point",void 0,d=>At(d,n),e.site);Ld(e,r);let s=e.keys.map((d,p)=>{let g=Hi(ue(d.value,n,t)),m=me(`writeKey${p+1}`,d.site);return t.statement(`const ${m} = ${g.code};`,d.value.site),{...g,code:m}}),o=new Map(r.columns.map((d,p)=>[d,s[p].code]));if(r.name!=="byId"||s.length!==1)return Dd(e,n,t,i.columns,r,s);let a=s[0];if(e.op==="delete")return t.statement(`db.delete(${e.table}, ${a.code});`,e.site),{code:"null",type:{kind:"unknown"},effectOnly:!0};let u=e.op==="update"?e.fields.filter(d=>!o.has(d.name)):e.fields;if(!u.some(d=>d.value&&Te(d.value))&&e.op!=="upsert"){let d=ds(u,n,t,i.columns);return t.statement(`db.${e.op}(${e.table}, ${a.code}, { ${d.join(", ")} });`,e.site),{code:"null",type:{kind:"unknown"},effectOnly:!0}}let l=n.focal,f=me("old",e.site);n.focal={code:f,type:{kind:"row",table:e.table,nullable:e.op==="upsert"}};try{t.raw(`db.${e.op}(${e.table}, ${a.code}, (${f}) => {`),t.nested(()=>{let d=du(u,n,t,i.columns,e.op==="upsert"?o:void 0);e.op==="upsert"&&!e.fields.some(p=>p.name==="id")&&d.unshift(`id: ${a.code}`),t.statement(`return { ${d.join(", ")} };`,e.site)}),t.statement("});",e.site)}finally{n.focal=l}return{code:"null",type:{kind:"unknown"},effectOnly:!0}}function Dd(e,n,t,i,r,s){let o=me("writeRow",e.site);t.statement(`const ${o} = db.get(${e.table}.${r.name}, [${s.map(c=>c.code).join(", ")}]);`,e.site);let a=new Map(r.columns.map((c,l)=>[c,s[l].code]));if(e.op==="delete")return t.statement(`db.require(${o} !== null, "NOT_FOUND");`,e.site),t.statement(`db.delete(${e.table}, ${o}!.id);`,e.site),{code:"null",type:{kind:"unknown"},effectOnly:!0};if(e.op==="update"){t.statement(`db.require(${o} !== null, "NOT_FOUND");`,e.site);let c=n.focal;n.focal={code:`${o}!`,type:{kind:"row",table:e.table,nullable:!1}};try{let l=e.fields.filter(d=>!a.has(d.name)),f=l.some(d=>d.value&&Te(d.value))?du(l,n,t,i):ds(l,n,t,i);t.statement(`db.update(${e.table}, ${o}!.id, { ${f.join(", ")} });`,e.site)}finally{n.focal=c}return{code:"null",type:{kind:"unknown"},effectOnly:!0}}let u=n.focal;n.focal={code:o,type:{kind:"row",table:e.table,nullable:!0}};try{let c=e.fields,l=me("upsertKey",e.site),f=fu(c,n,t,i,a),d=new Set(c.map(y=>y.name)),p=r.columns.flatMap((y,b)=>d.has(y)?[]:[{name:y,value:s[b].code}]);f.unshift(...p);let g=f.find(y=>y.name==="id");t.statement(`const ${l} = ${g?g.value:`${o}?.id ?? ctx.newId()`};`,e.site);let m=f.filter(y=>y.name!=="id").map(pu);m.unshift(`id: ${l}`),t.statement(`db.upsert(${e.table}, ${l}, { ${m.join(", ")} });`,e.site)}finally{n.focal=u}return{code:"null",type:{kind:"unknown"},effectOnly:!0}}function ds(e,n,t,i){return e.map(r=>{let s=ue(r.value??{kind:"name",name:r.name,site:r.site},n,t),o=r.name==="id"?{kind:"id",optional:!1}:i.get(r.name);gu(r,s.type,o,n);let a=o&&(o.kind==="ref"||o.kind==="id")?Hi(s).code:s.code;return`${Tt(r.name)}: ${a}`})}function du(e,n,t,i,r=new Map){return fu(e,n,t,i,r).map(pu)}function fu(e,n,t,i,r=new Map){return e.map(s=>{let o=r.get(s.name);if(o)return{name:s.name,value:o};let a=ue(s.value??{kind:"name",name:s.name,site:s.site},n,t),u=s.name==="id"?{kind:"id",optional:!1}:i.get(s.name);gu(s,a.type,u,n);let c=u&&(u.kind==="ref"||u.kind==="id")?Hi(a).code:a.code,l=me("patch",s.site);return t.statement(`const ${l} = ${c};`,s.site),{name:s.name,value:l}})}function pu(e){return`${Tt(e.name)}: ${e.value}`}function Ld(e,n){if(e.op==="delete")return;let t=e.op==="update"||e.op==="upsert"?e.fields.find(i=>i.name==="id"):void 0;t&&Q(t.site,e.op==="upsert"?"upsert rows may not name id; identity comes from the addressed row or is minted on insert":"update patches may not name id; row identity is immutable",fs(e,t));for(let[i,r]of n.columns.entries()){let s=e.fields.find(a=>a.name===r);if(!s)continue;let o=s.value??{kind:"name",name:s.name,site:s.site};te(o)!==te(e.keys[i].value)&&Q(s.site,`${e.op} may not reassign addressed key column ${r}; the ${n.name} address is authoritative`,fs(e,s))}}function fs(e,n){let t=e.op==="insert"?"":`[${e.keys.map(ps).join(", ")}]`,i=e.op==="delete"?"":` { ${e.fields.filter(r=>r!==n).map(mu).join(", ")} }`;return`${e.op} ${e.table}${t}${i}`}function ps(e){return`${e.column?`${e.column} = `:""}${te(e.value)}`}function mu(e){return e.value?`${e.name}: ${te(e.value)}`:e.name}function te(e){if(e.kind==="name")return e.name;if(e.kind==="focal")return".";if(e.kind==="literal")return JSON.stringify(e.value);if(e.kind==="array")return`[${e.items.map(te).join(", ")}]`;if(e.kind==="object")return`{ ${e.fields.map(mu).join(", ")} }`;if(e.kind==="unary")return`${e.op} (${te(e.value)})`;if(e.kind==="binary")return`(${te(e.left)} ${e.op} ${te(e.right)})`;if(e.kind==="member")return e.base.kind==="focal"?`.${e.name}`:`(${te(e.base)}).${e.name}`;if(e.kind==="call")return`${e.name}(${e.args.map(te).join(", ")})`;if(e.kind==="read"){let n=`${e.table}[${e.keys.map(ps).join(", ")}]`;return e.range?.cursor&&(n+=` ${e.range.cursorKind??"after"} ${te(e.range.cursor)}`),e.range&&(n+=` ${e.range.order==="asc"?"first":"last"} ${e.range.take}`),e.index&&(n+=` by ${e.index}`),e.range?.where&&(n+=` where ${te(e.range.where.predicate)}`),n}if(e.kind==="merge"){let n=e.cursor?` ${e.cursorKind??"after"} ${te(e.cursor)}`:"",t=e.lanes.map(i=>` [${i.prefix.map(te).join(", ")}]${i.loop?` for ${i.loop.name} in ${te(i.loop.domain)}`:""}`).join(`
16
+ `);return`merge ${e.table}${n} ${e.order==="asc"?"first":"last"} ${e.take} by ${e.index}:
17
+ ${t}`}if(e.kind==="exists"||e.kind==="created")return`${e.kind} ${te(e.read)}`;if(e.kind==="aggregate")return`#${e.table}[${e.keys.map(ps).join(", ")}]`;if(e.kind==="assert")return`(${te(e.value)})! else ${e.code}`;if(e.kind==="shapeUse")return`(${te(e.base)}) ${e.name}`;if(e.kind==="shape"){if(e.authoredName)return`(${te(e.base)}) ${e.authoredName}`;let n=(e.authoredFields??e.fields).map(t=>t.kind==="spread"?"*":t.kind==="namedSpread"?`...${t.name}`:t.kind==="bare"?t.name:`${t.name}: ${te(t.value)}`);return`(${te(e.base)}) { ${n.join(", ")} }`}return e.kind==="walk"?`walk ${e.table}[${te(e.seed)}] up .${e.column} depth ${e.depth}`:fs(e,{name:"",site:e.site})}function gu(e,n,t,i){let r=e.value??{kind:"name",name:e.name,site:e.site};if(t?.optional&&r.kind==="literal"&&r.value===null)return;if(t?.kind==="int"&&jn(r)&&Q(e.site,"int positions take integer literals",`replace ${oi(r)} with an integer literal`),t?.kind==="decimal"||t?.kind==="money"){if(si(r)||n.kind==="decimal"||n.kind==="money")return;Q(e.site,`${e.name} is ${fn(t)}; ${nn(n)} is nominally different`,`use a ${fn(t)} value`)}(n.kind==="decimal"||n.kind==="money")&&t&&Q(e.site,`${e.name} is ${t.kind}; ${fn(n)} is nominally different`,`use a ${t.kind} value`),t?.kind==="principal"&&n.kind!=="principal"&&I(e.site,`${e.name} is principal; ${n.kind} is nominally different (a ref/id is not a principal)`),(t?.kind==="ref"||t?.kind==="id")&&n.kind==="principal"&&I(e.site,`${e.name} is ${t.kind}; principal is nominally different`);let s=ii(t),o=ii(n),a=s?yu(r,n,t,i):!o;if((s||o)&&!a){let u=s&&o&&s.kind===o.kind,c=s?u?ou(s):`${s.kind} asset`:"non-asset",l=o?u?ou(o):`${o.kind} asset`:nn(n);Q(e.site,`${e.name} requires ${c} values at every nested asset position; received ${l}`,`use a ${c} value for ${e.name}`)}}function yu(e,n,t,i){if(t.kind==="list"&&e.kind==="array"){let r=n.kind==="list"||n.kind==="sequence"?n.item:{kind:"unknown"};return e.items.every(s=>yu(s,At(s,i)??r,t.item,i))}return Pd(ii(t),ii(n))}function ii(e){if(e){if(e.kind==="image"||e.kind==="video")return{kind:e.kind,wrappers:[],leafOptional:e.optional};if(e.kind==="list"||e.kind==="sequence"){let n=ii(e.item);if(n)return{...n,wrappers:[{optional:e.kind==="list"&&e.optional},...n.wrappers]}}}}function Pd(e,n){return!e||!n||e.kind!==n.kind||e.wrappers.length!==n.wrappers.length||n.leafOptional&&!e.leafOptional?!1:n.wrappers.every((t,i)=>!t.optional||e.wrappers[i].optional)}function ou(e){let n=`${e.kind} asset${e.leafOptional?" or null":""}`;for(let t of[...e.wrappers].reverse())n=`[${n}]${t.optional?" or null":""}`;return n}function At(e,n){if(e.kind==="name"){let t=n.bindings.get(e.name)?.type;if(t&&pn(t))return t;if(t?.kind==="row")return{kind:"ref",table:t.table,optional:t.nullable};if(e.name==="viewer")return{kind:"principal",optional:!1};if(e.name==="new")return{kind:"id",optional:!1};if(e.name==="now"||e.name==="commit")return{kind:"time",optional:!1}}if(e.kind==="focal"&&n.focal?.type.kind==="row")return{kind:"ref",table:n.focal.type.table,optional:n.focal.type.nullable};if(e.kind==="literal"){let t=bu(e);return pn(t)?t:void 0}if(e.kind==="member"){let t=At(e.base,n);if(t?.kind==="ref"&&t.table)return e.name==="id"?{kind:"ref",table:t.table,optional:t.optional}:n.catalog.get(t.table)?.columns.get(e.name)}}function bu(e){if(typeof e.value=="string")return{kind:"text",max:Math.max(1,e.value.length),optional:!1};if(typeof e.value=="number"){let n=ku(e.numericText);return n===0?{kind:"int",optional:!1}:{kind:"numeric-literal",fractionalDigits:n}}return typeof e.value=="boolean"?{kind:"bool",optional:!1}:{kind:"text",max:1,optional:!0}}function Fd(e){return pn(e)?e:{kind:"text",max:1,optional:!0}}function pn(e){return["cursor","text","id","principal","int","decimal","money","time","bool","json","bytes","image","video","enum","ref","list"].includes(e.kind)}function hu(e){return e.kind==="ref"}function Eu(e){return e.kind==="row"?{...e,nullable:!1}:e.kind==="object"?{...e,nullable:!1}:pn(e)?{...e,optional:!1}:e}function jd(e){return e.kind==="row"||e.kind==="object"?{...e,nullable:!0}:pn(e)?{...e,optional:!0}:{kind:"unknown"}}function ms(e){return e.kind==="row"||e.kind==="object"?e.nullable:e.kind==="unknown"?!0:pn(e)&&e.optional}function ri(e,n,t){if(n.kind==="bool"&&!n.optional)return;let i=pn(n)&&n.optional||(n.kind==="row"||n.kind==="object")&&n.nullable,r=e.kind==="name"?e.name:e.kind==="member"?`${nt(e.base)}.${e.name}`:"x";Q(e.site,`${t} requires a Boolean operand; got ${n.kind}${i?"?":""}`,i?`${r} != null`:`compare ${r} to a value so ${t} receives a Boolean`)}function nt(e){return e.kind==="name"?e.name:e.kind==="focal"?"":e.kind==="member"?`${nt(e.base)}.${e.name}`:"x"}function au(e,n){let t=nt(e),i=t==="x"?`(${te(e)})`:t;return ms(n)?`${i}!`:i}function $t(){return{kind:"bool",optional:!1}}function Hi(e){return e.type.kind==="row"?{...e,code:`${e.code}.id`,type:{kind:"ref",table:e.type.table,optional:e.type.nullable}}:e}function xu(e,n){return e.kind==="principal"||n.kind==="principal"?e.kind==="principal"&&n.kind==="principal":e.kind==="ref"||e.kind==="id"?n.kind==="ref"||n.kind==="id":n.kind==="ref"||n.kind==="id"?!1:e.kind==="enum"&&n.kind==="text"||e.kind==="text"&&n.kind==="enum"?!0:e.kind==="decimal"||n.kind==="decimal"?e.kind==="decimal"&&n.kind==="decimal"&&e.scale===n.scale:e.kind==="money"||n.kind==="money"?e.kind==="money"&&n.kind==="money"&&e.currency===n.currency&&e.scale===n.scale:e.kind===n.kind}function dn(e){return e.kind==="decimal"||e.kind==="money"?e:void 0}function fn(e){return e.kind==="decimal"?`decimal ${e.scale}`:`money ${e.currency} ${e.scale}`}function gs(e){return(e.kind==="int"||e.kind==="decimal"||e.kind==="money")&&!e.optional}function Bd(e){if(e.kind==="list"||e.kind==="sequence")return e.item;if(e.kind==="page")return{kind:"row",table:e.table,nullable:!1}}function qd(e,n){return e.kind==="row"||n.kind==="row"?e.kind==="row"&&n.kind==="row"&&e.table===n.table&&!e.nullable&&!n.nullable:!pn(e)||!pn(n)||e.optional||n.optional||e.kind!==n.kind?!1:e.kind==="ref"&&n.kind==="ref"?e.table===n.table:e.kind==="decimal"&&n.kind==="decimal"?e.scale===n.scale:e.kind==="money"&&n.kind==="money"?e.currency===n.currency&&e.scale===n.scale:!0}function nn(e){return e.kind==="numeric-literal"?"decimal literal":e.kind==="ref"?`ref ${e.table}`:e.kind==="row"?`row ${e.table}`:e.kind}function si(e){return e.kind==="literal"&&typeof e.value=="number"||e.kind==="unary"&&e.op==="-"&&si(e.value)}function jn(e){return e.kind==="unary"&&e.op==="-"?jn(e.value):e.kind==="literal"&&typeof e.value=="number"&&ku(e.numericText)>0}function ku(e){let n=e?.indexOf(".")??-1;return n<0?0:e.length-n-1}function Vd(e){return typeof e.value=="number"?e.numericText??JSON.stringify(e.value):JSON.stringify(e.value)}function oi(e){return e.kind==="unary"&&e.op==="-"?`-${oi(e.value)}`:e.kind==="literal"&&typeof e.value=="number"?e.numericText??String(e.value):"the literal"}function uu(e,n,t){let i=n.kind==="int"&&jn(e.right)?e.right:t.kind==="int"&&jn(e.left)?e.left:void 0;i&&Q(i.site,"int positions take integer literals",`replace ${oi(i)} with an integer literal`)}function cu(e){return e?.kind==="literal"&&typeof e.value=="number"?e.value:void 0}function Tt(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function me(e,n){return`__q_${e}_${n.line}_${n.col}`}function Ud(e){return`${e.file}:${e.line}:${e.col}`}function Te(e){return e.kind==="focal"?!0:e.kind==="member"?Te(e.base):e.kind==="binary"?Te(e.left)||Te(e.right):e.kind==="unary"||e.kind==="assert"?Te(e.value):e.kind==="call"?e.args.some(Te):e.kind==="array"?e.items.some(Te):e.kind==="read"?e.keys.some(n=>Te(n.value))||e.range?.cursor!==void 0&&Te(e.range.cursor):e.kind==="merge"?e.lanes.some(n=>n.prefix.some(Te)):e.kind==="exists"||e.kind==="created"?Te(e.read):e.kind==="aggregate"?e.keys.some(n=>Te(n.value)):e.kind==="shapeUse"?Te(e.base):e.kind==="shape"?Te(e.base)||e.fields.some(n=>n.kind==="field"&&Te(n.value)):e.kind==="walk"?Te(e.seed):e.kind==="object"?e.fields.some(n=>n.value!==void 0&&Te(n.value)):e.kind==="write"?e.keys.some(n=>Te(n.value))||e.fields.some(n=>n.value!==void 0&&Te(n.value)):!1}var Kd=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","insert","instanceof","interface","let","merge","new","null","package","private","protected","public","retain","return","static","shape","fn","cursor","super","switch","this","throw","true","try","typeof","update","upsert","var","void","while","with","yield"]),Su=new Map([["??",1],["or",2],["and",3],["=",4],["!=",4],["<",4],["<=",4],[">",4],[">=",4],["+",5],["-",5],["*",6],["/",6],["%",6]]);function wu(e,n){let t=Za(e,n),i=new bs(t.tokens,e,t.diagnostics);return{document:i.document(),diagnostics:i.diagnostics}}var bs=class{constructor(n,t,i){this.tokens=n;this.file=t;this.diagnostics=i}position=0;tables=[];maintains=[];channels=[];effects=[];shapes=[];programs=[];identity;document(){for(;!this.atKind("eof")&&(this.skipNewlines(),!this.atKind("eof"));)try{let n=this.peek();this.at("use")?this.parseUse():this.at("table")?this.tables.push(this.parseTable()):this.at("maintain")?this.maintains.push(this.parseMaintain()):this.at("channel")?this.channels.push(this.parseChannel()):this.at("query")||this.at("mutation")?this.programs.push(this.parseProgram()):this.at("effect")?this.effects.push(this.parseEffect()):this.at("shape")?this.shapes.push(this.parseShapeDeclaration()):this.at("fn")||this.at("cursor")?Ge(n,n.value,`${n.value} is reserved for a future Quarry form; rename this declaration`):this.at("schedule")?Ge(n,"schedule","perform the bounded work in a named mutation invoked by the caller"):this.at("index")||this.at("unique")?Y(n,"top-level indexes are invalid; place by/unique inside the table block","move the index line into its table block"):this.at("device")||this.at("oblivious")?Ge(n,n.value,"pass an explicit bounded argument to the operation"):Y(n,`unexpected top-level ${JSON.stringify(n.value)}`)}catch(n){this.capture(n),this.recoverTopLevel()}return{file:this.file,identity:this.identity,tables:this.tables,maintains:this.maintains,channels:this.channels,effects:this.effects,shapes:this.shapes,programs:this.programs}}parseUse(){let n=this.take("use"),t=this.word();t.value!=="identity"&&Ge(t,`use ${t.value}`,"use identity password, use identity guests, or use identity");let i=!0,r=!0;this.at("password")?(this.take("password"),r=!1):this.at("guests")&&(this.take("guests"),i=!1),this.identity={password:i,guests:r},this.endLine(n)}parseTable(){let n=this.take("table"),t=this.generatedBinding("table");this.take(":"),this.newline(),this.takeKind("indent");let i=[],r=[],s=[],o=[],a=[],u,c;for(;!this.atKind("dedent")&&!this.atKind("eof")&&(this.skipNewlines(),!this.atKind("dedent"));)try{if(this.at("public")){let l=this.take("public");c={reason:this.atKind("string")?this.takeKind("string").value:`${t} is public in Quarry`,site:l},this.newline()}else this.at("by")?r.push(this.parseIndex(!1)):this.at("unique")?r.push(this.parseIndex(!0)):this.at("immutable")?o.push(this.parseImmutable()):this.at("retain")?(u&&Xt(this.peek(),`table ${t} has more than one retain line`),u=this.parseRetention()):this.at("after")?a.push(this.parseFinalExists()):["read","insert","update","delete"].includes(this.peek().value)?s.push(this.parseRule()):i.push(this.parseColumn())}catch(l){this.capture(l),this.recoverLine()}return this.takeKind("dedent"),{name:t,columns:i,indexes:r,rules:s,immutable:o,finalExists:a,...u?{retain:u}:{},...c?{public:c}:{},site:n}}parseRetention(){let n=this.take("retain");this.atKind("word")||Xt(n,"retain requires a policy word");let t=this.word();return t.value!=="until-revoked"&&t.value!=="delivered-history"&&Xt(n,`unknown retention policy ${t.value}`),this.atKind("newline")||Xt(n,"retain accepts exactly one policy word"),this.newline(),{policy:t.value,site:n}}parseImmutable(){let n=this.take("immutable"),t=[this.word().value];for(;this.maybe(",");)t.push(this.word().value);return this.newline(),{columns:t,site:n}}parseFinalExists(){let n=this.take("after");this.take("insert");let t=this.parseFocalRuleValue("after insert",n);return t.kind!=="exists"&&Y(t.site,"after insert requires exactly one exists predicate"),this.newline(),{value:t,site:n}}parseColumn(){let n=this.word();this.take(":");let t=this.parseType();return t.kind==="cursor"&&Y(n,"cursor is an operation argument type, not a table column","use c: cursor ? on a query"),this.newline(),{name:n.value,type:t,site:n}}parseIndex(n){let t=this.take(n?"unique":"by"),i;this.atKind("word")&&this.peek(1).value===":"&&(i=this.word().value,this.take(":"));let r=[this.word().value];for(;this.maybe(",");)r.push(this.word().value);this.newline();let s=`by${r.map(Qd).join("")}`;return{name:i??s,columns:r,unique:n,site:t}}parseMaintain(){let n=this.take("maintain"),t=this.word().value;this.take("=");let i=this.word();i.value!=="count"&&i.value!=="sum"&&Ge(i,`maintain ${i.value}`,"use maintain name = count table by columns or maintain name = sum table of intColumn by columns");let r=this.word().value,s;i.value==="sum"&&(this.take("of"),s=this.word().value),this.take("by");let o=[this.word().value];for(;this.maybe(",");)o.push(this.word().value);this.take(":"),this.newline(),this.takeKind("indent");let a,u;for(;!this.atKind("dedent")&&!this.atKind("eof")&&(this.skipNewlines(),!this.atKind("dedent"));)try{let c=this.word();c.value!=="read"&&c.value!=="readable"&&Y(c,`unknown maintain property ${c.value}`);let l=this.parseFocalRuleValue(c.value,c);this.newline();let f={effect:"read",bindings:[],value:l,site:c};c.value==="read"?a=f:u=f}catch(c){this.capture(c),this.recoverLine()}return this.takeKind("dedent"),a||Y(n,`maintain ${t} requires read <- rule`),{name:t,aggregate:i.value,source:r,...s?{column:s}:{},by:o,read:a,...u?{readable:u}:{},site:n}}parseEffect(){let n=this.take("effect"),t=this.generatedBinding("effect");this.take("from");let i=this.word().value;return this.newline(),{name:t,module:i,site:n}}parseRule(){let n=this.word(),t=n.value,i=[],r;if(this.at("(")){for(this.take("("),i=[this.generatedBinding("rule")];this.maybe(",");)i.push(this.generatedBinding("rule"));this.take(")"),(t!=="update"||i.length!==2)&&Y(n,`${t} rules use <- for one row; only update (old, next) has named bindings`,`rewrite the ${t} rule with <- and direct .field terms`),this.take("<-"),r=this.expression(0,new Set(["<newline>"]))}else r=this.parseFocalRuleValue(t,n);return this.newline(),{effect:t,bindings:i,value:r,site:n}}parseFocalRuleValue(n,t){if(this.maybe("<-"))return this.expression(0,new Set(["<newline>"]));let i=this.word().value;this.take("<-");let r=this.expression(0,new Set(["<newline>"]));Y(t,`${n} rules use the focal row . and do not take a named single-row binding`,`${n} <- ${te(Ne(r,i))}`)}parseChannel(){let n=this.take("channel"),t=this.generatedBinding("channel"),i=this.parseArgs();this.take(":"),this.newline(),this.takeKind("indent");let r,s,o;for(;!this.atKind("dedent")&&!this.atKind("eof")&&(this.skipNewlines(),!this.atKind("dedent"));)try{let a=this.word();if(a.value==="publish"||a.value==="subscribe"){this.take("<-");let u=this.expression(0,new Set(["<newline>"]));a.value==="publish"?r=u:s=u}else if(a.value==="ttl"){let u=this.number();this.at("s")&&this.take("s"),o=u}else Y(a,`unknown channel property ${a.value}`);this.newline()}catch(a){this.capture(a),this.recoverLine()}return this.takeKind("dedent"),r||Y(n,`channel ${t} requires publish <- ...`),s||Y(n,`channel ${t} requires subscribe <- ...`),o===void 0&&Y(n,`channel ${t} requires ttl Ns`),{name:t,args:i,publish:r,subscribe:s,ttlSeconds:o,site:n}}parseProgram(){let n=this.word(),t=n.value,i=this.generatedBinding("operation"),r=this.parseArgs();this.at("->")&&Ge(this.peek(),"result annotations","results are inferred; remove the annotation"),this.take(":"),this.newline();let s=this.parseBlock();return s.length===0&&Y(n,`${t} ${i} has an empty body`),{kind:t,name:i,args:r,body:s,site:n}}parseShapeDeclaration(){let n=this.take("shape"),t=this.generatedBinding("shape");this.take("="),this.take("{");let i=this.parseShapeFields();return this.take("}"),this.newline(),{name:t,fields:i,site:n}}generatedBinding(n){let t=this.word();return Kd.has(t.value)&&I(t,`${n} name ${t.value} is reserved and cannot become a generated TypeScript binding`,`rename the ${n} ${t.value} to an identifier that is not reserved by JavaScript`),t.value}parseArgs(){this.take("(");let n=[];for(;!this.at(")");){let t=this.peek(),i=this.generatedBinding("argument");if(this.take(":"),n.push({name:i,type:this.parseType(),site:t}),!this.maybe(","))break}return this.take(")"),n}parseType(){let n=this.peek(),t;if(this.maybe("[")){let i=this.parseType();this.take("]"),this.take("<="),t={kind:"list",item:i,max:this.number(),optional:!1}}else{let i=this.word();if(i.value==="text"){let r,s;this.maybe("<=")?s=this.number():(r=this.number(),this.take("."),this.take("."),s=this.number());let o;if(this.maybe("format")){let a=this.word();a.value!=="handle"&&a.value!=="url"&&Y(a,`unknown text format ${a.value}`),o=a.value}t={kind:"text",...r===void 0?{}:{min:r},max:s,...o?{format:o}:{},optional:!1}}else if(i.value==="decimal")t={kind:"decimal",scale:this.scale("decimal 12"),optional:!1};else if(i.value==="money"){let r=this.word();/^[A-Z]{3}$/.test(r.value)||Y(r,"money currency must be exactly three uppercase letters","use money USD or money USD 2");let s=this.atKind("number");t={kind:"money",currency:r.value,scale:s?this.scale(`money ${r.value} 12`):2,...s?{explicitScale:!0}:{},optional:!1}}else if(["json","bytes","image","video"].includes(i.value))this.take("<="),t={kind:i.value,max:this.number(),optional:!1};else if(["cursor","id","principal","int","time","bool"].includes(i.value))t={kind:i.value,optional:!1};else if(i.value==="enum"){this.take("(");let r=[];for(;!this.at(")")&&(r.push(this.takeKind("string").value),!!this.maybe(",")););this.take(")"),t={kind:"enum",variants:r,optional:!1}}else t={kind:"ref",table:i.value,optional:!1}}return this.maybe("?")&&(t={...t,optional:!0}),t.kind==="list"&&t.item.optional&&Y(n,"list element types cannot be optional"),t}parseBlock(){this.takeKind("indent");let n=[];for(;!this.atKind("dedent")&&!this.atKind("eof")&&(this.skipNewlines(),!this.atKind("dedent"));)try{n.push(this.parseStatement())}catch(t){this.capture(t),this.recoverStatement()}return this.takeKind("dedent"),n}parseStatement(){if(this.at("while")&&Ge(this.peek(),"while","use a bounded for domain or walk"),this.at("if"))return this.parseIf();if(this.at("for"))return this.parseFor();if(this.at("match"))return this.parseMatch();if(this.at("require"))return this.parseRequire();if(this.at("return")){let t=this.take("return"),i=this.expression(0,new Set(["<newline>"]));return i.kind!=="merge"&&this.newline(),{kind:"return",value:i,site:t}}if(this.at("emit")){let t=this.take("emit"),i=this.word().value,r=this.expression(0,new Set(["<newline>"]));return this.newline(),{kind:"emit",effect:i,payload:r,site:t}}if((this.at("device")||this.at("oblivious"))&&Ge(this.peek(),this.peek().value,"pass an explicit bounded argument to the operation"),this.atKind("word")&&this.peek(1).value==="="){let t=this.peek(),i=this.generatedBinding("local");this.take("=");let r=this.expression(0,new Set(["<newline>"]));return r.kind!=="merge"&&this.newline(),{kind:"bind",names:[i],value:r,site:t}}if(this.at("(")&&this.tupleBindingAhead()){let t=this.take("("),i=[this.generatedBinding("local")];for(;this.maybe(",");)i.push(this.generatedBinding("local"));this.take(")"),this.take("=");let r=this.expression(0,new Set(["<newline>"]));return this.newline(),{kind:"bind",names:i,value:r,site:t}}let n=this.expression(0,new Set(["<newline>"]));return n.kind!=="merge"&&this.newline(),{kind:"expr",value:n,site:n.site}}parseIf(){let n=this.take("if"),t=this.expression(0,new Set([":"]));this.take(":"),this.newline();let i=this.parseBlock(),r=[];return this.at("else")&&(this.take("else"),this.take(":"),this.newline(),r=this.parseBlock()),{kind:"if",condition:t,thenBody:i,elseBody:r,site:n}}parseFor(){let n=this.take("for"),t=this.generatedBinding("loop");this.take("in");let i=this.expression(0,new Set([":"]));return this.take(":"),this.newline(),{kind:"for",name:t,domain:i,body:this.parseBlock(),site:n}}parseRequire(){let n=this.take("require"),t=this.expression(0,new Set(["else"]));this.take("else");let i=this.word().value;return this.newline(),{kind:"require",condition:t,code:i,site:n}}parseMatch(){let n=this.take("match"),t=this.expression(0,new Set([":"]));(t.kind!=="read"||t.range)&&Y(t.site,"match requires a point read t[key]"),this.take(":"),this.newline(),this.takeKind("indent"),this.take("some");let i=this.generatedBinding("match");this.take(":"),this.newline();let r=this.parseBlock();this.take("none"),this.take(":"),this.newline();let s=this.parseBlock();return this.takeKind("dedent"),{kind:"match",read:t,someName:i,someBody:r,noneBody:s,site:n}}expression(n=0,t=new Set){let i=this.prefix(t);for(;;){let r=this.peek();if(this.isStop(r,t))break;let s=Su.get(r.value);if(s===void 0||s<n)break;this.position+=1;let o=this.expression(s+(r.value==="??"?0:1),t);i={kind:"binary",op:r.value,left:i,right:o,site:r}}return i}prefix(n){let t=this.peek();if(t.value==="not")return this.position+=1,this.postfix({kind:"unary",op:"not",value:this.expression(7,n),site:t},n);if(t.value==="-"&&!(this.peek(1).kind==="word"&&this.peek(2).value==="["))return this.position+=1,this.postfix({kind:"unary",op:"-",value:this.expression(7,n),site:t},n);if(t.value==="exists"){this.position+=1;let r=this.prefix(n);return(r.kind!=="read"||r.range)&&Y(r.site,"exists requires an indexed read t[key]"),{kind:"exists",read:r,site:t}}if(t.value==="created"){this.position+=1;let r=this.prefix(n);return(r.kind!=="read"||r.range)&&Y(r.site,"created requires an indexed read t[key]"),{kind:"created",read:r,site:t}}if(t.value==="walk")return this.parseWalk();if(["insert","update","upsert","delete"].includes(t.value))return this.parseWrite();if((t.value==="+"&&(this.peek(1).kind==="word"||this.peek(1).value==="~")||t.value==="~"||t.value==="-"&&this.peek(1).kind==="word"&&this.peek(2).value==="[")&&Y(t,"write sigils are invalid; use insert, update, upsert, or delete","use insert, update, upsert, or delete"),t.value==="#"){this.position+=1;let r=this.word(),s=this.parseRead(r.value,r);return{kind:"aggregate",table:r.value,keys:s.keys,site:t}}if(t.value==="merge")return this.parseMerge();(t.value==="device"||t.value==="oblivious")&&Ge(t,t.value,"pass an explicit bounded argument to the operation");let i;if(t.kind==="string")this.position+=1,i={kind:"literal",value:t.value,site:t};else if(t.kind==="number")this.position+=1,i={kind:"literal",value:Number(t.value),numericText:t.value,site:t};else if(t.value==="true"||t.value==="false"||t.value==="null")this.position+=1,i={kind:"literal",value:t.value==="null"?null:t.value==="true",site:t};else if(t.value===".")this.position+=1,i={kind:"focal",site:t},this.atKind("word")&&(i={kind:"member",base:i,name:this.word().value,site:t});else if(t.value==="["){this.position+=1;let r=[];for(;!this.at("]")&&(r.push(this.expression(0,new Set([",","]"]))),!!this.maybe(",")););this.take("]"),i={kind:"array",items:r,site:t}}else if(t.value==="{")i={kind:"object",fields:this.parseObjectFields(),site:t};else if(t.value==="("){this.position+=1;let r=this.expression(0,new Set([",",")"]));if(this.maybe(",")){let s=[r];do s.push(this.expression(0,new Set([",",")"])));while(this.maybe(","));i={kind:"array",items:s,site:t}}else i=r;this.take(")")}else t.kind==="word"?(this.position+=1,i={kind:"name",name:t.value,site:t}):Y(t,`expected expression, got ${JSON.stringify(t.value)}`);return this.postfix(i,n)}postfix(n,t){let i=n;for(;;)if(this.at(".")&&this.peek(1).kind==="word"){let r=this.take("."),s=this.word().value;i={kind:"member",base:i,name:s,site:r}}else if(this.at("(")&&i.kind==="name"){let r=this.take("("),s=[];for(;!this.at(")")&&(s.push(this.expression(0,new Set([",",")"]))),!!this.maybe(",")););this.take(")"),i={kind:"call",name:i.name,args:s,site:r}}else if(this.at("[")&&i.kind==="name")i=this.parseRead(i.name,i.site);else if(i.kind==="read"&&this.at("where")){let r=this.take("where"),s=this.expression(0,new Set(["<newline>","{",",","}"]));i={...i,range:{...i.range,where:{predicate:s,site:r}}}}else if(i.kind==="read"&&this.at("before"))Ge(this.peek(),"before","use after c; reverse display order in the client when needed");else if(i.kind==="read"&&["after","first","last","by"].includes(this.peek().value))i=this.parseRange(i);else if(this.maybe("!")){let r=this.tokens[this.position-1],s="NOT_FOUND";this.maybe("else")&&(s=this.word().value),i={kind:"assert",value:i,code:s,site:r}}else if(this.at("{"))i=this.parseShape(i);else if(this.atKind("word")&&!Su.has(this.peek().value)&&!t.has(this.peek().value)&&!["else","some","none","for","in"].includes(this.peek().value)){let r=this.word();i={kind:"shapeUse",base:i,name:r.value,site:r}}else break;return i}parseRead(n,t){this.take("[");let i=[];for(;!this.at("]");){let r=this.peek(),s;this.atKind("word")&&this.peek(1).value==="="&&(s=this.word().value,this.take("="));let o=this.expression(0,new Set([",","]"]));if(i.push({column:s,value:o,site:r}),!this.maybe(","))break}return this.take("]"),{kind:"read",table:n,keys:i,site:t}}parseRange(n){let t,i,r,s,o=this.peek(),a=n.index,u=-1,c=new Set,l;for(;["after","first","last","by"].includes(this.peek().value);){let d=this.word(),p=d.value==="after"?0:d.value==="first"||d.value==="last"?1:2;if(!l&&(c.has(p)||p<u)&&(l=d),c.add(p),u=Math.max(u,p),d.value==="after"){let g=this.expression(0,new Set(["after","first","last","by","where","<newline>",":","{",",","}"]));r||(s=d.value,r=g)}else if(d.value==="first"||d.value==="last"){let g=this.number();i===void 0&&(t=d.value==="first"?"asc":"desc",i=g)}else if(d.value==="by"){let g=this.word().value;a||(a=g)}}if(i===void 0&&!r){let d={...n,index:a};return l&&Y(l,"read modifiers may appear once and only in canonical order",te(d)),d}(i===void 0||!t)&&Y(o,"range reads require first N or last N");let f={...n,index:a,range:{order:t,take:i,cursor:r,cursorKind:s,site:o}};return l&&Y(l,"read modifiers may appear once and only in canonical order",te(f)),f}parseMerge(){let n=this.take("merge"),t=this.word().value,i,r;this.at("before")&&Ge(this.peek(),"before","use after c in the merge header"),this.at("after")&&(r=this.word().value,i=this.expression(0,new Set(["first","last","by",":"])));let s=this.peek();!this.at("first")&&!this.at("last")&&Y(s,"merge modifiers use [after cursor] first|last N by index",`merge ${t} first 20 by index:`);let o=this.word().value==="first"?"asc":"desc",a=this.number();if(!this.at("by")){let l=i?` ${r} ${this.renderExpr(i)}`:"";Y(this.peek(),"merge requires by <index> in its header",`merge ${t}${l} ${o==="asc"?"first":"last"} ${a} by index:`)}this.take("by");let u=this.word().value;this.take(":"),this.newline(),this.atKind("indent")||Y(this.peek(),"merge requires an indented block with at least one [prefix] lane","[viewer]"),this.takeKind("indent");let c=[];for(;!this.atKind("dedent")&&!this.atKind("eof")&&(this.skipNewlines(),!this.atKind("dedent"));){let l=this.take("["),f=[];for(;!this.at("]")&&(f.push(this.expression(0,new Set([",","]"]))),!!this.maybe(",")););this.take("]");let d;if(this.maybe("for")){let p=this.generatedBinding("merge lane");this.take("in");let g=this.expression(0,new Set(["<newline>"]));(g.kind!=="read"||!g.range)&&Y(g.site,"a merge for lane requires a bounded range read","for row in table[prefix] first 50 by index"),d={name:p,domain:g}}this.newline(),c.push({prefix:f,...d?{loop:d}:{},site:l})}return this.takeKind("dedent"),c.length===0&&Y(n,"merge requires at least one lane","[viewer]"),{kind:"merge",table:t,index:u,order:o,take:a,cursor:i,cursorKind:r,lanes:c,site:n}}renderExpr(n){return te(n)}parseShape(n){let t=this.take("{"),i=this.parseShapeFields();return this.take("}"),{kind:"shape",base:n,fields:i,site:t}}parseShapeFields(){let n=[];for(;!this.at("}");){let t=this.peek();if(this.maybe("*"))n.push({kind:"spread",site:t});else if(this.at(".")&&this.peek(1).value==="."&&this.peek(2).value===".")this.take("."),this.take("."),this.take("."),n.push({kind:"namedSpread",name:this.word().value,site:t});else{let i=this.word().value;this.maybe(":")?n.push({kind:"field",name:i,value:this.expression(0,new Set([",","}"])),site:t}):n.push({kind:"bare",name:i,site:t})}if(!this.maybe(","))break}return n}parseWrite(){let n=this.word(),t=this.word().value,i=n.value,r=i==="insert"?[]:this.parseRead(t,n).keys,s=i==="delete"?[]:this.parseObjectFields();return{kind:"write",op:i,table:t,keys:r,fields:s,site:n}}parseObjectFields(){this.take("{");let n=[];for(;!this.at("}");){let t=this.word();if(n.push({name:t.value,value:this.maybe(":")?this.expression(0,new Set([",","}"])):void 0,site:t}),!this.maybe(","))break}return this.take("}"),n}parseWalk(){let n=this.take("walk"),t=this.word().value,i=this.parseRead(t,n);(i.keys.length!==1||i.keys[0].column)&&Y(i.site,"walk seed must be one positional reference t[seed]"),this.take("up"),this.take(".");let r=this.word().value;this.take("depth");let s=this.number();return{kind:"walk",table:t,seed:i.keys[0].value,column:r,depth:s,site:n}}tupleBindingAhead(){let n=this.position+1;if(this.tokens[n]?.kind!=="word")return!1;for(n+=1;this.tokens[n]?.value===",";){if(n+=1,this.tokens[n]?.kind!=="word")return!1;n+=1}return this.tokens[n]?.value===")"&&this.tokens[n+1]?.value==="="}isStop(n,t){return n.kind==="newline"||n.kind==="dedent"||n.kind==="eof"?!0:t.has(n.value)||t.has(`<${n.kind}>`)}endLine(n){this.atKind("newline")||Y(this.peek(),`unexpected token after declaration from line ${n.line}`),this.newline()}newline(){this.takeKind("newline")}skipNewlines(){for(;this.atKind("newline");)this.position+=1}number(){let n=this.takeKind("number");return/^\d+$/.test(n.value)||Y(n,"this position takes an integer literal"),Number(n.value)}scale(n){let t=this.peek(),i=this.number();return(i<0||i>12)&&Y(t,"decimal and money scales must be integers from 0 through 12",`use ${n}`),i}word(){return this.takeKind("word")}at(n){return this.peek().value===n}atKind(n){return this.peek().kind===n}maybe(n){return this.at(n)?(this.position+=1,!0):!1}take(n){let t=this.peek();return t.value!==n&&Y(t,`expected ${JSON.stringify(n)}, got ${JSON.stringify(t.value)}`),this.position+=1,t}takeKind(n){let t=this.peek();return t.kind!==n&&Y(t,`expected ${n}, got ${JSON.stringify(t.value)}`),this.position+=1,t}peek(n=0){return this.tokens[Math.min(this.position+n,this.tokens.length-1)]}capture(n){if(n instanceof xe)this.diagnostics.push(n.diagnostic);else throw n}recoverLine(){for(;!this.atKind("newline")&&!this.atKind("dedent")&&!this.atKind("eof");)this.position+=1;this.atKind("newline")&&(this.position+=1)}recoverStatement(){this.recoverLine()}recoverTopLevel(){this.recoverLine();let n=0,t=new Set(["use","table","maintain","channel","query","mutation","effect","shape","fn","cursor","schedule","index","unique","device","oblivious"]);for(;!this.atKind("eof");){if(this.atKind("indent")){n+=1,this.position+=1;continue}if(this.atKind("dedent")){n=Math.max(0,n-1),this.position+=1;continue}if(n===0&&this.atKind("word")&&t.has(this.peek().value))return;this.position+=1}}};function Ne(e,n){return e.kind==="name"?e.name===n?{kind:"focal",site:e.site}:e:e.kind==="unary"?{...e,value:Ne(e.value,n)}:e.kind==="binary"?{...e,left:Ne(e.left,n),right:Ne(e.right,n)}:e.kind==="member"?{...e,base:Ne(e.base,n)}:e.kind==="call"?{...e,args:e.args.map(t=>Ne(t,n))}:e.kind==="array"?{...e,items:e.items.map(t=>Ne(t,n))}:e.kind==="object"?{...e,fields:e.fields.map(t=>({...t,value:t.value&&Ne(t.value,n)}))}:e.kind==="read"?{...e,keys:e.keys.map(t=>({...t,value:Ne(t.value,n)})),range:e.range&&{...e.range,cursor:e.range.cursor&&Ne(e.range.cursor,n),where:e.range.where&&{...e.range.where,predicate:Ne(e.range.where.predicate,n)}}}:e.kind==="exists"||e.kind==="created"?{...e,read:Ne(e.read,n)}:e.kind==="aggregate"?{...e,keys:e.keys.map(t=>({...t,value:Ne(t.value,n)}))}:e.kind==="assert"?{...e,value:Ne(e.value,n)}:e.kind==="shapeUse"?{...e,base:Ne(e.base,n)}:e.kind==="shape"?{...e,base:Ne(e.base,n),fields:e.fields.map(t=>t.kind==="field"?{...t,value:Ne(t.value,n)}:t)}:e.kind==="walk"?{...e,seed:Ne(e.seed,n)}:e.kind==="write"?{...e,keys:e.keys.map(t=>({...t,value:Ne(t.value,n)})),fields:e.fields.map(t=>({...t,value:t.value&&Ne(t.value,n)}))}:e}function Qd(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}var Hd="use an index whose prefix pins the predicate, a table invariant (after insert <- exists ...), or merge for a fan-in feed";function Tu(e,n){let t=[];for(let i of e)for(let r of i.programs)_t(r.body,s=>{s.kind!=="read"||!s.range?.where||t.push(...zd(s,n))});return t}function zd(e,n){let t=e.range.where;if(!e.range?.order||!Number.isInteger(e.range.take))return[Nt(t.site)];let i=n.get(e.table),r=hs(t.predicate),s=i&&Wd(e,i.indexes);if(!i||!r||!s)return[Nt(t.site)];let o=s.columns.slice(0,e.keys.length),a=s.columns.slice(e.keys.length),u=[],c=[],l=new Map;for(let b of r){let S=i.columns.get(b.column);if(!S||!Jd(S))return[Nt(t.site)];let E=te(b.value),k=l.get(b.column);if(k!==void 0){if(k!==E)return[Nt(t.site)];continue}l.set(b.column,E);let $=o.indexOf(b.column);if($>=0){if(te(e.keys[$].value)!==E)return[Nt(t.site)];continue}u.push(b.column),c.push(b.value)}let f=[...o,...u],d=i.indexes.find(b=>Gd(b)&&f.every((S,E)=>b.columns[E]===S)),p,g,m;if(d)p=d,g=$u(d),m=`where repair reuses ${e.table}.${d.name} for the read at ${Au(t.site)}`;else{let b=new Set(u),S=[...f,...a.filter($=>!b.has($))],E=s.unique;if(!E&&S.at(-1)!=="id"&&S.push("id"),S.length>8)return[Nt(t.site)];p={name:Yd(S,i.indexes),columns:S,unique:E,site:s.site},g=$u(p),m=`where needs this index for the read at ${Au(t.site)}`}let y={...e,keys:[...e.keys,...c.map(b=>({value:b,site:b.site}))],index:p.name,range:{...e.range,where:void 0}};return[Es(p.site,m,g),Es(t.site,"where is refused; use the indexed prefix scan in this rewrite",te(y))]}function Wd(e,n){if(e.index)return n.find(r=>r.name===e.index&&e.keys.every((s,o)=>s.column===void 0||s.column===r.columns[o]));let t=e.keys.some(r=>r.column!==void 0);if(t&&e.keys.some(r=>r.column===void 0))return;let i=n.filter(r=>r.name!=="byId"&&r.columns.length>e.keys.length&&(!t||e.keys.every((s,o)=>s.column===r.columns[o])));return i.length===1?i[0]:void 0}function hs(e){if(e.kind==="binary"&&e.op==="and"){let n=hs(e.left),t=hs(e.right);return n&&t?[...n,...t]:void 0}if(!(e.kind!=="binary"||e.op!=="="||e.left.kind!=="member"||e.left.base.kind!=="focal"))return[{column:e.left.name,value:e.right}]}function Jd(e){let n=e.kind==="list"?e.item:e;return e.kind!=="list"&&n.kind!=="json"}function Gd(e){return e.unique||e.columns.at(-1)==="id"}function Yd(e,n){let i=`by${(e.at(-1)==="id"?e.slice(0,-1):e).map(Xd).join("")||"Repair"}`,r=new Set(n.map(o=>o.name));if(!r.has(i))return i;let s=2;for(;r.has(`${i}${s}`);)s+=1;return`${i}${s}`}function $u(e){return`${e.unique?"unique":"by"} ${e.name}: ${e.columns.join(", ")}`}function Es(e,n,t){return{...e,code:"E_QUARRY_UNSUPPORTED",message:n,rewrite:t,guide:"quarry/refusals"}}function Nt(e){return Es(e,"where is not part of the Snapback 2 platform",Hd)}function _t(e,n){for(let t of e)t.kind==="bind"||t.kind==="expr"||t.kind==="return"?le(t.value,n):t.kind==="require"?le(t.condition,n):t.kind==="emit"?le(t.payload,n):t.kind==="if"?(le(t.condition,n),_t(t.thenBody,n),_t(t.elseBody,n)):t.kind==="for"?(le(t.domain,n),_t(t.body,n)):(le(t.read,n),_t(t.someBody,n),_t(t.noneBody,n))}function le(e,n){n(e),e.kind==="unary"||e.kind==="assert"?le(e.value,n):e.kind==="binary"?(le(e.left,n),le(e.right,n)):e.kind==="member"||e.kind==="shapeUse"?le(e.base,n):e.kind==="call"?e.args.forEach(t=>le(t,n)):e.kind==="array"?e.items.forEach(t=>le(t,n)):e.kind==="object"?e.fields.forEach(t=>t.value&&le(t.value,n)):e.kind==="read"?(e.keys.forEach(t=>le(t.value,n)),e.range?.cursor&&le(e.range.cursor,n)):e.kind==="merge"?(e.cursor&&le(e.cursor,n),e.lanes.forEach(t=>{t.prefix.forEach(i=>le(i,n)),t.loop&&le(t.loop.domain,n)})):e.kind==="exists"||e.kind==="created"?le(e.read,n):e.kind==="aggregate"?e.keys.forEach(t=>le(t.value,n)):e.kind==="shape"?(le(e.base,n),e.fields.forEach(t=>t.kind==="field"&&le(t.value,n))):e.kind==="walk"?le(e.seed,n):e.kind==="write"&&(e.keys.forEach(t=>le(t.value,n)),e.fields.forEach(t=>t.value&&le(t.value,n)))}function Xd(e){return e&&e[0].toUpperCase()+e.slice(1)}function Au(e){return`${e.file}:${e.line}:${e.col}`}function ks(e){let n=[],t=[];for(let f of e){let d=wu(f.fileName,f.source);t.push(d.document),n.push(...d.diagnostics)}if(n.push(...Zd(t)),n.length>0)return{ok:!1,diagnostics:n.map(ai)};let i=Xa(t);if(t=i.documents,n.push(...i.diagnostics),n.length>0)return{ok:!1,diagnostics:n.map(ai)};let r;try{ef(t),r=Ha(t)}catch(f){return{ok:!1,diagnostics:[ai(xs(f,e[0]?.fileName))]}}if(n.push(...Tu(t,r)),n.length>0)return{ok:!1,diagnostics:n.map(ai)};let s=t.find(f=>Nn(f.file)==="schema.q"),o=e.find(f=>f.fileName===s.file),a="";try{a=tu(t,r,s.file)}catch(f){n.push(xs(f,s.file))}let u=new Map;for(let f of t.filter(d=>Nn(d.file)!=="schema.q")){let d=!0;for(let p of f.programs)try{ys([p],r,f.file,f.effects)}catch(g){d=!1,n.push(xs(g,f.file))}d&&u.set(f.file,ys(f.programs,r,f.file,f.effects))}if(n.length>0)return{ok:!1,diagnostics:n.map(ai)};let c=Nu(o.path.replace(/\.q$/,".ts"),s.file,a,o.source),l=t.filter(f=>Nn(f.file)!=="schema.q").map(f=>{let d=e.find(p=>p.fileName===f.file);return Nu(d.path.replace(/\.q$/,".ts"),f.file,u.get(f.file),d.source)});return{ok:!0,schema:c,modules:l}}function _u(e,n,t=!1){let i=nf(e.site),r=i&&Mu(n,i.line);return r?{...e,site:`${r.file}:${r.line}:${r.col}`,message:t?`in code generated from ${r.file}: ${e.message}`:e.message,rewrite:e.code==="E_DECIMAL_SCALE"?tf(n.authoredSource,r.line,e.message):t&&e.message.includes("undefined")?"add ! else CODE to assert the possibly absent Quarry value before using it here":n.authoredSource}:e}function Ou(e,n){return Mu(n,e.line)??e}function Cu(e){return e.map(n=>({file:n.authored,generated:Nn(n.path),source:n.source}))}function Zd(e){let n=[],t=e.find(i=>Nn(i.file)==="schema.q");t||n.push(tt(e[0]?.file??"snapback/schema.q",1,1,"a Quarry project requires snapback/schema.q","create snapback/schema.q and move schema declarations into it"));for(let i of e){let r=Nn(i.file)==="schema.q",s=i.tables[0]?.site??i.maintains[0]?.site??i.channels[0]?.site??(i.identity?{file:i.file,line:1,col:1}:void 0);if(!r&&s&&n.push(tt(i.file,s.line,s.col,"tables, maintains, channels, and use identity belong in schema.q","move this declaration to snapback/schema.q")),r&&i.shapes.length>0){let a=i.shapes[0].site;n.push(tt(i.file,a.line,a.col,"shape declarations belong in an operations .q module, not schema.q","move this shape declaration to snapback/<module>.q"))}if(r&&(i.programs.length>0||i.effects.length>0)){let a=i.programs[0]?.site??i.effects[0].site;n.push(tt(i.file,a.line,a.col,"schema.q holds declarations only; query, mutation, and effect declarations belong in a program module","move this declaration to snapback/<module>.q"))}!r&&i.programs.length===0&&n.push(tt(i.file,1,1,`${Nn(i.file)} must declare at least one query or mutation`,"add a query or mutation, or remove the empty module"));let o=Nn(i.file).slice(0,-2);/^[A-Za-z_$][A-Za-z0-9_$-]*$/.test(o)||n.push(tt(i.file,1,1,`file stem ${o} cannot become an API namespace`,"rename the module to an identifier-like stem"))}return t&&t.tables.length===0&&n.push(tt(t.file,1,1,"schema.q must declare at least one table","add a table declaration")),n}function ef(e){let n=e.find(t=>Nn(t.file)==="schema.q");for(let t of n.maintains){if(n.tables.some(l=>l.name===t.name))throw new xe(t.site,`maintain target ${t.name} duplicates a table`);let i=n.tables.find(l=>l.name===t.source);if(!i)throw new xe(t.site,`maintain ${t.name} names unknown source table ${t.source}`);let r=t.by.map(l=>{let f=i.columns.find(d=>d.name===l);if(!f)throw new xe(t.site,`maintain ${t.name} names unknown source column ${t.source}.${l}`);return{name:l,type:structuredClone(f.type),site:t.site}});if(t.aggregate==="sum"){let l=i.columns.find(f=>f.name===t.column);if(!l||!["int","decimal","money"].includes(l.type.kind))throw new xe(t.site,`sum maintain ${t.name} requires an int, decimal, or money source column`)}let s=t.aggregate==="sum"?i.columns.find(l=>l.name===t.column).type:{kind:"int",optional:!1};r.push({name:"value",type:structuredClone(s),site:t.site});let o=`by${t.by.map(l=>rf(l.endsWith("Id")&&l.length>2?l.slice(0,-2):l)).join("")}`,a=l=>({effect:l,bindings:["r"],value:{kind:"name",name:"deny",site:t.site},site:t.site}),u=r.some(l=>Iu(l.type)),c={name:t.name,columns:r,indexes:u?[]:[{name:o,columns:[...t.by],unique:!0,site:t.site}],rules:[t.read,a("insert"),a("update"),a("delete")],immutable:[],finalExists:[],site:t.site};n.tables.push(c)}}function Iu(e){return e.kind==="image"||e.kind==="video"?!0:e.kind==="list"&&Iu(e.item)}function Nu(e,n,t,i){let r=[],s;for(let o of t.split(`
18
+ `)){let a=o.match(/\/\/ q:(.+):(\d+):(\d+)\s*$/);a&&(s={file:a[1],line:Number(a[2]),col:Number(a[3])}),r.push(s)}return{path:e,fileName:e,source:t,authored:n,authoredSource:i,lineMap:r}}function ai(e){return{code:e.code,family:"quarry",message:e.message,site:`${e.file}:${e.line}:${e.col}`,rewrite:`-- ${e.rewrite.replace(/\n/g," ")}`,guide:e.guide}}function xs(e,n="snapback/schema.q"){return e instanceof xe?e.diagnostic:{file:n,line:1,col:1,code:"E_QUARRY_UNKNOWN",message:e instanceof Error?e.message:String(e),rewrite:"fix the named Quarry declaration",guide:"quarry/names"}}function tt(e,n,t,i,r){return{file:e,line:n,col:t,code:"E_QUARRY_PLACEMENT",message:i,rewrite:r,guide:"quarry/projects"}}function nf(e){let n=e.match(/^(.*):(\d+):(\d+)$/);return n?{file:n[1],line:Number(n[2]),col:Number(n[3])}:void 0}function Mu(e,n){for(let t=Math.min(n-1,e.lineMap.length-1);t>=0;t-=1){let i=e.lineMap[t];if(i)return i}}function tf(e,n,t){let i=e.replace(/\r\n?/g,`
19
+ `).split(`
20
+ `)[n-1]?.trimEnd();return i?`${i} -- ${t}`:`-- ${t}`}function rf(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}import{basename as vu,dirname as Ru,isAbsolute as sf,relative as of,resolve as Wi,sep as zi}from"node:path";import He from"typescript";function Du(e,n,t,i){let r=Wi(Ru(e),"__snapback2_lib.d.ts"),s=new Map([[e,n],[r,i],...t]),o={module:He.ModuleKind.ESNext,moduleResolution:He.ModuleResolutionKind.Bundler,noEmit:!0,noLib:!0,strict:!0,target:He.ScriptTarget.ES2022,types:[]},a=He.createCompilerHost(o,!0);a.resolveModuleNameLiterals=(d,p,g,m)=>d.map(y=>{let b=y.text;return b==="snapback2"||b.startsWith("snapback2/")?{resolvedModule:void 0}:He.resolveModuleName(b,p,m,a)});let u=a.getSourceFile.bind(a),c=a.readFile.bind(a),l=a.fileExists.bind(a);a.fileExists=d=>s.has(d)||l(d),a.readFile=d=>s.get(d)??c(d),a.getSourceFile=(d,p,g,m)=>{let y=s.get(d);return y===void 0?u(d,p,g,m):He.createSourceFile(d,y,p,!0)};let f=He.createProgram([...s.keys()],o,a);return{program:f,checker:f.getTypeChecker()}}function Lu(e,n){let t=e.getTypeChecker();return He.getPreEmitDiagnostics(e).flatMap(i=>{if(!i.file||i.file.fileName.endsWith("__snapback2_lib.d.ts"))return[];if(i.file.fileName.includes(`${zi}node_modules${zi}`))return[];if(!Wi(i.file.fileName).startsWith(`${Wi(n)}${zi}`))return[];if(af(i)||uf(i,t))return[];let r=i.start===void 0?{line:0,character:0}:i.file.getLineAndCharacterOfPosition(i.start),s=lf(n,i.file.fileName),o=He.flattenDiagnosticMessageText(i.messageText,`
21
+ `),a=i.start===void 0?i.file:ot(i.file,i.start),u=vi(a,s);return[qe(u.code,u.family,s,r.line+1,r.character+1,o,cf(i.file,a,o),u.guide)]})}function af(e){if(!e.file||e.start===void 0)return!1;let n=ot(e.file,e.start),t=Ss(n,He.isVariableDeclaration),i=t?.initializer&&N(t.initializer);return!!i&&B(i)==="table"&&He.isIdentifier(t.name)&&n.getText()===t.name.text}function uf(e,n){if(e.code!==2454||!e.file||e.start===void 0||vu(e.file.fileName)!=="schema.ts"||vu(Ru(e.file.fileName))!=="snapback")return!1;let t=ot(e.file,e.start);if(!He.isIdentifier(t))return!1;let i=n.getSymbolAtLocation(t)?.valueDeclaration;if(!i||!He.isVariableDeclaration(i)||i.getSourceFile()!==e.file)return!1;let r=Ss(i,He.isVariableStatement),s=i.initializer&&N(i.initializer);return!!r&&Pe(r)&&!!s&&B(s)==="table"}function Ss(e,n){let t=e;for(;t;){if(n(t))return t;t=t.parent}}function cf(e,n,t){let i=Ss(n,He.isStatement);if(i)return`${i.getText(e)}
22
+ // Fix the TypeScript error above: ${t.split(`
23
+ `)[0]}`;let r=e.getLineAndCharacterOfPosition(n.getStart(e)),s=e.getLineStarts(),o=s[r.line]??0,a=s[r.line+1]??e.text.length;return`${e.text.slice(o,a).trimEnd()}
24
+ // Fix the TypeScript error above: ${t.split(`
25
+ `)[0]}`}function lf(e,n){return of(e,sf(n)?n:Wi(n)).split(zi).join("/")}import ze from"typescript";var Ct=class{constructor(n){this.text=n}};function Ot(e,n=new Map){let t=h(e);if(t.kind===ze.SyntaxKind.NullKeyword)return null;let i=$n(t);if(i!==void 0)return i;if(ze.isNumericLiteral(t))return new Ct(t.getText());if(ze.isPrefixUnaryExpression(t)&&t.operator===ze.SyntaxKind.MinusToken&&ze.isNumericLiteral(t.operand))return new Ct(`-${t.operand.getText()}`);let r=q(t);if(r!==void 0)return r;if(ze.isIdentifier(t))return n.get(t.text);if(ze.isArrayLiteralExpression(t)){let s=[];for(let o of t.elements){if(ze.isSpreadElement(o))return;let a=Ot(o,n);if(a===void 0)return;s.push(a)}return s}if(ze.isObjectLiteralExpression(t)){let s=Object.create(null);for(let o of t.properties){if(ze.isSpreadAssignment(o)){let c=Ot(o.expression,n);if(!c||typeof c!="object"||Array.isArray(c))return;Object.assign(s,c);continue}let a=ze.isPropertyAssignment(o)?{name:H(o.name),value:o.initializer}:ze.isShorthandPropertyAssignment(o)?{name:o.name.text,value:o.name}:void 0;if(!a?.name)return;let u=Ot(a.value,n);if(u===void 0)return;s[a.name]=u}return s}}function Pu(e){let n=new Map;for(let t of e.statements)if(!(!ze.isVariableStatement(t)||!(t.declarationList.flags&ze.NodeFlags.Const)))for(let i of t.declarationList.declarations){if(!ze.isIdentifier(i.name)||!i.initializer)continue;let r=Ot(i.initializer,n);r!==void 0&&n.set(i.name.text,r)}return n}function Fu(e,n,t,i,r,s,o){if(!r||typeof r!="object"||Array.isArray(r)){o.push(L(e,"E_SEED_ROW",n,`seed ${t}[${i}] must be an object with a string id`,e.source));return}let a=r;(typeof a.id!="string"||a.id.length===0)&&o.push(L(e,"E_SEED_ROW",n,`seed ${t}[${i}].id must be a non-empty string`,e.source));for(let u of Object.keys(a))Object.hasOwn(s,u)||o.push(L(e,"E_SEED_VALUE",n,`seed ${t}[${i}] has unknown column ${u}`,e.source));for(let[u,c]of Object.entries(s)){if(!Object.hasOwn(a,u)){pf(c)||o.push(L(e,"E_SEED_VALUE",n,`seed ${t}[${i}] is missing required column ${u}`,e.source));continue}let l=ws(a[u],c,`${t}[${i}].${u}`);l.mismatch?o.push(L(e,l.mismatch.code,n,l.mismatch.message,l.mismatch.rewrite??e.source)):a[u]=l.value}}function ke(e){return{code:"E_SEED_VALUE",message:e}}function ws(e,n,t){if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;if(s.Decimal||s.Money)return df(e,s,t);if("Optional"in s)return e===null?{value:null}:ws(e,s.Optional,t);if(s.List){if(!Array.isArray(e))return{mismatch:ke(`${t} must be a list`)};if(e.length>s.List.max)return{mismatch:ke(`${t} exceeds list max ${s.List.max}`)};let o=[];for(let a=0;a<e.length;a+=1){let u=ws(e[a],s.List.of,`${t}[${a}]`);if(u.mismatch)return u;o.push(u.value)}return{value:o}}}let i=$s(e),r=As(i,n,t);return r?{mismatch:r}:{value:i}}function df(e,n,t){let i=e instanceof Ct?e.text:typeof e=="number"?String(e):typeof e=="string"?e:void 0,r=n.Decimal?`Decimal<${n.Decimal.scale}>`:`Money<${JSON.stringify(n.Money.currency)}, ${n.Money.scale}>`,s=Number((n.Decimal??n.Money).scale);if(i===void 0)return{mismatch:ke(`${t} must be a JSON number or decimal string in whole units`)};if(/[eE]/.test(i))return{mismatch:ke(`${t} refuses exponent notation; spell the whole-unit decimal directly`)};let o=i.match(/^(-?)(\d+)(?:\.(\d+))?$/);if(!o)return{mismatch:ke(`${t} must be a JSON number or decimal string in whole units`)};let a=o[3]??"";if(a.length>s)return{mismatch:ke(`${a.length} fractional digits, scale ${s}; ${r} cannot represent ${i}`)};let u=`${o[2]}${a.padEnd(s,"0")}`.replace(/^0+(?=\d)/,""),c=BigInt(`${o[1]}${u}`),l=9007199254740991n;return c<-l||c>l?{mismatch:ke(`${i} at scale ${s} is outside the safe integer wire range`)}:{value:Number(c)}}function $s(e){if(e instanceof Ct)return Number(e.text);if(Array.isArray(e))return e.map($s);if(e&&typeof e=="object"){let n=Object.create(null);for(let[t,i]of Object.entries(e))n[t]=$s(i);return n}return e}function As(e,n,t){if(n==="Id"||n==="Principal"||n&&typeof n=="object"&&"Ref"in n)return e===yt.systemPrincipalId?ke(`${t} cannot carry the reserved system principal`):typeof e=="string"&&e.length>0?void 0:ke(`${t} must be a non-empty string`);if(n==="Int"||n==="Time")return typeof e=="number"&&Number.isSafeInteger(e)?void 0:ke(`${t} must be an integer`);if(n==="Bool")return typeof e=="boolean"?void 0:ke(`${t} must be boolean`);if(!n||typeof n!="object"||Array.isArray(n))return ke(`${t} has an unsupported schema type`);let i=n;if(i.Text){if(typeof e!="string"||[...e].length>i.Text.max)return ke(`${t} must be text of at most ${i.Text.max} characters`);let r=ff(e);return r===void 0?void 0:ke(`${t} contains disallowed control character U+${r.toString(16).toUpperCase().padStart(4,"0")}`)}if(i.Bytes){let r=e&&typeof e=="object"&&!Array.isArray(e)?e:void 0,s=r?.Bytes;return r&&Object.keys(r).length===1&&typeof s=="string"&&/^(?:[0-9a-f]{2})*$/.test(s)&&s.length/2<=i.Bytes.max?void 0:ke(`${t} must be canonical lowercase base16 of at most ${i.Bytes.max} bytes`)}if(i.Json){let r=Ts(e,t);return r||(new TextEncoder().encode(JSON.stringify(e)).length<=i.Json.max_bytes?void 0:ke(`${t} JSON exceeds ${i.Json.max_bytes} bytes`))}if(i.Enum){let r=i.Enum.variants;return typeof e=="string"&&r.includes(e)?void 0:ke(`${t} must be one of ${r.map(String).join(", ")}`)}if(i.Decimal||i.Money)return ke(`${t} was not normalized from whole units`);if(i.Image||i.Video){let r=i.Image?"image":"video";return{code:"E_SCHEMA_ASSET_SEED",message:`${t} cannot seed a ${r} asset because seeds cannot mint ledger rows`,rewrite:"upload through the app; seeds cannot mint ledger rows"}}if("Optional"in i)return e===null?void 0:As(e,i.Optional,t);if(i.List){if(!Array.isArray(e))return ke(`${t} must be a list`);if(e.length>i.List.max)return ke(`${t} exceeds list max ${i.List.max}`);for(let r=0;r<e.length;r+=1){let s=As(e[r],i.List.of,`${t}[${r}]`);if(s)return s}return}return ke(`${t} has an unsupported schema type`)}function ff(e){for(let n of e){let t=n.codePointAt(0);if(t<32&&![9,10,13].includes(t))return t}}function pf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&"Optional"in e}function Ts(e,n){if(typeof e=="number")return Number.isSafeInteger(e)?void 0:ke(`${n} JSON numbers must be integers`);if(Array.isArray(e))for(let t=0;t<e.length;t+=1){let i=Ts(e[t],`${n}[${t}]`);if(i)return i}else if(e&&typeof e=="object")for(let[t,i]of Object.entries(e)){let r=Ts(i,`${n}.${t}`);if(r)return r}}function ju(e){return{...e,args:Object.fromEntries(Object.entries(e.args).sort(([n],[t])=>n.localeCompare(t))),body:Ns(e.body)}}function Ns(e,n=!1){if(Array.isArray(e))return e.map(r=>Ns(r));if(!e||typeof e!="object")return e;let t=Object.entries(e),i=n?t.sort(([r],[s])=>r.localeCompare(s)):t;return Object.fromEntries(i.map(([r,s])=>[r,Ns(s,["Object","Row","Map"].includes(r))]))}import{readFile as mf}from"node:fs/promises";import{basename as gf,relative as yf,resolve as bf,sep as hf}from"node:path";import yn from"typescript";var Bu=new Set(["query","mutation","table","channel","schema"]);async function qu(e,n,t){let i=[];n&&i.push(qe("E_QUARRY_ONLY","quarry","snapback/schema.ts",1,1,"backends are authored in Quarry; the schema is snapback/schema.q",`table items:
26
+ value: json <=1000
27
+ public`,"quarry/projects"));for(let r of t.sort()){let s=await mf(r,"utf8"),o=kf(e,r),a=yn.createSourceFile(r,s,yn.ScriptTarget.ES2022,!0),u={fileName:o,sourceFile:a},c=new Map;for(let l of a.statements)if(yn.isVariableStatement(l))for(let f of l.declarationList.declarations){if(!yn.isIdentifier(f.name)||!f.initializer)continue;let d=N(f.initializer),p=d&&tn(d,a);!d||!p||!Bu.has(p)||(c.set(f.name.text,{kind:p,call:d}),Pe(l)&&_s(i,u,o,f.name,f.name.text,p,d))}for(let l of a.statements)if(yn.isExportDeclaration(l)&&!l.moduleSpecifier&&l.exportClause&&yn.isNamedExports(l.exportClause))for(let f of l.exportClause.elements){let d=c.get(f.propertyName?.text??f.name.text);d&&_s(i,u,o,f.name,f.name.text,d.kind,d.call)}else if(yn.isExportAssignment(l)&&!l.isExportEquals){let f=N(l.expression),d=f&&tn(f,a),p=yn.isIdentifier(l.expression)?c.get(l.expression.text):void 0,g=f&&d&&Bu.has(d)?{kind:d,call:f}:p,m=p&&yn.isIdentifier(l.expression)?l.expression.text:"operation";g&&_s(i,u,o,l,m,g.kind,g.call)}}return i}function _s(e,n,t,i,r,s,o){e.push(L(n,"E_QUARRY_ONLY",i,Ef(t),xf(s,r,o)))}function Ef(e){return`queries and mutations are authored in Quarry (snapback/${gf(e,".ts")}.q); TypeScript modules may export effects only`}function xf(e,n,t){if(e==="query"||e==="mutation"){let i=z(t.arguments[0]),r=i?mn(i).entries.map(s=>`${s.name}: ${Os(s.value)}`):[];return`${e} ${n}(${r.join(", ")}):`}return e==="table"?`table ${n}:`:e==="channel"?`channel ${n}():`:`table items:
28
+ value: json <=1000
29
+ public`}function Os(e){let n=N(e);if(!n)return"json <=1000";let t=tn(n)??ye(n.expression)?.split(".").at(-1);if(t==="optional"&&n.arguments[0])return`${Os(n.arguments[0])} ?`;if(t==="id"||t==="principal"||t==="int"||t==="time"||t==="bool")return t;if(["text","json","bytes","image","video"].includes(t??""))return`${t} <=${X(n.arguments[0])??1e3}`;if(t==="ref")return ye(n.arguments[0])??"id";if(t==="list"&&n.arguments[0]){let i=z(n.arguments[1]),r=i&&X(_(i,"max"));return`[${Os(n.arguments[0])}] <=${r??100}`}return t==="enum"?`enum(${(n.arguments[0]&&yn.isArrayLiteralExpression(n.arguments[0])?n.arguments[0].elements.map(r=>q(r)).filter(r=>r!==void 0):[]).map(r=>JSON.stringify(r)).join(", ")})`:"json <=1000"}function kf(e,n){return yf(e,bf(n)).split(hf).join("/")}import A from"typescript";function zu(e,n,t,i,r){let s=new Map;for(let f of[...e.values()].sort((d,p)=>d.name.localeCompare(p.name))){let d=$f(n,f),p=d?.arguments[0]&&z(d.arguments[0]),g=p?Wu(p,t,f.kind==="mutation"):"{}",m=d?.arguments[1],y="unknown";if(m&&(A.isArrowFunction(m)||A.isFunctionExpression(m))){let S=t.getSignatureFromDeclaration(m);S&&(y=t.typeToString(t.getReturnTypeOfSignature(S),m,A.TypeFormatFlags.NoTruncation|A.TypeFormatFlags.InTypeAlias).replaceAll('import("snapback2").',""));let E=r.get(f.moduleName)??new Map,k=Af(m,p,E,t);k?.special&&(y=k.text)}let b=s.get(f.moduleName)??[];b.push(` readonly ${it(f.exportName)}: Op<${g}, ${y}>;`),s.set(f.moduleName,b)}let o=[...i.values()].sort((f,d)=>f.name.localeCompare(d.name)).map(wf).join(`
30
+ `),a=Sf(n,t),u=[...s].sort(([f],[d])=>f.localeCompare(d)).filter(([f])=>f!=="channels"||a.length===0).map(([f,d])=>` readonly ${it(f)}: {
31
+ ${d.join(`
32
+ `)}
33
+ };`).join(`
34
+ `),c=a.length===0?"":(()=>{let f=new Map(a.map(E=>[E.name,E])),d=[...e.values()].sort((E,k)=>E.name.localeCompare(k.name)).filter(E=>E.moduleName==="channels"),p=(s.get("channels")??[]).map((E,k)=>{let $=f.get(d[k].exportName);return $?E.replace(/;$/,` & Channel<${$.args}, unknown>;`):E}),g=new Set(d.map(E=>E.exportName)),m=a.filter(E=>!g.has(E.name)).map(E=>`${it(E.name)}: Channel<${E.args}, unknown>`),y=p.length===0?` readonly channels: { ${m.join("; ")} };`:` readonly channels: {
35
+ ${p.join(`
36
+ `)}
37
+ ${m.map(E=>` readonly ${E};`).join(`
38
+ `)}
39
+ };`,b=new Set([...s.keys(),"channels","op","then","toJSON"]),S=a.filter(E=>!b.has(E.name)).map(E=>` readonly ${it(E.name)}: Channel<${E.args}, unknown>;`);return[y,...S].join(`
40
+ `)})(),l=[u,c].filter(Boolean).join(`
41
+ `);return`import type { Bytes, Cursor, Decimal, ImageAsset, Json, Money, Page, Principal, VideoAsset } from 'snapback2';
42
+ import type { Channel, Op } from 'snapback2/client';
43
+
44
+ ${o}
45
+
46
+ declare module 'snapback2/client' {
47
+ interface Api {
48
+ ${l}
49
+ }
50
+ }
51
+
52
+ export {};
53
+ `}function Sf(e,n){let t=e.getSourceFiles().find(r=>/[/\\]snapback[/\\]schema\.ts$/.test(r.fileName));if(!t)return[];let i=[];for(let r of t.statements)if(!(!A.isVariableStatement(r)||!Pe(r)))for(let s of r.declarationList.declarations){if(!A.isIdentifier(s.name)||!s.initializer)continue;let o=N(s.initializer);if(!o||B(o)!=="channel")continue;let a=z(o.arguments[0]),u=a&&z(_(a,"args"));i.push({name:s.name.text,args:u?Wu(u,n,!1):"{}"})}return i.sort((r,s)=>r.name.localeCompare(s.name))}function wf(e){let n=Object.entries(e.columns??{}).map(([t,i])=>{let r=i.kind==="optional";return` ${it(t)}${r?"?":""}: ${Mt(r?i.of:i)};`});return n.some(t=>/^ id[?:]/.test(t))||n.unshift(" id: string;"),`type ${vt(e.name)} = {
54
+ ${n.join(`
55
+ `)}
56
+ };`}function vt(e){return`${e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t[0].toUpperCase()+t.slice(1)).join("")||"Table"}Row`}function $f(e,n){let t=e.getSourceFiles().find(i=>i.fileName.endsWith(`/snapback/${n.moduleName}.ts`));if(t){for(let i of t.statements)if(!(!A.isVariableStatement(i)||!Pe(i))){for(let r of i.declarationList.declarations)if(!(!A.isIdentifier(r.name)||r.name.text!==n.exportName||!r.initializer))return N(r.initializer)}}}function Wu(e,n,t){let i=mn(e).entries.map(r=>{let s=N(r.value),o=s&&B(s)==="optional",a=s?Ju(s,n,t):"unknown",u=s&&Gu(s);return`${u?`/** ${u} \u2014 minor units */ `:""}${it(r.name)}${o?"?":""}: ${a}`});return i.length===0?"{}":`{ ${i.join("; ")} }`}function Ju(e,n,t){let i=B(e);if(i==="decimal"||i==="money")return"number";if((i==="optional"||i==="list")&&e.arguments[0]){let r=N(e.arguments[0]),s=r?Ju(r,n,t):"unknown";return i==="list"?`${s.includes(" | ")?`(${s})`:s}[]`:`${s} | null`}return t&&(i==="image"||i==="video")?`File | ${i==="image"?"ImageAsset":"VideoAsset"}`:Yi(e,n)}function Gu(e){let n=B(e);if(n==="optional"&&e.arguments[0]){let t=N(e.arguments[0]);return t&&Gu(t)}if(n==="decimal")return`decimal ${X(e.arguments[0])??"?"}`;if(n==="money")return`money ${q(e.arguments[0])??"?"} ${X(e.arguments[1])??2}`}function Yi(e,n){let t=B(e);if(t==="cursor")return"Cursor";if(t==="principal")return"Principal";if(t==="id"||t==="text"||t==="ref")return"string";if(t==="bytes")return"Bytes";if(t==="image")return"ImageAsset";if(t==="video")return"VideoAsset";if(t==="int"||t==="time")return"number";if(t==="bool")return"boolean";if(t==="enum")return en(e.arguments[0])?.map(r=>JSON.stringify(r)).join(" | ")||"never";if(t==="decimal")return`Decimal<${X(e.arguments[0])??"number"}>`;if(t==="money")return`Money<${JSON.stringify(q(e.arguments[0])??"")}, ${X(e.arguments[1])??2}>`;if(t==="optional"&&e.arguments[0]){let i=N(e.arguments[0]);return i?Yi(i,n):"unknown"}if(t==="list"&&e.arguments[0]){let i=N(e.arguments[0]);return`${i?Yi(i,n):"unknown"}[]`}if(t==="json"){let r=n.getTypeAtLocation(e).getProperty("__value");if(r)return n.typeToString(n.getTypeOfSymbolAtLocation(r,e),e,A.TypeFormatFlags.NoTruncation)}return"unknown"}function Af(e,n,t,i){let r={bindings:new Map};for(let c of e.parameters)for(let l of Xi(c.name))r.bindings.set(l,{kind:"local"});let s=e.parameters[0]?.name;if(s&&A.isObjectBindingPattern(s))for(let c of s.elements){if(!A.isIdentifier(c.name))continue;let l=c.propertyName?H(c.propertyName):c.name.text;if(l==="args"&&r.bindings.set(c.name.text,{kind:"args"}),l==="ctx"){let f={text:"Principal",special:!0};r.bindings.set(c.name.text,{kind:"local",type:{text:"unknown",special:!0,fields:{viewer:f}}})}}if(!A.isBlock(e.body))return _e(e.body,n,t,i,r);let o=[],a=Yu(e.body.statements,n,t,i,r,o),u=o.reduce((c,l)=>c?Bn(c,l):l,void 0);return u&&a&&o.length>1&&!u.text.includes("unknown")?{...u,special:!0}:u}function Yu(e,n,t,i,r,s){for(let o of e)if(Gi(o,n,t,i,r,s))return!0;return!1}function Gi(e,n,t,i,r,s){if(A.isVariableStatement(e)){for(let o of e.declarationList.declarations){let a=o.initializer?_e(o.initializer,n,t,i,r):void 0;for(let u of Xi(o.name))r.bindings.set(u,It(a))}return!1}if(A.isExpressionStatement(e))return Tf(e.expression,n,t,i,r),!1;if(A.isReturnStatement(e)&&e.expression)return s.push(_e(e.expression,n,t,i,r)),!0;if(A.isBlock(e))return Yu(e.statements,n,t,i,r,s);if(A.isIfStatement(e)){let o=Ji(r),a=Ji(o),u=Ji(o);Nf(e.expression,a,u);let c=Gi(e.thenStatement,n,t,i,a,s),l=e.elseStatement?Gi(e.elseStatement,n,t,i,u,s):!1;return c&&l?!0:(Vu(r,o,[a,u]),!1)}if(A.isForOfStatement(e)){let o=Ji(r),a=_e(e.expression,n,t,i,r);if(A.isVariableDeclarationList(e.initializer))for(let u of e.initializer.declarations)for(let c of Xi(u.name))o.bindings.set(c,It(a.element));return Gi(e.statement,n,t,i,o,s),Vu(r,r,[r,o]),!1}return!1}function Tf(e,n,t,i,r){let s=h(e);if(A.isBinaryExpression(s)&&s.operatorToken.kind===A.SyntaxKind.EqualsToken&&A.isIdentifier(h(s.left))){let l=h(s.left).text,f=_e(s.right,n,t,i,r);r.bindings.set(l,It(f));return}if(!A.isCallExpression(s)||!A.isPropertyAccessExpression(s.expression)||s.expression.name.text!=="push"||s.arguments.length===0)return;let o=h(s.expression.expression);if(!A.isIdentifier(o))return;let a=r.bindings.get(o.text);if(a?.kind!=="local")return;let u=_e(s.arguments[0],n,t,i,r),c=a.type?.element?Bn(a.type.element,u):u;r.bindings.set(o.text,It(ui(c)))}function _e(e,n,t,i,r,s){let o=If(e),a=h(e),u=s&&ee(s);if(u?.kind==="decimal")return{text:Mt(u),special:!0};if(u?.kind==="enum"&&A.isStringLiteralLike(a))return{text:Mt(u),special:!0};if(A.isNumericLiteral(a))return{text:"number",special:!1};if(A.isStringLiteralLike(a)||A.isTemplateExpression(a))return{text:"string",special:!1};if(a.kind===A.SyntaxKind.TrueKeyword||a.kind===A.SyntaxKind.FalseKeyword)return{text:"boolean",special:!1};if(a.kind===A.SyntaxKind.NullKeyword)return{text:"null",special:!1};if(A.isIdentifier(a)){let d=r.bindings.get(a.text);if(d?.kind==="local"&&d.type)return o?Xu(d.type):d.type}if(A.isPrefixUnaryExpression(a)&&a.operator===A.SyntaxKind.MinusToken)return _e(a.operand,n,t,i,r);let c=A.isPropertyAccessExpression(a)?h(a.expression):void 0,l=c&&A.isIdentifier(c)?r.bindings.get(c.text):void 0;if(A.isPropertyAccessExpression(a)&&c&&A.isIdentifier(c)&&l?.kind==="args"&&n){let d=sn(n).find(g=>g.name===a.name.text)?.value,p=d&&N(d);if(p){let g=`${Yi(p,i)}${B(p)==="optional"?" | undefined":""}`;return{text:g,special:Hu(g)}}}if(A.isPropertyAccessExpression(a)&&c){let d=l?.kind==="local"&&l.type?l.type:_e(c,n,t,i,r),p=_f(d,a.name.text);if(p)return!!a.questionDotToken&&Cf(d)?Bn(p,{text:"undefined",special:!0,optional:!0}):p;if(a.name.text==="length"&&d.element)return{text:"number",special:d.special}}if(A.isObjectLiteralExpression(a)){let d=!1,p=[],g={},m=[];for(let k of a.properties){if(A.isSpreadAssignment(k)){let D=_e(k.expression,n,t,i,r);D.row&&(m.push(D.row),d=!0);continue}if(A.isShorthandPropertyAssignment(k)){let D=_e(k.name,n,t,i,r);d||=D.special,p.push(Ku(k.name.text,D)),g[k.name.text]=D;continue}if(!A.isPropertyAssignment(k))continue;let $=H(k.name);if(!$)continue;let R=_e(k.initializer,n,t,i,r);d||=R.special,p.push(Ku($,R)),g[$]=R}let b=[...new Map(m.map(k=>[k.name,k])).values()].map(k=>{let $=Object.keys(g).filter(D=>D==="id"||Object.hasOwn(k.columns??{},D)),R=vt(k.name);return $.length===0?R:`Omit<${R}, ${$.map(D=>JSON.stringify(D)).join(" | ")}>`}),S=`{ ${p.join("; ")} }`;return{text:b.length===0?S:[...b,...p.length>0?[S]:[]].join(" & "),special:d,fields:g,...m.length===1?{row:m[0]}:{},groupedInArray:b.length+ +(p.length>0)>1}}if(A.isArrayLiteralExpression(a)){if(a.elements.length===1&&A.isSpreadElement(a.elements[0])){let g=_e(a.elements[0].expression,n,t,i,r);if(g.element)return ui(g.element)}let p=a.elements.filter(g=>!A.isSpreadElement(g)).map(g=>_e(g,n,t,i,r)).reduce((g,m)=>g?Bn(g,m):m,void 0);return p?ui(p):{text:"unknown[]",special:!1}}if(A.isConditionalExpression(a)){let d=_e(a.whenTrue,n,t,i,r,u),p=_e(a.whenFalse,n,t,i,r,u);return Bn(d,p)}if(A.isBinaryExpression(a)){let d=_e(a.left,n,t,i,r),p=_e(a.right,n,t,i,r);if([A.SyntaxKind.LessThanToken,A.SyntaxKind.LessThanEqualsToken,A.SyntaxKind.GreaterThanToken,A.SyntaxKind.GreaterThanEqualsToken,A.SyntaxKind.EqualsEqualsToken,A.SyntaxKind.EqualsEqualsEqualsToken,A.SyntaxKind.ExclamationEqualsToken,A.SyntaxKind.ExclamationEqualsEqualsToken].includes(a.operatorToken.kind))return{text:"boolean",special:!1};if(a.operatorToken.kind===A.SyntaxKind.QuestionQuestionToken&&(d.special||p.special))return{...Of(d.special?d:p),special:!0};let g=[d,p].filter(m=>/^(Decimal|Money)</.test(m.text));if(a.operatorToken.kind===A.SyntaxKind.AsteriskToken&&g.length>0)return g.find(m=>m.text.startsWith("Money<"))??g[0];if(g.length>0&&[A.SyntaxKind.PlusToken,A.SyntaxKind.MinusToken].includes(a.operatorToken.kind))return g[0]}if(A.isCallExpression(a)){let d=B(a);if((d==="scan"||d==="get")&&a.arguments[0]){let p=ec(a.arguments[0],t);if(p){let g=Uu(p);return d==="scan"?{text:`Page<${g.text}>`,special:!0,element:g}:Bn(g,{text:"null",special:!1})}}if(d==="decimal")return{text:`Decimal<${X(a.arguments[1])??"number"}>`,special:!0};if(d==="recurse"&&a.arguments[1]){let p=Mf(a.arguments[1],t);if(p)return ui(Uu(p))}if(d==="divmod"&&a.arguments[0]){let p=_e(a.arguments[0],n,t,i,r);return{text:`{ quotient: ${p.text}; remainder: ${p.text} }`,special:p.special,fields:{quotient:p,remainder:p}}}if(d==="deterministicShare"&&a.arguments[0])return _e(a.arguments[0],n,t,i,r);if(d==="min"||d==="max"){let p=a.arguments.map(g=>_e(g,n,t,i,r)).find(g=>/^(Decimal|Money)</.test(g.text));if(p)return p}}let f=i.typeToString(i.getTypeAtLocation(a),a,A.TypeFormatFlags.NoTruncation|A.TypeFormatFlags.InTypeAlias).replaceAll('import("snapback2").',"");return{text:f,special:Hu(f)}}function It(e){return{kind:"local",...e?{type:e}:{},...e?.row?{row:e.row}:{},...e?.element?.row?{elementRow:e.element.row}:{}}}function Ji(e){return{bindings:new Map([...e.bindings].map(([n,t])=>[n,t.kind==="args"?t:{...t}]))}}function Vu(e,n,t){for(let[i,r]of n.bindings){if(r.kind==="args")continue;let u=t.map(c=>c.bindings.get(i)).filter(c=>!!c).filter(c=>c.kind==="local").flatMap(c=>c.type?[c.type]:[]).reduce((c,l)=>c?Bn(c,l):l,void 0);e.bindings.set(i,It(u))}}function Nf(e,n,t){let i=h(e);if(!A.isBinaryExpression(i))return;let r=h(i.left),s=h(i.right),o=A.isIdentifier(r)&&s.kind===A.SyntaxKind.NullKeyword?r:A.isIdentifier(s)&&r.kind===A.SyntaxKind.NullKeyword?s:void 0;if(!o)return;let a=i.operatorToken.kind===A.SyntaxKind.EqualsEqualsToken||i.operatorToken.kind===A.SyntaxKind.EqualsEqualsEqualsToken,u=i.operatorToken.kind===A.SyntaxKind.ExclamationEqualsToken||i.operatorToken.kind===A.SyntaxKind.ExclamationEqualsEqualsToken;if(!a&&!u)return;let c=u?n:t,l=c.bindings.get(o.text);l?.kind==="local"&&l.type&&c.bindings.set(o.text,It(Xu(l.type)))}function Uu(e){return{text:vt(e.name),special:!0,row:e}}function _f(e,n){let t=e.fields?.[n];if(t)return t;if(!e.row)return;if(n==="id")return{text:"string",special:!0};let i=e.row.columns?.[n];if(!i)return;let r=i.kind==="optional";return{text:`${Mt(r?i.of:i)}${r?" | undefined":""}`,special:!0,optional:r}}function Ku(e,n){return`${it(e)}${n.optional?"?":""}: ${n.text}`}function ui(e){return{text:`${e.groupedInArray?`(${e.text})`:e.text}[]`,special:e.special,element:e}}function Bn(e,n){if(e.text===n.text)return{...e,special:e.special||n.special,optional:e.optional||n.optional};if(e.text==="unknown[]"&&!e.element&&(n.element||n.text.endsWith("[]")))return n;if(n.text==="unknown[]"&&!n.element&&(e.element||e.text.endsWith("[]")))return e;if(e.element&&n.element)return ui(Bn(e.element,n.element));let t=[e,n].sort((s,o)=>Number(Qu(s))-Number(Qu(o))),i=[...new Set(t.flatMap(s=>Cs(s.text)))],r=t.find(s=>s.fields||s.row);return{text:i.join(" | "),special:e.special||n.special,...r?.fields?{fields:r.fields}:{},...r?.row?{row:r.row}:{},optional:e.optional||n.optional,groupedInArray:!0}}function Xu(e){return{...e,text:Zu(e.text,"null")}}function Of(e){return{...e,text:Zu(e.text,"undefined"),optional:!1}}function Zu(e,n){return Cs(e).filter(i=>i!==n).join(" | ")||"never"}function Cf(e){return Cs(e.text).includes("null")}function Qu(e){return e.text==="null"||e.text==="undefined"}function If(e){let n=e;for(;A.isParenthesizedExpression(n)||A.isAsExpression(n);)n=n.expression;return A.isNonNullExpression(n)}function Cs(e){let n=[],t=0,i=0,r="";for(let s=0;s<e.length;s+=1){let o=e[s];if(r){o===r&&e[s-1]!=="\\"&&(r="");continue}if(o==='"'||o==="'"){r=o;continue}"{[(<".includes(o)?i+=1:"}])>".includes(o)?i-=1:i===0&&e.slice(s,s+3)===" | "&&(n.push(e.slice(t,s)),t=s+3,s+=2)}return n.push(e.slice(t)),n}function Mf(e,n){let t=h(e);if(!A.isArrowFunction(t)&&!A.isFunctionExpression(t))return;let i,r=s=>{i||A.isCallExpression(s)&&B(s)==="get"&&s.arguments[0]&&(i=ec(s.arguments[0],n),i)||A.forEachChild(s,r)};return r(t.body),i}function Xi(e){return A.isIdentifier(e)?[e.text]:e.elements.flatMap(n=>A.isBindingElement(n)?Xi(n.name):[])}function Mt(e){return e.kind==="int"?"number":e.kind==="string"?"string":e.kind==="principal"?"Principal":e.kind==="bytes"?"Bytes":e.kind==="asset"?e.asset==="image"?"ImageAsset":"VideoAsset":e.kind==="bool"?"boolean":e.kind==="json"?"Json":e.kind==="decimal"?e.currency?`Money<${JSON.stringify(e.currency)}, ${e.scale}>`:`Decimal<${e.scale}>`:e.kind==="enum"?e.variants.map(n=>JSON.stringify(n)).join(" | ")||"never":e.kind==="list"?`${Mt(e.of)}[]`:e.kind==="optional"?Mt(e.of):e.kind==="row"?vt(e.table):"unknown"}function Hu(e){return/\b(?:Decimal|Money)</.test(e)||/\b(?:ImageAsset|VideoAsset)\b/.test(e)||e.includes(" | ")}function ec(e,n){let t=ye(e);if(!t)return;let i=n.get(t);if(i)return i;let r=t.lastIndexOf(".");return r>0?n.get(t.slice(0,r)):void 0}function it(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}async function vb(e,n={}){let t=performance.now(),i=qn(e),r=Se(i,"snapback"),s=Se(r,"schema.ts"),o=Se(r,"schema.q"),a=Rt(s),u=Rt(o);if(!a&&!u)return{ok:!1,diagnostics:[qe("E_SCHEMA_DEFAULT_EXPORT","schema","snapback/schema.q",1,1,"missing snapback/schema.q","create snapback/schema.q with table declarations","schema/project")],ms:rt(t)};let c=await vs(r),l=c.filter(j=>j.endsWith(".ts")).sort();if(n.authoring!=="any"){let j=await qu(i,a,l);if(j.length>0)return{ok:!1,diagnostics:j,ms:rt(t)}}if(a&&u)return{ok:!1,diagnostics:[qe("E_QUARRY_PLACEMENT","quarry","snapback/schema.q",1,1,"snapback/schema.q and snapback/schema.ts cannot coexist; exactly one schema is allowed","-- remove snapback/schema.ts or snapback/schema.q","quarry/projects")],ms:rt(t)};let f=c.filter(j=>j.endsWith(".q")).sort();if(!u&&f.length>0){let j=f[0];return{ok:!1,diagnostics:[qe("E_QUARRY_PLACEMENT","quarry",De(i,j),1,1,`Quarry module ${De(i,j)} requires snapback/schema.q; this project has snapback/schema.ts`,"-- move the schema to snapback/schema.q","quarry/projects")],ms:rt(t)}}let d=s,p=a?await st(s,"utf8"):"",g=[];if(u){let j=await Promise.all(f.map(async _n=>({path:_n,fileName:De(i,_n),source:await st(_n,"utf8")}))),Ee=ks(j);if(!Ee.ok)return{ok:!1,diagnostics:En(Ee.diagnostics,50,"Quarry refusals"),ms:rt(t)};d=Ee.schema.path,p=Ee.schema.source,g=[Ee.schema,...Ee.modules]}let m=new Map(g.map(j=>[De(i,j.path),j])),y=await Promise.all(l.map(async j=>[j,await st(j,"utf8")])),b=g.filter(j=>j!==g[0]).map(j=>[j.path,j.source]),S=[...y,...b].sort(([j],[Ee])=>j.localeCompare(Ee)),E=S.map(([j,Ee])=>({moduleName:fc(j),fileName:De(i,j),source:Ee,sourceFile:ie.createSourceFile(j,Ee,ie.ScriptTarget.ES2022,!0)})),k=De(i,d),$=Qr(p,k),R=[...l,...f.filter(j=>er(j)!=="schema.q")],D=[...$.diagnostics,...Pf(c,r,i),...Lf(R,i),...Ff($.tables,k)];E.length===0&&D.push(qe("E_OP_NONE","op",k,1,1,"module exports no query/mutation/effect",`query operation():
57
+ return null`,"programs/operations"));let J=zf(),se=Du(d,p,S,J);D.push(...Lu(se.program,i).map(j=>ac(j,m,!0)));let he=Vf(E);D.push(...Uf(he,p,k));let Dt=Fa(E),ce=Ba(Dt,he);D.push(...ce.diagnostics);let nr=[],Rs=Object.create(null),Ds=new Map;for(let j of E){let Ee=Qf(j,$.tables,D);Ds.set(j.moduleName,Ee);let _n=ja(j,Dt),tr=va(j.source,j.fileName,void 0,{tables:Ee,effects:_n,operationPrefix:j.moduleName});if(tr.ok){nr.push(...tr.programs.map(ju));for(let li of he.values()){if(li.moduleName!==j.moduleName)continue;let Ps=li.module.sourceFile.getLineAndCharacterOfPosition(li.call.getStart());Rs[li.name]={file:j.fileName,line:Ps.line+1,col:Ps.character+1}}}else D.push(...tr.diagnostics)}let Ls=Kf(D,E,he).map(j=>ac(j,m,!1));if(Ls.length>0)return{ok:!1,diagnostics:En(Ls,50,"project refusals"),ms:rt(t)};$.schema.effects=ce.effects.map(j=>j.name),nr.sort((j,Ee)=>j.name.localeCompare(Ee.name));let pc=zu(he,se.program,se.checker,$.tables,Ds);return{ok:!0,project:{schema:$.schema,programs:nr,effects:ce.effects},sources:Object.fromEntries(Object.entries(Rs).map(([j,Ee])=>{let _n=m.get(Ee.file);return[j,_n?Ou(Ee,_n):Ee]}).sort(([j],[Ee])=>j.localeCompare(Ee))),apiDts:pc,quarry:Cu(g),ms:rt(t)}}async function vs(e,n=e){let t=[];for(let i of await uc(e,{withFileTypes:!0})){let r=Se(e,i.name);if(i.isDirectory()){if(e===n&&i.name==="tests")continue;t.push(...await vs(r,n))}else i.isFile()&&(i.name.endsWith(".ts")||i.name.endsWith(".q"))&&!(e===n&&["schema.ts","seed.ts"].includes(i.name))&&t.push(r)}return t}function Lf(e,n){let t=new Map;for(let r of e){let s=fc(r),o=t.get(s)??[];o.push(r),t.set(s,o)}let i=[];for(let[r,s]of t)if(!(s.length<2))for(let o of s.sort()){let a=De(n,o);i.push(qe("E_OP_MODULE_BASENAME","op",a,1,1,`module basename ${r} is duplicated; read-site identity requires one flat module per basename`,`rename ${a} so every snapback module has a unique basename`,"programs/module-basename"))}return i}function Pf(e,n,t){return e.filter(i=>cc(i)!==n).sort().map(i=>{let r=De(t,i);return qe("E_OP_INVALID","op",r,1,1,`nested operation module ${r} is unsupported; operation modules must be direct children of snapback`,`move ${r} directly under snapback/`,"programs/operations")})}function Ff(e,n){let t=new Map;for(let i of e.values()){let r=vt(i.name);t.set(r,[...t.get(r)??[],i.name])}return[...t].filter(([,i])=>i.length>1).map(([i,r])=>qe("E_SCHEMA_INVALID","schema",n,1,1,`tables ${r.join(" and ")} generate the same row alias ${i}`,"rename one table so generated row type names are unique","schema/project"))}async function Rb(e){let n=qn(e),t=Se(n,"snapback","seed.ts");if(!Rt(t))return{ok:!0,seed:{personas:[],rows:{}}};let i=await st(t,"utf8"),r=De(n,t),s=ie.createSourceFile(t,i,ie.ScriptTarget.ES2022,!0),o;for(let R of s.statements)ie.isExportAssignment(R)&&!R.isExportEquals&&(o=R.expression);let a=o&&N(o);a&&B(a)==="seed"&&(o=a.arguments[0]);let u=o&&z(o),c=zt(s),l=Pu(s),f=u&&Ot(u,l),d=f&&typeof f=="object"?f:void 0,p={sourceFile:s,source:i,fileName:r},g=u&&Hf(u,c);if(!d&&g)return{ok:!1,diagnostics:[L(p,"E_SEED_SHAPE",g,`seed object spread ${g.expression.getText(s)} is not statically JSON`,"replace the spread with a JSON object constant or spell its fields explicitly")]};if(!d||!Array.isArray(d.personas)||typeof d.rows!="object"||d.rows===null||Array.isArray(d.rows))return{ok:!1,diagnostics:[L(p,"E_SEED_INVALID",o??s,"seed.ts must default-export seed({ personas, rows })",i)]};let m=[],y=d.personas,b=y.filter(R=>typeof R=="string"&&R.length>0);(b.length!==y.length||new Set(b).size!==b.length)&&m.push(L(p,"E_SEED_PERSONA",o??s,"seed personas must be unique, non-empty strings",i));let S;try{S=await st(Se(n,"snapback","schema.ts"),"utf8")}catch{let R=Se(n,"snapback"),D=(await vs(R)).filter(he=>he.endsWith(".q")),J=await Promise.all(D.map(async he=>({path:he,fileName:De(n,he),source:await st(he,"utf8")}))),se=ks(J);if(!se.ok)return{ok:!1,diagnostics:se.diagnostics};S=se.schema.source}let E=Qr(S,"snapback/schema.ts");if(E.diagnostics.length>0)return{ok:!1,diagnostics:E.diagnostics};let k=E.schema.tables,$=d.rows;for(let[R,D]of Object.entries($)){if(!Object.hasOwn(k,R)){m.push(L(p,"E_SEED_TABLE",o??s,`seed rows name unknown table ${R}`,i));continue}if(!Array.isArray(D)){m.push(L(p,"E_SEED_ROW",o??s,`seed rows.${R} must be an array`,i));continue}let J=k[R]?.columns??{};for(let[se,he]of D.entries())Fu(p,o??s,R,se,he,J,m)}return m.length>0?{ok:!1,diagnostics:En(m,50,"seed refusals")}:{ok:!0,seed:{personas:b,rows:$}}}async function jf(e){let n=qn(e),t=Se(n,"snapback","tests");return Rt(t)?(await uc(t,{withFileTypes:!0})).filter(r=>r.isFile()&&r.name.endsWith(".test.ts")).map(r=>De(n,Se(t,r.name))).sort():[]}async function Db(e,n){let t=qn(e),i=(await jf(t)).map(k=>Se(t,k)),r=Se(t,".snapback","build"),s=Se(r,"tests"),o=await oc(t,[Se(t,".snapback"),r,s]);if(o)return{ok:!1,diagnostics:[o]};await Rf(r,{recursive:!0});let a=await Df(Se(r,".tests-"));if(i.length===0)return await sc(s,a),{ok:!0,files:[]};let u=qf(),c=Se(u,"client.d.ts"),l=Se(u,"test.d.ts"),f=Se(r,`.api-${process.pid}-${Date.now()}.d.ts`);await ic(f,n);let d={baseUrl:t,jsx:ie.JsxEmit.ReactJSX,lib:["lib.es2022.d.ts","lib.dom.d.ts","lib.dom.iterable.d.ts"],module:ie.ModuleKind.ESNext,moduleResolution:ie.ModuleResolutionKind.Bundler,noEmit:!0,paths:{"snapback2/client":[c],"snapback2/test":[l]},skipLibCheck:!0,strict:!0,target:ie.ScriptTarget.ES2022,types:[]},p=ie.createProgram({rootNames:[...i,f],options:d}),g=new Set(i.map(k=>qn(k))),m=ie.getPreEmitDiagnostics(p).flatMap(k=>{if(!k.file||!g.has(qn(k.file.fileName)))return[];let $=k.start===void 0?{line:0,character:0}:k.file.getLineAndCharacterOfPosition(k.start);return[qe("E_OP_INVALID","op",De(t,k.file.fileName),$.line+1,$.character+1,ie.flattenDiagnosticMessageText(k.messageText,`
58
+ `),"fix the journey TypeScript error and rerun snapback2 check","testing/journeys")]});if(await Zi(f,{force:!0}),m.length>0)return await Zi(a,{recursive:!0,force:!0}),{ok:!1,diagnostics:En(m,50,"journey refusals")};let y=rc(Se(u,"client.mjs")).href,b=rc(Se(u,"test.mjs")).href,S=[];for(let k of i){let $=await st(k,"utf8"),R=ie.transpileModule($,{fileName:k,compilerOptions:{module:ie.ModuleKind.ESNext,target:ie.ScriptTarget.ES2022}}).outputText,D=Bf(R,new Map([["snapback2/client",y],["snapback2/test",b]])),se=`${er(k).slice(0,-8)}.mjs`,he=Se(a,se);await ic(he,D),S.push(De(t,he))}let E=await oc(t,[Se(t,".snapback"),r,s]);if(E)return await Zi(a,{recursive:!0,force:!0}),{ok:!1,diagnostics:[E]};await sc(s,a);for(let k=0;k<S.length;k+=1)S[k]=De(t,Se(s,er(S[k])));return{ok:!0,files:S}}async function sc(e,n){let t=`${e}.replaced-${process.pid}-${Date.now()}`;try{await Is(e,t)}catch(i){if(i.code!=="ENOENT")throw i}try{await Is(n,e)}catch(i){try{await Is(t,e)}catch{}throw i}await Zi(t,{recursive:!0,force:!0})}async function oc(e,n){let t=await tc(e);for(let i of n)try{if((await vf(i)).isSymbolicLink())return qe("E_OP_INVALID","op",De(e,i),1,1,`journey output component ${De(e,i)} is a symlink`,"replace the symlink with a project-owned directory","testing/journeys");let s=await tc(i),o=dc(t,s);if(o===".."||o.startsWith(`..${Ms}`)||lc(o))return qe("E_OP_INVALID","op",De(e,i),1,1,`journey output component ${De(e,i)} escapes the project`,"use a project-owned output directory","testing/journeys")}catch(r){if(r.code!=="ENOENT")throw r}}function Bf(e,n){let t=ie.createSourceFile("journey.mjs",e,ie.ScriptTarget.ES2022,!0,ie.ScriptKind.JS),i=[],r=s=>{if(!s||!ie.isStringLiteralLike(s))return;let o=n.get(s.text);o&&i.push({start:s.getStart(t),end:s.getEnd(),value:JSON.stringify(o)})};return we(t,s=>{(ie.isImportDeclaration(s)||ie.isExportDeclaration(s))&&r(s.moduleSpecifier),ie.isCallExpression(s)&&s.expression.kind===ie.SyntaxKind.ImportKeyword&&r(s.arguments[0])}),i.sort((s,o)=>o.start-s.start).reduce((s,o)=>`${s.slice(0,o.start)}${o.value}${s.slice(o.end)}`,e)}function qf(){let e=cc(ci(import.meta.url));return er(e)==="dist"?e:qn(e,"../../snapback2/dist")}function Vf(e){let n=new Map;for(let t of e)for(let i of t.sourceFile.statements)if(!(!ie.isVariableStatement(i)||!Pe(i)))for(let r of i.declarationList.declarations){if(!ie.isIdentifier(r.name)||!r.initializer)continue;let s=N(r.initializer),o=s&&B(s);if(!s||o!=="query"&&o!=="mutation")continue;let a=`${t.moduleName}.${r.name.text}`;n.set(a,{name:a,moduleName:t.moduleName,exportName:r.name.text,kind:o,call:s,module:t})}return n}function Uf(e,n,t){let i=[];for(let o of e.values())o.moduleName==="then"&&i.push(L(o.module,"E_OP_RESERVED",o.call,`operation ${o.name} uses reserved API path segment then`,`rename snapback/then.ts to snapback/${o.exportName==="then"?"operations":o.exportName}.ts`)),o.exportName==="then"&&i.push(L(o.module,"E_OP_RESERVED",o.call,`operation ${o.name} uses reserved API property then`,o.module.source.replace(/\bthen\b/,"thenOperation")));let r=ie.createSourceFile(t,n,ie.ScriptTarget.ES2022,!0),s={sourceFile:r,source:n,fileName:t};for(let o of r.statements)if(!(!ie.isVariableStatement(o)||!Pe(o)))for(let a of o.declarationList.declarations){if(!ie.isIdentifier(a.name)||a.name.text!=="then"||!a.initializer)continue;let u=N(a.initializer);!u||B(u)!=="channel"||i.push(L(s,"E_OP_RESERVED",a.name,"channel then uses a reserved API property",n.replace(/\bthen\b/g,"thenChannel")))}return i}function Kf(e,n,t){let i=e,r=[];for(let s of n){let o=i.filter(u=>u.site.startsWith(`${s.fileName}:`));i=i.filter(u=>!u.site.startsWith(`${s.fileName}:`));let a=[...t.values()].filter(u=>u.moduleName===s.moduleName).map(u=>({name:u.name,call:u.call}));r.push(...Bi(o,a,s))}return[...r,...i]}function Qf(e,n,t){let i=new Map;for(let r of e.sourceFile.statements){if(!ie.isImportDeclaration(r)||!ie.isStringLiteral(r.moduleSpecifier)||!/^\.\/schema(?:\.ts)?$/.test(r.moduleSpecifier.text))continue;let s=r.importClause?.namedBindings;if(s){if(ie.isNamespaceImport(s)){for(let[o,a]of n)i.set(`${s.name.text}.${o}`,a);continue}for(let o of s.elements){let a=o.propertyName?.text??o.name.text,u=n.get(a);u?i.set(o.name.text,u):t.push(L(e,"E_SCHEMA_UNKNOWN_TABLE",o,`schema has no exported table ${a}`,e.source))}}}return i}function Hf(e,n){let t;return we(e,i=>{if(t||!ie.isSpreadAssignment(i))return;let r=rn(i.expression,n);(!r||typeof r!="object"||Array.isArray(r))&&(t=i)}),t}function zf(){let e=[ci(new URL("../lib.d.ts",import.meta.url)),ci(new URL("./index.d.ts",import.meta.url))],n=[ci(new URL("../subset-lib.d.ts",import.meta.url)),ci(new URL("./compiler-lib.d.ts",import.meta.url))],t=e.find(Rt),i=n.find(Rt);if(!t||!i)throw new Error("snapback2 compiler: checker declarations are missing beside the compiler bundle");return`${nc(i,"utf8")}
59
+ ${nc(t,"utf8")}`}function fc(e){return e.split(Ms).at(-1).replace(/\.(?:q|ts)$/,"")}function ac(e,n,t){let i=e.site.replace(/:\d+:\d+$/,""),r=n.get(i);return r?_u(e,r,t):e}function De(e,n){return dc(e,lc(n)?n:qn(n)).split(Ms).join("/")}function rt(e){return Math.round((performance.now()-e)*100)/100}export{Db as compileJourneys,jf as listJourneys,vb as lowerProject,Rb as lowerSeed};
60
+ //# sourceMappingURL=compiler-core.mjs.map