Repository navigation
feat(codegen): emit api.mutators.* typed references - #202
Conversation
Custom mutators dispatched through `LUNORA_FUNCTIONS` but never appeared on the generated `api`, so a client `defineMutator` had no reference to bind and `serverRef` stayed an unchecked `"mutators:sendMessage"` string — the escape hatch dotflowy shipped 23 times (adoption finding #17). - `discoverMutators` lifts each mutator's `args` validator map and its `server` impl return type; `emitApi` renders them as `api.mutators.<name>: FunctionReference<"mutation", Args, Return>`. - `@lunora/db`'s reference overload was unusable on its own terms: `R extends MutatorReference<never>` rejects any reference carrying a concrete arg type, so a real generated reference fell through to the string overload. It now infers `TArgs` from the reference's phantom. - `_generated/server.ts` re-exports a project-bound `defineMutator` (typed `MutationCtx`), and discovery accepts the `_generated/server` specifier — no more hand-written mutator ctx type plus a cast per mutator. Two latent qualifier bugs surfaced with the first checker-rendered mutator types, both pre-existing for ordinary functions: an extensionless `import("./_generated/dataModel")` was a TS2835 inside `_generated/*`, and an `import("@lunora/values").Id<…>` was a TS2307 for an umbrella-only app. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`defineApp`'s `Env` is bound to `object` so a wrangler-generated `interface Env` is accepted, but `defineNotify`'s `store` factory takes `NotifyEnv` (`Record<string, unknown>`) — which an interface does not satisfy. Every app with a `lunora/notify.ts` therefore emitted an `app.ts` that failed tsc with TS2345, as `examples/notify-demo` does the moment it is regenerated. Widen at the call site, the same way the agent-binding lookup already does. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Picks up the project-typed `defineMutator` re-export in `_generated/server.ts`, plus the pre-existing drift the examples had accumulated against the emitter (notify-demo's `defineApp`/`AppTableName` blocks and the widened notify store call). Every example typechecks. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Re-read of the merged port on top of #187: the reported `serverRef` gap (#17) plus its two causes (#17b/#17c, fixed here) and three open findings — writes have no `owner: true` counterpart to shapes (#22), `bindMutators`' collections map is type-erased so its `apply` seam went unused (#23), and a fire-and-forget mutator has no error hook (#24). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Pre-existing drift on alpha — `@lunora/notify`'s public surface changed in #195 (`SubscriptionFilter.limit`, `normalizeRegisterInput` options, a typed `runPushBroadcastJob` result) without an `api:update`, so `api:check` fails on any branch that rebuilds it. No source change. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
✅ Deploy Preview for lunorash ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
Thank you for following the naming conventions! 🙏 |
WalkthroughCustom mutator discovery now extracts argument and return metadata, code generation emits typed mutator references and server helpers, and runtime bindings support typed collections, rejected-write reporting, and owner-scoped writes. Documentation and playground examples use the generated surfaces. ChangesCustom mutator platform
Estimated code review effort: 4 (Complex) | ~50 minutes Sequence Diagram(s)sequenceDiagram
participant MutatorSource
participant Codegen
participant GeneratedAPI
participant ClientStore
participant ServerHandler
MutatorSource->>Codegen: defineMutator declaration
Codegen->>GeneratedAPI: emit typed api.mutators reference
GeneratedAPI->>ClientStore: provide serverRef
ClientStore->>ServerHandler: invoke mutation
ServerHandler->>ServerHandler: validate owner and execute server handler
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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 confirming the Contributor License Agreement! 🙏 |
Merging this PR will degrade performance by 6.66%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| ❌ | in-batch: single IN(...) query + id->doc re-projection |
785.5 µs | 949.8 µs | -17.3% |
| ❌ | count, no attributes |
57.8 µs | 64.9 µs | -10.86% |
| ⚡ | baseline (Object.keys + toInternal + path spread per field) |
71.6 µs | 64.9 µs | +10.33% |
Tip
Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.
Comparing fix/codegen-mutators-refs (f76f9ea) with alpha (5fa52a6)2
Footnotes
-
2 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩
-
No successful run was found on
alpha(31956c1) during the generation of this report, so 5fa52a6 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩
Each discoverer hard-coded its own set of accepted module specifiers and three omitted `lunorash/server` — the subpath the umbrella exists to provide, and the one codegen itself emits into `_generated/*`. An unrecognized specifier is skipped silently, so declaring `query`/`mutation` through the umbrella dropped the function from both `api.ts` and `LUNORA_FUNCTIONS` (every call 404s at runtime), `cronJobs()` stopped emitting `_generated/crons.ts` entirely (the schedule never fires), and `defineMigration` left `LUNORA_MIGRATIONS` empty (`lunora migrate up` finds nothing) — with codegen still exiting `ok`. Reproduced against apps/playground, where a real `node_modules` lets the checker resolve the symbol and reach the gate. The fixture tests never caught it: with no resolvable package there is no symbol, so discovery falls back to matching identifier text and never consults the specifier. Replaced with one shared `module-specifiers.ts` used by functions, crons, migrations, mutators, shapes, env, and identity discovery. The new regression test installs a resolvable stub into the fixture's own `node_modules`, so it fails on all five factories if the umbrella entry is dropped again. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Follow-up: a P0 found while auditing for other generation bugsPushed as Every discoverer hard-coded its own set of accepted module specifiers, and three omitted
Codegen exits Reproduced end-to-end against Why it hid. With no resolvable package the checker has no symbol, so every discoverer falls back to matching the identifier text and the specifier gate is never consulted — which is exactly the configuration the fixture tests run in. Nothing in the repo imported Fix. One shared Add-on factories ( 902 codegen tests pass; |
…hook Closes the three findings deferred from the dotflowy re-read (#22-24 in plans/170), each a boilerplate tax the only production port had to pay. `defineMutator` gains `owner: "<column>"` (#22). Before `server` runs it requires a verified identity — an anonymous caller is rejected outright, the fail-closed rule an owner-scoped `defineShape` already applies to reads — rejects a client-supplied owner that disagrees with the session as a 403, then sets the column to the verified value. So the impl reads `args[owner]` without trusting the client, replacing the `assertOwner(ctx, args.userId)` that opened all 23 of dotflowy's mutators. It names the column rather than taking a shape's `true`: a shape is bound to one table so `.ownedBy(field)` is unambiguous, while a mutator may write several. `contextUserId` moves to a shared module so reads and writes resolve "who is this" identically. `ClientMutatorContext` / `ClientMutatorDef` / `BindMutatorsContext` become generic over the collections map, and `initMutators<TCollections>()` binds `defineMutator` + `bindMutators` to a project's collections in one place (#23). `Collection` is invariant in its row type, so the old shared `Record<string, Collection<Row, string>>` both forced an `as never` on every entry and handed `apply` a type too wide to use — which is why every optimistic body ignored `context.collections` and closed over module state instead. `bindMutators` gains `onWriteRejected` (#24), symmetric with the outbox hook of the same name. Setting it also consumes the `isPersisted` rejection, so a fire-and-forget call no longer needs an app-level `.catch` wrapper; a caller that awaits still sees it. Opt-in on purpose: an unconditional `.catch` would swallow dropped writes for callers who never asked. All three are additive — the standalone `defineMutator`/`bindMutators` keep working against the widest map, and a mutator without `owner` is untouched. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
All remaining findings fixed (#22, #23, #24)Pushed as #22 — owner-scoped writes (
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/codegen/src/module-specifiers.ts`:
- Around line 22-23: Update GENERATED_SERVER_RE to require a relative import
prefix (`./` or `../`) before `_generated/server`, while retaining optional
`.js` support and variable relative depth. Add regression cases covering valid
relative specifiers and rejecting bare `_generated/server` and package-prefixed
forms.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: af1b285c-2844-4b22-be12-77dd0aee47d2
⛔ Files ignored due to path filters (6)
api-snapshots/db.api.mdis excluded by none and included by noneapi-snapshots/server.api.mdis excluded by none and included by nonepackages/codegen/__tests__/discover-module-specifiers.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included bypackages/**packages/db/__tests__/define-mutators.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included bypackages/**packages/server/__tests__/mutators.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included bypackages/**plans/170-dotflowy-adoption-feedback.mdis excluded by none and included by none
📒 Files selected for processing (17)
apps/docs/src/content/docs/concepts/local-first.mdxpackages/codegen/src/discover-crons.tspackages/codegen/src/discover-env.tspackages/codegen/src/discover-functions.tspackages/codegen/src/discover-identity.tspackages/codegen/src/discover-migrations.tspackages/codegen/src/discover-mutators.tspackages/codegen/src/discover-shapes.tspackages/codegen/src/module-specifiers.tspackages/db/docs/index.mdxpackages/db/src/define-mutators.tspackages/db/src/index.tspackages/db/src/mutators/index.tspackages/server/docs/index.mdxpackages/server/src/context-identity.tspackages/server/src/mutators.tspackages/server/src/shapes.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/db/docs/index.mdx
- packages/server/docs/index.mdx
- packages/codegen/src/discover-mutators.ts
| /** Relative depth varies by file location, and the `.js` extension is present under NodeNext. */ | ||
| const GENERATED_SERVER_RE = /(?:^|\/)_generated\/server(?:\.js)?$/u; |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Restrict generated-server matching to relative imports.
Line 23 also accepts _generated/server and some-package/_generated/server, so arbitrary package exports can be treated as Lunora factories and silently enter generated output. Require ./ or ../ prefixes and add regression cases for accepted and rejected specifiers.
Proposed fix
-const GENERATED_SERVER_RE = /(?:^|\/)_generated\/server(?:\.js)?$/u;
+const GENERATED_SERVER_RE = /^(?:\.\.?\/)+_generated\/server(?:\.js)?$/u;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /** Relative depth varies by file location, and the `.js` extension is present under NodeNext. */ | |
| const GENERATED_SERVER_RE = /(?:^|\/)_generated\/server(?:\.js)?$/u; | |
| /** Relative depth varies by file location, and the `.js` extension is present under NodeNext. */ | |
| const GENERATED_SERVER_RE = /^(?:\.\.?\/)+_generated\/server(?:\.js)?$/u; |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/codegen/src/module-specifiers.ts` around lines 22 - 23, Update
GENERATED_SERVER_RE to require a relative import prefix (`./` or `../`) before
`_generated/server`, while retaining optional `.js` support and variable
relative depth. Add regression cases covering valid relative specifiers and
rejecting bare `_generated/server` and package-prefixed forms.
Three leftovers from the target-selector review, none behavioural: - `--target` was spread into each command's `options` array right after `api-spec`/`env`, breaking the alphabetical run those arrays otherwise keep and landing the flag in an odd spot in `--help`. Moved to its alphabetical slot in `codegen`, `deploy`, `logs`, `build`, and `verify` (`prepare` was already correct, and `dev`'s array is not alphabetical to begin with, so the flag is simply placed alphabetically there). - Dropped a stray blank line #225 introduced before `projectRoot` in `LunoraPluginOptions`. This file separates members with a blank line only ahead of a multi-line docblock; `projectRoot`'s is one line. - Regenerated `examples/blog`'s `_generated/server.ts`, stale since #202 — one commit before vector emission landed in #203, so it was missing the `vectors` ctx surface and left a dirty tree for anyone running codegen there. This PR changes codegen emission, which is what makes the regen its chore.
|
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. |
Summary
Reported back on cameronapak/dotflowy#310 after the post-#187 re-port: codegen still didn't emit
api.mutators.*, so typedserverReffell back to the string escape hatch (adoption feedback finding #17). It wasn't one gap but a chain of three, all in@lunora/codegen+@lunora/db:discoverMutatorslifted only the export name, so there was nothing forserverRefto point at — dotflowy's generatedApiTypesis literally{}. It now lifts each mutator'sargsvalidator map and itsserverimpl return type, andemitApirendersapi.mutators.<name>: FunctionReference<"mutation", Args, Return>. That's a real function reference, not a parallel shape: a mutator already dispatches throughLUNORA_FUNCTIONSwithkind: "mutation", and thenamespace:fnref matches theLUNORA_MUTATOR_PATHSentry the DO'sisCustomMutatoroverride reads.@lunora/db's reference overload could never match.R extends MutatorReference<never>rejects any reference carrying a concrete arg type —{ text: string }is not assignable tonever— so a genuine generated reference failed the constraint, fell through to theserverRef: stringoverload, and errored. The overload shipped in fix: fixed and improved lunora based on real app implementation #187 was never exercised against a typed reference (its test used a bare{ __lunoraRef }literal), which is why the hole survived review. Now<TArgs>(… serverRef: MutatorReference<TArgs>), inferring straight off the phantom._generated/server.tsexported nodefineMutator. This is the cause of the 30-line hand-writtenMutatorCtxtype and the 33const mctx = ctx as unknown as MutatorCtxcasts in dotflowy'slunora/mutators.ts:defineMutator'sServerContextdefaulted to the untyped baseMutationCtx, and codegen re-exported project-typedquery/mutation/action/definePolicy/vbut notdefineMutator— the one authoring surface whosectx.dbwrites need the schema most. It now re-exports a project-bounddefineMutator, and discovery accepts the_generated/serverspecifier so the typed path still registers.Two latent qualifier bugs surfaced with the first checker-rendered mutator types, both pre-existing for ordinary functions:
import("./_generated/dataModel")qualifier (written by a function file that follows the repo's no-.jsconvention) emitted a TS2835 into_generated/*, which is consumed under NodeNext;import("@lunora/values").Id<…>qualifier was a TS2307 for an umbrella-only app, which declares no@lunora/values.And one more found by re-reading #310 (
fix(codegen): widen env for the defineNotify store factory):defineApp'sEnvis bound toobjectso a wrangler-generatedinterface Envis accepted, butdefineNotify'sstoretakesNotifyEnv(Record<string, unknown>) — which an interface does not satisfy. Every app with alunora/notify.tsemitted anapp.tsthat fails tsc, asexamples/notify-demodoes the moment it is regenerated.Packages touched:
@lunora/codegen,@lunora/db, docs (apps/docs,@lunora/server+@lunora/dbpackage docs).Before / after
Linked issues
plans/170-dotflowy-adoption-feedback.mdfix(codegen): break generated server.ts cycle + return-type inference & DX #17 (and its new #17b / #17c)Test plan
pnpm --filter "@lunora/codegen" run test— 891 passed (87 files), including new coverage for the mutator refs, namespace-collision precedence, mutator-free byte-identical output, both qualifier rewrites, and the notify env wideningpnpm --filter "@lunora/db" run test— 75 passed, including anexpectTypeOftest asserting the inferredargstype off a typedapi.mutators.*reference (not just the runtime dispatch path)pnpm run test:affected/lint:affected:types/lint:affected:eslint— greenpnpm run lint:package-json,node scripts/api-snapshot.js check,prettier --checkon the diff — greencapture-expected);apps/playgroundregenerated +tsc --noEmitclean, with itslunora/mutators.tsswitched to the typeddefineMutatorso the new path is dogfoodedexamples/*regenerated and typechecked individuallyReviewers may want to re-run the codegen + db suites and
examples/notify-demo'stsc --noEmit(that one fails onalphaonce regenerated).Checklist
feat(scope): subject)apps/docs(orREADME.mdfor package-local docs)package.jsonfiles inpackages/*modified outside the touched packageproject.jsonhastype:packageand acategory:*tag — n/aMigration
Additive; nothing breaks.
serverRef: "mutators:sendMessage"still works as the documented escape hatch, and importingdefineMutatorfrom@lunora/server/lunorash/serveris still discovered. Two opt-in upgrades, both surfaced by re-runninglunora codegen:serverRefatapi.mutators.<name>and drop the hand-writtendefineMutator<{…}>arg type;defineMutatorfrom./_generated/serverand delete the local mutator-ctx type and its casts.Notes for reviewers
Start with commit 1 (
feat(codegen): emit api.mutators.* typed references) — the other four are consequences.@lunora/dboverload keeps a deliberate@typescript-eslint/unified-signaturesdisable. Merging the two overloads into astring | MutatorReference<TArgs>union leavesTArgsuninferable on the string branch, which then silently falls back to its default and erases the args type at every reference call site — the exact failure this PR exists to fix.renderApiBodynow sorts members by export name. Discovery output was already sorted, so this is a no-op except where a namespace mixes discovered functions with synthetic entries (agents, mutators) — the goldenapi.tsfixture is unchanged.chore(codegen): regenerate example generated filessweeps in the pre-existing drift the examples had accumulated against the emitter (notify-demo'sdefineApp/AppTableNameblocks), andchore(api): refresh the notify API snapshotfixes drift from feat(notify): security + robustness hardening + delta tests (Wave 15: 182, 183, 192) #195 that failsapi:checkon any branch that rebuilds@lunora/notify— no source change in either.Deferred, filed as #22–24 in
plans/170(found in the same re-read, each needs its own change):defineShape({ owner: true })from #9); writes got no counterpartuserId: v.string()arg and open with a hand-rolledassertOwnerbindMutators'collectionsmap is type-erased (Record<string, Collection<Row, string>>, invariant in the row type)nodes: collection as never×4, and all 23applybodies bypassctx.collectionsto close over module state — the seam is dead code in its only production portonWriteRejected)trackLunoraMutationwrapper on 8 call sites, purely to consumeisPersistedrejectionsAlso worth relaying to the adopter:
applyPlanToCollections/applyPlanToDb(#18's shared-planner answer) shipped, so their hand-rolledapplyPlanToCollection+commitPlantwins can go.🤖 Generated with Claude Code
Summary by CodeRabbit
api.mutators.<name>references.initMutatorsand handling rejected writes viaonWriteRejected.