@lunora/codegen 1.0.0-alpha.110 → 1.0.0-alpha.112
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 +59 -2
- package/dist/index.d.ts +59 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-D9rvsQ0t.mjs → SCHEMA_SNAPSHOT_FILENAME-BYsNQnIS.mjs} +1 -1
- package/dist/packem_shared/SDK_LANGUAGES-DcXlLVZ1.mjs +371 -0
- package/dist/packem_shared/{emitApp-hKEej7rj.mjs → emitApp-DZlIvflD.mjs} +3 -3
- package/dist/packem_shared/isTypedSchema-BBIBMZTg.mjs +2 -0
- package/package.json +6 -6
- package/dist/packem_shared/SDK_LANGUAGES-p7vq4x7B.mjs +0 -320
- package/dist/packem_shared/isTypedSchema-CU-O5qSH.mjs +0 -2
package/dist/index.d.mts
CHANGED
|
@@ -3420,6 +3420,17 @@ interface OpenRpcDocument {
|
|
|
3420
3420
|
type RuntimeVerb = "action" | "mutation" | "query";
|
|
3421
3421
|
/** One RPC function, parsed and language-neutral. */
|
|
3422
3422
|
interface SdkMethod {
|
|
3423
|
+
/**
|
|
3424
|
+
* Where this function's ARGUMENT nulls mean "unset" and where they mean
|
|
3425
|
+
* "null" — see {@link ModelNullPaths}.
|
|
3426
|
+
*
|
|
3427
|
+
* On the method rather than on a shared render input because it is a
|
|
3428
|
+
* per-method fact and the parser already holds the schema it comes from. Read
|
|
3429
|
+
* by the three targets whose rendered models cannot tell the two apart
|
|
3430
|
+
* (ruby, rust, swift); the other five have a marker of their own and ignore
|
|
3431
|
+
* it.
|
|
3432
|
+
*/
|
|
3433
|
+
argsNullPaths: ModelNullPaths;
|
|
3423
3434
|
/**
|
|
3424
3435
|
* Generated args model name, or `undefined` when NO model could be named for
|
|
3425
3436
|
* this function's arguments.
|
|
@@ -3469,6 +3480,52 @@ interface SdkNamespace {
|
|
|
3469
3480
|
* discarding the real payload rather than leaving it untyped.
|
|
3470
3481
|
*/
|
|
3471
3482
|
declare const isTypedSchema: (schema: Record<string, unknown> | undefined) => boolean;
|
|
3483
|
+
/**
|
|
3484
|
+
* A path from a model's root to one property. `*` stands for every element of an
|
|
3485
|
+
* array or every value of a record, neither of which has named positions.
|
|
3486
|
+
*/
|
|
3487
|
+
type SchemaPath = ReadonlyArray<string>;
|
|
3488
|
+
/**
|
|
3489
|
+
* Where a model's nulls mean different things — the one fact a generated model
|
|
3490
|
+
* flattens away, and the reason three ports could not send a `v.nullable()`
|
|
3491
|
+
* argument at all.
|
|
3492
|
+
*
|
|
3493
|
+
* An unset `v.optional()` and a `v.nullable()` set to null are the SAME value in
|
|
3494
|
+
* every generated model (a nil field), and opposite things on the wire: the
|
|
3495
|
+
* validator rejects an explicit null for the first and requires the key present
|
|
3496
|
+
* for the second. Neither Ruby, Rust nor Swift renders a marker telling them
|
|
3497
|
+
* apart, so the distinction is computed here, from the schema, where `required`
|
|
3498
|
+
* still exists — and handed to the targets that need it.
|
|
3499
|
+
*
|
|
3500
|
+
* Two lists rather than one because the ports need opposite operations. Ruby and
|
|
3501
|
+
* Rust project a whole value tree and prune nulls, so they prune at
|
|
3502
|
+
* {@link ModelNullPaths.optional} and nowhere else — which also stops them
|
|
3503
|
+
* dropping a legitimate null inside a record or an array, as a blanket prune
|
|
3504
|
+
* does. Swift's `JSONEncoder` has already dropped every struct-property nil
|
|
3505
|
+
* before the transport sees a tree, so it restores nulls at
|
|
3506
|
+
* {@link ModelNullPaths.nullable} instead: an absent key at a required path can
|
|
3507
|
+
* only have been a nil, so putting the null back is exact.
|
|
3508
|
+
*
|
|
3509
|
+
* A `$ref` is NOT resolved. `openrpc.ts` inlines everything it emits, so this
|
|
3510
|
+
* never comes up for a generated document — but `--spec` accepts a hand-written
|
|
3511
|
+
* one, and there a `$ref`'d sub-object contributes no paths at all: the ports
|
|
3512
|
+
* that prune would send its unset optionals as null, and Swift would not restore
|
|
3513
|
+
* its nullables. Inline the schema, or teach this to follow the pointer.
|
|
3514
|
+
*
|
|
3515
|
+
* Both lists name PROPERTIES only. A record's values and an array's elements can
|
|
3516
|
+
* be null too, but no port drops one: the pruning ports prune at `optional`
|
|
3517
|
+
* paths, which a `*` position can never be, and `JSONEncoder` drops a nil only
|
|
3518
|
+
* from a struct property — a nil inside a dictionary or array encodes as null.
|
|
3519
|
+
* Listing a `*` leaf would also make Swift's restore INVENT record keys that
|
|
3520
|
+
* were never there, which is why the walk records the path it descends through
|
|
3521
|
+
* but never the `*` position itself.
|
|
3522
|
+
*/
|
|
3523
|
+
interface ModelNullPaths {
|
|
3524
|
+
/** Required properties that permit null — a null there is a VALUE and must survive. */
|
|
3525
|
+
nullable: ReadonlyArray<SchemaPath>;
|
|
3526
|
+
/** Properties absent from their object's `required` — a null there means UNSET. */
|
|
3527
|
+
optional: ReadonlyArray<SchemaPath>;
|
|
3528
|
+
}
|
|
3472
3529
|
/** What a target renders from. */
|
|
3473
3530
|
interface SdkRenderInput {
|
|
3474
3531
|
/**
|
|
@@ -3550,8 +3607,8 @@ interface SdkTarget {
|
|
|
3550
3607
|
renderModels?: (document: OpenRpcDocument) => Record<string, string>;
|
|
3551
3608
|
/**
|
|
3552
3609
|
* THIRD-PARTY packages a consuming project must still install, reported by
|
|
3553
|
-
* the CLI. Empty for
|
|
3554
|
-
*
|
|
3610
|
+
* the CLI. Empty for six of the eight — the transport is vendored and those
|
|
3611
|
+
* six reach the wire with only their standard library.
|
|
3555
3612
|
*
|
|
3556
3613
|
* A list, and not derivable from the transport, because a target's MODELS can
|
|
3557
3614
|
* carry a dependency the transport does not: quicktype's Ruby backend emits
|
package/dist/index.d.ts
CHANGED
|
@@ -3420,6 +3420,17 @@ interface OpenRpcDocument {
|
|
|
3420
3420
|
type RuntimeVerb = "action" | "mutation" | "query";
|
|
3421
3421
|
/** One RPC function, parsed and language-neutral. */
|
|
3422
3422
|
interface SdkMethod {
|
|
3423
|
+
/**
|
|
3424
|
+
* Where this function's ARGUMENT nulls mean "unset" and where they mean
|
|
3425
|
+
* "null" — see {@link ModelNullPaths}.
|
|
3426
|
+
*
|
|
3427
|
+
* On the method rather than on a shared render input because it is a
|
|
3428
|
+
* per-method fact and the parser already holds the schema it comes from. Read
|
|
3429
|
+
* by the three targets whose rendered models cannot tell the two apart
|
|
3430
|
+
* (ruby, rust, swift); the other five have a marker of their own and ignore
|
|
3431
|
+
* it.
|
|
3432
|
+
*/
|
|
3433
|
+
argsNullPaths: ModelNullPaths;
|
|
3423
3434
|
/**
|
|
3424
3435
|
* Generated args model name, or `undefined` when NO model could be named for
|
|
3425
3436
|
* this function's arguments.
|
|
@@ -3469,6 +3480,52 @@ interface SdkNamespace {
|
|
|
3469
3480
|
* discarding the real payload rather than leaving it untyped.
|
|
3470
3481
|
*/
|
|
3471
3482
|
declare const isTypedSchema: (schema: Record<string, unknown> | undefined) => boolean;
|
|
3483
|
+
/**
|
|
3484
|
+
* A path from a model's root to one property. `*` stands for every element of an
|
|
3485
|
+
* array or every value of a record, neither of which has named positions.
|
|
3486
|
+
*/
|
|
3487
|
+
type SchemaPath = ReadonlyArray<string>;
|
|
3488
|
+
/**
|
|
3489
|
+
* Where a model's nulls mean different things — the one fact a generated model
|
|
3490
|
+
* flattens away, and the reason three ports could not send a `v.nullable()`
|
|
3491
|
+
* argument at all.
|
|
3492
|
+
*
|
|
3493
|
+
* An unset `v.optional()` and a `v.nullable()` set to null are the SAME value in
|
|
3494
|
+
* every generated model (a nil field), and opposite things on the wire: the
|
|
3495
|
+
* validator rejects an explicit null for the first and requires the key present
|
|
3496
|
+
* for the second. Neither Ruby, Rust nor Swift renders a marker telling them
|
|
3497
|
+
* apart, so the distinction is computed here, from the schema, where `required`
|
|
3498
|
+
* still exists — and handed to the targets that need it.
|
|
3499
|
+
*
|
|
3500
|
+
* Two lists rather than one because the ports need opposite operations. Ruby and
|
|
3501
|
+
* Rust project a whole value tree and prune nulls, so they prune at
|
|
3502
|
+
* {@link ModelNullPaths.optional} and nowhere else — which also stops them
|
|
3503
|
+
* dropping a legitimate null inside a record or an array, as a blanket prune
|
|
3504
|
+
* does. Swift's `JSONEncoder` has already dropped every struct-property nil
|
|
3505
|
+
* before the transport sees a tree, so it restores nulls at
|
|
3506
|
+
* {@link ModelNullPaths.nullable} instead: an absent key at a required path can
|
|
3507
|
+
* only have been a nil, so putting the null back is exact.
|
|
3508
|
+
*
|
|
3509
|
+
* A `$ref` is NOT resolved. `openrpc.ts` inlines everything it emits, so this
|
|
3510
|
+
* never comes up for a generated document — but `--spec` accepts a hand-written
|
|
3511
|
+
* one, and there a `$ref`'d sub-object contributes no paths at all: the ports
|
|
3512
|
+
* that prune would send its unset optionals as null, and Swift would not restore
|
|
3513
|
+
* its nullables. Inline the schema, or teach this to follow the pointer.
|
|
3514
|
+
*
|
|
3515
|
+
* Both lists name PROPERTIES only. A record's values and an array's elements can
|
|
3516
|
+
* be null too, but no port drops one: the pruning ports prune at `optional`
|
|
3517
|
+
* paths, which a `*` position can never be, and `JSONEncoder` drops a nil only
|
|
3518
|
+
* from a struct property — a nil inside a dictionary or array encodes as null.
|
|
3519
|
+
* Listing a `*` leaf would also make Swift's restore INVENT record keys that
|
|
3520
|
+
* were never there, which is why the walk records the path it descends through
|
|
3521
|
+
* but never the `*` position itself.
|
|
3522
|
+
*/
|
|
3523
|
+
interface ModelNullPaths {
|
|
3524
|
+
/** Required properties that permit null — a null there is a VALUE and must survive. */
|
|
3525
|
+
nullable: ReadonlyArray<SchemaPath>;
|
|
3526
|
+
/** Properties absent from their object's `required` — a null there means UNSET. */
|
|
3527
|
+
optional: ReadonlyArray<SchemaPath>;
|
|
3528
|
+
}
|
|
3472
3529
|
/** What a target renders from. */
|
|
3473
3530
|
interface SdkRenderInput {
|
|
3474
3531
|
/**
|
|
@@ -3550,8 +3607,8 @@ interface SdkTarget {
|
|
|
3550
3607
|
renderModels?: (document: OpenRpcDocument) => Record<string, string>;
|
|
3551
3608
|
/**
|
|
3552
3609
|
* THIRD-PARTY packages a consuming project must still install, reported by
|
|
3553
|
-
* the CLI. Empty for
|
|
3554
|
-
*
|
|
3610
|
+
* the CLI. Empty for six of the eight — the transport is vendored and those
|
|
3611
|
+
* six reach the wire with only their standard library.
|
|
3555
3612
|
*
|
|
3556
3613
|
* A list, and not derivable from the transport, because a target's MODELS can
|
|
3557
3614
|
* carry a dependency the transport does not: quicktype's Ruby backend emits
|
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-DIqnj_32.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-BjTV22uR.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-h8i51Mec.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-MX6y-iVE.mjs";import{default as G}from"./packem_shared/discoverInserts-YX8AmrzL.mjs";import{default as b}from"./packem_shared/discoverMaskProcedures-DhcK-YMG.mjs";import{default as y}from"./packem_shared/discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as j,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-CRmTpN4y.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-CjS2Mznw.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as q,discoverNotifyConfig as B}from"./packem_shared/NOTIFY_FILENAME-BybR3Xbd.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-DuTuaSMM.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-BYVq6cVp.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-L0lV17de.mjs";import{default as pe}from"./packem_shared/discoverSchema-BtlNz9b_.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-DxoIrQhA.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-CKPFWHT5.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-Ba3NiOwK.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-BjTV22uR.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-h8i51Mec.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-MX6y-iVE.mjs";import{default as G}from"./packem_shared/discoverInserts-YX8AmrzL.mjs";import{default as b}from"./packem_shared/discoverMaskProcedures-DhcK-YMG.mjs";import{default as y}from"./packem_shared/discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as j,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-CRmTpN4y.mjs";import{default as z}from"./packem_shared/discoverNondeterministicCalls-CjS2Mznw.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as q,discoverNotifyConfig as B}from"./packem_shared/NOTIFY_FILENAME-BybR3Xbd.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-DuTuaSMM.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-BYVq6cVp.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-L0lV17de.mjs";import{default as pe}from"./packem_shared/discoverSchema-BtlNz9b_.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-DxoIrQhA.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-CKPFWHT5.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-Ba3NiOwK.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-DZlIvflD.mjs";import{buildOpenApiDocument as be,emitOpenApi as ke,emitOpenApiModule as ye}from"./packem_shared/buildOpenApiDocument-B2mW3f5a.mjs";import{OPENRPC_VERSION as je,buildOpenRpcDocument as Ke,emitOpenRpc as Ve,emitOpenRpcModule as ze}from"./packem_shared/OPENRPC_VERSION-DB1PSt8W.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-BYsNQnIS.mjs";import{SchemaSnapshotParseError as tr,buildSchemaSnapshot as sr,evaluateSchemaDrift as ar,parseSchemaSnapshot as ir}from"./packem_shared/SchemaSnapshotParseError-Dc1aZAph.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-DcXlLVZ1.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-BBIBMZTg.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,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as N,mkdirSync as Bt,readFileSync as dt,writeFileSync as $t,rmSync as qt}from"node:fs";import{join as f,dirname as le}from"node:path";import{performance as ue}from"node:perf_hooks";import{runAdvisor as jt}from"@lunora/advisor";import{LunoraError as R}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as He}from"ts-morph";import{serializeSchemaSnapshot as Wt}from"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{toAdvisorContext as Vt}from"./formatAdvisories-BjTV22uR.mjs";import{discoverAgents as Ht}from"./AGENTS_FILENAME-CPHo8Se5.mjs";import{discoverContainers as Gt}from"./CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{diagnosticAt as Z}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as J}from"./module-specifiers-WF8iAydP.mjs";import{C as de,i as Yt,f as Xt,n as Qt,a as Zt,h as Jt,j as es,b as ts,c as ss,l as ns,e as rs,o as is,d as os,k as as,g as cs,p as ls,m as us}from"./emit-Ba3NiOwK.mjs";import{l as h,a as E,c as y,p as S,f as ft,i as ds,r as pt,e as fs}from"./discover-ast-D33zP-NZ.mjs";import ps from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as gs}from"./QUEUES_FILENAME-BnGLtAIu.mjs";import{discoverSandboxUsage as ms}from"./discoverSandboxUsage-L0lV17de.mjs";import hs from"./discoverStorageRulesMetadata-CKPFWHT5.mjs";import{discoverWorkflows as xs}from"./WORKFLOWS_FILENAME-B8y51Frf.mjs";import{gatePlatformFeatures as Es,resolveCodegenTarget as vs}from"./DEFAULT_TARGET-CIH5PRk1.mjs";import{i as T,a as F,e as x,c as I,r as Ss,b as As,s as ee,f as Ns,g as ys,d as bs}from"./discover-queries-Dfj_0WJG.mjs";import{classifyProcedureCall as _,inlineHandler as Is,procedureHandler as gt,chainUsesWrappedCall as mt,isDatabaseAccessor as K,chainHasStep as Ps,discoverFunctions as ws,resolveStandardSchemaType as Ts}from"./discoverFunctions-h8i51Mec.mjs";import Cs from"./discoverAuthApiCalls-DUjcl0SB.mjs";import Os from"./discoverCrons-BUJO2ipU.mjs";import{discoverFlagKeys as Rs}from"./FLAGS_FILENAME-DtBWyUKq.mjs";import Fs from"./discoverHttpRoutes-MX6y-iVE.mjs";import Ls from"./discoverInserts-YX8AmrzL.mjs";import Ds,{discoverMaskStrategies as ks,discoverMaskMetadata as Ms,discoverMaskHasNonLiteralPolicy as Ks}from"./discoverMaskProcedures-DhcK-YMG.mjs";import _s from"./discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as zs,isDefineMutatorCallee as Us,discoverMutators as Bs}from"./MUTATORS_FILENAME-CRmTpN4y.mjs";import $s from"./discoverNondeterministicCalls-CjS2Mznw.mjs";import{discoverNotifyConfig as qs,discoverNotifyCalls as js}from"./NOTIFY_FILENAME-BybR3Xbd.mjs";import Ws from"./discoverR2sqlCalls-DuTuaSMM.mjs";import Vs,{discoverRlsMetadata as Hs}from"./discoverRlsMetadata-BYVq6cVp.mjs";import Gs from"./discoverSchema-BtlNz9b_.mjs";import{secretKindOf as Ys,redact as Xs,isHeuristicSecretKind as Qs,isSecretishName as Zs}from"./redact-Cy14LEnc.mjs";import{discoverShapes as Js}from"./SHAPES_FILENAME-DxoIrQhA.mjs";import{emitApp as en}from"./emitApp-
|
|
1
|
+
import{existsSync as N,mkdirSync as Bt,readFileSync as dt,writeFileSync as $t,rmSync as qt}from"node:fs";import{join as f,dirname as le}from"node:path";import{performance as ue}from"node:perf_hooks";import{runAdvisor as jt}from"@lunora/advisor";import{LunoraError as R}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as He}from"ts-morph";import{serializeSchemaSnapshot as Wt}from"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{toAdvisorContext as Vt}from"./formatAdvisories-BjTV22uR.mjs";import{discoverAgents as Ht}from"./AGENTS_FILENAME-CPHo8Se5.mjs";import{discoverContainers as Gt}from"./CONTAINERS_FILENAME-Bvn6LZP6.mjs";import{diagnosticAt as Z}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as J}from"./module-specifiers-WF8iAydP.mjs";import{C as de,i as Yt,f as Xt,n as Qt,a as Zt,h as Jt,j as es,b as ts,c as ss,l as ns,e as rs,o as is,d as os,k as as,g as cs,p as ls,m as us}from"./emit-Ba3NiOwK.mjs";import{l as h,a as E,c as y,p as S,f as ft,i as ds,r as pt,e as fs}from"./discover-ast-D33zP-NZ.mjs";import ps from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as gs}from"./QUEUES_FILENAME-BnGLtAIu.mjs";import{discoverSandboxUsage as ms}from"./discoverSandboxUsage-L0lV17de.mjs";import hs from"./discoverStorageRulesMetadata-CKPFWHT5.mjs";import{discoverWorkflows as xs}from"./WORKFLOWS_FILENAME-B8y51Frf.mjs";import{gatePlatformFeatures as Es,resolveCodegenTarget as vs}from"./DEFAULT_TARGET-CIH5PRk1.mjs";import{i as T,a as F,e as x,c as I,r as Ss,b as As,s as ee,f as Ns,g as ys,d as bs}from"./discover-queries-Dfj_0WJG.mjs";import{classifyProcedureCall as _,inlineHandler as Is,procedureHandler as gt,chainUsesWrappedCall as mt,isDatabaseAccessor as K,chainHasStep as Ps,discoverFunctions as ws,resolveStandardSchemaType as Ts}from"./discoverFunctions-h8i51Mec.mjs";import Cs from"./discoverAuthApiCalls-DUjcl0SB.mjs";import Os from"./discoverCrons-BUJO2ipU.mjs";import{discoverFlagKeys as Rs}from"./FLAGS_FILENAME-DtBWyUKq.mjs";import Fs from"./discoverHttpRoutes-MX6y-iVE.mjs";import Ls from"./discoverInserts-YX8AmrzL.mjs";import Ds,{discoverMaskStrategies as ks,discoverMaskMetadata as Ms,discoverMaskHasNonLiteralPolicy as Ks}from"./discoverMaskProcedures-DhcK-YMG.mjs";import _s from"./discoverMigrations-4Jjf5DJE.mjs";import{MUTATORS_FILENAME as zs,isDefineMutatorCallee as Us,discoverMutators as Bs}from"./MUTATORS_FILENAME-CRmTpN4y.mjs";import $s from"./discoverNondeterministicCalls-CjS2Mznw.mjs";import{discoverNotifyConfig as qs,discoverNotifyCalls as js}from"./NOTIFY_FILENAME-BybR3Xbd.mjs";import Ws from"./discoverR2sqlCalls-DuTuaSMM.mjs";import Vs,{discoverRlsMetadata as Hs}from"./discoverRlsMetadata-BYVq6cVp.mjs";import Gs from"./discoverSchema-BtlNz9b_.mjs";import{secretKindOf as Ys,redact as Xs,isHeuristicSecretKind as Qs,isSecretishName as Zs}from"./redact-Cy14LEnc.mjs";import{discoverShapes as Js}from"./SHAPES_FILENAME-DxoIrQhA.mjs";import{emitApp as en}from"./emitApp-DZlIvflD.mjs";import{buildOpenApiDocument as tn,emitOpenApiModule as sn}from"./buildOpenApiDocument-B2mW3f5a.mjs";import{buildOpenRpcDocument as nn,emitOpenRpcModule as rn}from"./OPENRPC_VERSION-DB1PSt8W.mjs";import{s as on}from"./parse-validator-DtALyvid.mjs";import{buildSchemaSnapshot as an}from"./SchemaSnapshotParseError-Dc1aZAph.mjs";const cn=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},ln=(e,t)=>{if(t===void 0)return;const s=cn(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 R("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
3
|
${n}
|
|
4
4
|
|
|
@@ -0,0 +1,371 @@
|
|
|
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-BBIBMZTg.mjs";import{isTypedSchema as br}from"./isTypedSchema-BBIBMZTg.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
|
+
`)},L=`${f("dart").map(e=>`// ${e}`).join(`
|
|
3
|
+
`)}
|
|
4
|
+
|
|
5
|
+
`,Me=`# GENERATED by \`lunora sdk generate --lang dart\` — do not edit.
|
|
6
|
+
#
|
|
7
|
+
# The transport is vendored under lib/, so this package has no dependencies and
|
|
8
|
+
# nothing to fetch. Add it to a consuming app as a path dependency — pub takes a
|
|
9
|
+
# path dependency's identity from the "name" below, NOT from the directory, so
|
|
10
|
+
# this is the name you write no matter where you generated into:
|
|
11
|
+
#
|
|
12
|
+
# dependencies:
|
|
13
|
+
# lunora_sdk:
|
|
14
|
+
# path: sdk/dart
|
|
15
|
+
#
|
|
16
|
+
# import 'package:lunora_sdk/lunora_api.dart';
|
|
17
|
+
name: lunora_sdk
|
|
18
|
+
description: Generated Lunora SDK, transport included.
|
|
19
|
+
version: 0.0.0
|
|
20
|
+
publish_to: none
|
|
21
|
+
|
|
22
|
+
environment:
|
|
23
|
+
sdk: ^3.6.0
|
|
24
|
+
`,Re=new Set(["assert","break","case","catch","class","const","continue","default","do","else","enum","extends","false","final","finally","for","if","in","is","new","null","rethrow","return","super","switch","this","throw","true","try","var","void","while","with"]),E=e=>{const n=o(e),r=n.charAt(0).toLowerCase()+n.slice(1);return Re.has(r)?`${r}_`:r},pe=e=>$(e).replaceAll("$",String.raw`\$`),De=e=>e.replaceAll(" == null ? [] : List<"," == null ? null : List<").replaceAll(/Map\.from\((?<source>[^()]*?)!\)/gu,"$<source> == null ? null : Map.from($<source>!)"),z=" ".repeat(8),Pe=/^class (\w+) \{/u,Ve=/^class \w+ \{\n[\s\S]*?\n\}$/gmu,Ke=/^ {4}\w+\(\{\n([\s\S]*?)^ {4}\}\);$/mu,Ie=/^ {8}(?:required )?this\.\w+,$/gmu,Fe=/^ {4}Map<String, dynamic> toJson\(\) => \{\n([\s\S]*?)^ {4}\};$/mu,xe=/^ {8}"(?:[^\\"]|\\.)*": .*,$/gmu,qe=e=>e.replaceAll(Ve,n=>{const[,r]=Ke.exec(n)??[],[,t]=Fe.exec(n)??[];if(r===void 0||t===void 0)return n;const a=[...r.matchAll(Ie)].map(m=>{const d=m[0].trim();return{field:d.slice(d.indexOf("this.")+5,-1),optional:!d.startsWith("required ")}}),i=[...t.matchAll(xe)],s=a.filter(m=>m.optional);if(a.length!==i.length){if(s.length===0)return n;throw new Error(`dart models: cannot place the optional-field guards in ${Pe.exec(n)?.[1]??"a generated class"} — ${String(a.length)} constructor parameter(s) against ${String(i.length)} toJson entr(ies). quicktype's Dart output has changed shape; \`guardOptionalFields\` in targets/dart.ts must be updated to match.`)}let u=t;for(const[m,d]of i.entries()){const c=a[m];if(!c?.optional)continue;const g=d[0],Te=g.slice(z.length).replace(`${c.field} == null ? null : `,"");u=u.replace(g,`${z}if (${c.field} != null) ${Te}`)}return n.replace(t,u)}),de=e=>p(e,{none:"null",typed:()=>"LunoraClient.wireValue(args)",untyped:"args"}),$e={declaration:"LunoraOptimistic? optimistic, LunoraOptimisticUpdate? optimisticUpdate, bool Function()? precondition",forward:"optimistic: optimistic, optimisticUpdate: optimisticUpdate, precondition: precondition"},Z=e=>{const n=e.verb==="mutation"?`{String? shardKey, ${$e.declaration}}`:"{String? shardKey}";return p(e,{none:n,typed:r=>`${r} args, ${n}`,untyped:`Object? args, ${n}`})},me=(e,n)=>`${e}.fromJson(${n} as Map<String, dynamic>)`,X=e=>{const n=e.verb==="mutation"?`, ${$e.forward}`:"",r=`_client.${e.verb}("${pe(e.functionPath)}", args: ${de(e)}, shardKey: shardKey${n})`;return e.resultType===void 0?[` /// ${l(e.summary)}`,` Future<Object?> ${E(e.functionName)}(${Z(e)}) => ${r};`].join(`
|
|
25
|
+
`):[` /// ${l(e.summary)}`,` Future<${e.resultType}> ${E(e.functionName)}(${Z(e)}) async =>`,` ${me(e.resultType,`await ${r}`)};`].join(`
|
|
26
|
+
`)},Ue=e=>{const n=p(e,{none:"",typed:s=>`${s} args`,untyped:"Object? args"}),r=n===""?"":`${n}, `,t=de(e),a=`"${pe(e.functionPath)}"`,i=`_client.watch(${a}, args: ${t})`;return[` /// live ${l(e.summary)} — re-runs on every write to the tables it reads.`,` LunoraUnsubscribe subscribe${o(e.functionName)}(`,` ${r}{LunoraDataCallback? onData, LunoraErrorCallback? onError}`,` ) => _client.subscribe(${a}, args: ${t}, onData: onData, onError: onError);`,"",` /// live ${l(e.summary)}, as a Stream — bind it with StreamBuilder.`,e.resultType===void 0?` Stream<Object?> watch${o(e.functionName)}(${n}) => ${i};`:[` Stream<${e.resultType}> watch${o(e.functionName)}(${n}) =>`,` ${i}.map((raw) => ${me(e.resultType,"raw")});`].join(`
|
|
27
|
+
`)].join(`
|
|
28
|
+
`)},He=e=>{const n=`${o(e.name)}Api`,r=e.methods.map(t=>t.verb==="query"?`${X(t)}
|
|
29
|
+
|
|
30
|
+
${Ue(t)}`:X(t)).join(`
|
|
31
|
+
|
|
32
|
+
`);return[`/// Functions declared in \`${l(e.name)}\`.`,`class ${n} {`,` const ${n}(this._client);`,""," final LunoraClient _client;","",r,"}"].join(`
|
|
33
|
+
`)},Ge=({models:e,namespaces:n})=>{const r=n.map(s=>` final ${o(s.name)}Api ${E(s.name)};`).join(`
|
|
34
|
+
`),t=n.map(s=>` ${E(s.name)} = ${o(s.name)}Api(client)`).join(`,
|
|
35
|
+
`),a=N(n).length>0?`import 'models.dart';
|
|
36
|
+
`:"";return{"lib/lunora_api.dart":[L,`/// The generated Lunora surface. Re-exports the vendored transport, so one
|
|
37
|
+
`,`/// import gives a consumer the client, the wire types and the models.
|
|
38
|
+
`,`library;
|
|
39
|
+
`,`
|
|
40
|
+
`,`export 'lunora.dart';
|
|
41
|
+
`,`export 'models.dart';
|
|
42
|
+
`,`
|
|
43
|
+
`,`import 'lunora.dart';
|
|
44
|
+
`,a,`
|
|
45
|
+
`,n.map(s=>He(s)).join(`
|
|
46
|
+
|
|
47
|
+
`),n.length>0?`
|
|
48
|
+
|
|
49
|
+
`:"","/// Typed entry point: `Api(client).<namespace>.<function>(args)`.\n",`class Api {
|
|
50
|
+
`,n.length>0?` Api(LunoraClient client)
|
|
51
|
+
: ${t.trimStart()};
|
|
52
|
+
|
|
53
|
+
${r}
|
|
54
|
+
`:` const Api(LunoraClient client);
|
|
55
|
+
`,`}
|
|
56
|
+
`].join(""),"lib/models.dart":e.length>0?`${L}${qe(De(e))}
|
|
57
|
+
`:`${L}// No typed argument or result schemas in this deployment.
|
|
58
|
+
`,"pubspec.yaml":Me}},Be={id:"dart",quicktype:{lang:"dart"},render:Ge,requires:[],vendor:[{from:"lib",to:"lib"}]},W=`${f("go").map(e=>`// ${e}`).join(`
|
|
59
|
+
`)}
|
|
60
|
+
|
|
61
|
+
`,b="lunoraapi",_="lunorasdk",Je=`${_}/lunora`,Ye="1.22",V=e=>o(e),Q=(e,n)=>{const r=p(n,{none:"",typed:u=>`args ${u}, `,untyped:"args any, "}),t=p(n,{none:"nil",typed:()=>"args",untyped:"args"}),a=n.resultType??"any",i=`lunora.Verb${n.verb.charAt(0).toUpperCase()}${n.verb.slice(1)}`,s=`lunora.Call[${a}](a.client, ${i}, "${$(n.functionPath)}", ${t}, shardKey)`;return[`// ${V(n.functionName)} invokes ${l(n.summary)}.`,`func (a *${e}) ${V(n.functionName)}(${r}shardKey string) (${a}, error) {`,` return ${s}`,"}"].join(`
|
|
62
|
+
`)},ze=(e,n)=>{const r=p(n,{none:"",typed:i=>`args ${i}, `,untyped:"args any, "}),t=p(n,{none:"nil",typed:()=>"args",untyped:"args"}),a=`Subscribe${V(n.functionName)}`;return[`// ${a} opens a live ${l(n.functionPath)}; it re-runs on every write to the tables it reads.`,`func (a *${e}) ${a}(${r}onData lunora.DataHandler, onError lunora.ErrorHandler, shardKey string) lunora.Unsubscribe {`,` return a.client.Subscribe("${$(n.functionPath)}", ${t}, onData, onError, shardKey)`,"}"].join(`
|
|
63
|
+
`)},Ze=e=>{const n=`${o(e.name)}API`,r=e.methods.map(t=>t.verb==="query"?`${Q(n,t)}
|
|
64
|
+
|
|
65
|
+
${ze(n,t)}`:Q(n,t)).join(`
|
|
66
|
+
|
|
67
|
+
`);return[`// ${n} groups the functions declared in ${l(e.name)}.`,`type ${n} struct{ client *lunora.Client }`,"",r].join(`
|
|
68
|
+
`)},Xe=({models:e,namespaces:n})=>{const r=n.map(s=>` ${o(s.name)} *${o(s.name)}API`).join(`
|
|
69
|
+
`),t=n.map(s=>` ${o(s.name)}: &${o(s.name)}API{client: client},`).join(`
|
|
70
|
+
`),a=[W,`package ${b}
|
|
71
|
+
`,`
|
|
72
|
+
`,`import "${Je}"
|
|
73
|
+
`,`
|
|
74
|
+
`,`// API is the typed entry point: api.<Namespace>.<Function>(args, shardKey).
|
|
75
|
+
`,`type API struct {
|
|
76
|
+
`,`${r}
|
|
77
|
+
`,`}
|
|
78
|
+
`,`
|
|
79
|
+
`,`// NewAPI binds the generated surface to a client.
|
|
80
|
+
`,`func NewAPI(client *lunora.Client) *API {
|
|
81
|
+
`,` return &API{
|
|
82
|
+
`,`${t}
|
|
83
|
+
`,` }
|
|
84
|
+
`,`}
|
|
85
|
+
`,`
|
|
86
|
+
`,n.map(s=>Ze(s)).join(`
|
|
87
|
+
|
|
88
|
+
`),`
|
|
89
|
+
`].join(""),i=e.length>0?`${W}package ${b}
|
|
90
|
+
|
|
91
|
+
${e}
|
|
92
|
+
`:`${W}package ${b}
|
|
93
|
+
|
|
94
|
+
// No typed argument or result schemas in this deployment.
|
|
95
|
+
`;return{[`${b}/api.go`]:a,[`${b}/models.go`]:i,"go.mod":[`// The generated Lunora Go SDK, with the transport vendored under ./lunora.
|
|
96
|
+
`,`//
|
|
97
|
+
`,`// A consuming module wires it in without a network fetch:
|
|
98
|
+
`,`//
|
|
99
|
+
`,`// require ${_} v0.0.0
|
|
100
|
+
`,`// replace ${_} => ./path/to/this/directory
|
|
101
|
+
`,`module ${_}
|
|
102
|
+
`,`
|
|
103
|
+
`,`go ${Ye}
|
|
104
|
+
`].join("")}},Qe={id:"go",quicktype:{lang:"go",rendererOptions:{"just-types":"true",package:b}},render:Xe,requires:[],vendor:[{from:"lunora",to:"lunora"}]},w="lunoraapi.models",K="lunoraapi/models",en=24,nn=new Set(["abstract","as","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","fromWire","fun","goto","if","implements","import","in","instanceof","int","interface","is","long","native","new","null","object","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","toWire","transient","true","try","typealias","typeof","val","var","void","volatile","when","while","wireValue"]),rn=/[^A-Za-z0-9]+/gu,tn=/([a-z0-9])([A-Z])/gu,an=/^[A-Za-z]/u,sn=/^[A-Z]/u;class ye extends Error{}const y=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,on=e=>{const n=e.anyOf??e.oneOf;if(!Array.isArray(n)||n.length===0)return;const r=n.map(t=>y(t)?.const);if(r.every(t=>typeof t=="string"))return[...new Set(r)].toSorted((t,a)=>t.localeCompare(a))},fe=e=>{const n=e.anyOf??e.oneOf;if(!Array.isArray(n)||n.length!==2)return e;const r=n.filter(t=>y(t)?.type!=="null");return r.length===1?y(r[0])??e:e},ln=e=>{const n=o(e),r=n.charAt(0).toLowerCase()+n.slice(1),t=an.test(r)?r:`value${n}`;return nn.has(t)?`${t}_`:t},un=e=>{const n=e.replaceAll(tn,"$1_$2").replaceAll(rn,"_").toUpperCase().split("_").filter(r=>r.length>0).join("_");return sn.test(n)?n:`VALUE_${n}`},ge=(e,n)=>{if(!n.has(e))return n.add(e),e;let r=2;for(;n.has(`${e}${String(r)}`);)r+=1;return n.add(`${e}${String(r)}`),`${e}${String(r)}`},ee=(e,n)=>{if(e.has(n.name))throw new ye(`sdk: two schemas both produce the JVM model "${n.name}"`);e.set(n.name,n)},cn=(e,n,r,t,a)=>{const i=new Set(Array.isArray(n)?n.filter(u=>typeof u=="string"):[]),s=new Set;return Object.entries(e).map(([u,m])=>{const d=y(m)??{},c=!i.has(u);return{name:ge(ln(u),s),nullable:!c&&fe(d)!==d,optional:c,type:j(d,`${r}${o(u)}`,t+1,a),wireKey:u}})},j=(e,n,r,t)=>{if(r>=en)return{kind:"unknown"};const a=on(e);if(a!==void 0){const d=new Set;return ee(t,{constants:a.map(c=>({name:ge(un(c),d),wireValue:c})),kind:"enum",name:n}),{kind:"enum",name:n}}const i=fe(e);if(i!==e)return j(i,n,r+1,t);const s=y(e.properties);if(s!==void 0)return ee(t,{fields:cn(s,e.required,n,r,t),kind:"class",name:n}),{kind:"class",name:n};const u=y(e.additionalProperties);if(u!==void 0)return{kind:"record",value:j(u,`${n}Value`,r+1,t)};const m=y(e.items);if(m!==void 0)return{item:j(m,`${n}Item`,r+1,t),kind:"list"};switch(e.type){case"boolean":return{kind:"boolean"};case"integer":case"number":return{kind:"number"};case"string":return{kind:"string"};default:return{kind:"unknown"}}},be=e=>{const n=new Map;for(const r of ce(e)){if(y(r.schema.properties)===void 0)continue;const t=new Map;try{j(r.schema,r.name,0,t)}catch(a){if(a instanceof ye)continue;throw a}if(![...t.keys()].some(a=>n.has(a)))for(const[a,i]of t)n.set(a,i)}return[...n.values()].toSorted((r,t)=>r.name.localeCompare(t.name))},C=e=>[`// GENERATED by \`lunora sdk generate --lang ${e}\` — do not edit.`,"// Run the command again to regenerate."],T=e=>{switch(e.kind){case"boolean":return"Boolean";case"class":case"enum":return e.name;case"list":return`java.util.List<${T(e.item)}>`;case"number":return"Double";case"record":return`java.util.Map<String, ${T(e.value)}>`;case"string":return"String";default:return"Object"}},I=e=>{switch(e.kind){case"class":case"enum":return!0;case"list":return I(e.item);case"record":return I(e.value);default:return!1}},F=(e,n,r)=>{if(!I(e))return n;const t=`item${String(r)}`;switch(e.kind){case"class":return`${n} == null ? null : ${n}.toWire()`;case"enum":return`${n} == null ? null : ${n}.toValue()`;case"list":return`ModelWire.writeList(${n}, ${t} -> ${F(e.item,t,r+1)})`;case"record":return`ModelWire.writeRecord(${n}, ${t} -> ${F(e.value,t,r+1)})`;default:return n}},x=(e,n,r)=>{const t=`item${String(r)}`;switch(e.kind){case"boolean":return`ModelWire.flag(${n})`;case"class":return`ModelWire.readObject(${n}, ${e.name}::fromWire)`;case"enum":return`ModelWire.readEnum(${n}, ${e.name}::forValue)`;case"list":return`ModelWire.readList(${n}, ${t} -> ${x(e.item,t,r+1)})`;case"number":return`ModelWire.number(${n})`;case"record":return`ModelWire.readRecord(${n}, ${t} -> ${x(e.value,t,r+1)})`;case"string":return`ModelWire.text(${n})`;default:return n}},pn=e=>{const n=l(e.wireKey);return e.optional?[" /**",` * Wire key {@code ${n}} — OPTIONAL: null omits the key entirely, because`," * `v.optional` accepts the value or `undefined` and rejects an explicit null."," */"]:[` /** Wire key {@code ${n}}.${e.nullable?" Nullable: null is sent as an explicit null.":""} */`]},dn=100,$n=e=>{const n=e.fields.map(t=>`${T(t.type)} ${t.name}`),r=` public ${e.name}(${n.join(", ")}) {`;return r.length<=dn?[r]:[` public ${e.name}(`,...n.map((t,a)=>` ${t}${a===n.length-1?") {":","}`)]},mn=e=>{const n=e.fields.flatMap(t=>{const a=`wire.put("${$(t.wireKey)}", ${F(t.type,`this.${t.name}`,0)});`;return t.optional?[` if (this.${t.name} != null) {`,` ${a}`," }"]:[` ${a}`]}),r=e.fields.map(t=>` ${x(t.type,`wire.get("${$(t.wireKey)}")`,0)}`);return[...C("java"),"",`package ${w};`,"","/**",` * The \`${e.name}\` model.`," *"," * <p>Field names are local; the keys {@link #toWire()} and {@link #fromWire(Object)} use are"," * the schema's own, emitted verbatim, so a renamed field cannot reach the wire."," */",`public final class ${e.name} {`,...e.fields.flatMap(t=>[...pn(t),` public final ${T(t.type)} ${t.name};`,""]),...$n(e),...e.fields.map(t=>` this.${t.name} = ${t.name};`)," }",""," /** This model as the wire-shaped map the transport encodes. */"," public java.util.Map<String, Object> toWire() {"," java.util.Map<String, Object> wire = new java.util.LinkedHashMap<>();",...n,""," return wire;"," }",""," /** Rebuild from a decoded wire value. */",` public static ${e.name} fromWire(Object value) {`," java.util.Map<String, Object> wire = ModelWire.object(value);","",...r.length===0?[` return new ${e.name}();`]:[` return new ${e.name}(`,`${r.join(`,
|
|
105
|
+
`)});`]," }","}",""].join(`
|
|
106
|
+
`)},yn=e=>[...C("java"),"",`package ${w};`,"",`/** The \`${e.name}\` union. Each constant keeps the wire string it encodes to. */`,`public enum ${e.name} {`,...e.constants.map((n,r)=>` ${n.name}("${$(n.wireValue)}")${r===e.constants.length-1?";":","}`),""," private final String value;","",` ${e.name}(String value) {`," this.value = value;"," }",""," /** The wire string this constant encodes to. */"," public String toValue() {"," return this.value;"," }",""," /** The constant a wire string decodes to. */",` public static ${e.name} forValue(String value) {`,` for (${e.name} candidate : values()) {`," if (candidate.value.equals(value)) {"," return candidate;"," }"," }","",` throw new IllegalArgumentException("${e.name}: unknown wire value " + value);`," }","}",""].join(`
|
|
107
|
+
`),fn=[{lines:[' @SuppressWarnings("unchecked")'," static java.util.Map<String, Object> object(Object value) {"," return value instanceof java.util.Map"," ? (java.util.Map<String, Object>) value"," : new java.util.LinkedHashMap<String, Object>();"," }"],name:"object"},{lines:[" static String text(Object value) {"," return value instanceof String ? (String) value : null;"," }"],name:"text"},{lines:[" static Double number(Object value) {"," return value instanceof Number ? ((Number) value).doubleValue() : null;"," }"],name:"number"},{lines:[" static Boolean flag(Object value) {"," return value instanceof Boolean ? (Boolean) value : null;"," }"],name:"flag"},{lines:[" /** A nested model, or null when the payload carried no object there. */"," static <T> T readObject(Object value, java.util.function.Function<Object, T> read) {"," return value instanceof java.util.Map ? read.apply(value) : null;"," }"],name:"readObject"},{lines:[" /** An enum constant, or null when the payload carried no string there. */"," static <T> T readEnum(Object value, java.util.function.Function<String, T> read) {"," return value instanceof String ? read.apply((String) value) : null;"," }"],name:"readEnum"},{lines:[" static <T> java.util.List<T> readList("," Object value, java.util.function.Function<Object, T> read) {"," if (!(value instanceof java.util.List)) {"," return null;"," }",""," java.util.List<T> items = new java.util.ArrayList<T>();",""," for (Object item : (java.util.List<?>) value) {"," items.add(read.apply(item));"," }",""," return items;"," }"],name:"readList"},{lines:[" static <T> java.util.Map<String, T> readRecord("," Object value, java.util.function.Function<Object, T> read) {"," if (!(value instanceof java.util.Map)) {"," return null;"," }",""," java.util.Map<String, T> entries = new java.util.LinkedHashMap<String, T>();",""," for (java.util.Map.Entry<?, ?> entry : ((java.util.Map<?, ?>) value).entrySet()) {"," entries.put(String.valueOf(entry.getKey()), read.apply(entry.getValue()));"," }",""," return entries;"," }"],name:"readRecord"},{lines:[" static <T> java.util.List<Object> writeList("," java.util.List<T> items, java.util.function.Function<T, Object> write) {"," if (items == null) {"," return null;"," }",""," java.util.List<Object> encoded = new java.util.ArrayList<Object>(items.size());",""," for (T item : items) {"," encoded.add(write.apply(item));"," }",""," return encoded;"," }"],name:"writeList"},{lines:[" static <T> java.util.Map<String, Object> writeRecord("," java.util.Map<String, T> entries, java.util.function.Function<T, Object> write) {"," if (entries == null) {"," return null;"," }",""," java.util.Map<String, Object> encoded = new java.util.LinkedHashMap<String, Object>();",""," for (java.util.Map.Entry<String, T> entry : entries.entrySet()) {"," encoded.put(entry.getKey(), write.apply(entry.getValue()));"," }",""," return encoded;"," }"],name:"writeRecord"}],gn=e=>{const n=fn.filter(r=>e.includes(`ModelWire.${r.name}(`));return[...C("java"),"",`package ${w};`,"","/** Wire readers and writers shared by the generated models. */","final class ModelWire {"," private ModelWire() {}",...n.flatMap(r=>["",...r.lines]),"}",""].join(`
|
|
108
|
+
`)},bn=e=>{const n=be(e);if(n.length===0)return{};const r={};for(const t of n)r[`${K}/${t.name}.java`]=t.kind==="enum"?yn(t):mn(t);return{[`${K}/ModelWire.java`]:gn(Object.values(r).join(`
|
|
109
|
+
`)),...r}},q=e=>{switch(e.kind){case"boolean":return"Boolean";case"class":case"enum":return e.name;case"list":return`List<${q(e.item)}>`;case"number":return"Double";case"record":return`Map<String, ${q(e.value)}>`;case"string":return"String";default:return"WireValue"}},h=(e,n,r)=>{const t=`item${String(r)}`,a=`entry${String(r)}`;switch(e.kind){case"boolean":return`WireValue.Bool(${n})`;case"class":return`${n}.toWire()`;case"enum":return`WireValue.Text(${n}.wireValue)`;case"list":return`WireValue.Arr(${n}.map { ${t} -> ${h(e.item,t,r+1)} })`;case"number":return`WireValue.Num(${n})`;case"record":return`WireValue.Obj(${n}.map { ${a} -> ${a}.key to ${h(e.value,`${a}.value`,r+1)} })`;case"string":return`WireValue.Text(${n})`;default:return n}},U=(e,n,r,t)=>`wireNeed(${ve(e,n,r,t)}, "${v(t)}")`,ve=(e,n,r,t)=>{const a=`item${String(r)}`,i=`entry${String(r)}`;switch(e.kind){case"boolean":return`wireBool(${n})`;case"class":return`wireObj(${n})?.let { ${a} -> ${e.name}.fromWire(${a}) }`;case"enum":return`wireText(${n})?.let { ${a} -> ${e.name}.forValue(${a}) }`;case"list":return`wireArr(${n})?.items?.map { ${a} -> ${U(e.item,a,r+1,`${t}[]`)} }`;case"number":return`wireNum(${n})`;case"record":return`wireObj(${n})?.fields?.associate { ${i} -> ${i}.first to ${U(e.value,`${i}.second`,r+1,`${t}{}`)} }`;case"string":return`wireText(${n})`;default:return n}},vn=e=>{const n=e.fields.map(a=>{const i=l(a.wireKey);return[...a.optional?[" /**",` * Wire key \`${i}\` — OPTIONAL: null omits the key entirely, because`," * `v.optional` accepts the value or `undefined` and rejects an explicit null."," */"]:[` /** Wire key \`${i}\`.${a.nullable?" Nullable: null is sent as an explicit null.":""} */`],` val ${a.name}: ${q(a.type)}${a.optional||a.nullable?"?":""}${a.optional?" = null":""},`]}),r=e.fields.map(a=>{const i=v(a.wireKey);return a.optional?` ${a.name}?.let { add("${i}" to ${h(a.type,"it",0)}) }`:a.nullable?` add("${i}" to (${a.name}?.let { ${h(a.type,"it",0)} } ?: WireValue.Null))`:` add("${i}" to ${h(a.type,a.name,0)})`}),t=e.fields.map(a=>{const i=`wireField(value, "${v(a.wireKey)}")`,s=a.optional||a.nullable?ve(a.type,i,0,a.wireKey):U(a.type,i,0,a.wireKey);return` ${a.name} = ${s},`});return["/**",` * The \`${e.name}\` model.`," *"," * Property names are local; the keys [toWire] and [fromWire] use are the schema's own,"," * emitted verbatim, so a renamed property cannot reach the wire."," */",`class ${e.name}(`,...n.flat(),") {"," /** This model as the wire-shaped object the transport encodes. */"," fun toWire(): WireValue ="," WireValue.Obj("," buildList {",...r," },"," )",""," companion object {"," /** Rebuild from a decoded wire value. */",` fun fromWire(value: WireValue): ${e.name} =`,` ${e.name}(`,...t," )"," }","}"]},wn=e=>[`/** The \`${e.name}\` union. Each entry keeps the wire string it encodes to. */`,`enum class ${e.name}(val wireValue: String) {`,...e.constants.map(n=>` ${n.name}("${v(n.wireValue)}"),`)," ;",""," companion object {"," /** The entry a wire string decodes to. */",` fun forValue(value: String): ${e.name} =`," entries.firstOrNull { it.wireValue == value }",` ?: throw IllegalArgumentException("${e.name}: unknown wire value " + value)`," }","}"],jn=[{lines:["private fun wireField(value: WireValue, key: String): WireValue? ="," (value as? WireValue.Obj)?.fields?.firstOrNull { it.first == key }?.second"],name:"wireField"},{lines:["private fun wireText(value: WireValue?): String? = (value as? WireValue.Text)?.value"],name:"wireText"},{lines:["private fun wireNum(value: WireValue?): Double? = (value as? WireValue.Num)?.value"],name:"wireNum"},{lines:["private fun wireBool(value: WireValue?): Boolean? = (value as? WireValue.Bool)?.value"],name:"wireBool"},{lines:["private fun wireArr(value: WireValue?): WireValue.Arr? = value as? WireValue.Arr"],name:"wireArr"},{lines:["private fun wireObj(value: WireValue?): WireValue.Obj? = value as? WireValue.Obj"],name:"wireObj"},{lines:["/** A required field the payload omitted or mistyped is a contract violation, not a null. */","private fun <T> wireNeed(read: T?, label: String): T =",' read ?: throw WireFormatException("lunora: the wire payload is missing or mistyped " + label)'],name:"wireNeed"}],hn=e=>{const n=be(e);if(n.length===0)return{};const r=n.flatMap(s=>[...s.kind==="enum"?wn(s):vn(s),""]),t=jn.filter(s=>r.some(u=>u.includes(`${s.name}(`))),a=t.flatMap((s,u)=>u===0?[...s.lines]:["",...s.lines]),i=[...C("kotlin"),"",`package ${w}`,"",...t.some(s=>s.name==="wireNeed")?["import dev.lunora.WireFormatException"]:[],"import dev.lunora.WireValue","",...r,...a,""].join(`
|
|
110
|
+
`);return{[`${K}/Models.kt`]:i}},An=`${f("java").map(e=>`// ${e}`).join(`
|
|
111
|
+
`)}
|
|
112
|
+
|
|
113
|
+
`,ne="lunoraapi",_n=new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while"]),H=e=>{const n=o(e),r=n.charAt(0).toLowerCase()+n.slice(1);return _n.has(r)?`${r}_`:r},Sn=e=>`Client.Verb.${e.toUpperCase()}`,we=e=>e.argsType===void 0?{payload:"args",type:"java.util.Map<String, Object>"}:{payload:"args == null ? null : args.toWire()",type:e.argsType},re=e=>{const n=we(e),r=`client.call(
|
|
114
|
+
${Sn(e.verb)}, "${$(e.functionPath)}", ${n.payload}, shardKey)`;return[` /** ${l(e.summary)} */`,` public ${e.resultType??"Object"} ${H(e.functionName)}(${n.type} args, String shardKey) {`,` return ${e.resultType===void 0?r:`${e.resultType}.fromWire(${r})`};`," }"].join(`
|
|
115
|
+
`)},En=e=>{const n=we(e);return[` /** live ${l(e.summary)} — re-runs on every write to the tables it reads. */`,` public Runnable subscribe${o(e.functionName)}(`,` ${n.type} args,`," java.util.function.Consumer<Object> onData,"," java.util.function.Consumer<Client.SubscriptionError> onError,"," String shardKey) {"," return client.subscribe(",` "${$(e.functionPath)}", ${n.payload}, onData, onError, shardKey);`," }"].join(`
|
|
116
|
+
`)},Tn=e=>{const n=`${o(e.name)}Api`,r=e.methods.map(t=>t.verb==="query"?`${re(t)}
|
|
117
|
+
|
|
118
|
+
${En(t)}`:re(t)).join(`
|
|
119
|
+
|
|
120
|
+
`);return[` /** Functions declared in \`${l(e.name)}\`. */`,` public static final class ${n} {`," private final Client client;","",` ${n}(Client client) {`," this.client = client;"," }","",r.replaceAll(/^ {4}/gmu," ")," }"].join(`
|
|
121
|
+
`)},kn=({namespaces:e})=>{const n=e.map(i=>` public final ${o(i.name)}Api ${H(i.name)};`).join(`
|
|
122
|
+
`),r=e.map(i=>` this.${H(i.name)} = new ${o(i.name)}Api(client);`).join(`
|
|
123
|
+
`),t=N(e).map(i=>`import ${w}.${i};
|
|
124
|
+
`),a=[An,`package ${ne};
|
|
125
|
+
`,`
|
|
126
|
+
`,`import dev.lunora.Client;
|
|
127
|
+
`,...t,`
|
|
128
|
+
`,"/** Typed entry point: `new Api(client).<namespace>.<function>(args, shardKey)`. */\n",`public final class Api {
|
|
129
|
+
`,n.length>0?`${n}
|
|
130
|
+
|
|
131
|
+
`:"",` public Api(Client client) {
|
|
132
|
+
`,r.length>0?`${r}
|
|
133
|
+
`:` // No functions in this deployment.
|
|
134
|
+
`,` }
|
|
135
|
+
`,`
|
|
136
|
+
`,e.map(i=>Tn(i)).join(`
|
|
137
|
+
|
|
138
|
+
`),`
|
|
139
|
+
}
|
|
140
|
+
`].join("");return{[`${ne}/Api.java`]:a}},On={id:"java",render:kn,renderModels:bn,requires:[],vendor:[{from:"src/dev/lunora",to:"dev/lunora"}]},Nn=`${f("kotlin").map(e=>`// ${e}`).join(`
|
|
141
|
+
`)}
|
|
142
|
+
|
|
143
|
+
`,te="lunoraapi",Cn=new Set(["as","break","class","continue","do","else","false","for","fun","if","in","interface","is","null","object","package","return","super","this","throw","true","try","typealias","typeof","val","var","when","while"]),je=e=>{const n=o(e),r=n.charAt(0).toLowerCase()+n.slice(1);return Cn.has(r)?`\`${r}\``:r},Ln=e=>`Verb.${e.toUpperCase()}`,he=e=>e.argsType===void 0?{declaration:"args: WireValue? = null",payload:"args"}:{declaration:`args: ${e.argsType}`,payload:"args.toWire()"},ae=e=>{const n=he(e),r=`client.call(${Ln(e.verb)}, "${v(e.functionPath)}", ${n.payload}, shardKey)`;return[` /** ${l(e.summary)} */`,` fun ${je(e.functionName)}(${n.declaration}, shardKey: String? = null): ${e.resultType??"WireValue"} =`,` ${e.resultType===void 0?r:`${e.resultType}.fromWire(${r})`}`].join(`
|
|
144
|
+
`)},Wn=e=>{const n=he(e);return[` /** live ${l(e.summary)} — re-runs on every write to the tables it reads. */`,` fun subscribe${o(e.functionName)}(`,` ${n.declaration},`," onData: ((WireValue) -> Unit)?,"," onError: ((SubscriptionError) -> Unit)? = null,"," shardKey: String? = null,"," ): () -> Unit =",` client.subscribe("${v(e.functionPath)}", ${n.payload}, onData, onError, shardKey)`].join(`
|
|
145
|
+
`)},Mn=e=>{const n=`${o(e.name)}Api`,r=e.methods.map(t=>t.verb==="query"?`${ae(t)}
|
|
146
|
+
|
|
147
|
+
${Wn(t)}`:ae(t)).join(`
|
|
148
|
+
|
|
149
|
+
`);return[`/** Functions declared in \`${l(e.name)}\`. */`,`class ${n}(private val client: Client) {`,r,"}"].join(`
|
|
150
|
+
`)},Rn=({namespaces:e})=>{const n=e.map(i=>` val ${je(i.name)}: ${o(i.name)}Api = ${o(i.name)}Api(client)`).join(`
|
|
151
|
+
`),r=e.flatMap(i=>i.methods),t=[`import dev.lunora.Client
|
|
152
|
+
`,...r.some(i=>i.verb==="query")?[`import dev.lunora.SubscriptionError
|
|
153
|
+
`]:[],`import dev.lunora.Verb
|
|
154
|
+
`,...r.some(i=>i.argsType===void 0||i.resultType===void 0)?[`import dev.lunora.WireValue
|
|
155
|
+
`]:[],...N(e).map(i=>`import ${w}.${i}
|
|
156
|
+
`)],a=[Nn,`package ${te}
|
|
157
|
+
`,`
|
|
158
|
+
`,...t,`
|
|
159
|
+
`,e.map(i=>Mn(i)).join(`
|
|
160
|
+
|
|
161
|
+
`),`
|
|
162
|
+
|
|
163
|
+
`,"/** Typed entry point: `Api(client).<namespace>.<function>(args)`. */\n",`class Api(client: Client) {
|
|
164
|
+
`,n.length>0?`${n}
|
|
165
|
+
`:` init { require(true) { client } }
|
|
166
|
+
`,`}
|
|
167
|
+
`].join("");return{[`${te}/Api.kt`]:a}},Dn={id:"kotlin",render:Rn,renderModels:hn,requires:[],vendor:[{from:"src",to:"dev/lunora"}]},Pn=new Set(["and","as","assert","async","await","break","class","continue","def","del","elif","else","except","False","finally","for","from","global","if","import","in","is","lambda","None","nonlocal","not","or","pass","raise","return","True","try","while","with","yield"]),A=`"""${f("python").join(`
|
|
168
|
+
|
|
169
|
+
`)}
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
`,M="lunora_api",J=e=>{const n=B(e);return Pn.has(n)?`${n}_`:n},Ae=e=>p(e,{none:"{}",typed:()=>"args.to_dict()",untyped:"args"}),Vn=(e,n,r,t)=>p(e,{none:n,typed:r,untyped:t}),ie=e=>{const n=e.resultType??"Any",r=Vn(e,"self",i=>`self, args: ${i}`,"self, args: Any"),t=Ae(e),a=`await self._client.${e.verb}("${$(e.functionPath)}", ${t}, shard_key)`;return[` async def ${J(e.functionName)}(${r}, *, shard_key: Optional[str] = None) -> ${n}:`,` """${l(e.summary)}"""`,` ${e.resultType===void 0?`return ${a}`:`return ${e.resultType}.from_dict(${a})`}`].join(`
|
|
173
|
+
`)},Kn=e=>{const n=Ae(e),r=["self",...p(e,{none:[],typed:t=>[`args: ${t}`],untyped:["args: Any"]}),"on_data: Callback","on_error: Optional[ErrorCallback] = None","*","shard_key: Optional[str] = None"];return[` def subscribe_${J(e.functionName)}(`,...r.map(t=>` ${t},`)," ) -> Unsubscribe:",` """live ${l(e.summary)} — re-runs on every write to the tables it reads."""`,` return self._client.subscribe("${$(e.functionPath)}", ${n}, on_data, on_error, shard_key)`].join(`
|
|
174
|
+
`)},In=e=>{const n=e.methods.map(r=>r.verb==="query"?`${ie(r)}
|
|
175
|
+
|
|
176
|
+
${Kn(r)}`:ie(r)).join(`
|
|
177
|
+
|
|
178
|
+
`);return[`class ${o(e.name)}Api:`,` """Functions declared in \`${l(e.name)}\`."""`,""," def __init__(self, client: LunoraClient) -> None:"," self._client = client","",n].join(`
|
|
179
|
+
`)},Fn=e=>e.replaceAll(/^([ \t]*)except:$/gmu,"$1except Exception:"),xn=({models:e,namespaces:n})=>{const r=N(n),t=r.length>0?`from .models import ${r.join(", ")}
|
|
180
|
+
`:"",i=P(n).some(c=>c.verb==="query")?"Callback, ErrorCallback, LunoraClient, Unsubscribe":"LunoraClient",s=P(n).some(c=>c.resultType===void 0),u=n.map(c=>` self.${J(c.name)} = ${o(c.name)}Api(client)`).join(`
|
|
181
|
+
`),m=[A,`from typing import ${s?"Any, Optional":"Optional"}
|
|
182
|
+
`,`
|
|
183
|
+
`,`from lunora.client import ${i}
|
|
184
|
+
`,t,`
|
|
185
|
+
|
|
186
|
+
`,n.map(c=>In(c)).join(`
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
`),`
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
`,`class Api:
|
|
193
|
+
`,' """Typed entry point: `Api(client).<namespace>.<function>(args)`."""\n',`
|
|
194
|
+
`,` def __init__(self, client: LunoraClient) -> None:
|
|
195
|
+
`,u.length>0?`${u}
|
|
196
|
+
`:` pass
|
|
197
|
+
`].join(""),d=["Api",...n.map(c=>`${o(c.name)}Api`)];return{[`${M}/__init__.py`]:[A,`from .api import ${d.join(", ")}
|
|
198
|
+
`,`
|
|
199
|
+
`,`__all__ = [${d.map(c=>`"${c}"`).join(", ")}]
|
|
200
|
+
`].join(""),[`${M}/api.py`]:m,[`${M}/models.py`]:e.length>0?`${A}${Fn(e)}
|
|
201
|
+
`:`${A}# No typed argument or result schemas in this deployment.
|
|
202
|
+
`}},qn={id:"python",quicktype:{lang:"python",rendererOptions:{"python-version":"3.7"}},render:xn,requires:[],vendor:[{from:"lunora",to:"lunora"}]},R=`${f("ruby").map(e=>`# ${e}`).join(`
|
|
203
|
+
`)}
|
|
204
|
+
|
|
205
|
+
`,Un=new Set(["alias","and","begin","break","case","class","def","defined?","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield"]),Y=e=>$(e).replaceAll("#","\\#"),k=e=>{const n=B(e);return Un.has(n)?`${n}_`:n},Hn=` # Delegates to the transport, which owns the projection and its tests — see
|
|
206
|
+
# \`Lunora.wire_args\`. The path list is generated per model because only the
|
|
207
|
+
# schema knows which nils may be dropped.
|
|
208
|
+
def self.wire_args(model, optional_paths = [])
|
|
209
|
+
Lunora.wire_args(model, optional_paths)
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
`,Gn=e=>`[${e.map(n=>`[${n.map(r=>`"${Y(r)}"`).join(", ")}]`).join(", ")}]`,_e=e=>p(e,{none:"{}",typed:()=>`LunoraApi.wire_args(args, ${Gn(e.argsNullPaths.optional)})`,untyped:"args"}),se=e=>{const n=e.argsType===void 0&&!e.takesArgs?"shard_key: nil":"args, shard_key: nil",r=_e(e),t=`@client.${e.verb}("${Y(e.functionPath)}", ${r}, shard_key)`,a=e.resultType===void 0?t:`${e.resultType}.from_dynamic!(${t})`;return[` # ${l(e.summary)}`,` def ${k(e.functionName)}(${n})`,` ${a}`," end"].join(`
|
|
213
|
+
`)},Bn=e=>{const n=e.argsType===void 0&&!e.takesArgs?"on_data, on_error = nil, shard_key: nil":"args, on_data, on_error = nil, shard_key: nil",r=_e(e);return[` # live ${l(e.summary)} — re-runs on every write to the tables it reads.`,` def subscribe_${k(e.functionName)}(${n})`,` @client.subscribe("${Y(e.functionPath)}", ${r}, on_data, on_error, shard_key)`," end"].join(`
|
|
214
|
+
`)},Jn=e=>{const n=e.methods.map(r=>r.verb==="query"?`${se(r)}
|
|
215
|
+
|
|
216
|
+
${Bn(r)}`:se(r)).join(`
|
|
217
|
+
|
|
218
|
+
`);return[` # Functions declared in \`${l(e.name)}\`.`,` class ${o(e.name)}Api`," def initialize(client)"," @client = client"," end","",n," end"].join(`
|
|
219
|
+
`)},Yn=({models:e,namespaces:n})=>{const r=n.map(i=>`:${k(i.name)}`).join(", "),t=n.map(i=>` @${k(i.name)} = ${o(i.name)}Api.new(client)`).join(`
|
|
220
|
+
`);return{"api.rb":[`# frozen_string_literal: true
|
|
221
|
+
|
|
222
|
+
`,R,`require_relative "models"
|
|
223
|
+
`,`
|
|
224
|
+
`,`module LunoraApi
|
|
225
|
+
`,P(n).some(i=>i.argsType!==void 0)?Hn:"",n.map(i=>Jn(i)).join(`
|
|
226
|
+
|
|
227
|
+
`),`
|
|
228
|
+
|
|
229
|
+
`," # Typed entry point: `Api.new(client).<namespace>.<function>(args)`.\n",` class Api
|
|
230
|
+
`,r.length>0?` attr_reader ${r}
|
|
231
|
+
|
|
232
|
+
`:"",` def initialize(client)
|
|
233
|
+
`,t.length>0?`${t}
|
|
234
|
+
`:` @client = client
|
|
235
|
+
`,` end
|
|
236
|
+
`,` end
|
|
237
|
+
`,`end
|
|
238
|
+
`].join(""),"models.rb":e.length>0?`# frozen_string_literal: true
|
|
239
|
+
|
|
240
|
+
${R}${e}
|
|
241
|
+
`:`# frozen_string_literal: true
|
|
242
|
+
|
|
243
|
+
${R}# No typed argument or result schemas in this deployment.
|
|
244
|
+
`}},zn={id:"ruby",quicktype:{lang:"ruby",rendererOptions:{}},render:Yn,requires:["dry-struct + dry-types (gems, required by the generated models)"],vendor:[{from:"lib/lunora.rb",to:"lunora.rb"},{from:"lib/lunora",to:"lunora"}]},S=`${f("rust").map(e=>`// ${e}`).join(`
|
|
245
|
+
`)}
|
|
246
|
+
|
|
247
|
+
`,Zn=`${S}pub mod api;
|
|
248
|
+
pub mod models;
|
|
249
|
+
`,Xn=`# The generated Lunora Rust SDK, with the transport vendored under ./lunora.
|
|
250
|
+
#
|
|
251
|
+
# Add to a consuming crate:
|
|
252
|
+
#
|
|
253
|
+
# lunora-api = { path = "sdk/rust" }
|
|
254
|
+
|
|
255
|
+
[package]
|
|
256
|
+
name = "lunora-api"
|
|
257
|
+
version = "0.1.0"
|
|
258
|
+
edition = "2021"
|
|
259
|
+
publish = false
|
|
260
|
+
|
|
261
|
+
# Its own workspace root, so a consumer whose project IS a workspace does not
|
|
262
|
+
# adopt this directory as a member (which then fails to build on its own).
|
|
263
|
+
[workspace]
|
|
264
|
+
|
|
265
|
+
[dependencies]
|
|
266
|
+
lunora = { path = "lunora" }
|
|
267
|
+
serde = { version = "1", features = ["derive"] }
|
|
268
|
+
serde_json = "1"
|
|
269
|
+
`,Qn=new Set(["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","static","struct","super","trait","true","try","type","typeof","unsafe","unsized","use","virtual","where","while","yield"]),O=e=>{const n=B(e);return Qn.has(n)?`r#${n}`:n},er=e=>`Verb::${o(e)}`,Se=e=>e.length===0?"&[]":`&[${e.map(n=>`&["${n.map(r=>$(r)).join('", "')}"][..]`).join(", ")}]`,oe=e=>{const n=p(e,{none:"&self, shard_key: Option<&str>",typed:a=>`&self, args: &${a}, shard_key: Option<&str>`,untyped:"&self, args: &WireValue, shard_key: Option<&str>"}),r=p(e,{none:"&WireValue::Object(Vec::new())",typed:()=>`&from_model_json(&serde_json::to_value(args).map_err(|error| ClientError::Transport(error.to_string()))?, ${Se(e.argsNullPaths.optional)})`,untyped:"args"}),t=`self.client.call(${er(e.verb)}, "${$(e.functionPath)}", ${r}, shard_key)`;return e.resultType===void 0?[` /// ${l(e.summary)}`,` pub fn ${O(e.functionName)}(${n}) -> Result<WireValue, ClientError> {`,` ${t}`," }"].join(`
|
|
270
|
+
`):[` /// ${l(e.summary)}`,` pub fn ${O(e.functionName)}(${n}) -> Result<${e.resultType}, ClientError> {`,` let raw = ${t}?;`," let json = encode_wire(&raw).map_err(ClientError::Wire)?;"," serde_json::from_value(json).map_err(|error| ClientError::Transport(error.to_string()))"," }"].join(`
|
|
271
|
+
`)},nr=e=>{const n=p(e,{none:"",typed:t=>`args: &${t}, `,untyped:"args: &WireValue, "}),r=p(e,{none:"WireValue::Object(Vec::new())",typed:()=>`from_model_json(&serde_json::to_value(args).map_err(|error| ClientError::Transport(error.to_string()))?, ${Se(e.argsNullPaths.optional)})`,untyped:"args.clone()"});return[` /// live ${l(e.summary)} — re-runs on every write to the tables it reads.`,` pub fn subscribe_${O(e.functionName)}(`," &mut self,",` ${n}on_data: DataHandler,`," on_error: ErrorHandler,"," shard_key: Option<&str>,"," ) -> Result<String, ClientError> {"," let _ = shard_key;",` Ok(self.client.subscribe("${$(e.functionPath)}", ${r}, on_data, on_error))`," }"].join(`
|
|
272
|
+
`)},rr=e=>{const n=`${o(e.name)}Api`,r=e.methods.map(t=>t.verb==="query"?`${oe(t)}
|
|
273
|
+
|
|
274
|
+
${nr(t)}`:oe(t)).join(`
|
|
275
|
+
|
|
276
|
+
`);return[`/// Functions declared in \`${l(e.name)}\`.`,`pub struct ${n}<'client> {`," client: &'client mut Client,","}","",`impl<'client> ${n}<'client> {`,r,"}"].join(`
|
|
277
|
+
`)},tr=({models:e,namespaces:n})=>{const r=n.map(a=>[` /// Functions declared in \`${l(a.name)}\`.`,` pub fn ${O(a.name)}(&mut self) -> ${o(a.name)}Api<'_> {`,` ${o(a.name)}Api { client: self.client }`," }"].join(`
|
|
278
|
+
`)).join(`
|
|
279
|
+
|
|
280
|
+
`),t=[S,`#![allow(dead_code, unused_imports)]
|
|
281
|
+
`,`
|
|
282
|
+
`,`use lunora::client::{Client, ClientError, DataHandler, ErrorHandler, Verb};
|
|
283
|
+
`,`use lunora::wire::{encode_wire, from_model_json, WireValue};
|
|
284
|
+
`,`
|
|
285
|
+
`,`use crate::models::*;
|
|
286
|
+
`,`
|
|
287
|
+
`,n.map(a=>rr(a)).join(`
|
|
288
|
+
|
|
289
|
+
`),`
|
|
290
|
+
|
|
291
|
+
`,"/// Typed entry point: `Api::new(&client).<namespace>().<function>(args)`.\n",`pub struct Api<'client> {
|
|
292
|
+
`,` client: &'client mut Client,
|
|
293
|
+
`,`}
|
|
294
|
+
`,`
|
|
295
|
+
`,`impl<'client> Api<'client> {
|
|
296
|
+
`,` pub fn new(client: &'client mut Client) -> Self {
|
|
297
|
+
`,` Self { client }
|
|
298
|
+
`,` }
|
|
299
|
+
`,r.length>0?`
|
|
300
|
+
${r}
|
|
301
|
+
`:"",`}
|
|
302
|
+
`].join("");return{"Cargo.toml":Xn,"src/api.rs":t,"src/lib.rs":Zn,"src/models.rs":e.length>0?`${S}#![allow(dead_code)]
|
|
303
|
+
|
|
304
|
+
${e}
|
|
305
|
+
`:`${S}#![allow(dead_code)]
|
|
306
|
+
|
|
307
|
+
// No typed argument or result schemas in this deployment.
|
|
308
|
+
`}},ar={id:"rust",quicktype:{lang:"rust",rendererOptions:{"just-types":"true"}},render:tr,requires:["serde (derive) + serde_json — declared in the emitted Cargo.toml, fetched by cargo"],vendor:[{from:"Cargo.toml",to:"lunora/Cargo.toml"},{from:"src",to:"lunora/src"}]},D=`${f("swift").map(e=>`// ${e}`).join(`
|
|
309
|
+
`)}
|
|
310
|
+
|
|
311
|
+
`,le="Sources/LunoraApi",ir=`// swift-tools-version:5.9
|
|
312
|
+
|
|
313
|
+
import PackageDescription
|
|
314
|
+
|
|
315
|
+
// The generated Lunora Swift SDK, with the transport vendored under
|
|
316
|
+
// Sources/Lunora. Add to a consuming package — where "swift" below is the NAME OF
|
|
317
|
+
// THE DIRECTORY THIS FILE IS IN, which is how SwiftPM identifies a local path
|
|
318
|
+
// dependency. It ignores the "name:" field for that, and a bare product name in a
|
|
319
|
+
// target's dependencies does not resolve at all, so the directory name is the one
|
|
320
|
+
// spelling that works:
|
|
321
|
+
//
|
|
322
|
+
// dependencies: [.package(path: "sdk/swift")],
|
|
323
|
+
// targets: [
|
|
324
|
+
// .target(
|
|
325
|
+
// name: "YourTarget",
|
|
326
|
+
// dependencies: [.product(name: "LunoraApi", package: "swift")]
|
|
327
|
+
// )
|
|
328
|
+
// ]
|
|
329
|
+
let package = Package(
|
|
330
|
+
name: "LunoraSdk",
|
|
331
|
+
platforms: [.macOS(.v12), .iOS(.v15)],
|
|
332
|
+
products: [
|
|
333
|
+
.library(name: "LunoraApi", targets: ["LunoraApi"]),
|
|
334
|
+
.library(name: "Lunora", targets: ["Lunora"]),
|
|
335
|
+
],
|
|
336
|
+
targets: [
|
|
337
|
+
.target(name: "Lunora"),
|
|
338
|
+
.target(name: "LunoraApi", dependencies: ["Lunora"]),
|
|
339
|
+
]
|
|
340
|
+
)
|
|
341
|
+
`,sr=new Set(["as","associatedtype","borrowing","break","case","catch","class","consuming","continue","default","defer","deinit","do","else","enum","extension","fallthrough","false","fileprivate","for","func","guard","if","import","in","init","inout","internal","is","let","nil","nonisolated","open","operator","precedencegroup","private","protocol","public","repeat","rethrows","return","self","static","struct","subscript","super","switch","throw","throws","true","try","typealias","var","where","while"]),G=e=>{const n=o(e),r=n.charAt(0).toLowerCase()+n.slice(1);return sr.has(r)?`\`${r}\``:r},or=e=>`[${e.map(n=>`["${n.map(r=>$(r)).join('", "')}"]`).join(", ")}]`,Ee=e=>p(e,{none:"nil",typed:()=>{const{nullable:n}=e.argsNullPaths;return n.length===0?"try LunoraClient.wireValue(args)":`try LunoraClient.wireValue(args, nullablePaths: ${or(n)})`},untyped:"args"}),ue=e=>{const n=p(e,{none:"shardKey: String? = nil",typed:s=>`_ args: ${s}, shardKey: String? = nil`,untyped:"_ args: Any, shardKey: String? = nil"}),r=Ee(e),t=e.resultType??"Any",a=`try client.${e.verb}("${$(e.functionPath)}", args: ${r}, shardKey: shardKey)`,i=e.resultType===void 0?`return ${a}`:[`let raw = ${a}`," let data = try JSONSerialization.data(withJSONObject: raw, options: [.fragmentsAllowed])",` return try JSONDecoder().decode(${e.resultType}.self, from: data)`].join(`
|
|
342
|
+
`);return[` /// ${l(e.summary)}`,` public func ${G(e.functionName)}(${n}) throws -> ${t} {`,` ${i}`," }"].join(`
|
|
343
|
+
`)},lr=e=>{const n=p(e,{none:"",typed:t=>`_ args: ${t}, `,untyped:"_ args: Any, "}),r=Ee(e);return[` /// live ${l(e.summary)} — re-runs on every write to the tables it reads.`," @discardableResult",` public func subscribe${o(e.functionName)}(`,` ${n}onData: ((Any) -> Void)?,`," onError: ((LunoraSubscriptionError) -> Void)? = nil,"," shardKey: String? = nil"," ) throws -> LunoraUnsubscribe {",` client.subscribe("${$(e.functionPath)}", args: ${r}, onData: onData, onError: onError, shardKey: shardKey)`," }"].join(`
|
|
344
|
+
`)},ur=e=>{const n=`${o(e.name)}API`,r=e.methods.map(t=>t.verb==="query"?`${ue(t)}
|
|
345
|
+
|
|
346
|
+
${lr(t)}`:ue(t)).join(`
|
|
347
|
+
|
|
348
|
+
`);return[`/// Functions declared in \`${l(e.name)}\`.`,`public struct ${n} {`," let client: LunoraClient","",r,"}"].join(`
|
|
349
|
+
`)},cr=({models:e,namespaces:n})=>{const r=n.map(i=>` public let ${G(i.name)}: ${o(i.name)}API`).join(`
|
|
350
|
+
`),t=n.map(i=>` ${G(i.name)} = ${o(i.name)}API(client: client)`).join(`
|
|
351
|
+
`),a=[D,`import Foundation
|
|
352
|
+
`,`import Lunora
|
|
353
|
+
`,`
|
|
354
|
+
`,n.map(i=>ur(i)).join(`
|
|
355
|
+
|
|
356
|
+
`),`
|
|
357
|
+
|
|
358
|
+
`,"/// Typed entry point: `API(client:).<namespace>.<function>(args)`.\n",`public struct API {
|
|
359
|
+
`,r.length>0?`${r}
|
|
360
|
+
|
|
361
|
+
`:"",` public init(client: LunoraClient) {
|
|
362
|
+
`,t.length>0?`${t}
|
|
363
|
+
`:` _ = client
|
|
364
|
+
`,` }
|
|
365
|
+
`,`}
|
|
366
|
+
`].join("");return{"Package.swift":ir,[`${le}/Api.swift`]:a,[`${le}/Models.swift`]:e.length>0?`${D}${e}
|
|
367
|
+
`:`${D}import Foundation
|
|
368
|
+
|
|
369
|
+
// No typed argument or result schemas in this deployment.
|
|
370
|
+
`}},pr={id:"swift",quicktype:{lang:"swift",rendererOptions:{"access-level":"public"}},render:cr,requires:[],vendor:[{from:"Sources/Lunora",to:"Sources/Lunora"}]},dr={dart:Be,go:Qe,java:On,kotlin:Dn,python:qn,ruby:zn,rust:ar,swift:pr},mr=Object.keys(dr).toSorted((e,n)=>e.localeCompare(n)),yr=async(e,n)=>{const r=ke(e);Oe(r);const t=n.renderModels?.(e),a=t===void 0?await We(e,n):Object.values(t).join(`
|
|
371
|
+
`),i=Ne(r,a);return{files:{...t,...n.render({models:a,namespaces:i})},undeclared:Le(r,a),unrepresentable:Ce(e)}};export{mr as SDK_LANGUAGES,dr as SDK_TARGETS,yr as generateSdk,br as isTypedSchema};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as S,G as D}from"./emit-Ba3NiOwK.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),g=e=>v.some(([t])=>e[t]),A=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],R=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],x=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,
|
|
1
|
+
import{A as S,G as D}from"./emit-Ba3NiOwK.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),g=e=>v.some(([t])=>e[t]),A=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],R=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],x=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,C=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:r,hasFramework:a,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:c,hasQueue:s,hasScheduler:d,hasStorage:u,hasWorkflow:h,useUmbrella:l,wantsOpenApi:p,wantsOpenRpc:b}=e,i=l?"lunorash/runtime":"@lunora/runtime",m=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&m.push("GlobalIntrospector","AdminTableResolver"),a&&m.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...a?["withFrameworkWorker"]:[]].join(", ");return[...r?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...R(t,r),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, importGlobalRows, listGlobalTables, readGlobalTablePage } from "@lunora/d1";']:[],...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...x(c),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...u?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...h?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),`import type { ${[...m].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...L(e),...n||o?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...b?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},I=e=>[...e.hasStorage?[`/** \`.storage(...)\` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs \`ctx.storage\` AND the studio file browser. */
|
|
2
2
|
interface StorageDeclaration<Env> {
|
|
3
3
|
/** The default R2 bucket binding (the bare \`ctx.storage\`). */
|
|
4
4
|
bucket: Selector<Env, R2BucketLike>;
|
|
@@ -8,12 +8,12 @@ interface StorageDeclaration<Env> {
|
|
|
8
8
|
publicBaseUrl?: Selector<Env, string>;
|
|
9
9
|
/** HMAC secret for signed URLs. */
|
|
10
10
|
signingSecret?: Selector<Env, string>;
|
|
11
|
-
}`]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace plus the worker origin its callbacks dispatch back to. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n /** The worker origin the `SchedulerDO` dispatches HTTP job callbacks back to. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],j=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...g(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],N=e=>v.filter(([t])=>e[t]).map(([,t,r,a])=>` /** ${a} */
|
|
11
|
+
}`]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace plus the worker origin its callbacks dispatch back to. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n /** The worker origin the `SchedulerDO` dispatches HTTP job callbacks back to. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],j=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...g(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],N=e=>v.filter(([t])=>e[t]).map(([,t,r,a])=>` /** ${a} */
|
|
12
12
|
public ${t}(factory: NonNullable<ShardConfig["${r}"]>): this {
|
|
13
13
|
this.shardExtras.${r} = factory;
|
|
14
14
|
|
|
15
15
|
return this;
|
|
16
|
-
}`),q=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) —
|
|
16
|
+
}`),q=e=>[...e.hasAccess?[" /** Wire Cloudflare Access (Zero Trust) — feeds the verified Access identity into `ctx.auth` / RLS via `resolveIdentity`. Call it with no argument when the Access policy is attached to the Worker (the identity arrives on the execution context; nothing to configure); pass `teamDomain` + `aud` for a hostname-scoped Access application, whose `Cf-Access-Jwt-Assertion` JWT is verified against your team JWKS. When `.auth(...)` is also configured, Access is composed ahead of it (Access wins when it authenticated the caller; everyone else falls through to the app session). */\n public access(selector?: Selector<Env, CreateAccessResolverOptions>): this {\n this.accessSelector = selector ?? (() => undefined);\n\n return this;\n }"]:[],` /** Bearer token gating the \`/_lunora/admin/*\` endpoints the studio calls. */
|
|
17
17
|
public admin(selector: Selector<Env, string>): this {
|
|
18
18
|
this.adminToken = selector;
|
|
19
19
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const b=/[^a-zA-Z0-9]+/gu,M=/([a-z0-9])([A-Z])/gu,p=t=>t.split(b).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),L=t=>t.replaceAll(M,"$1_$2").replaceAll(b,"_").toLowerCase(),d=t=>t===void 0?!1:["$ref","allOf","anyOf","enum","items","oneOf","properties","type"].some(e=>e in t),O=t=>t==="query"?"query":t==="action"?"action":"mutation",i=(t,e=0)=>{if(e>32||t===null||typeof t!="object")return!1;if(Array.isArray(t))return t.some(o=>i(o,e+1));const r=t;if(r.type==="integer"&&r.format==="int64"||r.type==="string"&&r.contentEncoding==="base64")return!0;const{properties:n}=r;return n!==null&&typeof n=="object"&&Object.values(n).some(o=>i(o,e+1))?!0:["additionalProperties","allOf","anyOf","items","oneOf"].some(o=>i(r[o],e+1))},R=t=>t.replaceAll(/[\n\r\u2028\u2029]+/gu," ").replaceAll("*/","* /").replaceAll('"""','" ""'),T=t=>t.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(`
|
|
2
|
+
`,"\\n").replaceAll("\r","\\r"),j=["$","{","'","$","'","}"].join(""),_=t=>T(t).split("$").join(j),D=(t,e)=>t.argsType!==void 0?e.typed(t.argsType):t.takesArgs?e.untyped:e.none,f=32,A=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return!1;const r=t;return r.type==="null"||Array.isArray(r.type)&&r.type.includes("null")?!0:["anyOf","oneOf"].some(n=>{const o=r[n];return Array.isArray(o)&&o.some(a=>A(a,e+1))})},E=(t,e,r)=>e.length===0?r===0?[]:[t]:e.map(n=>({properties:{...t.properties,...n.properties},required:new Set([...t.required,...n.required])})),C=t=>{const{properties:e}=t;if(e===null||typeof e!="object")return[];const r=t.required;return[{properties:e,required:new Set(Array.isArray(r)?r.filter(n=>typeof n=="string"):[])}]},m=(t,e,r)=>{const n=t[e];return Array.isArray(n)?n.flatMap(o=>h(o,r+1)):[]},h=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const r=t,n=[...C(r),...m(r,"allOf",e)],o={properties:Object.assign({},...n.map(s=>s.properties)),required:new Set(n.flatMap(s=>[...s.required]))},a=[...m(r,"anyOf",e),...m(r,"oneOf",e)];return E(o,a,n.length)},S=(t,e=0)=>{if(e>f||t===null||typeof t!="object")return[];const r=t,n=[r];for(const o of["anyOf","oneOf","allOf"]){const a=r[o];if(Array.isArray(a))for(const s of a)n.push(...S(s,e+1))}return n},y=(t,e,r,n=0)=>{if(n>f||t===null||typeof t!="object")return;const o=h(t),a=[...new Set(o.flatMap(s=>Object.keys(s.properties)))].toSorted((s,c)=>s.localeCompare(c));for(const s of a){const c=[...e,s],u=o.every(l=>l.required.has(s)),g=o.map(l=>l.properties[s]).filter(l=>l!==void 0);u?g.some(l=>A(l))&&r.nullable.push(c):r.optional.push(c);for(const l of g)y(l,c,r,n+1)}for(const s of S(t))for(const c of["additionalProperties","items"]){const u=s[c];u!==null&&typeof u=="object"&&y(u,[...e,"*"],r,n+1)}},N=(t,e)=>t.join("\0").localeCompare(e.join("\0")),k=t=>{const e={nullable:[],optional:[]};y(t,[],e);const r=n=>[...new Map(n.map(o=>[o.join("\0"),o])).values()].toSorted(N);return{nullable:r(e.nullable),optional:r(e.optional)}},w=t=>{const[e="",r=""]=t.name.split(":"),n=`${p(e)}${p(r)}`,o=t.params?.[0]?.schema,a=t.result?.schema;return{argsNullPaths:k(o),argsType:d(o)&&!i(o)?`${n}Args`:void 0,takesArgs:d(o),functionName:r,functionPath:t.name,namespace:e,resultType:d(a)&&!i(a)?`${n}Result`:void 0,summary:t.summary??t.name,verb:O(t["x-lunora-function-kind"])}},x=t=>{const e=new Map;for(const r of t.methods){const n=w(r),o=e.get(n.namespace);o===void 0?e.set(n.namespace,[n]):o.push(n)}return[...e.entries()].toSorted(([r],[n])=>r.localeCompare(n)).map(([r,n])=>({methods:n.toSorted((o,a)=>o.functionName.localeCompare(a.functionName)),name:r}))},I=t=>t.methods.flatMap(e=>{const r=w(e);return[{name:r.argsType,schema:e.params?.[0]?.schema},{name:r.resultType,schema:e.result?.schema}]}).filter(e=>e.name!==void 0&&e.schema!==void 0).toSorted((e,r)=>e.name.localeCompare(r.name)),P=/^[A-Za-z][A-Za-z0-9]*$/u,$=t=>P.test(t),q=t=>{const e=new Map;for(const r of t.methods){const n=p(r.functionName);if(!$(n))throw new Error(`sdk: function "${r.functionPath}" produces the invalid identifier "${n}" — rename the export so it starts with a letter.`);const o=r.verb==="query"?[n,`Subscribe${n}`]:[n];for(const a of o){const s=e.get(a);if(s!==void 0)throw new Error(`sdk: functions "${s}" and "${r.functionPath}" both generate "${a}" — rename one so the generated methods stay distinct.`);e.set(a,r.functionPath)}}},z=t=>{const e=new Map;for(const r of t){const n=p(r.name);if(!$(n))throw new Error(`sdk: namespace "${r.name}" produces the invalid identifier "${n}" — rename the file so it starts with a letter.`);const o=e.get(n);if(o!==void 0)throw new Error(`sdk: namespaces "${o}" and "${r.name}" both generate "${n}" — rename one so the generated types stay distinct.`);e.set(n,r.name),q(r)}},v=t=>t.flatMap(e=>e.methods),H=t=>[`GENERATED by \`lunora sdk generate --lang ${t}\` — do not edit.`,"Run the command again to regenerate."],U=(t,e)=>{const r=n=>n!==void 0&&new RegExp(String.raw`\b${n}\b`,"u").test(e)?n:void 0;return t.map(n=>({methods:n.methods.map(o=>({...o,argsType:r(o.argsType),resultType:r(o.resultType)})),name:n.name}))},Z=t=>t.methods.filter(e=>i(e.params?.[0]?.schema)||i(e.result?.schema)).map(e=>e.name).toSorted((e,r)=>e.localeCompare(r)),F=(t,e)=>[...new Set(v(t).flatMap(r=>[r.argsType,r.resultType]).filter(r=>r!==void 0&&!new RegExp(String.raw`\b${r}\b`,"u").test(e)))].toSorted((r,n)=>r.localeCompare(n)),G=t=>[...new Set(v(t).flatMap(e=>[e.argsType,e.resultType]).filter(e=>e!==void 0))].toSorted((e,r)=>e.localeCompare(r));export{v as allMethods,D as argsChoice,z as assertGeneratable,R as commentText,H as generatedHeaderLines,i as hasUnrepresentableWireType,d as isTypedSchema,_ as kotlinLiteral,I as modelSources,k as nullPathsOf,w as parseMethod,x as parseSpec,G as referencedModels,T as stringLiteral,p as toPascalCase,L as toSnakeCase,F as undeclaredModels,Z as unrepresentableFunctions,O as verbForKind,U as withDeclaredModels};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.112",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,13 +46,13 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
50
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.81",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.56",
|
|
51
51
|
"@lunora/container": "1.0.0-alpha.31",
|
|
52
52
|
"@lunora/errors": "1.0.0-alpha.22",
|
|
53
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
54
|
-
"@lunora/queue": "1.0.0-alpha.
|
|
55
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
53
|
+
"@lunora/platform": "1.0.0-alpha.12",
|
|
54
|
+
"@lunora/queue": "1.0.0-alpha.28",
|
|
55
|
+
"@lunora/scheduler": "1.0.0-alpha.32",
|
|
56
56
|
"@lunora/values": "1.0.0-alpha.27",
|
|
57
57
|
"@lunora/workflow": "1.0.0-alpha.29",
|
|
58
58
|
"jsonc-parser": "^3.3.1",
|
|
@@ -1,320 +0,0 @@
|
|
|
1
|
-
import{modelSources as ae,toPascalCase as o,generatedHeaderLines as f,commentText as l,argsChoice as p,stringLiteral as d,kotlinLiteral as g,referencedModels as H,allMethods as M,toSnakeCase as G,parseSpec as be,assertGeneratable as ge,withDeclaredModels as ve,unrepresentableFunctions as we,undeclaredModels as je}from"./isTypedSchema-CU-O5qSH.mjs";import{isTypedSchema as Gn}from"./isTypedSchema-CU-O5qSH.mjs";const he=async(e,n)=>{if(n.quicktype===void 0)return"";const r=ae(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 O of r)await m.addSource({name:O.name,schema:JSON.stringify(O.schema)});const $=new t;$.addInput(m);const{lines:c}=await s({inputData:$,lang:n.quicktype.lang,rendererOptions:n.quicktype.rendererOptions??{}});return c.join(`
|
|
2
|
-
`)},N=`${f("go").map(e=>`// ${e}`).join(`
|
|
3
|
-
`)}
|
|
4
|
-
|
|
5
|
-
`,b="lunoraapi",A="lunorasdk",Ae=`${A}/lunora`,_e="1.22",V=e=>o(e),B=(e,n)=>{const r=p(n,{none:"",typed:u=>`args ${u}, `,untyped:"args any, "}),t=p(n,{none:"nil",typed:()=>"args",untyped:"args"}),a=n.resultType??"any",i=`lunora.Verb${n.verb.charAt(0).toUpperCase()}${n.verb.slice(1)}`,s=`lunora.Call[${a}](a.client, ${i}, "${d(n.functionPath)}", ${t}, shardKey)`;return[`// ${V(n.functionName)} invokes ${l(n.summary)}.`,`func (a *${e}) ${V(n.functionName)}(${r}shardKey string) (${a}, error) {`,` return ${s}`,"}"].join(`
|
|
6
|
-
`)},Se=(e,n)=>{const r=p(n,{none:"",typed:i=>`args ${i}, `,untyped:"args any, "}),t=p(n,{none:"nil",typed:()=>"args",untyped:"args"}),a=`Subscribe${V(n.functionName)}`;return[`// ${a} opens a live ${l(n.functionPath)}; it re-runs on every write to the tables it reads.`,`func (a *${e}) ${a}(${r}onData lunora.DataHandler, onError lunora.ErrorHandler, shardKey string) lunora.Unsubscribe {`,` return a.client.Subscribe("${d(n.functionPath)}", ${t}, onData, onError, shardKey)`,"}"].join(`
|
|
7
|
-
`)},ke=e=>{const n=`${o(e.name)}API`,r=e.methods.map(t=>t.verb==="query"?`${B(n,t)}
|
|
8
|
-
|
|
9
|
-
${Se(n,t)}`:B(n,t)).join(`
|
|
10
|
-
|
|
11
|
-
`);return[`// ${n} groups the functions declared in ${l(e.name)}.`,`type ${n} struct{ client *lunora.Client }`,"",r].join(`
|
|
12
|
-
`)},Ee=({models:e,namespaces:n})=>{const r=n.map(s=>` ${o(s.name)} *${o(s.name)}API`).join(`
|
|
13
|
-
`),t=n.map(s=>` ${o(s.name)}: &${o(s.name)}API{client: client},`).join(`
|
|
14
|
-
`),a=[N,`package ${b}
|
|
15
|
-
`,`
|
|
16
|
-
`,`import "${Ae}"
|
|
17
|
-
`,`
|
|
18
|
-
`,`// API is the typed entry point: api.<Namespace>.<Function>(args, shardKey).
|
|
19
|
-
`,`type API struct {
|
|
20
|
-
`,`${r}
|
|
21
|
-
`,`}
|
|
22
|
-
`,`
|
|
23
|
-
`,`// NewAPI binds the generated surface to a client.
|
|
24
|
-
`,`func NewAPI(client *lunora.Client) *API {
|
|
25
|
-
`,` return &API{
|
|
26
|
-
`,`${t}
|
|
27
|
-
`,` }
|
|
28
|
-
`,`}
|
|
29
|
-
`,`
|
|
30
|
-
`,n.map(s=>ke(s)).join(`
|
|
31
|
-
|
|
32
|
-
`),`
|
|
33
|
-
`].join(""),i=e.length>0?`${N}package ${b}
|
|
34
|
-
|
|
35
|
-
${e}
|
|
36
|
-
`:`${N}package ${b}
|
|
37
|
-
|
|
38
|
-
// No typed argument or result schemas in this deployment.
|
|
39
|
-
`;return{[`${b}/api.go`]:a,[`${b}/models.go`]:i,"go.mod":[`// The generated Lunora Go SDK, with the transport vendored under ./lunora.
|
|
40
|
-
`,`//
|
|
41
|
-
`,`// A consuming module wires it in without a network fetch:
|
|
42
|
-
`,`//
|
|
43
|
-
`,`// require ${A} v0.0.0
|
|
44
|
-
`,`// replace ${A} => ./path/to/this/directory
|
|
45
|
-
`,`module ${A}
|
|
46
|
-
`,`
|
|
47
|
-
`,`go ${_e}
|
|
48
|
-
`].join("")}},Te={id:"go",quicktype:{lang:"go",rendererOptions:{"just-types":"true",package:b}},render:Ee,requires:[],vendor:[{from:"lunora",to:"lunora"}]},v="lunoraapi.models",R="lunoraapi/models",Oe=24,Ne=new Set(["abstract","as","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","false","final","finally","float","for","fromWire","fun","goto","if","implements","import","in","instanceof","int","interface","is","long","native","new","null","object","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","toWire","transient","true","try","typealias","typeof","val","var","void","volatile","when","while","wireValue"]),Ce=/[^A-Za-z0-9]+/gu,We=/([a-z0-9])([A-Z])/gu,Le=/^[A-Za-z]/u,Me=/^[A-Z]/u;class ie extends Error{}const y=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0,Ve=e=>{const n=e.anyOf??e.oneOf;if(!Array.isArray(n)||n.length===0)return;const r=n.map(t=>y(t)?.const);if(r.every(t=>typeof t=="string"))return[...new Set(r)].toSorted((t,a)=>t.localeCompare(a))},se=e=>{const n=e.anyOf??e.oneOf;if(!Array.isArray(n)||n.length!==2)return e;const r=n.filter(t=>y(t)?.type!=="null");return r.length===1?y(r[0])??e:e},Re=e=>{const n=o(e),r=n.charAt(0).toLowerCase()+n.slice(1),t=Le.test(r)?r:`value${n}`;return Ne.has(t)?`${t}_`:t},De=e=>{const n=e.replaceAll(We,"$1_$2").replaceAll(Ce,"_").toUpperCase().split("_").filter(r=>r.length>0).join("_");return Me.test(n)?n:`VALUE_${n}`},oe=(e,n)=>{if(!n.has(e))return n.add(e),e;let r=2;for(;n.has(`${e}${String(r)}`);)r+=1;return n.add(`${e}${String(r)}`),`${e}${String(r)}`},z=(e,n)=>{if(e.has(n.name))throw new ie(`sdk: two schemas both produce the JVM model "${n.name}"`);e.set(n.name,n)},Pe=(e,n,r,t,a)=>{const i=new Set(Array.isArray(n)?n.filter(u=>typeof u=="string"):[]),s=new Set;return Object.entries(e).map(([u,m])=>{const $=y(m)??{},c=!i.has(u);return{name:oe(Re(u),s),nullable:!c&&se($)!==$,optional:c,type:w($,`${r}${o(u)}`,t+1,a),wireKey:u}})},w=(e,n,r,t)=>{if(r>=Oe)return{kind:"unknown"};const a=Ve(e);if(a!==void 0){const $=new Set;return z(t,{constants:a.map(c=>({name:oe(De(c),$),wireValue:c})),kind:"enum",name:n}),{kind:"enum",name:n}}const i=se(e);if(i!==e)return w(i,n,r+1,t);const s=y(e.properties);if(s!==void 0)return z(t,{fields:Pe(s,e.required,n,r,t),kind:"class",name:n}),{kind:"class",name:n};const u=y(e.additionalProperties);if(u!==void 0)return{kind:"record",value:w(u,`${n}Value`,r+1,t)};const m=y(e.items);if(m!==void 0)return{item:w(m,`${n}Item`,r+1,t),kind:"list"};switch(e.type){case"boolean":return{kind:"boolean"};case"integer":case"number":return{kind:"number"};case"string":return{kind:"string"};default:return{kind:"unknown"}}},le=e=>{const n=new Map;for(const r of ae(e)){if(y(r.schema.properties)===void 0)continue;const t=new Map;try{w(r.schema,r.name,0,t)}catch(a){if(a instanceof ie)continue;throw a}if(![...t.keys()].some(a=>n.has(a)))for(const[a,i]of t)n.set(a,i)}return[...n.values()].toSorted((r,t)=>r.name.localeCompare(t.name))},T=e=>[`// GENERATED by \`lunora sdk generate --lang ${e}\` — do not edit.`,"// Run the command again to regenerate."],S=e=>{switch(e.kind){case"boolean":return"Boolean";case"class":case"enum":return e.name;case"list":return`java.util.List<${S(e.item)}>`;case"number":return"Double";case"record":return`java.util.Map<String, ${S(e.value)}>`;case"string":return"String";default:return"Object"}},D=e=>{switch(e.kind){case"class":case"enum":return!0;case"list":return D(e.item);case"record":return D(e.value);default:return!1}},P=(e,n,r)=>{if(!D(e))return n;const t=`item${String(r)}`;switch(e.kind){case"class":return`${n} == null ? null : ${n}.toWire()`;case"enum":return`${n} == null ? null : ${n}.toValue()`;case"list":return`ModelWire.writeList(${n}, ${t} -> ${P(e.item,t,r+1)})`;case"record":return`ModelWire.writeRecord(${n}, ${t} -> ${P(e.value,t,r+1)})`;default:return n}},I=(e,n,r)=>{const t=`item${String(r)}`;switch(e.kind){case"boolean":return`ModelWire.flag(${n})`;case"class":return`ModelWire.readObject(${n}, ${e.name}::fromWire)`;case"enum":return`ModelWire.readEnum(${n}, ${e.name}::forValue)`;case"list":return`ModelWire.readList(${n}, ${t} -> ${I(e.item,t,r+1)})`;case"number":return`ModelWire.number(${n})`;case"record":return`ModelWire.readRecord(${n}, ${t} -> ${I(e.value,t,r+1)})`;case"string":return`ModelWire.text(${n})`;default:return n}},Ie=e=>{const n=l(e.wireKey);return e.optional?[" /**",` * Wire key {@code ${n}} — OPTIONAL: null omits the key entirely, because`," * `v.optional` accepts the value or `undefined` and rejects an explicit null."," */"]:[` /** Wire key {@code ${n}}.${e.nullable?" Nullable: null is sent as an explicit null.":""} */`]},Ke=100,Fe=e=>{const n=e.fields.map(t=>`${S(t.type)} ${t.name}`),r=` public ${e.name}(${n.join(", ")}) {`;return r.length<=Ke?[r]:[` public ${e.name}(`,...n.map((t,a)=>` ${t}${a===n.length-1?") {":","}`)]},xe=e=>{const n=e.fields.flatMap(t=>{const a=`wire.put("${d(t.wireKey)}", ${P(t.type,`this.${t.name}`,0)});`;return t.optional?[` if (this.${t.name} != null) {`,` ${a}`," }"]:[` ${a}`]}),r=e.fields.map(t=>` ${I(t.type,`wire.get("${d(t.wireKey)}")`,0)}`);return[...T("java"),"",`package ${v};`,"","/**",` * The \`${e.name}\` model.`," *"," * <p>Field names are local; the keys {@link #toWire()} and {@link #fromWire(Object)} use are"," * the schema's own, emitted verbatim, so a renamed field cannot reach the wire."," */",`public final class ${e.name} {`,...e.fields.flatMap(t=>[...Ie(t),` public final ${S(t.type)} ${t.name};`,""]),...Fe(e),...e.fields.map(t=>` this.${t.name} = ${t.name};`)," }",""," /** This model as the wire-shaped map the transport encodes. */"," public java.util.Map<String, Object> toWire() {"," java.util.Map<String, Object> wire = new java.util.LinkedHashMap<>();",...n,""," return wire;"," }",""," /** Rebuild from a decoded wire value. */",` public static ${e.name} fromWire(Object value) {`," java.util.Map<String, Object> wire = ModelWire.object(value);","",...r.length===0?[` return new ${e.name}();`]:[` return new ${e.name}(`,`${r.join(`,
|
|
49
|
-
`)});`]," }","}",""].join(`
|
|
50
|
-
`)},qe=e=>[...T("java"),"",`package ${v};`,"",`/** The \`${e.name}\` union. Each constant keeps the wire string it encodes to. */`,`public enum ${e.name} {`,...e.constants.map((n,r)=>` ${n.name}("${d(n.wireValue)}")${r===e.constants.length-1?";":","}`),""," private final String value;","",` ${e.name}(String value) {`," this.value = value;"," }",""," /** The wire string this constant encodes to. */"," public String toValue() {"," return this.value;"," }",""," /** The constant a wire string decodes to. */",` public static ${e.name} forValue(String value) {`,` for (${e.name} candidate : values()) {`," if (candidate.value.equals(value)) {"," return candidate;"," }"," }","",` throw new IllegalArgumentException("${e.name}: unknown wire value " + value);`," }","}",""].join(`
|
|
51
|
-
`),He=[{lines:[' @SuppressWarnings("unchecked")'," static java.util.Map<String, Object> object(Object value) {"," return value instanceof java.util.Map"," ? (java.util.Map<String, Object>) value"," : new java.util.LinkedHashMap<String, Object>();"," }"],name:"object"},{lines:[" static String text(Object value) {"," return value instanceof String ? (String) value : null;"," }"],name:"text"},{lines:[" static Double number(Object value) {"," return value instanceof Number ? ((Number) value).doubleValue() : null;"," }"],name:"number"},{lines:[" static Boolean flag(Object value) {"," return value instanceof Boolean ? (Boolean) value : null;"," }"],name:"flag"},{lines:[" /** A nested model, or null when the payload carried no object there. */"," static <T> T readObject(Object value, java.util.function.Function<Object, T> read) {"," return value instanceof java.util.Map ? read.apply(value) : null;"," }"],name:"readObject"},{lines:[" /** An enum constant, or null when the payload carried no string there. */"," static <T> T readEnum(Object value, java.util.function.Function<String, T> read) {"," return value instanceof String ? read.apply((String) value) : null;"," }"],name:"readEnum"},{lines:[" static <T> java.util.List<T> readList("," Object value, java.util.function.Function<Object, T> read) {"," if (!(value instanceof java.util.List)) {"," return null;"," }",""," java.util.List<T> items = new java.util.ArrayList<T>();",""," for (Object item : (java.util.List<?>) value) {"," items.add(read.apply(item));"," }",""," return items;"," }"],name:"readList"},{lines:[" static <T> java.util.Map<String, T> readRecord("," Object value, java.util.function.Function<Object, T> read) {"," if (!(value instanceof java.util.Map)) {"," return null;"," }",""," java.util.Map<String, T> entries = new java.util.LinkedHashMap<String, T>();",""," for (java.util.Map.Entry<?, ?> entry : ((java.util.Map<?, ?>) value).entrySet()) {"," entries.put(String.valueOf(entry.getKey()), read.apply(entry.getValue()));"," }",""," return entries;"," }"],name:"readRecord"},{lines:[" static <T> java.util.List<Object> writeList("," java.util.List<T> items, java.util.function.Function<T, Object> write) {"," if (items == null) {"," return null;"," }",""," java.util.List<Object> encoded = new java.util.ArrayList<Object>(items.size());",""," for (T item : items) {"," encoded.add(write.apply(item));"," }",""," return encoded;"," }"],name:"writeList"},{lines:[" static <T> java.util.Map<String, Object> writeRecord("," java.util.Map<String, T> entries, java.util.function.Function<T, Object> write) {"," if (entries == null) {"," return null;"," }",""," java.util.Map<String, Object> encoded = new java.util.LinkedHashMap<String, Object>();",""," for (java.util.Map.Entry<String, T> entry : entries.entrySet()) {"," encoded.put(entry.getKey(), write.apply(entry.getValue()));"," }",""," return encoded;"," }"],name:"writeRecord"}],Ge=e=>{const n=He.filter(r=>e.includes(`ModelWire.${r.name}(`));return[...T("java"),"",`package ${v};`,"","/** Wire readers and writers shared by the generated models. */","final class ModelWire {"," private ModelWire() {}",...n.flatMap(r=>["",...r.lines]),"}",""].join(`
|
|
52
|
-
`)},Ue=e=>{const n=le(e);if(n.length===0)return{};const r={};for(const t of n)r[`${R}/${t.name}.java`]=t.kind==="enum"?qe(t):xe(t);return{[`${R}/ModelWire.java`]:Ge(Object.values(r).join(`
|
|
53
|
-
`)),...r}},K=e=>{switch(e.kind){case"boolean":return"Boolean";case"class":case"enum":return e.name;case"list":return`List<${K(e.item)}>`;case"number":return"Double";case"record":return`Map<String, ${K(e.value)}>`;case"string":return"String";default:return"WireValue"}},j=(e,n,r)=>{const t=`item${String(r)}`,a=`entry${String(r)}`;switch(e.kind){case"boolean":return`WireValue.Bool(${n})`;case"class":return`${n}.toWire()`;case"enum":return`WireValue.Text(${n}.wireValue)`;case"list":return`WireValue.Arr(${n}.map { ${t} -> ${j(e.item,t,r+1)} })`;case"number":return`WireValue.Num(${n})`;case"record":return`WireValue.Obj(${n}.map { ${a} -> ${a}.key to ${j(e.value,`${a}.value`,r+1)} })`;case"string":return`WireValue.Text(${n})`;default:return n}},F=(e,n,r,t)=>`wireNeed(${ue(e,n,r,t)}, "${g(t)}")`,ue=(e,n,r,t)=>{const a=`item${String(r)}`,i=`entry${String(r)}`;switch(e.kind){case"boolean":return`wireBool(${n})`;case"class":return`wireObj(${n})?.let { ${a} -> ${e.name}.fromWire(${a}) }`;case"enum":return`wireText(${n})?.let { ${a} -> ${e.name}.forValue(${a}) }`;case"list":return`wireArr(${n})?.items?.map { ${a} -> ${F(e.item,a,r+1,`${t}[]`)} }`;case"number":return`wireNum(${n})`;case"record":return`wireObj(${n})?.fields?.associate { ${i} -> ${i}.first to ${F(e.value,`${i}.second`,r+1,`${t}{}`)} }`;case"string":return`wireText(${n})`;default:return n}},Be=e=>{const n=e.fields.map(a=>{const i=l(a.wireKey);return[...a.optional?[" /**",` * Wire key \`${i}\` — OPTIONAL: null omits the key entirely, because`," * `v.optional` accepts the value or `undefined` and rejects an explicit null."," */"]:[` /** Wire key \`${i}\`.${a.nullable?" Nullable: null is sent as an explicit null.":""} */`],` val ${a.name}: ${K(a.type)}${a.optional||a.nullable?"?":""}${a.optional?" = null":""},`]}),r=e.fields.map(a=>{const i=g(a.wireKey);return a.optional?` ${a.name}?.let { add("${i}" to ${j(a.type,"it",0)}) }`:a.nullable?` add("${i}" to (${a.name}?.let { ${j(a.type,"it",0)} } ?: WireValue.Null))`:` add("${i}" to ${j(a.type,a.name,0)})`}),t=e.fields.map(a=>{const i=`wireField(value, "${g(a.wireKey)}")`,s=a.optional||a.nullable?ue(a.type,i,0,a.wireKey):F(a.type,i,0,a.wireKey);return` ${a.name} = ${s},`});return["/**",` * The \`${e.name}\` model.`," *"," * Property names are local; the keys [toWire] and [fromWire] use are the schema's own,"," * emitted verbatim, so a renamed property cannot reach the wire."," */",`class ${e.name}(`,...n.flat(),") {"," /** This model as the wire-shaped object the transport encodes. */"," fun toWire(): WireValue ="," WireValue.Obj("," buildList {",...r," },"," )",""," companion object {"," /** Rebuild from a decoded wire value. */",` fun fromWire(value: WireValue): ${e.name} =`,` ${e.name}(`,...t," )"," }","}"]},ze=e=>[`/** The \`${e.name}\` union. Each entry keeps the wire string it encodes to. */`,`enum class ${e.name}(val wireValue: String) {`,...e.constants.map(n=>` ${n.name}("${g(n.wireValue)}"),`)," ;",""," companion object {"," /** The entry a wire string decodes to. */",` fun forValue(value: String): ${e.name} =`," entries.firstOrNull { it.wireValue == value }",` ?: throw IllegalArgumentException("${e.name}: unknown wire value " + value)`," }","}"],Ye=[{lines:["private fun wireField(value: WireValue, key: String): WireValue? ="," (value as? WireValue.Obj)?.fields?.firstOrNull { it.first == key }?.second"],name:"wireField"},{lines:["private fun wireText(value: WireValue?): String? = (value as? WireValue.Text)?.value"],name:"wireText"},{lines:["private fun wireNum(value: WireValue?): Double? = (value as? WireValue.Num)?.value"],name:"wireNum"},{lines:["private fun wireBool(value: WireValue?): Boolean? = (value as? WireValue.Bool)?.value"],name:"wireBool"},{lines:["private fun wireArr(value: WireValue?): WireValue.Arr? = value as? WireValue.Arr"],name:"wireArr"},{lines:["private fun wireObj(value: WireValue?): WireValue.Obj? = value as? WireValue.Obj"],name:"wireObj"},{lines:["/** A required field the payload omitted or mistyped is a contract violation, not a null. */","private fun <T> wireNeed(read: T?, label: String): T =",' read ?: throw WireFormatException("lunora: the wire payload is missing or mistyped " + label)'],name:"wireNeed"}],Je=e=>{const n=le(e);if(n.length===0)return{};const r=n.flatMap(s=>[...s.kind==="enum"?ze(s):Be(s),""]),t=Ye.filter(s=>r.some(u=>u.includes(`${s.name}(`))),a=t.flatMap((s,u)=>u===0?[...s.lines]:["",...s.lines]),i=[...T("kotlin"),"",`package ${v}`,"",...t.some(s=>s.name==="wireNeed")?["import dev.lunora.WireFormatException"]:[],"import dev.lunora.WireValue","",...r,...a,""].join(`
|
|
54
|
-
`);return{[`${R}/Models.kt`]:i}},Ze=`${f("java").map(e=>`// ${e}`).join(`
|
|
55
|
-
`)}
|
|
56
|
-
|
|
57
|
-
`,Y="lunoraapi",Xe=new Set(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while"]),x=e=>{const n=o(e),r=n.charAt(0).toLowerCase()+n.slice(1);return Xe.has(r)?`${r}_`:r},Qe=e=>`Client.Verb.${e.toUpperCase()}`,ce=e=>e.argsType===void 0?{payload:"args",type:"java.util.Map<String, Object>"}:{payload:"args == null ? null : args.toWire()",type:e.argsType},J=e=>{const n=ce(e),r=`client.call(
|
|
58
|
-
${Qe(e.verb)}, "${d(e.functionPath)}", ${n.payload}, shardKey)`;return[` /** ${l(e.summary)} */`,` public ${e.resultType??"Object"} ${x(e.functionName)}(${n.type} args, String shardKey) {`,` return ${e.resultType===void 0?r:`${e.resultType}.fromWire(${r})`};`," }"].join(`
|
|
59
|
-
`)},en=e=>{const n=ce(e);return[` /** live ${l(e.summary)} — re-runs on every write to the tables it reads. */`,` public Runnable subscribe${o(e.functionName)}(`,` ${n.type} args,`," java.util.function.Consumer<Object> onData,"," java.util.function.Consumer<Client.SubscriptionError> onError,"," String shardKey) {"," return client.subscribe(",` "${d(e.functionPath)}", ${n.payload}, onData, onError, shardKey);`," }"].join(`
|
|
60
|
-
`)},nn=e=>{const n=`${o(e.name)}Api`,r=e.methods.map(t=>t.verb==="query"?`${J(t)}
|
|
61
|
-
|
|
62
|
-
${en(t)}`:J(t)).join(`
|
|
63
|
-
|
|
64
|
-
`);return[` /** Functions declared in \`${l(e.name)}\`. */`,` public static final class ${n} {`," private final Client client;","",` ${n}(Client client) {`," this.client = client;"," }","",r.replaceAll(/^ {4}/gmu," ")," }"].join(`
|
|
65
|
-
`)},rn=({namespaces:e})=>{const n=e.map(i=>` public final ${o(i.name)}Api ${x(i.name)};`).join(`
|
|
66
|
-
`),r=e.map(i=>` this.${x(i.name)} = new ${o(i.name)}Api(client);`).join(`
|
|
67
|
-
`),t=H(e).map(i=>`import ${v}.${i};
|
|
68
|
-
`),a=[Ze,`package ${Y};
|
|
69
|
-
`,`
|
|
70
|
-
`,`import dev.lunora.Client;
|
|
71
|
-
`,...t,`
|
|
72
|
-
`,"/** Typed entry point: `new Api(client).<namespace>.<function>(args, shardKey)`. */\n",`public final class Api {
|
|
73
|
-
`,n.length>0?`${n}
|
|
74
|
-
|
|
75
|
-
`:"",` public Api(Client client) {
|
|
76
|
-
`,r.length>0?`${r}
|
|
77
|
-
`:` // No functions in this deployment.
|
|
78
|
-
`,` }
|
|
79
|
-
`,`
|
|
80
|
-
`,e.map(i=>nn(i)).join(`
|
|
81
|
-
|
|
82
|
-
`),`
|
|
83
|
-
}
|
|
84
|
-
`].join("");return{[`${Y}/Api.java`]:a}},tn={id:"java",render:rn,renderModels:Ue,requires:[],vendor:[{from:"src/dev/lunora",to:"dev/lunora"}]},an=`${f("kotlin").map(e=>`// ${e}`).join(`
|
|
85
|
-
`)}
|
|
86
|
-
|
|
87
|
-
`,Z="lunoraapi",sn=new Set(["as","break","class","continue","do","else","false","for","fun","if","in","interface","is","null","object","package","return","super","this","throw","true","try","typealias","typeof","val","var","when","while"]),pe=e=>{const n=o(e),r=n.charAt(0).toLowerCase()+n.slice(1);return sn.has(r)?`\`${r}\``:r},on=e=>`Verb.${e.toUpperCase()}`,de=e=>e.argsType===void 0?{declaration:"args: WireValue? = null",payload:"args"}:{declaration:`args: ${e.argsType}`,payload:"args.toWire()"},X=e=>{const n=de(e),r=`client.call(${on(e.verb)}, "${g(e.functionPath)}", ${n.payload}, shardKey)`;return[` /** ${l(e.summary)} */`,` fun ${pe(e.functionName)}(${n.declaration}, shardKey: String? = null): ${e.resultType??"WireValue"} =`,` ${e.resultType===void 0?r:`${e.resultType}.fromWire(${r})`}`].join(`
|
|
88
|
-
`)},ln=e=>{const n=de(e);return[` /** live ${l(e.summary)} — re-runs on every write to the tables it reads. */`,` fun subscribe${o(e.functionName)}(`,` ${n.declaration},`," onData: ((WireValue) -> Unit)?,"," onError: ((SubscriptionError) -> Unit)? = null,"," shardKey: String? = null,"," ): () -> Unit =",` client.subscribe("${g(e.functionPath)}", ${n.payload}, onData, onError, shardKey)`].join(`
|
|
89
|
-
`)},un=e=>{const n=`${o(e.name)}Api`,r=e.methods.map(t=>t.verb==="query"?`${X(t)}
|
|
90
|
-
|
|
91
|
-
${ln(t)}`:X(t)).join(`
|
|
92
|
-
|
|
93
|
-
`);return[`/** Functions declared in \`${l(e.name)}\`. */`,`class ${n}(private val client: Client) {`,r,"}"].join(`
|
|
94
|
-
`)},cn=({namespaces:e})=>{const n=e.map(i=>` val ${pe(i.name)}: ${o(i.name)}Api = ${o(i.name)}Api(client)`).join(`
|
|
95
|
-
`),r=e.flatMap(i=>i.methods),t=[`import dev.lunora.Client
|
|
96
|
-
`,...r.some(i=>i.verb==="query")?[`import dev.lunora.SubscriptionError
|
|
97
|
-
`]:[],`import dev.lunora.Verb
|
|
98
|
-
`,...r.some(i=>i.argsType===void 0||i.resultType===void 0)?[`import dev.lunora.WireValue
|
|
99
|
-
`]:[],...H(e).map(i=>`import ${v}.${i}
|
|
100
|
-
`)],a=[an,`package ${Z}
|
|
101
|
-
`,`
|
|
102
|
-
`,...t,`
|
|
103
|
-
`,e.map(i=>un(i)).join(`
|
|
104
|
-
|
|
105
|
-
`),`
|
|
106
|
-
|
|
107
|
-
`,"/** Typed entry point: `Api(client).<namespace>.<function>(args)`. */\n",`class Api(client: Client) {
|
|
108
|
-
`,n.length>0?`${n}
|
|
109
|
-
`:` init { require(true) { client } }
|
|
110
|
-
`,`}
|
|
111
|
-
`].join("");return{[`${Z}/Api.kt`]:a}},pn={id:"kotlin",render:cn,renderModels:Je,requires:[],vendor:[{from:"src",to:"dev/lunora"}]},dn=new Set(["and","as","assert","async","await","break","class","continue","def","del","elif","else","except","False","finally","for","from","global","if","import","in","is","lambda","None","nonlocal","not","or","pass","raise","return","True","try","while","with","yield"]),h=`"""${f("python").join(`
|
|
112
|
-
|
|
113
|
-
`)}
|
|
114
|
-
"""
|
|
115
|
-
|
|
116
|
-
`,C="lunora_api",U=e=>{const n=G(e);return dn.has(n)?`${n}_`:n},$e=e=>p(e,{none:"{}",typed:()=>"args.to_dict()",untyped:"args"}),$n=(e,n,r,t)=>p(e,{none:n,typed:r,untyped:t}),Q=e=>{const n=e.resultType??"Any",r=$n(e,"self",i=>`self, args: ${i}`,"self, args: Any"),t=$e(e),a=`await self._client.${e.verb}("${d(e.functionPath)}", ${t}, shard_key)`;return[` async def ${U(e.functionName)}(${r}, *, shard_key: Optional[str] = None) -> ${n}:`,` """${l(e.summary)}"""`,` ${e.resultType===void 0?`return ${a}`:`return ${e.resultType}.from_dict(${a})`}`].join(`
|
|
117
|
-
`)},mn=e=>{const n=$e(e),r=["self",...p(e,{none:[],typed:t=>[`args: ${t}`],untyped:["args: Any"]}),"on_data: Callback","on_error: Optional[ErrorCallback] = None","*","shard_key: Optional[str] = None"];return[` def subscribe_${U(e.functionName)}(`,...r.map(t=>` ${t},`)," ) -> Unsubscribe:",` """live ${l(e.summary)} — re-runs on every write to the tables it reads."""`,` return self._client.subscribe("${d(e.functionPath)}", ${n}, on_data, on_error, shard_key)`].join(`
|
|
118
|
-
`)},yn=e=>{const n=e.methods.map(r=>r.verb==="query"?`${Q(r)}
|
|
119
|
-
|
|
120
|
-
${mn(r)}`:Q(r)).join(`
|
|
121
|
-
|
|
122
|
-
`);return[`class ${o(e.name)}Api:`,` """Functions declared in \`${l(e.name)}\`."""`,""," def __init__(self, client: LunoraClient) -> None:"," self._client = client","",n].join(`
|
|
123
|
-
`)},fn=e=>e.replaceAll(/^([ \t]*)except:$/gmu,"$1except Exception:"),bn=({models:e,namespaces:n})=>{const r=H(n),t=r.length>0?`from .models import ${r.join(", ")}
|
|
124
|
-
`:"",i=M(n).some(c=>c.verb==="query")?"Callback, ErrorCallback, LunoraClient, Unsubscribe":"LunoraClient",s=M(n).some(c=>c.resultType===void 0),u=n.map(c=>` self.${U(c.name)} = ${o(c.name)}Api(client)`).join(`
|
|
125
|
-
`),m=[h,`from typing import ${s?"Any, Optional":"Optional"}
|
|
126
|
-
`,`
|
|
127
|
-
`,`from lunora.client import ${i}
|
|
128
|
-
`,t,`
|
|
129
|
-
|
|
130
|
-
`,n.map(c=>yn(c)).join(`
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
`),`
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
`,`class Api:
|
|
137
|
-
`,' """Typed entry point: `Api(client).<namespace>.<function>(args)`."""\n',`
|
|
138
|
-
`,` def __init__(self, client: LunoraClient) -> None:
|
|
139
|
-
`,u.length>0?`${u}
|
|
140
|
-
`:` pass
|
|
141
|
-
`].join(""),$=["Api",...n.map(c=>`${o(c.name)}Api`)];return{[`${C}/__init__.py`]:[h,`from .api import ${$.join(", ")}
|
|
142
|
-
`,`
|
|
143
|
-
`,`__all__ = [${$.map(c=>`"${c}"`).join(", ")}]
|
|
144
|
-
`].join(""),[`${C}/api.py`]:m,[`${C}/models.py`]:e.length>0?`${h}${fn(e)}
|
|
145
|
-
`:`${h}# No typed argument or result schemas in this deployment.
|
|
146
|
-
`}},gn={id:"python",quicktype:{lang:"python",rendererOptions:{"python-version":"3.7"}},render:bn,requires:[],vendor:[{from:"lunora",to:"lunora"}]},W=`${f("ruby").map(e=>`# ${e}`).join(`
|
|
147
|
-
`)}
|
|
148
|
-
|
|
149
|
-
`,vn=new Set(["alias","and","begin","break","case","class","def","defined?","do","else","elsif","end","ensure","false","for","if","in","module","next","nil","not","or","redo","rescue","retry","return","self","super","then","true","undef","unless","until","when","while","yield"]),me=e=>d(e).replaceAll("#","\\#"),k=e=>{const n=G(e);return vn.has(n)?`${n}_`:n},wn=` def self.wire_args(model)
|
|
150
|
-
drop_nils(model.to_dynamic)
|
|
151
|
-
end
|
|
152
|
-
|
|
153
|
-
def self.drop_nils(value)
|
|
154
|
-
case value
|
|
155
|
-
when ::Hash then value.each_with_object({}) { |(key, item), out| out[key] = drop_nils(item) unless item.nil? }
|
|
156
|
-
when ::Array then value.map { |item| drop_nils(item) }
|
|
157
|
-
else value
|
|
158
|
-
end
|
|
159
|
-
end
|
|
160
|
-
|
|
161
|
-
`,ye=e=>p(e,{none:"{}",typed:()=>"LunoraApi.wire_args(args)",untyped:"args"}),ee=e=>{const n=e.argsType===void 0&&!e.takesArgs?"shard_key: nil":"args, shard_key: nil",r=ye(e),t=`@client.${e.verb}("${me(e.functionPath)}", ${r}, shard_key)`,a=e.resultType===void 0?t:`${e.resultType}.from_dynamic!(${t})`;return[` # ${l(e.summary)}`,` def ${k(e.functionName)}(${n})`,` ${a}`," end"].join(`
|
|
162
|
-
`)},jn=e=>{const n=e.argsType===void 0&&!e.takesArgs?"on_data, on_error = nil, shard_key: nil":"args, on_data, on_error = nil, shard_key: nil",r=ye(e);return[` # live ${l(e.summary)} — re-runs on every write to the tables it reads.`,` def subscribe_${k(e.functionName)}(${n})`,` @client.subscribe("${me(e.functionPath)}", ${r}, on_data, on_error, shard_key)`," end"].join(`
|
|
163
|
-
`)},hn=e=>{const n=e.methods.map(r=>r.verb==="query"?`${ee(r)}
|
|
164
|
-
|
|
165
|
-
${jn(r)}`:ee(r)).join(`
|
|
166
|
-
|
|
167
|
-
`);return[` # Functions declared in \`${l(e.name)}\`.`,` class ${o(e.name)}Api`," def initialize(client)"," @client = client"," end","",n," end"].join(`
|
|
168
|
-
`)},An=({models:e,namespaces:n})=>{const r=n.map(i=>`:${k(i.name)}`).join(", "),t=n.map(i=>` @${k(i.name)} = ${o(i.name)}Api.new(client)`).join(`
|
|
169
|
-
`);return{"api.rb":[`# frozen_string_literal: true
|
|
170
|
-
|
|
171
|
-
`,W,`require_relative "models"
|
|
172
|
-
`,`
|
|
173
|
-
`,`module LunoraApi
|
|
174
|
-
`,M(n).some(i=>i.argsType!==void 0)?wn:"",n.map(i=>hn(i)).join(`
|
|
175
|
-
|
|
176
|
-
`),`
|
|
177
|
-
|
|
178
|
-
`," # Typed entry point: `Api.new(client).<namespace>.<function>(args)`.\n",` class Api
|
|
179
|
-
`,r.length>0?` attr_reader ${r}
|
|
180
|
-
|
|
181
|
-
`:"",` def initialize(client)
|
|
182
|
-
`,t.length>0?`${t}
|
|
183
|
-
`:` @client = client
|
|
184
|
-
`,` end
|
|
185
|
-
`,` end
|
|
186
|
-
`,`end
|
|
187
|
-
`].join(""),"models.rb":e.length>0?`# frozen_string_literal: true
|
|
188
|
-
|
|
189
|
-
${W}${e}
|
|
190
|
-
`:`# frozen_string_literal: true
|
|
191
|
-
|
|
192
|
-
${W}# No typed argument or result schemas in this deployment.
|
|
193
|
-
`}},_n={id:"ruby",quicktype:{lang:"ruby",rendererOptions:{}},render:An,requires:["dry-struct + dry-types (gems, required by the generated models)"],vendor:[{from:"lib/lunora.rb",to:"lunora.rb"},{from:"lib/lunora",to:"lunora"}]},_=`${f("rust").map(e=>`// ${e}`).join(`
|
|
194
|
-
`)}
|
|
195
|
-
|
|
196
|
-
`,Sn=`${_}pub mod api;
|
|
197
|
-
pub mod models;
|
|
198
|
-
`,kn=`# The generated Lunora Rust SDK, with the transport vendored under ./lunora.
|
|
199
|
-
#
|
|
200
|
-
# Add to a consuming crate:
|
|
201
|
-
#
|
|
202
|
-
# lunora-api = { path = "sdk/rust" }
|
|
203
|
-
|
|
204
|
-
[package]
|
|
205
|
-
name = "lunora-api"
|
|
206
|
-
version = "0.1.0"
|
|
207
|
-
edition = "2021"
|
|
208
|
-
publish = false
|
|
209
|
-
|
|
210
|
-
# Its own workspace root, so a consumer whose project IS a workspace does not
|
|
211
|
-
# adopt this directory as a member (which then fails to build on its own).
|
|
212
|
-
[workspace]
|
|
213
|
-
|
|
214
|
-
[dependencies]
|
|
215
|
-
lunora = { path = "lunora" }
|
|
216
|
-
serde = { version = "1", features = ["derive"] }
|
|
217
|
-
serde_json = "1"
|
|
218
|
-
`,En=new Set(["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","static","struct","super","trait","true","try","type","typeof","unsafe","unsized","use","virtual","where","while","yield"]),E=e=>{const n=G(e);return En.has(n)?`r#${n}`:n},Tn=e=>`Verb::${o(e)}`,ne=e=>{const n=p(e,{none:"&self, shard_key: Option<&str>",typed:a=>`&self, args: &${a}, shard_key: Option<&str>`,untyped:"&self, args: &WireValue, shard_key: Option<&str>"}),r=p(e,{none:"&WireValue::Object(Vec::new())",typed:()=>"&from_model_json(&serde_json::to_value(args).map_err(|error| ClientError::Transport(error.to_string()))?)",untyped:"args"}),t=`self.client.call(${Tn(e.verb)}, "${d(e.functionPath)}", ${r}, shard_key)`;return e.resultType===void 0?[` /// ${l(e.summary)}`,` pub fn ${E(e.functionName)}(${n}) -> Result<WireValue, ClientError> {`,` ${t}`," }"].join(`
|
|
219
|
-
`):[` /// ${l(e.summary)}`,` pub fn ${E(e.functionName)}(${n}) -> Result<${e.resultType}, ClientError> {`,` let raw = ${t}?;`," let json = encode_wire(&raw).map_err(ClientError::Wire)?;"," serde_json::from_value(json).map_err(|error| ClientError::Transport(error.to_string()))"," }"].join(`
|
|
220
|
-
`)},On=e=>{const n=p(e,{none:"",typed:t=>`args: &${t}, `,untyped:"args: &WireValue, "}),r=p(e,{none:"WireValue::Object(Vec::new())",typed:()=>"from_model_json(&serde_json::to_value(args).map_err(|error| ClientError::Transport(error.to_string()))?)",untyped:"args.clone()"});return[` /// live ${l(e.summary)} — re-runs on every write to the tables it reads.`,` pub fn subscribe_${E(e.functionName)}(`," &mut self,",` ${n}on_data: DataHandler,`," on_error: ErrorHandler,"," shard_key: Option<&str>,"," ) -> Result<String, ClientError> {"," let _ = shard_key;",` Ok(self.client.subscribe("${d(e.functionPath)}", ${r}, on_data, on_error))`," }"].join(`
|
|
221
|
-
`)},Nn=e=>{const n=`${o(e.name)}Api`,r=e.methods.map(t=>t.verb==="query"?`${ne(t)}
|
|
222
|
-
|
|
223
|
-
${On(t)}`:ne(t)).join(`
|
|
224
|
-
|
|
225
|
-
`);return[`/// Functions declared in \`${l(e.name)}\`.`,`pub struct ${n}<'client> {`," client: &'client mut Client,","}","",`impl<'client> ${n}<'client> {`,r,"}"].join(`
|
|
226
|
-
`)},Cn=({models:e,namespaces:n})=>{const r=n.map(a=>[` /// Functions declared in \`${l(a.name)}\`.`,` pub fn ${E(a.name)}(&mut self) -> ${o(a.name)}Api<'_> {`,` ${o(a.name)}Api { client: self.client }`," }"].join(`
|
|
227
|
-
`)).join(`
|
|
228
|
-
|
|
229
|
-
`),t=[_,`#![allow(dead_code, unused_imports)]
|
|
230
|
-
`,`
|
|
231
|
-
`,`use lunora::client::{Client, ClientError, DataHandler, ErrorHandler, Verb};
|
|
232
|
-
`,`use lunora::wire::{encode_wire, from_model_json, WireValue};
|
|
233
|
-
`,`
|
|
234
|
-
`,`use crate::models::*;
|
|
235
|
-
`,`
|
|
236
|
-
`,n.map(a=>Nn(a)).join(`
|
|
237
|
-
|
|
238
|
-
`),`
|
|
239
|
-
|
|
240
|
-
`,"/// Typed entry point: `Api::new(&client).<namespace>().<function>(args)`.\n",`pub struct Api<'client> {
|
|
241
|
-
`,` client: &'client mut Client,
|
|
242
|
-
`,`}
|
|
243
|
-
`,`
|
|
244
|
-
`,`impl<'client> Api<'client> {
|
|
245
|
-
`,` pub fn new(client: &'client mut Client) -> Self {
|
|
246
|
-
`,` Self { client }
|
|
247
|
-
`,` }
|
|
248
|
-
`,r.length>0?`
|
|
249
|
-
${r}
|
|
250
|
-
`:"",`}
|
|
251
|
-
`].join("");return{"Cargo.toml":kn,"src/api.rs":t,"src/lib.rs":Sn,"src/models.rs":e.length>0?`${_}#![allow(dead_code)]
|
|
252
|
-
|
|
253
|
-
${e}
|
|
254
|
-
`:`${_}#![allow(dead_code)]
|
|
255
|
-
|
|
256
|
-
// No typed argument or result schemas in this deployment.
|
|
257
|
-
`}},Wn={id:"rust",quicktype:{lang:"rust",rendererOptions:{"just-types":"true"}},render:Cn,requires:["serde (derive) + serde_json — declared in the emitted Cargo.toml, fetched by cargo"],vendor:[{from:"Cargo.toml",to:"lunora/Cargo.toml"},{from:"src",to:"lunora/src"}]},L=`${f("swift").map(e=>`// ${e}`).join(`
|
|
258
|
-
`)}
|
|
259
|
-
|
|
260
|
-
`,re="Sources/LunoraApi",Ln=`// swift-tools-version:5.9
|
|
261
|
-
|
|
262
|
-
import PackageDescription
|
|
263
|
-
|
|
264
|
-
// The generated Lunora Swift SDK, with the transport vendored under
|
|
265
|
-
// Sources/Lunora. Add to a consuming package — where "swift" below is the NAME OF
|
|
266
|
-
// THE DIRECTORY THIS FILE IS IN, which is how SwiftPM identifies a local path
|
|
267
|
-
// dependency. It ignores the "name:" field for that, and a bare product name in a
|
|
268
|
-
// target's dependencies does not resolve at all, so the directory name is the one
|
|
269
|
-
// spelling that works:
|
|
270
|
-
//
|
|
271
|
-
// dependencies: [.package(path: "sdk/swift")],
|
|
272
|
-
// targets: [
|
|
273
|
-
// .target(
|
|
274
|
-
// name: "YourTarget",
|
|
275
|
-
// dependencies: [.product(name: "LunoraApi", package: "swift")]
|
|
276
|
-
// )
|
|
277
|
-
// ]
|
|
278
|
-
let package = Package(
|
|
279
|
-
name: "LunoraSdk",
|
|
280
|
-
platforms: [.macOS(.v12), .iOS(.v15)],
|
|
281
|
-
products: [
|
|
282
|
-
.library(name: "LunoraApi", targets: ["LunoraApi"]),
|
|
283
|
-
.library(name: "Lunora", targets: ["Lunora"]),
|
|
284
|
-
],
|
|
285
|
-
targets: [
|
|
286
|
-
.target(name: "Lunora"),
|
|
287
|
-
.target(name: "LunoraApi", dependencies: ["Lunora"]),
|
|
288
|
-
]
|
|
289
|
-
)
|
|
290
|
-
`,Mn=new Set(["as","associatedtype","borrowing","break","case","catch","class","consuming","continue","default","defer","deinit","do","else","enum","extension","fallthrough","false","fileprivate","for","func","guard","if","import","in","init","inout","internal","is","let","nil","nonisolated","open","operator","precedencegroup","private","protocol","public","repeat","rethrows","return","self","static","struct","subscript","super","switch","throw","throws","true","try","typealias","var","where","while"]),q=e=>{const n=o(e),r=n.charAt(0).toLowerCase()+n.slice(1);return Mn.has(r)?`\`${r}\``:r},fe=e=>p(e,{none:"nil",typed:()=>"try LunoraClient.wireValue(args)",untyped:"args"}),te=e=>{const n=p(e,{none:"shardKey: String? = nil",typed:s=>`_ args: ${s}, shardKey: String? = nil`,untyped:"_ args: Any, shardKey: String? = nil"}),r=fe(e),t=e.resultType??"Any",a=`try client.${e.verb}("${d(e.functionPath)}", args: ${r}, shardKey: shardKey)`,i=e.resultType===void 0?`return ${a}`:[`let raw = ${a}`," let data = try JSONSerialization.data(withJSONObject: raw, options: [.fragmentsAllowed])",` return try JSONDecoder().decode(${e.resultType}.self, from: data)`].join(`
|
|
291
|
-
`);return[` /// ${l(e.summary)}`,` public func ${q(e.functionName)}(${n}) throws -> ${t} {`,` ${i}`," }"].join(`
|
|
292
|
-
`)},Vn=e=>{const n=p(e,{none:"",typed:t=>`_ args: ${t}, `,untyped:"_ args: Any, "}),r=fe(e);return[` /// live ${l(e.summary)} — re-runs on every write to the tables it reads.`," @discardableResult",` public func subscribe${o(e.functionName)}(`,` ${n}onData: ((Any) -> Void)?,`," onError: ((LunoraSubscriptionError) -> Void)? = nil,"," shardKey: String? = nil"," ) throws -> LunoraUnsubscribe {",` client.subscribe("${d(e.functionPath)}", args: ${r}, onData: onData, onError: onError, shardKey: shardKey)`," }"].join(`
|
|
293
|
-
`)},Rn=e=>{const n=`${o(e.name)}API`,r=e.methods.map(t=>t.verb==="query"?`${te(t)}
|
|
294
|
-
|
|
295
|
-
${Vn(t)}`:te(t)).join(`
|
|
296
|
-
|
|
297
|
-
`);return[`/// Functions declared in \`${l(e.name)}\`.`,`public struct ${n} {`," let client: LunoraClient","",r,"}"].join(`
|
|
298
|
-
`)},Dn=({models:e,namespaces:n})=>{const r=n.map(i=>` public let ${q(i.name)}: ${o(i.name)}API`).join(`
|
|
299
|
-
`),t=n.map(i=>` ${q(i.name)} = ${o(i.name)}API(client: client)`).join(`
|
|
300
|
-
`),a=[L,`import Foundation
|
|
301
|
-
`,`import Lunora
|
|
302
|
-
`,`
|
|
303
|
-
`,n.map(i=>Rn(i)).join(`
|
|
304
|
-
|
|
305
|
-
`),`
|
|
306
|
-
|
|
307
|
-
`,"/// Typed entry point: `API(client:).<namespace>.<function>(args)`.\n",`public struct API {
|
|
308
|
-
`,r.length>0?`${r}
|
|
309
|
-
|
|
310
|
-
`:"",` public init(client: LunoraClient) {
|
|
311
|
-
`,t.length>0?`${t}
|
|
312
|
-
`:` _ = client
|
|
313
|
-
`,` }
|
|
314
|
-
`,`}
|
|
315
|
-
`].join("");return{"Package.swift":Ln,[`${re}/Api.swift`]:a,[`${re}/Models.swift`]:e.length>0?`${L}${e}
|
|
316
|
-
`:`${L}import Foundation
|
|
317
|
-
|
|
318
|
-
// No typed argument or result schemas in this deployment.
|
|
319
|
-
`}},Pn={id:"swift",quicktype:{lang:"swift",rendererOptions:{"access-level":"public"}},render:Dn,requires:[],vendor:[{from:"Sources/Lunora",to:"Sources/Lunora"}]},In={go:Te,java:tn,kotlin:pn,python:gn,ruby:_n,rust:Wn,swift:Pn},Fn=Object.keys(In).toSorted((e,n)=>e.localeCompare(n)),xn=async(e,n)=>{const r=be(e);ge(r);const t=n.renderModels?.(e),a=t===void 0?await he(e,n):Object.values(t).join(`
|
|
320
|
-
`),i=ve(r,a);return{files:{...t,...n.render({models:a,namespaces:i})},undeclared:je(r,a),unrepresentable:we(e)}};export{Fn as SDK_LANGUAGES,In as SDK_TARGETS,xn as generateSdk,Gn as isTypedSchema};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const p=/[^a-zA-Z0-9]+/gu,f=/([a-z0-9])([A-Z])/gu,c=t=>t.split(p).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),b=t=>t.replaceAll(f,"$1_$2").replaceAll(p,"_").toLowerCase(),i=t=>t===void 0?!1:["$ref","allOf","anyOf","enum","items","oneOf","properties","type"].some(e=>e in t),g=t=>t==="query"?"query":t==="action"?"action":"mutation",o=(t,e=0)=>{if(e>32||t===null||typeof t!="object")return!1;if(Array.isArray(t))return t.some(a=>o(a,e+1));const n=t;if(n.type==="integer"&&n.format==="int64"||n.type==="string"&&n.contentEncoding==="base64")return!0;const{properties:r}=n;return r!==null&&typeof r=="object"&&Object.values(r).some(a=>o(a,e+1))?!0:["additionalProperties","allOf","anyOf","items","oneOf"].some(a=>o(n[a],e+1))},w=t=>t.replaceAll(/[\n\r\u2028\u2029]+/gu," ").replaceAll("*/","* /").replaceAll('"""','" ""'),y=t=>t.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(`
|
|
2
|
-
`,"\\n").replaceAll("\r","\\r"),h=["$","{","'","$","'","}"].join(""),v=t=>y(t).split("$").join(h),T=(t,e)=>t.argsType!==void 0?e.typed(t.argsType):t.takesArgs?e.untyped:e.none,u=t=>{const[e="",n=""]=t.name.split(":"),r=`${c(e)}${c(n)}`,a=t.params?.[0]?.schema,s=t.result?.schema;return{argsType:i(a)&&!o(a)?`${r}Args`:void 0,takesArgs:i(a),functionName:n,functionPath:t.name,namespace:e,resultType:i(s)&&!o(s)?`${r}Result`:void 0,summary:t.summary??t.name,verb:g(t["x-lunora-function-kind"])}},S=t=>{const e=new Map;for(const n of t.methods){const r=u(n),a=e.get(r.namespace);a===void 0?e.set(r.namespace,[r]):a.push(r)}return[...e.entries()].toSorted(([n],[r])=>n.localeCompare(r)).map(([n,r])=>({methods:r.toSorted((a,s)=>a.functionName.localeCompare(s.functionName)),name:n}))},E=t=>t.methods.flatMap(e=>{const n=u(e);return[{name:n.argsType,schema:e.params?.[0]?.schema},{name:n.resultType,schema:e.result?.schema}]}).filter(e=>e.name!==void 0&&e.schema!==void 0).toSorted((e,n)=>e.name.localeCompare(n.name)),A=/^[A-Za-z][A-Za-z0-9]*$/u,m=t=>A.test(t),$=t=>{const e=new Map;for(const n of t.methods){const r=c(n.functionName);if(!m(r))throw new Error(`sdk: function "${n.functionPath}" produces the invalid identifier "${r}" — rename the export so it starts with a letter.`);const a=n.verb==="query"?[r,`Subscribe${r}`]:[r];for(const s of a){const l=e.get(s);if(l!==void 0)throw new Error(`sdk: functions "${l}" and "${n.functionPath}" both generate "${s}" — rename one so the generated methods stay distinct.`);e.set(s,n.functionPath)}}},M=t=>{const e=new Map;for(const n of t){const r=c(n.name);if(!m(r))throw new Error(`sdk: namespace "${n.name}" produces the invalid identifier "${r}" — rename the file so it starts with a letter.`);const a=e.get(r);if(a!==void 0)throw new Error(`sdk: namespaces "${a}" and "${n.name}" both generate "${r}" — rename one so the generated types stay distinct.`);e.set(r,n.name),$(n)}},d=t=>t.flatMap(e=>e.methods),C=t=>[`GENERATED by \`lunora sdk generate --lang ${t}\` — do not edit.`,"Run the command again to regenerate."],N=(t,e)=>{const n=r=>r!==void 0&&new RegExp(String.raw`\b${r}\b`,"u").test(e)?r:void 0;return t.map(r=>({methods:r.methods.map(a=>({...a,argsType:n(a.argsType),resultType:n(a.resultType)})),name:r.name}))},O=t=>t.methods.filter(e=>o(e.params?.[0]?.schema)||o(e.result?.schema)).map(e=>e.name).toSorted((e,n)=>e.localeCompare(n)),k=(t,e)=>[...new Set(d(t).flatMap(n=>[n.argsType,n.resultType]).filter(n=>n!==void 0&&!new RegExp(String.raw`\b${n}\b`,"u").test(e)))].toSorted((n,r)=>n.localeCompare(r)),L=t=>[...new Set(d(t).flatMap(e=>[e.argsType,e.resultType]).filter(e=>e!==void 0))].toSorted((e,n)=>e.localeCompare(n));export{d as allMethods,T as argsChoice,M as assertGeneratable,w as commentText,C as generatedHeaderLines,o as hasUnrepresentableWireType,i as isTypedSchema,v as kotlinLiteral,E as modelSources,u as parseMethod,S as parseSpec,L as referencedModels,y as stringLiteral,c as toPascalCase,b as toSnakeCase,k as undeclaredModels,O as unrepresentableFunctions,g as verbForKind,N as withDeclaredModels};
|