Repository navigation
TML-2849: Make entries[kind][name] the canonical PSL-namespace store, with typed accessors over it (Slice 3) - #757
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (13)
📝 WalkthroughWalkthroughThis PR refactors PSL namespaces to use a canonical frozen ChangesNamespace entries model migration
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
✨ 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 |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
71ffbca to
0ca207e
Compare
bd57d14 to
9416e8d
Compare
…ks (Slice 2 — write side) (#754) ## At a glance Slice 2 of 4 of **[Target-contributed top-level PSL blocks](https://linear.app/prisma-company/issue/TML-2854)** — the **write side** of the declarative SPI. Slice 1 ([#753](#753), merged) gave the framework a generic *read* path (parse → validate → lower an extension-contributed block from its descriptor). This PR adds the matching *write* path: one generic descriptor-driven printer renders any registered block back to PSL, and `contract infer` threads the registered descriptors through so an inferred contract prints its extension blocks. No extension-supplied printer code runs. ```prisma policy_select ProfilesSelect { target = Post using = "auth.uid() = author_id" } ``` The printer never learns the `policy_select` keyword — it reads the descriptor (keyword, `name`, typed `parameters`) and renders each parameter by its declared kind. ## What's in this PR - **Generic descriptor-driven printer** (`psl-printer`) — `serializePrintDocument` builds a discriminator-keyed dispatch map from the registered `pslBlockDescriptors` and renders each block's parameters by kind: `ref` → identifier, `option` → token, `list` → bracketed elements, `value` → the codec's JSON medium (below). An unregistered discriminator throws, naming it. - **`value` params are serialized *through the codec*, not echoed** — `renderValueParam` runs a value literal through `JSON.stringify(codec.encodeJson(codec.decodeJson(JSON.parse(raw))))`. This is the exact print-back mirror of Slice 1's parse-side validator (`codecLookup.get(codecId).decodeJson(JSON.parse(raw))`): a PSL value literal *is* the JSON serialization of the value, and the codec owns that medium. There is no bespoke codec PSL hook. - **`contract infer` threading** (`cli`) — the assembled `pslBlockDescriptors` namespace flows from `inspectLiveSchema` into `printPsl`, so an inferred contract can print extension blocks. - **Round-trip + codec-drives-output coverage** — the declarative `policy_select` fixture now round-trips the full pipeline (parse → validate → lower → IR → serialize → hydrate → IR → **print** → re-parse → structurally-equivalent AST), and a dedicated printer test proves the codec — not the captured raw text — produces the literal. ## A design decision worth a look **The codec owns the serialized form of a value parameter, on both sides.** The original cut of this slice shipped a bespoke codec PSL hook (`parsePslLiteral` / `printPslLiteral`); that was rejected in Slice 1 in favour of the codec's existing JSON medium, and this PR was **rebased onto `main`** with that hook commit dropped and the printer reworked to `encodeJson`/`decodeJson` + `JSON.parse`/`JSON.stringify`. The risk with that path is a test that can't tell "the codec serialized the value" apart from "the raw text passed through untouched" — an identity codec (`encodeJson(v) => v`) makes them indistinguishable. So the proof test uses a **non-identity** codec: `decodeJson` coerces a quoted `"42"` to the number `42`, `encodeJson` emits a bare JSON number, and the printed literal is `using = 42` (unquoted) — which can only come from the codec running on the value. Mutating `renderValueParam` to echo `raw` fails this test (`using = "42"` ≠ `using = 42`). This is also the exact value path an IR/value source would take, fabricated directly rather than waiting on a production block contributor. ## Out of scope (later slices / first consumer) - **`PslNamespace` → ADR 224 `entries` migration** — Slice 3, [TML-2849](https://linear.app/prisma-company/issue/TML-2849) ([#757](#757), to be rebased onto this). - **ADR 126 revision + three-layer ADR + close-out** — Slice 4, [TML-2806](https://linear.app/prisma-company/issue/TML-2806). - **A standalone `value → raw` lowering helper for IR-originated blocks** — deferred to the first real block-contributing extension. The print seam already routes through the codec and is proven; the node stores `raw`, and there is no production contributor yet to fix a helper's signature against. ## Verification | Gate | Result | |---|---| | `pnpm build` (framework-components → psl-parser → psl-printer) | clean | | `pnpm typecheck` (psl-printer / cli) | clean | | `pnpm test` — psl-printer / cli | 50 / 1317 pass | | `pnpm lint:deps` | clean | | `pnpm lint:casts` | `delta=0` (the one new cast is a `blindCast` with reason, not a bare `as`) | | `pnpm fixtures:check` | clean — except a pre-existing `supabase` example failure (`prisma-next: command not found`, an env/PATH issue in that example) that reproduces independently of this PR | ## Relationships - **[#753](#753) / TML-2804** — Slice 1, merged; this is its write-side mirror. Rebased onto `main`; the superseded codec-PSL-hook commit was dropped. - **[#757](#757) / TML-2849** — Slice 3, stacked; will be rebased onto this branch. Refs [TML-2854](https://linear.app/prisma-company/issue/TML-2854). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Extension blocks are now properly printed and serialized in PSL documents with support for codec-based parameter rendering and custom block descriptors. * **Tests** * Added comprehensive test coverage for extension block printing, round-trip validation, and command integration with extension blocks. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Will Madden <[email protected]> Co-authored-by: Will Madden <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]>
de75dae to
e398808
Compare
entries[kind][name] the canonical PSL-namespace store, with typed accessors over it (Slice 3)
97158b6 to
07a8a3b
Compare
…ccessors (E1) PslNamespace.entries[kind][name] (ADR 224: singular essence-named keys model/enum/compositeType + contributed discriminators; container + inner maps frozen) is the single canonical store, built via makePslNamespaceEntries. models/enums/compositeTypes are PERMANENT typed accessors that DERIVE from entries via a makePslNamespace factory (Object.create getter descriptors, blindCast once each) — no parallel stored arrays. extensionBlocks dropped from the interface; contributed kinds read via namespacePslExtensionBlocks(ns) (generic over entries). Parser builds entries and constructs via the factory; both printer phases + the extension-block validator read entries/accessors; framework packages green, lint:casts delta=0. External producers (E2) and the IR layer are untouched. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…bility hardening (E2) Closing dispatch. Migrates the 2 producers that constructed PslNamespace literals (sql-schema-ir-to-psl-ast, a cli contract-infer test) to build entries via makePslNamespaceEntries + makePslNamespace; no per-kind data fields; the extension block goes into entries under its discriminator. Makes the derived models/enums/compositeTypes accessors non-enumerable so spread/serialize copies only entries (no duplication). Adds a uniform-coordinate-access test (built-in entries[model] + contributed entries[policy_select] via one expression). Readers untouched (accessors preserve the interface). Emitted output unchanged (fixtures:check clean; contract.* diff empty) — the migration is in-memory AST only. Spec DoD item 10 reworded to the canonical-entries + derived-typed-accessors decision; slice plan updated. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
The entries migration (E1) was authored before Slice 1/2's later test additions landed on main, so the rebase surfaced readers/producers E1 could not have updated: the #753 generic-parser coverage tests read ns.extensionBlocks, and Slice 2's printer tests built inline old-shape namespace literals (models/enums/compositeTypes/extensionBlocks arrays). Route them through the namespacePslExtensionBlocks helper and the makeNs factory, matching the rest of the entries migration. No behaviour change; psl-parser 110, psl-printer 55. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…locks The entries migration removed the PslNamespace.extensionBlocks field, but two JSDoc @link references still pointed at it. Repoint them at entries + namespacePslExtensionBlocks. Doc-only. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…te types
Address PR review:
- Replace the Object.create(null, {…descriptors…}) + whole-object blindCast in
makePslNamespace with a PslNamespaceNode class: entries stored in the
constructor, models/enums/compositeTypes as getter accessors. Prototype
getters are non-enumerable by construction, so the spread/serialize guarantee
holds without descriptor gymnastics, and the whole-object cast is gone (the
per-getter slice narrowing remains). makePslNamespace returns an instance.
- Add a JSDoc to PslCompositeType explaining what a composite type is (an
embedded reusable field group, the `type X { … }` block), since the term was
unclear in review.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The canonical-entries fact was documented three times over (interface JSDoc with two code blocks, the entries field, the class), and several comments restated the getter code or described branching the code does not have. Trim to tight doc on each exported type; let the uniform entries[kind][name] lookups speak for themselves. Also fold the extension-block grouping in makePslNamespaceEntries into a spread rather than a copy loop with a how-it-works comment. No behaviour change. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
3a9355f to
3b628dc
Compare
All four slices delivered (#753/#754/#757 + this PR); the durable architecture decisions landed in ADR 126/225 and the retro lessons in adr-writing.mdc + docs/Testing Guide.md. The transient project workspace (spec, plans, slice plans) drops with the close-out. No external references to scrub. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ecture docs Make the architecture record match what Slices 1-3 shipped (#753/#754/#757): - Rewrite ADR 126 from the superseded parseFn/validateFn/emitFn function SPI to the declarative AuthoringPslBlockDescriptor design: keyword + name + typed parameters (ref/value/option/list), interpreted by one generic framework parser/validator/printer; value rides the codec JSON medium; option is an authoring-token constraint, not a domain enum; the block lowers via the entityTypes factory. - Add ADR 225: how the three layers carry a pack-contributed entity kind, tied by its discriminator (IR class -> entityTypes lowering -> declarative parse+print). Subsystem doc 6 points at it. - Fix the AuthoringContributions.entities -> entityTypes doc-bug in AGENTS.md (CLAUDE.md symlinks it) and docs/reference/typescript-patterns.md. Markdown-only. Project close-out (project-dir deletion + retro) follows separately. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
All four slices delivered (#753/#754/#757 + this PR); the durable architecture decisions landed in ADR 126/225 and the retro lessons in adr-writing.mdc + docs/Testing Guide.md. The transient project workspace (spec, plans, slice plans) drops with the close-out. No external references to scrub. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
At a glance
A PSL namespace now stores every entity it contains — built-in and extension-contributed — in one place, addressed the same way:
entries[kind][name].The decision
Make
entries[kind][name]the single canonical store onPslNamespace. Keep the typed reads (models/enums/compositeTypes) exactly as callers know them, but compute them as derived getters overentriesrather than storing them as parallel arrays.Why this PR exists
The contract IR already addresses entities by
(kind, name)coordinates. The PSL AST didn't. Built-in kinds lived in typed arrays (models,enums,compositeTypes); the extension-contributed blocks added in Slices 1–2 sat in a separateextensionBlocksarray. So "give me the entity namedXof kindK" had two different shapes depending on whetherKwas built in — and extension kinds had no coordinate access at all. This PR closes that gap, so the PSL AST and the IR share one coordinate model (ADR 224).How it works
entriesis the canonical store — a frozen outer container of frozen per-kind maps. Keys are singular, essence-named:model/enum/compositeTypefor built-ins, and each extension block'sdiscriminator(e.g.policy_select) for contributed kinds.models/enums/compositeTypesare getters built by themakePslNamespacefactory, each narrowing its slice once (viablindCast). Framework code that needs a built-in kind's static type reads it directly; no per-call-site casts.entries[discriminator], or thenamespacePslExtensionBlocks(ns)helper.JSON.stringify-ing a namespace copies onlyentries— the derived views never double up the data.Why the blast radius is small
Because the accessors preserve the exact
.models/.enumsread interface callers already use, every reader is untouched. Only the two places that construct a namespace had to change —sql-schema-ir-to-psl-astand onecontract inferCLI test — and they now go throughmakePslNamespace. The framework-wide migration this first looked like collapsed to two producer sites.No behavioral change
This is an in-memory AST shape change only. Emitted artifacts are unaffected:
fixtures:checkis clean andgit diffovercontract.*is empty. Contract emission runs through the separate domain-IR path (untouched), and the printer reads the PSL AST through the accessors, never spreading or serializing the namespace object.What's in this PR
entriesbecomes the canonical store;makePslNamespaceEntriesbuilds it;makePslNamespaceprovides the derived getters; the parser writesentries, and both printer phases + the extension-block validator read it.entries['model']) and a contributed (entries['policy_select']) kind are reached through the same expression.#753(Slice 1) and#754(Slice 2) merged after E1/E2 were authored, so a few of their later test readers still used the oldns.extensionBlocksfield / inline namespace literals; those move tonamespacePslExtensionBlocksand themakeNsfactory. Two stale{@link PslNamespace.extensionBlocks}JSDoc references (the removed field) are repointed atentries.Verification
pnpm typecheck(framework-components / psl-parser / psl-printer / family-sql / cli)pnpm test(those packages, in isolation)contract infergreenpnpm lint:depspnpm lint:castsdelta=0(accessor narrowing isblindCast, not bareas)pnpm fixtures:check/git diff contract.*(Pre-existing cli
client.test/version.testflakes are unrelated — they pass in isolation and Slice 3 touches no cli command/version/client source. Thesupabaseexample'sfixtures:check/build failure is a worktree env artifact —prisma-next: command not found— independent of this PR.)Out of scope
entries+ typed accessors over it", not "deleted the typed slots".entriesalready shipped); real RLS (downstream).Open item recorded
namespacePslExtensionBlocksreturns contributed blocks grouped by kind, not in flat cross-kind source order. Not exercised today; revisit when a consumer interleaves multiplepolicy_*kinds and needs cross-kind print order preserved.Alternatives considered
Delete the typed slots and expose a raw generic map (
Record<string, Record<string, PslNamespaceEntry>>). Rejected: the generic container loses per-kind static types, so every typed read across the SQL/Mongo families would need a narrowing cast at the call site — a cast regression for negative ergonomic value. ADR 224's own IR already solves this by keepingentriesas canonical storage with typed accessors layered over it; this PR mirrors that proven shape rather than inventing a flatter, less-typed one.Refs TML-2849.
🤖 Generated with Claude Code
Summary by CodeRabbit