@lunora/codegen 1.0.0-alpha.117 → 1.0.0-alpha.119
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 +15 -22
- package/dist/index.d.ts +15 -22
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-TYN36IWp.mjs → GENERATED_HEADER-Cx5Qh2XJ.mjs} +1 -1
- package/dist/packem_shared/{MUTATORS_FILENAME-sGAt-yC1.mjs → MUTATORS_FILENAME-B2-W8Bm3.mjs} +1 -1
- package/dist/packem_shared/{NOTIFY_FILENAME-CTZI61e3.mjs → NOTIFY_FILENAME-IJXY4yHt.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-BGbPExk0.mjs → OPENRPC_VERSION-14yZ-O3V.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-ks41Eeih.mjs → SCHEMA_SNAPSHOT_FILENAME-CbOqo05-.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs +2 -0
- package/dist/packem_shared/{SDK_LANGUAGES-BHYgTciL.mjs → SDK_LANGUAGES-CFyux-74.mjs} +1 -1
- package/dist/packem_shared/{SchemaSnapshotParseError-Dc1aZAph.mjs → SchemaSnapshotParseError-BoHDfCO3.mjs} +1 -1
- package/dist/packem_shared/{buildOpenApiDocument-Dk1RRaq3.mjs → buildOpenApiDocument-DI8bgteQ.mjs} +1 -1
- package/dist/packem_shared/discoverFunctions-006teuNG.mjs +1 -0
- package/dist/packem_shared/{discoverHttpRoutes-DOirwCWw.mjs → discoverHttpRoutes-BxF4FRZL.mjs} +1 -1
- package/dist/packem_shared/{discoverMaskProcedures-D-09Qb8S.mjs → discoverMaskProcedures-BCl3fNrQ.mjs} +1 -1
- package/dist/packem_shared/{discoverNondeterministicCalls-DhNToI6C.mjs → discoverNondeterministicCalls-BA91Z-vF.mjs} +1 -1
- package/dist/packem_shared/{discoverR2sqlCalls-B6e4j4rD.mjs → discoverR2sqlCalls-M2ob41UX.mjs} +1 -1
- package/dist/packem_shared/{discoverRlsMetadata-Pw0_c1aS.mjs → discoverRlsMetadata-Dwt2p8IK.mjs} +1 -1
- package/dist/packem_shared/{discoverSchema-D_wHstA-.mjs → discoverSchema-gJ93Xjpx.mjs} +1 -1
- package/dist/packem_shared/{discoverStorageRulesMetadata-DthHu3mC.mjs → discoverStorageRulesMetadata-69Y8wZb2.mjs} +1 -1
- package/dist/packem_shared/{emit-B6siM7LU.mjs → emit-C0azW4mT.mjs} +307 -216
- package/dist/packem_shared/{emitApp-C6P6ckvr.mjs → emitApp-Dyr-onNf.mjs} +1 -1
- package/dist/packem_shared/{formatAdvisories-BjTV22uR.mjs → formatAdvisories-CkEu1eye.mjs} +1 -1
- package/dist/packem_shared/isTypedSchema-B_qlBbE-.mjs +2 -0
- package/package.json +6 -6
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs +0 -2
- package/dist/packem_shared/discoverFunctions-4eSpCR6m.mjs +0 -1
- package/dist/packem_shared/isTypedSchema-BBIBMZTg.mjs +0 -2
package/dist/index.d.mts
CHANGED
|
@@ -7,27 +7,6 @@ import { StudioFeaturesResult } from '@lunora/shard-engine';
|
|
|
7
7
|
import { Schema } from '@lunora/server';
|
|
8
8
|
import { JsonSchema } from '@lunora/values';
|
|
9
9
|
import { LanguageName } from 'quicktype-core';
|
|
10
|
-
/**
|
|
11
|
-
* The structural schema-snapshot format and its diff, shared by `@lunora/codegen`
|
|
12
|
-
* (which builds snapshots from the parsed schema IR and gates deploys on the
|
|
13
|
-
* diff) and `@lunora/studio` (which renders the same diff as a visual migration
|
|
14
|
-
* history).
|
|
15
|
-
*
|
|
16
|
-
* Having ONE diff is the point: the Studio's schema-history view and the
|
|
17
|
-
* pre-deploy drift gate must classify a change identically, or the UI will say a
|
|
18
|
-
* change is safe while `lunora deploy` refuses it. `@lunora/codegen` is a
|
|
19
|
-
* build-time package the browser bundle cannot import, and neither package sits
|
|
20
|
-
* below the other, so — like `shared/quote-identifier.ts` — this lives outside
|
|
21
|
-
* both and is bundler-inlined into each. Keep it genuinely zero-dependency
|
|
22
|
-
* (relative/built-in imports only) or inlining breaks. Consumers must drop
|
|
23
|
-
* `outDir`/`rootDir` from their `tsconfig.json` (a set `rootDir` raises TS6059
|
|
24
|
-
* for this out-of-package file under `tsc --noEmit`).
|
|
25
|
-
*
|
|
26
|
-
* What stays in `@lunora/codegen`: building a snapshot from `SchemaIR`, the
|
|
27
|
-
* `SchemaSnapshotParseError` class (it extends `LunoraError`), and the deploy
|
|
28
|
-
* gate's policy (`evaluateSchemaDrift`). What lives here: the format, the diff,
|
|
29
|
-
* the severity classification, and the content hash.
|
|
30
|
-
*/
|
|
31
10
|
/** Current snapshot format version. Bumped if the structural shape below changes. */
|
|
32
11
|
declare const SCHEMA_SNAPSHOT_VERSION: 1;
|
|
33
12
|
/** A single field's structural shape: its value kind and whether it is optional. */
|
|
@@ -294,6 +273,13 @@ interface ExternalSourceIR {
|
|
|
294
273
|
unanalyzable?: boolean;
|
|
295
274
|
}
|
|
296
275
|
interface TableIR {
|
|
276
|
+
/**
|
|
277
|
+
* `true` when the table chain carried `.commitOrdered()` — every row carries
|
|
278
|
+
* `_commitSeq`, a per-shard integer allocated once per mutation and strictly
|
|
279
|
+
* increasing in commit order. Optional: hand-built IR and tables that never
|
|
280
|
+
* called `.commitOrdered()` default it to `false`.
|
|
281
|
+
*/
|
|
282
|
+
commitOrdered?: boolean;
|
|
297
283
|
/**
|
|
298
284
|
* The `defineSchemaExtension` key that contributed this table, set when it
|
|
299
285
|
* arrived through `defineSchema(...).extend(...)`. Absent for a table the app
|
|
@@ -334,6 +320,13 @@ interface TableIR {
|
|
|
334
320
|
* `false`.
|
|
335
321
|
*/
|
|
336
322
|
isPublic?: boolean;
|
|
323
|
+
/**
|
|
324
|
+
* `true` when the table chain carried `.memory()` — its rows are cleared on
|
|
325
|
+
* every Durable Object cold start and never reach the CDC changelog.
|
|
326
|
+
* Optional: hand-built IR and tables that never called `.memory()` default it
|
|
327
|
+
* to `false`.
|
|
328
|
+
*/
|
|
329
|
+
memory?: boolean;
|
|
337
330
|
name: string;
|
|
338
331
|
/** Rank indexes declared inline via `.rankIndex(name, …)`. */
|
|
339
332
|
rankIndexes: ReadonlyArray<RankIndexIR>;
|
|
@@ -416,7 +409,7 @@ interface FunctionIR {
|
|
|
416
409
|
* it into the `LUNORA_LIFECYCLE_HOOKS` manifest keyed by this side. Absent on
|
|
417
410
|
* ordinary functions.
|
|
418
411
|
*/
|
|
419
|
-
lifecycle?: "connect" | "disconnect";
|
|
412
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor";
|
|
420
413
|
/**
|
|
421
414
|
* The `.output(validator)` declaration, when the chain has one.
|
|
422
415
|
*
|
package/dist/index.d.ts
CHANGED
|
@@ -7,27 +7,6 @@ import { StudioFeaturesResult } from '@lunora/shard-engine';
|
|
|
7
7
|
import { Schema } from '@lunora/server';
|
|
8
8
|
import { JsonSchema } from '@lunora/values';
|
|
9
9
|
import { LanguageName } from 'quicktype-core';
|
|
10
|
-
/**
|
|
11
|
-
* The structural schema-snapshot format and its diff, shared by `@lunora/codegen`
|
|
12
|
-
* (which builds snapshots from the parsed schema IR and gates deploys on the
|
|
13
|
-
* diff) and `@lunora/studio` (which renders the same diff as a visual migration
|
|
14
|
-
* history).
|
|
15
|
-
*
|
|
16
|
-
* Having ONE diff is the point: the Studio's schema-history view and the
|
|
17
|
-
* pre-deploy drift gate must classify a change identically, or the UI will say a
|
|
18
|
-
* change is safe while `lunora deploy` refuses it. `@lunora/codegen` is a
|
|
19
|
-
* build-time package the browser bundle cannot import, and neither package sits
|
|
20
|
-
* below the other, so — like `shared/quote-identifier.ts` — this lives outside
|
|
21
|
-
* both and is bundler-inlined into each. Keep it genuinely zero-dependency
|
|
22
|
-
* (relative/built-in imports only) or inlining breaks. Consumers must drop
|
|
23
|
-
* `outDir`/`rootDir` from their `tsconfig.json` (a set `rootDir` raises TS6059
|
|
24
|
-
* for this out-of-package file under `tsc --noEmit`).
|
|
25
|
-
*
|
|
26
|
-
* What stays in `@lunora/codegen`: building a snapshot from `SchemaIR`, the
|
|
27
|
-
* `SchemaSnapshotParseError` class (it extends `LunoraError`), and the deploy
|
|
28
|
-
* gate's policy (`evaluateSchemaDrift`). What lives here: the format, the diff,
|
|
29
|
-
* the severity classification, and the content hash.
|
|
30
|
-
*/
|
|
31
10
|
/** Current snapshot format version. Bumped if the structural shape below changes. */
|
|
32
11
|
declare const SCHEMA_SNAPSHOT_VERSION: 1;
|
|
33
12
|
/** A single field's structural shape: its value kind and whether it is optional. */
|
|
@@ -294,6 +273,13 @@ interface ExternalSourceIR {
|
|
|
294
273
|
unanalyzable?: boolean;
|
|
295
274
|
}
|
|
296
275
|
interface TableIR {
|
|
276
|
+
/**
|
|
277
|
+
* `true` when the table chain carried `.commitOrdered()` — every row carries
|
|
278
|
+
* `_commitSeq`, a per-shard integer allocated once per mutation and strictly
|
|
279
|
+
* increasing in commit order. Optional: hand-built IR and tables that never
|
|
280
|
+
* called `.commitOrdered()` default it to `false`.
|
|
281
|
+
*/
|
|
282
|
+
commitOrdered?: boolean;
|
|
297
283
|
/**
|
|
298
284
|
* The `defineSchemaExtension` key that contributed this table, set when it
|
|
299
285
|
* arrived through `defineSchema(...).extend(...)`. Absent for a table the app
|
|
@@ -334,6 +320,13 @@ interface TableIR {
|
|
|
334
320
|
* `false`.
|
|
335
321
|
*/
|
|
336
322
|
isPublic?: boolean;
|
|
323
|
+
/**
|
|
324
|
+
* `true` when the table chain carried `.memory()` — its rows are cleared on
|
|
325
|
+
* every Durable Object cold start and never reach the CDC changelog.
|
|
326
|
+
* Optional: hand-built IR and tables that never called `.memory()` default it
|
|
327
|
+
* to `false`.
|
|
328
|
+
*/
|
|
329
|
+
memory?: boolean;
|
|
337
330
|
name: string;
|
|
338
331
|
/** Rank indexes declared inline via `.rankIndex(name, …)`. */
|
|
339
332
|
rankIndexes: ReadonlyArray<RankIndexIR>;
|
|
@@ -416,7 +409,7 @@ interface FunctionIR {
|
|
|
416
409
|
* it into the `LUNORA_LIFECYCLE_HOOKS` manifest keyed by this side. Absent on
|
|
417
410
|
* ordinary functions.
|
|
418
411
|
*/
|
|
419
|
-
lifecycle?: "connect" | "disconnect";
|
|
412
|
+
lifecycle?: "connect" | "disconnect" | "init" | "reactor";
|
|
420
413
|
/**
|
|
421
414
|
* The `.output(validator)` declaration, when the chain has one.
|
|
422
415
|
*
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as S}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-CPHo8Se5.mjs";import{default as g}from"./packem_shared/discoverAuthApiCalls-DUjcl0SB.mjs";import{CONTAINERS_FILENAME as R,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{default as C}from"./packem_shared/discoverCrons-BUJO2ipU.mjs";import{FLAGS_FILENAME as T,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-DtBWyUKq.mjs";import{discoverFunctions as F}from"./packem_shared/discoverFunctions-006teuNG.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-BxF4FRZL.mjs";import{default as G}from"./packem_shared/discoverInserts-YX8AmrzL.mjs";import{default as b}from"./packem_shared/discoverMaskProcedures-BCl3fNrQ.mjs";import{default as y}from"./packem_shared/discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as j,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-B2-W8Bm3.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-BA91Z-vF.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as q,discoverNotifyConfig as B}from"./packem_shared/NOTIFY_FILENAME-IJXY4yHt.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as Z}from"./packem_shared/discover-queries-Dfj_0WJG.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-BnGLtAIu.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-M2ob41UX.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-Dwt2p8IK.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-L0lV17de.mjs";import{default as pe}from"./packem_shared/discoverSchema-gJ93Xjpx.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-DTp6VI6K.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-69Y8wZb2.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-B8y51Frf.mjs";import{G as Ne,e as ge,a as Oe,b as Re,c as Me,d as he,f as Ce,g as _e,h as Te,i as Ie,j as Le,k as Fe,l as De,m as Pe}from"./packem_shared/emit-C0azW4mT.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-Dyr-onNf.mjs";import{buildOpenApiDocument as be,emitOpenApi as ke,emitOpenApiModule as ye}from"./packem_shared/buildOpenApiDocument-DI8bgteQ.mjs";import{OPENRPC_VERSION as je,buildOpenRpcDocument as Ke,emitOpenRpc as Ve,emitOpenRpcModule as ze}from"./packem_shared/OPENRPC_VERSION-14yZ-O3V.mjs";import{DEFAULT_TARGET as we,platformMatrixIds as qe,readProjectTarget as Be,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-CIH5PRk1.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Xe,createCodegenProject as Ze,findTsconfig as $e,refreshCodegenProject as er,runCodegen as rr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-CbOqo05-.mjs";import{SchemaSnapshotParseError as tr,buildSchemaSnapshot as sr,evaluateSchemaDrift as ar,parseSchemaSnapshot as ir}from"./packem_shared/SchemaSnapshotParseError-BoHDfCO3.mjs";import{schemaFromIr as dr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as pr,validatorIrToJsonSchema as cr}from"./packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs";import{SDK_LANGUAGES as Sr,SDK_TARGETS as lr,generateSdk as Er}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Ar,secretKindOf as ur}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Nr,findSolutionByMessage as gr}from"@lunora/errors";import{isTypedSchema as Rr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,R as CONTAINERS_FILENAME,E as CodegenDiagnosticError,we as DEFAULT_TARGET,T as FLAGS_FILENAME,Ne as GENERATED_HEADER,pr as LUNORA_ERROR_CODES,Nr as LUNORA_SOLUTION_RULES,j as MUTATORS_FILENAME,w as NOTIFY_FILENAME,je as OPENRPC_VERSION,ee as QUEUES_FILENAME,Xe as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Sr as SDK_LANGUAGES,lr as SDK_TARGETS,ne as SHAPES_FILENAME,tr as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,be as buildOpenApiDocument,Ke as buildOpenRpcDocument,sr as buildSchemaSnapshot,Ze as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,g as discoverAuthApiCalls,M as discoverContainers,C as discoverCrons,I as discoverFlags,F as discoverFunctions,P as discoverHttpRoutes,G as discoverInserts,b as discoverMaskProcedures,y as discoverMigrations,K as discoverMutators,z as discoverNondeterministicCalls,q as discoverNotifyCalls,B as discoverNotifyConfig,Z as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,pe as discoverSchema,Se as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,ge as emitAgents,Oe as emitApi,Ge as emitApp,Re as emitCollections,Me as emitContainers,he as emitCrons,Ce as emitDataModel,_e as emitDrizzleSchema,Te as emitFunctions,ke as emitOpenApi,ye as emitOpenApiModule,Ve as emitOpenRpc,ze as emitOpenRpcModule,Ie as emitServer,Le as emitShard,Fe as emitVectors,De as emitWorkflows,Pe as emitWranglerCronTriggers,n as errorAdvisoryNames,S as errorPlatformDiagnosticNames,ar as evaluateSchemaDrift,gr as findLunoraSolution,$e as findTsconfig,m as formatAdvisories,Er as generateSdk,Rr as isTypedSchema,d as lintSchema,ir as parseSchemaSnapshot,qe as platformMatrixIds,Y as readPackageDependencies,Be as readProjectTarget,Ar as redact,er as refreshCodegenProject,Je as resolveCodegenTarget,rr as runCodegen,dr as schemaFromIr,ur as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,cr as validatorIrToJsonSchema};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs";import{G as t,U as m,n as r,e as o,a as n,b as l,c as A,d as E,f as S,g,h as C,o as c,p as d,i as p,j as u,k as D,l as f,m as h}from"./emit-C0azW4mT.mjs";import"./paths-C-9fwEgQ.mjs";export{t as GENERATED_HEADER,m as UMBRELLA_BASE_PACKAGES,r as buildStorageColumns,o as emitAgents,n as emitApi,l as emitCollections,A as emitContainers,E as emitCrons,S as emitDataModel,g as emitDrizzleSchema,C as emitFunctions,c as emitQueues,d as emitSeed,p as emitServer,u as emitShard,D as emitVectors,f as emitWorkflows,h as emitWranglerCronTriggers};
|
package/dist/packem_shared/{MUTATORS_FILENAME-sGAt-yC1.mjs → MUTATORS_FILENAME-B2-W8Bm3.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as f}from"node:fs";import{join as p}from"node:path";import{Node as o,SyntaxKind as u}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapHandlerReturn as g}from"./discoverFunctions-
|
|
1
|
+
import{existsSync as f}from"node:fs";import{join as p}from"node:path";import{Node as o,SyntaxKind as u}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{unwrapHandlerReturn as g}from"./discoverFunctions-006teuNG.mjs";import{a as d}from"./module-specifiers-WF8iAydP.mjs";import{a as x}from"./parse-validator-C5ycrhR3.mjs";const M="mutators.ts",m=d,y=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineMutator";for(const e of t.getDeclarations())if(o.isImportSpecifier(e))return m(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineMutator":!1;return!1},S=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(u.ImportDeclaration);return i!==void 0&&m(i.getModuleSpecifierValue())}return!1},N=r=>{if(o.isIdentifier(r))return y(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineMutator"&&o.isIdentifier(t)&&S(t)}return!1},I=r=>{const t=r.getArguments()[0];return t&&o.isObjectLiteralExpression(t)?t:void 0},b=r=>{const t=r?.getProperty("args");if(!t||!o.isPropertyAssignment(t))return{};const e=t.getInitializer();return e&&o.isObjectLiteralExpression(e)?x(e):{}},A=r=>{const t=r?.getProperty("server");if(!t||!o.isPropertyAssignment(t))return"unknown";const e=t.getInitializer();return!e||!(o.isArrowFunction(e)||o.isFunctionExpression(e))?"unknown":g(e)},E=r=>{const t=[];for(const e of r.getVariableDeclarations()){if(!e.isExported())continue;const i=e.getInitializer();if(i?.getKind()!==u.CallExpression)continue;const n=i,a=n.getExpression();if(!N(a))continue;const s=e.getNameNode();if(!o.isIdentifier(s))throw l(s,"defineMutator exports must be plain named exports (no destructuring)");const c=I(n);t.push({args:b(c),exportName:s.getText(),filePath:"mutators",returnType:A(c)})}return t},w=(r,t)=>{const e=p(t,M);if(!f(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),n=E(i);return n.sort((a,s)=>a.exportName.localeCompare(s.exportName)),n};export{M as MUTATORS_FILENAME,w as discoverMutators,N as isDefineMutatorCallee};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as m}from"node:fs";import{join as x}from"node:path";import{SyntaxKind as d,Node as c}from"ts-morph";import{l,a as g,d as P,h as E}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as S}from"./discoverFunctions-
|
|
1
|
+
import{existsSync as m}from"node:fs";import{join as x}from"node:path";import{SyntaxKind as d,Node as c}from"ts-morph";import{l,a as g,d as P,h as E}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as S}from"./discoverFunctions-006teuNG.mjs";const y="notify.ts",v=new Set(["chat","inApp","send","webhook"]),p=new Set(["broadcast","send"]),N=e=>{const t=e.getInitializer();if(!t||!c.isCallExpression(t))return;const o=S(t);if(!o)return;const s=E(t,o.receiver);return s?{exportName:e.getName(),handler:s,kind:o.kind}:void 0},h=e=>{const t=[];for(const o of e.getVariableStatements())if(o.isExported())for(const s of o.getDeclarations()){const r=N(s);r&&t.push(r)}return t},f=e=>{if(!c.isPropertyAccessExpression(e))return;const t=e.getName(),o=e.getExpression();if((t==="notify"||t==="push")&&c.isIdentifier(o)&&o.getText()==="ctx")return t;if(t==="push"&&f(o)==="notify")return"push"},F=e=>{if(!c.isPropertyAccessExpression(e))return;const t=e.getName(),o=f(e.getExpression());if(o==="notify"&&v.has(t))return`ctx.notify.${t}`;if(o==="push"&&p.has(t))return`ctx.push.${t}`},A=e=>c.isPropertyAccessExpression(e)?f(e.getExpression())==="push"&&p.has(e.getName()):!1,T=(e,t)=>{const o=[];for(const s of l(t)){const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),a=g(t,s);for(const n of h(r))if(!(n.kind!=="query"&&n.kind!=="mutation"))for(const i of n.handler.getDescendantsOfKind(d.PropertyAccessExpression)){const u=F(i);u!==void 0&&o.push({callee:u,exportName:n.exportName,file:a,kind:n.kind,line:i.getStartLineNumber()})}}return o},O=(e,t)=>{for(const o of l(t)){const s=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const r of h(s))for(const a of r.handler.getDescendantsOfKind(d.PropertyAccessExpression))if(A(a))return!0}return!1},_=(e,t)=>{const o=x(t,y);if(!m(o))return;const s=e.getSourceFile(o)??e.addSourceFileAtPath(o),r=P(s);let a=!1,n=!1;if(r&&c.isCallExpression(r)){const i=r.getArguments()[0];i&&c.isObjectLiteralExpression(i)&&(a=i.getProperty("webPush")!==void 0,n=i.getProperty("fcm")!==void 0)}return{hasFcm:n,hasWebPush:a,usesPush:O(e,t)}};export{y as NOTIFY_FILENAME,T as discoverNotifyCalls,_ as discoverNotifyConfig};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as c}from"./emit-
|
|
1
|
+
import{G as c}from"./emit-C0azW4mT.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
|
|
2
2
|
`,v=e=>`${c}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{l as OPENRPC_VERSION,g as buildOpenRpcDocument,S as emitOpenRpc,v as emitOpenRpcModule};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as N,mkdirSync as jt,readFileSync as ht,writeFileSync as Vt,rmSync as Wt}from"node:fs";import{join as f,dirname as ue}from"node:path";import{performance as de}from"node:perf_hooks";import{runAdvisor as Ht}from"@lunora/advisor";import{LunoraError as O}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as Qe}from"ts-morph";import{serializeSchemaSnapshot as Gt}from"./SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import{existsSync as N,mkdirSync as jt,readFileSync as ht,writeFileSync as Vt,rmSync as Wt}from"node:fs";import{join as f,dirname as ue}from"node:path";import{performance as de}from"node:perf_hooks";import{runAdvisor as Ht}from"@lunora/advisor";import{LunoraError as O}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as Qe}from"ts-morph";import{serializeSchemaSnapshot as Gt}from"./SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs";import{toAdvisorContext as Yt}from"./formatAdvisories-CkEu1eye.mjs";import{discoverAgents as Qt}from"./AGENTS_FILENAME-CPHo8Se5.mjs";import{discoverContainers as Xt}from"./CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{diagnosticAt as J}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ee}from"./module-specifiers-WF8iAydP.mjs";import{C as fe,i as Zt,f as Jt,n as es,a as ts,h as ss,j as ns,b as rs,c as is,l as os,e as as,o as cs,d as ls,k as us,g as ds,p as fs,m as ps}from"./emit-C0azW4mT.mjs";import{l as h,a as E,c as y,p as S,f as xt,i as gs,r as Et,e as ms}from"./discover-ast-D33zP-NZ.mjs";import hs from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as xs}from"./QUEUES_FILENAME-BnGLtAIu.mjs";import{discoverSandboxUsage as Es}from"./discoverSandboxUsage-L0lV17de.mjs";import vs from"./discoverStorageRulesMetadata-69Y8wZb2.mjs";import{discoverWorkflows as Ss}from"./WORKFLOWS_FILENAME-B8y51Frf.mjs";import{gatePlatformFeatures as As,resolveCodegenTarget as Ns}from"./DEFAULT_TARGET-CIH5PRk1.mjs";import{i as T,a as F,e as x,c as I,r as ys,b as bs,s as te,f as Is,g as Ps,d as ws}from"./discover-queries-Dfj_0WJG.mjs";import{classifyProcedureCall as _,inlineHandler as Ts,procedureHandler as vt,chainUsesWrappedCall as St,isDatabaseAccessor as K,chainHasStep as Cs,discoverFunctions as Rs,resolveStandardSchemaType as Os}from"./discoverFunctions-006teuNG.mjs";import Fs from"./discoverAuthApiCalls-DUjcl0SB.mjs";import Ls from"./discoverCrons-BUJO2ipU.mjs";import{discoverFlagKeys as Ds}from"./FLAGS_FILENAME-DtBWyUKq.mjs";import ks from"./discoverHttpRoutes-BxF4FRZL.mjs";import Ms from"./discoverInserts-YX8AmrzL.mjs";import Ks,{discoverMaskStrategies as _s,discoverMaskMetadata as zs,discoverMaskHasNonLiteralPolicy as Us}from"./discoverMaskProcedures-BCl3fNrQ.mjs";import Bs from"./discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as qs,isDefineMutatorCallee as $s,discoverMutators as js}from"./MUTATORS_FILENAME-B2-W8Bm3.mjs";import Vs from"./discoverNondeterministicCalls-BA91Z-vF.mjs";import{discoverNotifyConfig as Ws,discoverNotifyCalls as Hs}from"./NOTIFY_FILENAME-IJXY4yHt.mjs";import Gs from"./discoverR2sqlCalls-M2ob41UX.mjs";import Ys,{discoverRlsMetadata as Qs}from"./discoverRlsMetadata-Dwt2p8IK.mjs";import Xs from"./discoverSchema-gJ93Xjpx.mjs";import{secretKindOf as Zs,redact as Js,isHeuristicSecretKind as en,isSecretishName as tn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as sn}from"./SHAPES_FILENAME-DTp6VI6K.mjs";import{emitApp as nn}from"./emitApp-Dyr-onNf.mjs";import{buildOpenApiDocument as rn,emitOpenApiModule as on}from"./buildOpenApiDocument-DI8bgteQ.mjs";import{buildOpenRpcDocument as an,emitOpenRpcModule as cn}from"./OPENRPC_VERSION-14yZ-O3V.mjs";import{s as ln}from"./parse-validator-C5ycrhR3.mjs";import{buildSchemaSnapshot as un}from"./SchemaSnapshotParseError-BoHDfCO3.mjs";const dn=e=>{const t=[],s=e.tables.filter(n=>n.shardMode==="global");return s.some(n=>n.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(n=>n.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},fn=(e,t)=>{if(t===void 0)return;const s=dn(e).filter(o=>!t.has(o.name));if(s.length===0)return;const n=s.map(o=>` - ${o.name} — ${o.reason}`).join(`
|
|
2
2
|
`);throw new O("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
3
|
${n}
|
|
4
4
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const r=(e,i)=>{let t=i;for(let s=0;s<e.length;s+=1)t^=e.codePointAt(s)??0,t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},l=e=>`${r(e,2166136261)}${r(e,16777619)}`,g=1;function $(e){const i={},t=Object.keys(e);t.sort();for(const s of t)i[s]=e[s];return i}const c=e=>`${JSON.stringify(e,void 0,2)}
|
|
2
|
+
`,S=e=>l(c(e)),a=e=>typeof e=="object"&&e!==null,f=e=>a(e)&&a(e.fields)&&a(e.indexes)&&a(e.relations)&&typeof e.shardMode=="string",O=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let i;try{i=JSON.parse(e)}catch(s){return{error:`baseline is not valid JSON: ${s instanceof Error?s.message:String(s)}`,status:"invalid"}}if(!a(i)||i.version!==1||!a(i.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[s,o]of Object.entries(i.tables))if(!f(o))return{error:`baseline table "${s}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof i.jurisdiction=="string"?i.jurisdiction:void 0,migrationIds:Array.isArray(i.migrationIds)?i.migrationIds:[],tables:i.tables,version:1},status:"ok"}},p=(e,i)=>e.unique===i.unique&&e.fields.length===i.fields.length&&e.fields.every((t,s)=>t===i.fields[s]),y=(e,i,t,s)=>{const o=[];return t.kind!==s.kind&&o.push({severity:"breaking",summary:`field ${e}.${i} changed type: ${t.kind} → ${s.kind} — add a data migration to convert existing values`,table:e,scope:"table",type:"changedFieldKind"}),t.optional&&!s.optional?o.push({severity:"breaking",summary:`field ${e}.${i} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!t.optional&&s.optional&&o.push({scope:"table",severity:"safe",summary:`field ${e}.${i} became optional`,table:e,type:"fieldRequiredToOptional"}),o},u=(e,i,t)=>t.optional?{scope:"table",severity:"safe",summary:`added optional field ${e}.${i}`,table:e,type:"addedOptionalField"}:{severity:"breaking",summary:`added required field ${e}.${i} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},h=(e,i,t,s)=>{for(const[o,d]of Object.entries(t.fields)){const n=i.fields[o];n===void 0?s.push(u(e,o,d)):s.push(...y(e,o,n,d))}for(const o of Object.keys(i.fields))t.fields[o]===void 0&&s.push({severity:"breaking",summary:`removed field ${e}.${o} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},m=(e,i,t,s)=>{for(const[o,d]of Object.entries(t.indexes)){const n=i.indexes[o];if(n===void 0){s.push({scope:"table",severity:"safe",summary:`added index ${o} on ${e}`,table:e,type:"addedIndex"});continue}p(n,d)||s.push({severity:"breaking",summary:`index ${o} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const o of Object.keys(i.indexes))t.indexes[o]===void 0&&s.push({severity:"breaking",summary:`removed index ${o} on ${e} — a query that used \`.withIndex("${o}")\` would break`,table:e,scope:"table",type:"removedIndex"})},v=(e,i,t,s)=>{for(const o of Object.keys(t.relations))i.relations[o]===void 0&&s.push({scope:"schema",severity:"safe",summary:`added relation ${e}.${o}`,table:e,type:"addedRelation"});for(const o of Object.keys(i.relations))t.relations[o]===void 0&&s.push({scope:"schema",severity:"breaking",summary:`removed relation ${e}.${o}`,table:e,type:"removedRelation"})},b=(e,i,t,s)=>{i.shardMode!==t.shardMode&&s.push({severity:"breaking",summary:`table ${e} changed shard mode: ${i.shardMode} → ${t.shardMode} — its physical storage moves; add a data migration / re-shard plan`,table:e,scope:"table",type:"changedShardMode"}),h(e,i,t,s),m(e,i,t,s),v(e,i,t,s)},k=(e,i)=>{const t=[],s=e?.tables??{};for(const[o,d]of Object.entries(i.tables)){const n=s[o];if(n===void 0){t.push({scope:"table",severity:"safe",summary:`added table ${o}`,table:o,type:"addedTable"});continue}b(o,n,d,t)}for(const o of Object.keys(s))i.tables[o]===void 0&&t.push({scope:"table",severity:"breaking",summary:`removed table ${o} — add a data migration if its data must be archived/cleaned up`,table:o,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==i.jurisdiction){const o=e.jurisdiction??"(none)",d=i.jurisdiction??"(none)";t.push({scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${o} to ${d} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (no in-place migration; export then import to move it). Revert the change, or override the gate to proceed intentionally.`,type:"changedJurisdiction"})}return{changes:t}};export{g as SCHEMA_SNAPSHOT_VERSION,k as diffSchemaSnapshots,S as hashSchemaSnapshot,f as isValidTableSnapshot,O as parseSnapshotJson,c as serializeSchemaSnapshot,$ as sortKeys};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{modelSources as ce,toPascalCase as o,referencedModels as N,generatedHeaderLines as f,commentText as l,argsChoice as p,stringLiteral as $,kotlinLiteral as v,allMethods as P,toSnakeCase as B,parseSpec as ke,assertGeneratable as Oe,withDeclaredModels as Ne,unrepresentableFunctions as Ce,undeclaredModels as Le}from"./isTypedSchema-
|
|
1
|
+
import{modelSources as ce,toPascalCase as o,referencedModels as N,generatedHeaderLines as f,commentText as l,argsChoice as p,stringLiteral as $,kotlinLiteral as v,allMethods as P,toSnakeCase as B,parseSpec as ke,assertGeneratable as Oe,withDeclaredModels as Ne,unrepresentableFunctions as Ce,undeclaredModels as Le}from"./isTypedSchema-B_qlBbE-.mjs";import{isTypedSchema as br}from"./isTypedSchema-B_qlBbE-.mjs";const We=async(e,n)=>{if(n.quicktype===void 0)return"";const r=ce(e);if(r.length===0)return"";const{InputData:t,JSONSchemaInput:a,JSONSchemaStore:i,quicktype:s}=await import("quicktype-core");class u extends i{fetch(){return Promise.resolve(void 0)}}const m=new a(new u);for(const g of r)await m.addSource({name:g.name,schema:JSON.stringify(g.schema)});const d=new t;d.addInput(m);const{lines:c}=await s({inputData:d,lang:n.quicktype.lang,rendererOptions:n.quicktype.rendererOptions??{}});return c.join(`
|
|
2
2
|
`)},L=`${f("dart").map(e=>`// ${e}`).join(`
|
|
3
3
|
`)}
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as m,sortKeys as b,diffSchemaSnapshots as S,parseSnapshotJson as k}from"./SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as m,sortKeys as b,diffSchemaSnapshots as S,parseSnapshotJson as k}from"./SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs";import{serializeSchemaSnapshot as O}from"./SCHEMA_SNAPSHOT_VERSION-B0cTpK1D.mjs";const w=e=>e==="global"||e==="root"?e:`shardBy:${e.field}`,$=e=>e.kind==="optional"?{kind:e.inner?.kind??"unknown",optional:!0}:{kind:e.kind,optional:!1},v=e=>{const t={};for(const[n,o]of Object.entries(e.shape))t[n]=$(o);const a={};for(const n of e.indexes)a[n.name]={fields:[...n.fields],unique:n.unique??!1};const s={};for(const n of e.relations)s[n.name]={field:n.field,kind:n.kind,table:n.table};return{fields:t,indexes:a,relations:s,shardMode:w(e.shardMode)}},D=(e,t)=>{const a={};for(const n of e.tables)a[n.name]=v(n);const s=[...t].sort();return{jurisdiction:e.jurisdiction,migrationIds:s,tables:b(a),version:m}};class y extends g{constructor(t){super("SCHEMA_SNAPSHOT_PARSE",t,{name:"SchemaSnapshotParseError"})}}const L=e=>{const t=k(e);if(t.status==="invalid")throw new y(t.error);return t.status==="ok"?t.snapshot:void 0},E={deploy:{allowDrift:!0,updateBaseline:!0},prepare:{allowDrift:!0,updateBaseline:!0},verify:{allowDrift:!0,updateBaseline:!1}},f=" • For backward-compatible changes (e.g. adding an optional field): pass `--allow-schema-drift` to skip the block.",p=" • To accept the new shape without a migration (you know data is compatible): pass `--update-schema-baseline`.",I=e=>{const t=e===void 0?void 0:E[e];if(e===void 0||t===void 0)return`${f}
|
|
2
2
|
${p}
|
|
3
3
|
`;const a=t.updateBaseline?p:` • To accept the new shape without a migration, run \`lunora prepare --update-schema-baseline\` — \`lunora ${e}\` does not take that flag.`;return`${f}
|
|
4
4
|
${a}
|
package/dist/packem_shared/{buildOpenApiDocument-Dk1RRaq3.mjs → buildOpenApiDocument-DI8bgteQ.mjs}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as S}from"./emit-
|
|
1
|
+
import{G as S}from"./emit-C0azW4mT.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
|
|
2
2
|
`,U=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{I as buildOpenApiDocument,J as emitOpenApi,U as emitOpenApiModule};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as s,SyntaxKind as O}from"ts-morph";import{l as w,a as k}from"./discover-ast-D33zP-NZ.mjs";import{a as z}from"./module-specifiers-WF8iAydP.mjs";import{p as _,a as b}from"./parse-validator-C5ycrhR3.mjs";import{s as R}from"./paths-C-9fwEgQ.mjs";const y=new Set(["action","mutation","query","stream"]),P=/\bany\b(?!\s*(?:\?\s*)?:)/u,T=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,U=/^[A-Za-z_$][\w$]*$/u,j=e=>U.test(e)?e:JSON.stringify(e),N={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},$={onConnect:"connect",onDisconnect:"disconnect",onQueryChange:"reactor",onShardInit:"init"},V=z,h=e=>{const t=e.getSymbol();if(!t)return e.getText();const r=t.getDeclarations();for(const i of r){if(!s.isImportSpecifier(i))continue;const o=i.getImportDeclaration().getModuleSpecifierValue();return V(o)?i.getNameNode().getText():void 0}},S=(e,t=!1)=>{let r=e;for(;s.isCallExpression(r);){const n=r.getExpression();if(!s.isPropertyAccessExpression(n))return;r=n.getExpression()}if(!s.isIdentifier(r))return;const i=h(r);if(i===void 0){if(t)return;const n=r.getSymbol()?.getValueDeclaration();if(n&&s.isVariableDeclaration(n)){const o=n.getInitializer();return o?S(o,!0):void 0}return}return y.has(i)?"public":N[i]?"internal":void 0},m=(e,t)=>{const r=e.getProperty(t);if(r===void 0||!s.isPropertyAssignment(r))return;const i=r.getInitializer();return i!==void 0&&s.isStringLiteral(i)?i.getLiteralValue():void 0},E=(e,t)=>{const r=e.getProperty(t);if(r===void 0||!s.isPropertyAssignment(r))return;const i=r.getInitializer();return i!==void 0&&s.isNumericLiteral(i)?i.getLiteralValue():void 0},M=e=>{const t=e.getProperty("cache");if(t===void 0||!s.isPropertyAssignment(t))return;const r=t.getInitializer();if(r===void 0||!s.isObjectLiteralExpression(r))return;const i=m(r,"scope"),n=E(r,"maxAge"),o=E(r,"staleWhileRevalidate"),a=m(r,"tag"),c=m(r,"vary"),l={...n===void 0?{}:{maxAge:n},...i==="private"||i==="public"?{scope:i}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},B=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const t=M(e),r=e.getProperty("rest");return r!==void 0&&s.isPropertyAssignment(r)?{...t===void 0?{}:{cache:t},rest:r.getInitializer()?.getText()==="true"}:t===void 0?{}:{cache:t}},K=e=>{let t=e;for(;s.isCallExpression(t);){const r=t.getExpression();if(!s.isPropertyAccessExpression(r))return;if(r.getName()==="expose")return B(t.getArguments()[0]);t=r.getExpression()}},H=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return{};const r=t.getProperty("args");if(!r||!s.isPropertyAssignment(r))return{};const i=r.getInitializer();return!i||!s.isObjectLiteralExpression(i)?{}:b(i)},G="/_generated/",q=(e,t,r)=>{const i=t.getSourceFile(),n=(a,c)=>i.getImportDeclarations().some(l=>l.getModuleSpecifierSourceFile()!==a?!1:l.getNamespaceImport()!==void 0||l.getNamedImports().some(f=>f.getName()===c)),o=a=>{const c=a.getSourceFile();if(c.isInNodeModules()||c.isDeclarationFile()||!s.isInterfaceDeclaration(a)&&!s.isTypeAliasDeclaration(a))return!1;const l=c.getFilePath();return l.includes(G)?!1:l===r||n(c,a.getName())};return[e.getSymbol(),e.getAliasSymbol()].flatMap(a=>a?.getDeclarations()??[]).some(a=>o(a))},Q=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},I=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0,g=(e,t,r,i=new Set)=>i.has(e)?!1:(i.add(e),q(e,t,r)||Q(e).some(n=>g(n,t,r,i))?!0:I(e)?e.getProperties().some(n=>g(n.getTypeAtLocation(t),t,r,i)):!1),W=(e,t)=>{const r=e.getValueDeclaration()??e.getDeclarations()[0];return r&&(s.isPropertySignature(r)||s.isPropertyDeclaration(r))&&r.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(i=>i.isUndefined())},X=8,Y=(e,t,r,i,n,o)=>{const a=e.getArrayElementType(),c=a?o(a,t,r,i,n):void 0;if(c!==void 0)return a?.isUnion()?`(${c})[]`:`${c}[]`},J=(e,t,r,i,n,o)=>{const a=[];for(const c of e.getUnionTypes()){const l=o(c,t,r,i,n);if(l===void 0)return;a.push(l)}return a.join(" | ")},Z=(e,t,r,i,n,o)=>{if(!I(e))return;const a=[];for(const c of e.getProperties()){const l=c.getTypeAtLocation(t),f=W(c,l),L=f&&l.isUnion()?l.getUnionTypes().filter(d=>!d.isUndefined()):[l],v=[];for(const d of L){const x=o(d,t,r,i+1,n);if(x===void 0)return;v.push(x)}a.push(`${j(c.getName())}${f?"?":""}: ${v.join(" | ")}`)}return a.length>0?`{ ${a.join("; ")} }`:"{}"},p=(e,t,r,i,n)=>{if(i>X||n.has(e))return;if(!g(e,t,r))return e.getText(t);const o=new Set(n).add(e);return e.isArray()?Y(e,t,r,i,o,p):e.isUnion()?J(e,t,r,i,o,p):Z(e,t,r,i,o,p)},C=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let r=t.getReturnType();const n=(r.getSymbol()??r.getAliasSymbol())?.getName();if(n==="Promise"||n==="AsyncIterable"||n==="AsyncIterableIterator"||n==="AsyncGenerator"){const c=r.getTypeArguments()[0];c&&(r=c)}const o=r.getText(e);if(!o||o==="any"||o==="never"||P.test(o.replaceAll(T,"")))return"unknown";const a=e.getSourceFile().getFilePath();return g(r,e,a)?p(r,e,a,0,new Set)??"unknown":o},ve=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const r=t.getTypeAtLocation(e).getProperty("types");if(!r)return;const i=r.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!i)return;const n=i.getTypeAtLocation(e),o=n.getText(e);if(!o||o==="any"||o==="never"||P.test(o.replaceAll(T,"")))return;const a=e.getSourceFile().getFilePath();return g(n,e,a)?p(n,e,a,0,new Set):o},ee=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return"unknown";const r=t.getProperty("handler");if(!r||!s.isPropertyAssignment(r))return"unknown";const i=r.getInitializer();return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":C(i)},te=e=>{const t=e.getArguments()[0];return!t||!(s.isArrowFunction(t)||s.isFunctionExpression(t))?"unknown":C(t)},re=e=>{let t={},r=e;for(;s.isCallExpression(r);){const i=r.getExpression();if(!s.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const n=r.getArguments()[0];n&&s.isObjectLiteralExpression(n)&&(t={...b(n),...t})}r=i.getExpression()}return t},ie=e=>{let t=e;for(;s.isCallExpression(t);){const r=t.getExpression();if(!s.isPropertyAccessExpression(r))return;if(r.getName()==="output"){const i=t.getArguments()[0];return i&&s.isExpression(i)?_(i):void 0}t=r.getExpression()}},ne=e=>{const t=e.getExpression();if(s.isPropertyAccessExpression(t)){const o=t.getName();if(!y.has(o))return;const a=t.getExpression();if(a.getType().getProperty("__lunoraProcedure"))return{kind:o,receiver:a,visibility:a.getType().getProperty("__lunoraVisibility")?"internal":"public"};const c=S(a);return c?{kind:o,receiver:a,visibility:c}:void 0}if(!s.isIdentifier(t))return;const r=h(t);if(!r)return;if(y.has(r))return{kind:r,visibility:"public"};const i=N[r];if(i)return{kind:i,visibility:"internal"};const n=$[r];if(n)return{kind:"mutation",lifecycle:n,visibility:"internal"}},A=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,xe=e=>s.isPropertyAccessExpression(e)&&e.getName()==="db"||s.isIdentifier(e)&&e.getText()==="db",Ee=e=>{const t=e.getArguments()[0],r=A(t);if(r!==void 0)return r;if(t===void 0||!s.isObjectLiteralExpression(t))return;const i=t.getProperty("handler");return i!==void 0&&s.isPropertyAssignment(i)?A(i.getInitializer()):void 0},se=e=>s.isIdentifier(e)?e.getText():s.isPropertyAccessExpression(e)?e.getName():"",Ae=(e,t)=>{let r=e;for(;s.isCallExpression(r);){const i=r.getExpression();if(!s.isPropertyAccessExpression(i))break;if(i.getName()===t)return!0;r=i.getExpression()}return!1},be=(e,t,r)=>{let i=e;for(;s.isCallExpression(i);){const n=i.getExpression();if(!s.isPropertyAccessExpression(n))break;const o=i.getArguments()[0];if(n.getName()===t&&o!==void 0&&s.isCallExpression(o)&&se(o.getExpression())===r)return!0;i=n.getExpression()}return!1},oe=e=>{const t=ne(e);if(t){if(t.receiver){const r=K(t.receiver),i=ie(t.receiver);return{args:re(t.receiver),...r?{expose:r}:{},kind:t.kind,...i?{output:i}:{},returnType:te(e),visibility:t.visibility}}return t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",visibility:t.visibility}:{args:H(e),kind:t.kind,returnType:ee(e),visibility:t.visibility}}},ae=8,u=(e,t=0)=>{if(t>ae)return;if(s.isCallExpression(e))return e;if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return u(e.getExpression(),t+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const r=e.getSymbol()?.getValueDeclaration();return r?F(r,t+1):void 0},F=(e,t)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const r=e.getInitializer();return r?u(r,t):void 0}if(s.isShorthandPropertyAssignment(e))return u(e.getNameNode(),t);if(s.isBindingElement(e)){const r=e.getPropertyNameNode()?.getText()??e.getName(),o=e.getFirstAncestorByKind(O.VariableDeclaration)?.getInitializer()?.getType().getProperty(r)?.getValueDeclaration();return o?F(o,t+1):void 0}},ce=e=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const n=[];for(const o of t.getElements()){const a=u(o.getNameNode());a&&n.push([o.getName(),a])}return n}const r=e.getInitializer(),i=r&&(s.isCallExpression(r)?r:u(r));return i?[[e.getName(),i]]:[]},D=(e,t,r)=>{const i=oe(e);if(i)return{args:i.args,exportName:t,filePath:r,kind:i.kind,returnType:i.returnType,...i.output?{output:i.output}:{},visibility:i.visibility,...i.expose?{expose:i.expose}:{},...i.lifecycle?{lifecycle:i.lifecycle}:{}}},le=(e,t)=>{const r=[];for(const i of e.getExportAssignments()){if(i.isExportEquals())continue;const n=u(i.getExpression()),o=n?D(n,"default",t):void 0;o&&r.push(o)}return r},ue=(e,t)=>{const r=[];for(const i of e.getVariableStatements())if(i.isExported())for(const n of i.getDeclarations())for(const[o,a]of ce(n)){const c=D(a,o,t);c&&r.push(c)}return r.push(...le(e,t)),r},pe=e=>{const t=new Map;for(const r of e){const i=R(r.filePath),n=t.get(i);if(n&&n!==r.filePath)throw Object.assign(new Error(`Namespace collision: "${n}" and "${r.filePath}" both resolve to "${i}". 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:[n,r.filePath],status:500});t.set(i,r.filePath)}},Pe=(e,t)=>{const r=w(t),i=[];for(const n of r){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),a=k(t,n);i.push(...ue(o,a))}return i.sort((n,o)=>`${n.filePath}:${n.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),pe(i),i};export{Ae as chainHasStep,be as chainUsesWrappedCall,ne as classifyProcedureCall,Pe as discoverFunctions,A as inlineHandler,xe as isDatabaseAccessor,w as listLunoraSourceFiles,k as lunoraRelativePath,Ee as procedureHandler,ve as resolveStandardSchemaType,C as unwrapHandlerReturn};
|
package/dist/packem_shared/{discoverHttpRoutes-DOirwCWw.mjs → discoverHttpRoutes-BxF4FRZL.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as a}from"ts-morph";import{l,a as m}from"./discover-ast-D33zP-NZ.mjs";import{unwrapHandlerReturn as d}from"./discoverFunctions-
|
|
1
|
+
import{Node as a}from"ts-morph";import{l,a as m}from"./discover-ast-D33zP-NZ.mjs";import{unwrapHandlerReturn as d}from"./discoverFunctions-006teuNG.mjs";import{p as h,a as f}from"./parse-validator-C5ycrhR3.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&&a.isStringLiteral(e))return e.getLiteralValue()},x=r=>{const e=r.getArguments()[0];return e&&a.isObjectLiteralExpression(e)?f(e):{}},P=r=>{if(!a.isCallExpression(r))return;const e=r.getExpression();if(!a.isPropertyAccessExpression(e))return;const o=e.getName();if(!u.has(o))return;const n=e.getExpression();if(!a.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(!a.isPropertyAccessExpression(n))return;let s=n.getExpression();for(;a.isCallExpression(s);){const i=s.getExpression();if(!a.isPropertyAccessExpression(i))break;const c=i.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&&a.isExpression(p)&&(o.output=h(p))}s=i.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||!(a.isArrowFunction(e)||a.isFunctionExpression(e))?"unknown":d(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||!a.isCallExpression(t))continue;const i=t.getExpression();if(!a.isPropertyAccessExpression(i))continue;const c=T(t,i,s.getName(),e);c&&o.push(c)}return o},F=(r,e)=>{const o=l(e),n=[];for(const s of o){const t=r.getSourceFile(s)??r.addSourceFileAtPath(s),i=m(e,s);n.push(...b(t,i))}return n.sort((s,t)=>`${s.method} ${s.path}`.localeCompare(`${t.method} ${t.path}`)||s.filePath.localeCompare(t.filePath)),n};export{F as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as i}from"ts-morph";import{l as f,a as P,t as x}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as p}from"./discoverFunctions-
|
|
1
|
+
import{Node as i}from"ts-morph";import{l as f,a as P,t as x}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as p}from"./discoverFunctions-006teuNG.mjs";const A=e=>{if(!i.isCallExpression(e))return!1;const s=e.getExpression();return i.isIdentifier(s)?s.getText()==="mask":i.isPropertyAccessExpression(s)?s.getName()==="mask":!1},u=e=>{if(i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e))return e.getName()},k=e=>{const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const t=[];for(const r of s.getProperties()){const o=u(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=u(a);c!==void 0&&t.push({column:c,table:o})}}return t},g=e=>{const s=[];let t=e;for(;i.isCallExpression(t);){const r=t.getExpression();if(!i.isPropertyAccessExpression(r))break;if(r.getName()==="use"){const o=t.getArguments()[0];o&&A(o)&&s.push(o)}t=r.getExpression()}return s},E=e=>{const s=g(e);return{maskColumns:s.flatMap(t=>k(t)),usesMask:s.length>0}},M=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),S=new Set(["delete","insert","patch","replace"]),b=(e,s)=>{if(!i.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const r=p(t);if(!r)return;const o=r.receiver?E(r.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=x(e,M,S);return{exportName:e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:r.visibility}},w=(e,s)=>{const t=[];for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=P(s,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations()){const l=b(c,n);l&&t.push(l)}}return t},h=e=>{if(i.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&i.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},C=e=>{const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const t=[];for(const r of s.getProperties()){const o=u(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=u(a);c!==void 0&&t.push({column:c,strategy:h(a),table:o})}}return t},v=e=>{const s=[];for(const t of e.getVariableStatements())if(t.isExported())for(const r of t.getDeclarations()){const o=r.getInitializer(),n=o&&i.isCallExpression(o)?p(o):void 0;n?.receiver&&s.push(n.receiver)}return s},R=(e,s)=>{const t=new Map;for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const n of v(o))for(const a of g(n))for(const c of C(a)){const l=`${c.table}\0${c.column}`;t.has(l)||t.set(l,c)}}return{columns:[...t.values()]}},F=(e,s,t)=>{const r=e.getArguments()[0];if(!r||!i.isObjectLiteralExpression(r))return[];const o=[];for(const n of r.getProperties()){const a=u(n);if(a===void 0||!i.isPropertyAssignment(n))continue;const c=n.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const m=u(l);if(m===void 0)continue;const d=h(l);d!=="custom"&&o.push({column:m,exportName:s,file:t,line:l.getStartLineNumber(),strategy:d,table:a})}}return o},z=(e,s)=>{if(!i.isVariableDeclaration(e))return[];const t=e.getInitializer(),r=t&&i.isCallExpression(t)?p(t):void 0;return r?.receiver?g(r.receiver).flatMap(o=>F(o,e.getName(),s)):[]},T=(e,s)=>{const t=[];for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=P(s,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())t.push(...z(c,n))}return t},D=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,L=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?D(e):!0,y=(e,s=!1)=>{for(const t of e.getProperties()){if(L(t))return!0;if(s)continue;if(!i.isPropertyAssignment(t))return!0;const r=t.getInitializer();if(!r||!i.isObjectLiteralExpression(r)||y(r,!0))return!0}return!1},j=(e,s)=>{for(const t of f(s)){const r=e.getSourceFile(t)??e.addSourceFileAtPath(t);for(const o of v(r))for(const n of g(o)){const a=n.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||y(a)))return!0}}return!1};export{w as default,j as discoverMaskHasNonLiteralPolicy,R as discoverMaskMetadata,T as discoverMaskStrategies};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as s,SyntaxKind as a}from"ts-morph";import{l,a as c,h as d}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as f}from"./discoverFunctions-
|
|
1
|
+
import{Node as s,SyntaxKind as a}from"ts-morph";import{l,a as c,h as d}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as f}from"./discoverFunctions-006teuNG.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 l(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...S(o,c(t,i)))}return n};export{w as default};
|
package/dist/packem_shared/{discoverR2sqlCalls-B6e4j4rD.mjs → discoverR2sqlCalls-M2ob41UX.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as o,SyntaxKind as a}from"ts-morph";import{l as c,a as l,h as d}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as f}from"./discoverFunctions-
|
|
1
|
+
import{Node as o,SyntaxKind as a}from"ts-morph";import{l as c,a as l,h as d}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as f}from"./discoverFunctions-006teuNG.mjs";const u=t=>{const r=t.getInitializer();if(!r||!o.isCallExpression(r))return;const e=f(r);if(!e||e.kind!=="query"&&e.kind!=="mutation")return;const n=d(r,e.receiver);return n?{exportName:t.getName(),handler:n,kind:e.kind}:void 0},p=t=>{if(!o.isPropertyAccessExpression(t)||t.getName()!=="r2sql")return;const r=t.getExpression();if(!o.isIdentifier(r)||r.getText()!=="ctx")return;const e=t.getParent();return e&&o.isPropertyAccessExpression(e)&&e.getExpression()===t?`ctx.r2sql.${e.getName()}`:"ctx.r2sql"},x=(t,r)=>{const e=[];for(const n of t.handler.getDescendantsOfKind(a.PropertyAccessExpression)){const s=p(n);s!==void 0&&e.push({callee:s,exportName:t.exportName,file:r,kind:t.kind,line:n.getStartLineNumber()})}return e},m=(t,r)=>{const e=[];for(const n of t.getVariableStatements())if(n.isExported())for(const s of n.getDeclarations()){const i=u(s);i&&e.push(...x(i,r))}return e},P=(t,r)=>{const e=[];for(const n of c(r)){const s=t.getSourceFile(n)??t.addSourceFileAtPath(n);e.push(...m(s,l(r,n)))}return e};export{P as default};
|
package/dist/packem_shared/{discoverRlsMetadata-Pw0_c1aS.mjs → discoverRlsMetadata-Dwt2p8IK.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as n}from"ts-morph";import{l as d,a as x,t as P,b as l}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as E}from"./discoverFunctions-
|
|
1
|
+
import{Node as n}from"ts-morph";import{l as d,a as x,t as P,b as l}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as E}from"./discoverFunctions-006teuNG.mjs";const b=t=>{if(!n.isCallExpression(t))return!1;const e=t.getExpression();return n.isIdentifier(e)?e.getText()==="rls":n.isPropertyAccessExpression(e)?e.getName()==="rls":!1},v=t=>{const e=t.getArguments()[0];if(!e||!n.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements()){if(!n.isObjectLiteralExpression(r))continue;const i=r.getProperty("table");if(!i||!n.isPropertyAssignment(i))continue;const o=i.getInitializer();o&&n.isStringLiteral(o)&&s.push(o.getLiteralText())}return s},h=t=>{const e=[];let s=t;for(;n.isCallExpression(s);){const r=s.getExpression();if(!n.isPropertyAccessExpression(r))break;if(r.getName()==="use"){const i=s.getArguments()[0];i&&b(i)&&e.push(i)}s=r.getExpression()}return e},y=t=>{const e=h(t);return{rlsTables:e.flatMap(s=>v(s)),usesRls:e.length>0}},A=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),L=new Set(["delete","deleteMany","insert","insertMany","patch","patchMany","replace"]),S=(t,e)=>{if(!n.isVariableDeclaration(t))return;const s=t.getInitializer();if(!s||!n.isCallExpression(s))return;const r=E(s);if(!r)return;const i=r.receiver?y(r.receiver):{rlsTables:[],usesRls:!1},{tablesRead:o,tablesWritten:a}=P(t,A,L);return{exportName:t.getName(),file:e,rlsTables:i.rlsTables,tablesRead:o,tablesWritten:a,usesRls:i.usesRls,visibility:r.visibility}},w=(t,e)=>{const s=[];for(const r of d(e)){const i=t.getSourceFile(r)??t.addSourceFileAtPath(r),o=x(e,r);for(const a of i.getVariableStatements())if(a.isExported())for(const u of a.getDeclarations()){const c=S(u,o);c&&s.push(c)}}return s},C=new Set(["delete","insert","read","update"]),T=(t,e,s)=>{const r=t.getArguments()[0];if(!r||!n.isArrayLiteralExpression(r))return[];const i=[];for(const o of r.getElements()){if(!n.isObjectLiteralExpression(o))continue;const a=l(o,"on");a===void 0||!C.has(a)||i.push({file:e,on:a,procedure:s,table:l(o,"table")??""})}return i},g=t=>{if(!n.isObjectLiteralExpression(t))return[];const e=t.getProperty("permissions");if(!e||!n.isPropertyAssignment(e))return[];const s=e.getInitializer();if(!s||!n.isArrayLiteralExpression(s))return[];const r=[];for(const i of s.getElements()){if(n.isStringLiteral(i)){r.push(i.getLiteralText());continue}if(n.isCallExpression(i)){const o=i.getArguments()[0];o&&n.isStringLiteral(o)&&r.push(o.getLiteralText())}}return r},m=(t,e)=>e===void 0?t:{...t,description:e},R=t=>{if(n.isCallExpression(t)){const e=t.getArguments()[0];if(!e||!n.isStringLiteral(e))return;const s=t.getArguments()[1],r=s?l(s,"description"):void 0,i=s?g(s):[];return m({name:e.getLiteralText(),permissions:i},r)}if(n.isObjectLiteralExpression(t)){const e=l(t,"name");return e===void 0?void 0:m({name:e,permissions:g(t)},l(t,"description"))}},F=t=>{const e=t.getArguments()[1];if(!e||!n.isObjectLiteralExpression(e))return[];const s=e.getProperty("roles");if(!s||!n.isPropertyAssignment(s))return[];const r=s.getInitializer();if(!r||!n.isArrayLiteralExpression(r))return[];const i=[];for(const o of r.getElements()){const a=R(o);a&&i.push(a)}return i},I=(t,e,s)=>{const r=h(t);return{policies:r.flatMap(i=>T(i,e,s)),roles:r.flatMap(i=>F(i))}},M=t=>{const e=[];for(const s of t.getVariableStatements())if(s.isExported())for(const r of s.getDeclarations()){const i=r.getInitializer(),o=i&&n.isCallExpression(i)?E(i):void 0;o?.receiver&&e.push({name:r.getName(),receiver:o.receiver})}return e},D=(t,e)=>{const s=[],r=new Map;for(const i of d(e)){const o=t.getSourceFile(i)??t.addSourceFileAtPath(i),a=x(e,i);for(const{name:u,receiver:c}of M(o)){const p=I(c,a,u);s.push(...p.policies);for(const f of p.roles)r.has(f.name)||r.set(f.name,f)}}return{policies:s,roles:[...r.values()]}};export{w as default,D as discoverRlsMetadata};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as _}from"@lunora/errors";import{Node as i,SyntaxKind as j}from"ts-morph";import{diagnosticAt as f}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as $}from"./parse-validator-C5ycrhR3.mjs";import{createRequire as z}from"node:module";import{join as D}from"node:path";const C=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}},R=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}:{}}),p=e=>{const n=e?._meta??{},t=e?.kind??"unknown",s={column:R(n.column),kind:t};switch(t){case"array":case"optional":{s.inner=p(n.inner);break}case"from":break;case"id":{s.tableName=n.tableName;break}case"literal":{s.literalValue=C(n.value);break}case"object":{const r=n.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,p(a)]));break}case"record":{s.valueType=p(n.valueValidator),n.keyValidator!==void 0&&(s.keyType=p(n.keyValidator));break}case"storage":{typeof n.bucket=="string"&&(s.bucket=n.bucket);break}case"union":{const r=n.members??[];s.members=r.map(o=>p(o));break}}return s},M=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",F=(e,n)=>{const t=[];e.relationMap&&Object.keys(e.relationMap).length>0&&t.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&t.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&t.push("vector indexes"),t.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${n}" declares ${t.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},B=(e,n)=>{const t=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return F(e,n),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:n,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(t).map(([r,o])=>[r,p(o)])),shardMode:M(e.shardMode),vectorIndexes:[]}},V=e=>{const{key:n,tables:t}=e;if(typeof n!="string"||typeof t!="object"||t===null)return;const s=Object.entries(t).map(([a,l])=>B(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:n}},q=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n.getText():void 0}},J=e=>{const n=q(e);if(n===void 0)return;const t=i.isPropertyAccessExpression(e)?e.getName():void 0,s=t===void 0?[]:[t];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===n)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===n)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===n&&t!==void 0)return{importedName:t,moduleSpecifier:o,propertyPath:[]}}},U=(e,n)=>{let t=e[n.importedName];for(const s of n.propertyPath){if(typeof t!="object"||t===null)return;t=t[s]}return t},K=(e,n)=>{const t=J(e);if(t)try{const s=z(D(n,"noop.cjs")),r=s.resolve(t.moduleSpecifier),o=s(r),a=U(o,t);return typeof a!="object"||a===null?void 0:V(a)}catch{return}},G=new Set(["cosine","dot-product","euclidean"]),Z=new Set(["cascade","restrict","set null"]),I=new Set(["delete","get","insert","normalizeId","patch","query","replace","system"]),Q=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"]),W=/^[A-Za-z_$][\w$]*$/u,k=e=>e.replaceAll(/^["']|["']$/gu,""),w=(e,n)=>{const t=k(e);if(I.has(t))throw f(n,`table name "${t}" is reserved — it collides with a \`ctx.db\` member (one of ${[...I].map(s=>`"${s}"`).join(", ")}). Rename the table.`);if(Q.has(t))throw f(n,`table name "${t}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${t} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!W.test(t))throw f(n,`table name ${JSON.stringify(t)} 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.`)},g=(e,n)=>{const t=e.getProperty(n);if(t&&i.isPropertyAssignment(t))return t.getInitializer()},d=(e,n)=>{const t=g(e,n);if(t&&i.isStringLiteral(t))return t.getLiteralText()},m=(e,n)=>{const t=g(e,n);if(t&&i.isNumericLiteral(t))return Number(t.getLiteralText())},X=(e,n)=>{const t=g(e,n);if(t&&(i.isTrueLiteral(t)||i.isFalseLiteral(t)))return t.getLiteralValue()},x=(e,n)=>{const t=g(e,n);if(t&&i.isArrayLiteralExpression(t))return t.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},T=e=>e&&G.has(e)?e:void 0,H=e=>e&&Z.has(e)?e:void 0,Y=e=>{if(!i.isArrowFunction(e))return;let n=e.getBody();if(i.isParenthesizedExpression(n))n=n.getExpression();else if(i.isBlock(n)){const t=n.getStatements().find(s=>i.isReturnStatement(s));n=t&&i.isReturnStatement(t)?t.getExpression()??n:n}return i.isObjectLiteralExpression(n)?n:void 0},ee=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName();if(s!=="one"&&s!=="many")return;const[r,o]=n.getArguments();if(!r||!i.isStringLiteral(r))throw f(r??n,`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",u;return o&&i.isObjectLiteralExpression(o)&&(l=d(o,"field")??l,c=d(o,"references")??c,u=s==="one"?H(d(o,"onDelete")):void 0),{field:l,kind:s,name:e.getName(),onDelete:u,references:c,table:a}},te=e=>{const n=Y(e);if(!n)return[];const t=[];for(const s of n.getProperties()){const r=ee(s);r&&t.push(r)}return t},b=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",ne=(e,n,t)=>{if(!n.includes("."))return;const[s="",...r]=n.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw f(e,`index "${t}" indexes the nested path ${JSON.stringify(n)} — 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.`)},re=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const n=e.getProperty("unique");if(!n||!i.isPropertyAssignment(n))return!1;const t=n.getInitializer();if(t===void 0)return!1;if(!i.isTrueLiteral(t)&&!i.isFalseLiteral(t))throw f(t,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(t.getText())}`);return i.isTrueLiteral(t)},se=e=>{const[n,t,s]=e,r=re(s),o=b(n),a=t&&i.isArrayLiteralExpression(t)?t.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw f(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)ne(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},ie=e=>{const[n,t]=e;let s="_unknown_",r,o,a,l;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=x(t,"filterFields"),o=d(t,"language"),a=X(t,"staged"),l=d(t,"strategy")),{field:s,filterFields:r,language:o,name:b(n),staged:a,strategy:l}},oe=e=>{const[n,t]=e;let s="_unknown_",r;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=m(t,"precision")),{field:s,name:b(n),precision:r}},ae=e=>{const[n,t]=e,s=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";let r;return t&&i.isObjectLiteralExpression(t)&&(r=m(t,"after")),{after:r,field:s}},le=e=>{if(!i.isObjectLiteralExpression(e))return;const n=d(e,"field");return n===void 0?void 0:{direction:d(e,"direction")==="desc"?"desc":"asc",field:n}},ce=e=>{const[n,t]=e;let s=[],r;if(t&&i.isObjectLiteralExpression(t)){const o=t.getProperty("sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>le(l)).filter(l=>l!==void 0))}r=x(t,"partitionBy")}return{name:b(n),partitionBy:r,sortBy:s}},de=(e,n)=>{const[t,s]=e,r=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:m(s,"dimensions"),field:r,metadata:x(s,"metadata"),metric:T(d(s,"metric")),name:d(s,"index")??"_unnamed_",table:n}},fe=e=>{const n=e[0];return n&&i.isObjectLiteralExpression(n)&&d(n,"backend")==="hyperdrive"?"hyperdrive":"d1"},ue=e=>{if(e&&i.isObjectLiteralExpression(e)){const n=e.getProperty("field");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isStringLiteral(t))return t.getLiteralText()}}return"deletedAt"},pe=(e,n)=>{const t=x(e,n);return t!==void 0&&t.length>0?t:void 0},ge=e=>{const n=e[0];return!n||!i.isObjectLiteralExpression(n)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:d(n,"binding")??"",columns:pe(n,"columns"),hasReconcile:n.getProperty("reconcileEveryMs")!==void 0,hasSoftDelete:n.getProperty("softDeleteColumn")!==void 0,hasTenantBy:n.getProperty("tenantBy")!==void 0,idColumn:d(n,"idColumn"),mode:d(n,"mode"),query:d(n,"query")}},me=(e,n,t,s)=>{switch(n){case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(oe(t));break}case"global":{e.shardMode="global",e.globalBackend=fe(t);break}case"index":{e.indexes.push(se(t));break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(ce(t));break}case"relations":{const r=t[0];r&&e.relations.push(...te(r));break}case"searchIndex":{e.searchIndexes.push(ie(t));break}case"shardBy":{const r=t[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:ue(t[0])};break}case"source":{e.externalSource=ge(t),e.externallyManaged=!0;break}case"ttl":{e.ttl=ae(t);break}case"vectorize":{const r=de(t,s);r&&e.vectorIndexes.push(r);break}}},S=["__vocab","_config","_content","_data","_docsize","_idx"],xe=(e,n,t)=>{const s=new Set(t.map(r=>r.name));for(const r of t)for(const o of S){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 f(e,`table "${n}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${n}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${S.join(", ")}.`)}},L=(e,n)=>{const t={externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!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))me(t,o.getName(),a,n),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=$(l);else if(l)throw f(l,`table "${n}" 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_${n}\` / \`Insert_${n}\` type instead of sharing the runtime value.`);break}else break}return t.softDelete&&!(t.softDelete.field in s)&&(s={...s,[t.softDelete.field]:{inner:{kind:"number"},kind:"optional"}}),xe(e,n,t.searchIndexes),{externallyManaged:t.externallyManaged,externalSource:t.externalSource,geoIndexes:t.geoIndexes,globalBackend:t.shardMode==="global"?t.globalBackend??"d1":void 0,indexes:t.indexes,isPublic:t.isPublic,name:n,rankIndexes:t.rankIndexes,relations:t.relations,searchIndexes:t.searchIndexes,shape:s,shardMode:t.shardMode,softDelete:t.softDelete,ttl:t.ttl,vectorIndexes:t.vectorIndexes}},be=e=>{const n=e.getProperty("source");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isObjectLiteralExpression(t))return d(t,"table")??"_unknown_"}return"_unknown_"},he=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isIdentifier(t)||t.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:m(s,"dimensions"),metric:T(d(s,"metric")),name:o,table:be(s)}},P=e=>{const n=[];for(const t of e.getProperties()){const s=he(t);s&&n.push(s)}return n},v=(e,n)=>`${e}_${n}`,y=(e,n,t)=>t.has(e)?v(n,e):e,ye=(e,n,t)=>{const s=v(n,e.name);return{...e,extensionKey:n,name:s,relations:e.relations.map(r=>({...r,table:y(r.table,n,t)})),vectorIndexes:e.vectorIndexes.map(r=>({...r,table:y(r.table,n,t)}))}},ve=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Ee=e=>{if(!i.isCallExpression(e))return!1;const n=e.getExpression();return i.isIdentifier(n)&&n.getText()==="defineSchemaExtension"},Ie=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n:void 0}},Se=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const n=e.getExpression();let t;if(i.isIdentifier(n)?t=n.getText():i.isPropertyAccessExpression(n)&&(t=n.getName()),t==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},ke=(e,n)=>{const t=ve(e);if(t){if(i.isPropertyAccessExpression(n)){const s=Se(t);return s?g(s,n.getName()):void 0}return t}},we=e=>{let n=e,t=0;for(;n&&t<32;){if(t+=1,Ee(n))return n;const s=Ie(n),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;n=ke(a,n)}},Te=e=>{const[n,t]=e.getArguments();if(!(!n||!i.isStringLiteral(n))&&!(!t||!i.isObjectLiteralExpression(t)))return{key:n.getLiteralText(),options:t}},Le=e=>{const n=e.getProperty("tables");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const r of t.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=r.getName();w(a,r.getNameNode()),s.push(L(o,a))}return s},Pe=e=>{const n=e.getProperty("vectorIndexes");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();return!t||!i.isObjectLiteralExpression(t)?[]:P(t)},N=(e,n,t)=>{const s=new Set(n.map(a=>a.name)),r=n.map(a=>ye(a,e,s)),o=t.map(a=>({...a,name:v(e,a.name),table:y(a.table,e,s)}));return{tables:r,vectorIndexes:o}},Ne=(e,n)=>N(e,Le(n),Pe(n)),Oe=(e,n)=>{const t=e.getArguments()[0];if(!t)return;const s=we(t);if(!s){if(n!==void 0){const o=K(t,n);if(o)return N(o.key,o.bareTables,o.bareVectorIndexes)}console.warn(`@lunora/codegen: skipping \`.extend(${t.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${n===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=Te(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Ne(r.key,r.options)},Ae=e=>{const n=[];let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&n.push(r),t=r}return n},O=(e,n,t,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()===n){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw f(l,`\`.${n}(...)\` expects a string literal (${r})`);const u=c.getLiteralText();if(!s.has(u))throw f(c,`unknown ${t} ${JSON.stringify(u)} — expected ${r}`);return u}o=l}},_e=new Set(["eu","fedramp","us"]),je=e=>O(e,"jurisdiction","jurisdiction",_e,'"eu", "us", or "fedramp"'),$e=new Set(["required"]),ze=e=>O(e,"rls","rls mode",$e,'"required"'),De=e=>{const n=[],t=new Set;for(const s of e.getProperties()){if(!i.isPropertyAssignment(s))continue;const r=s.getInitializer();if(r){const o=s.getName();w(o,s.getNameNode());const a=k(o);if(t.has(a))throw f(s.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);t.add(a),n.push(L(r,o))}}return n},Ce=(e,n,t)=>{const s=new Set(n.map(o=>o.name)),r=[];for(const o of Ae(e)){const a=Oe(o,t);if(a){for(const l of a.tables){if(s.has(l.name))throw f(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),n.push(l)}r.push(...a.vectorIndexes)}}return r},Je=(e,n,t)=>{const r=e.addSourceFileAtPath(n).getDescendantsOfKind(j.CallExpression).find(h=>{const E=h.getExpression();return i.isIdentifier(E)&&E.getText()==="defineSchema"});if(!r)throw new _("INTERNAL",`defineSchema() not found in ${n}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw f(r,"defineSchema() expects an object literal");const a=De(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?P(l):[],u=Ce(r,a,t),A=[...a.flatMap(h=>h.vectorIndexes),...c,...u];return{jurisdiction:je(r),rlsMode:ze(r),tables:a,vectorIndexes:A}};export{Je as default};
|
|
1
|
+
import{LunoraError as _}from"@lunora/errors";import{Node as i,SyntaxKind as j}from"ts-morph";import{diagnosticAt as f}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as $}from"./parse-validator-C5ycrhR3.mjs";import{createRequire as z}from"node:module";import{join as D}from"node:path";const C=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}},R=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}:{}}),p=e=>{const n=e?._meta??{},t=e?.kind??"unknown",s={column:R(n.column),kind:t};switch(t){case"array":case"optional":{s.inner=p(n.inner);break}case"from":break;case"id":{s.tableName=n.tableName;break}case"literal":{s.literalValue=C(n.value);break}case"object":{const r=n.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,p(a)]));break}case"record":{s.valueType=p(n.valueValidator),n.keyValidator!==void 0&&(s.keyType=p(n.keyValidator));break}case"storage":{typeof n.bucket=="string"&&(s.bucket=n.bucket);break}case"union":{const r=n.members??[];s.members=r.map(o=>p(o));break}}return s},M=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",F=(e,n)=>{const t=[];e.relationMap&&Object.keys(e.relationMap).length>0&&t.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&t.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&t.push("vector indexes"),t.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${n}" declares ${t.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},B=(e,n)=>{const t=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return F(e,n),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:n,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(t).map(([r,o])=>[r,p(o)])),shardMode:M(e.shardMode),vectorIndexes:[]}},V=e=>{const{key:n,tables:t}=e;if(typeof n!="string"||typeof t!="object"||t===null)return;const s=Object.entries(t).map(([a,l])=>B(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:n}},q=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n.getText():void 0}},J=e=>{const n=q(e);if(n===void 0)return;const t=i.isPropertyAccessExpression(e)?e.getName():void 0,s=t===void 0?[]:[t];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===n)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===n)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===n&&t!==void 0)return{importedName:t,moduleSpecifier:o,propertyPath:[]}}},U=(e,n)=>{let t=e[n.importedName];for(const s of n.propertyPath){if(typeof t!="object"||t===null)return;t=t[s]}return t},K=(e,n)=>{const t=J(e);if(t)try{const s=z(D(n,"noop.cjs")),r=s.resolve(t.moduleSpecifier),o=s(r),a=U(o,t);return typeof a!="object"||a===null?void 0:V(a)}catch{return}},G=new Set(["cosine","dot-product","euclidean"]),Z=new Set(["cascade","restrict","set null"]),I=new Set(["delete","get","insert","normalizeId","patch","query","replace","system"]),Q=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"]),W=/^[A-Za-z_$][\w$]*$/u,k=e=>e.replaceAll(/^["']|["']$/gu,""),w=(e,n)=>{const t=k(e);if(I.has(t))throw f(n,`table name "${t}" is reserved — it collides with a \`ctx.db\` member (one of ${[...I].map(s=>`"${s}"`).join(", ")}). Rename the table.`);if(Q.has(t))throw f(n,`table name "${t}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${t} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!W.test(t))throw f(n,`table name ${JSON.stringify(t)} 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.`)},g=(e,n)=>{const t=e.getProperty(n);if(t&&i.isPropertyAssignment(t))return t.getInitializer()},d=(e,n)=>{const t=g(e,n);if(t&&i.isStringLiteral(t))return t.getLiteralText()},m=(e,n)=>{const t=g(e,n);if(t&&i.isNumericLiteral(t))return Number(t.getLiteralText())},X=(e,n)=>{const t=g(e,n);if(t&&(i.isTrueLiteral(t)||i.isFalseLiteral(t)))return t.getLiteralValue()},x=(e,n)=>{const t=g(e,n);if(t&&i.isArrayLiteralExpression(t))return t.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},T=e=>e&&G.has(e)?e:void 0,H=e=>e&&Z.has(e)?e:void 0,Y=e=>{if(!i.isArrowFunction(e))return;let n=e.getBody();if(i.isParenthesizedExpression(n))n=n.getExpression();else if(i.isBlock(n)){const t=n.getStatements().find(s=>i.isReturnStatement(s));n=t&&i.isReturnStatement(t)?t.getExpression()??n:n}return i.isObjectLiteralExpression(n)?n:void 0},ee=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName();if(s!=="one"&&s!=="many")return;const[r,o]=n.getArguments();if(!r||!i.isStringLiteral(r))throw f(r??n,`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",u;return o&&i.isObjectLiteralExpression(o)&&(l=d(o,"field")??l,c=d(o,"references")??c,u=s==="one"?H(d(o,"onDelete")):void 0),{field:l,kind:s,name:e.getName(),onDelete:u,references:c,table:a}},te=e=>{const n=Y(e);if(!n)return[];const t=[];for(const s of n.getProperties()){const r=ee(s);r&&t.push(r)}return t},b=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",ne=(e,n,t)=>{if(!n.includes("."))return;const[s="",...r]=n.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw f(e,`index "${t}" indexes the nested path ${JSON.stringify(n)} — 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.`)},re=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const n=e.getProperty("unique");if(!n||!i.isPropertyAssignment(n))return!1;const t=n.getInitializer();if(t===void 0)return!1;if(!i.isTrueLiteral(t)&&!i.isFalseLiteral(t))throw f(t,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(t.getText())}`);return i.isTrueLiteral(t)},se=e=>{const[n,t,s]=e,r=re(s),o=b(n),a=t&&i.isArrayLiteralExpression(t)?t.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw f(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)ne(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},ie=e=>{const[n,t]=e;let s="_unknown_",r,o,a,l;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=x(t,"filterFields"),o=d(t,"language"),a=X(t,"staged"),l=d(t,"strategy")),{field:s,filterFields:r,language:o,name:b(n),staged:a,strategy:l}},oe=e=>{const[n,t]=e;let s="_unknown_",r;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=m(t,"precision")),{field:s,name:b(n),precision:r}},ae=e=>{const[n,t]=e,s=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";let r;return t&&i.isObjectLiteralExpression(t)&&(r=m(t,"after")),{after:r,field:s}},le=e=>{if(!i.isObjectLiteralExpression(e))return;const n=d(e,"field");return n===void 0?void 0:{direction:d(e,"direction")==="desc"?"desc":"asc",field:n}},ce=e=>{const[n,t]=e;let s=[],r;if(t&&i.isObjectLiteralExpression(t)){const o=t.getProperty("sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>le(l)).filter(l=>l!==void 0))}r=x(t,"partitionBy")}return{name:b(n),partitionBy:r,sortBy:s}},de=(e,n)=>{const[t,s]=e,r=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:m(s,"dimensions"),field:r,metadata:x(s,"metadata"),metric:T(d(s,"metric")),name:d(s,"index")??"_unnamed_",table:n}},fe=e=>{const n=e[0];return n&&i.isObjectLiteralExpression(n)&&d(n,"backend")==="hyperdrive"?"hyperdrive":"d1"},ue=e=>{if(e&&i.isObjectLiteralExpression(e)){const n=e.getProperty("field");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isStringLiteral(t))return t.getLiteralText()}}return"deletedAt"},pe=(e,n)=>{const t=x(e,n);return t!==void 0&&t.length>0?t:void 0},ge=e=>{const n=e[0];return!n||!i.isObjectLiteralExpression(n)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:d(n,"binding")??"",columns:pe(n,"columns"),hasReconcile:n.getProperty("reconcileEveryMs")!==void 0,hasSoftDelete:n.getProperty("softDeleteColumn")!==void 0,hasTenantBy:n.getProperty("tenantBy")!==void 0,idColumn:d(n,"idColumn"),mode:d(n,"mode"),query:d(n,"query")}},me=(e,n,t,s)=>{switch(n){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(oe(t));break}case"global":{e.shardMode="global",e.globalBackend=fe(t);break}case"index":{e.indexes.push(se(t));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(ce(t));break}case"relations":{const r=t[0];r&&e.relations.push(...te(r));break}case"searchIndex":{e.searchIndexes.push(ie(t));break}case"shardBy":{const r=t[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:ue(t[0])};break}case"source":{e.externalSource=ge(t),e.externallyManaged=!0;break}case"ttl":{e.ttl=ae(t);break}case"vectorize":{const r=de(t,s);r&&e.vectorIndexes.push(r);break}}},S=["__vocab","_config","_content","_data","_docsize","_idx"],xe=(e,n,t)=>{const s=new Set(t.map(r=>r.name));for(const r of t)for(const o of S){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 f(e,`table "${n}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${n}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${S.join(", ")}.`)}},L=(e,n)=>{const t={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))me(t,o.getName(),a,n),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=$(l);else if(l)throw f(l,`table "${n}" 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_${n}\` / \`Insert_${n}\` type instead of sharing the runtime value.`);break}else break}return t.softDelete&&!(t.softDelete.field in s)&&(s={...s,[t.softDelete.field]:{inner:{kind:"number"},kind:"optional"}}),xe(e,n,t.searchIndexes),{commitOrdered:t.commitOrdered,externallyManaged:t.externallyManaged,externalSource:t.externalSource,geoIndexes:t.geoIndexes,globalBackend:t.shardMode==="global"?t.globalBackend??"d1":void 0,indexes:t.indexes,isPublic:t.isPublic,memory:t.memory,name:n,rankIndexes:t.rankIndexes,relations:t.relations,searchIndexes:t.searchIndexes,shape:s,shardMode:t.shardMode,softDelete:t.softDelete,ttl:t.ttl,vectorIndexes:t.vectorIndexes}},be=e=>{const n=e.getProperty("source");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isObjectLiteralExpression(t))return d(t,"table")??"_unknown_"}return"_unknown_"},he=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isIdentifier(t)||t.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:m(s,"dimensions"),metric:T(d(s,"metric")),name:o,table:be(s)}},O=e=>{const n=[];for(const t of e.getProperties()){const s=he(t);s&&n.push(s)}return n},v=(e,n)=>`${e}_${n}`,y=(e,n,t)=>t.has(e)?v(n,e):e,ye=(e,n,t)=>{const s=v(n,e.name);return{...e,extensionKey:n,name:s,relations:e.relations.map(r=>({...r,table:y(r.table,n,t)})),vectorIndexes:e.vectorIndexes.map(r=>({...r,table:y(r.table,n,t)}))}},ve=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Ee=e=>{if(!i.isCallExpression(e))return!1;const n=e.getExpression();return i.isIdentifier(n)&&n.getText()==="defineSchemaExtension"},Ie=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n:void 0}},Se=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const n=e.getExpression();let t;if(i.isIdentifier(n)?t=n.getText():i.isPropertyAccessExpression(n)&&(t=n.getName()),t==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},ke=(e,n)=>{const t=ve(e);if(t){if(i.isPropertyAccessExpression(n)){const s=Se(t);return s?g(s,n.getName()):void 0}return t}},we=e=>{let n=e,t=0;for(;n&&t<32;){if(t+=1,Ee(n))return n;const s=Ie(n),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;n=ke(a,n)}},Te=e=>{const[n,t]=e.getArguments();if(!(!n||!i.isStringLiteral(n))&&!(!t||!i.isObjectLiteralExpression(t)))return{key:n.getLiteralText(),options:t}},Le=e=>{const n=e.getProperty("tables");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const r of t.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=r.getName();w(a,r.getNameNode()),s.push(L(o,a))}return s},Oe=e=>{const n=e.getProperty("vectorIndexes");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();return!t||!i.isObjectLiteralExpression(t)?[]:O(t)},P=(e,n,t)=>{const s=new Set(n.map(a=>a.name)),r=n.map(a=>ye(a,e,s)),o=t.map(a=>({...a,name:v(e,a.name),table:y(a.table,e,s)}));return{tables:r,vectorIndexes:o}},Pe=(e,n)=>P(e,Le(n),Oe(n)),Ne=(e,n)=>{const t=e.getArguments()[0];if(!t)return;const s=we(t);if(!s){if(n!==void 0){const o=K(t,n);if(o)return P(o.key,o.bareTables,o.bareVectorIndexes)}console.warn(`@lunora/codegen: skipping \`.extend(${t.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${n===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=Te(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Pe(r.key,r.options)},Ae=e=>{const n=[];let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&n.push(r),t=r}return n},N=(e,n,t,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()===n){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw f(l,`\`.${n}(...)\` expects a string literal (${r})`);const u=c.getLiteralText();if(!s.has(u))throw f(c,`unknown ${t} ${JSON.stringify(u)} — expected ${r}`);return u}o=l}},_e=new Set(["eu","fedramp","us"]),je=e=>N(e,"jurisdiction","jurisdiction",_e,'"eu", "us", or "fedramp"'),$e=new Set(["required"]),ze=e=>N(e,"rls","rls mode",$e,'"required"'),De=e=>{const n=[],t=new Set;for(const s of e.getProperties()){if(!i.isPropertyAssignment(s))continue;const r=s.getInitializer();if(r){const o=s.getName();w(o,s.getNameNode());const a=k(o);if(t.has(a))throw f(s.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);t.add(a),n.push(L(r,o))}}return n},Ce=(e,n,t)=>{const s=new Set(n.map(o=>o.name)),r=[];for(const o of Ae(e)){const a=Ne(o,t);if(a){for(const l of a.tables){if(s.has(l.name))throw f(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),n.push(l)}r.push(...a.vectorIndexes)}}return r},Je=(e,n,t)=>{const r=e.addSourceFileAtPath(n).getDescendantsOfKind(j.CallExpression).find(h=>{const E=h.getExpression();return i.isIdentifier(E)&&E.getText()==="defineSchema"});if(!r)throw new _("INTERNAL",`defineSchema() not found in ${n}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw f(r,"defineSchema() expects an object literal");const a=De(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?O(l):[],u=Ce(r,a,t),A=[...a.flatMap(h=>h.vectorIndexes),...c,...u];return{jurisdiction:je(r),rlsMode:ze(r),tables:a,vectorIndexes:A}};export{Je as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as n}from"ts-morph";import{l as f,a as p,b as u}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as g}from"./discoverFunctions-
|
|
1
|
+
import{Node as n}from"ts-morph";import{l as f,a as p,b as u}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as g}from"./discoverFunctions-006teuNG.mjs";const m=new Set(["delete","list","read","write"]),d=o=>{if(!n.isCallExpression(o))return!1;const e=o.getExpression();return n.isIdentifier(e)?e.getText()==="storageRules":n.isPropertyAccessExpression(e)&&e.getName()==="storageRules"},x=o=>{const e=[];let s=o;for(;n.isCallExpression(s);){const t=s.getExpression();if(!n.isPropertyAccessExpression(t))break;if(t.getName()==="use"){const r=s.getArguments()[0];r&&d(r)&&e.push(r)}s=t.getExpression()}return e},h=(o,e,s)=>{const t=o.getArguments()[0];if(!t||!n.isArrayLiteralExpression(t))return[];const r=[];for(const i of t.getElements()){if(!n.isObjectLiteralExpression(i))continue;const a=u(i,"on");if(a===void 0||!m.has(a))continue;const c=u(i,"prefix"),l={bucket:u(i,"bucket")??"",file:e,on:a,procedure:s};c!==void 0&&(l.prefix=c),r.push(l)}return r},E=o=>{const e=[];for(const s of o.getVariableStatements())if(s.isExported())for(const t of s.getDeclarations()){const r=t.getInitializer(),i=r&&n.isCallExpression(r)?g(r):void 0;i?.receiver&&e.push({name:t.getName(),receiver:i.receiver})}return e},R=(o,e)=>{const s=[];for(const t of f(e)){const r=o.getSourceFile(t)??o.addSourceFileAtPath(t),i=p(e,t);for(const{name:a,receiver:c}of E(r))for(const l of x(c))s.push(...h(l,i,a))}return{rules:s}};export{R as default};
|