@lunora/codegen 1.0.0-alpha.108 → 1.0.0-alpha.109

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/index.d.mts +0 -1
  2. package/dist/index.d.ts +0 -1
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/AGENTS_FILENAME-CPHo8Se5.mjs +1 -0
  5. package/dist/packem_shared/{CONTAINERS_FILENAME-DQpyhY6c.mjs → CONTAINERS_FILENAME-Bvn6LZP6.mjs} +1 -1
  6. package/dist/packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs +1 -0
  7. package/dist/packem_shared/DEFAULT_TARGET-CIH5PRk1.mjs +1 -0
  8. package/dist/packem_shared/FLAGS_FILENAME-DtBWyUKq.mjs +1 -0
  9. package/dist/packem_shared/GENERATED_HEADER-GSCh67g3.mjs +1 -0
  10. package/dist/packem_shared/{LUNORA_ERROR_CODES-zfAI2OFs.mjs → LUNORA_ERROR_CODES-BYg8Lpgb.mjs} +1 -1
  11. package/dist/packem_shared/MUTATORS_FILENAME-CRmTpN4y.mjs +1 -0
  12. package/dist/packem_shared/NOTIFY_FILENAME-BybR3Xbd.mjs +1 -0
  13. package/dist/packem_shared/OPENRPC_VERSION-DB1PSt8W.mjs +3 -0
  14. package/dist/packem_shared/QUEUES_FILENAME-BnGLtAIu.mjs +1 -0
  15. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-D9rvsQ0t.mjs +9 -0
  16. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs +2 -0
  17. package/dist/packem_shared/SDK_LANGUAGES-p7vq4x7B.mjs +320 -0
  18. package/dist/packem_shared/SHAPES_FILENAME-DxoIrQhA.mjs +1 -0
  19. package/dist/packem_shared/SchemaSnapshotParseError-Dc1aZAph.mjs +16 -0
  20. package/dist/packem_shared/WORKFLOWS_FILENAME-B8y51Frf.mjs +1 -0
  21. package/dist/packem_shared/buildOpenApiDocument-B2mW3f5a.mjs +3 -0
  22. package/dist/packem_shared/describeErrorLevelFindings-D23VSkFP.mjs +1 -0
  23. package/dist/packem_shared/discover-ast-D33zP-NZ.mjs +1 -0
  24. package/dist/packem_shared/discover-queries-Dfj_0WJG.mjs +1 -0
  25. package/dist/packem_shared/discoverAuthApiCalls-DUjcl0SB.mjs +1 -0
  26. package/dist/packem_shared/discoverCrons-BUJO2ipU.mjs +1 -0
  27. package/dist/packem_shared/discoverFunctions-h8i51Mec.mjs +1 -0
  28. package/dist/packem_shared/discoverHttpRoutes-MX6y-iVE.mjs +1 -0
  29. package/dist/packem_shared/discoverInserts-YX8AmrzL.mjs +1 -0
  30. package/dist/packem_shared/discoverMaskProcedures-DhcK-YMG.mjs +1 -0
  31. package/dist/packem_shared/discoverMigrations-4Jjf5DJE.mjs +1 -0
  32. package/dist/packem_shared/discoverNondeterministicCalls-CjS2Mznw.mjs +1 -0
  33. package/dist/packem_shared/discoverQueries-C5S9tFoD.mjs +1 -0
  34. package/dist/packem_shared/discoverR2sqlCalls-DuTuaSMM.mjs +1 -0
  35. package/dist/packem_shared/discoverRlsMetadata-BYVq6cVp.mjs +1 -0
  36. package/dist/packem_shared/{discoverSandboxUsage-DBM98vVh.mjs → discoverSandboxUsage-L0lV17de.mjs} +1 -1
  37. package/dist/packem_shared/discoverSchema-BtlNz9b_.mjs +1 -0
  38. package/dist/packem_shared/discoverStorageRulesMetadata-CKPFWHT5.mjs +1 -0
  39. package/dist/packem_shared/{emit-BbLyaTLJ.mjs → emit-Ba3NiOwK.mjs} +326 -326
  40. package/dist/packem_shared/{emitApp-DkO-Qvoo.mjs → emitApp-hKEej7rj.mjs} +18 -18
  41. package/dist/packem_shared/formatAdvisories-BjTV22uR.mjs +2 -0
  42. package/dist/packem_shared/isTypedSchema-CU-O5qSH.mjs +2 -0
  43. package/dist/packem_shared/module-specifiers-WF8iAydP.mjs +1 -0
  44. package/dist/packem_shared/parse-validator-DtALyvid.mjs +1 -0
  45. package/dist/packem_shared/paths-C-9fwEgQ.mjs +1 -0
  46. package/dist/packem_shared/readPackageDependencies-C6h6FZuP.mjs +1 -0
  47. package/dist/packem_shared/redact-Cy14LEnc.mjs +1 -0
  48. package/dist/packem_shared/schemaFromIr-BWFnvCVg.mjs +1 -0
  49. package/package.json +3 -3
  50. package/dist/packem_shared/AGENTS_FILENAME-Dk-k250h.mjs +0 -1
  51. package/dist/packem_shared/CodegenDiagnosticError-DPezpZTz.mjs +0 -1
  52. package/dist/packem_shared/DEFAULT_TARGET-CH5disA3.mjs +0 -1
  53. package/dist/packem_shared/FLAGS_FILENAME-Boqm0YCP.mjs +0 -1
  54. package/dist/packem_shared/GENERATED_HEADER-CtitJsDk.mjs +0 -1
  55. package/dist/packem_shared/MUTATORS_FILENAME-Cp_JxLSz.mjs +0 -1
  56. package/dist/packem_shared/NOTIFY_FILENAME-DwyJ5I4Q.mjs +0 -1
  57. package/dist/packem_shared/OPENRPC_VERSION-Bzh1vxcl.mjs +0 -3
  58. package/dist/packem_shared/QUEUES_FILENAME-QpMZsde0.mjs +0 -1
  59. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-lAJi8U-X.mjs +0 -9
  60. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs +0 -2
  61. package/dist/packem_shared/SDK_LANGUAGES-fIqQtE14.mjs +0 -320
  62. package/dist/packem_shared/SHAPES_FILENAME-WxXOsYfe.mjs +0 -1
  63. package/dist/packem_shared/SchemaSnapshotParseError-BkgxjBPQ.mjs +0 -16
  64. package/dist/packem_shared/WORKFLOWS_FILENAME-Dz80zqeT.mjs +0 -1
  65. package/dist/packem_shared/buildOpenApiDocument-B8-PH9af.mjs +0 -3
  66. package/dist/packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs +0 -1
  67. package/dist/packem_shared/discover-ast-7ABwvTVn.mjs +0 -1
  68. package/dist/packem_shared/discover-queries-CU9o_j87.mjs +0 -1
  69. package/dist/packem_shared/discoverAuthApiCalls-XfNbxqlq.mjs +0 -1
  70. package/dist/packem_shared/discoverCrons-RlATa0_t.mjs +0 -1
  71. package/dist/packem_shared/discoverFunctions-4TNKUv7P.mjs +0 -1
  72. package/dist/packem_shared/discoverHttpRoutes-DQivLBqT.mjs +0 -1
  73. package/dist/packem_shared/discoverInserts-D6szWzrV.mjs +0 -1
  74. package/dist/packem_shared/discoverMaskProcedures-BBPqLXA5.mjs +0 -1
  75. package/dist/packem_shared/discoverMigrations-rbjxflR8.mjs +0 -1
  76. package/dist/packem_shared/discoverNondeterministicCalls-Bxr652Rz.mjs +0 -1
  77. package/dist/packem_shared/discoverQueries-CIU5dc0u.mjs +0 -1
  78. package/dist/packem_shared/discoverR2sqlCalls-DMxG6gHr.mjs +0 -1
  79. package/dist/packem_shared/discoverRlsMetadata-B63ARnKG.mjs +0 -1
  80. package/dist/packem_shared/discoverSchema-BNr7PVcZ.mjs +0 -1
  81. package/dist/packem_shared/discoverStorageRulesMetadata-_40MGqRX.mjs +0 -1
  82. package/dist/packem_shared/formatAdvisories-CQvIhQ04.mjs +0 -2
  83. package/dist/packem_shared/isTypedSchema-9wiKtXr2.mjs +0 -2
  84. package/dist/packem_shared/module-specifiers-8FEEiUcv.mjs +0 -1
  85. package/dist/packem_shared/parse-validator-CusS8QwU.mjs +0 -1
  86. package/dist/packem_shared/paths-BmX5O1sG.mjs +0 -1
  87. package/dist/packem_shared/readPackageDependencies-CogJX1Ia.mjs +0 -1
  88. package/dist/packem_shared/redact-6jD4lAhq.mjs +0 -1
  89. package/dist/packem_shared/schemaFromIr-R1ZFzVyy.mjs +0 -1
@@ -0,0 +1,320 @@
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};
@@ -0,0 +1 @@
1
+ import{existsSync as f}from"node:fs";import{join as l}from"node:path";import{SyntaxKind as c,Node as o}from"ts-morph";import{diagnosticAt as u}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as p}from"./module-specifiers-WF8iAydP.mjs";import{a as g}from"./parse-validator-DtALyvid.mjs";const m="shapes.ts",d=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineShape";for(const e of t.getDeclarations())if(o.isImportSpecifier(e))return p(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineShape":!1;return!1},S=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(c.ImportDeclaration);return i!==void 0&&p(i.getModuleSpecifierValue())}return!1},h=r=>{if(o.isIdentifier(r))return d(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineShape"&&o.isIdentifier(t)&&S(t)}return!1},x=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return;const e=t.getProperty("table");if(!e||!o.isPropertyAssignment(e))return;const i=e.getInitializer();return i&&o.isStringLiteral(i)?i.getLiteralValue():void 0},b=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return{};const e=t.getProperty("args");if(!e||!o.isPropertyAssignment(e))return{};const i=e.getInitializer();return!i||!o.isObjectLiteralExpression(i)?{}:g(i)},y=r=>{const t=[];for(const e of r.getVariableDeclarations()){if(!e.isExported())continue;const i=e.getInitializer();if(i?.getKind()!==c.CallExpression)continue;const s=i,a=s.getExpression();if(!h(a))continue;const n=e.getNameNode();if(!o.isIdentifier(n))throw u(n,"defineShape exports must be plain named exports (no destructuring)");t.push({args:b(s),exportName:n.getText(),filePath:"shapes",table:x(s)})}return t},v=(r,t)=>{const e=l(t,m);if(!f(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),s=y(i);return s.sort((a,n)=>a.exportName.localeCompare(n.exportName)),s};export{m as SHAPES_FILENAME,v as discoverShapes};
@@ -0,0 +1,16 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as m,sortKeys as b,diffSchemaSnapshots as S,parseSnapshotJson as k}from"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";import{serializeSchemaSnapshot as O}from"./SCHEMA_SNAPSHOT_VERSION-DIqnj_32.mjs";const w=e=>e==="global"||e==="root"?e:`shardBy:${e.field}`,$=e=>e.kind==="optional"?{kind:e.inner?.kind??"unknown",optional:!0}:{kind:e.kind,optional:!1},v=e=>{const t={};for(const[n,o]of Object.entries(e.shape))t[n]=$(o);const a={};for(const n of e.indexes)a[n.name]={fields:[...n.fields],unique:n.unique??!1};const s={};for(const n of e.relations)s[n.name]={field:n.field,kind:n.kind,table:n.table};return{fields:t,indexes:a,relations:s,shardMode:w(e.shardMode)}},D=(e,t)=>{const a={};for(const n of e.tables)a[n.name]=v(n);const s=[...t].sort();return{jurisdiction:e.jurisdiction,migrationIds:s,tables:b(a),version:m}};class y extends g{constructor(t){super("SCHEMA_SNAPSHOT_PARSE",t,{name:"SchemaSnapshotParseError"})}}const L=e=>{const t=k(e);if(t.status==="invalid")throw new y(t.error);return t.status==="ok"?t.snapshot:void 0},E={deploy:{allowDrift:!0,updateBaseline:!0},prepare:{allowDrift:!0,updateBaseline:!0},verify:{allowDrift:!0,updateBaseline:!1}},f=" • For backward-compatible changes (e.g. adding an optional field): pass `--allow-schema-drift` to skip the block.",p=" • To accept the new shape without a migration (you know data is compatible): pass `--update-schema-baseline`.",I=e=>{const t=e===void 0?void 0:E[e];if(e===void 0||t===void 0)return`${f}
2
+ ${p}
3
+ `;const a=t.updateBaseline?p:` • To accept the new shape without a migration, run \`lunora prepare --update-schema-baseline\` — \`lunora ${e}\` does not take that flag.`;return`${f}
4
+ ${a}
5
+ `},T=e=>{const{allowDrift:t=!1,baseline:a,command:s,current:n}=e,o=S(a,n),d=o.changes.filter(r=>r.severity==="breaking"),l=n.migrationIds.filter(r=>!(a?.migrationIds??[]).includes(r)),i=(r,c)=>({blocked:r,changes:o.changes,newMigrationIds:l,reason:c});if(o.changes.length===0||a===void 0)return i(!1,"");if(d.length===0){const r=o.changes.map(c=>` - ${c.summary}`).join(`
6
+ `);return i(!1,`schema drift detected (all additive/safe):
7
+ ${r}`)}const u=d.map(r=>` - ${r.summary}`).join(`
8
+ `);if(l.length>0)return i(!1,`breaking schema drift detected, but ${String(l.length)} new migration(s) were added (${l.join(", ")}):
9
+ ${u}`);const h=`deploy blocked: ${String(d.length)} breaking schema change(s) detected since the last blessed schema baseline — these changes are incompatible with existing data without a migration:
10
+ ${u}
11
+
12
+ To fix:
13
+ • For breaking changes: add a \`defineMigration({ id, table, up })\` in lunora/ for each affected table, then run \`lunora migrate\` (or \`lunora codegen\`) to apply and re-bless the baseline.
14
+ ${I(s)}Docs: https://lunora.dev/docs/migrations`;return t?i(!1,`${h}
15
+
16
+ (overridden by --allow-schema-drift)`):i(!0,h)};export{m as SCHEMA_SNAPSHOT_VERSION,y as SchemaSnapshotParseError,D as buildSchemaSnapshot,S as diffSchemaSnapshots,T as evaluateSchemaDrift,L as parseSchemaSnapshot,O as serializeSchemaSnapshot};
@@ -0,0 +1 @@
1
+ import{existsSync as p}from"node:fs";import{join as m}from"node:path";import{LunoraError as a}from"@lunora/errors";import{workflowDefaultName as u,workflowClassName as d,workflowBindingName as g}from"@lunora/workflow";import{Node as i,VariableDeclarationKind as w,SyntaxKind as x}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{u as b,s as h}from"./discover-ast-D33zP-NZ.mjs";const k="workflows.ts",N=new Set(["do","sleep","sleepUntil","waitForEvent"]),y=n=>{const e=n.getSymbol();if(!e)return n.getText()==="defineWorkflow";for(const t of e.getDeclarations())if(i.isImportSpecifier(t))return t.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/workflow"?!1:t.getNameNode().getText()==="defineWorkflow";return!1},E=h("workflow"),S=n=>{const e=n.getExpression();if(!i.isPropertyAccessExpression(e)||!N.has(e.getName()))return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="step"?!0:i.isIdentifier(t)&&t.getText()==="step"},D=n=>{const e=n.getProperty("handler");if(!e)return[];const t=i.isPropertyAssignment(e)?e.getInitializer():e;if(!t)return[];const o=[];for(const r of t.getDescendantsOfKind(x.CallExpression)){if(!S(r))continue;const s=r.getArguments()[0];!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s))||o.push({line:r.getStartLineNumber(),method:r.getExpression().getName(),name:s.getLiteralValue()})}return o},l=n=>{let e=n;for(;e&&(i.isAsExpression(e)||i.isSatisfiesExpression(e)||i.isParenthesizedExpression(e));)e=e.getExpression();return e},P=n=>{const e=l(n);if(e&&i.isObjectLiteralExpression(e))return e;if(!(!e||!i.isIdentifier(e)))for(const t of e.getSymbol()?.getDeclarations()??[]){const r=i.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===w.Const?l(t.getInitializer()):void 0;if(r&&i.isObjectLiteralExpression(r))return r}},W=(n,e)=>{const t=P(n.getArguments()[0]);if(!t)throw c(n,`workflow "${e}": defineWorkflow's argument must be an object literal, or a local \`const\` holding one — codegen reads \`name\` and the \`ctx.step.*\` calls out of it statically. Keep the handler wherever you like and pass it through: \`const config = { handler: myHandler }; export const ${e} = defineWorkflow(config);\`.`);const o={bindingName:g(e),className:d(e),exportName:e,name:u(e),steps:D(t)},r=t.getProperty("name");return r&&i.isPropertyAssignment(r)&&(o.name=E(r.getInitializerOrThrow(),e,"name")),o},I=n=>{const e=[];for(const t of n.getVariableDeclarations()){if(!t.isExported())continue;const o=b(t.getInitializer());if(!o)continue;const r=o.getExpression();if(!i.isIdentifier(r)||!y(r))continue;const s=t.getNameNode();if(!i.isIdentifier(s))throw c(s,"defineWorkflow exports must be plain named exports (no destructuring)");e.push(W(o,s.getText()))}return e},A=n=>{const e=new Map,t=new Map;for(const o of n){const r=e.get(o.name);if(r!==void 0)throw new a("DUPLICATE_WORKFLOW_NAME",`Duplicate workflow name "${o.name}": produced by both "${r}" and "${o.exportName}". Deployed workflow names must be unique across the project.`,{status:500});e.set(o.name,o.exportName);const s=t.get(o.bindingName);if(s!==void 0)throw new a("DUPLICATE_WORKFLOW_BINDING",`Duplicate workflow binding "${o.bindingName}": produced by both "${s}" and "${o.exportName}". Workflow export names must yield unique binding names.`,{status:500});t.set(o.bindingName,o.exportName)}},$=(n,e)=>{const t=m(e,k);if(!p(t))return[];const o=n.getSourceFile(t)??n.addSourceFileAtPath(t),r=I(o);return r.sort((s,f)=>s.exportName.localeCompare(f.exportName)),A(r),r};export{k as WORKFLOWS_FILENAME,$ as discoverWorkflows};
@@ -0,0 +1,3 @@
1
+ import{G as S}from"./emit-Ba3NiOwK.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
2
+ `,U=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
+ `;export{I as buildOpenApiDocument,J as emitOpenApi,U as emitOpenApiModule};
@@ -0,0 +1 @@
1
+ const o=r=>[...new Set(r)].toSorted((e,a)=>e.localeCompare(a)),s=r=>o(r.filter(e=>e.level==="ERROR").map(e=>e.name)),t=r=>o(r.filter(e=>e.level==="error").map(e=>e.name)),i=r=>({advisoryNames:s(r.advisories),platformDiagnosticNames:t(r.platformDiagnostics)});export{i as describeErrorLevelFindings,s as errorAdvisoryNames,t as errorPlatformDiagnosticNames};
@@ -0,0 +1 @@
1
+ import{readdirSync as d,lstatSync as x}from"node:fs";import{join as m,extname as E,relative as b,sep as A}from"node:path";import{Node as i,SyntaxKind as f}from"ts-morph";import{diagnosticAt as y}from"./CodegenDiagnosticError-BUXlG3P-.mjs";const S=/\.ts$/u,h=(t,e)=>b(t,e).split(A).join("/").replace(S,""),p=(t,e=[],s=t)=>{let r;try{r=d(t)}catch{return e}for(const n of r){const o=m(t,n),a=x(o);if(a.isDirectory()){if(n==="_generated"||n==="node_modules")continue;p(o,e,s)}else if(a.isFile()&&E(n)===".ts"){if(n==="schema.ts"&&t===s)continue;e.push(o)}}return e},I=(t,e,s)=>{const r=[];for(const n of p(e)){const o=t.getSourceFile(n)??t.addSourceFileAtPath(n),a=h(e,n);for(const u of o.getDescendantsOfKind(f.CallExpression)){const c=s(u,a);c!==void 0&&r.push(c)}}return r},N=t=>{for(const e of t.getAncestors())if(i.isVariableDeclaration(e)&&e.getVariableStatement()?.hasExportKeyword()===!0)return e.getName();return""},O=(t,e)=>{if(e){const o=t.getArguments()[0];return o&&(i.isArrowFunction(o)||i.isFunctionExpression(o))?o:void 0}const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=s.getProperty("handler");if(!r||!i.isPropertyAssignment(r))return;const n=r.getInitializer();return n&&(i.isArrowFunction(n)||i.isFunctionExpression(n))?n:void 0},F=(t,e)=>{if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty(e);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},P=new Set(["findFirst","findFirstOrThrow","findMany"]),D=t=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||!P.has(e.getName()))return;const s=e.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=t.getArguments()[0];return{options:t.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:t.getArguments()[0],table:s.getName()}}},l=(t,e)=>{const s=t.getExpression();if(!i.isPropertyAccessExpression(s)||!e.has(s.getName()))return!1;const r=s.getExpression();return i.isPropertyAccessExpression(r)?r.getName()==="db":i.isIdentifier(r)&&r.getText()==="db"},g=t=>{const e=t.getArguments()[0];return e&&i.isStringLiteral(e)?e.getLiteralText():""},z=(t,e,s)=>{const r=new Set,n=new Set;for(const o of t.getDescendantsOfKind(f.CallExpression))if(l(o,e)){const a=g(o);a!==""&&r.add(a)}else if(l(o,s)){const a=g(o);a!==""&&n.add(a)}return{tablesRead:[...r],tablesWritten:[...n]}},C=t=>{let e=t;for(;e&&(i.isAsExpression(e)||i.isSatisfiesExpression(e)||i.isParenthesizedExpression(e));)e=e.getExpression();return e&&i.isCallExpression(e)?e:void 0},R=t=>{const e=t.getExportAssignment(n=>!n.isExportEquals());if(!e)return;const s=e.getExpression();if(!i.isIdentifier(s))return s;const r=s.getSymbol()?.getValueDeclaration();return r&&i.isVariableDeclaration(r)?r.getInitializer():s},V=t=>{const e=t.getArguments()[1];return e&&i.isStringLiteral(e)?e.getLiteralValue():""},_=(t,e)=>{if(!i.isObjectLiteralExpression(t))return;const s=t.getProperty(e);if(!s||!i.isPropertyAssignment(s))return;const r=s.getInitializer();return r&&i.isStringLiteral(r)?r.getLiteralText():void 0},K=t=>i.isIdentifier(t)&&t.getText()==="ctx",$=t=>(e,s,r)=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw y(e,`${t} "${s}": \`${r}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)};export{h as a,_ as b,I as c,R as d,N as e,V as f,O as h,K as i,p as l,F as p,D as r,$ as s,z as t,C as u};
@@ -0,0 +1 @@
1
+ import{Node as s,SyntaxKind as f}from"ts-morph";import{l as P,a as h}from"./discover-ast-D33zP-NZ.mjs";const x=(e,t)=>{if(e.getText()!==t)return!1;const r=e.getParent();return s.isPropertyAccessExpression(r)&&r.getNameNode()===e?!1:!(s.isPropertyAssignment(r)&&r.getNameNode()===e)},m=(e,t)=>s.isIdentifier(e)?x(e,t):e.getDescendantsOfKind(f.Identifier).some(r=>x(r,t)),g=e=>m(e,"ctx"),A=e=>{let t=e;for(;s.isPropertyAccessExpression(t)||s.isElementAccessExpression(t)||s.isNonNullExpression(t);)t=t.getExpression();return s.isIdentifier(t)?t:void 0},F=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e))return e.getName()},E=e=>m(e,"args"),u=e=>{if(!s.isIdentifier(e))return;const t=e.getText(),r=e.getFirstAncestor(o=>s.isArrowFunction(o)||s.isFunctionExpression(o)||s.isFunctionDeclaration(o));if(r===void 0)return;const i=e.getStart();let n,a=-1;for(const o of r.getDescendantsOfKind(f.VariableDeclaration)){if(o.getName()!==t)continue;const c=o.getInitializer(),l=o.getStart();c!==void 0&&l<i&&l>a&&(n=c,a=l)}return n},T=e=>{if(E(e))return!0;const t=u(e);return t!==void 0&&E(t)},C=e=>{if(s.isCallExpression(e)||s.isNewExpression(e))return!1;const t=u(e);return t===void 0||!(s.isCallExpression(t)||s.isNewExpression(t))},K=e=>{if(g(e))return!0;const t=u(e);if(t!==void 0&&g(t))return!0;const r=t??e;return(s.isIdentifier(r)?[r]:r.getDescendantsOfKind(f.Identifier)).some(n=>{const a=u(n);return a!==void 0&&g(a)})},p=(e,t)=>m(e,t),O=(e,t)=>{if(p(e,t))return!0;const r=u(e);if(r!==void 0&&p(r,t))return!0;const i=A(e);if(i!==void 0){const n=u(i);return n!==void 0&&p(n,t)}return!1},I=e=>{for(const t of e.getAncestors())if(s.isVariableDeclaration(t)&&t.getVariableStatement()?.hasExportKeyword()===!0)return t.getName();return"<module>"},v=new Set(["withGeoIndex","withIndex","withSearchIndex"]),N=new Set(["collect","collectWithScores","first","paginate","take","unique"]),y=e=>{const t=e.getExpression();if(!s.isPropertyAccessExpression(t)||t.getName()!=="query")return!1;const r=t.getExpression();return s.isPropertyAccessExpression(r)?r.getName()==="db":s.isIdentifier(r)&&r.getText()==="db"},b=e=>{const t=[];let r=e;for(;;){const i=r.getParent();if(!i||!s.isPropertyAccessExpression(i))break;const n=i.getParent();if(!n||!s.isCallExpression(n))break;t.push(i.getName()),r=n}return t},S=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,D=e=>{let t=e;for(;;){const r=t.getParent();if(!r||!s.isPropertyAccessExpression(r))return!1;const i=r.getParent();if(!i||!s.isCallExpression(i))return!1;if(r.getName()==="filter"){const n=i.getArguments()[0];if(n&&S.test(n.getText()))return!0}t=i}},w=e=>{const t=e.getArguments()[0];return t&&s.isStringLiteral(t)?t.getLiteralText():""},_=(e,t)=>{const r=[];for(const i of P(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i),a=h(t,i);for(const o of n.getDescendantsOfKind(f.CallExpression)){if(!y(o))continue;const c=b(o),l=c.includes("filter");r.push({exportName:I(o),file:a,filtersPrimaryKey:l&&D(o),hasFilter:l,hasIndex:c.some(d=>v.has(d)),line:o.getStartLineNumber(),table:w(o),terminal:c.findLast(d=>N.has(d))})}}return r};export{K as a,C as b,F as c,_ as d,I as e,O as f,p as g,T as i,E as r,u as s};
@@ -0,0 +1 @@
1
+ import{SyntaxKind as p,Node as s}from"ts-morph";import{l as f,a as g,e as d}from"./discover-ast-D33zP-NZ.mjs";const m=r=>{const t=r.getExpression();if(!s.isPropertyAccessExpression(t))return!1;const e=t.getExpression();return s.isPropertyAccessExpression(e)?e.getName()==="authApi":s.isIdentifier(e)&&e.getText()==="authApi"},h=r=>{const t=r.getArguments()[0];if(t===void 0)return!1;if(!s.isObjectLiteralExpression(t))return!0;for(const e of t.getProperties())if((s.isPropertyAssignment(e)||s.isShorthandPropertyAssignment(e))&&e.getName()==="headers"||s.isSpreadAssignment(e))return!0;return!1},P=(r,t)=>{const e=[];for(const n of f(t)){const c=r.getSourceFile(n)??r.addSourceFileAtPath(n),l=g(t,n);for(const i of c.getDescendantsOfKind(p.CallExpression)){if(!m(i))continue;const o=d(i);if(o==="")continue;const a=i.getExpression(),u=s.isPropertyAccessExpression(a)?a.getName():"";e.push({exportName:o,file:l,hasHeaders:h(i),line:i.getStartLineNumber(),method:u})}}return e};export{P as default};
@@ -0,0 +1 @@
1
+ import{LunoraError as L}from"@lunora/errors";import{CRON_SCHEDULE_KINDS as A,isValidCronExpression as O,warnIfSecondsLeading as S,compileCronSchedule as b}from"@lunora/scheduler";import{SyntaxKind as m,Node as s}from"ts-morph";import{diagnosticAt as f,CodegenDiagnosticError as I}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{i as R}from"./module-specifiers-WF8iAydP.mjs";import{s as $}from"./paths-C-9fwEgQ.mjs";import{l as y}from"./discover-ast-D33zP-NZ.mjs";const P=new Set([...A,"cron"]),D=e=>{const t=e.getSymbol();if(!t)return e.getText()==="cronJobs";for(const r of t.getDeclarations())if(s.isImportSpecifier(r))return R(r.getImportDeclaration().getModuleSpecifierValue())?r.getNameNode().getText()==="cronJobs":!1;return!1},v=e=>{const t=new Set;for(const r of e.getVariableDeclarations()){const o=r.getInitializer();if(o?.getKind()!==m.CallExpression)continue;const i=o.getExpression();s.isIdentifier(i)&&D(i)&&t.add(r.getName())}return t},F=e=>{let t=e;for(;s.isCallExpression(t)||s.isPropertyAccessExpression(t);)t=t.getExpression();return s.isIdentifier(t)?t.getText():void 0},x=(e,t)=>{const r=e.getArguments()[t];return r&&(s.isStringLiteral(r)||s.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},_=(e,t)=>{if(s.isStringLiteral(e)||s.isNoSubstitutionTemplateLiteral(e)||s.isNumericLiteral(e))return e.getLiteralValue();if(s.isTrueLiteral(e))return!0;if(s.isFalseLiteral(e))return!1;if(s.isPrefixUnaryExpression(e)&&e.getOperatorToken()===m.MinusToken){const r=e.getOperand();if(s.isNumericLiteral(r))return-r.getLiteralValue()}if(s.isObjectLiteralExpression(e))return p(e,t);if(s.isArrayLiteralExpression(e))return e.getElements().map(r=>_(r,t));throw f(e,`Cron job "${t}" passes a non-static value where a literal is required; codegen can only read literals.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500})},p=(e,t)=>{const r={};for(const o of e.getProperties()){if(!s.isPropertyAssignment(o))throw f(o,`Cron job "${t}" uses an unsupported object property (shorthand/spread/method) where a static literal is required.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500});const i=o.getInitializer();i&&(r[o.getName()]=_(i,t))}return r},C=(e,t,r)=>{const o=e.getArguments()[t];if(!o||!s.isPropertyAccessExpression(o))throw f(e,`Cron job "${r}" must reference a function statically (e.g. internal.email.digest); codegen cannot resolve a dynamic reference.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const i=o.getName(),n=o.getExpression();if(!s.isPropertyAccessExpression(n))throw f(o,`Cron job "${r}" function reference must be of the form internal.file.fn (two property accesses).`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const a=n.getName();return`${$(a)}:${i}`},h=e=>({workflow:{binding:e.bindingName,exportName:e.exportName}}),w=e=>({workflow:{binding:e.bindingName,exportName:e.exportName}}),T=(e,t,r,o,i,n)=>{const a=e.getExpression();if(!s.isIdentifier(a)||a.getText()!==t)return;const c=r.get(e.getName());if(c)return n(c);throw f(e,`Cron job "${o}" targets ${t}.${e.getName()}, but no such ${i} is declared in lunora/${i}s.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})},V=(e,t,r,o,i)=>{const n=e.getArguments()[t];if(n&&s.isPropertyAccessExpression(n)){const a=T(n,"workflows",o,r,"workflow",h);if(a)return a;const c=T(n,"agents",i,r,"agent",w);return c||{functionPath:C(e,t,r)}}if(n&&s.isIdentifier(n)){const a=o.get(n.getText()),c=i.get(n.getText());if(a&&c)throw f(n,`Cron job "${r}" references "${n.getText()}", which is ambiguous: a workflow and an agent are both declared under that name.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});if(a)return h(a);if(c)return w(c);throw f(n,`Cron job "${r}" references "${n.getText()}", which is neither a function (internal.file.fn / api.file.fn) nor a declared workflow in lunora/workflows.ts nor a declared agent in lunora/agents.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})}return{functionPath:C(e,t,r)}},j=/^@lunora\/scheduler:\s*/u,k=(e,t)=>{const r=x(e,1);if(r===void 0)throw f(e,`Cron job "${t}" must pass a string-literal cron expression to ".cron(...)".`,{code:"CRON_EXPR_NOT_STATIC",name:"LunoraError",status:500});if(!O(r))throw f(e,`Cron job "${t}" has an invalid cron expression "${r}" — expected 5 or 6 space-separated fields.`,{code:"CRON_EXPR_INVALID",name:"LunoraError",status:500});return S(r,`cron expression for job "${t}"`),r},U=(e,t,r)=>{const o=e.getArguments()[1];if(!o||!s.isObjectLiteralExpression(o))throw f(e,`Cron job "${r}" must pass an object-literal schedule to ".${t}(...)".`,{code:"CRON_SCHEDULE_NOT_STATIC",name:"LunoraError",status:500});try{return b(t,p(o,r),r)}catch(i){if(i instanceof I)throw i;const n=i instanceof Error?i.message.replace(j,""):String(i);throw f(e,n,{code:"CRON_SCHEDULE_INVALID",name:"LunoraError",status:500})}},M=(e,t,r,o,i)=>{const n=t.getName();if(!P.has(n)||!r.has(F(t.getExpression())??""))return;const a=x(e,0);if(a===void 0||a.trim()==="")throw f(e,`A cron ".${n}(...)" registration must pass a non-empty string-literal name as its first argument.`,{code:"CRON_NAME_NOT_STATIC",name:"LunoraError",status:500});const c=n==="cron"?k(e,a):U(e,n,a),u=V(e,2,a,o,i),l=e.getArguments()[3];return{args:l&&s.isObjectLiteralExpression(l)?p(l,a):{},cron:c,name:a,...u}},z=e=>{const t=new Set;for(const r of e){if(t.has(r.name))throw new L("DUPLICATE_CRON_NAME",`Duplicate cron job name "${r.name}": cron names must be unique across the project.`,{status:500});t.add(r.name)}},Q=(e,t,r=[],o=[])=>{const i=y(t),n=[],a=new Map(r.map(u=>[u.exportName,u])),c=new Map(o.map(u=>[u.exportName,u]));for(const u of i){const l=e.getSourceFile(u)??e.addSourceFileAtPath(u),g=v(l);if(g.size!==0)for(const d of l.getDescendantsOfKind(m.CallExpression)){const N=d.getExpression();if(!s.isPropertyAccessExpression(N))continue;const E=M(d,N,g,a,c);E&&n.push(E)}}return n.sort((u,l)=>u.name.localeCompare(l.name)),z(n),n};export{Q as default};
@@ -0,0 +1 @@
1
+ import{Node as s,SyntaxKind as O}from"ts-morph";import{l as w,a as k}from"./discover-ast-D33zP-NZ.mjs";import{a as z}from"./module-specifiers-WF8iAydP.mjs";import{p as _,a as b}from"./parse-validator-DtALyvid.mjs";import{s as R}from"./paths-C-9fwEgQ.mjs";const y=new Set(["action","mutation","query","stream"]),P=/\bany\b(?!\s*(?:\?\s*)?:)/u,T=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,U=/^[A-Za-z_$][\w$]*$/u,j=e=>U.test(e)?e:JSON.stringify(e),N={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},$={onConnect:"connect",onDisconnect:"disconnect"},V=z,h=e=>{const t=e.getSymbol();if(!t)return e.getText();const r=t.getDeclarations();for(const i of r){if(!s.isImportSpecifier(i))continue;const o=i.getImportDeclaration().getModuleSpecifierValue();return V(o)?i.getNameNode().getText():void 0}},S=(e,t=!1)=>{let r=e;for(;s.isCallExpression(r);){const n=r.getExpression();if(!s.isPropertyAccessExpression(n))return;r=n.getExpression()}if(!s.isIdentifier(r))return;const i=h(r);if(i===void 0){if(t)return;const n=r.getSymbol()?.getValueDeclaration();if(n&&s.isVariableDeclaration(n)){const o=n.getInitializer();return o?S(o,!0):void 0}return}return y.has(i)?"public":N[i]?"internal":void 0},m=(e,t)=>{const r=e.getProperty(t);if(r===void 0||!s.isPropertyAssignment(r))return;const i=r.getInitializer();return i!==void 0&&s.isStringLiteral(i)?i.getLiteralValue():void 0},E=(e,t)=>{const r=e.getProperty(t);if(r===void 0||!s.isPropertyAssignment(r))return;const i=r.getInitializer();return i!==void 0&&s.isNumericLiteral(i)?i.getLiteralValue():void 0},M=e=>{const t=e.getProperty("cache");if(t===void 0||!s.isPropertyAssignment(t))return;const r=t.getInitializer();if(r===void 0||!s.isObjectLiteralExpression(r))return;const i=m(r,"scope"),n=E(r,"maxAge"),o=E(r,"staleWhileRevalidate"),a=m(r,"tag"),c=m(r,"vary"),l={...n===void 0?{}:{maxAge:n},...i==="private"||i==="public"?{scope:i}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(l).length===0?void 0:l},B=e=>{if(e===void 0||!s.isObjectLiteralExpression(e))return{};const t=M(e),r=e.getProperty("rest");return r!==void 0&&s.isPropertyAssignment(r)?{...t===void 0?{}:{cache:t},rest:r.getInitializer()?.getText()==="true"}:t===void 0?{}:{cache:t}},K=e=>{let t=e;for(;s.isCallExpression(t);){const r=t.getExpression();if(!s.isPropertyAccessExpression(r))return;if(r.getName()==="expose")return B(t.getArguments()[0]);t=r.getExpression()}},H=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return{};const r=t.getProperty("args");if(!r||!s.isPropertyAssignment(r))return{};const i=r.getInitializer();return!i||!s.isObjectLiteralExpression(i)?{}:b(i)},G="/_generated/",q=(e,t,r)=>{const i=t.getSourceFile(),n=(a,c)=>i.getImportDeclarations().some(l=>l.getModuleSpecifierSourceFile()!==a?!1:l.getNamespaceImport()!==void 0||l.getNamedImports().some(f=>f.getName()===c)),o=a=>{const c=a.getSourceFile();if(c.isInNodeModules()||c.isDeclarationFile()||!s.isInterfaceDeclaration(a)&&!s.isTypeAliasDeclaration(a))return!1;const l=c.getFilePath();return l.includes(G)?!1:l===r||n(c,a.getName())};return[e.getSymbol(),e.getAliasSymbol()].flatMap(a=>a?.getDeclarations()??[]).some(a=>o(a))},W=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},I=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0,g=(e,t,r,i=new Set)=>i.has(e)?!1:(i.add(e),q(e,t,r)||W(e).some(n=>g(n,t,r,i))?!0:I(e)?e.getProperties().some(n=>g(n.getTypeAtLocation(t),t,r,i)):!1),X=(e,t)=>{const r=e.getValueDeclaration()??e.getDeclarations()[0];return r&&(s.isPropertySignature(r)||s.isPropertyDeclaration(r))&&r.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(i=>i.isUndefined())},Y=8,J=(e,t,r,i,n,o)=>{const a=e.getArrayElementType(),c=a?o(a,t,r,i,n):void 0;if(c!==void 0)return a?.isUnion()?`(${c})[]`:`${c}[]`},Q=(e,t,r,i,n,o)=>{const a=[];for(const c of e.getUnionTypes()){const l=o(c,t,r,i,n);if(l===void 0)return;a.push(l)}return a.join(" | ")},Z=(e,t,r,i,n,o)=>{if(!I(e))return;const a=[];for(const c of e.getProperties()){const l=c.getTypeAtLocation(t),f=X(c,l),L=f&&l.isUnion()?l.getUnionTypes().filter(d=>!d.isUndefined()):[l],v=[];for(const d of L){const x=o(d,t,r,i+1,n);if(x===void 0)return;v.push(x)}a.push(`${j(c.getName())}${f?"?":""}: ${v.join(" | ")}`)}return a.length>0?`{ ${a.join("; ")} }`:"{}"},p=(e,t,r,i,n)=>{if(i>Y||n.has(e))return;if(!g(e,t,r))return e.getText(t);const o=new Set(n).add(e);return e.isArray()?J(e,t,r,i,o,p):e.isUnion()?Q(e,t,r,i,o,p):Z(e,t,r,i,o,p)},C=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let r=t.getReturnType();const n=(r.getSymbol()??r.getAliasSymbol())?.getName();if(n==="Promise"||n==="AsyncIterable"||n==="AsyncIterableIterator"||n==="AsyncGenerator"){const c=r.getTypeArguments()[0];c&&(r=c)}const o=r.getText(e);if(!o||o==="any"||o==="never"||P.test(o.replaceAll(T,"")))return"unknown";const a=e.getSourceFile().getFilePath();return g(r,e,a)?p(r,e,a,0,new Set)??"unknown":o},ve=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const r=t.getTypeAtLocation(e).getProperty("types");if(!r)return;const i=r.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!i)return;const n=i.getTypeAtLocation(e),o=n.getText(e);if(!o||o==="any"||o==="never"||P.test(o.replaceAll(T,"")))return;const a=e.getSourceFile().getFilePath();return g(n,e,a)?p(n,e,a,0,new Set):o},ee=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return"unknown";const r=t.getProperty("handler");if(!r||!s.isPropertyAssignment(r))return"unknown";const i=r.getInitializer();return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":C(i)},te=e=>{const t=e.getArguments()[0];return!t||!(s.isArrowFunction(t)||s.isFunctionExpression(t))?"unknown":C(t)},re=e=>{let t={},r=e;for(;s.isCallExpression(r);){const i=r.getExpression();if(!s.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const n=r.getArguments()[0];n&&s.isObjectLiteralExpression(n)&&(t={...b(n),...t})}r=i.getExpression()}return t},ie=e=>{let t=e;for(;s.isCallExpression(t);){const r=t.getExpression();if(!s.isPropertyAccessExpression(r))return;if(r.getName()==="output"){const i=t.getArguments()[0];return i&&s.isExpression(i)?_(i):void 0}t=r.getExpression()}},ne=e=>{const t=e.getExpression();if(s.isPropertyAccessExpression(t)){const o=t.getName();if(!y.has(o))return;const a=t.getExpression();if(a.getType().getProperty("__lunoraProcedure"))return{kind:o,receiver:a,visibility:a.getType().getProperty("__lunoraVisibility")?"internal":"public"};const c=S(a);return c?{kind:o,receiver:a,visibility:c}:void 0}if(!s.isIdentifier(t))return;const r=h(t);if(!r)return;if(y.has(r))return{kind:r,visibility:"public"};const i=N[r];if(i)return{kind:i,visibility:"internal"};const n=$[r];if(n)return{kind:"mutation",lifecycle:n,visibility:"internal"}},A=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,xe=e=>s.isPropertyAccessExpression(e)&&e.getName()==="db"||s.isIdentifier(e)&&e.getText()==="db",Ee=e=>{const t=e.getArguments()[0],r=A(t);if(r!==void 0)return r;if(t===void 0||!s.isObjectLiteralExpression(t))return;const i=t.getProperty("handler");return i!==void 0&&s.isPropertyAssignment(i)?A(i.getInitializer()):void 0},se=e=>s.isIdentifier(e)?e.getText():s.isPropertyAccessExpression(e)?e.getName():"",Ae=(e,t)=>{let r=e;for(;s.isCallExpression(r);){const i=r.getExpression();if(!s.isPropertyAccessExpression(i))break;if(i.getName()===t)return!0;r=i.getExpression()}return!1},be=(e,t,r)=>{let i=e;for(;s.isCallExpression(i);){const n=i.getExpression();if(!s.isPropertyAccessExpression(n))break;const o=i.getArguments()[0];if(n.getName()===t&&o!==void 0&&s.isCallExpression(o)&&se(o.getExpression())===r)return!0;i=n.getExpression()}return!1},oe=e=>{const t=ne(e);if(t){if(t.receiver){const r=K(t.receiver),i=ie(t.receiver);return{args:re(t.receiver),...r?{expose:r}:{},kind:t.kind,...i?{output:i}:{},returnType:te(e),visibility:t.visibility}}return t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",visibility:t.visibility}:{args:H(e),kind:t.kind,returnType:ee(e),visibility:t.visibility}}},ae=8,u=(e,t=0)=>{if(t>ae)return;if(s.isCallExpression(e))return e;if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return u(e.getExpression(),t+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const r=e.getSymbol()?.getValueDeclaration();return r?F(r,t+1):void 0},F=(e,t)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const r=e.getInitializer();return r?u(r,t):void 0}if(s.isShorthandPropertyAssignment(e))return u(e.getNameNode(),t);if(s.isBindingElement(e)){const r=e.getPropertyNameNode()?.getText()??e.getName(),o=e.getFirstAncestorByKind(O.VariableDeclaration)?.getInitializer()?.getType().getProperty(r)?.getValueDeclaration();return o?F(o,t+1):void 0}},ce=e=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const n=[];for(const o of t.getElements()){const a=u(o.getNameNode());a&&n.push([o.getName(),a])}return n}const r=e.getInitializer(),i=r&&(s.isCallExpression(r)?r:u(r));return i?[[e.getName(),i]]:[]},D=(e,t,r)=>{const i=oe(e);if(i)return{args:i.args,exportName:t,filePath:r,kind:i.kind,returnType:i.returnType,...i.output?{output:i.output}:{},visibility:i.visibility,...i.expose?{expose:i.expose}:{},...i.lifecycle?{lifecycle:i.lifecycle}:{}}},le=(e,t)=>{const r=[];for(const i of e.getExportAssignments()){if(i.isExportEquals())continue;const n=u(i.getExpression()),o=n?D(n,"default",t):void 0;o&&r.push(o)}return r},ue=(e,t)=>{const r=[];for(const i of e.getVariableStatements())if(i.isExported())for(const n of i.getDeclarations())for(const[o,a]of ce(n)){const c=D(a,o,t);c&&r.push(c)}return r.push(...le(e,t)),r},pe=e=>{const t=new Map;for(const r of e){const i=R(r.filePath),n=t.get(i);if(n&&n!==r.filePath)throw Object.assign(new Error(`Namespace collision: "${n}" and "${r.filePath}" both resolve to "${i}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[n,r.filePath],status:500});t.set(i,r.filePath)}},Pe=(e,t)=>{const r=w(t),i=[];for(const n of r){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),a=k(t,n);i.push(...ue(o,a))}return i.sort((n,o)=>`${n.filePath}:${n.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),pe(i),i};export{Ae as chainHasStep,be as chainUsesWrappedCall,ne as classifyProcedureCall,Pe as discoverFunctions,A as inlineHandler,xe as isDatabaseAccessor,w as listLunoraSourceFiles,k as lunoraRelativePath,Ee as procedureHandler,ve as resolveStandardSchemaType,C as unwrapHandlerReturn};
@@ -0,0 +1 @@
1
+ import{Node as a}from"ts-morph";import{l,a as m}from"./discover-ast-D33zP-NZ.mjs";import{unwrapHandlerReturn as d}from"./discoverFunctions-h8i51Mec.mjs";import{p as h,a as f}from"./parse-validator-DtALyvid.mjs";const u=new Set(["delete","get","head","options","patch","post","put"]),g=new Set(["body","params","searchParams"]),E=new Set(["handler","stream"]),v=r=>{const e=r.getArguments()[0];if(e&&a.isStringLiteral(e))return e.getLiteralValue()},x=r=>{const e=r.getArguments()[0];return e&&a.isObjectLiteralExpression(e)?f(e):{}},P=r=>{if(!a.isCallExpression(r))return;const e=r.getExpression();if(!a.isPropertyAccessExpression(e))return;const o=e.getName();if(!u.has(o))return;const n=e.getExpression();if(!a.isIdentifier(n)||n.getText()!=="httpRoute")return;const s=v(r);return s===void 0?void 0:{method:o.toUpperCase(),path:s}},S=(r,e)=>{const o={body:{},params:{},searchParams:{},stream:e==="stream"},n=r.getExpression();if(!a.isPropertyAccessExpression(n))return;let s=n.getExpression();for(;a.isCallExpression(s);){const i=s.getExpression();if(!a.isPropertyAccessExpression(i))break;const c=i.getName();if(u.has(c))break;if(g.has(c)){const p=x(s);o[c]={...p,...o[c]}}else if(c==="output"&&o.output===void 0){const p=s.getArguments()[0];p&&a.isExpression(p)&&(o.output=h(p))}s=i.getExpression()}const t=P(s);if(t)return o.method=t.method,o.path=t.path,o},A=r=>{const e=r.getArguments()[0];return!e||!(a.isArrowFunction(e)||a.isFunctionExpression(e))?"unknown":d(e)},T=(r,e,o,n)=>{const s=e.getName();if(!E.has(s))return;const t=S(r,s);if(!(t?.method===void 0||t.path===void 0))return{body:t.body,exportName:o,filePath:n,method:t.method,params:t.params,path:t.path,searchParams:t.searchParams,stream:t.stream,...t.stream?{chunkType:A(r)}:{},...t.output?{output:t.output}:{}}},b=(r,e)=>{const o=[];for(const n of r.getVariableStatements())if(n.isExported())for(const s of n.getDeclarations()){const t=s.getInitializer();if(!t||!a.isCallExpression(t))continue;const i=t.getExpression();if(!a.isPropertyAccessExpression(i))continue;const c=T(t,i,s.getName(),e);c&&o.push(c)}return o},F=(r,e)=>{const o=l(e),n=[];for(const s of o){const t=r.getSourceFile(s)??r.addSourceFileAtPath(s),i=m(e,s);n.push(...b(t,i))}return n.sort((s,t)=>`${s.method} ${s.path}`.localeCompare(`${t.method} ${t.path}`)||s.filePath.localeCompare(t.filePath)),n};export{F as default};
@@ -0,0 +1 @@
1
+ import{SyntaxKind as c,Node as i}from"ts-morph";import{l as f,a as g,e as u}from"./discover-ast-D33zP-NZ.mjs";const d=t=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="insert")return!1;const r=e.getExpression();return i.isPropertyAccessExpression(r)?r.getName()==="db":i.isIdentifier(r)&&r.getText()==="db"},m=t=>{if(!i.isIdentifier(t))return;const e=t.getSymbol(),r=e?.getAliasedSymbol()?.getDeclarations()??e?.getDeclarations()??[];for(const s of r)if(i.isVariableDeclaration(s)){const n=s.getInitializer();if(n&&i.isStringLiteral(n))return n.getLiteralText()}},p=t=>{const e=t.getArguments()[0];return e?i.isStringLiteral(e)?e.getLiteralText():m(e)??"":""},S=(t,e)=>{const r=[];for(const s of f(e)){const n=t.getSourceFile(s)??t.addSourceFileAtPath(s),l=g(e,s);for(const o of n.getDescendantsOfKind(c.CallExpression)){if(!d(o))continue;const a=u(o);a!==""&&r.push({exportName:a,file:l,line:o.getStartLineNumber(),table:p(o)})}}return r};export{S as default};
@@ -0,0 +1 @@
1
+ import{Node as i}from"ts-morph";import{l as f,a as P,t as x}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as p}from"./discoverFunctions-h8i51Mec.mjs";const A=e=>{if(!i.isCallExpression(e))return!1;const s=e.getExpression();return i.isIdentifier(s)?s.getText()==="mask":i.isPropertyAccessExpression(s)?s.getName()==="mask":!1},u=e=>{if(i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e))return e.getName()},k=e=>{const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const t=[];for(const r of s.getProperties()){const o=u(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=u(a);c!==void 0&&t.push({column:c,table:o})}}return t},g=e=>{const s=[];let t=e;for(;i.isCallExpression(t);){const r=t.getExpression();if(!i.isPropertyAccessExpression(r))break;if(r.getName()==="use"){const o=t.getArguments()[0];o&&A(o)&&s.push(o)}t=r.getExpression()}return s},E=e=>{const s=g(e);return{maskColumns:s.flatMap(t=>k(t)),usesMask:s.length>0}},M=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),S=new Set(["delete","insert","patch","replace"]),b=(e,s)=>{if(!i.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const r=p(t);if(!r)return;const o=r.receiver?E(r.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=x(e,M,S);return{exportName:e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:r.visibility}},w=(e,s)=>{const t=[];for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=P(s,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations()){const l=b(c,n);l&&t.push(l)}}return t},h=e=>{if(i.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&i.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},C=e=>{const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const t=[];for(const r of s.getProperties()){const o=u(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=u(a);c!==void 0&&t.push({column:c,strategy:h(a),table:o})}}return t},v=e=>{const s=[];for(const t of e.getVariableStatements())if(t.isExported())for(const r of t.getDeclarations()){const o=r.getInitializer(),n=o&&i.isCallExpression(o)?p(o):void 0;n?.receiver&&s.push(n.receiver)}return s},R=(e,s)=>{const t=new Map;for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const n of v(o))for(const a of g(n))for(const c of C(a)){const l=`${c.table}\0${c.column}`;t.has(l)||t.set(l,c)}}return{columns:[...t.values()]}},F=(e,s,t)=>{const r=e.getArguments()[0];if(!r||!i.isObjectLiteralExpression(r))return[];const o=[];for(const n of r.getProperties()){const a=u(n);if(a===void 0||!i.isPropertyAssignment(n))continue;const c=n.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const m=u(l);if(m===void 0)continue;const d=h(l);d!=="custom"&&o.push({column:m,exportName:s,file:t,line:l.getStartLineNumber(),strategy:d,table:a})}}return o},z=(e,s)=>{if(!i.isVariableDeclaration(e))return[];const t=e.getInitializer(),r=t&&i.isCallExpression(t)?p(t):void 0;return r?.receiver?g(r.receiver).flatMap(o=>F(o,e.getName(),s)):[]},T=(e,s)=>{const t=[];for(const r of f(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=P(s,r);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())t.push(...z(c,n))}return t},D=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,L=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?D(e):!0,y=(e,s=!1)=>{for(const t of e.getProperties()){if(L(t))return!0;if(s)continue;if(!i.isPropertyAssignment(t))return!0;const r=t.getInitializer();if(!r||!i.isObjectLiteralExpression(r)||y(r,!0))return!0}return!1},j=(e,s)=>{for(const t of f(s)){const r=e.getSourceFile(t)??e.addSourceFileAtPath(t);for(const o of v(r))for(const n of g(o)){const a=n.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||y(a)))return!0}}return!1};export{w as default,j as discoverMaskHasNonLiteralPolicy,R as discoverMaskMetadata,T as discoverMaskStrategies};
@@ -0,0 +1 @@
1
+ import{SyntaxKind as f,Node as a}from"ts-morph";import{diagnosticAt as u}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{l as m,a as p}from"./discover-ast-D33zP-NZ.mjs";import{b as h}from"./module-specifiers-WF8iAydP.mjs";const I=r=>{const i=r.getSymbol();if(!i)return r.getText()==="defineMigration";for(const t of i.getDeclarations())if(a.isImportSpecifier(t))return h(t.getImportDeclaration().getModuleSpecifierValue())?t.getNameNode().getText()==="defineMigration":!1;return!1},d=(r,i)=>{const t=r.getProperty(i);if(!t||!a.isPropertyAssignment(t))return;const e=t.getInitializer();return e&&a.isStringLiteral(e)?e.getLiteralValue():void 0},P=(r,i)=>{const t=r.getInitializer();if(t?.getKind()!==f.CallExpression)return;const e=t.getExpression();if(!a.isIdentifier(e)||!I(e))return;const o=t.getArguments()[0];if(!o||!a.isObjectLiteralExpression(o))return;const n=d(o,"id"),s=r.getName();if(n===void 0||n.trim()==="")throw u(o,`Migration "${s}" in "${i}" must declare \`id\` as a non-empty string literal so codegen can key the registry.`,{code:"MIGRATION_ID_NOT_STATIC",name:"LunoraError",status:500});return{exportName:s,filePath:i,id:n,table:d(o,"table")??""}},M=r=>{const i=new Map;for(const t of r){const e=i.get(t.id);if(e!==void 0)throw Object.assign(new Error(`Duplicate migration id "${t.id}": declared in both "${e}" and "${t.filePath}". Migration ids must be unique across the project.`),{code:"DUPLICATE_MIGRATION_ID",id:t.id,name:"LunoraError",paths:[e,t.filePath],status:500});i.set(t.id,t.filePath)}},y=(r,i)=>{const t=m(i),e=[];for(const o of t){const n=r.getSourceFile(o)??r.addSourceFileAtPath(o),s=p(i,o);for(const c of n.getVariableStatements())if(c.isExported())for(const g of c.getDeclarations()){const l=P(g,s);l&&e.push(l)}}return e.sort((o,n)=>o.id.localeCompare(n.id)),M(e),e};export{y as default};
@@ -0,0 +1 @@
1
+ import{Node as s,SyntaxKind as a}from"ts-morph";import{l,a as c,h as d}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as f}from"./discoverFunctions-h8i51Mec.mjs";const u={"crypto.getRandomValues":"crypto.getRandomValues","crypto.randomUUID":"crypto.randomUUID","Date.now":"Date.now","Math.random":"Math.random"},m=new Set(["globalThis","self"]),g=new Set(["globalThis","self","window"]),p=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const t=e.getExpression();if(s.isIdentifier(t)&&g.has(t.getText()))return e.getName()}},h=e=>{const t=e.getExpression();if(s.isIdentifier(t)){const o=t.getText();return o==="fetch"||o==="Date"?o:void 0}if(!s.isPropertyAccessExpression(t))return;const n=t.getName(),i=p(t.getExpression());if(i!==void 0)return n==="fetch"&&m.has(i)?"fetch":u[`${i}.${n}`]},x=e=>{const t=e.getExpression();if(!s.isIdentifier(t)||t.getText()!=="Date")return;const n=e.getArguments(),i=n.every(o=>s.isNumericLiteral(o)||s.isStringLiteral(o)||s.isNoSubstitutionTemplateLiteral(o));return n.length>0&&i?void 0:"new Date"},N=e=>{const t=e.getInitializer();if(!t||!s.isCallExpression(t))return;const n=f(t);if(!n||n.kind!=="query"&&n.kind!=="mutation")return;const i=d(t,n.receiver);return i?{exportName:e.getName(),handler:i,kind:n.kind}:void 0},E=(e,t)=>{const n=[];for(const i of e.handler.getDescendantsOfKind(a.CallExpression)){const o=h(i);o!==void 0&&n.push({callee:o,exportName:e.exportName,file:t,kind:e.kind,line:i.getStartLineNumber()})}for(const i of e.handler.getDescendantsOfKind(a.NewExpression)){const o=x(i);o!==void 0&&n.push({callee:o,exportName:e.exportName,file:t,kind:e.kind,line:i.getStartLineNumber()})}return n},S=(e,t)=>{const n=[];for(const i of e.getVariableStatements())if(i.isExported())for(const o of i.getDeclarations()){const r=N(o);r&&n.push(...E(r,t))}return n},w=(e,t)=>{const n=[];for(const i of l(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...S(o,c(t,i)))}return n};export{w as default};
@@ -0,0 +1 @@
1
+ import{d as a}from"./discover-queries-Dfj_0WJG.mjs";import"./discover-ast-D33zP-NZ.mjs";export{a as default};
@@ -0,0 +1 @@
1
+ import{Node as o,SyntaxKind as a}from"ts-morph";import{l as c,a as l,h as d}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as f}from"./discoverFunctions-h8i51Mec.mjs";const u=t=>{const r=t.getInitializer();if(!r||!o.isCallExpression(r))return;const e=f(r);if(!e||e.kind!=="query"&&e.kind!=="mutation")return;const n=d(r,e.receiver);return n?{exportName:t.getName(),handler:n,kind:e.kind}:void 0},p=t=>{if(!o.isPropertyAccessExpression(t)||t.getName()!=="r2sql")return;const r=t.getExpression();if(!o.isIdentifier(r)||r.getText()!=="ctx")return;const e=t.getParent();return e&&o.isPropertyAccessExpression(e)&&e.getExpression()===t?`ctx.r2sql.${e.getName()}`:"ctx.r2sql"},x=(t,r)=>{const e=[];for(const n of t.handler.getDescendantsOfKind(a.PropertyAccessExpression)){const s=p(n);s!==void 0&&e.push({callee:s,exportName:t.exportName,file:r,kind:t.kind,line:n.getStartLineNumber()})}return e},m=(t,r)=>{const e=[];for(const n of t.getVariableStatements())if(n.isExported())for(const s of n.getDeclarations()){const i=u(s);i&&e.push(...x(i,r))}return e},P=(t,r)=>{const e=[];for(const n of c(r)){const s=t.getSourceFile(n)??t.addSourceFileAtPath(n);e.push(...m(s,l(r,n)))}return e};export{P as default};
@@ -0,0 +1 @@
1
+ import{Node as n}from"ts-morph";import{l as d,a as x,t as P,b as l}from"./discover-ast-D33zP-NZ.mjs";import{classifyProcedureCall as E}from"./discoverFunctions-h8i51Mec.mjs";const b=t=>{if(!n.isCallExpression(t))return!1;const e=t.getExpression();return n.isIdentifier(e)?e.getText()==="rls":n.isPropertyAccessExpression(e)?e.getName()==="rls":!1},v=t=>{const e=t.getArguments()[0];if(!e||!n.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements()){if(!n.isObjectLiteralExpression(r))continue;const i=r.getProperty("table");if(!i||!n.isPropertyAssignment(i))continue;const o=i.getInitializer();o&&n.isStringLiteral(o)&&s.push(o.getLiteralText())}return s},h=t=>{const e=[];let s=t;for(;n.isCallExpression(s);){const r=s.getExpression();if(!n.isPropertyAccessExpression(r))break;if(r.getName()==="use"){const i=s.getArguments()[0];i&&b(i)&&e.push(i)}s=r.getExpression()}return e},y=t=>{const e=h(t);return{rlsTables:e.flatMap(s=>v(s)),usesRls:e.length>0}},A=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),L=new Set(["delete","deleteMany","insert","insertMany","patch","patchMany","replace"]),S=(t,e)=>{if(!n.isVariableDeclaration(t))return;const s=t.getInitializer();if(!s||!n.isCallExpression(s))return;const r=E(s);if(!r)return;const i=r.receiver?y(r.receiver):{rlsTables:[],usesRls:!1},{tablesRead:o,tablesWritten:a}=P(t,A,L);return{exportName:t.getName(),file:e,rlsTables:i.rlsTables,tablesRead:o,tablesWritten:a,usesRls:i.usesRls,visibility:r.visibility}},w=(t,e)=>{const s=[];for(const r of d(e)){const i=t.getSourceFile(r)??t.addSourceFileAtPath(r),o=x(e,r);for(const a of i.getVariableStatements())if(a.isExported())for(const u of a.getDeclarations()){const c=S(u,o);c&&s.push(c)}}return s},C=new Set(["delete","insert","read","update"]),T=(t,e,s)=>{const r=t.getArguments()[0];if(!r||!n.isArrayLiteralExpression(r))return[];const i=[];for(const o of r.getElements()){if(!n.isObjectLiteralExpression(o))continue;const a=l(o,"on");a===void 0||!C.has(a)||i.push({file:e,on:a,procedure:s,table:l(o,"table")??""})}return i},g=t=>{if(!n.isObjectLiteralExpression(t))return[];const e=t.getProperty("permissions");if(!e||!n.isPropertyAssignment(e))return[];const s=e.getInitializer();if(!s||!n.isArrayLiteralExpression(s))return[];const r=[];for(const i of s.getElements()){if(n.isStringLiteral(i)){r.push(i.getLiteralText());continue}if(n.isCallExpression(i)){const o=i.getArguments()[0];o&&n.isStringLiteral(o)&&r.push(o.getLiteralText())}}return r},m=(t,e)=>e===void 0?t:{...t,description:e},R=t=>{if(n.isCallExpression(t)){const e=t.getArguments()[0];if(!e||!n.isStringLiteral(e))return;const s=t.getArguments()[1],r=s?l(s,"description"):void 0,i=s?g(s):[];return m({name:e.getLiteralText(),permissions:i},r)}if(n.isObjectLiteralExpression(t)){const e=l(t,"name");return e===void 0?void 0:m({name:e,permissions:g(t)},l(t,"description"))}},F=t=>{const e=t.getArguments()[1];if(!e||!n.isObjectLiteralExpression(e))return[];const s=e.getProperty("roles");if(!s||!n.isPropertyAssignment(s))return[];const r=s.getInitializer();if(!r||!n.isArrayLiteralExpression(r))return[];const i=[];for(const o of r.getElements()){const a=R(o);a&&i.push(a)}return i},I=(t,e,s)=>{const r=h(t);return{policies:r.flatMap(i=>T(i,e,s)),roles:r.flatMap(i=>F(i))}},M=t=>{const e=[];for(const s of t.getVariableStatements())if(s.isExported())for(const r of s.getDeclarations()){const i=r.getInitializer(),o=i&&n.isCallExpression(i)?E(i):void 0;o?.receiver&&e.push({name:r.getName(),receiver:o.receiver})}return e},D=(t,e)=>{const s=[],r=new Map;for(const i of d(e)){const o=t.getSourceFile(i)??t.addSourceFileAtPath(i),a=x(e,i);for(const{name:u,receiver:c}of M(o)){const p=I(c,a,u);s.push(...p.policies);for(const f of p.roles)r.has(f.name)||r.set(f.name,f)}}return{policies:s,roles:[...r.values()]}};export{w as default,D as discoverRlsMetadata};
@@ -1 +1 @@
1
- import{g as u}from"./discover-ast-7ABwvTVn.mjs";const d=new Set(["@lunora/agent","@lunora/agent/sandbox"]),i=o=>{const s={usesSandboxBrowser:!1,usesSandboxContainer:!1};if(!d.has(o.getModuleSpecifierValue())||o.isTypeOnly())return s;for(const e of o.getNamedImports()){if(e.isTypeOnly())continue;const n=e.getNameNode().getText();n==="browserTool"?s.usesSandboxBrowser=!0:n==="containerTool"&&(s.usesSandboxContainer=!0)}return s},b=(o,s)=>{const e={usesSandboxBrowser:!1,usesSandboxContainer:!1};for(const n of u(s)){const a=o.getSourceFile(n)??o.addSourceFileAtPath(n);for(const t of a.getImportDeclarations()){const r=i(t);e.usesSandboxBrowser||=r.usesSandboxBrowser,e.usesSandboxContainer||=r.usesSandboxContainer}if(e.usesSandboxBrowser&&e.usesSandboxContainer)break}return e};export{b as discoverSandboxUsage};
1
+ import{l as u}from"./discover-ast-D33zP-NZ.mjs";const i=new Set(["@lunora/agent","@lunora/agent/sandbox"]),d=o=>{const s={usesSandboxBrowser:!1,usesSandboxContainer:!1};if(!i.has(o.getModuleSpecifierValue())||o.isTypeOnly())return s;for(const e of o.getNamedImports()){if(e.isTypeOnly())continue;const n=e.getNameNode().getText();n==="browserTool"?s.usesSandboxBrowser=!0:n==="containerTool"&&(s.usesSandboxContainer=!0)}return s},S=(o,s)=>{const e={usesSandboxBrowser:!1,usesSandboxContainer:!1};for(const n of u(s)){const a=o.getSourceFile(n)??o.addSourceFileAtPath(n);for(const t of a.getImportDeclarations()){const r=d(t);e.usesSandboxBrowser||=r.usesSandboxBrowser,e.usesSandboxContainer||=r.usesSandboxContainer}if(e.usesSandboxBrowser&&e.usesSandboxContainer)break}return e};export{S as discoverSandboxUsage};