lecodes-cli 0.16.0 → 0.16.2

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 (38) hide show
  1. package/README.md +27 -4
  2. package/dist/index.js +170706 -72
  3. package/package.json +11 -6
  4. package/runtime/sdk/compile/bundler.ts +10 -2
  5. package/runtime/sdk/compile/compileProject.ts +10 -2
  6. package/runtime/sdk/compile/detectEntry.ts +5 -2
  7. package/runtime/sdk/compile/index.ts +17 -1
  8. package/runtime/sdk/compile/serverSplit.ts +233 -0
  9. package/runtime/sdk/compile/serverTypes.ts +227 -0
  10. package/runtime/sdk/gl/AnimationClip.ts +174 -0
  11. package/runtime/sdk/gl/Animator.ts +634 -0
  12. package/runtime/sdk/gl/CharacterController.ts +6 -1
  13. package/runtime/sdk/gl/IK.ts +170 -0
  14. package/runtime/sdk/gl/Material.ts +1 -1
  15. package/runtime/sdk/gl/ModelAnimation.ts +34 -3
  16. package/runtime/sdk/gl/Node.ts +21 -0
  17. package/runtime/sdk/inject.ts +10 -0
  18. package/runtime/sdk/plugins/oauth.ts +61 -0
  19. package/runtime/sdk/runtime/rpc.ts +218 -0
  20. package/runtime/sdk/server/auth/appConfig.ts +12 -0
  21. package/runtime/sdk/server/auth/global.ts +80 -0
  22. package/runtime/sdk/server/auth/host.ts +318 -0
  23. package/runtime/sdk/server/auth/models.ts +83 -0
  24. package/runtime/sdk/server/auth/types.ts +50 -0
  25. package/runtime/sdk/server/channel.ts +56 -0
  26. package/runtime/sdk/server/context.ts +36 -0
  27. package/runtime/sdk/server/db/defineDb.ts +237 -0
  28. package/runtime/sdk/server/db/fields.ts +132 -0
  29. package/runtime/sdk/server/db/httpTransport.ts +93 -0
  30. package/runtime/sdk/server/db/index.ts +7 -0
  31. package/runtime/sdk/server/db/marci/query.ts +412 -0
  32. package/runtime/sdk/server/db/types.ts +202 -0
  33. package/runtime/sdk/server/errors.ts +12 -0
  34. package/runtime/sdk/server/host.ts +74 -0
  35. package/runtime/sdk/server/inject.ts +13 -0
  36. package/runtime/sdk/server/runtime.ts +133 -0
  37. package/runtime/sdk/server/validate.ts +87 -0
  38. package/runtime/sdk-types.json +1 -1
@@ -0,0 +1,74 @@
1
+ /**
2
+ * `sdk/server` — the HOST side of the app backend, imported normally by the runner
3
+ * (packages/lecodes-runner), the backend and tests. Nothing here is bundled into project code; the
4
+ * bundle carries its own SDK copy and meets this module only through the `globalThis.__lecodes*`
5
+ * seams (see ./runtime.ts).
6
+ */
7
+
8
+ export {
9
+ loadServerModules, createInvoker, createJoinGuard, setChannelPublisher, setRequestProvider,
10
+ } from "./runtime"
11
+ export type { LoadedServer, InvokeResult, InvokerOptions, ServerRegistration } from "./runtime"
12
+ export type { RequestContext } from "./context"
13
+ export { setDbTransport } from "./db/defineDb"
14
+ export { marciHttpTransport, marciRequest, encodeMarciId, MarciHttpError } from "./db/httpTransport"
15
+ export type { MarciHttpOptions } from "./db/httpTransport"
16
+ export type { MarciOp, MarciTransport } from "./db/marci/query"
17
+ export type { ServerManifest, ServerExport } from "../compile/serverSplit"
18
+ export { validateArgs, ValidationError } from "./validate"
19
+ export type { ParamSchema, Schema as ParamSchemaNode } from "./validate"
20
+ export { createAuthHost, signNonce, verifyNonce, sha256 } from "./auth/host"
21
+ export type { AuthHost, AuthHostConfig, AuthMail } from "./auth/host"
22
+ export type { AuthUser, AuthState, AuthOps, OAuthProfile, OAuthCredential } from "./auth/types"
23
+ export type { AuthProvider, AppConfig } from "./auth/appConfig"
24
+
25
+ import type { LoadedServer } from "./runtime"
26
+ import type { Field, FieldDef } from "./db/fields"
27
+ import type { Model } from "./db/types"
28
+
29
+ /** JSON view of one field for the platform (Data tab, docs): `FieldDef` with nested struct fields flattened
30
+ * to defs and functions/undefineds dropped. */
31
+ export type FieldDescription = Omit<FieldDef, "fields" | "default"> & { fields?: Record<string, FieldDescription>, default?: unknown }
32
+
33
+ /** What the runner reports to the platform after loading a bundle: schema text + models + the
34
+ * endpoint/channel lists (with the manifest's param schemas). */
35
+ export type ServerDescription = {
36
+ /** `.marci` schema text ("" when the project defines no db). */
37
+ marci: string
38
+ models: Record<string, { fields: Record<string, FieldDescription> }>
39
+ endpoints: { id: string, params: unknown[] | null }[]
40
+ channels: string[]
41
+ /** Which models the auth runtime binds to (`null` = the project has no db) and the app.json providers. */
42
+ auth: { user: string | null, session: string | null, providers: string[] }
43
+ /** `app.json` name (when the compile embedded one). */
44
+ appName?: string
45
+ }
46
+
47
+ const describeField = (f: Field<any, any>): FieldDescription => {
48
+ const def = f.def
49
+ const out: FieldDescription = { ...def, fields: undefined, default: undefined }
50
+ delete out.fields
51
+ delete out.default
52
+ if (def.hasDefault) out.default = def.default === undefined ? null : def.default
53
+ if (def.fields) out.fields = Object.fromEntries(Object.entries(def.fields).map(([k, v]) => [k, describeField(v)]))
54
+ return JSON.parse(JSON.stringify(out))
55
+ }
56
+
57
+ export const describeServer = (server: LoadedServer): ServerDescription => {
58
+ const db = server.dbs[0]
59
+ const models: ServerDescription["models"] = {}
60
+ if (db) {
61
+ for (const [name, m] of Object.entries(db.$models as Record<string, Model>)) {
62
+ models[name] = { fields: Object.fromEntries(Object.entries(m.fields as Record<string, Field<any, any>>).map(([k, f]) => [k, describeField(f)])) }
63
+ }
64
+ }
65
+ const params = (server.manifest.params ?? {}) as Record<string, unknown[]>
66
+ return {
67
+ marci: db?.$schema ?? "",
68
+ models,
69
+ endpoints: [...server.endpoints.keys()].map(id => ({ id, params: params[id] ?? null })),
70
+ channels: [...server.channels.keys()],
71
+ auth: { user: db?.$auth.user ?? null, session: db?.$auth.session ?? null, providers: server.manifest.app?.auth?.providers ?? [] },
72
+ appName: server.manifest.app?.name,
73
+ }
74
+ }
@@ -0,0 +1,13 @@
1
+ /*
2
+ * The SERVER inject module — the globals available in `*.server.ts` files (docs/backend-plan.md §4).
3
+ * chisel injects these into the server bundle exactly like ./inject.ts does for the client bundle;
4
+ * nothing here may reach the client bundle. Keep this the ONLY file that exports server globals.
5
+ *
6
+ * Globals: t, model, defineDb, ref (schema + queries), ApiError, channel, request, auth.
7
+ */
8
+
9
+ export { t, model, defineDb, ref } from "./db"
10
+ export { ApiError } from "./errors"
11
+ export { channel } from "./channel"
12
+ export { request } from "./context"
13
+ export { auth } from "./auth/global"
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Host side of a compiled server bundle — used by the runner (packages/lecodes-runner) and by tests.
3
+ * Imported normally (Node/Bun), NOT through chisel: the bundle carries its own SDK copy and talks
4
+ * to this module only through globals (`__lecodesServer`, `__lecodesRequest`, `__lecodesPublish`).
5
+ *
6
+ * evaluate the bundle (it sets globalThis.__lecodesServer)
7
+ * const server = loadServerModules() // classify exports, name channels
8
+ * const invoke = createInvoker(server) // validate → run in request context → envelope
9
+ * await invoke("notes.server.ts#listNotes", [20], { headers, ip })
10
+ */
11
+
12
+ import { AsyncLocalStorage } from "node:async_hooks"
13
+ import type { ServerManifest } from "../compile/serverSplit"
14
+ import type { AuthHost } from "./auth/host"
15
+ import type { AuthState } from "./auth/types"
16
+ import { setChannelPublisher, type Channel } from "./channel"
17
+ import { setRequestProvider, type RequestContext } from "./context"
18
+ import type { Db } from "./db/types"
19
+ import { takeRegisteredDbs } from "./db/defineDb"
20
+ import { validateArgs, ValidationError, type ParamSchema } from "./validate"
21
+
22
+ export type ServerRegistration = { modules: Record<string, Record<string, unknown>>, manifest: ServerManifest }
23
+
24
+ export type LoadedServer = {
25
+ endpoints: Map<string, (...args: any[]) => unknown>
26
+ channels: Map<string, Channel<any>>
27
+ /** Every `defineDb` handle — exported or not (the bundle registers them on globalThis; normally exactly one). */
28
+ dbs: Db<any>[]
29
+ manifest: ServerManifest
30
+ }
31
+
32
+ const isDb = (v: unknown): v is Db<any> => typeof v === "object" && v !== null && typeof (v as Db<any>).$schema === "string"
33
+ const isChannel = (v: unknown): v is Channel<any> => typeof v === "object" && v !== null && (v as Channel<any>).__channel === true
34
+
35
+ /** Read the registration a server bundle left on `globalThis.__lecodesServer` (or a given one). */
36
+ export const loadServerModules = (
37
+ reg: ServerRegistration | undefined = (globalThis as any).__lecodesServer,
38
+ ): LoadedServer => {
39
+ if (!reg) throw new Error("loadServerModules: no server bundle registered (globalThis.__lecodesServer)")
40
+ const out: LoadedServer = { endpoints: new Map(), channels: new Map(), dbs: [], manifest: reg.manifest }
41
+ for (const [mod, exports] of Object.entries(reg.modules)) {
42
+ for (const [name, value] of Object.entries(exports)) {
43
+ const id = `${mod}#${name}`
44
+ if (typeof value === "function") out.endpoints.set(id, value as (...args: any[]) => unknown)
45
+ else if (isChannel(value)) { value.__id = id; out.channels.set(id, value) }
46
+ else if (isDb(value)) out.dbs.push(value)
47
+ }
48
+ }
49
+ // Non-exported handles (`const db = defineDb(...)`): the bundle's SDK copy registered them on globalThis.
50
+ for (const db of takeRegisteredDbs()) if (!out.dbs.includes(db)) out.dbs.push(db)
51
+ return out
52
+ }
53
+
54
+ /** The wire envelope. `session` = a token the client must store from now on (new guest session / rotation). */
55
+ export type InvokeResult =
56
+ | { ok: true, result: unknown, session?: string }
57
+ | { ok: false, status: number, message: string, session?: string }
58
+
59
+ export type InvokerOptions = {
60
+ /** Validate args against the manifest's param schemas (default true; endpoints without a schema pass). */
61
+ validate?: boolean
62
+ /** Where unexpected (non-ApiError) failures are reported. Default: console.error. */
63
+ onError?: (id: string, error: unknown) => void
64
+ /** The auth host (./auth/host.ts): resolves the bearer token into `ctx.auth` before each call. Absent = no sessions. */
65
+ auth?: AuthHost | null
66
+ }
67
+
68
+ // The bundle's ApiError is a different class object than ours (its own SDK copy) — duck-type it.
69
+ const apiStatus = (e: unknown): number | null =>
70
+ e && typeof e === "object" && (e as { name?: string }).name === "ApiError" && typeof (e as { status?: unknown }).status === "number"
71
+ ? (e as { status: number }).status : null
72
+
73
+ /**
74
+ * Build the invoker: `invoke(id, args, ctx)` runs endpoint `id` inside an AsyncLocalStorage-scoped
75
+ * request context (what the `request`/`auth` globals read) and returns the wire envelope.
76
+ */
77
+ // One request store for endpoints AND channel guards (a second store would steal the provider).
78
+ const als = new AsyncLocalStorage<RequestContext>()
79
+ const installProvider = () => setRequestProvider(() => als.getStore())
80
+
81
+ // A token minted/rotated during the call rides on the envelope (the client transport stores it).
82
+ const withSession = (r: InvokeResult, rc: RequestContext): InvokeResult => {
83
+ const issued = (rc.auth as AuthState | undefined)?.issuedToken
84
+ return issued ? { ...r, session: issued } : r
85
+ }
86
+
87
+ export const createInvoker = (server: LoadedServer, opts: InvokerOptions = {}) => {
88
+ installProvider()
89
+ const validate = opts.validate ?? true
90
+ const onError = opts.onError ?? ((id, e) => console.error(`[server] ${id}:`, e))
91
+ const params = server.manifest.params as Record<string, ParamSchema[]> | undefined
92
+ const auth = opts.auth ?? null
93
+
94
+ return async (id: string, args: unknown[], ctx: Omit<RequestContext, "id"> = { headers: {} }): Promise<InvokeResult> => {
95
+ const fn = server.endpoints.get(id)
96
+ if (!fn) return { ok: false, status: 404, message: `Unknown endpoint ${id}` }
97
+ if (!Array.isArray(args)) return { ok: false, status: 400, message: "args must be an array" }
98
+ const rc: RequestContext = { ...ctx, id }
99
+ try {
100
+ if (validate && params?.[id]) validateArgs(params[id], args)
101
+ if (auth) await auth.resolve(rc)
102
+ const result = await als.run(rc, () => fn(...args))
103
+ return withSession({ ok: true, result: result === undefined ? null : result }, rc)
104
+ } catch (e) {
105
+ const status = apiStatus(e)
106
+ if (status !== null) return withSession({ ok: false, status, message: (e as Error).message }, rc)
107
+ if (e instanceof ValidationError) return { ok: false, status: 400, message: e.message }
108
+ onError(id, e)
109
+ return withSession({ ok: false, status: 500, message: "Internal error" }, rc)
110
+ }
111
+ }
112
+ }
113
+
114
+ /** Run a channel's `onJoin` guard for a subscription (same request scoping as endpoints). */
115
+ export const createJoinGuard = (server: LoadedServer, opts: Pick<InvokerOptions, "auth"> = {}) => {
116
+ installProvider()
117
+ const auth = opts.auth ?? null
118
+ return async (channelId: string, topic: string, ctx: Omit<RequestContext, "id"> = { headers: {} }): Promise<InvokeResult> => {
119
+ const ch = server.channels.get(channelId)
120
+ if (!ch) return { ok: false, status: 404, message: `Unknown channel ${channelId}` }
121
+ const rc: RequestContext = { ...ctx, id: channelId }
122
+ try {
123
+ if (auth) await auth.resolve(rc)
124
+ await als.run(rc, () => ch.options.onJoin?.(topic))
125
+ return withSession({ ok: true, result: null }, rc)
126
+ } catch (e) {
127
+ const status = apiStatus(e)
128
+ return withSession({ ok: false, status: status ?? 500, message: status !== null ? (e as Error).message : "Internal error" }, rc)
129
+ }
130
+ }
131
+ }
132
+
133
+ export { setChannelPublisher, setRequestProvider }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Runtime validation of endpoint arguments against the compact schemas the compiler derives from the
3
+ * TypeScript parameter types (src/compile/serverTypes.ts). Dependency-free; the schema is JSON so it
4
+ * travels inside the server bundle's manifest.
5
+ */
6
+
7
+ export type Schema =
8
+ | { t: "any" }
9
+ | { t: "string" } | { t: "number" } | { t: "boolean" } | { t: "null" } | { t: "undefined" }
10
+ | { t: "lit", v: string | number | boolean }
11
+ | { t: "array", of: Schema }
12
+ | { t: "tuple", items: Schema[], rest?: Schema }
13
+ | { t: "object", props: Record<string, Schema>, optional?: string[], index?: Schema }
14
+ | { t: "union", of: Schema[] }
15
+
16
+ /** One endpoint parameter: its schema and whether it may be omitted (`?`, default value, rest). */
17
+ export type ParamSchema = { name: string, schema: Schema, optional?: boolean, rest?: boolean }
18
+
19
+ export class ValidationError extends Error {
20
+ readonly status = 400
21
+ constructor(message: string) { super(message); this.name = "ValidationError" }
22
+ }
23
+
24
+ const typeName = (v: unknown) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v
25
+
26
+ /** Returns the first problem as a message, or null when `value` matches. */
27
+ export const check = (schema: Schema, value: unknown, path: string): string | null => {
28
+ switch (schema.t) {
29
+ case "any": return null
30
+ case "string": case "number": case "boolean":
31
+ return typeof value === schema.t ? null : `${path}: expected ${schema.t}, got ${typeName(value)}`
32
+ case "null": return value === null ? null : `${path}: expected null, got ${typeName(value)}`
33
+ case "undefined": return value === undefined ? null : `${path}: expected undefined, got ${typeName(value)}`
34
+ case "lit": return value === schema.v ? null : `${path}: expected ${JSON.stringify(schema.v)}, got ${JSON.stringify(value)}`
35
+ case "array":
36
+ if (!Array.isArray(value)) return `${path}: expected array, got ${typeName(value)}`
37
+ for (let i = 0; i < value.length; i++) { const e = check(schema.of, value[i], `${path}[${i}]`); if (e) return e }
38
+ return null
39
+ case "tuple": {
40
+ if (!Array.isArray(value)) return `${path}: expected tuple, got ${typeName(value)}`
41
+ if (value.length < schema.items.length || (!schema.rest && value.length > schema.items.length))
42
+ return `${path}: expected ${schema.items.length} items, got ${value.length}`
43
+ for (let i = 0; i < value.length; i++) {
44
+ const s = i < schema.items.length ? schema.items[i] : schema.rest!
45
+ const e = check(s, value[i], `${path}[${i}]`); if (e) return e
46
+ }
47
+ return null
48
+ }
49
+ case "object": {
50
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return `${path}: expected object, got ${typeName(value)}`
51
+ const obj = value as Record<string, unknown>
52
+ const optional = new Set(schema.optional ?? [])
53
+ for (const [k, s] of Object.entries(schema.props)) {
54
+ if (!(k in obj) || obj[k] === undefined) { if (optional.has(k)) continue; return `${path}.${k}: required` }
55
+ const e = check(s, obj[k], `${path}.${k}`); if (e) return e
56
+ }
57
+ for (const k of Object.keys(obj)) {
58
+ if (k in schema.props) continue
59
+ if (schema.index) { const e = check(schema.index, obj[k], `${path}.${k}`); if (e) return e }
60
+ // unknown keys without an index signature are ignored (structural typing)
61
+ }
62
+ return null
63
+ }
64
+ case "union": {
65
+ const errors: string[] = []
66
+ for (const s of schema.of) { const e = check(s, value, path); if (!e) return null; errors.push(e) }
67
+ return `${path}: no union member matched (${errors.join("; ")})`
68
+ }
69
+ }
70
+ }
71
+
72
+ /** Validate a positional argument list. Extra arguments are ignored (JS call semantics). */
73
+ export const validateArgs = (params: ParamSchema[], args: unknown[]): void => {
74
+ for (let i = 0; i < params.length; i++) {
75
+ const p = params[i]
76
+ if (p.rest) {
77
+ const rest = args.slice(i)
78
+ const e = check(p.schema, rest, p.name)
79
+ if (e) throw new ValidationError(e)
80
+ return
81
+ }
82
+ const v = args[i]
83
+ if (v === undefined) { if (p.optional) continue; throw new ValidationError(`${p.name}: required`) }
84
+ const e = check(p.schema, v, p.name)
85
+ if (e) throw new ValidationError(e)
86
+ }
87
+ }