@lunora/codegen 1.0.0-alpha.256 → 1.0.0-alpha.257
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +118 -66
- package/dist/index.d.ts +118 -66
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{AGENTS_FILENAME-D8SgT3OR.mjs → AGENTS_FILENAME-D0fmyQlq.mjs} +1 -1
- package/dist/packem_shared/{CONTAINERS_FILENAME-C13yKxas.mjs → CONTAINERS_FILENAME-C2wrJ9hF.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_TARGET-Co7ZXJ21.mjs → DEFAULT_TARGET-D5J5j3CW.mjs} +1 -1
- package/dist/packem_shared/{FLAGS_FILENAME-W5XQz_Po.mjs → FLAGS_FILENAME-C1tAv68t.mjs} +1 -1
- package/dist/packem_shared/{MUTATORS_FILENAME-DqWOgC5Z.mjs → MUTATORS_FILENAME-CDYDr1iG.mjs} +1 -1
- package/dist/packem_shared/{NOTIFY_FILENAME-C1J_47et.mjs → NOTIFY_FILENAME-Dmylk3YO.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-Cr7Zzp6s.mjs → OPENRPC_VERSION-LZowDAOS.mjs} +1 -1
- package/dist/packem_shared/QUEUES_FILENAME-CQXsARur.mjs +1 -0
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CYrLeST3.mjs +11 -0
- package/dist/packem_shared/{SHAPES_FILENAME-DRUFomCj.mjs → SHAPES_FILENAME-CNUAxXo3.mjs} +1 -1
- package/dist/packem_shared/WORKFLOWS_FILENAME-DrRu8060.mjs +1 -0
- package/dist/packem_shared/attribution-DpIyvmtn.mjs +1 -0
- package/dist/packem_shared/{buildOpenApiDocument-SxfElVzK.mjs → buildOpenApiDocument-DZMRzaEx.mjs} +1 -1
- package/dist/packem_shared/{capabilitiesUsedBy-DqrbgTKV.mjs → capabilitiesUsedBy-DLv5b8Ss.mjs} +1 -1
- package/dist/packem_shared/chain-Bah-gxpx.mjs +1 -0
- package/dist/packem_shared/{classify-procedure-call-CmcShAze.mjs → classify-procedure-call-DcsbRyEV.mjs} +1 -1
- package/dist/packem_shared/{context-property-calls-CWf9-6G5.mjs → context-property-calls-BClPebao.mjs} +1 -1
- package/dist/packem_shared/discoverAuthApiCalls-CEL1n0I0.mjs +1 -0
- package/dist/packem_shared/{discoverCrons-BEALHx1S.mjs → discoverCrons-BcrneOpi.mjs} +1 -1
- package/dist/packem_shared/{discoverFunctions-BcBzcG5x.mjs → discoverFunctions-TvTtRhvv.mjs} +1 -1
- package/dist/packem_shared/{discoverHttpRoutes-CJHS4llq.mjs → discoverHttpRoutes-BdaGy42T.mjs} +1 -1
- package/dist/packem_shared/discoverHyperdriveCalls-CDm53WpH.mjs +1 -0
- package/dist/packem_shared/discoverInserts-B2MLcH9M.mjs +1 -0
- package/dist/packem_shared/discoverMaskProcedures-Cj-dvv0H.mjs +1 -0
- package/dist/packem_shared/{discoverMigrations-Dt7ywfZv.mjs → discoverMigrations-jUmsOO70.mjs} +1 -1
- package/dist/packem_shared/{discoverNondeterministicCalls-CNJV2BiP.mjs → discoverNondeterministicCalls-BJzH9mEn.mjs} +1 -1
- package/dist/packem_shared/discoverQueries-B4enrT1h.mjs +1 -0
- package/dist/packem_shared/discoverR2sqlCalls-BgbXtbva.mjs +1 -0
- package/dist/packem_shared/{discoverRlsMetadata-mXBmPOGj.mjs → discoverRlsMetadata-DewerjgN.mjs} +1 -1
- package/dist/packem_shared/{discoverRlsProcedures-F4Cy-kSi.mjs → discoverRlsProcedures-DY5xYy7C.mjs} +1 -1
- package/dist/packem_shared/{discoverSandboxUsage-DC6q7rZy.mjs → discoverSandboxUsage-CJPFsjOS.mjs} +1 -1
- package/dist/packem_shared/{discoverSchema-D5R60b4F.mjs → discoverSchema-DPRQni-9.mjs} +1 -1
- package/dist/packem_shared/{discoverStorageRulesMetadata-D3Ot9g5f.mjs → discoverStorageRulesMetadata-DnVGPbZl.mjs} +1 -1
- package/dist/packem_shared/{exported-procedure-chains-D48EXUVQ.mjs → exported-procedure-chains-BVawk4h7.mjs} +1 -1
- package/dist/packem_shared/{fingerprintSchemaSources-Cl1CJFeh.mjs → fingerprintSchemaSources-D5z-pfpY.mjs} +1 -1
- package/dist/packem_shared/handler-reference-DLDPO906.mjs +1 -0
- package/dist/packem_shared/{index-D7dKfGPh.mjs → index-CpnWNNMK.mjs} +1 -1
- package/dist/packem_shared/listLunoraSourceFiles-jTik1QWu.mjs +1 -0
- package/dist/packem_shared/{loadProjectConfig-nNIDOrlR.mjs → loadProjectConfig-D_pUUrhQ.mjs} +1 -1
- package/dist/packem_shared/{modules-DyCocr1e.mjs → modules-B7lb5-dN.mjs} +1 -1
- package/dist/packem_shared/{parse-validator-C6fHL7OS.mjs → parse-validator-0q0Uz-Cx.mjs} +1 -1
- package/dist/packem_shared/{readServiceBindings-CeQvSswr.mjs → readServiceBindings-B_M_ZvhO.mjs} +1 -1
- package/dist/packem_shared/{unwrap-handler-return-DVY_kFF7.mjs → unwrap-handler-return-DFT18rnR.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/QUEUES_FILENAME-RGwht3Xu.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DsV2KbZm.mjs +0 -11
- package/dist/packem_shared/WORKFLOWS_FILENAME-4-ib4HH-.mjs +0 -1
- package/dist/packem_shared/chain-mte5djRJ.mjs +0 -1
- package/dist/packem_shared/discoverAuthApiCalls-DoSN_yc3.mjs +0 -1
- package/dist/packem_shared/discoverHyperdriveCalls-Bkbh4tG7.mjs +0 -1
- package/dist/packem_shared/discoverInserts-DpuLYPPd.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-B0w8gM0S.mjs +0 -1
- package/dist/packem_shared/discoverQueries-BcdqjYky.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-30Wtbc0P.mjs +0 -1
- package/dist/packem_shared/listLunoraSourceFiles-CSlcBYlo.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as L}from"@lunora/errors";import{CRON_SCHEDULE_KINDS as A,isValidCronExpression as O,warnIfSecondsLeading as S,compileCronSchedule as I}from"@lunora/scheduler";import{SyntaxKind as m,Node as n}from"ts-morph";import{diagnosticAt as f,CodegenDiagnosticError as R}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{i as b}from"./module-specifiers-WF8iAydP.mjs";import{s as $}from"./paths-C-9fwEgQ.mjs";import{listLunoraSourceFiles as y,propertyKeyName as P}from"./listLunoraSourceFiles-
|
|
1
|
+
import{LunoraError as L}from"@lunora/errors";import{CRON_SCHEDULE_KINDS as A,isValidCronExpression as O,warnIfSecondsLeading as S,compileCronSchedule as I}from"@lunora/scheduler";import{SyntaxKind as m,Node as n}from"ts-morph";import{diagnosticAt as f,CodegenDiagnosticError as R}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{i as b}from"./module-specifiers-WF8iAydP.mjs";import{s as $}from"./paths-C-9fwEgQ.mjs";import{listLunoraSourceFiles as y,propertyKeyName as P}from"./listLunoraSourceFiles-jTik1QWu.mjs";const D=new Set([...A,"cron"]),v=e=>{const t=e.getSymbol();if(!t)return e.getText()==="cronJobs";for(const r of t.getDeclarations())if(n.isImportSpecifier(r))return b(r.getImportDeclaration().getModuleSpecifierValue())?r.getNameNode().getText()==="cronJobs":!1;return!1},F=e=>{const t=new Set;for(const r of e.getVariableDeclarations()){const s=r.getInitializer();if(s?.getKind()!==m.CallExpression)continue;const i=s.getExpression();n.isIdentifier(i)&&v(i)&&t.add(r.getName())}return t},V=e=>{let t=e;for(;n.isCallExpression(t)||n.isPropertyAccessExpression(t);)t=t.getExpression();return n.isIdentifier(t)?t.getText():void 0},x=(e,t)=>{const r=e.getArguments()[t];return r&&(n.isStringLiteral(r)||n.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},_=(e,t)=>{if(n.isStringLiteral(e)||n.isNoSubstitutionTemplateLiteral(e)||n.isNumericLiteral(e))return e.getLiteralValue();if(n.isTrueLiteral(e))return!0;if(n.isFalseLiteral(e))return!1;if(n.isPrefixUnaryExpression(e)&&e.getOperatorToken()===m.MinusToken){const r=e.getOperand();if(n.isNumericLiteral(r))return-r.getLiteralValue()}if(n.isObjectLiteralExpression(e))return p(e,t);if(n.isArrayLiteralExpression(e))return e.getElements().map(r=>_(r,t));throw f(e,`Cron job "${t}" passes a non-static value where a literal is required; codegen can only read literals.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500})},p=(e,t)=>{const r={};for(const s of e.getProperties()){if(!n.isPropertyAssignment(s))throw f(s,`Cron job "${t}" uses an unsupported object property (shorthand/spread/method) where a static literal is required.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500});const i=s.getInitializer();i&&(r[P(s)]=_(i,t))}return r},C=(e,t,r)=>{const s=e.getArguments()[t];if(!s||!n.isPropertyAccessExpression(s))throw f(e,`Cron job "${r}" must reference a function statically (e.g. internal.email.digest); codegen cannot resolve a dynamic reference.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const i=s.getName(),o=s.getExpression();if(!n.isPropertyAccessExpression(o))throw f(s,`Cron job "${r}" function reference must be of the form internal.file.fn (two property accesses).`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const a=o.getName();return`${$(a)}:${i}`},h=e=>({workflow:{className:e.className,exportName:e.exportName}}),w=e=>({workflow:{className:e.className,exportName:e.exportName}}),T=(e,t,r,s,i,o)=>{const a=e.getExpression();if(!n.isIdentifier(a)||a.getText()!==t)return;const c=r.get(e.getName());if(c)return o(c);throw f(e,`Cron job "${s}" targets ${t}.${e.getName()}, but no such ${i} is declared in lunora/${i}s.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})},j=(e,t,r,s,i)=>{const o=e.getArguments()[t];if(o&&n.isPropertyAccessExpression(o)){const a=T(o,"workflows",s,r,"workflow",h);if(a)return a;const c=T(o,"agents",i,r,"agent",w);return c||{functionPath:C(e,t,r)}}if(o&&n.isIdentifier(o)){const a=s.get(o.getText()),c=i.get(o.getText());if(a&&c)throw f(o,`Cron job "${r}" references "${o.getText()}", which is ambiguous: a workflow and an agent are both declared under that name.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});if(a)return h(a);if(c)return w(c);throw f(o,`Cron job "${r}" references "${o.getText()}", which is neither a function (internal.file.fn / api.file.fn) nor a declared workflow in lunora/workflows.ts nor a declared agent in lunora/agents.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})}return{functionPath:C(e,t,r)}},k=/^@lunora\/scheduler:\s*/u,U=(e,t)=>{const r=x(e,1);if(r===void 0)throw f(e,`Cron job "${t}" must pass a string-literal cron expression to ".cron(...)".`,{code:"CRON_EXPR_NOT_STATIC",name:"LunoraError",status:500});if(!O(r))throw f(e,`Cron job "${t}" has an invalid cron expression "${r}" — expected 5 or 6 space-separated fields.`,{code:"CRON_EXPR_INVALID",name:"LunoraError",status:500});return S(r,`cron expression for job "${t}"`),r},M=(e,t,r)=>{const s=e.getArguments()[1];if(!s||!n.isObjectLiteralExpression(s))throw f(e,`Cron job "${r}" must pass an object-literal schedule to ".${t}(...)".`,{code:"CRON_SCHEDULE_NOT_STATIC",name:"LunoraError",status:500});try{return I(t,p(s,r),r)}catch(i){if(i instanceof R)throw i;const o=i instanceof Error?i.message.replace(k,""):String(i);throw f(e,o,{code:"CRON_SCHEDULE_INVALID",name:"LunoraError",status:500})}},z=(e,t,r,s,i)=>{const o=t.getName();if(!D.has(o)||!r.has(V(t.getExpression())??""))return;const a=x(e,0);if(a===void 0||a.trim()==="")throw f(e,`A cron ".${o}(...)" registration must pass a non-empty string-literal name as its first argument.`,{code:"CRON_NAME_NOT_STATIC",name:"LunoraError",status:500});const c=o==="cron"?U(e,a):M(e,o,a),u=j(e,2,a,s,i),l=e.getArguments()[3];return{args:l&&n.isObjectLiteralExpression(l)?p(l,a):{},cron:c,name:a,...u}},H=e=>{const t=new Set;for(const r of e){if(t.has(r.name))throw new L("DUPLICATE_CRON_NAME",`Duplicate cron job name "${r.name}": cron names must be unique across the project.`,{status:500});t.add(r.name)}},W=(e,t,r=[],s=[])=>{const i=y(t),o=[],a=new Map(r.map(u=>[u.exportName,u])),c=new Map(s.map(u=>[u.exportName,u]));for(const u of i){const l=e.getSourceFile(u)??e.addSourceFileAtPath(u),g=F(l);if(g.size!==0)for(const d of l.getDescendantsOfKind(m.CallExpression)){const N=d.getExpression();if(!n.isPropertyAccessExpression(N))continue;const E=z(d,N,g,a,c);E&&o.push(E)}}return o.sort((u,l)=>u.name.localeCompare(l.name)),H(o),o};export{W as default};
|
package/dist/packem_shared/{discoverFunctions-BcBzcG5x.mjs → discoverFunctions-TvTtRhvv.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as P}from"./declared-output-Iaar469J.mjs";import{s as b}from"./paths-C-9fwEgQ.mjs";import{findObjectProperty as c,bindingKeyName as A,listLunoraSourceFiles as F,lunoraRelativePath as N}from"./listLunoraSourceFiles-
|
|
1
|
+
import{d as P}from"./declared-output-Iaar469J.mjs";import{s as b}from"./paths-C-9fwEgQ.mjs";import{findObjectProperty as c,bindingKeyName as A,listLunoraSourceFiles as F,lunoraRelativePath as N}from"./listLunoraSourceFiles-jTik1QWu.mjs";import{u as y,p as O,c as m,r as z}from"./unwrap-handler-return-DFT18rnR.mjs";import{b as d,c as C}from"./classify-procedure-call-DcsbRyEV.mjs";import{Node as n,SyntaxKind as S}from"ts-morph";import{r as h,p as x,a as L}from"./parse-validator-0q0Uz-Cx.mjs";const k=i=>{const t=i.getArguments()[0];if(!t||!n.isObjectLiteralExpression(t))return"unknown";const e=c(t,"handler");if(!e||!n.isPropertyAssignment(e))return"unknown";const r=e.getInitializer();return!r||!(n.isArrowFunction(r)||n.isFunctionExpression(r))?"unknown":y(r)},I=i=>{const t=i.getArguments()[0];return!t||!(n.isArrowFunction(t)||n.isFunctionExpression(t))?"unknown":y(t)},T=i=>{let t={};for(const e of d(i)){if(e.name!=="input")continue;const r=e.call.getArguments()[0],s=r!==void 0&&n.isExpression(r)?h(r):void 0;s!==void 0&&(t={...x(s),...t})}return t},V=i=>{const t=d(i).find(r=>r.name==="output");if(!t)return;const e=t.call.getArguments()[0];return e&&n.isExpression(e)?O(t.call,()=>L(e)):void 0},p=(i,t)=>{const e=c(i,t);if(e===void 0||!n.isPropertyAssignment(e))return;const r=e.getInitializer();return r!==void 0&&n.isStringLiteral(r)?r.getLiteralValue():void 0},v=(i,t)=>{const e=c(i,t);if(e===void 0||!n.isPropertyAssignment(e))return;const r=e.getInitializer();return r!==void 0&&n.isNumericLiteral(r)?r.getLiteralValue():void 0},w=i=>{const t=c(i,"cache");if(t===void 0||!n.isPropertyAssignment(t))return;const e=t.getInitializer();if(e===void 0||!n.isObjectLiteralExpression(e))return;const r=p(e,"scope"),s=v(e,"maxAge"),o=v(e,"staleWhileRevalidate"),a=p(e,"tag"),l=p(e,"vary"),g={...s===void 0?{}:{maxAge:s},...r==="private"||r==="public"?{scope:r}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...l===void 0?{}:{vary:l}};return Object.keys(g).length===0?void 0:g},D=i=>{if(i===void 0||!n.isObjectLiteralExpression(i))return{};const t=w(i),e=c(i,"rest");return e!==void 0&&n.isPropertyAssignment(e)?{...t===void 0?{}:{cache:t},rest:e.getInitializer()?.getText()==="true"}:t===void 0?{}:{cache:t}},j=i=>{const t=d(i).find(e=>e.name==="expose");return t?D(t.call.getArguments()[0]):void 0},R=i=>{const t=i.getArguments()[0];if(!t||!n.isObjectLiteralExpression(t))return{};const e=c(t,"args");if(!e||!n.isPropertyAssignment(e))return{};const r=e.getInitializer(),s=r===void 0?void 0:h(r);return s===void 0?{}:x(s)},B=8,u=(i,t=0)=>{if(t>B)return;if(n.isCallExpression(i))return i;if(n.isParenthesizedExpression(i)||n.isAsExpression(i)||n.isSatisfiesExpression(i)||n.isNonNullExpression(i))return u(i.getExpression(),t+1);if(!n.isIdentifier(i)&&!n.isPropertyAccessExpression(i))return;const e=i.getSymbol()?.getValueDeclaration();return e?f(e,t+1):void 0},f=(i,t)=>{if(n.isVariableDeclaration(i)||n.isPropertyAssignment(i)){const e=i.getInitializer();return e?u(e,t):void 0}if(n.isShorthandPropertyAssignment(i)){const e=i.getValueSymbol()?.getValueDeclaration();return e?f(e,t+1):void 0}if(n.isBindingElement(i)){const e=A(i),o=i.getFirstAncestorByKind(S.VariableDeclaration)?.getInitializer()?.getType().getProperty(e)?.getValueDeclaration();return o?f(o,t+1):void 0}},$=i=>{const t=i.getNameNode();if(n.isObjectBindingPattern(t)){const s=[];for(const o of t.getElements()){const a=u(o.getNameNode());a&&s.push([o.getName(),a])}return s}const e=i.getInitializer(),r=e&&(n.isCallExpression(e)?e:u(e));return r?[[i.getName(),r]]:[]},W=i=>{const t=C(i);if(!t)return;const{receiver:e}=t;if(e){const r=j(e),s=m(()=>V(e)),o=m(()=>I(i)),a=P({kind:t.kind,output:s.value});return z(a?s.erased:o.erased),{args:T(e),...r?{expose:r}:{},kind:t.kind,...s.value?{output:s.value}:{},returnType:o.value,visibility:t.visibility}}return t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",visibility:t.visibility}:{args:R(i),kind:t.kind,returnType:k(i),visibility:t.visibility}},E=(i,t,e)=>{const r=W(i);if(r)return{args:r.args,exportName:t,filePath:e,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},visibility:r.visibility,...r.expose?{expose:r.expose}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{}}},_=(i,t)=>{const e=[];for(const r of i.getExportAssignments()){if(r.isExportEquals())continue;const s=u(r.getExpression()),o=s?E(s,"default",t):void 0;o&&e.push(o)}return e},H=(i,t)=>{const e=[];for(const r of i.getVariableStatements())if(r.isExported())for(const s of r.getDeclarations())for(const[o,a]of $(s)){const l=E(a,o,t);l&&e.push(l)}return e.push(..._(i,t)),e},K=i=>{const t=new Map;for(const e of i){const r=b(e.filePath),s=t.get(r);if(s&&s!==e.filePath)throw Object.assign(new Error(`Namespace collision: "${s}" and "${e.filePath}" both resolve to "${r}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[s,e.filePath],status:500});t.set(r,e.filePath)}},Y=(i,t)=>{const e=F(t),r=[];for(const s of e){const o=i.getSourceFile(s)??i.addSourceFileAtPath(s),a=N(t,s);r.push(...H(o,a))}return r.sort((s,o)=>`${s.filePath}:${s.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),K(r),r};export{Y as default};
|
package/dist/packem_shared/{discoverHttpRoutes-CJHS4llq.mjs → discoverHttpRoutes-BdaGy42T.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as i}from"ts-morph";import{a as m,p as l}from"./parse-validator-
|
|
1
|
+
import{Node as i}from"ts-morph";import{a as m,p as l}from"./parse-validator-0q0Uz-Cx.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as h}from"./listLunoraSourceFiles-jTik1QWu.mjs";import{u as f}from"./unwrap-handler-return-DFT18rnR.mjs";const u=new Set(["delete","get","head","options","patch","post","put"]),g=new Set(["body","params","searchParams"]),E=new Set(["handler","stream"]),v=r=>{const e=r.getArguments()[0];if(e&&i.isStringLiteral(e))return e.getLiteralValue()},x=r=>{const e=r.getArguments()[0];return e&&i.isObjectLiteralExpression(e)?l(e):{}},P=r=>{if(!i.isCallExpression(r))return;const e=r.getExpression();if(!i.isPropertyAccessExpression(e))return;const o=e.getName();if(!u.has(o))return;const n=e.getExpression();if(!i.isIdentifier(n)||n.getText()!=="httpRoute")return;const s=v(r);return s===void 0?void 0:{method:o.toUpperCase(),path:s}},S=(r,e)=>{const o={body:{},params:{},searchParams:{},stream:e==="stream"},n=r.getExpression();if(!i.isPropertyAccessExpression(n))return;let s=n.getExpression();for(;i.isCallExpression(s);){const a=s.getExpression();if(!i.isPropertyAccessExpression(a))break;const c=a.getName();if(u.has(c))break;if(g.has(c)){const p=x(s);o[c]={...p,...o[c]}}else if(c==="output"&&o.output===void 0){const p=s.getArguments()[0];p&&i.isExpression(p)&&(o.output=m(p))}s=a.getExpression()}const t=P(s);if(t)return o.method=t.method,o.path=t.path,o},A=r=>{const e=r.getArguments()[0];return!e||!(i.isArrowFunction(e)||i.isFunctionExpression(e))?"unknown":f(e)},T=(r,e,o,n)=>{const s=e.getName();if(!E.has(s))return;const t=S(r,s);if(!(t?.method===void 0||t.path===void 0))return{body:t.body,exportName:o,filePath:n,method:t.method,params:t.params,path:t.path,searchParams:t.searchParams,stream:t.stream,...t.stream?{chunkType:A(r)}:{},...t.output?{output:t.output}:{}}},b=(r,e)=>{const o=[];for(const n of r.getVariableStatements())if(n.isExported())for(const s of n.getDeclarations()){const t=s.getInitializer();if(!t||!i.isCallExpression(t))continue;const a=t.getExpression();if(!i.isPropertyAccessExpression(a))continue;const c=T(t,a,s.getName(),e);c&&o.push(c)}return o},F=(r,e)=>{const o=d(e),n=[];for(const s of o){const t=r.getSourceFile(s)??r.addSourceFileAtPath(s),a=h(e,s);n.push(...b(t,a))}return n.sort((s,t)=>`${s.method} ${s.path}`.localeCompare(`${t.method} ${t.path}`)||s.filePath.localeCompare(t.filePath)),n};export{F as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as o}from"./context-property-calls-BClPebao.mjs";const t=(r,e)=>o(r,e,"sql");export{t as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as i}from"ts-morph";import{collectCallRows as n,isDatabaseAccessor as a}from"./listLunoraSourceFiles-jTik1QWu.mjs";import{c}from"./attribution-DpIyvmtn.mjs";const l=t=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="insert")return!1;const r=e.getExpression();return a(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)??"":""},b=(t,e)=>n(t,e,(r,s)=>l(r)?{file:s,line:r.getStartLineNumber(),scope:c(r),table:f(r)}:void 0);export{b as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./listLunoraSourceFiles-jTik1QWu.mjs";import"./classify-procedure-call-DcsbRyEV.mjs";import{d as p}from"./index-CpnWNNMK.mjs";export{p as default};
|
package/dist/packem_shared/{discoverMigrations-Dt7ywfZv.mjs → discoverMigrations-jUmsOO70.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SyntaxKind as g,Node as s}from"ts-morph";import{diagnosticAt as u}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as m}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,lunoraRelativePath as h,findObjectProperty as I}from"./listLunoraSourceFiles-
|
|
1
|
+
import{SyntaxKind as g,Node as s}from"ts-morph";import{diagnosticAt as u}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as m}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,lunoraRelativePath as h,findObjectProperty as I}from"./listLunoraSourceFiles-jTik1QWu.mjs";const P=r=>{const i=r.getSymbol();if(!i)return r.getText()==="defineMigration";for(const t of i.getDeclarations())if(s.isImportSpecifier(t))return m(t.getImportDeclaration().getModuleSpecifierValue())?t.getNameNode().getText()==="defineMigration":!1;return!1},d=(r,i)=>{const t=I(r,i);if(!t||!s.isPropertyAssignment(t))return;const e=t.getInitializer();return e&&s.isStringLiteral(e)?e.getLiteralValue():void 0},b=(r,i)=>{const t=r.getInitializer();if(t?.getKind()!==g.CallExpression)return;const e=t.getExpression();if(!s.isIdentifier(e)||!P(e))return;const o=t.getArguments()[0];if(!o||!s.isObjectLiteralExpression(o))return;const n=d(o,"id"),a=r.getName();if(n===void 0||n.trim()==="")throw u(o,`Migration "${a}" in "${i}" must declare \`id\` as a non-empty string literal so codegen can key the registry.`,{code:"MIGRATION_ID_NOT_STATIC",name:"LunoraError",status:500});return{exportName:a,filePath:i,id:n,table:d(o,"table")??""}},M=r=>{const i=new Map;for(const t of r){const e=i.get(t.id);if(e!==void 0)throw Object.assign(new Error(`Duplicate migration id "${t.id}": declared in both "${e}" and "${t.filePath}". Migration ids must be unique across the project.`),{code:"DUPLICATE_MIGRATION_ID",id:t.id,name:"LunoraError",paths:[e,t.filePath],status:500});i.set(t.id,t.filePath)}},A=(r,i)=>{const t=p(i),e=[];for(const o of t){const n=r.getSourceFile(o)??r.addSourceFileAtPath(o),a=h(i,o);for(const c of n.getVariableStatements())if(c.isExported())for(const f of c.getDeclarations()){const l=b(f,a);l&&e.push(l)}}return e.sort((o,n)=>o.id.localeCompare(n.id)),M(e),e};export{A as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as s,SyntaxKind as a}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as l,handlerOf as d}from"./listLunoraSourceFiles-
|
|
1
|
+
import{Node as s,SyntaxKind as a}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as l,handlerOf as d}from"./listLunoraSourceFiles-jTik1QWu.mjs";import{c as f}from"./classify-procedure-call-DcsbRyEV.mjs";const u={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},m=new Set(["globalThis","self"]),g=new Set(["globalThis","self","window"]),p=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const t=e.getExpression();if(s.isIdentifier(t)&&g.has(t.getText()))return e.getName()}},h=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=p(t.getExpression());if(i!==void 0)return n==="fetch"&&m.has(i)?"fetch":u[`${i}.${n}`]},x=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"},N=e=>{const t=e.getInitializer();if(!t||!s.isCallExpression(t))return;const n=f(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const i=d(t,n.receiver);return i?{exportName:e.getName(),handler:i,kind:n.kind}:void 0},E=(e,t)=>{const n=[];for(const i of e.handler.getDescendantsOfKind(a.CallExpression)){const o=h(i);o!==void 0&&n.push({callee:o,exportName:e.exportName,file:t,kind:e.kind,line:i.getStartLineNumber()})}for(const i of e.handler.getDescendantsOfKind(a.NewExpression)){const o=x(i);o!==void 0&&n.push({callee:o,exportName:e.exportName,file:t,kind:e.kind,line:i.getStartLineNumber()})}return n},S=(e,t)=>{const n=[];for(const i of e.getVariableStatements())if(i.isExported())for(const o of i.getDeclarations()){const r=N(o);r&&n.push(...E(r,t))}return n},w=(e,t)=>{const n=[];for(const i of c(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...S(o,l(t,i)))}return n};export{w as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as i}from"ts-morph";import{collectCallRows as c,isDatabaseAccessor as l}from"./listLunoraSourceFiles-jTik1QWu.mjs";import{c as f}from"./attribution-DpIyvmtn.mjs";const u=new Set(["withGeoIndex","withIndex","withSearchIndex"]),p=new Set(["collect","collectWithScores","first","paginate","take","unique"]),g=n=>{const t=n.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="query")return!1;const e=t.getExpression();return l(e)},m=n=>{const t=[];let e=n;for(;;){const r=e.getParent();if(!r||!i.isPropertyAccessExpression(r))break;const s=r.getParent();if(!s||!i.isCallExpression(s))break;t.push(r.getName()),e=s}return t},d=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,E=n=>{let t=n;for(;;){const e=t.getParent();if(!e||!i.isPropertyAccessExpression(e))return!1;const r=e.getParent();if(!r||!i.isCallExpression(r))return!1;if(e.getName()==="filter"){const s=r.getArguments()[0];if(s&&d.test(s.getText()))return!0}t=r}},h=n=>{const t=n.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},S=(n,t)=>c(n,t,(e,r)=>{if(!g(e))return;const s=m(e),a=s.includes("filter");return{file:r,filtersPrimaryKey:a&&E(e),hasFilter:a,hasIndex:s.some(o=>u.has(o)),line:e.getStartLineNumber(),scope:f(e),table:h(e),terminal:s.findLast(o=>p.has(o))}});export{S as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as r}from"./context-property-calls-BClPebao.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
|
package/dist/packem_shared/{discoverRlsMetadata-mXBmPOGj.mjs → discoverRlsMetadata-DewerjgN.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as x,lunoraRelativePath as h,findObjectProperty as m,stringPropertyOf as c}from"./listLunoraSourceFiles-
|
|
1
|
+
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as x,lunoraRelativePath as h,findObjectProperty as m,stringPropertyOf as c}from"./listLunoraSourceFiles-jTik1QWu.mjs";import{e as A}from"./exported-procedure-chains-BVawk4h7.mjs";import{r as L}from"./chain-Bah-gxpx.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};
|
package/dist/packem_shared/{discoverRlsProcedures-F4Cy-kSi.mjs → discoverRlsProcedures-DY5xYy7C.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as u,tablesAccessedIn as d,findObjectProperty as p}from"./listLunoraSourceFiles-
|
|
1
|
+
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as u,tablesAccessedIn as d,findObjectProperty as p}from"./listLunoraSourceFiles-jTik1QWu.mjs";import{c as m}from"./classify-procedure-call-DcsbRyEV.mjs";import{r as b}from"./chain-Bah-gxpx.mjs";const g=e=>{const t=e.getArguments()[0];if(!t||!o.isArrayLiteralExpression(t))return[];const s=[];for(const r of t.getElements()){if(!o.isObjectLiteralExpression(r))continue;const i=p(r,"table");if(!i||!o.isPropertyAssignment(i))continue;const n=i.getInitializer();n&&o.isStringLiteral(n)&&s.push(n.getLiteralText())}return s},h=e=>{const t=b(e);return{rlsTables:t.flatMap(s=>g(s)),usesRls:t.length>0}},y=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),v=new Set(["delete","deleteMany","insert","insertMany","patch","patchMany","replace"]),P=(e,t)=>{if(!o.isVariableDeclaration(e))return;const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=m(s);if(!r)return;const i=r.receiver?h(r.receiver):{rlsTables:[],usesRls:!1},{tablesRead:n,tablesWritten:l}=d(e,y,v);return{exportName:e.getName(),file:t,rlsTables:i.rlsTables,tablesRead:n,tablesWritten:l,usesRls:i.usesRls,visibility:r.visibility}},x=(e,t)=>{const s=[];for(const r of f(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=u(t,r);for(const l of i.getVariableStatements())if(l.isExported())for(const c of l.getDeclarations()){const a=P(c,n);a&&s.push(a)}}return s};export{x as default};
|
package/dist/packem_shared/{discoverSandboxUsage-DC6q7rZy.mjs → discoverSandboxUsage-CJPFsjOS.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{listLunoraSourceFiles as d}from"./listLunoraSourceFiles-
|
|
1
|
+
import{listLunoraSourceFiles as d}from"./listLunoraSourceFiles-jTik1QWu.mjs";const f=new Set(["@lunora/agent","@lunora/agent/sandbox"]),t={browserTool:"usesSandboxBrowser",containerFsTool:"usesSandboxContainer",containerTool:"usesSandboxContainer",fsTool:"usesSandboxFs",jsCodeTool:"usesSandboxLoader"},u=()=>({usesSandboxBrowser:!1,usesSandboxContainer:!1,usesSandboxFs:!1,usesSandboxLoader:!1}),i=o=>{const s=u();if(!f.has(o.getModuleSpecifierValue())||o.isTypeOnly())return s;for(const e of o.getNamedImports()){if(e.isTypeOnly())continue;const n=t[e.getNameNode().getText()];n!==void 0&&(s[n]=!0)}return s},b=(o,s)=>{const e=u();for(const n of d(s)){const c=o.getSourceFile(n)??o.addSourceFileAtPath(n);for(const a of c.getImportDeclarations()){const l=i(a);for(const r of Object.values(t))e[r]||=l[r]}if(Object.values(t).every(a=>e[a]))break}return e};export{b as discoverSandboxUsage,u as noSandboxUsage,i as scanImportDeclaration};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as M}from"@lunora/errors";import{Node as i,SyntaxKind as R}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as F}from"node:module";import{join as C}from"node:path";import{findObjectProperty as u,propertyKeyName as I}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{r as B,p as V}from"./parse-validator-C6fHL7OS.mjs";const q=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,J=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},U=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),m=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:U(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=m(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=J(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,m(a)]));break}case"record":{s.valueType=m(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=m(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>m(o));break}}return s},K=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Z=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},G=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Z(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,m(o)])),shardMode:K(e.shardMode),vectorIndexes:[]}},W=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>G(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},X=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},H=e=>{const t=X(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},Q=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},Y=(e,t)=>{const n=H(e);if(n)try{const s=F(C(t,"noop.cjs")),r=s.resolve(n.moduleSpecifier),o=s(r),a=Q(o,n);return typeof a!="object"||a===null?void 0:W(a)}catch{return}},ee=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},x=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},L=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},h=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},O=e=>e&&ee.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",te=(e,t)=>{const n=h(e,t);return n!==void 0&&n.length>0?n:void 0},A=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw d(c,`unknown ${n} ${JSON.stringify(g)} — expected ${r}`);return g}o=l}},ne=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,re=/^(?:sqlite_|_cf_|__)/u,se=/__(?:agg|rank|geo|fts)_/u,ie=e=>re.test(e)||se.test(e),oe=new Set(["cascade","restrict","set null"]),ae=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),le=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","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),N=/^[A-Za-z_$][\w$]*$/u,w=(e,t)=>{if(ae.has(e))throw d(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(le.has(e))throw d(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!N.test(e))throw d(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(ie(e))throw d(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},ce=e=>e&&oe.has(e)?e:void 0,de=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},fe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw d(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();let l="_unknown_",c="_id",g;return o&&i.isObjectLiteralExpression(o)&&(l=f(o,"field")??l,c=f(o,"references")??c,g=s==="one"?ce(f(o,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:a}},ue=e=>{const t=de(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=fe(s);r&&n.push(r)}return n},pe=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw d(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},ge=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},me=e=>{const[t,n,s]=e,r=ge(s),o=y(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw d(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>i.isStringLiteral(c));for(const c of l)pe(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},be=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=h(n,"filterFields"),o=f(n,"language"),a=L(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:y(t),staged:a,strategy:l}},xe=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=x(n,"precision")),{field:s,name:y(t),precision:r}},he=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=x(n,"after")),{after:r,field:s}},ye=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},ve=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>ye(l)).filter(l=>l!==void 0))}r=h(n,"partitionBy")}return{name:y(t),partitionBy:r,sortBy:s}},Ee=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:O(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},Ie=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},we=e=>{if(e&&i.isObjectLiteralExpression(e)){const t=u(e,"field");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isStringLiteral(n))return n.getLiteralText()}}return"deletedAt"},Se=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:te(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},ke=(e,t,n,s)=>{switch(t){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(xe(n));break}case"global":{e.shardMode="global",e.globalBackend=Ie(n);break}case"index":{e.indexes.push(me(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(ve(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ue(r));break}case"searchIndex":{e.searchIndexes.push(be(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:we(n[0])};break}case"source":{e.externalSource=Se(n),e.externallyManaged=!0;break}case"ttl":{e.ttl=he(n);break}case"vectorize":{const r=Ee(n,s);r&&e.vectorIndexes.push(r);break}}},_=["__vocab","_config","_content","_data","_docsize","_idx"],Te=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of _){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw d(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${_.join(", ")}.`)}},_e=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,ne(t))},P=(e,t)=>{const n={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))ke(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=V(l);else if(l)throw d(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return n.softDelete&&!(n.softDelete.field in s)&&(s={...s,[n.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),Te(e,t,n.searchIndexes),_e(e,t,n),{commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},j=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=B(r.getExpression());a!==void 0&&!s.has(a)&&j(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=I(r);if(w(a,r.getNameNode()),n.has(a))throw d(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(P(o,a))}}return t},Le=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},Oe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:O(f(s,"metric")),name:o,table:Le(s)}},$=e=>{const t=[];for(const n of e.getProperties()){const s=Oe(n);s&&t.push(s)}return t},S=(e,t)=>`${e}_${t}`,Ae=(e,t)=>{if(!N.test(e))throw d(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},E=(e,t,n)=>n.has(e)?S(t,e):e,Ne=(e,t,n,s)=>{const r=S(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,relations:e.relations.map(o=>({...o,table:E(o.table,t,n)})),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:E(o.table,t,n)}))}},Pe=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},je=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},$e=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},De=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},ze=(e,t)=>{const n=Pe(e);if(n){if(i.isPropertyAccessExpression(t)){const s=De(n);return s?b(s,t.getName()):void 0}return n}},Me=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,je(t))return t;const s=$e(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=ze(a,t)}},Re=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Fe=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=I(r);w(a,r.getNameNode()),s.push(P(o,a))}return s},Ce=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:$(n)},D=(e,t,n,s,r)=>{Ae(e,s);const o=new Set(t.map(c=>c.name)),a=t.map(c=>Ne(c,e,o,r)),l=n.map(c=>({...c,name:S(e,c.name),table:E(c.table,e,o)}));return{tables:a,vectorIndexes:l}},Be=(e,t,n)=>D(e,Fe(n),Ce(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ve=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Me(n);if(!s){if(t!==void 0){const o=Y(n,t);if(o){for(const a of o.bareTables)w(a.name,n);return D(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Re(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Be(r.key,r.keyNode,r.options)},qe=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},Je=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of qe(e)){const a=Ve(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw d(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},Ue=new Set(["eu","fedramp","us"]),Ke=e=>A(e,"jurisdiction","jurisdiction",Ue,'"eu", "us", or "fedramp"'),Ze=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&L(r,"pinAuth")===!0}t=s}},Ge=new Set(["required"]),We=e=>A(e,"rls","rls mode",Ge,'"required"'),rt=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(R.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new M("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw d(r,"defineSchema() expects an object literal");const a=j(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?$(l):[],g=Je(r,a,n),k=[...a.flatMap(p=>p.vectorIndexes),...c,...g],z=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),v=k.find(p=>z.has(p.table));if(v)throw d(r,q(v.table,v.name));return{jurisdiction:Ke(r),...Ze(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:We(r),tables:a,vectorIndexes:k}};export{rt as default};
|
|
1
|
+
import{LunoraError as M}from"@lunora/errors";import{Node as i,SyntaxKind as R}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as F}from"node:module";import{join as C}from"node:path";import{findObjectProperty as u,propertyKeyName as I}from"./listLunoraSourceFiles-jTik1QWu.mjs";import{r as B,p as V}from"./parse-validator-0q0Uz-Cx.mjs";const q=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,J=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},U=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),m=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:U(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=m(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=J(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,m(a)]));break}case"record":{s.valueType=m(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=m(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>m(o));break}}return s},K=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Z=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},G=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Z(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,m(o)])),shardMode:K(e.shardMode),vectorIndexes:[]}},W=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>G(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},X=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},H=e=>{const t=X(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},Q=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},Y=(e,t)=>{const n=H(e);if(n)try{const s=F(C(t,"noop.cjs")),r=s.resolve(n.moduleSpecifier),o=s(r),a=Q(o,n);return typeof a!="object"||a===null?void 0:W(a)}catch{return}},ee=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},x=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},L=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},h=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},O=e=>e&&ee.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",te=(e,t)=>{const n=h(e,t);return n!==void 0&&n.length>0?n:void 0},A=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw d(c,`unknown ${n} ${JSON.stringify(g)} — expected ${r}`);return g}o=l}},ne=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,re=/^(?:sqlite_|_cf_|__)/u,se=/__(?:agg|rank|geo|fts)_/u,ie=e=>re.test(e)||se.test(e),oe=new Set(["cascade","restrict","set null"]),ae=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),le=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","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),N=/^[A-Za-z_$][\w$]*$/u,w=(e,t)=>{if(ae.has(e))throw d(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(le.has(e))throw d(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!N.test(e))throw d(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(ie(e))throw d(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},ce=e=>e&&oe.has(e)?e:void 0,de=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},fe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw d(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();let l="_unknown_",c="_id",g;return o&&i.isObjectLiteralExpression(o)&&(l=f(o,"field")??l,c=f(o,"references")??c,g=s==="one"?ce(f(o,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:a}},ue=e=>{const t=de(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=fe(s);r&&n.push(r)}return n},pe=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw d(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},ge=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},me=e=>{const[t,n,s]=e,r=ge(s),o=y(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw d(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>i.isStringLiteral(c));for(const c of l)pe(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},be=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=h(n,"filterFields"),o=f(n,"language"),a=L(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:y(t),staged:a,strategy:l}},xe=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=x(n,"precision")),{field:s,name:y(t),precision:r}},he=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=x(n,"after")),{after:r,field:s}},ye=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},ve=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>ye(l)).filter(l=>l!==void 0))}r=h(n,"partitionBy")}return{name:y(t),partitionBy:r,sortBy:s}},Ee=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:O(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},Ie=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},we=e=>{if(e&&i.isObjectLiteralExpression(e)){const t=u(e,"field");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isStringLiteral(n))return n.getLiteralText()}}return"deletedAt"},Se=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:te(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},ke=(e,t,n,s)=>{switch(t){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(xe(n));break}case"global":{e.shardMode="global",e.globalBackend=Ie(n);break}case"index":{e.indexes.push(me(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(ve(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ue(r));break}case"searchIndex":{e.searchIndexes.push(be(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:we(n[0])};break}case"source":{e.externalSource=Se(n),e.externallyManaged=!0;break}case"ttl":{e.ttl=he(n);break}case"vectorize":{const r=Ee(n,s);r&&e.vectorIndexes.push(r);break}}},_=["__vocab","_config","_content","_data","_docsize","_idx"],Te=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of _){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw d(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${_.join(", ")}.`)}},_e=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,ne(t))},P=(e,t)=>{const n={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))ke(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=V(l);else if(l)throw d(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return n.softDelete&&!(n.softDelete.field in s)&&(s={...s,[n.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),Te(e,t,n.searchIndexes),_e(e,t,n),{commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},j=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=B(r.getExpression());a!==void 0&&!s.has(a)&&j(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=I(r);if(w(a,r.getNameNode()),n.has(a))throw d(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(P(o,a))}}return t},Le=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},Oe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:O(f(s,"metric")),name:o,table:Le(s)}},$=e=>{const t=[];for(const n of e.getProperties()){const s=Oe(n);s&&t.push(s)}return t},S=(e,t)=>`${e}_${t}`,Ae=(e,t)=>{if(!N.test(e))throw d(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},E=(e,t,n)=>n.has(e)?S(t,e):e,Ne=(e,t,n,s)=>{const r=S(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,relations:e.relations.map(o=>({...o,table:E(o.table,t,n)})),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:E(o.table,t,n)}))}},Pe=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},je=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},$e=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},De=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},ze=(e,t)=>{const n=Pe(e);if(n){if(i.isPropertyAccessExpression(t)){const s=De(n);return s?b(s,t.getName()):void 0}return n}},Me=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,je(t))return t;const s=$e(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=ze(a,t)}},Re=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Fe=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=I(r);w(a,r.getNameNode()),s.push(P(o,a))}return s},Ce=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:$(n)},D=(e,t,n,s,r)=>{Ae(e,s);const o=new Set(t.map(c=>c.name)),a=t.map(c=>Ne(c,e,o,r)),l=n.map(c=>({...c,name:S(e,c.name),table:E(c.table,e,o)}));return{tables:a,vectorIndexes:l}},Be=(e,t,n)=>D(e,Fe(n),Ce(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ve=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Me(n);if(!s){if(t!==void 0){const o=Y(n,t);if(o){for(const a of o.bareTables)w(a.name,n);return D(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Re(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Be(r.key,r.keyNode,r.options)},qe=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},Je=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of qe(e)){const a=Ve(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw d(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},Ue=new Set(["eu","fedramp","us"]),Ke=e=>A(e,"jurisdiction","jurisdiction",Ue,'"eu", "us", or "fedramp"'),Ze=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&L(r,"pinAuth")===!0}t=s}},Ge=new Set(["required"]),We=e=>A(e,"rls","rls mode",Ge,'"required"'),rt=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(R.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new M("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw d(r,"defineSchema() expects an object literal");const a=j(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?$(l):[],g=Je(r,a,n),k=[...a.flatMap(p=>p.vectorIndexes),...c,...g],z=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),v=k.find(p=>z.has(p.table));if(v)throw d(r,q(v.table,v.name));return{jurisdiction:Ke(r),...Ze(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:We(r),tables:a,vectorIndexes:k}};export{rt as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./listLunoraSourceFiles-
|
|
1
|
+
import{Node as u}from"ts-morph";import{listLunoraSourceFiles as f,lunoraRelativePath as p,stringPropertyOf as l}from"./listLunoraSourceFiles-jTik1QWu.mjs";import{w as d}from"./classify-procedure-call-DcsbRyEV.mjs";import{e as m}from"./exported-procedure-chains-BVawk4h7.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 +1 @@
|
|
|
1
|
-
import{Node as a}from"ts-morph";import{c as n}from"./classify-procedure-call-
|
|
1
|
+
import{Node as a}from"ts-morph";import{c as n}from"./classify-procedure-call-DcsbRyEV.mjs";const f=s=>{const i=[];for(const r of s.getVariableStatements())if(r.isExported())for(const t of r.getDeclarations()){const e=t.getInitializer(),o=e&&a.isCallExpression(e)?n(e):void 0;o?.receiver&&i.push({name:t.getName(),receiver:o.receiver})}return i};export{f as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as c}from"node:crypto";import{existsSync as s,readFileSync as i}from"node:fs";import{join as h}from"node:path";import{listLunoraSourceFiles as u}from"./listLunoraSourceFiles-
|
|
1
|
+
import{createHash as c}from"node:crypto";import{existsSync as s,readFileSync as i}from"node:fs";import{join as h}from"node:path";import{listLunoraSourceFiles as u}from"./listLunoraSourceFiles-jTik1QWu.mjs";const S=t=>{if(!s(t))return"unreadable";const e=u(t),o=h(t,"schema.ts");s(o)&&e.push(o);const r=c("sha256");for(const a of e.toSorted((n,p)=>n.localeCompare(p)))try{r.update(a).update("\0").update(i(a))}catch{}return r.digest("hex")};export{S as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{dirname as F}from"node:path";import{Node as e}from"ts-morph";import{unwrapExpression as m,lunoraRelativePath as u}from"./listLunoraSourceFiles-jTik1QWu.mjs";import{r as v,e as b}from"./attribution-DpIyvmtn.mjs";const h=i=>e.isPropertyAssignment(i)?m(i.getInitializer()):e.isShorthandPropertyAssignment(i)?i.getNameNode():void 0,A=(i,s)=>{const o=i===void 0?void 0:h(i);if(o===void 0||!e.isIdentifier(o))return;const a=v(o),g=a?.getAliasedSymbol()??a;for(const t of g?.getDeclarations()??[]){const n=e.isVariableDeclaration(t)?m(t.getInitializer()):t;if(!(e.isFunctionDeclaration(n)||e.isArrowFunction(n)||e.isFunctionExpression(n))||!(e.isFunctionDeclaration(t)||e.isVariableDeclaration(t)))continue;const r=t.getSourceFile(),c=u(s,r.getFilePath()),l=!c.startsWith("../"),d=l?c:u(F(s),r.getFilePath()),f=b(t);return{body:n,...r===o.getSourceFile()?{}:{file:d},...l&&f!==void 0?{site:{exportName:f,file:d}}:{}}}};export{A as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as r}from"ts-morph";import{propertyKeyName as f,listLunoraSourceFiles as m,lunoraRelativePath as p,tablesAccessedIn as d}from"./listLunoraSourceFiles-
|
|
1
|
+
import{Node as r}from"ts-morph";import{propertyKeyName as f,listLunoraSourceFiles as m,lunoraRelativePath as p,tablesAccessedIn as d}from"./listLunoraSourceFiles-jTik1QWu.mjs";import{w as g,c as h}from"./classify-procedure-call-DcsbRyEV.mjs";const u=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return f(e)},k=e=>g(e,"use","mask"),x=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();if(t&&r.isStringLiteral(t)){const s=t.getLiteralText();if(s==="redact"||s==="hash")return s}}return"custom"},v=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const i of t.getProperties()){const n=u(i);if(n===void 0||!r.isPropertyAssignment(i))continue;const o=i.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=u(a);c!==void 0&&s.push({column:c,table:n})}}return s},P=e=>{const t=k(e);return{maskColumns:t.flatMap(s=>v(s)),usesMask:t.length>0}},y=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),C=new Set(["delete","insert","patch","replace"]),M=(e,t)=>{if(!r.isVariableDeclaration(e))return;const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const i=h(s);if(!i)return;const n=i.receiver?P(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:o,tablesWritten:a}=d(e,y,C);return{exportName:e.getName(),file:t,maskColumns:n.maskColumns,tablesRead:o,tablesWritten:a,usesMask:n.usesMask,visibility:i.visibility}},E=(e,t)=>{const s=[];for(const i of m(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i),o=p(t,i);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations()){const l=M(c,o);l&&s.push(l)}}return s};export{u as a,E as d,k as m,x as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readdirSync as S,realpathSync as A,lstatSync as O,statSync as N}from"node:fs";import{dirname as w,join as g,relative as R,sep as T,extname as y}from"node:path";import{SyntaxKind as d,Node as s,VariableDeclarationKind as F}from"ts-morph";import{diagnosticAt as I}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findProjectConfigFile as D}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const C=/\.ts$/u,p=(t,e)=>R(t,e).split(T).join("/").replace(C,""),_=new Set(["_generated","node_modules"]),j=(t,e,i)=>t==="schema.ts"&&e===i,z=t=>{try{return N(t)}catch{console.warn(`@lunora/codegen: skipping ${t} — it is a symlink that does not resolve (or vanished mid-scan).`);return}},b=(t,e,i,n)=>{let o,r;try{o=S(t),r=A(t)}catch{return e}if(n.has(r))return e;n.add(r);for(const a of o){const c=g(t,a),l=z(c);l!==void 0&&(l.isDirectory()?_.has(a)||b(c,e,i,n):l.isFile()&&y(a)===".ts"&&!j(a,t,i)&&e.push(c))}return e},h=t=>b(t,[],t,new Set),K=["src/server","src/index.ts","src/worker.ts"],V=new Set([".ts",".tsx"]),v=(t,e=[])=>{let i;try{i=O(t)}catch{return e}if(i.isFile())return V.has(y(t))&&e.push(t),e;if(!i.isDirectory())return e;for(const n of S(t))n==="_generated"||n==="node_modules"||v(g(t,n),e);return e},k=t=>{const e=w(t),i=h(t).map(r=>({displayPath:p(t,r),filePath:r})),n=new Set(i.map(r=>r.filePath)),o=D(e);for(const r of[...K.flatMap(a=>v(g(e,a))),...o===void 0?[]:[o]])n.has(r)||(n.add(r),i.push({displayPath:p(e,r),filePath:r}));return i},M=t=>Array.isArray(t),L=(t,e,i,n)=>{const o=[];for(const{displayPath:r,filePath:a}of e){const c=t.getSourceFile(a)??t.addSourceFileAtPath(a);for(const l of c.getDescendantsOfKind(i)){const u=n(l,r);M(u)?o.push(...u):u!==void 0&&o.push(u)}}return o},$=t=>h(t).map(e=>({displayPath:p(t,e),filePath:e})),B=(t,e,i,n)=>L(t,$(e),i,n),it=(t,e,i)=>B(t,e,d.CallExpression,i),st=(t,e,i)=>L(t,k(e),d.CallExpression,i),P=t=>{if(s.isStringLiteral(t)||s.isNoSubstitutionTemplateLiteral(t)||s.isNumericLiteral(t))return t.getLiteralText();if(s.isComputedPropertyName(t)){const e=t.getExpression();if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText()}return t.getText()},U=t=>P(t.getNameNode()),nt=t=>P(t.getPropertyNameNode()??t.getNameNode()),E=(t,e)=>t?.getProperties().find(i=>!s.isSpreadAssignment(i)&&U(i)===e),rt=(t,e)=>{if(e){const r=t.getArguments()[0];return r&&(s.isArrowFunction(r)||s.isFunctionExpression(r))?r:void 0}const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return;const n=E(i,"handler");if(!n||!s.isPropertyAssignment(n))return;const o=n.getInitializer();return o&&(s.isArrowFunction(o)||s.isFunctionExpression(o))?o:void 0},ot=(t,e)=>{if(!t||!s.isObjectLiteralExpression(t))return;const i=E(t,e);return i&&s.isPropertyAssignment(i)?i.getInitializer():void 0},W=t=>{const e=t?.getDeclarations().find(o=>s.isVariableDeclaration(o));if(e===void 0||!s.isVariableDeclaration(e))return;const i=e.getParent();if(!s.isVariableDeclarationList(i)||i.getDeclarationKind()!==F.Const)return;const n=i.getParent();return s.isVariableStatement(n)&&s.isSourceFile(n.getParent())?e.getInitializer():void 0},q=t=>W(t.getSymbol()),at=t=>{if(!t)return;if(s.isObjectLiteralExpression(t))return t;if(!s.isIdentifier(t))return;const e=q(t);return e!==void 0&&s.isObjectLiteralExpression(e)?e:void 0},f=t=>s.isPropertyAccessExpression(t)&&t.getName()==="db"||s.isIdentifier(t)&&t.getText()==="db",H=new Set(["findFirst","findFirstOrThrow","findMany","findUnique"]),ct=t=>{const e=t.getExpression();if(!s.isPropertyAccessExpression(e)||!H.has(e.getName()))return;const i=e.getExpression();if(f(i)){const n=t.getArguments()[0];return{options:t.getArguments()[1],table:n&&s.isStringLiteral(n)?n.getLiteralText():""}}if(s.isPropertyAccessExpression(i)){const n=i.getExpression();if(f(n))return{options:t.getArguments()[0],table:i.getName()}}},x=(t,e)=>{const i=t.getExpression();return!s.isPropertyAccessExpression(i)||!e.has(i.getName())?!1:f(i.getExpression())},m=t=>{const e=t.getArguments()[0];return e&&s.isStringLiteral(e)?e.getLiteralText():""},lt=(t,e,i)=>{const n=new Set,o=new Set;for(const r of t.getDescendantsOfKind(d.CallExpression))if(x(r,e)){const a=m(r);a!==""&&n.add(a)}else if(x(r,i)){const a=m(r);a!==""&&o.add(a)}return{tablesRead:[...n],tablesWritten:[...o]}},X=t=>{let e=t;for(;e&&(s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isParenthesizedExpression(e)||s.isNonNullExpression(e));)e=e.getExpression();return e},ut=t=>{const e=X(t);return e&&s.isCallExpression(e)?e:void 0},pt=t=>{const e=t.getExportAssignment(o=>!o.isExportEquals());if(!e)return;const i=e.getExpression();if(!s.isIdentifier(i))return i;const n=i.getSymbol()?.getValueDeclaration();return n&&s.isVariableDeclaration(n)?n.getInitializer():i},ft=t=>{const e=t.getArguments()[1];return e&&s.isStringLiteral(e)?e.getLiteralValue():""},gt=(t,e)=>{if(!s.isObjectLiteralExpression(t))return;const i=E(t,e);if(!i||!s.isPropertyAssignment(i))return;const n=i.getInitializer();return n&&s.isStringLiteral(n)?n.getLiteralText():void 0},Y=t=>{const e=t.getStatements(),[i]=e;if(e.length!==1||i===void 0||!s.isReturnStatement(i))return;const n=i.getExpression();return n!==void 0&&s.isObjectLiteralExpression(n)?n:void 0},dt=t=>{if(s.isObjectLiteralExpression(t))return t;if(s.isParenthesizedExpression(t)){const e=t.getExpression();return s.isObjectLiteralExpression(e)?e:void 0}return s.isBlock(t)?Y(t):void 0},Et=t=>s.isIdentifier(t)&&t.getText()==="ctx",xt=t=>(e,i,n)=>{if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw I(e,`${t} "${i}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},Q=new Set(["api","internal"]),mt=new Set(["run","runAction","runMutation","runQuery"]),St=t=>{if(t===void 0||!s.isPropertyAccessExpression(t))return;const e=[];let i=t;for(;s.isPropertyAccessExpression(i);)e.unshift(i.getName()),i=i.getExpression();return s.isIdentifier(i)&&Q.has(i.getText())&&e.length>=2?e:void 0};export{mt as RUN_METHODS,C as TS_EXTENSION_RE,nt as bindingKeyName,it as collectCallRows,B as collectNodeRows,st as collectSecurityCallRows,pt as defaultExportExpression,E as findObjectProperty,St as functionReferenceSegments,rt as handlerOf,Et as isContextIdentifier,f as isDatabaseAccessor,ft as limitNameOf,h as listLunoraSourceFiles,k as listSecurityScanFiles,p as lunoraRelativePath,dt as objectLiteralFromCallbackBody,at as optionsObjectLiteral,ot as propertyInitializer,U as propertyKeyName,P as propertyNameText,ct as readTargetOf,xt as stringPropertyFor,gt as stringPropertyOf,W as symbolConstInitializer,m as tableArgumentOf,lt as tablesAccessedIn,X as unwrapExpression,ut as unwrapToCallExpression};
|
package/dist/packem_shared/{loadProjectConfig-nNIDOrlR.mjs → loadProjectConfig-D_pUUrhQ.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{statSync as E,readFileSync as y}from"node:fs";import{basename as P}from"node:path";import{createJiti as x}from"jiti";import{Project as S,Node as t}from"ts-morph";import{propertyKeyName as l}from"./listLunoraSourceFiles-
|
|
1
|
+
import{statSync as E,readFileSync as y}from"node:fs";import{basename as P}from"node:path";import{createJiti as x}from"jiti";import{Project as S,Node as t}from"ts-morph";import{propertyKeyName as l}from"./listLunoraSourceFiles-jTik1QWu.mjs";import{findProjectConfigFile as v}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{PROJECT_CONFIG_FILENAMES as T}from"./PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";const f=new Map,F=async i=>{const r=v(i);if(r===void 0)return{};let e;try{const n=E(r);e=`${String(n.mtimeMs)}:${String(n.size)}`}catch{return{}}const s=f.get(r);if(s?.key===e)return s.value;const a=(async()=>{try{const u=(await x(r,{interopDefault:!1,moduleCache:!1}).import(r))?.default;return{config:u!==null&&typeof u=="object"?u:void 0}}catch(n){return{error:n instanceof Error?n.message:String(n)}}})();return f.set(r,{key:e,value:a}),a},L=i=>{let e=i.getExportAssignments().find(s=>!s.isExportEquals())?.getExpression();for(;e!==void 0&&(t.isSatisfiesExpression(e)||t.isAsExpression(e)||t.isParenthesizedExpression(e));)e=e.getExpression();if(e!==void 0&&t.isIdentifier(e))for(e=i.getVariableDeclaration(e.getText())?.getInitializer();e!==void 0&&(t.isSatisfiesExpression(e)||t.isAsExpression(e));)e=e.getExpression();return e!==void 0&&t.isObjectLiteralExpression(e)?e:void 0},c=(i,r)=>t.isPropertyAssignment(i)?i.getInitializer():r.getVariableDeclaration(l(i))?.getInitializer(),g=i=>{let r=i;for(;r!==void 0&&(t.isSatisfiesExpression(r)||t.isAsExpression(r)||t.isParenthesizedExpression(r));)r=r.getExpression();return r},h=(i,r)=>{const e=g(i);if(e===void 0||!t.isObjectLiteralExpression(e))return{advisor:{unreadable:!0}};const s=e.getProperties(),a=s.filter(o=>t.isPropertyAssignment(o)&&!t.isComputedPropertyName(o.getNameNode())||t.isShorthandPropertyAssignment(o));if(a.length!==s.length)return{advisor:{unreadable:!0}};const n=a.find(o=>l(o)==="minSeverity");if(n===void 0)return{advisor:{}};const u=c(n,r);return u!==void 0&&t.isStringLiteral(u)?{advisor:{minSeverity:u.getLiteralValue()}}:{advisor:{unreadable:!0}}},A=new Map([["advisor",{advisor:{unreadable:!0}}],["remote",{unreadable:!0}],["target",{unreadable:!0}]]),b=(i,r)=>{const e=i.getProperty(r);if(e!==void 0)return(t.isPropertyAssignment(e)?e.getInitializer():void 0)??"unreadable"},m=(i,r)=>{const e=b(i,r);if(e!==void 0)return e!=="unreadable"&&(t.isStringLiteral(e)||t.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():!1},j=i=>{const r=b(i,"rpc");if(r!==void 0)return r!=="unreadable"&&t.isFalseLiteral(r)?!1:"unreadable"},N=i=>{const r=g(i);if(r===void 0||!t.isObjectLiteralExpression(r))return{services:{unreadable:!0}};const e={};for(const s of r.getProperties()){if(!t.isPropertyAssignment(s)||t.isComputedPropertyName(s.getNameNode()))return{services:{unreadable:!0}};const a=g(s.getInitializer());if(a===void 0||!t.isObjectLiteralExpression(a)||a.getProperties().some(d=>!t.isPropertyAssignment(d)))return{services:{unreadable:!0}};const n=m(a,"dir"),u=m(a,"entrypoint"),o=j(a);if(typeof n!="string"||u===!1||o==="unreadable")return{services:{unreadable:!0}};e[l(s)]={dir:n,...u===void 0?{}:{entrypoint:u},...o===void 0?{}:{rpc:o}}}return{services:{declared:e}}},w=(i,r)=>{if(t.isGetAccessorDeclaration(i)||t.isMethodDeclaration(i))return A.get(l(i))??{};if(!t.isPropertyAssignment(i)&&!t.isShorthandPropertyAssignment(i))return{};const e=l(i);if(e==="advisor")return h(c(i,r),r);if(e==="services")return N(c(i,r));if(e!=="target"&&e!=="remote")return{};const s=c(i,r);return s===void 0?{unreadable:!0}:e==="target"?t.isStringLiteral(s)?{target:s.getLiteralValue()}:{unreadable:!0}:t.isTrueLiteral(s)||t.isFalseLiteral(s)?{remote:s.getLiteralValue()}:t.isObjectLiteralExpression(s)?{remote:!0}:{unreadable:!0}},V=i=>{const r=v(i);if(r===void 0)return{};let e;try{e=y(r,"utf8")}catch{return{unreadable:!0}}const a=new S({compilerOptions:{allowJs:!0},skipFileDependencyResolution:!0,skipLoadingLibFiles:!0,useInMemoryFileSystem:!0}).createSourceFile(P(r),e,{overwrite:!0}),n=L(a);if(n===void 0)return{unreadable:!0};if(n.getProperties().some(o=>t.isSpreadAssignment(o))){const o=d=>n.getProperties().some(p=>!t.isSpreadAssignment(p)&&l(p)===d);return{...o("advisor")?{advisor:{unreadable:!0}}:{},...o("services")?{services:{unreadable:!0}}:{},unreadable:!0}}let u={};for(const o of n.getProperties())u={...u,...w(o,a)};return u};export{T as PROJECT_CONFIG_FILENAMES,v as findProjectConfigFile,F as loadProjectConfig,V as readProjectConfigLiterals};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{s as g}from"./paths-C-9fwEgQ.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./listLunoraSourceFiles-
|
|
1
|
+
import{basename as b}from"node:path";import{Node as d}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{s as g}from"./paths-C-9fwEgQ.mjs";import{listLunoraSourceFiles as $,lunoraRelativePath as v,unwrapToCallExpression as E,defaultExportExpression as S,findObjectProperty as M}from"./listLunoraSourceFiles-jTik1QWu.mjs";const h=(e,o)=>e.find(t=>t.ownsFolder!==!1&&o.startsWith(`${t.name}/`))?.name,F="module.ts",w=(e,o,t)=>{if(d.isStringLiteral(e)||d.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw c(e,`module "${o}": \`${t}\` must be a static string literal — codegen reads it without running the file`)},L=(e,o,t)=>{if(!d.isArrayLiteralExpression(e))throw c(e,`module "${o}": \`${t}\` must be an inline array of table names`);return e.getElements().map(n=>w(n,o,t))},p=(e,o,t)=>{const n=M(e,o);if(n!==void 0){if(!d.isPropertyAssignment(n))throw c(n,`module "${t}": write \`${o}\` inline as \`${o}: …\` — codegen reads it without running the file`);return n.getInitializerOrThrow()}},A=(e,o,t)=>{const n=e.getSourceFile(o)??e.addSourceFileAtPath(o),s=E(S(n)),a=s?.getExpression();if(!s||!a||!d.isIdentifier(a)||a.getText()!=="defineModule")return;if(t==="")throw c(s,"defineModule: lunora/module.ts would make the whole app one module — move it into the folder it describes (lunora/<module>/module.ts)");const i=s.getArguments()[0],m={name:t,tables:[]};if(i===void 0)return m;if(!d.isObjectLiteralExpression(i))throw c(i,`module "${t}": defineModule must be passed an inline object literal`);const r=p(i,"description",t);r!==void 0&&(m.description=w(r,t,"description"));const l=p(i,"tables",t);return l!==void 0&&(m.tables=L(l,t,"tables")),m},k=(e,o)=>{const t=[];for(const n of $(o)){if(b(n)!==F)continue;const s=v(o,n),a=A(e,n,s==="module"?"":s.slice(0,-7));a&&t.push(a)}return t.toSorted((n,s)=>n.name.localeCompare(s.name))},T=(e,o)=>{const t=new Set(e.map(r=>r.name)),n=new Set(e.flatMap(r=>r.tables)),s=o.tables.filter(r=>r.extensionKey!==void 0&&!n.has(r.name)),a=Map.groupBy(s,r=>String(r.extensionKey)),i=e.map(r=>{const l=a.get(r.name);return l===void 0?r:{...r,tables:[...r.tables,...l.map(u=>u.name)]}}),m=[...a].filter(([r])=>!t.has(r)).map(([r,l])=>{const u=l.every(f=>f.extensionFromPackage===!0);return{installed:!0,name:r,...u?{ownsFolder:!1}:{},tables:l.map(f=>f.name)}});return[...i,...m].toSorted((r,l)=>r.name.localeCompare(l.name))},x=e=>{for(const o of e){const t=e.find(n=>n.name.startsWith(`${o.name}/`));if(t)throw new Error(`@lunora/codegen: module "${t.name}" is nested inside ${o.installed===!0?"installed component":"module"} "${o.name}" — a file can belong to one module only, so move one of the two`)}},y=(e,o)=>{const t=new Set(o.tables.map(s=>s.name)),n=new Map;for(const s of e)for(const a of s.tables){if(!t.has(a))throw new Error(`@lunora/codegen: module "${s.name}" declares table "${a}", which lunora/schema.ts does not define`);const i=n.get(a);if(i!==void 0)throw new Error(`@lunora/codegen: table "${a}" is claimed by both module "${i}" and module "${s.name}" — a table has one owner`);n.set(a,s.name)}},C=(e,o,t)=>{if(e.length===0)return;const n=new Set(o.map(s=>s.name));for(const s of t){const a=g(s);if(h(o,s)===void 0&&n.has(a))throw new Error(`@lunora/codegen: lunora/${s}.ts sits beside module "${a}" and shares its name — move it into lunora/${a}/ or rename one of them`)}},z=(e,o,t)=>{const n=T(e,o);return x(n),y(n,o),C(e,n,t),n},K=(e,o)=>h(e,o)??g(o);export{h as a,k as d,K as m,z as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";import{Node as n,VariableDeclarationKind as h}from"ts-morph";import{diagnosticAt as v}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{propertyKeyName as E}from"./listLunoraSourceFiles-
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{Node as n,VariableDeclarationKind as h}from"ts-morph";import{diagnosticAt as v}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{propertyKeyName as E}from"./listLunoraSourceFiles-jTik1QWu.mjs";let f;const j=e=>{f=e},A=/^[A-Za-z_$][\w$]*$/u,p=new Set(["$defaultFn","$onUpdateFn","$type","default","defaultNow","nullable","serverDefault","unique"]),k=(e,t)=>{const r={notNull:!0,...e.column};switch(t){case"$defaultFn":case"default":case"defaultNow":case"serverDefault":{r.hasDefault=!0;break}case"$onUpdateFn":{r.hasOnUpdate=!0;break}case"$type":break;case"nullable":{r.notNull=!1;break}case"unique":{r.unique=!0;break}}return{...e,column:r}},N=new Set(["any","bigint","boolean","bytes","date","geoPoint","null","number","string","timestamp"]),m=new Set(["check","email","int","length","max","min","pattern","positive","url"]),I=new Set(["meta"]),L=new Set(["strip"]),l=new Set,g=new Set,S=e=>{const t=e.getSymbol();let r=(t?.getAliasedSymbol()??t)?.getValueDeclaration();if(r!==void 0&&n.isShorthandPropertyAssignment(r)){const i=r.getValueSymbol();r=(i?.getAliasedSymbol()??i)?.getValueDeclaration()}if(!(r===void 0||!n.isVariableDeclaration(r)))return r.getInitializer()},T=e=>{const t=e.getParent();return!n.isVariableDeclaration(t)||t.getVariableStatement()?.getDeclarationKind()===h.Const},u=e=>{if(n.isParenthesizedExpression(e)||n.isAsExpression(e)||n.isSatisfiesExpression(e))return u(e.getExpression());if(n.isObjectLiteralExpression(e))return e;if(n.isPropertyAccessExpression(e)){const r=e.getSymbol()?.getValueDeclaration(),i=r!==void 0&&n.isPropertyAssignment(r)?r.getInitializer():void 0;return i===void 0?void 0:u(i)}if(!n.isIdentifier(e)||l.has(e))return;const t=S(e);if(!(t===void 0||!T(t))){l.add(e);try{return u(t)}finally{l.delete(e)}}},w="v",D=e=>{if(n.isIdentifier(e))return!0;let t=e;for(;n.isCallExpression(t);){const r=t.getExpression();if(!n.isPropertyAccessExpression(r))return!1;t=r.getExpression()}return n.isIdentifier(t)&&t.getText()===w},c=e=>{if(n.isIdentifier(e)&&!l.has(e)){const t=S(e);if(t!==void 0&&D(t)){l.add(e);try{return c(t)}finally{l.delete(e)}}}return n.isCallExpression(e)?P(e):{kind:"any",sourceText:e.getText()}},R=e=>{const t=u(e.getExpression());if(t===void 0||g.has(t))return{};g.add(t);try{return b(t)}finally{g.delete(t)}},b=e=>{const t={};for(const r of e.getProperties()){if(n.isSpreadAssignment(r)){Object.assign(t,R(r));continue}const i=n.isShorthandPropertyAssignment(r);if(!i&&!n.isPropertyAssignment(r))continue;const o=r.getNameNode();if(n.isComputedPropertyName(o))continue;const a=i?r.getNameNode():r.getInitializer();if(!a)continue;const s=E(r);if(!A.test(s))throw new y("INTERNAL",`@lunora/codegen: field name is not a valid JS identifier: ${JSON.stringify(s)}`);t[s]=c(a)}return t},d=(e,t)=>e&&n.isExpression(e)?c(e):t,V=e=>e===void 0?"undefined":n.isStringLiteral(e)||n.isNoSubstitutionTemplateLiteral(e)?JSON.stringify(e.getLiteralValue()):e.getText(),O=e=>{const t=e&&f?f(e):void 0;return t===void 0?{kind:"from"}:{kind:"from",tsType:t}},x=(e,t,r)=>{if(N.has(e))return{kind:e};const[i,o]=t;switch(e){case"array":return{inner:d(i,{kind:"any"}),kind:"array"};case"from":return O(i);case"id":{if(!i||!n.isStringLiteral(i))throw v(i??r,`v.id(...) target table must be a string literal — codegen resolves foreign-key targets statically. Got ${i?i.getText():"no argument"}.`);return{kind:"id",tableName:i.getLiteralText()}}case"literal":return{kind:"literal",literalValue:V(i)};case"object":return i&&n.isObjectLiteralExpression(i)?{kind:"object",shape:b(i)}:{kind:"object",shape:{}};case"optional":return{inner:d(i,{kind:"any"}),kind:"optional"};case"record":return{keyType:d(i,{kind:"string"}),kind:"record",valueType:d(o,{kind:"any"})};case"storage":return i&&n.isStringLiteral(i)?{bucket:i.getLiteralText(),kind:"storage"}:{kind:"storage"};case"union":return{kind:"union",members:t.filter(a=>n.isExpression(a)).map(a=>c(a))};default:throw new y("INTERNAL",`Unsupported validator kind: ${e}`)}},M=e=>{const[t]=e;if(e.length!==1||t===void 0||!n.isNumericLiteral(t))return;const r=Number(t.getText().replaceAll("_",""));return Number.isSafeInteger(r)&&r>=0?r:void 0},P=e=>{const t=e.getExpression();if(!n.isPropertyAccessExpression(t))return{kind:"any",sourceText:e.getText()};const r=t.getName(),i=e.getArguments();if(p.has(r)||m.has(r)||I.has(r)||L.has(r)){const o=t.getExpression(),a=n.isExpression(o)?c(o):{kind:"any"};if(p.has(r))return k(a,r);if(!m.has(r))return a;const s=r==="max"&&a.kind==="string"?M(i):void 0;return s!==void 0?{...a,hasRefinement:!0,stringMaxLength:Math.min(a.stringMaxLength??s,s)}:{...a,hasRefinement:!0,unmodelledRefinement:!0}}return x(r,i,e)};export{c as a,b as p,u as r,j as s};
|
package/dist/packem_shared/{readServiceBindings-CeQvSswr.mjs → readServiceBindings-B_M_ZvhO.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as g,readFileSync as p}from"node:fs";import{isAbsolute as w,resolve as m,join as u}from"node:path";import{ts as h}from"ts-morph";import{readProjectConfigLiterals as E}from"./loadProjectConfig-
|
|
1
|
+
import{existsSync as g,readFileSync as p}from"node:fs";import{isAbsolute as w,resolve as m,join as u}from"node:path";import{ts as h}from"ts-morph";import{readProjectConfigLiterals as E}from"./loadProjectConfig-D_pUUrhQ.mjs";const f=/^[A-Za-z_$][\w$]*$/u,$=["wrangler.jsonc","wrangler.json"],b=t=>`SERVICE_${t.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/gu,"_").toUpperCase()}`,y=(t,e)=>{const r=$.map(n=>u(e,n)).find(n=>g(n));if(r===void 0){const n=g(u(e,"wrangler.toml"))?" (its wrangler.toml is not read — Lunora reads a service's config as JSON(C) only)":"";throw new Error(`@lunora/codegen: service "${t}" points at ${e}, which has no wrangler.jsonc / wrangler.json${n}`)}const o=h.parseConfigFileTextToJson(r,p(r,"utf8"));if(o.error!==void 0||typeof o.config!="object"||o.config===null)throw new Error(`@lunora/codegen: service "${t}": ${r} is not valid JSON(C)`);return{config:o.config,path:r}},v=(t,e)=>{const r=t.route??e.route,o=t.routes??e.routes;return!(r!==void 0||Array.isArray(o)&&o.length>0)&&(t.workers_dev??e.workers_dev)!==!1},S=(t,e,r)=>{if(!f.test(e))throw new Error(`@lunora/codegen: service key "${e}" must be an identifier — it becomes ctx.services.${e}`);if(r.entrypoint!==void 0&&!f.test(r.entrypoint))throw new Error(`@lunora/codegen: service "${e}": entrypoint "${r.entrypoint}" must name an exported WorkerEntrypoint class`);const o=w(r.dir)?r.dir:m(t,r.dir),{config:n,path:s}=y(e,o),{main:c,name:l}=n;if(typeof l!="string"||l==="")throw new Error(`@lunora/codegen: service "${e}": ${s} declares no Worker "name"`);if(typeof c!="string"||c==="")throw new Error(`@lunora/codegen: service "${e}": ${s} declares no "main" entry module`);const d=Object.entries(n.env??{}).map(([i,a])=>[i,a??{}]);return{binding:b(e),...r.entrypoint===void 0?{}:{entrypoint:r.entrypoint},envWorkers:Object.fromEntries(d.flatMap(([i,a])=>typeof a.name=="string"&&a.name!==""?[[i,a.name]]:[])),main:m(o,c),name:e,publicScopes:[...v(n,n)?[""]:[],...d.filter(([,i])=>v(i,n)).map(([i])=>i)],...r.entrypoint===void 0||r.rpc===!1?{}:{rpcEntrypoint:r.entrypoint},worker:l,wranglerPath:s}},j=t=>{const{services:e}=E(t);if(e?.unreadable===!0)throw new Error('@lunora/codegen: lunora.config `services` must be an inline object of { dir: "…", entrypoint?: "…", rpc?: false } literals — codegen reads it without running the file');const r=Object.entries(e?.declared??{}).map(([o,n])=>S(t,o,n)).toSorted((o,n)=>o.name.localeCompare(n.name));for(const[o,n]of r.entries()){const s=r.slice(o+1).find(c=>c.binding===n.binding);if(s!==void 0)throw new Error(`@lunora/codegen: services "${n.name}" and "${s.name}" both map to the binding ${n.binding} — rename one`)}return r},A=t=>{try{return{services:j(t)}}catch(e){return{error:e instanceof Error?e.message:String(e),services:[]}}};export{A as readServiceBindings,j as resolveServiceBindings};
|
package/dist/packem_shared/{unwrap-handler-return-DVY_kFF7.mjs → unwrap-handler-return-DFT18rnR.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as l,SyntaxKind as g}from"ts-morph";import{lunoraRelativePath as L}from"./listLunoraSourceFiles-CSlcBYlo.mjs";import{posix as D}from"node:path";let S,v;const Ae=e=>{const t=S,n=[];S=n;try{return{erased:n,value:e()}}finally{S=t}},Te=e=>{S?.push(...e)},j=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},w=(e,t)=>{S?.push({exportName:j(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Ne=e=>{v!==void 0&&w(v,e)},xe=(e,t)=>{const n=v;v=e;try{return t()}finally{v=n}},k=(e,t)=>{const n=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${n}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${n}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},De=(e,t)=>{const n=new Map;for(const r of e){const s=k(r,L(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},P=/\bany\b(?!\s*(?:\?\s*)?:)/u,U=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,O=e=>P.test(e.replaceAll(U,"")),K="/_generated/",B=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},F=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,T=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=F.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},h=new WeakMap,V=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=h.get(n.compilerSymbol);return r===void 0&&(r=new Map,h.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},_=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),W=(e,t,n)=>e.getModuleSpecifierValue()===t&&_(e,n)?n:void 0,q=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},G=(e,t,n)=>{if(!_(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:V(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},X=/^\.\.?(?:$|\/)/u,H=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),Y=(e,t)=>{const n=t.getModuleSpecifierValue();if(!X.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:H.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${D.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=D.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},J=(e,t,n)=>{const r=T(t);for(const s of e.getImportDeclarations()){const i=r===void 0?q(s,t)??G(s,t,n):W(s,r,n);if(i!==void 0)return{exportName:i,specifier:Y(e,s)??s.getModuleSpecifierValue()}}},z=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),m={kind:"verbatim"},p={kind:"expand"},Q=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),Z=e=>T(e)!==void 0||l.isExportable(e)&&e.isExported(),ee=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),M=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&T(e)===void 0||!Q.has(e.getKind()))return m;const i=s.getFilePath();if(i.includes(K))return m;if(i===n)return p;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return p;const a=J(t.getSourceFile(),o,o.getName());return a===void 0?Z(o)||!ee(r(),o.getName())?m:p:z(a.specifier,t)?p:{kind:"qualify",qualified:a}},te=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),I=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},ne=e=>{for(const t of e.getDeclarations()){const n=t.getFirstChildByKind(g.ComputedPropertyName);if(n!==void 0){let r=n.getExpression();for(;l.isPropertyAccessExpression(r);)r=r.getExpression();return r}}},re=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=ne(s);return i===void 0||!I(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>te.has(s.getKind()))&&!I(r)&&t().startsWith("typeof ")},R=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,a;const c=()=>(a??=e.getText(t),a);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=M(u,t,n,c);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||re(e,c)?p:m},se=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return m;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const a of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const c=M(a,t,n,()=>i.getText());if(c.kind==="qualify")return c;s||=c.kind!=="verbatim"}}return s?p:m},oe=/^[A-Za-z_$][\w$]*$/u,ie=e=>oe.test(e)?e:JSON.stringify(e),$=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},y=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),E=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),R(e,t,n).kind!=="verbatim"||$(e).some(s=>E(s,t,n,r))?!0:y(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>se(i,t,n).kind!=="verbatim")?!0:E(s.getTypeAtLocation(t),t,n,r)):!1),ae=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(l.isPropertySignature(n)||l.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},C=(e,t)=>e!==void 0&&(y(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,ce=32,ue=8,le=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),a=o?i(o,t,n,r,s):void 0;if(a!==void 0)return`${C(o,a)}[]`},ge=(e,t,n,r,s,i)=>{const o=[];for(const a of e.getUnionTypes()){const c=i(a,t,n,r,s);if(c===void 0)return;o.push(c)}return o.join(" | ")},de=(e,t,n,r,s,i)=>{const o=[];for(const a of e.getIntersectionTypes()){const c=i(a,t,n,r,s);if(c===void 0)return;o.push(C(a,c))}return o.join(" & ")},me=(e,t,n,r,s,i)=>{if(!y(e))return;const o=[];for(const a of e.getProperties()){const c=a.getTypeAtLocation(t),u=ae(a,c),d=u&&c.isUnion()?c.getUnionTypes().filter(A=>!A.isUndefined()):[c],N=[];for(const A of d){const x=i(A,t,n,r+1,s);if(x===void 0)return;N.push(x)}o.push(`${ie(a.getName())}${u?"?":""}: ${N.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},fe=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},pe=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),b=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>ce)return!0;const i=new Set(r).add(e);if($(e).some(u=>b(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return b(o,t,n+1,i,s);if(B(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const c=y(e)&&e.getProperties().some(u=>b(u.getTypeAtLocation(t),t,n+1,i,s));return c||s.add(e),c},Se=(e,t,n,r,s,i,o)=>{const a=[];for(const c of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(c,n,r,s+1,i);if(u===void 0)return;a.push(u)}return`import("${e.specifier}").${e.exportName}${a.length>0?`<${a.join(", ")}>`:""}`},ve=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),f=(e,t,n,r,s)=>{if(r>ue||s.has(e))return;const i=R(e,t,n);if(i.kind==="verbatim"&&!E(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!pe(e)){if(e.isEnumLiteral())return fe(e);if(i.kind==="qualify"&&!ve(e)){const a=Se(i.qualified,e,t,n,r,o,f);if(a!==void 0)return a}return e.isArray()?le(e,t,n,r,o,f):e.isUnion()?ge(e,t,n,r,o,f):e.isIntersection()?de(e,t,n,r,o,f):me(e,t,n,r,o,f)}},he=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let n=t.getReturnType();const s=(n.getSymbol()??n.getAliasSymbol())?.getName();if(s==="Promise"||s==="AsyncIterable"||s==="AsyncIterableIterator"||s==="AsyncGenerator"){const a=n.getTypeArguments()[0];a&&(n=a)}const i=n.getText(e);if(!i||i==="any"||i==="never"||O(i)||b(n,e,0,new Set))return"unknown";const o=e.getSourceFile().getFilePath();if(E(n,e,o)){const a=f(n,e,o,0,new Set);return a===void 0&&w(e,i),a??"unknown"}return i};export{E as a,Ne as b,Ae as c,De as d,f as e,O as i,xe as p,Te as r,he as u};
|
|
1
|
+
import{Node as l,SyntaxKind as g}from"ts-morph";import{lunoraRelativePath as L}from"./listLunoraSourceFiles-jTik1QWu.mjs";import{posix as D}from"node:path";let S,v;const Ae=e=>{const t=S,n=[];S=n;try{return{erased:n,value:e()}}finally{S=t}},Te=e=>{S?.push(...e)},j=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},w=(e,t)=>{S?.push({exportName:j(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Ne=e=>{v!==void 0&&w(v,e)},xe=(e,t)=>{const n=v;v=e;try{return t()}finally{v=n}},k=(e,t)=>{const n=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${n}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${n}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},De=(e,t)=>{const n=new Map;for(const r of e){const s=k(r,L(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},P=/\bany\b(?!\s*(?:\?\s*)?:)/u,U=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,O=e=>P.test(e.replaceAll(U,"")),K="/_generated/",B=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},F=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,T=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=F.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},h=new WeakMap,V=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=h.get(n.compilerSymbol);return r===void 0&&(r=new Map,h.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},_=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),W=(e,t,n)=>e.getModuleSpecifierValue()===t&&_(e,n)?n:void 0,q=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},G=(e,t,n)=>{if(!_(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:V(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},X=/^\.\.?(?:$|\/)/u,H=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),Y=(e,t)=>{const n=t.getModuleSpecifierValue();if(!X.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:H.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${D.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=D.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},J=(e,t,n)=>{const r=T(t);for(const s of e.getImportDeclarations()){const i=r===void 0?q(s,t)??G(s,t,n):W(s,r,n);if(i!==void 0)return{exportName:i,specifier:Y(e,s)??s.getModuleSpecifierValue()}}},z=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),m={kind:"verbatim"},p={kind:"expand"},Q=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),Z=e=>T(e)!==void 0||l.isExportable(e)&&e.isExported(),ee=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),M=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&T(e)===void 0||!Q.has(e.getKind()))return m;const i=s.getFilePath();if(i.includes(K))return m;if(i===n)return p;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return p;const a=J(t.getSourceFile(),o,o.getName());return a===void 0?Z(o)||!ee(r(),o.getName())?m:p:z(a.specifier,t)?p:{kind:"qualify",qualified:a}},te=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),I=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},ne=e=>{for(const t of e.getDeclarations()){const n=t.getFirstChildByKind(g.ComputedPropertyName);if(n!==void 0){let r=n.getExpression();for(;l.isPropertyAccessExpression(r);)r=r.getExpression();return r}}},re=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=ne(s);return i===void 0||!I(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>te.has(s.getKind()))&&!I(r)&&t().startsWith("typeof ")},R=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,a;const c=()=>(a??=e.getText(t),a);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=M(u,t,n,c);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||re(e,c)?p:m},se=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return m;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const a of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const c=M(a,t,n,()=>i.getText());if(c.kind==="qualify")return c;s||=c.kind!=="verbatim"}}return s?p:m},oe=/^[A-Za-z_$][\w$]*$/u,ie=e=>oe.test(e)?e:JSON.stringify(e),$=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},y=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),E=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),R(e,t,n).kind!=="verbatim"||$(e).some(s=>E(s,t,n,r))?!0:y(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>se(i,t,n).kind!=="verbatim")?!0:E(s.getTypeAtLocation(t),t,n,r)):!1),ae=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(l.isPropertySignature(n)||l.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},C=(e,t)=>e!==void 0&&(y(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,ce=32,ue=8,le=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),a=o?i(o,t,n,r,s):void 0;if(a!==void 0)return`${C(o,a)}[]`},ge=(e,t,n,r,s,i)=>{const o=[];for(const a of e.getUnionTypes()){const c=i(a,t,n,r,s);if(c===void 0)return;o.push(c)}return o.join(" | ")},de=(e,t,n,r,s,i)=>{const o=[];for(const a of e.getIntersectionTypes()){const c=i(a,t,n,r,s);if(c===void 0)return;o.push(C(a,c))}return o.join(" & ")},me=(e,t,n,r,s,i)=>{if(!y(e))return;const o=[];for(const a of e.getProperties()){const c=a.getTypeAtLocation(t),u=ae(a,c),d=u&&c.isUnion()?c.getUnionTypes().filter(A=>!A.isUndefined()):[c],N=[];for(const A of d){const x=i(A,t,n,r+1,s);if(x===void 0)return;N.push(x)}o.push(`${ie(a.getName())}${u?"?":""}: ${N.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},fe=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},pe=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),b=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>ce)return!0;const i=new Set(r).add(e);if($(e).some(u=>b(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return b(o,t,n+1,i,s);if(B(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const c=y(e)&&e.getProperties().some(u=>b(u.getTypeAtLocation(t),t,n+1,i,s));return c||s.add(e),c},Se=(e,t,n,r,s,i,o)=>{const a=[];for(const c of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(c,n,r,s+1,i);if(u===void 0)return;a.push(u)}return`import("${e.specifier}").${e.exportName}${a.length>0?`<${a.join(", ")}>`:""}`},ve=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),f=(e,t,n,r,s)=>{if(r>ue||s.has(e))return;const i=R(e,t,n);if(i.kind==="verbatim"&&!E(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!pe(e)){if(e.isEnumLiteral())return fe(e);if(i.kind==="qualify"&&!ve(e)){const a=Se(i.qualified,e,t,n,r,o,f);if(a!==void 0)return a}return e.isArray()?le(e,t,n,r,o,f):e.isUnion()?ge(e,t,n,r,o,f):e.isIntersection()?de(e,t,n,r,o,f):me(e,t,n,r,o,f)}},he=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let n=t.getReturnType();const s=(n.getSymbol()??n.getAliasSymbol())?.getName();if(s==="Promise"||s==="AsyncIterable"||s==="AsyncIterableIterator"||s==="AsyncGenerator"){const a=n.getTypeArguments()[0];a&&(n=a)}const i=n.getText(e);if(!i||i==="any"||i==="never"||O(i)||b(n,e,0,new Set))return"unknown";const o=e.getSourceFile().getFilePath();if(E(n,e,o)){const a=f(n,e,o,0,new Set);return a===void 0&&w(e,i),a??"unknown"}return i};export{E as a,Ne as b,Ae as c,De as d,f as e,O as i,xe as p,Te as r,he as u};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.257",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
50
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.187",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.170",
|
|
51
51
|
"@lunora/container": "1.0.0-alpha.69",
|
|
52
52
|
"@lunora/errors": "1.0.0-alpha.50",
|
|
53
53
|
"@lunora/platform": "1.0.0-alpha.55",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{existsSync as g}from"node:fs";import{join as b}from"node:path";import{LunoraError as f}from"@lunora/errors";import{queueDefaultName as y,queueBindingName as h}from"@lunora/queue";import{SyntaxKind as q,Node as a}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as d,stringPropertyFor as w}from"./listLunoraSourceFiles-CSlcBYlo.mjs";const N="queues.ts",x=i=>{const t=e=>e==="defineQueue"||e==="defineSubscription"||e==="defineTopic",o=i.getSymbol();if(!o){const e=i.getText();return t(e)?e:void 0}for(const e of o.getDeclarations()){if(!a.isImportSpecifier(e))continue;if(e.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/queue")return;const r=e.getNameNode().getText();return t(r)?r:void 0}},p=w("queue"),E=(i,t,o)=>{if(a.isNumericLiteral(i))return i.getLiteralValue();throw c(i,`queue "${t}": \`${o}\` must be a static numeric literal — it is deploy configuration codegen writes into wrangler.jsonc`)},S=(i,t)=>{const o=d(i,"name");if(!o||!a.isPropertyAssignment(o))return;const e=p(o.getInitializerOrThrow(),t,"name");if(e.length===0)throw c(o,`queue "${t}": \`name\` must be a non-empty string when provided`);return e},l=(i,t,o)=>{const e={bindingName:h(t),exportName:t,mode:"push",name:S(i,t)??y(t),...o===void 0?{}:{topic:o},tuning:{}},r=d(i,"mode");if(r&&a.isPropertyAssignment(r)){if(o!==void 0)throw c(r,`subscription "${t}": \`mode\` is not allowed — a subscription is always a push consumer`);const s=p(r.getInitializerOrThrow(),t,"mode");if(s!=="push"&&s!=="pull")throw c(r,`queue "${t}": \`mode\` must be "push" or "pull" (got ${JSON.stringify(s)})`);e.mode=s}const n=d(i,"deadLetterQueue");n&&a.isPropertyAssignment(n)&&(e.tuning.deadLetterQueue=p(n.getInitializerOrThrow(),t,"deadLetterQueue"));for(const s of["maxBatchSize","maxBatchTimeout","maxRetries","retryDelay"]){const u=d(i,s);u&&a.isPropertyAssignment(u)&&(e.tuning[s]=E(u.getInitializerOrThrow(),t,s))}return e},v=(i,t)=>{const o=i.getArguments()[0];if(!o||!a.isObjectLiteralExpression(o))throw c(i,`queue "${t}": defineQueue must be passed an inline object literal`);return l(o,t,void 0)},$=(i,t,o)=>{const[e,r]=i.getArguments();if(!e||!a.isIdentifier(e)||!o.has(e.getText()))throw c(e??i,`subscription "${t}": the first argument must name a \`defineTopic()\` export of lunora/queues.ts`);if(!r||!a.isObjectLiteralExpression(r))throw c(i,`subscription "${t}": defineSubscription must be passed an inline object literal`);return l(r,t,e.getText())},I=i=>{const t=[];for(const o of i.getVariableDeclarations()){if(!o.isExported())continue;const e=o.getInitializer();if(e?.getKind()!==q.CallExpression)continue;const r=e,n=r.getExpression(),s=a.isIdentifier(n)?x(n):void 0;if(s===void 0)continue;const u=o.getNameNode();if(!a.isIdentifier(u))throw c(u,`${s} exports must be plain named exports (no destructuring)`);t.push({call:r,exportName:u.getText(),factory:s})}return t},P=i=>{const t=I(i),o=new Set(t.filter(n=>n.factory==="defineTopic").map(n=>n.exportName)),e=[];for(const n of t)n.factory==="defineQueue"?e.push(v(n.call,n.exportName)):n.factory==="defineSubscription"&&e.push($(n.call,n.exportName,o));const r=[...o].map(n=>({exportName:n}));return{queues:e,topics:r}},T=i=>{const t=new Map,o=new Map;for(const e of i){const r=t.get(e.name);if(r!==void 0)throw new f("DUPLICATE_QUEUE_NAME",`Duplicate queue name "${e.name}": produced by both "${r}" and "${e.exportName}". Deployed queue names must be unique across the project.`,{status:500});t.set(e.name,e.exportName);const n=o.get(e.bindingName);if(n!==void 0)throw new f("DUPLICATE_QUEUE_BINDING",`Duplicate queue binding "${e.bindingName}": produced by both "${n}" and "${e.exportName}". Queue export names must yield unique binding names.`,{status:500});o.set(e.bindingName,e.exportName)}},A=(i,t)=>{const o=b(t,N);if(!g(o))return{queues:[],topics:[]};const e=i.getSourceFile(o)??i.addSourceFileAtPath(o),{queues:r,topics:n}=P(e),s=r.toSorted((u,m)=>u.exportName.localeCompare(m.exportName));return T(s),{queues:s,topics:n.toSorted((u,m)=>u.exportName.localeCompare(m.exportName))}},j=(i,t)=>A(i,t).queues;export{N as QUEUES_FILENAME,A as discoverQueueDeclarations,j as discoverQueues};
|