@lunora/codegen 1.0.0-alpha.406 → 1.0.0-alpha.408

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 (35) hide show
  1. package/dist/index.d.mts +24 -1
  2. package/dist/index.d.ts +24 -1
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{ALL_NOTIFY_CHANNELS-DPxI0EHQ.mjs → ALL_NOTIFY_CHANNELS-D1LVGz6_.mjs} +1 -1
  5. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CitMcXVT.mjs +54 -0
  6. package/dist/packem_shared/{SHAPES_FILENAME-CH0KrAdb.mjs → SHAPES_FILENAME-BYnZ1Xw-.mjs} +1 -1
  7. package/dist/packem_shared/chain-CONXUmWW.mjs +1 -0
  8. package/dist/packem_shared/{classify-procedure-call-BZ164dkJ.mjs → classify-procedure-call-n9urVsqb.mjs} +1 -1
  9. package/dist/packem_shared/{context-property-calls-Ggrmu3UL.mjs → context-property-calls-DXzNVV1P.mjs} +1 -1
  10. package/dist/packem_shared/{context-root-DnvrQxae.mjs → context-root-DP9WbBI_.mjs} +1 -1
  11. package/dist/packem_shared/{database-calls-BRI5W-Mp.mjs → database-calls-Do0YbPCL.mjs} +1 -1
  12. package/dist/packem_shared/discoverFunctions-CeHY4_ii.mjs +1 -0
  13. package/dist/packem_shared/discoverHyperdriveCalls-W96s1VgA.mjs +1 -0
  14. package/dist/packem_shared/{discoverInserts-DmSa4WKU.mjs → discoverInserts-BtyJbg8A.mjs} +1 -1
  15. package/dist/packem_shared/discoverMaskProcedures-BFm9rkZ7.mjs +1 -0
  16. package/dist/packem_shared/{discoverNondeterministicCalls-BoF6ob-B.mjs → discoverNondeterministicCalls-DR0S5Xb4.mjs} +1 -1
  17. package/dist/packem_shared/{discoverQueries-spxu-wHR.mjs → discoverQueries-BLyL2qzX.mjs} +1 -1
  18. package/dist/packem_shared/discoverR2sqlCalls-Cb4AmcY8.mjs +1 -0
  19. package/dist/packem_shared/{discoverRlsMetadata-Cc0zA-gZ.mjs → discoverRlsMetadata-Cf4gZvxW.mjs} +1 -1
  20. package/dist/packem_shared/{discoverRlsProcedures-mjiA0I4S.mjs → discoverRlsProcedures-_Dh3Xb9Z.mjs} +1 -1
  21. package/dist/packem_shared/{discoverStorageRulesMetadata-CtE5trUR.mjs → discoverStorageRulesMetadata-ZKW6DInk.mjs} +1 -1
  22. package/dist/packem_shared/{emitApp-BsXqg0CQ.mjs → emitApp-pPxkJ2Z-.mjs} +74 -66
  23. package/dist/packem_shared/{emitServer-DsSAaZaT.mjs → emitServer-CbcZN_Ug.mjs} +1 -1
  24. package/dist/packem_shared/{exported-procedure-chains-h8Y7xDjq.mjs → exported-procedure-chains-DomRzs5_.mjs} +1 -1
  25. package/dist/packem_shared/{index-jtzAVdUp.mjs → index-BH3e-J44.mjs} +1 -1
  26. package/dist/packem_shared/{index-mFEIaT45.mjs → index-D03C6Kao.mjs} +1 -1
  27. package/dist/packem_shared/{ip-reads-BPDWkzEu.mjs → ip-reads-ByzaRhd2.mjs} +1 -1
  28. package/dist/packem_shared/{server-CRFaUMKQ.mjs → server-5ph4hltf.mjs} +63 -55
  29. package/package.json +1 -1
  30. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DfLhJQrR.mjs +0 -54
  31. package/dist/packem_shared/chain-CXiqZFUk.mjs +0 -1
  32. package/dist/packem_shared/discoverFunctions-mAWlAiuj.mjs +0 -1
  33. package/dist/packem_shared/discoverHyperdriveCalls-BaRayTZe.mjs +0 -1
  34. package/dist/packem_shared/discoverMaskProcedures-CyjXtZgc.mjs +0 -1
  35. package/dist/packem_shared/discoverR2sqlCalls-CZjqFVi_.mjs +0 -1
@@ -0,0 +1 @@
1
+ import{d as o}from"./context-property-calls-DXzNVV1P.mjs";const t=(r,e)=>o(r,e,"sql");export{t as default};
@@ -1 +1 @@
1
- import{Node as i}from"ts-morph";import{collectCallRows as n}from"./isTestPath-DRIdZaij.mjs";import{c as a}from"./attribution-BhGR_h0Z.mjs";import{i as c}from"./database-calls-BRI5W-Mp.mjs";const l=t=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="insert")return!1;const r=e.getExpression();return c(r)},g=t=>{if(!i.isIdentifier(t))return;const e=t.getSymbol(),r=e?.getAliasedSymbol()?.getDeclarations()??e?.getDeclarations()??[];for(const s of r)if(i.isVariableDeclaration(s)){const o=s.getInitializer();if(o&&i.isStringLiteral(o))return o.getLiteralText()}},f=t=>{const e=t.getArguments()[0];return e?i.isStringLiteral(e)?e.getLiteralText():g(e)??"":""},d=(t,e)=>n(t,e,(r,s)=>l(r)?{file:s,line:r.getStartLineNumber(),scope:a(r),table:f(r)}:void 0);export{d as default};
1
+ import{Node as i}from"ts-morph";import{collectCallRows as n}from"./isTestPath-DRIdZaij.mjs";import{c as a}from"./attribution-BhGR_h0Z.mjs";import{i as c}from"./database-calls-Do0YbPCL.mjs";const l=t=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="insert")return!1;const r=e.getExpression();return c(r)},g=t=>{if(!i.isIdentifier(t))return;const e=t.getSymbol(),r=e?.getAliasedSymbol()?.getDeclarations()??e?.getDeclarations()??[];for(const s of r)if(i.isVariableDeclaration(s)){const o=s.getInitializer();if(o&&i.isStringLiteral(o))return o.getLiteralText()}},f=t=>{const e=t.getArguments()[0];return e?i.isStringLiteral(e)?e.getLiteralText():g(e)??"":""},d=(t,e)=>n(t,e,(r,s)=>l(r)?{file:s,line:r.getStartLineNumber(),scope:a(r),table:f(r)}:void 0);export{d as default};
@@ -0,0 +1 @@
1
+ import"./isTestPath-DRIdZaij.mjs";import"./attribution-BhGR_h0Z.mjs";import"./database-calls-Do0YbPCL.mjs";import"./classify-procedure-call-n9urVsqb.mjs";import{d as a}from"./index-D03C6Kao.mjs";export{a as default};
@@ -1 +1 @@
1
- import{Node as s,SyntaxKind as d}from"ts-morph";import{listLunoraSourceFiles as m,lunoraRelativePath as g,handlerOf as u,descendantsOfKind as l}from"./isTestPath-DRIdZaij.mjs";import{j as N,h as x}from"./attribution-BhGR_h0Z.mjs";import{c as p}from"./classify-procedure-call-BZ164dkJ.mjs";const h={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},E=new Set(["globalThis","self"]),v=new Set(["globalThis","self","window"]),I=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const t=e.getExpression();if(s.isIdentifier(t)&&v.has(t.getText()))return e.getName()}},S=e=>{const t=e.getExpression();if(s.isIdentifier(t)){const o=t.getText();return o==="fetch"||o==="Date"?o:void 0}if(!s.isPropertyAccessExpression(t))return;const n=t.getName(),i=I(t.getExpression());if(i!==void 0)return n==="fetch"&&E.has(i)?"fetch":h[`${i}.${n}`]},T=e=>{const t=e.getExpression();if(!s.isIdentifier(t)||t.getText()!=="Date")return;const n=e.getArguments(),i=n.every(o=>s.isNumericLiteral(o)||s.isStringLiteral(o)||s.isNoSubstitutionTemplateLiteral(o));return n.length>0&&i?void 0:"new Date"},y=e=>{const t=e.getInitializer();if(!t||!s.isCallExpression(t))return;const n=p(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const i=u(t,n.receiver);return i?{exportName:x(e)??e.getName(),handler:i,kind:n.kind}:void 0},L=e=>{const t=new Set(["ctx"]),n=r=>{if(s.isObjectBindingPattern(r))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getNameNode().getText(),f=a.getNameNode();c==="ctx"&&s.isIdentifier(f)&&t.add(f.getText())}},[i]=s.isParametered(e)?e.getParameters():[],o=i!==void 0&&s.isIdentifier(i.getNameNode())?i.getNameNode().getText():void 0;if(i!==void 0){const r=i.getNameNode();s.isIdentifier(r)?t.add(r.getText()):n(r)}for(const r of l(e,d.VariableDeclaration)){const a=r.getInitializer();o!==void 0&&a!==void 0&&s.isIdentifier(a)&&a.getText()===o&&n(r.getNameNode())}return t},P=(e,t,n)=>{const i=e.getExpression();if(!s.isPropertyAccessExpression(i)||i.getName()!=="random")return!1;const o=i.getExpression();return!s.isIdentifier(o)||!t.has(o.getText())?!1:o.getSymbol()?.getDeclarations()[0]?.getFirstAncestor(c=>s.isFunctionLikeDeclaration(c))===n},w=(e,t)=>{const n=[],i=L(e.handler);for(const o of l(e.handler,d.CallExpression)){const r=e.kind==="query"&&P(o,i,e.handler)?"ctx.random":S(o);r!==void 0&&n.push({callee:r,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}for(const o of l(e.handler,d.NewExpression)){const r=T(o);r!==void 0&&n.push({callee:r,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}return n},O=(e,t)=>{const n=[];for(const i of N(e)){const o=y(i);o&&n.push(...w(o,t))}return n},A=(e,t)=>{const n=[];for(const i of m(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...O(o,g(t,i)))}return n};export{A as default};
1
+ import{Node as s,SyntaxKind as d}from"ts-morph";import{listLunoraSourceFiles as m,lunoraRelativePath as g,handlerOf as u,descendantsOfKind as l}from"./isTestPath-DRIdZaij.mjs";import{j as N,h as x}from"./attribution-BhGR_h0Z.mjs";import{c as p}from"./classify-procedure-call-n9urVsqb.mjs";const h={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},E=new Set(["globalThis","self"]),v=new Set(["globalThis","self","window"]),I=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const t=e.getExpression();if(s.isIdentifier(t)&&v.has(t.getText()))return e.getName()}},S=e=>{const t=e.getExpression();if(s.isIdentifier(t)){const o=t.getText();return o==="fetch"||o==="Date"?o:void 0}if(!s.isPropertyAccessExpression(t))return;const n=t.getName(),i=I(t.getExpression());if(i!==void 0)return n==="fetch"&&E.has(i)?"fetch":h[`${i}.${n}`]},T=e=>{const t=e.getExpression();if(!s.isIdentifier(t)||t.getText()!=="Date")return;const n=e.getArguments(),i=n.every(o=>s.isNumericLiteral(o)||s.isStringLiteral(o)||s.isNoSubstitutionTemplateLiteral(o));return n.length>0&&i?void 0:"new Date"},y=e=>{const t=e.getInitializer();if(!t||!s.isCallExpression(t))return;const n=p(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const i=u(t,n.receiver);return i?{exportName:x(e)??e.getName(),handler:i,kind:n.kind}:void 0},L=e=>{const t=new Set(["ctx"]),n=r=>{if(s.isObjectBindingPattern(r))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getNameNode().getText(),f=a.getNameNode();c==="ctx"&&s.isIdentifier(f)&&t.add(f.getText())}},[i]=s.isParametered(e)?e.getParameters():[],o=i!==void 0&&s.isIdentifier(i.getNameNode())?i.getNameNode().getText():void 0;if(i!==void 0){const r=i.getNameNode();s.isIdentifier(r)?t.add(r.getText()):n(r)}for(const r of l(e,d.VariableDeclaration)){const a=r.getInitializer();o!==void 0&&a!==void 0&&s.isIdentifier(a)&&a.getText()===o&&n(r.getNameNode())}return t},P=(e,t,n)=>{const i=e.getExpression();if(!s.isPropertyAccessExpression(i)||i.getName()!=="random")return!1;const o=i.getExpression();return!s.isIdentifier(o)||!t.has(o.getText())?!1:o.getSymbol()?.getDeclarations()[0]?.getFirstAncestor(c=>s.isFunctionLikeDeclaration(c))===n},w=(e,t)=>{const n=[],i=L(e.handler);for(const o of l(e.handler,d.CallExpression)){const r=e.kind==="query"&&P(o,i,e.handler)?"ctx.random":S(o);r!==void 0&&n.push({callee:r,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}for(const o of l(e.handler,d.NewExpression)){const r=T(o);r!==void 0&&n.push({callee:r,exportName:e.exportName,file:t,kind:e.kind,line:o.getStartLineNumber()})}return n},O=(e,t)=>{const n=[];for(const i of N(e)){const o=y(i);o&&n.push(...w(o,t))}return n},A=(e,t)=>{const n=[];for(const i of m(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...O(o,g(t,i)))}return n};export{A as default};
@@ -1 +1 @@
1
- import{Node as i,SyntaxKind as u}from"ts-morph";import{collectCallRows as x}from"./isTestPath-DRIdZaij.mjs";import{w as E,c as h}from"./attribution-BhGR_h0Z.mjs";import{i as v}from"./database-calls-BRI5W-Mp.mjs";const A=new Set(["withGeoIndex","withIndex","withSearchIndex"]),S=new Set(["collect","collectWithScores","first","paginate","take","unique"]),w=t=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="query")return!1;const n=e.getExpression();return v(n)},y=t=>{const e=[];let n=t;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;e.push(r),n=r}return e},l=t=>{const e=t.getExpression();return i.isPropertyAccessExpression(e)?e.getName():""},m=t=>{if(t===void 0||!(i.isArrowFunction(t)||i.isFunctionExpression(t)))return;const e=t.getParameters()[0]?.getNameNode();return e!==void 0&&i.isIdentifier(e)?e.getText():void 0},O=t=>{let e=t;for(;i.isCallExpression(e)||i.isPropertyAccessExpression(e);)e=e.getExpression();return e},P=(t,e)=>{const n=new Set,s=[t,...t.getDescendantsOfKind(u.CallExpression)].filter(r=>i.isCallExpression(r));for(const r of s){const c=r.getExpression();if(i.isPropertyAccessExpression(c)){const o=O(c);i.isIdentifier(o)&&o.getText()===e&&n.add(c.getName())}}return n},f=(t,e)=>{if(i.isParenthesizedExpression(t))return f(t.getExpression(),e);if(i.isConditionalExpression(t)){const n=f(t.getWhenFalse(),e);return new Set([...f(t.getWhenTrue(),e)].filter(s=>n.has(s)))}return P(t,e)},C=t=>{if(!(i.isArrowFunction(t)||i.isFunctionExpression(t)))return;const e=t.getBody();if(!i.isBlock(e))return i.isExpression(e)?[e]:void 0;const n=e.getDescendantsOfKind(u.ReturnStatement).filter(s=>s.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r))?.compilerNode===t.compilerNode).map(s=>s.getExpression()).filter(s=>s!==void 0);return n.length===0?void 0:n},F=(t,e)=>{const n=C(t);if(n===void 0)return;const[s,...r]=n.map(o=>f(o,e));return[...s??new Set].filter(o=>r.every(d=>d.has(o))).toSorted((o,d)=>o.localeCompare(d))},I=(t,e)=>{const n=new Set;for(const s of t.getDescendantsOfKind(u.PropertyAccessExpression)){const r=s.getExpression();i.isIdentifier(r)&&r.getText()===e&&n.add(s.getName())}for(const s of t.getDescendantsOfKind(u.ElementAccessExpression)){const r=s.getExpression(),c=s.getArgumentExpression();i.isIdentifier(r)&&r.getText()===e&&c!==void 0&&i.isStringLiteral(c)&&n.add(c.getLiteralText())}return[...n]},N=t=>{if(t===void 0)return;const[e,n]=t.getArguments(),s=m(n),r=e!==void 0&&i.isStringLiteral(e)?e.getLiteralText():void 0;return n===void 0?{bounds:[],name:r}:{bounds:s===void 0?void 0:F(n,s),name:r}},T=t=>{const e=t.flatMap(n=>{const s=n.getArguments()[0],r=m(s);return s===void 0||r===void 0?[]:I(s,r)});if(e.length!==0)return[...new Set(e)].toSorted((n,s)=>n.localeCompare(s))},b=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,D=t=>t.some(e=>l(e)==="filter"&&b.test(e.getArguments()[0]?.getText()??"")),L=t=>{const e=t.getArguments()[0];return e&&i.isStringLiteral(e)?e.getLiteralText():""},k=(t,e,n=[])=>{const s=x(t,e,(r,c)=>{if(!w(r))return;const o=y(r),d=o.map(a=>l(a)),p=o.filter(a=>l(a)==="filter"),g=p.length>0;return{file:c,filterFields:g?T(p):void 0,filtersPrimaryKey:g&&D(o),hasFilter:g,hasIndex:d.some(a=>A.has(a)),index:N(o.find(a=>l(a)==="withIndex")),line:r.getStartLineNumber(),scope:h(r),table:L(r),terminal:d.findLast(a=>S.has(a))}});return E(s,n)};export{k as default};
1
+ import{Node as i,SyntaxKind as u}from"ts-morph";import{collectCallRows as x}from"./isTestPath-DRIdZaij.mjs";import{w as E,c as h}from"./attribution-BhGR_h0Z.mjs";import{i as v}from"./database-calls-Do0YbPCL.mjs";const A=new Set(["withGeoIndex","withIndex","withSearchIndex"]),S=new Set(["collect","collectWithScores","first","paginate","take","unique"]),w=t=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="query")return!1;const n=e.getExpression();return v(n)},y=t=>{const e=[];let n=t;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;e.push(r),n=r}return e},l=t=>{const e=t.getExpression();return i.isPropertyAccessExpression(e)?e.getName():""},m=t=>{if(t===void 0||!(i.isArrowFunction(t)||i.isFunctionExpression(t)))return;const e=t.getParameters()[0]?.getNameNode();return e!==void 0&&i.isIdentifier(e)?e.getText():void 0},O=t=>{let e=t;for(;i.isCallExpression(e)||i.isPropertyAccessExpression(e);)e=e.getExpression();return e},P=(t,e)=>{const n=new Set,s=[t,...t.getDescendantsOfKind(u.CallExpression)].filter(r=>i.isCallExpression(r));for(const r of s){const c=r.getExpression();if(i.isPropertyAccessExpression(c)){const o=O(c);i.isIdentifier(o)&&o.getText()===e&&n.add(c.getName())}}return n},f=(t,e)=>{if(i.isParenthesizedExpression(t))return f(t.getExpression(),e);if(i.isConditionalExpression(t)){const n=f(t.getWhenFalse(),e);return new Set([...f(t.getWhenTrue(),e)].filter(s=>n.has(s)))}return P(t,e)},C=t=>{if(!(i.isArrowFunction(t)||i.isFunctionExpression(t)))return;const e=t.getBody();if(!i.isBlock(e))return i.isExpression(e)?[e]:void 0;const n=e.getDescendantsOfKind(u.ReturnStatement).filter(s=>s.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r))?.compilerNode===t.compilerNode).map(s=>s.getExpression()).filter(s=>s!==void 0);return n.length===0?void 0:n},F=(t,e)=>{const n=C(t);if(n===void 0)return;const[s,...r]=n.map(o=>f(o,e));return[...s??new Set].filter(o=>r.every(d=>d.has(o))).toSorted((o,d)=>o.localeCompare(d))},I=(t,e)=>{const n=new Set;for(const s of t.getDescendantsOfKind(u.PropertyAccessExpression)){const r=s.getExpression();i.isIdentifier(r)&&r.getText()===e&&n.add(s.getName())}for(const s of t.getDescendantsOfKind(u.ElementAccessExpression)){const r=s.getExpression(),c=s.getArgumentExpression();i.isIdentifier(r)&&r.getText()===e&&c!==void 0&&i.isStringLiteral(c)&&n.add(c.getLiteralText())}return[...n]},N=t=>{if(t===void 0)return;const[e,n]=t.getArguments(),s=m(n),r=e!==void 0&&i.isStringLiteral(e)?e.getLiteralText():void 0;return n===void 0?{bounds:[],name:r}:{bounds:s===void 0?void 0:F(n,s),name:r}},T=t=>{const e=t.flatMap(n=>{const s=n.getArguments()[0],r=m(s);return s===void 0||r===void 0?[]:I(s,r)});if(e.length!==0)return[...new Set(e)].toSorted((n,s)=>n.localeCompare(s))},b=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,D=t=>t.some(e=>l(e)==="filter"&&b.test(e.getArguments()[0]?.getText()??"")),L=t=>{const e=t.getArguments()[0];return e&&i.isStringLiteral(e)?e.getLiteralText():""},k=(t,e,n=[])=>{const s=x(t,e,(r,c)=>{if(!w(r))return;const o=y(r),d=o.map(a=>l(a)),p=o.filter(a=>l(a)==="filter"),g=p.length>0;return{file:c,filterFields:g?T(p):void 0,filtersPrimaryKey:g&&D(o),hasFilter:g,hasIndex:d.some(a=>A.has(a)),index:N(o.find(a=>l(a)==="withIndex")),line:r.getStartLineNumber(),scope:h(r),table:L(r),terminal:d.findLast(a=>S.has(a))}});return E(s,n)};export{k as default};
@@ -0,0 +1 @@
1
+ import{d as r}from"./context-property-calls-DXzNVV1P.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
@@ -1 +1 @@
1
- import{Node as o}from"ts-morph";import{listLunoraSourceFiles as x,lunoraRelativePath as h,findObjectProperty as m,stringPropertyOf as c}from"./isTestPath-DRIdZaij.mjs";import{e as A}from"./exported-procedure-chains-h8Y7xDjq.mjs";import{r as L}from"./chain-CXiqZFUk.mjs";const E=new Set(["delete","insert","read","update"]),P=(e,t,i)=>{const r=e.getArguments()[0];if(!r||!o.isArrayLiteralExpression(r))return[];const s=[];for(const n of r.getElements()){if(!o.isObjectLiteralExpression(n))continue;const a=c(n,"on");a===void 0||!E.has(a)||s.push({file:t,on:a,procedure:i,table:c(n,"table")??""})}return s},u=e=>{if(!o.isObjectLiteralExpression(e))return[];const t=m(e,"permissions");if(!t||!o.isPropertyAssignment(t))return[];const i=t.getInitializer();if(!i||!o.isArrayLiteralExpression(i))return[];const r=[];for(const s of i.getElements()){if(o.isStringLiteral(s)){r.push(s.getLiteralText());continue}if(o.isCallExpression(s)){const n=s.getArguments()[0];n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}}return r},f=(e,t)=>t===void 0?e:{...e,description:t},v=e=>{if(o.isCallExpression(e)){const t=e.getArguments()[0];if(!t||!o.isStringLiteral(t))return;const i=e.getArguments()[1],r=i?c(i,"description"):void 0,s=i?u(i):[];return f({name:t.getLiteralText(),permissions:s},r)}if(o.isObjectLiteralExpression(e)){const t=c(e,"name");return t===void 0?void 0:f({name:t,permissions:u(e)},c(e,"description"))}},y=e=>{const t=e.getArguments()[1];if(!t||!o.isObjectLiteralExpression(t))return[];const i=m(t,"roles");if(!i||!o.isPropertyAssignment(i))return[];const r=i.getInitializer();if(!r||!o.isArrayLiteralExpression(r))return[];const s=[];for(const n of r.getElements()){const a=v(n);a&&s.push(a)}return s},O=(e,t,i)=>{const r=L(e);return{policies:r.flatMap(s=>P(s,t,i)),roles:r.flatMap(s=>y(s))}},I=(e,t)=>{const i=[],r=new Map;for(const s of x(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),a=h(t,s);for(const{name:g,receiver:d}of A(n)){const p=O(d,a,g);i.push(...p.policies);for(const l of p.roles)r.has(l.name)||r.set(l.name,l)}}return{policies:i,roles:[...r.values()]}};export{I as default};
1
+ import{Node as o}from"ts-morph";import{listLunoraSourceFiles as x,lunoraRelativePath as h,findObjectProperty as m,stringPropertyOf as c}from"./isTestPath-DRIdZaij.mjs";import{e as A}from"./exported-procedure-chains-DomRzs5_.mjs";import{r as L}from"./chain-CONXUmWW.mjs";const E=new Set(["delete","insert","read","update"]),P=(e,t,i)=>{const r=e.getArguments()[0];if(!r||!o.isArrayLiteralExpression(r))return[];const s=[];for(const n of r.getElements()){if(!o.isObjectLiteralExpression(n))continue;const a=c(n,"on");a===void 0||!E.has(a)||s.push({file:t,on:a,procedure:i,table:c(n,"table")??""})}return s},u=e=>{if(!o.isObjectLiteralExpression(e))return[];const t=m(e,"permissions");if(!t||!o.isPropertyAssignment(t))return[];const i=t.getInitializer();if(!i||!o.isArrayLiteralExpression(i))return[];const r=[];for(const s of i.getElements()){if(o.isStringLiteral(s)){r.push(s.getLiteralText());continue}if(o.isCallExpression(s)){const n=s.getArguments()[0];n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}}return r},f=(e,t)=>t===void 0?e:{...e,description:t},v=e=>{if(o.isCallExpression(e)){const t=e.getArguments()[0];if(!t||!o.isStringLiteral(t))return;const i=e.getArguments()[1],r=i?c(i,"description"):void 0,s=i?u(i):[];return f({name:t.getLiteralText(),permissions:s},r)}if(o.isObjectLiteralExpression(e)){const t=c(e,"name");return t===void 0?void 0:f({name:t,permissions:u(e)},c(e,"description"))}},y=e=>{const t=e.getArguments()[1];if(!t||!o.isObjectLiteralExpression(t))return[];const i=m(t,"roles");if(!i||!o.isPropertyAssignment(i))return[];const r=i.getInitializer();if(!r||!o.isArrayLiteralExpression(r))return[];const s=[];for(const n of r.getElements()){const a=v(n);a&&s.push(a)}return s},O=(e,t,i)=>{const r=L(e);return{policies:r.flatMap(s=>P(s,t,i)),roles:r.flatMap(s=>y(s))}},I=(e,t)=>{const i=[],r=new Map;for(const s of x(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),a=h(t,s);for(const{name:g,receiver:d}of A(n)){const p=O(d,a,g);i.push(...p.policies);for(const l of p.roles)r.has(l.name)||r.set(l.name,l)}}return{policies:i,roles:[...r.values()]}};export{I as default};
@@ -1 +1 @@
1
- import{Node as o}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as f,findObjectProperty as u}from"./isTestPath-DRIdZaij.mjs";import{j as p,h as m}from"./attribution-BhGR_h0Z.mjs";import{t as d}from"./database-calls-BRI5W-Mp.mjs";import{c as b}from"./classify-procedure-call-BZ164dkJ.mjs";import{r as h}from"./chain-CXiqZFUk.mjs";const g=e=>{const t=e.getArguments()[0];if(!t||!o.isArrayLiteralExpression(t))return[];const r=[];for(const s of t.getElements()){if(!o.isObjectLiteralExpression(s))continue;const i=u(s,"table");if(!i||!o.isPropertyAssignment(i))continue;const n=i.getInitializer();n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}return r},y=e=>{const t=h(e);return{rlsTables:t.flatMap(r=>g(r)),usesRls:t.length>0}},v=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),x=new Set(["delete","deleteMany","insert","insertMany","patch","patchIf","patchMany","replace"]),P=(e,t)=>{if(!o.isVariableDeclaration(e))return;const r=e.getInitializer();if(!r||!o.isCallExpression(r))return;const s=b(r);if(!s)return;const i=s.receiver?y(s.receiver):{rlsTables:[],usesRls:!1},{tablesRead:n,tablesWritten:a}=d(e,v,x);return{exportName:m(e)??e.getName(),file:t,rlsTables:i.rlsTables,tablesRead:n,tablesWritten:a,usesRls:i.usesRls,visibility:s.visibility}},M=(e,t)=>{const r=[];for(const s of c(t)){const i=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=f(t,s);for(const a of p(i)){const l=P(a,n);l&&r.push(l)}}return r};export{M as default};
1
+ import{Node as o}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as f,findObjectProperty as u}from"./isTestPath-DRIdZaij.mjs";import{j as p,h as m}from"./attribution-BhGR_h0Z.mjs";import{t as d}from"./database-calls-Do0YbPCL.mjs";import{c as b}from"./classify-procedure-call-n9urVsqb.mjs";import{r as h}from"./chain-CONXUmWW.mjs";const g=e=>{const t=e.getArguments()[0];if(!t||!o.isArrayLiteralExpression(t))return[];const r=[];for(const s of t.getElements()){if(!o.isObjectLiteralExpression(s))continue;const i=u(s,"table");if(!i||!o.isPropertyAssignment(i))continue;const n=i.getInitializer();n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}return r},y=e=>{const t=h(e);return{rlsTables:t.flatMap(r=>g(r)),usesRls:t.length>0}},v=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),x=new Set(["delete","deleteMany","insert","insertMany","patch","patchIf","patchMany","replace"]),P=(e,t)=>{if(!o.isVariableDeclaration(e))return;const r=e.getInitializer();if(!r||!o.isCallExpression(r))return;const s=b(r);if(!s)return;const i=s.receiver?y(s.receiver):{rlsTables:[],usesRls:!1},{tablesRead:n,tablesWritten:a}=d(e,v,x);return{exportName:m(e)??e.getName(),file:t,rlsTables:i.rlsTables,tablesRead:n,tablesWritten:a,usesRls:i.usesRls,visibility:s.visibility}},M=(e,t)=>{const r=[];for(const s of c(t)){const i=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=f(t,s);for(const a of p(i)){const l=P(a,n);l&&r.push(l)}}return r};export{M as default};
@@ -1 +1 @@
1
- import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./isTestPath-DRIdZaij.mjs";import{w as d}from"./classify-procedure-call-BZ164dkJ.mjs";import{e as m}from"./exported-procedure-chains-h8Y7xDjq.mjs";const h=new Set(["delete","list","read","write"]),g=t=>d(t,"use","storageRules"),x=(t,s,n)=>{const e=t.getArguments()[0];if(!e||!u.isArrayLiteralExpression(e))return[];const i=[];for(const o of e.getElements()){if(!u.isObjectLiteralExpression(o))continue;const r=l(o,"on");if(r===void 0||!h.has(r))continue;const a=l(o,"prefix"),c={bucket:l(o,"bucket")??"",file:s,on:r,procedure:n};a!==void 0&&(c.prefix=a),i.push(c)}return i},A=(t,s)=>{const n=[];for(const e of f(s)){const i=t.getSourceFile(e)??t.addSourceFileAtPath(e),o=p(s,e);for(const{name:r,receiver:a}of m(i))for(const c of g(a))n.push(...x(c,o,r))}return{rules:n}};export{A as default};
1
+ import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./isTestPath-DRIdZaij.mjs";import{w as d}from"./classify-procedure-call-n9urVsqb.mjs";import{e as m}from"./exported-procedure-chains-DomRzs5_.mjs";const h=new Set(["delete","list","read","write"]),g=t=>d(t,"use","storageRules"),x=(t,s,n)=>{const e=t.getArguments()[0];if(!e||!u.isArrayLiteralExpression(e))return[];const i=[];for(const o of e.getElements()){if(!u.isObjectLiteralExpression(o))continue;const r=l(o,"on");if(r===void 0||!h.has(r))continue;const a=l(o,"prefix"),c={bucket:l(o,"bucket")??"",file:s,on:r,procedure:n};a!==void 0&&(c.prefix=a),i.push(c)}return i},A=(t,s)=>{const n=[];for(const e of f(s)){const i=t.getSourceFile(e)??t.addSourceFileAtPath(e),o=p(s,e);for(const{name:r,receiver:a}of m(i))for(const c of g(a))n.push(...x(c,o,r))}return{rules:n}};export{A as default};
@@ -1,11 +1,11 @@
1
- import{APP_METHOD_CAPABILITIES as T}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{i as N}from"./schema-BgM8A3XV.mjs";import{a as I,I as L,G as y}from"./shared-Cn7dMQ_u.mjs";const j={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...T.filter(({key:r})=>e.capabilities.has(r)).map(({appMethod:r})=>r),...e.hasVectors?[j]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,l=e=>e.tables.some(r=>N(r)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,$=e=>e.hasScheduler?`
1
+ import{APP_METHOD_CAPABILITIES as N}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{i as I}from"./schema-BgM8A3XV.mjs";import{a as L,I as j,G as y}from"./shared-Cn7dMQ_u.mjs";const $={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...N.filter(({key:t})=>e.capabilities.has(t)).map(({appMethod:t})=>t),...e.hasVectors?[$]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,c=e=>e.tables.some(t=>I(t)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,P=e=>e.hasScheduler?`
2
2
  /** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
3
3
  private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
4
4
  const namespace = this.schedulerDeclaration?.namespace(env);
5
5
 
6
6
  return namespace ? createScheduler({${e.jurisdiction?` jurisdiction: ${JSON.stringify(e.jurisdiction)},`:""} namespace }) : undefined;
7
7
  }
8
- `:"",P=e=>e?`
8
+ `:"",G=e=>e?`
9
9
  /**
10
10
  * One bucket's \`Storage\`, signing under the name it is registered as.
11
11
  *
@@ -114,7 +114,7 @@ import{APP_METHOD_CAPABILITIES as T}from"./CAPABILITY_PROBES-BuNEmlCO.mjs";impor
114
114
  storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
115
115
  };
116
116
  }
117
- `:"",G=e=>e?`
117
+ `:"",_=e=>e?`
118
118
  /**
119
119
  * Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`).
120
120
  *
@@ -382,12 +382,12 @@ const buildGlobalCdcApplier =
382
382
 
383
383
  return request.changes.length;
384
384
  };
385
- `:"",_=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(async () => (await import("postgres")).default(env.HYPERDRIVE.connectionString, { fetch_types: false, max: 5 })))`. Called per request, by the shard and by the stateless worker\'s admin plane, so return an exec on a connection opened for that call: never cache a driver or socket at module scope, since Workers refuse I/O across requests. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],M=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[],...e.hasAdminRevocations===!1?[]:[" private adminRevocationsSelector?: Selector<Env, ShardNamespaceLike>;"]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;",...e.hasDeliveryAuthorization===!1?[]:[' private deliveryAuthorizationSelector?: ShardConfig["deliveryAuthorization"];']," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...w(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...l(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],W=e=>f(e).map(({configKey:r,doc:t,method:a})=>` /** ${t} */
386
- public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${r}"]>>): this {
387
- this.shardExtras.${r} = factory as NonNullable<ShardConfig["${r}"]>;
385
+ `:"",M=e=>[...e.hasStorage?["/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket(\"name\")` and the studio's bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. Omit it and `ctx.storage` in a mutation, action or HTTP handler (and the studio's copy-URL) signs against the origin the request reached the worker on — no per-environment value to ship. Queries get no such fallback (a live query re-runs with no request behind it), so a query that signs URLs needs this set. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}"]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(async () => (await import("postgres")).default(env.HYPERDRIVE.connectionString, { fetch_types: false, max: 5 })))`. Called per request, by the shard and by the stateless worker\'s admin plane, so return an exec on a connection opened for that call: never cache a driver or socket at module scope, since Workers refuse I/O across requests. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],W=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[],...e.hasAdminRevocations===!1?[]:[" private adminRevocationsSelector?: Selector<Env, ShardNamespaceLike>;"]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;",...e.hasDeliveryAuthorization===!1?[]:[' private deliveryAuthorizationSelector?: ShardConfig["deliveryAuthorization"];']," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...w(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[],...c(e)?[" private shardRegistrySelector?: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>;"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],B=e=>f(e).map(({configKey:t,doc:r,method:a})=>` /** ${r} */
386
+ public ${a}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${t}"]>>): this {
387
+ this.shardExtras.${t} = factory as NonNullable<ShardConfig["${t}"]>;
388
388
 
389
389
  return this;
390
- }`),B=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
390
+ }`),H=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
391
391
  public admin(selector: Selector<Env, string>): this {
392
392
  this.adminToken = selector;
393
393
 
@@ -446,7 +446,7 @@ const buildGlobalCdcApplier =
446
446
  this.adminRevocationsSelector = selector;
447
447
 
448
448
  return this;
449
- }`],...l(e)?[" /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). Each shard registers itself for the `.shardBy()` tables it writes, and cross-shard export, CDC sync and migrations fan out to the shards it lists. Without it they refuse a `.shardBy()` table. */\n public shardRegistry(selector: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>): this {\n this.shardRegistrySelector = selector;\n\n return this;\n }"]:[],...e.hasSourcedTables?[` /** Resolve the SQL client a \`.source(...)\` table's ingest poll reads from, given the wrangler Hyperdrive binding it named. Build it with \`@lunora/hyperdrive\`'s \`createHyperdrive\` plus your driver adapter. REQUIRED for a sourced table: without it every poll tick records "no sourceClient resolved for binding" and the table stays empty. */
449
+ }`],...c(e)?[" /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). Each shard registers itself for the `.shardBy()` tables it writes, and cross-shard export, CDC sync and migrations fan out to the shards it lists. Without it they refuse a `.shardBy()` table. */\n public shardRegistry(selector: Selector<Env, ShardNamespaceLike | ShardRegistryRpc>): this {\n this.shardRegistrySelector = selector;\n\n return this;\n }"]:[],...e.hasSourcedTables?[` /** Resolve the SQL client a \`.source(...)\` table's ingest poll reads from, given the wrangler Hyperdrive binding it named. Build it with \`@lunora/hyperdrive\`'s \`createHyperdrive\` plus your driver adapter. REQUIRED for a sourced table: without it every poll tick records "no sourceClient resolved for binding" and the table stays empty. */
450
450
  public sourceClient(factory: (env: Env, binding: string) => ReturnType<NonNullable<ShardConfig["sourceClient"]>>): this {
451
451
  this.sourceClientFactory = factory as NonNullable<ShardConfig["sourceClient"]>;
452
452
 
@@ -456,8 +456,8 @@ const buildGlobalCdcApplier =
456
456
  this.storageDeclaration = declaration;
457
457
 
458
458
  return this;
459
- }`]:[],...W(e)],H=e=>{const r=a=>e.hasScheduler?`
460
- ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",t=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),",...e.hasDeliveryAuthorization===!1?[]:[" ...(this.deliveryAuthorizationSelector === undefined ? {} : { deliveryAuthorization: this.deliveryAuthorizationSelector }),"]," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
459
+ }`]:[],...B(e)],U=e=>{const t=a=>e.hasScheduler?`
460
+ ...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${a}["scheduler"] } : {}),`:"",r=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),",...e.hasDeliveryAuthorization===!1?[]:[" ...(this.deliveryAuthorizationSelector === undefined ? {} : { deliveryAuthorization: this.deliveryAuthorizationSelector }),"]," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
461
461
  ? {
462
462
  d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown> | undefined; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null | undefined }) => {
463
463
  const env = rawEnv as Env;
@@ -481,7 +481,7 @@ const buildGlobalCdcApplier =
481
481
  : undefined;
482
482
 
483
483
  return createD1CtxDb({
484
- ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${r("D1CtxDbOptions")}
484
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("D1CtxDbOptions")}
485
485
  ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
486
486
  // Getters, like the cross-shard identity above: reading the
487
487
  // request's caller marks the live query as caller-dependent, so
@@ -533,7 +533,7 @@ const buildGlobalCdcApplier =
533
533
  : undefined;
534
534
 
535
535
  return createHyperdriveGlobalCtxDb({
536
- ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${r("SqlCtxDbOptions")}
536
+ ...(crossShard ? { crossShardCounter: crossShard.crossShardCounter, crossShardReader: crossShard.crossShardReader } : {}),${t("SqlCtxDbOptions")}
537
537
  ...(request?.cdcRetentionMs === undefined ? {} : { cdcRetentionMs: request.cdcRetentionMs }),
538
538
  // Getters, like the cross-shard identity above: reading the
539
539
  // request's caller marks the live query as caller-dependent, so
@@ -564,29 +564,30 @@ const buildGlobalCdcApplier =
564
564
  ? {
565
565
  scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
566
566
  }
567
- : {}),`]:[],...l(e)?[" ...(this.shardRegistrySelector ? { shardRegistry: (rawEnv: Record<string, unknown>) => this.shardRegistrySelector?.(rawEnv as Env) } : {}),"]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>, origin?: string) => this.resolveStorage(rawEnv as Env, origin) } : {}),"]:[],...w(e)?[" ...this.shardExtras,"]:[]];return t.length>0?`
568
- ${t.join(`
567
+ : {}),`]:[],...c(e)?[" ...(this.shardRegistrySelector ? { shardRegistry: (rawEnv: Record<string, unknown>) => this.shardRegistrySelector?.(rawEnv as Env) } : {}),"]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>, origin?: string) => this.resolveStorage(rawEnv as Env, origin) } : {}),"]:[],...w(e)?[" ...this.shardExtras,"]:[]];return r.length>0?`
568
+ ${r.join(`
569
569
  `)}
570
- `:""},U=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],F=(e,r)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${r?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],z=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],Q=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],J=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, applySqlMigrationFiles, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],K=e=>e?['import notifyConfig from "../notify.js";']:[],V=e=>k(e)?e.lazyFunctions===!0?['import type { dispatchAgentEmail } from "@lunora/agent/inbound";']:['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],Y=e=>k(e)&&e.lazyFunctions!==!0?['import * as lunoraAgentDefinitions from "../agents.js";']:[],X=e=>{const{hasFramework:r,hasGlobal:t,hasHyperdriveGlobal:a,hasQueue:s,useUmbrella:n}=e,i=n?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","SecurityOptions","ShardNamespaceLike",...l(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...s?["TriggerTrace"]:[],...t?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...r?["FrameworkHostHandler"]:[]],c=[...t||a?["createCrossShardRelationCapabilities"]:[],...l(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...r?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((o,u)=>o.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${c} } from "${i}";`]},Z=e=>{const{hasAccess:r,hasAuth:t,hasGlobal:a,hasHyperdriveGlobal:s,hasKvIntrospector:n,hasQueue:i,hasScheduler:d,hasStorage:c,hasWorkflow:o}=e;return[...t?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...F(r,t),...J(a),...s?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { applyHyperdriveGlobalCdc, createHyperdriveGlobalCtxDb, createHyperdriveGlobalIntrospector, exportHyperdriveGlobalRows, importHyperdriveGlobalRows, readHyperdriveGlobalCdc } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...z(n),...Q(e.hasVectors),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...c?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...o?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...V(e),...X(e),"",...U(e.identity),...Y(e),...a||s?['import schema from "../schema.js";']:[],...K(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";',...e.lazyFunctions===!0?[]:['import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']]:[],'import { createShardDO } from "./shard.js";',...p(e)?[`import { liveStreamRouter } from "${e.useUmbrella?"lunorash/server":"@lunora/server"}";`]:[],...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},ee=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
570
+ `:""},F=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],z=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],Q=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],J=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],K=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, applySqlMigrationFiles, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],V=e=>e?['import notifyConfig from "../notify.js";']:[],Y=e=>k(e)?e.lazyFunctions===!0?['import type { dispatchAgentEmail } from "@lunora/agent/inbound";']:['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],X=e=>k(e)&&e.lazyFunctions!==!0?['import * as lunoraAgentDefinitions from "../agents.js";']:[],Z=e=>{const{hasFramework:t,hasGlobal:r,hasHyperdriveGlobal:a,hasQueue:s,useUmbrella:n}=e,i=n?"lunorash/runtime":"@lunora/runtime",d=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","SecurityOptions","ShardNamespaceLike",...c(e)?["ShardRegistryRpc"]:[],"WorkerOptions",...s?["TriggerTrace"]:[],...r?["GlobalIntrospector"]:[],...e.tables.length>0?["ShardingInfo"]:[],...t?["FrameworkHostHandler"]:[]],l=[...r||a?["createCrossShardRelationCapabilities"]:[],...c(e)?["createDynamicShardRegistry","createQueryCoordinator"]:[],"createWorker",...e.jurisdiction?["declareAppJurisdiction"]:[],"resolveLogArchiveFromEnv",...e.hasAuth?["memoizeIdentity"]:[],...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...d].toSorted((o,u)=>o.localeCompare(u)).join(", ")} } from "${i}";`,`import { ${l} } from "${i}";`]},ee=e=>{const{hasAccess:t,hasAuth:r,hasGlobal:a,hasHyperdriveGlobal:s,hasKvIntrospector:n,hasQueue:i,hasScheduler:d,hasStorage:l,hasWorkflow:o}=e;return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import type * as LunoraAuthModule from "./authModule.js";']:[],...z(t,r),...K(a),...s?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { applyHyperdriveGlobalCdc, createHyperdriveGlobalCtxDb, createHyperdriveGlobalIntrospector, exportHyperdriveGlobalRows, importHyperdriveGlobalRows, readHyperdriveGlobalCdc } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...Q(n),...J(e.hasVectors),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...l?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...o?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...Y(e),...Z(e),"",...F(e.identity),...X(e),...a||s?['import schema from "../schema.js";']:[],...V(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...i?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";',...e.lazyFunctions===!0?[]:['import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']]:[],'import { createShardDO } from "./shard.js";',...p(e)?[`import { liveStreamRouter } from "${e.useUmbrella?"lunorash/server":"@lunora/server"}";`]:[],...e.hasVectors?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},S=e=>e.authClaims===void 0||e.authClaims.length===0?void 0:JSON.stringify(e.authClaims),te=e=>{const t=S(e);return t===void 0?"":`, ${t}`},re=e=>{const t=S(e);return t===void 0?"":`
571
+ claims: ${t},`},ae=e=>e.jurisdiction&&e.jurisdictionPinsAuth===!0?`
571
572
  // The schema's jurisdiction pins the auth object like every other DO.
572
- jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",te=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,re=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
573
- ${e.tables.map(r=>` [${JSON.stringify(r.name)}, ${te(r.shardMode)}],`).join(`
573
+ jurisdiction: ${JSON.stringify(e.jurisdiction)},`:"",se=e=>typeof e=="string"?`{ mode: { kind: ${JSON.stringify(e)} } }`:`{ mode: { field: ${JSON.stringify(e.field)}, kind: "shardBy" } }`,ne=e=>[...e.tables.length>0?[` const tableSharding = new Map<string, ShardingInfo>([
574
+ ${e.tables.map(t=>` [${JSON.stringify(t.name)}, ${se(t.shardMode)}],`).join(`
574
575
  `)}
575
576
  ]);
576
577
 
577
578
  options.listSchemaTables = () => [...tableSharding.keys()];
578
- options.resolveTableSharding = (table) => tableSharding.get(table);`]:[],...l(e)?[` const shardRegistry = this.shardRegistrySelector?.(env);
579
+ options.resolveTableSharding = (table) => tableSharding.get(table);`]:[],...c(e)?[` const shardRegistry = this.shardRegistrySelector?.(env);
579
580
 
580
581
  if (shardRegistry) {
581
582
  options.queryCoordinator = createQueryCoordinator({ registry: createDynamicShardRegistry({ ${e.jurisdiction?`jurisdiction: ${JSON.stringify(e.jurisdiction)}, `:""}env, namespace: shardRegistry }) });
582
- }`]:[]],ae=[` const adminRevocations = this.adminRevocationsSelector?.(env);
583
+ }`]:[]],oe=[` const adminRevocations = this.adminRevocationsSelector?.(env);
583
584
 
584
585
  if (adminRevocations) {
585
586
  options.adminRevocations = adminRevocations;
586
- }`],S=e=>(e.liveStreamDeclarations??[]).map(r=>{if(I(r.exportName,"live stream export name"),!L.test(r.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(r.filePath)}`);return` { id: ${JSON.stringify(r.id)}, load: () => import("../${r.filePath}.js").then((m) => m.${r.exportName}) },`}),se=e=>p(e)?[" httpRouter: liveStreamRouter([",...S(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],ne=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(r=>[` ${JSON.stringify(`GET /live/${r.id}/connect`)},`,` ${JSON.stringify(`POST /live/${r.id}/control`)},`])," ],"]:[],oe=e=>p(e)?`liveStreamRouter([
587
- ${S(e).join(`
587
+ }`],E=e=>(e.liveStreamDeclarations??[]).map(t=>{if(L(t.exportName,"live stream export name"),!j.test(t.filePath))throw new Error(`@lunora/codegen: live stream file path is not safe to import: ${JSON.stringify(t.filePath)}`);return` { id: ${JSON.stringify(t.id)}, load: () => import("../${t.filePath}.js").then((m) => m.${t.exportName}) },`}),ie=e=>p(e)?[" httpRouter: liveStreamRouter([",...E(e)," ], this.httpRouterApp),"]:[" ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"],le=e=>p(e)?[" liveStreamRoutes: [",...(e.liveStreamDeclarations??[]).flatMap(t=>[` ${JSON.stringify(`GET /live/${t.id}/connect`)},`,` ${JSON.stringify(`POST /live/${t.id}/control`)},`])," ],"]:[],ce=e=>p(e)?`liveStreamRouter([
588
+ ${E(e).join(`
588
589
  `)}
589
- ], host)`:"host",ie=e=>e.agentWorkflows===void 0?[]:[` options.agentWorkflows = ${JSON.stringify(e.agentWorkflows)};`],ce=e=>[...re(e),...e.hasAdminRevocations===!1?[]:ae,...e.hasScheduler?[` if (this.schedulerDeclaration) {
590
+ ], host)`:"host",de=e=>e.agentWorkflows===void 0?[]:[` options.agentWorkflows = ${JSON.stringify(e.agentWorkflows)};`],he=e=>[...ne(e),...e.hasAdminRevocations===!1?[]:oe,...e.hasScheduler?[` if (this.schedulerDeclaration) {
590
591
  options.schedulerDO = this.schedulerDeclaration.namespace(env);
591
592
  }`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
592
593
  const source = workflowEnv as Record<string, unknown>;
@@ -718,7 +719,7 @@ ${S(e).join(`
718
719
  // Memoised on the declaration: each worker built for a new \`env\` runs
719
720
  // these options again, and \`options(env)\` rebuilds every plugin.
720
721
  discoveryPaths,
721
- internalSecret,${ee(e)}
722
+ internalSecret,${ae(e)}${re(e)}
722
723
  namespace,
723
724
  ...(objectName === undefined ? {} : { objectName }),
724
725
  });
@@ -760,7 +761,7 @@ ${S(e).join(`
760
761
  // the same claims (role, expiry, profile, and the active organization and
761
762
  // team checked against membership) on the identity, and it is unit-tested
762
763
  // where this template cannot be.
763
- return resolveSessionIdentity(auth, (request as Request).headers);
764
+ return resolveSessionIdentity(auth, (request as Request).headers${te(e)});
764
765
  };
765
766
  const authInstance = getAuth();
766
767
 
@@ -826,9 +827,16 @@ ${S(e).join(`
826
827
  memo = memoizeIdentity(options.resolveIdentity, {
827
828
  // better-auth resolves the session from ALL request headers, so the key
828
829
  // must cover every header a supported plugin authenticates on: the
829
- // session cookie, \`Authorization\` (bearer / jwt) and \`x-api-key\` (apiKey).
830
+ // session cookie and \`Authorization\` (bearer / jwt). \`x-api-key\` requests are never keyed (see below).
830
831
  cacheKey: (request: Request) => {
831
- const parts = ["authorization", "cookie", "x-api-key"].map((name) => request.headers.get(name) ?? "");
832
+ // A revoked API key must stop resolving on its next call. Revocation is a row
833
+ // delete with nothing in the cookie to change, so a key request is never
834
+ // memoised across requests; the lookup is one row read per call.
835
+ if (request.headers.get("x-api-key") !== null) {
836
+ return undefined;
837
+ }
838
+
839
+ const parts = ["authorization", "cookie"].map((name) => request.headers.get(name) ?? "");
832
840
 
833
841
  if (parts.every((part) => part === "")) {
834
842
  return undefined;
@@ -857,16 +865,16 @@ ${S(e).join(`
857
865
  options.resolveIdentity = fallback ? composeResolvers(accessResolver, fallback) : accessResolver;
858
866
  }`:` if (this.accessSelector) {
859
867
  options.resolveIdentity = createAccessResolver(this.accessSelector(env));
860
- }`]:[],...ie(e),...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
861
- ${e.voiceAgents.map(r=>` ${JSON.stringify(r.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(r.bindingName)}] as ShardNamespaceLike,`).join(`
868
+ }`]:[],...de(e),...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
869
+ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
862
870
  `)}
863
- };`]:[]],le=e=>e.hasQueue?[` queue: ${e.lazyFunctions===!0?"async ":""}(batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace, ${e.liveStreams?"queueLive":"_live"}: Parameters<typeof dispatchQueueBatch>[2]["live"], queueFetch: Parameters<typeof dispatchQueueBatch>[2]["fetchImpl"]): Promise<void> =>`,` dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], ${e.lazyFunctions===!0?'(await import("./queues.js")).LUNORA_QUEUE_REGISTRY':"LUNORA_QUEUE_REGISTRY"}, {`," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," holdSeconds: trigger.holdSeconds,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[],de=e=>[' aiChatBinding: (env as Record<string, unknown>)["AI"] as WorkerOptions["aiChatBinding"],',' aiOptInLevel: (env as Record<string, unknown>)["LUNORA_AI_OPT_IN"] as WorkerOptions["aiOptInLevel"],'," cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture: deferred.architecture,"]:[],...e.wantsOpenApi?[" openApiSpec: deferred.openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec: deferred.openRpcSpec,"]:[],...le(e),...se(e),...ne(e)," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),",...e.spaAssetsBindings===void 0||e.spaAssetsBindings.length===0?[]:[` spaAssets: (${e.spaAssetsBindings.map(r=>`(env as Record<string, unknown>)[${JSON.stringify(r)}]`).join(" ?? ")}) as WorkerOptions["spaAssets"],`]],he=e=>e?`
871
+ };`]:[]],ue=e=>e.hasQueue?[` queue: ${e.lazyFunctions===!0?"async ":""}(batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace, ${e.liveStreams?"queueLive":"_live"}: Parameters<typeof dispatchQueueBatch>[2]["live"], queueFetch: Parameters<typeof dispatchQueueBatch>[2]["fetchImpl"]): Promise<void> =>`,` dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], ${e.lazyFunctions===!0?'(await import("./queues.js")).LUNORA_QUEUE_REGISTRY':"LUNORA_QUEUE_REGISTRY"}, {`," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," holdSeconds: trigger.holdSeconds,"," traceparent: trigger.traceparent,"," fetchImpl: queueFetch,",...e.liveStreams?[" live: queueLive,"]:[]," }),"]:[],pe=e=>[' aiChatBinding: (env as Record<string, unknown>)["AI"] as WorkerOptions["aiChatBinding"],',' aiOptInLevel: (env as Record<string, unknown>)["LUNORA_AI_OPT_IN"] as WorkerOptions["aiOptInLevel"],'," cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsArchitecture?[" architecture: deferred.architecture,"]:[],...e.wantsOpenApi?[" openApiSpec: deferred.openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec: deferred.openRpcSpec,"]:[],...ue(e),...ie(e),...le(e)," routes: this.routeMap,",...e.liveStreamsWithheld?[" liveStreams: false,"]:[]," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),",...e.spaAssetsBindings===void 0||e.spaAssetsBindings.length===0?[]:[` spaAssets: (${e.spaAssetsBindings.map(t=>`(env as Record<string, unknown>)[${JSON.stringify(t)}]`).join(" ?? ")}) as WorkerOptions["spaAssets"],`]],me=e=>e?`
864
872
  /** The identity memo per \`env\` object, owned by one assembled worker. */
865
873
  type IdentityMemoStore = WeakMap<object, ReturnType<typeof memoizeIdentity>>;
866
- `:"",E=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,ue=e=>{if(!E(e))return"";const t=[[e.wantsArchitecture,"architecture","unknown",'(await import("./architecture.js")).architecture'],[e.hasAuth,"auth","typeof LunoraAuthModule",'await import("./authModule.js")'],[e.wantsOpenApi,"openApiSpec","unknown",'(await import("./openapi.js")).openApiSpec'],[e.wantsOpenRpc,"openRpcSpec","unknown",'(await import("./openrpc.js")).openRpcSpec']].filter(([a])=>a).map(([,a,s,n])=>[a,s,n]);return`
874
+ `:"",R=e=>e.hasAuth||e.wantsArchitecture||e.wantsOpenApi||e.wantsOpenRpc,be=e=>{if(!R(e))return"";const r=[[e.wantsArchitecture,"architecture","unknown",'(await import("./architecture.js")).architecture'],[e.hasAuth,"auth","typeof LunoraAuthModule",'await import("./authModule.js")'],[e.wantsOpenApi,"openApiSpec","unknown",'(await import("./openapi.js")).openApiSpec'],[e.wantsOpenRpc,"openRpcSpec","unknown",'(await import("./openrpc.js")).openRpcSpec']].filter(([a])=>a).map(([,a,s,n])=>[a,s,n]);return`
867
875
  /** What the worker reads only once a request arrives: loaded then, not at isolate startup (Cloudflare caps startup at 1 s of CPU). */
868
876
  interface DeferredModules {
869
- ${t.map(([a,s])=>` ${a}: ${s};`).join(`
877
+ ${r.map(([a,s])=>` ${a}: ${s};`).join(`
870
878
  `)}
871
879
  }
872
880
 
@@ -876,19 +884,19 @@ let deferredModules: Promise<DeferredModules> | undefined;
876
884
  const loadDeferredModules = (): Promise<DeferredModules> =>
877
885
  (deferredModules ??= (async (): Promise<DeferredModules> => {
878
886
  return {
879
- ${t.map(([a,,s])=>` ${a}: ${s},`).join(`
887
+ ${r.map(([a,,s])=>` ${a}: ${s},`).join(`
880
888
  `)}
881
889
  };
882
890
  })());
883
- `},pe=(e,r)=>{const t=`buildWorker(rawEnv as Env${r})`,a=e?`
891
+ `},ge=(e,t)=>{const r=`buildWorker(rawEnv as Env${t})`,a=e?`
884
892
  await ensureAuth(env);`:"",s=e?`
885
893
  await ensureAuth(rawEnv as Env);`:"";return e?{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"target",eventWorkerLine:`
886
- const target = (await authReady(rawEnv as Env)) ? (worker ??= ${t}) : ${t};`}:{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"worker",eventWorkerLine:`
887
- worker ??= ${t};`}},me=e=>E(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
888
- const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},ke=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
889
- `:"",be=e=>{const r=e.emailAgents??[];if(r.length===0)return"";const t=a=>r.map(s=>`${a}{ agent: lunoraAgentDefinitions.${s.exportName}, className: ${JSON.stringify(s.className)} },`).join(`
894
+ const target = (await authReady(rawEnv as Env)) ? (worker ??= ${r}) : ${r};`}:{ensureAuthCall:a,ensureRawAuthCall:s,eventWorker:"worker",eventWorkerLine:`
895
+ worker ??= ${r};`}},ve=e=>R(e)?{asyncIfDeferred:"async ",deferredArgument:", deferred",deferredParameter:", deferred: DeferredModules",loadDeferredLine:`
896
+ const deferred = await loadDeferredModules();`}:{asyncIfDeferred:"",deferredArgument:"",deferredParameter:"",loadDeferredLine:""},Re=e=>e?`${y}export { authDiscoveryPathsFor, createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, handleAuthDiscoveryRequest, handleAuthRequest, lunoraD1Adapter, resolveSessionIdentity } from "@lunora/auth/worker";
897
+ `:"",ye=e=>{const t=e.emailAgents??[];if(t.length===0)return"";const r=a=>t.map(s=>`${a}{ agent: lunoraAgentDefinitions.${s.exportName}, className: ${JSON.stringify(s.className)} },`).join(`
890
898
  `);return e.lazyFunctions!==!0?` composed.email = dispatchAgentEmail([
891
- ${t(" ")}
899
+ ${r(" ")}
892
900
  ]);
893
901
 
894
902
  `:` let agentEmail: ReturnType<typeof dispatchAgentEmail> | undefined;
@@ -898,21 +906,21 @@ ${t(" ")}
898
906
  const [{ dispatchAgentEmail: dispatch }, lunoraAgentDefinitions] = await Promise.all([import("@lunora/agent/inbound"), import("../agents.js")]);
899
907
 
900
908
  agentEmail ??= dispatch([
901
- ${t(" ")}
909
+ ${r(" ")}
902
910
  ]);
903
911
  }
904
912
 
905
913
  return agentEmail(message, rawEnv, context);
906
914
  };
907
915
 
908
- `},ge=e=>e.securityHeaders===void 0?"":`
916
+ `},fe=e=>e.securityHeaders===void 0?"":`
909
917
  /**
910
918
  * \`security.headers\` from \`lunora.config\`: the baseline security headers the Worker sends, and the same values
911
919
  * the build writes into the static assets' \`_headers\`. An app that calls \`createWorker\` itself passes it as
912
920
  * \`security: { headers: LUNORA_SECURITY_HEADERS }\`.
913
921
  */
914
922
  const LUNORA_SECURITY_HEADERS: SecurityOptions["headers"] = ${JSON.stringify(e.securityHeaders)};
915
- `,ve=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((r,t)=>r.localeCompare(t)).join(", "),Se=e=>{const r=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,t={...e,hasVectors:r},{hasAuth:a}=t,s=_(t),n=ce(t),i=a?` let auth: LunoraAuth | null = null;
923
+ `,we=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),De=e=>{const t=(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0,r={...e,hasVectors:t},{hasAuth:a}=r,s=M(r),n=he(r),i=a?` let auth: LunoraAuth | null = null;
916
924
  let authInit: Promise<void> | null = null;
917
925
  // One memo per env for THIS assembled worker: every worker it builds reuses it, but a second
918
926
  // \`assemble()\` has its own auth closure and must not share.
@@ -983,11 +991,11 @@ const LUNORA_SECURITY_HEADERS: SecurityOptions["headers"] = ${JSON.stringify(e.s
983
991
  return false;
984
992
  },
985
993
  );
986
- `:"",{asyncIfDeferred:c,deferredArgument:o,deferredParameter:u,loadDeferredLine:h}=me(t),{ensureAuthCall:R,ensureRawAuthCall:D,eventWorker:m,eventWorkerLine:b}=pe(a,o),g=`${a?"() => auth, identityMemos":"() => null"}${o}`,A=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,v=`env: Env${u}`,x=t.hasFramework?` const buildWorker = (${v}): LunoraWorker =>
987
- host ? withFrameworkWorker(${oe(t)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${g})) : createWorker(this.buildWorkerOptions(env, ${g}));`:` const buildWorker = (${v}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${g}));`,C=t.hasFramework?"host?: FrameworkHostHandler":"",O=be(t),q=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
994
+ `:"",{asyncIfDeferred:l,deferredArgument:o,deferredParameter:u,loadDeferredLine:h}=ve(r),{ensureAuthCall:D,ensureRawAuthCall:A,eventWorker:m,eventWorkerLine:b}=ge(a,o),g=`${a?"() => auth, identityMemos":"() => null"}${o}`,x=`${a?"getAuth: () => LunoraAuth | null, identityMemos: IdentityMemoStore":"_getAuth: () => null"}${u}`,v=`env: Env${u}`,C=r.hasFramework?` const buildWorker = (${v}): LunoraWorker =>
995
+ host ? withFrameworkWorker(${ce(r)}, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${g})) : createWorker(this.buildWorkerOptions(env, ${g}));`:` const buildWorker = (${v}): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${g}));`,O=r.hasFramework?"host?: FrameworkHostHandler":"",q=ye(r),T=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
988
996
  public build(): ComposedApp {
989
997
  return this.assemble();
990
- }${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${y}${Z(t).join(`
998
+ }${r.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${y}${ee(r).join(`
991
999
  `)}
992
1000
 
993
1001
  /** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
@@ -995,11 +1003,11 @@ type Selector<Env, T> = (env: Env) => T | undefined;
995
1003
 
996
1004
  /** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
997
1005
  type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
998
- ${ge(t)}${he(a)}${ue(t)}${t.jurisdiction?`
1006
+ ${fe(r)}${me(a)}${be(r)}${r.jurisdiction?`
999
1007
  // Module scope, so every isolate loading this script (the worker and each Durable
1000
1008
  // Object class it exports) knows the schema's jurisdiction before a request runs.
1001
1009
  // \`@lunora/mail\` reads it to pin its shard RPC like every other DO path.
1002
- declareAppJurisdiction(${JSON.stringify(t.jurisdiction)});
1010
+ declareAppJurisdiction(${JSON.stringify(r.jurisdiction)});
1003
1011
  `:""}
1004
1012
  ${s.join(`
1005
1013
 
@@ -1020,32 +1028,32 @@ interface ComposedApp extends LunoraWorker {
1020
1028
  * first request so per-isolate singletons are built once.
1021
1029
  */
1022
1030
  class AppBuilder<Env extends object> {
1023
- ${M(t).join(`
1031
+ ${W(r).join(`
1024
1032
  `)}
1025
1033
 
1026
1034
  private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
1027
1035
 
1028
- ${B(t).join(`
1036
+ ${H(r).join(`
1029
1037
 
1030
1038
  `)}
1031
1039
 
1032
- ${q}
1040
+ ${T}
1033
1041
 
1034
1042
  /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
1035
- private assemble(${C}): ComposedApp {
1036
- const ShardDO = createShardDO({${H(t)}});
1043
+ private assemble(${O}): ComposedApp {
1044
+ const ShardDO = createShardDO({${U(r)}});
1037
1045
 
1038
1046
  // Per-isolate singletons: the worker (and auth instance) are expensive to
1039
1047
  // build, so the first request constructs them and every later request on
1040
1048
  // the same isolate reuses them.
1041
1049
  let worker: LunoraWorker | null = null;
1042
1050
  ${i}${d}
1043
- ${x}
1051
+ ${C}
1044
1052
 
1045
1053
  const composed: ComposedApp = {
1046
1054
  ShardDO,
1047
1055
  fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
1048
- const env = rawEnv as Env;${h}${R}
1056
+ const env = rawEnv as Env;${h}${D}
1049
1057
  worker ??= buildWorker(env${o});
1050
1058
 
1051
1059
  return worker.fetch(request, rawEnv, context);
@@ -1054,29 +1062,29 @@ ${x}
1054
1062
 
1055
1063
  return ${m}.scheduled(controller, rawEnv, context);
1056
1064
  },
1057
- serverQuery: ${c}(request, rawEnv, reference, args, options) => {${h}${D}
1065
+ serverQuery: ${l}(request, rawEnv, reference, args, options) => {${h}${A}
1058
1066
  worker ??= buildWorker(rawEnv as Env${o});
1059
1067
 
1060
1068
  return worker.serverQuery(request, rawEnv, reference, args, options);
1061
- },${t.hasQueue||t.hasFramework?`
1069
+ },${r.hasQueue||r.hasFramework?`
1062
1070
  queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {${h}${b}
1063
1071
 
1064
1072
  return ${m}.queue?.(batch, rawEnv, context);
1065
1073
  },`:""}
1066
1074
  };
1067
1075
 
1068
- ${O} if (this.emailHandler) {
1076
+ ${q} if (this.emailHandler) {
1069
1077
  const handler = this.emailHandler;
1070
1078
 
1071
1079
  composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
1072
1080
  }
1073
- ${t.hasFramework?`
1081
+ ${r.hasFramework?`
1074
1082
  // A framework host may export its own \`email\` (Nitro's \`cloudflare-module\`
1075
1083
  // does). Nothing in Lunora serves one, so when the app registered no handler
1076
1084
  // of its own the host's is the only one there is — forward to it rather than
1077
1085
  // dropping the entry.
1078
1086
  if (!composed.email && host && typeof host === "object" && typeof host.email === "function") {
1079
- composed.email = ${c}(message, rawEnv, context) => {${h}${b}
1087
+ composed.email = ${l}(message, rawEnv, context) => {${h}${b}
1080
1088
 
1081
1089
  return ${m}.email?.(message, rawEnv, context) ?? Promise.resolve();
1082
1090
  };
@@ -1084,11 +1092,11 @@ ${t.hasFramework?`
1084
1092
  `:""}
1085
1093
  return composed;
1086
1094
  }
1087
- ${$(t)}${P(t.hasStorage)}
1095
+ ${P(r)}${G(r.hasStorage)}
1088
1096
  /** Fan the recorded declarations into the worker-side \`createWorker\` options. */
1089
- private buildWorkerOptions(env: Env, ${A}): WorkerOptions {
1097
+ private buildWorkerOptions(env: Env, ${x}): WorkerOptions {
1090
1098
  const options: WorkerOptions = {
1091
- ${de(t).join(`
1099
+ ${pe(r).join(`
1092
1100
  `)}
1093
1101
  };
1094
1102
 
@@ -1105,11 +1113,11 @@ ${n.join(`
1105
1113
  `:""} for (const fn of this.extendFns) {
1106
1114
  Object.assign(options, fn(env, { ...options }));
1107
1115
  }
1108
- ${t.securityHeaders===void 0?"":"\n // `security.headers` from lunora.config, unless code set its own. After `.extend()`, whose shallow\n // assign would otherwise drop it when an extension sets only `security.cors`.\n if (options.security?.headers === undefined) {\n options.security = { ...options.security, headers: LUNORA_SECURITY_HEADERS };\n }\n"}
1116
+ ${r.securityHeaders===void 0?"":"\n // `security.headers` from lunora.config, unless code set its own. After `.extend()`, whose shallow\n // assign would otherwise drop it when an extension sets only `security.cors`.\n if (options.security?.headers === undefined) {\n options.security = { ...options.security, headers: LUNORA_SECURITY_HEADERS };\n }\n"}
1109
1117
  return options;
1110
1118
  }
1111
1119
  }
1112
- ${G(t.hasGlobal)}
1120
+ ${_(r.hasGlobal)}
1113
1121
  /**
1114
1122
  * Shape of the project's root \`lunora.config.*\`.
1115
1123
  *
@@ -1151,6 +1159,6 @@ interface LunoraConfig<Env extends object = object> {
1151
1159
  */
1152
1160
  const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
1153
1161
 
1154
- export { AppBuilder, defineApp${t.securityHeaders===void 0?"":", LUNORA_SECURITY_HEADERS"} };
1155
- export type { ${ve(t)} };
1156
- `};export{Se as emitApp,ke as emitAuthModule};
1162
+ export { AppBuilder, defineApp${r.securityHeaders===void 0?"":", LUNORA_SECURITY_HEADERS"} };
1163
+ export type { ${we(r)} };
1164
+ `};export{De as emitApp,Re as emitAuthModule};
@@ -1 +1 @@
1
- import"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{e}from"./server-CRFaUMKQ.mjs";import"./shared-Cn7dMQ_u.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
1
+ import"./CAPABILITY_PROBES-BuNEmlCO.mjs";import{e}from"./server-5ph4hltf.mjs";import"./shared-Cn7dMQ_u.mjs";import"./platform-8oj7iXQy.mjs";export{e as default};
@@ -1 +1 @@
1
- import{Node as s}from"ts-morph";import{j as t,h as c}from"./attribution-BhGR_h0Z.mjs";import{c as n}from"./classify-procedure-call-BZ164dkJ.mjs";const m=a=>{const i=[];for(const e of t(a)){const r=e.getInitializer(),o=r&&s.isCallExpression(r)?n(r):void 0;o?.receiver&&i.push({name:c(e)??e.getName(),receiver:o.receiver})}return i};export{m as e};
1
+ import{Node as s}from"ts-morph";import{j as t,h as c}from"./attribution-BhGR_h0Z.mjs";import{c as n}from"./classify-procedure-call-n9urVsqb.mjs";const m=a=>{const i=[];for(const e of t(a)){const r=e.getInitializer(),o=r&&s.isCallExpression(r)?n(r):void 0;o?.receiver&&i.push({name:c(e)??e.getName(),receiver:o.receiver})}return i};export{m as e};