Repository navigation
feat: portable generated API surface + typed service-binding client - #337
Conversation
`api.ts` imports `dataModel.ts` for `Doc`/`Id`, and `dataModel.ts` imported `@lunora/server/data-model`. So a sibling package — a web app, another Worker — that only wanted the typed `api` had to install and compile a SERVER package to get a branded string and a few interfaces. That is the raw-TS coupling issue #18 narrowed but did not remove. The half that needs the server package is the query-DSL binding layer: `WithArg`, `LoadWith`, the reader/writer facades, the ORM builders, and the `Where`/`SearchReader` re-exports. None of it is referenced outside `server.ts`, which is the server-only file already — so it moves there, and `dataModel.ts` is left with the schema's own shapes and no imports at all. That is asserted directly rather than implied: the new test reads the emitted `dataModel.ts` and requires it to contain no import statement and no mention of `@lunora/server` or `lunorash/server`. `emitDataModel` loses its `useUmbrella` parameter, which only ever chose between two specifiers it no longer emits. Users importing the moved types from `./_generated/dataModel` must import them from `./_generated/server` instead. Pre-1.0, and the split is the point: the file a consumer compiles should not name a package it cannot install. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
`ctx.run*` covers calls within one Lunora app. A sibling Worker in the same
account had nothing, so the documented path was the callee's public HTTPS route
— which teams reached with a plain fetch and a hand-rolled HMAC. That pays a
per-request fee, a public-internet round trip, and the upkeep of a shared secret
for a call between two Workers on one account, and because it goes out untyped, a
renamed function surfaces as a runtime 404.
`createServiceClient(env.BACKEND)` types `query`/`mutation`/`action` against the
generated `api`, so the call is checked at compile time. A service binding incurs
no request fee, never leaves the edge, and is authenticated by construction — the
binding IS the capability, so the callee needs no public route.
Three details that would each have been a silent failure:
- Arguments and results go through the same wire codec as the HTTP client. Plain
JSON cannot carry a `bigint` — `JSON.stringify` throws on one — so skipping it
would make the money path fail over bindings and nowhere else.
- The response envelope is `{ result }` / `{ error: { code, message, data } }`,
and errors are reconstructed with their `code` and wire-decoded `data`, so a
caller across a binding sees what it would see calling in-process.
- A non-JSON reply names the likeliest cause — a binding pointed at a Worker that
is not this app — because the status alone sends people hunting through the
callee's handlers instead of their wrangler config.
The binding is accepted structurally as `{ fetch }`: `env.BACKEND` satisfies it
without dragging `@cloudflare/workers-types` into consumers, and a one-method fake
is a complete test double.
Only public functions are reachable; an `internal*` procedure is absent from `api`
and refused by the callee, because a binding is a boundary between deployments
rather than the intra-app `ctx.run*` seam.
Closes the last open half of issue #16 — the docs previously said no such client
existed, and stated the raw-TS coupling that the dataModel split just removed.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. 🗂️ Base branches to auto review (2)
Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Thank you for following the naming conventions! 🙏 |
|
Thank you for confirming the Contributor License Agreement! 🙏 |
…gen (#336) * refactor(codegen): extract the declaration-surface phase from runCodegen `runCodegen` was 619 lines carrying a `sonarjs/cognitive-complexity` suppression whose stated reason was that splitting it "would obscure the linear pipeline". The previous commit disproved that: it moved ~130 lines of discovery from the middle of the function to the top, and that the move was mechanically possible is the evidence a seam was already there. The seam is the ordering constraint the reorder existed to satisfy. Everything feeding `dataModel.ts`/`server.ts` must run before `discoverFunctions` infers against them, and — the half that makes the split safe — none of it may depend on inference. `buildDeclarationSurface` is now that phase by construction rather than by comment: it cannot read the discovered functions, because it does not receive them. The thirteen `const hasX = featureUsage.x` aliases are gone. Each restated one map lookup and carried a comment explaining the capability rather than the alias, so call sites read `featureUsage.<key>` directly. The three that were never plain lookups keep their own fields and say why: `hasBrowser` (a sandbox tool drives it too), `hasFlags` and `hasNotify` (gated on the module file existing, not on code usage — the ShardDO imports their default export, so wiring the ctx without the module emits a broken import). `emitServer`/`emitShard`/`emitApp` signatures are untouched, so goldens and the emit tests are unaffected. `assertNoWorkflowAgentCollision` moves with the discovery it guards and is no longer exported — nothing outside used it. runCodegen 619 → 474 lines; the new module is 290. Behaviour is unchanged: 1053 codegen tests pass, and regenerating every example's `_generated/` produces byte-identical output. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * feat: portable generated API surface + typed service-binding client (#337) * feat(codegen): make dataModel.ts compilable without a server dependency `api.ts` imports `dataModel.ts` for `Doc`/`Id`, and `dataModel.ts` imported `@lunora/server/data-model`. So a sibling package — a web app, another Worker — that only wanted the typed `api` had to install and compile a SERVER package to get a branded string and a few interfaces. That is the raw-TS coupling issue #18 narrowed but did not remove. The half that needs the server package is the query-DSL binding layer: `WithArg`, `LoadWith`, the reader/writer facades, the ORM builders, and the `Where`/`SearchReader` re-exports. None of it is referenced outside `server.ts`, which is the server-only file already — so it moves there, and `dataModel.ts` is left with the schema's own shapes and no imports at all. That is asserted directly rather than implied: the new test reads the emitted `dataModel.ts` and requires it to contain no import statement and no mention of `@lunora/server` or `lunorash/server`. `emitDataModel` loses its `useUmbrella` parameter, which only ever chose between two specifiers it no longer emits. Users importing the moved types from `./_generated/dataModel` must import them from `./_generated/server` instead. Pre-1.0, and the split is the point: the file a consumer compiles should not name a package it cannot install. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * feat(client): add a typed service-binding client for worker→worker calls `ctx.run*` covers calls within one Lunora app. A sibling Worker in the same account had nothing, so the documented path was the callee's public HTTPS route — which teams reached with a plain fetch and a hand-rolled HMAC. That pays a per-request fee, a public-internet round trip, and the upkeep of a shared secret for a call between two Workers on one account, and because it goes out untyped, a renamed function surfaces as a runtime 404. `createServiceClient(env.BACKEND)` types `query`/`mutation`/`action` against the generated `api`, so the call is checked at compile time. A service binding incurs no request fee, never leaves the edge, and is authenticated by construction — the binding IS the capability, so the callee needs no public route. Three details that would each have been a silent failure: - Arguments and results go through the same wire codec as the HTTP client. Plain JSON cannot carry a `bigint` — `JSON.stringify` throws on one — so skipping it would make the money path fail over bindings and nowhere else. - The response envelope is `{ result }` / `{ error: { code, message, data } }`, and errors are reconstructed with their `code` and wire-decoded `data`, so a caller across a binding sees what it would see calling in-process. - A non-JSON reply names the likeliest cause — a binding pointed at a Worker that is not this app — because the status alone sends people hunting through the callee's handlers instead of their wrangler config. The binding is accepted structurally as `{ fetch }`: `env.BACKEND` satisfies it without dragging `@cloudflare/workers-types` into consumers, and a one-method fake is a complete test double. Only public functions are reachable; an `internal*` procedure is absent from `api` and refused by the callee, because a binding is a boundary between deployments rather than the intra-app `ctx.run*` seam. Closes the last open half of issue #16 — the docs previously said no such client existed, and stated the raw-TS coupling that the dataModel split just removed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
…lumns + binding manifest (#335) * fix(codegen): resolve a const-referenced validator to its initializer A validator written once and reused — `const vDocumentDoc = v.object({…})`, then `.output(v.union(vDocumentDoc, v.null()))` — reached the parser as a bare `Identifier`, which is not a `CallExpression`, so it fell through to the `{ kind: "any" }` catch-all and rendered `unknown` in the generated api. `unknown` does not stay contained: a consumer narrowing it gets `{}`, and every property access on that is an error. The only workaround was to inline the object literal at every call site, giving up the one place a table's public shape is defined. Resolution goes through the symbol (with `getAliasedSymbol` for an import), so a validator imported from a sibling module resolves like a local one, and it applies to every validator position — `.input()` shapes, table columns, and nested `v.array(vRow)` arguments all route through the same parser and degraded the same way. A const holding something the parser does not recognise keeps the previous behaviour rather than aborting the run. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * fix(codegen): rebase relative import() qualifiers in argument types The type checker prints a type relative to the module it was read in, so a recovered `v.from(externalSchema)` whose type names something from the handler's own `./lib/…` renders as `import("./lib/tools").Tool`. Inlined verbatim into `lunora/_generated/api.ts` that resolves to `lunora/_generated/lib/tools`, which does not exist. Return types were already rebased against the output directory; argument types were not, so the same qualifier in an argument position stayed one directory too deep. That is a TS2307 inside a generated file while `lunora codegen` exits 0, which is why it only surfaces when a sibling package typechecks the same file and has nowhere to filter the error away. The generated-vs-user rebase order is load-bearing, so the pair now lives behind one helper applied to arguments, returns, and HTTP stream chunk types alike. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * fix(codegen): expand a type imported into the handler's module The reachability guard only treated a type as unprintable when it was declared in the handler's OWN file. A type declared elsewhere in user code but imported into that file is equally nameable there, so the checker prints it bare too — and a generated file imports nothing from the user's modules, so the bare name lands in `api.ts`/`functions.ts` as an undeclared identifier (TS2304). A shared `./lib/types` interface is the ordinary way to write one, so this was easy to hit. Bare-vs-qualified is now decided by asking the checker what it renders: an out-of-scope type comes back carrying an `import("…")` qualifier, which the emitter rebases instead, so only the qualifier-free rendering is expanded. `_generated/` declarations are excluded — the emitter deliberately imports `Doc`/`Id` by name, and expanding them instead discards a branded `Id` (not an expandable object) and falls back to `unknown`, which collapses every `Doc`/`Id`-shaped return type at once. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * fix(codegen): emit the declaration surface before inferring against it Codegen infers each handler's return type against the ts-morph project as it stands when `discoverFunctions` runs. Everything a handler's type can depend on — `Doc`/`Id` from `dataModel.ts`, the schema-typed `ctx.db` and its paginated results from `server.ts` — lives in those two files, so whatever version of them the project happens to hold is what pass 1 sees. Emitting them only on a cold start was not enough. An ordinary edit — add a table, add a handler returning a row from it — left pass 1 inferring against the previous run's declarations, which name neither the new table nor its `Doc`. The return collapsed to `unknown`/`{}` and the collapse was written into `api.ts`, so the tree converged only on a second run. That is what pushes a project into wrapping the CLI in a run-until-the-hash-stops-changing loop. Both files are pure functions of inputs that never depended on `discoverFunctions`, so their discovery is hoisted above it and each is now rendered exactly once, before inference. Rendering unconditionally costs nothing extra: these are the same two strings the run emits anyway, and `writeIfChanged` no-ops when the bytes match, so an unchanged project touches neither disk nor any watcher. Syncing the project copy uses in-place `replaceWithText` rather than `createSourceFile` with overwrite. The latter swaps in a new `SourceFile`, so already-loaded handler modules keep pointing at the orphaned one and their `dataModel` type import stops resolving — which collapses every `Doc`/`Id`-shaped return type in the run. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * feat(values): allow v.from() as a table column `v.from(externalSchema)` was args-only, so a project that needs both validator languages — commonly because an SDK's types demand zod — had to maintain the same shape twice, in two languages, and hope they stayed in step. Inlining the `v.*` equivalent at the column was the only option, which gives up the one place the shape is defined. The restriction existed because a column needs a type and codegen could not recover one from an external schema. It can now, through `~standard.types.output`, and a column needs no SQL type of its own: a shard row is a JSON document, and a `.global()` table maps this to a JSON text column exactly like `v.object`/`v.record`/`v.union` already do. So the emitted drizzle column carries the recovered type as its `$type<…>()` annotation instead of `unknown`, and the runtime validates through the wrapped schema as before. Two consequences stated rather than hidden. The on-disk form is the JSON encoding of whatever the external schema produces, so `v.from(z.string())` holds `"x"` rather than a bare TEXT `x` — use `v.string()` when the plain column type matters. And `@lunora/seed` cannot introspect an external schema to invent a conforming value, so it now refuses such a column by name rather than generating one that fails validation on the very next insert. `isOrWrapsFromValidator` keeps its export — nothing calls it from `defineTable` any more, but it remains the way tooling asks whether a value is validated externally. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * feat(cli): add build --emit-bindings for external deployers `lunora deploy` is the batteries-included path: infer, reconcile, provision, publish. A project running its own infrastructure-as-code wants only the first half of that — the bundle — plus a statement of what the bundle expects to be bound to, so its own program can create the resources. Without one, those requirements get restated by hand in the IaC program and the two drift silently: a binding added on one side is simply missing on the other, and the failure lands at runtime as an undefined `env.X`. `lunora build --emit-bindings <file>` writes a JSON manifest of the bindings, crons, `vars` names, and compatibility settings the built Worker needs. It is derived from `wrangler.jsonc` AFTER the pre-deploy pipeline has reconciled it, because that is the point at which the config IS the resolved answer — reading it earlier would describe what the project happened to write down rather than what the bundle actually needs. Three decisions worth stating: - Every binding is listed, including the ones Lunora cannot provision (KV, Hyperdrive and Vectorize ids it warns about and never writes). Those are precisely the ones an external deployer CAN create. - An unrecognised wrangler section is reported in `unknown` and warned about rather than dropped, so a binding type added to wrangler before it is added here degrades to a name instead of vanishing into an under-provisioned deploy. - `vars` contributes names only. The manifest is committed and read by CI, and a var can hold a value a project would rather not publish. A project with no wrangler config fails the flag instead of writing an empty manifest — "this Worker needs nothing" is the one answer a deployer must never be handed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * feat(config): configure a project's linters to skip generated files Codegen output lands in the repo and is linted like source, so a project's first lint run reports thousands of errors in files nobody wrote — one port measured 23,553, effectively all of them from generated output. Every consumer independently rediscovers the same five paths. `.gitignore` does not cover it. Two of the paths are committed on purpose (the schema-drift baseline is the whole point of the deploy gate), and a project may legitimately commit `_generated/` so the API surface is reviewable — at which point every gitignore-derived exclusion stops applying. `detectLintTools` reads both the manifest and the config files on disk: a dependency without a config is a tool about to be configured, and a config without a dependency is one installed globally or hoisted from a monorepo root. Missing either signal means silently skipping a tool the project runs. `applyLintIgnores` writes each tool's own mechanism, verified rather than assumed: - Prettier gets `.prettierignore`. - oxlint gets `ignorePatterns` in `.oxlintrc.json`, the key its published configuration schema declares. - Biome v2 has no ignore key — exclusions are negated patterns in `files.includes`, seeded with `**` so they have something to subtract from. v1's `files.ignore` is still in the wild, so the writer follows whichever key the config already uses instead of sniffing a version. - ESLint gets an `eslint.config.js` when the project has none, and is reported as `manual` with a paste-ready snippet when it already has one — a flat config is arbitrary JavaScript and is not something to rewrite on a user's behalf. No `.eslintignore` is ever written. Flat config removed support for it, and ESLint warns about the file while ignoring its contents, so creating one would leave behind something that looks like it works. Every writer appends only what is missing, so re-running is a no-op. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * feat(cli): ask at init which linters to configure, detect them on add Two entry points, because they know different things. `lunora init` asks. A template ships no lint tooling, so at scaffold time there is usually nothing to detect — the answer is the developer's, not the filesystem's. Whatever IS detectable pre-selects the prompt, so it confirms rather than guesses, and a non-interactive run configures the detected set instead of blocking automation on a question. `lunora add` does not ask. It already refuses to run outside a Lunora project, so the manifest answers the question, and prompting on every feature install would be noise. It re-runs after each successful add because that is exactly when the generated surface grows — and because a team that adopted Prettier or Biome after `init`, or ported an existing app in, would otherwise never be configured at all. Both go through the same writers, which append only what is missing, so the common case is silent. Where the change cannot be made safely — an existing ESLint flat config, which is arbitrary JavaScript — the exact snippet is printed rather than the omission left to surface as a few thousand lint errors. The lint prompt gets its own injection point rather than reusing the feature offer's: that one is pinned to the feature value union, so sharing it would only typecheck through a cast. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * fix(sql-store): decode a v.from() column on a global table `sqliteEncode` keys off the runtime JS type; `sqliteDecode` keys off the validator kind, and `from` was in neither group — so it fell through to "verbatim" and a `.global()` column stored as JSON came back as the raw string. The generated `Doc_*` and the drizzle `$type<…>()` both promise the object, so every consumer type-checks clean and fails at the first property access. One decoder backs D1, Postgres, MySQL, the studio data browser, and admin export alike, so the miss reached all of them. `from` joins `union`/`any` rather than `object`/`array`/`record`: an external Standard Schema can describe a string as easily as an object, and since encode is JS-type driven, parsing unconditionally would read a `v.from(z.string())` column holding "123" back as the NUMBER 123. The union rule parses only a stored JSON non-scalar, which round-trips both shapes. The MySQL dialect's LONGTEXT mapping is correct for the same reason and now says so — a `JSON` column would reject the bare string at insert. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * fix(codegen): rebase column types, tighten scope check, keep _generated atomic Four fixes to the codegen changes earlier on this branch. **Column types were never rebased.** `api.ts`/`functions.ts` route argument and return types through the relative-qualifier rebase; `dataModel.ts` and the drizzle view did not, because a `v.from()` column was rejected at runtime and the path was unreachable. Allowing the column opened it: a recovered type naming the schema module's own `./lib/…` landed verbatim one directory too deep — TS2307 inside a generated file while codegen exits 0. Both emitters now rebase against `schema.ts`, applied to the whole rendered file so a future column-rendering path cannot miss it. `emitCollections` was the last un-rebased argument site. **The reachability probe conflated a type with its type arguments.** Deciding "printed bare" by scanning the rendered text for `import(` cleared an imported `Wrapper<import("./x").Bar>`, because the ARGUMENT supplied the qualifier — so the wrapper printed bare and became TS2304, the same bug class one generic deep. It now asks the handler's source file whether it imports the name, which is depth-independent. **Alias resolution swallowed real errors.** A catch around the recursive parse also caught `Unsupported validator kind` raised by a typo inside a hoisted validator, so `const vRow = v.object({ x: v.strng() })` rendered `unknown` while the identical expression written inline aborted the run. Two forms that are meant to be interchangeable must not diverge on the error path. Replaced with a precondition — the target must look like a `v.*` chain — so anything past the gate throws exactly as the inline form does. **A failed run committed a torn `_generated/`.** Writing the declaration surface before inference meant any later throw left a new `dataModel.ts` beside a stale `api.ts`/`shard.ts`; worst on a table removal, where `Doc_x` vanishes while its referrers stay and the errors point at generated code rather than the cause. The disk write was never what made the fix work — `discoverFunctions` reads the ts-morph project, which the in-memory sync feeds — so the writes move back to the write phase and the run is all-or-nothing again. Also removes a 27-line comment describing the deleted cold-start bootstrap, which asserted the opposite of what now runs. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * fix(config): never shadow a workspace lint config from a package directory `detectLintTools` fires on a declared dependency alone — deliberately — but in a monorepo the dependency sits in the package while the config sits at the root. The writers then created a config in the directory they were handed, which does not add ignores there: it SHADOWS the root. ESLint 9 stops at the first flat config walking up, so a package-level file holding only `ignores` and no rules silently switched off every rule the root enforced, and lint still exited 0. Biome and oxlint replace an outer rule set the same way. `lunora add` ran this with no prompt and no opt-out. Configs are now resolved by walking up to the repository boundary. A config found above the project is reported with a paste-ready snippet, never duplicated downward; creation is reserved for the case it was meant for — a standalone project with nothing above it. `.prettierignore` is exempt: it only ever adds exclusions and resolves from the working directory, so a nested one cannot disable anything. A created ESLint config is now `eslint.config.mjs`. The body is ESM, and a `.js` config in a package without `"type": "module"` is loaded as CommonJS, where ESLint dies on `Unexpected token 'export'`. `lunora init --dry-run` no longer writes. It was the one post-scaffold step without a guard, and `--in-place --dry-run` targets the user's existing repo. The manifest gains three corrections: `$schema` is no longer reported as unmodelled on every real project (it heads every scaffolded wrangler config, and crying wolf trains users to ignore the one signal the design depends on); `env.*` and `assets` are no longer silently dropped as non-binding settings — `assets` is modelled, `env` is reported; and an entry with no binding name is reported rather than emitted as `{"binding": ""}`, which hands an IaC program a resource it cannot wire. Internals: the four parallel per-tool maps collapse to one table, the duplicated dependency reader gives way to the package's own `readProjectDependencyNames`, the two copies of the outcome-reporting loop become one helper, `collectBindings` splits into three functions and drops its complexity suppression, and `writeBindingManifest` returns a typed result instead of "a string means failure". `@lunora/seed`'s refusal message now names escapes the seeder actually offers (`overrides`, `only`) instead of one it does not. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * refactor(codegen): extract the declaration-surface phase from runCodegen (#336) * refactor(codegen): extract the declaration-surface phase from runCodegen `runCodegen` was 619 lines carrying a `sonarjs/cognitive-complexity` suppression whose stated reason was that splitting it "would obscure the linear pipeline". The previous commit disproved that: it moved ~130 lines of discovery from the middle of the function to the top, and that the move was mechanically possible is the evidence a seam was already there. The seam is the ordering constraint the reorder existed to satisfy. Everything feeding `dataModel.ts`/`server.ts` must run before `discoverFunctions` infers against them, and — the half that makes the split safe — none of it may depend on inference. `buildDeclarationSurface` is now that phase by construction rather than by comment: it cannot read the discovered functions, because it does not receive them. The thirteen `const hasX = featureUsage.x` aliases are gone. Each restated one map lookup and carried a comment explaining the capability rather than the alias, so call sites read `featureUsage.<key>` directly. The three that were never plain lookups keep their own fields and say why: `hasBrowser` (a sandbox tool drives it too), `hasFlags` and `hasNotify` (gated on the module file existing, not on code usage — the ShardDO imports their default export, so wiring the ctx without the module emits a broken import). `emitServer`/`emitShard`/`emitApp` signatures are untouched, so goldens and the emit tests are unaffected. `assertNoWorkflowAgentCollision` moves with the discovery it guards and is no longer exported — nothing outside used it. runCodegen 619 → 474 lines; the new module is 290. Behaviour is unchanged: 1053 codegen tests pass, and regenerating every example's `_generated/` produces byte-identical output. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * feat: portable generated API surface + typed service-binding client (#337) * feat(codegen): make dataModel.ts compilable without a server dependency `api.ts` imports `dataModel.ts` for `Doc`/`Id`, and `dataModel.ts` imported `@lunora/server/data-model`. So a sibling package — a web app, another Worker — that only wanted the typed `api` had to install and compile a SERVER package to get a branded string and a few interfaces. That is the raw-TS coupling issue #18 narrowed but did not remove. The half that needs the server package is the query-DSL binding layer: `WithArg`, `LoadWith`, the reader/writer facades, the ORM builders, and the `Where`/`SearchReader` re-exports. None of it is referenced outside `server.ts`, which is the server-only file already — so it moves there, and `dataModel.ts` is left with the schema's own shapes and no imports at all. That is asserted directly rather than implied: the new test reads the emitted `dataModel.ts` and requires it to contain no import statement and no mention of `@lunora/server` or `lunorash/server`. `emitDataModel` loses its `useUmbrella` parameter, which only ever chose between two specifiers it no longer emits. Users importing the moved types from `./_generated/dataModel` must import them from `./_generated/server` instead. Pre-1.0, and the split is the point: the file a consumer compiles should not name a package it cannot install. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * feat(client): add a typed service-binding client for worker→worker calls `ctx.run*` covers calls within one Lunora app. A sibling Worker in the same account had nothing, so the documented path was the callee's public HTTPS route — which teams reached with a plain fetch and a hand-rolled HMAC. That pays a per-request fee, a public-internet round trip, and the upkeep of a shared secret for a call between two Workers on one account, and because it goes out untyped, a renamed function surfaces as a runtime 404. `createServiceClient(env.BACKEND)` types `query`/`mutation`/`action` against the generated `api`, so the call is checked at compile time. A service binding incurs no request fee, never leaves the edge, and is authenticated by construction — the binding IS the capability, so the callee needs no public route. Three details that would each have been a silent failure: - Arguments and results go through the same wire codec as the HTTP client. Plain JSON cannot carry a `bigint` — `JSON.stringify` throws on one — so skipping it would make the money path fail over bindings and nowhere else. - The response envelope is `{ result }` / `{ error: { code, message, data } }`, and errors are reconstructed with their `code` and wire-decoded `data`, so a caller across a binding sees what it would see calling in-process. - A non-JSON reply names the likeliest cause — a binding pointed at a Worker that is not this app — because the status alone sends people hunting through the callee's handlers instead of their wrangler config. The binding is accepted structurally as `{ fetch }`: `env.BACKEND` satisfies it without dragging `@cloudflare/workers-types` into consumers, and a one-method fake is a complete test double. Only public functions are reachable; an `internal*` procedure is absent from `api` and refused by the callee, because a binding is a boundary between deployments rather than the intra-app `ctx.run*` seam. Closes the last open half of issue #16 — the docs previously said no such client existed, and stated the raw-TS coupling that the dataModel split just removed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> * fix(lunora): forward the client/service subpath through the umbrella Adding `@lunora/client/service` without the matching `lunorash/client/service` mapping broke the umbrella's re-export test, which asserts every upstream subpath has one unless it is a declared opt-out. That test is the whole reason the gap is visible rather than shipping as a subpath that resolves for granular installs and 404s for umbrella ones — a `lunorash`-only project would have had no way to reach the service client at all. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * fix: address review findings on the v.from column and service client Ten of eleven review comments were real; each is fixed below. The eleventh — "re-export Insert/InsertModel from server.ts" — is skipped: both are still exported from `dataModel.ts`, and `server.ts` never re-exported them on alpha either, so nothing was removed. **The storage contract said two different things.** The `v.from` docblock and the drizzle emitter both claimed "always JSON", while `sqliteEncode` stores a scalar verbatim and only JSON-encodes a non-scalar — which is what the value codec and the MySQL LONGTEXT mapping already documented. The code was right and the public docblock was wrong, so the docblock now states the real rule. The drizzle column moves off `mode: "json"` to plain text with the same `$type<…>()` annotation: json mode would `JSON.parse` a bare `hello` and throw on every read of a `v.from(z.string())` column. **Every container was misreported.** The manifest keyed `containers[]` on a `name` field that wrangler entries do not have — `@lunora/config`'s own `ContainerEntry` is `{ class_name }` — so each real container fell into `unnamed`, the manifest inventing a problem. Keyed on `class_name` now, with `image` as the resource an external deployer has to build or pull. **A lint-ignore write failure failed the whole command.** `applyLintIgnores` had no error isolation, and both callers run it AFTER their real work succeeded — so a read-only directory reported `lunora add` as failed when the feature had installed fine. Each writer is now isolated and reports a `failed` outcome the CLI surfaces as a warning. **Service-client fixes.** Errors now carry `hint`/`docsUrl` from the catalog, not just `code`/`data`, so a caller across a binding gets the same actionable error it would get over HTTP. A JSON body that is not an object (`null`, `4`) is reported instead of crashing on `"error" in parsed`. The deliberate absence of the client-identity headers is now stated in the code: a service-binding caller is a server, and inventing a mutation id would fabricate an idempotency key that dedups unrelated writes. **Docs.** The service-client snippet built the client at module scope, where `env` does not exist on Workers — a reader copying it got a reference error. Also corrects the "(and written)" phase comment, which contradicted the atomicity docblock 50 lines below it, and the Biome version framing (v1 accepted `files.includes` too; the writer follows the key, not the version). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 * docs: cover v.from columns, --emit-bindings, and generated-code linting Four pages, two of which asserted the opposite of what now ships. `concepts/data-types.mdx` and `concepts/typescript.mdx` both stated that `v.from()` is arguments-only and that `defineTable` throws on one. It is now allowed as a column, so both say so — with the trade-offs that decide whether you should reach for it: storage follows the runtime type (a `v.from(z.string())` column holds a bare `hello`, which is also why it cannot be a Postgres/MySQL `JSON` column), a comparison index wants a concrete type, `@lunora/seed` refuses the column by name, and the JSON Schema surface documents it as unconstrained. `concepts/monorepos-and-iac.mdx` documents `lunora build --emit-bindings`, the piece that closes the binding-list duplication the rest of that page describes — including why every binding is listed (the ones Lunora cannot provision are exactly the ones your program must create), why `vars` contributes names only, and why a non-empty `unknown` is worth reading before trusting the file. `concepts/generated-code.mdx` gains three facts a reader currently has to discover the hard way: `dataModel.ts` imports nothing, so a sibling package compiles it with `@lunora/client` alone; the linter/formatter configuration `init` and `add` write, including the two cases reported rather than written and why no `.eslintignore` is ever created; and that one codegen run converges, so nobody else builds the run-until-the-hash-stops-changing loop that prompted the fix. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347 --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
|
This pull request has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. |
Stacked on #336 → #335. Base is
refactor/declaration-surface; retarget as the stack lands.Closes the last two open items from the third-party port: #18 (no way to consume the generated API from a sibling package) and #16's remaining half (no typed worker→worker client).
#18 —
dataModel.tsno longer needs a server packageapi.tsimportsdataModel.tsforDoc/Id, anddataModel.tsimported@lunora/server/data-model. So a web app that wanted nothing but the typedapihad to install and compile a server package to get a branded string and a few interfaces.The half that genuinely needs the server package is the query-DSL binding layer —
WithArg,LoadWith, the reader/writer facades, the ORM builders, theWhere/SearchReaderre-exports. Nothing outsideserver.tsreferenced any of it, andserver.tsis the server-only file already, so that is where it now lives.dataModel.tsis left with the schema's own shapes and no imports at all — asserted directly rather than implied:emitDataModelloses itsuseUmbrellaparameter, which only ever chose between two specifiers it no longer emits.Breaking, deliberately: importing the moved types from
./_generated/dataModelmust become./_generated/server. Pre-1.0, and the split is the whole point — the file a consumer compiles should not name a package it cannot install.#16 — a typed service-binding client
ctx.run*covers calls within one app. A sibling Worker had nothing, so the documented path was the callee's public HTTPS route, reached with a plain fetch and a hand-rolled HMAC — a per-request fee, a public round trip, and a shared secret to maintain, for a call between two Workers on one account. Untyped, so a renamed function surfaced as a runtime 404.Three details that would each have been a silent failure, and each has a test:
bigint—JSON.stringifythrows on one — so skipping it would break the money path over bindings and nowhere else. (My first draft guessed a{ value }response envelope and no codec; readingLunoraClient's own RPC path corrected both.){ result }/{ error: { code, message, data } }; errors are rebuilt with theircodeand wire-decodeddata, so a caller across a binding sees what it would see in-process.The binding is accepted structurally as
{ fetch }, soenv.BACKENDsatisfies it without dragging@cloudflare/workers-typesinto consumers, and a one-method fake is a complete test double.Only public functions are reachable: an
internal*procedure is absent fromapiand refused by the callee, because a binding is a boundary between deployments rather than the intra-appctx.run*seam.Studio multi-app
Not built. #16 offers "an explicit statement that it is single-app and should be run standalone" as the alternative, and
concepts/monorepos-and-iac.mdxalready carries it — including the/__lunoramount caveat. A combined multi-app Studio is a feature, not a fix, and does not belong in this PR.Verification
codegen 1054, client 638, cli 1072, vite 189, server 568, react 154 — all pass. Lint, types,
lint:package-json,lint:registry:syncgreen;dist:checkpasses after a prod build.api:checkupdated: additive apart from the intentionalemitDataModelsignature narrowing. Every example's_generated/regenerated.🤖 Generated with Claude Code
https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347