Skip to content

feat(codegen): emit api.mutators.* typed references - #202

Merged
prisis merged 8 commits into
alphafrom
fix/codegen-mutators-refs
Jul 26, 2026
Merged

prisis merged 8 commits into
alphafrom
fix/codegen-mutators-refs

Conversation

@prisis

@prisis prisis commented Jul 26, 2026 •

Copy link
Copy Markdown
Member

Summary

Reported back on cameronapak/dotflowy#310 after the post-#187 re-port: codegen still didn't emit api.mutators.*, so typed serverRef fell 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:

  1. Codegen never emitted the references. discoverMutators lifted only the export name, so there was nothing for serverRef to point at — dotflowy's generated ApiTypes is literally {}. It now lifts each mutator's args validator map and its server impl return type, and emitApi renders api.mutators.<name>: FunctionReference<"mutation", Args, Return>. That's a real function reference, not a parallel shape: a mutator already dispatches through LUNORA_FUNCTIONS with kind: "mutation", and the namespace:fn ref matches the LUNORA_MUTATOR_PATHS entry the DO's isCustomMutator override reads.
  2. @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 to never — so a genuine generated reference failed the constraint, fell through to the serverRef: string overload, 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.
  3. _generated/server.ts exported no defineMutator. This is the cause of the 30-line hand-written MutatorCtx type and the 33 const mctx = ctx as unknown as MutatorCtx casts in dotflowy's lunora/mutators.ts: defineMutator's ServerContext defaulted to the untyped base MutationCtx, and codegen re-exported project-typed query/mutation/action/definePolicy/v but not defineMutator — the one authoring surface whose ctx.db writes need the schema most. It now re-exports a project-bound defineMutator, and discovery accepts the _generated/server specifier so the typed path still registers.

Two latent qualifier bugs surfaced with the first checker-rendered mutator types, both pre-existing for ordinary functions:

  • an extensionless import("./_generated/dataModel") qualifier (written by a function file that follows the repo's no-.js convention) emitted a TS2835 into _generated/*, which is consumed under NodeNext;
  • an 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's Env is bound to object so a wrangler-generated interface Env is accepted, but defineNotify's store takes NotifyEnv (Record<string, unknown>) — which an interface does not satisfy. Every app with a lunora/notify.ts emitted an app.ts that fails tsc, as examples/notify-demo does the moment it is regenerated.

Packages touched: @lunora/codegen, @lunora/db, docs (apps/docs, @lunora/server + @lunora/db package docs).

Before / after

// Before — nothing checks the path, and the arg type is restated per mutator (×23)
insertSibling: defineMutator<{ id: string; userId: string; parentId: string | null; /* … */ }>({
    serverRef: "mutators:insertSibling",
    apply: (_ctx, args) => { /* … */ },
});

// After — bound at compile time, args inferred from the server mutator's validators
insertSibling: defineMutator({
    serverRef: api.mutators.insertSibling,
    apply: (_ctx, args) => { /* … */ },
});
// Before — `ctx` is the untyped base MutationCtx (×33 casts + a hand-written MutatorCtx)
import { defineMutator } from "lunorash/server";
server: async (ctx, args) => { const mctx = ctx as unknown as MutatorCtx; /* … */ }

// After — `ctx` is this project's typed MutationCtx
import { defineMutator } from "./_generated/server";
server: async (ctx, args) => { await ctx.db.patch(args.id, { text: args.text }); }

Linked issues

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 widening
  • pnpm --filter "@lunora/db" run test — 75 passed, including an expectTypeOf test asserting the inferred args type off a typed api.mutators.* reference (not just the runtime dispatch path)
  • pnpm run test:affected / lint:affected:types / lint:affected:eslint — green
  • pnpm run lint:package-json, node scripts/api-snapshot.js check, prettier --check on the diff — green
  • Golden fixture regenerated (capture-expected); apps/playground regenerated + tsc --noEmit clean, with its lunora/mutators.ts switched to the typed defineMutator so the new path is dogfooded
  • All 8 examples/* regenerated and typechecked individually

Reviewers may want to re-run the codegen + db suites and examples/notify-demo's tsc --noEmit (that one fails on alpha once regenerated).

Checklist

  • Commit messages follow the Conventional Commits style (feat(scope): subject)
  • Added or updated tests covering the change
  • Updated relevant docs in apps/docs (or README.md for package-local docs)
  • No package.json files in packages/* modified outside the touched package
  • If a new package was added: project.json has type:package and a category:* tag — n/a
  • If migration impact: noted upgrade steps in the PR description and changelog entry — see Migration below

Migration

Additive; nothing breaks. serverRef: "mutators:sendMessage" still works as the documented escape hatch, and importing defineMutator from @lunora/server / lunorash/server is still discovered. Two opt-in upgrades, both surfaced by re-running lunora codegen:

  • point serverRef at api.mutators.<name> and drop the hand-written defineMutator<{…}> arg type;
  • import defineMutator from ./_generated/server and 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.

  • The @lunora/db overload keeps a deliberate @typescript-eslint/unified-signatures disable. Merging the two overloads into a string | MutatorReference<TArgs> union leaves TArgs uninferable 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.
  • renderApiBody now 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 golden api.ts fixture is unchanged.
  • The last two commits are deliberately separate and reviewable on their own: chore(codegen): regenerate example generated files sweeps in the pre-existing drift the examples had accumulated against the emitter (notify-demo's defineApp / AppTableName blocks), and chore(api): refresh the notify API snapshot fixes drift from feat(notify): security + robustness hardening + delta tests (Wave 15: 182, 183, 192) #195 that fails api:check on 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):

# Finding Evidence in #310
22 Reads are owner-scoped declaratively (defineShape({ owner: true }) from #9); writes got no counterpart 23 mutators each declare a redundant userId: v.string() arg and open with a hand-rolled assertOwner
23 bindMutators' collections map is type-erased (Record<string, Collection<Row, string>>, invariant in the row type) nodes: collection as never ×4, and all 23 apply bodies bypass ctx.collections to close over module state — the seam is dead code in its only production port
24 A fire-and-forget mutator has no error hook (the outbox path has onWriteRejected) an app-level trackLunoraMutation wrapper on 8 call sites, purely to consume isPersisted rejections

Also worth relaying to the adopter: applyPlanToCollections / applyPlanToDb (#18's shared-planner answer) shipped, so their hand-rolled applyPlanToCollection + commitPlan twins can go.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added project-generated, typed support for custom mutators, including api.mutators.<name> references.
    • Introduced owner-scoped writes for mutators with fail-closed enforcement and rejection of forged owner values.
  • Bug Fixes
    • Mutator renames/moves now surface as compile-time type errors instead of runtime failures.
    • Improved generated type/import handling for more reliable NodeNext consumption.
  • Documentation
    • Updated mutator examples to use generated, schema-aware APIs and type-safe references.
    • Expanded guidance on initMutators and handling rejected writes via onWriteRejected.

prisis and others added 5 commits July 26, 2026 12:05
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>
@netlify

netlify Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for lunorash ready!

Name Link
🔨 Latest commit f76f9ea
🔍 Latest deploy log https://app.netlify.com/projects/lunorash/deploys/6a6632945faee70008b3e9b4
😎 Deploy Preview https://deploy-preview-202--lunorash.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@github-actions

Copy link
Copy Markdown
Contributor

Thank you for following the naming conventions! 🙏

@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Custom 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.

Changes

Custom mutator platform

Layer / File(s) Summary
Centralized codegen module discovery
packages/codegen/src/module-specifiers.ts, packages/codegen/src/discover-*.ts
Shared predicates recognize server, generated-server, and cron source modules across codegen discovery paths.
Mutator metadata and generated surfaces
packages/codegen/src/ir.ts, packages/codegen/src/discover-mutators.ts, packages/codegen/src/emit.ts, packages/codegen/src/run-codegen.ts
Mutator validators and return types flow into MutatorIR; generated APIs expose api.mutators.<name>, and generated servers export typed defineMutator.
Typed runtime bindings and owner enforcement
packages/db/src/define-mutators.ts, packages/db/src/index.ts, packages/db/src/mutators/index.ts, packages/server/src/*
Mutator arguments and collection maps are typed, rejected writes are reported through onWriteRejected, and configured owner columns are checked against verified identity.
Examples and documentation
apps/playground/lunora/mutators.ts, apps/docs/..., packages/db/docs/..., packages/server/docs/..., packages/codegen/src/emit-app.ts
Examples use generated imports and references; docs describe owner-scoped writes, typed collections, and rejection handling, while notification store emission casts the environment shape.

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
Loading

Possibly related PRs

  • anolilab/lunora#37: Modifies the custom-mutator engine and overlapping server and codegen mutator paths.
  • anolilab/lunora#187: Changes owner-scoped enforcement in the shapes pipeline and shares the context identity handling updated here.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise, conventional, and accurately summarizes the main change: emitting typed api.mutators references.
Description check ✅ Passed The description includes the key template sections and enough detail to review the change effectively.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/codegen-mutators-refs

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown
Contributor

Thank you for confirming the Contributor License Agreement! 🙏

@codspeed

codspeed Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 6.66%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 1 improved benchmark
❌ 2 regressed benchmarks
✅ 236 untouched benchmarks
⏩ 2 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

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

Open in CodSpeed

Footnotes

  1. 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. ↩

  2. 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>
@prisis

prisis commented Jul 26, 2026

Copy link
Copy Markdown
Member Author

Follow-up: a P0 found while auditing for other generation bugs

Pushed as fix(codegen): accept umbrella imports in every discoverer. Unrelated to the mutator work, but the same class as the two qualifier bugs — a hard-coded specifier list that nothing exercised.

Every 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/* when a project depends on it. Discovery skips an unrecognized specifier silently:

declared as @lunora/server lunorash/server (before)
query / mutation / action registered dropped — absent from api.ts and LUNORA_FUNCTIONS, so every call 404s at runtime
cronJobs() registered dropped — _generated/crons.ts not emitted at all; the schedule never fires
defineMigration registered dropped — LUNORA_MIGRATIONS empty; lunora migrate up finds nothing

Codegen exits ok in all three cases.

Reproduced end-to-end against apps/playground (a real node_modules, so the checker resolves the callee symbol and actually reaches the gate) by switching one function file, a crons.ts and a migrations.ts to the umbrella form, then diffing the generated output.

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 query/mutation from the umbrella either (examples and the playground both use ./_generated/server.js), so the one form an umbrella-only adopter reaches was the untested one. discover-crons' own comment already warned that a missed specifier "has every cron silently dropped" — and still missed the umbrella.

Fix. One shared module-specifiers.ts (isServerSurfaceModule / isServerPackageModule / isCronSourceModule), now used by functions, crons, migrations, mutators, shapes, env and identity discovery. The new discover-module-specifiers.test.ts installs a resolvable stub package into the fixture's own node_modules so the gate is genuinely exercised — it fails on all five factories if the umbrella entry is removed (verified by removing it).

Add-on factories (defineQueue, defineWorkflow, defineAgent, defineContainer) correctly stay scoped — the umbrella ships no subpath for them. httpRoute and defineSchema match on identifier text with no specifier gate, so neither was affected.

902 codegen tests pass; test:affected / lint:affected:types / lint:eslint / api:check green. Written up as finding #25 in plans/170.

…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>
@prisis

prisis commented Jul 26, 2026

Copy link
Copy Markdown
Member Author

All remaining findings fixed (#22, #23, #24)

Pushed as feat(server,db): owner-scoped mutators, typed collections, rejection hook. Every finding from the dotflowy re-read is now closed; plans/170 marks #17/#17b/#17c/#22/#23/#24/#25 all FIXED.

#22 — owner-scoped writes (@lunora/server)

defineMutator gains owner: "<column>". Before server runs it:

  1. requires a verified identity — an anonymous caller is rejected outright, the same fail-closed rule an owner-scoped defineShape applies to reads (filtering on a nullish value would match a nullable owner column);
  2. rejects a forged owner — a client-supplied value that disagrees with the session is a 403, not a correctable input;
  3. sets the column to the verified value — so the impl reads args[owner] without trusting the client, and declaring it v.optional(...) drops it from the wire.

That deletes the assertOwner(ctx, args.userId) opening all 23 of dotflowy's mutators, and makes it impossible to forget on mutator 24.

Design note worth reviewing: it names the column instead of taking a shape's owner: true. A shape is bound to one table, so its .ownedBy(field) resolves unambiguously; a mutator may write several tables and has no single owning table to read it from. Supporting true would mean either threading a schema-derived ownerField through the generic handler(ctx, args) seam every registered function shares, or teaching codegen to discover .ownedBy() (TableIR doesn't carry it today) — real plumbing for one saved string literal. contextUserId moved to a shared module so reads and writes resolve identity identically.

#23 — typed collections map (@lunora/db)

ClientMutatorContext / ClientMutatorDef / BindMutatorsContext are now generic over the map, plus initMutators<TCollections>() to bind defineMutator + bindMutators once (mirroring initLunora.dataModel<DataModel>().create()):

const { bindMutators, defineMutator } = initMutators<{ nodes: typeof wholeOutlineCollection }>();

Collection is invariant in its row type, so the old shared Record<string, Collection<Row, string>> did double damage: as never on every entry at the bind site, and an apply context too wide to use — which is why all 23 optimistic bodies ignored context.collections and closed over module-scope variables instead. Both ends are typed now; the standalone functions still work against the widest map.

#24 — onWriteRejected (@lunora/db)

{ args, code, error, mutator, serverRef }, matching the outbox hook's shape. Setting it also consumes the isPersisted rejection, so a fire-and-forget call no longer needs an app-level wrapper (dotflowy's trackLunoraMutation, 8 call sites); a caller that awaits still observes it. Opt-in deliberately — an unconditional .catch would swallow dropped writes for callers who never asked. A throwing listener is swallowed so reporting a failure can't manufacture a second one.

Verification

Everything is additive: a mutator without owner is untouched, and the standalone defineMutator/bindMutators keep their previous types.

  • 451 @lunora/server tests, 80 @lunora/db tests (6 new owner cases, 3 new rejection cases, 2 new initMutators cases incl. expectTypeOf on both the collection row type and the inferred args)
  • The @tanstack/db test mock gained a faithful isPersisted deferred that settles with mutationFn — the existing 16 cases pass through it unchanged
  • test:affected / lint:affected:types / lint:affected:eslint / api:check / prettier green; all 8 examples typecheck
  • API snapshots show exactly the intended surface (owner?: string, the generic params, BoundMutatorApi, CollectionMap, MutatorRejectedEvent)

Docs updated: a new "Owner-scoped writes" section in the local-first guide, plus initMutators / onWriteRejected sections in the @lunora/db package docs.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 95fc7a7 and 50f7631.

⛔ Files ignored due to path filters (6)
  • api-snapshots/db.api.md is excluded by none and included by none
  • api-snapshots/server.api.md is excluded by none and included by none
  • packages/codegen/__tests__/discover-module-specifiers.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/db/__tests__/define-mutators.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/server/__tests__/mutators.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • plans/170-dotflowy-adoption-feedback.md is excluded by none and included by none
📒 Files selected for processing (17)
  • apps/docs/src/content/docs/concepts/local-first.mdx
  • packages/codegen/src/discover-crons.ts
  • packages/codegen/src/discover-env.ts
  • packages/codegen/src/discover-functions.ts
  • packages/codegen/src/discover-identity.ts
  • packages/codegen/src/discover-migrations.ts
  • packages/codegen/src/discover-mutators.ts
  • packages/codegen/src/discover-shapes.ts
  • packages/codegen/src/module-specifiers.ts
  • packages/db/docs/index.mdx
  • packages/db/src/define-mutators.ts
  • packages/db/src/index.ts
  • packages/db/src/mutators/index.ts
  • packages/server/docs/index.mdx
  • packages/server/src/context-identity.ts
  • packages/server/src/mutators.ts
  • packages/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

Comment on lines +22 to +23
/** Relative depth varies by file location, and the `.js` extension is present under NodeNext. */
const GENERATED_SERVER_RE = /(?:^|\/)_generated\/server(?:\.js)?$/u;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
/** 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.

@prisis
prisis merged commit 5fa52a6 into alpha Jul 26, 2026
14 of 16 checks passed
@prisis
prisis deleted the fix/codegen-mutators-refs branch July 26, 2026 16:15
prisis added a commit that referenced this pull request Jul 28, 2026
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.
@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

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.
Please note this issue tracker is not a help forum. We recommend using our GitHub Discussions tab for questions.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Sep 8, 2026

This branch was previously deployed

1 inactive deployment
benchmarks — f76f9eae Deployed Jul 26, 2026 by prisis via Benchmarks #1016
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant