From 8738b7a01befb4200deb6b9d01879c6ec1732d4b Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 20 Nov 2026 19:37:56 -0500 Subject: [PATCH 01/15] feat(codegen-ts): take Biome out of generation meta gen no longer formats generated TypeScript with Biome. codegen-ts drops @biomejs/js-api and @biomejs/wasm-nodejs; each generator writes the layout it means. formatTs stays exported as a pass-through so an owned 1.2 generator copy still loads. The Hono routes no longer emit biome-ignore lines. Golden files, the showcase and advanced-modeling output, owned copies and the site payload are regenerated. --- CHANGELOG.md | 12 +- bun.lock | 2 - .../.gen-state/.hashes/acme.learn.json | 34 ++--- .../codegen/generators/barrel.ts | 5 +- .../codegen/generators/entity.ts | 5 +- .../codegen/generators/queries.ts | 3 +- .../codegen/generators/routes.ts | 5 +- .../codegen/templates/routes-index.ts | 1 - .../codegen/templates/view-decl.ts | 11 +- .../src/generated/Author.queries.ts | 46 ++----- .../src/generated/Author.routes.ts | 31 +++-- .../advanced-modeling/src/generated/Author.ts | 12 +- .../src/generated/InstructorProfile.ts | 8 +- .../src/generated/Lesson.queries.ts | 61 ++------- .../src/generated/Lesson.routes.ts | 31 +++-- .../advanced-modeling/src/generated/Lesson.ts | 38 ++---- .../src/generated/Program.queries.ts | 61 ++------- .../src/generated/Program.routes.ts | 51 ++++---- .../src/generated/Program.ts | 119 +++++------------- .../src/generated/ProgramSummary.queries.ts | 11 +- .../src/generated/ProgramSummary.routes.ts | 25 ++-- .../src/generated/ProgramSummary.ts | 33 +---- .../src/generated/Purchase.queries.ts | 61 ++------- .../src/generated/Purchase.routes.ts | 37 +++--- .../src/generated/Purchase.ts | 118 +++++------------ .../src/generated/SyllabusSection.ts | 9 +- .../.metaobjects/.gen-state/.hashes/acme.json | 6 +- .../showcase/codegen/generators/barrel.ts | 5 +- .../showcase/codegen/generators/entity.ts | 5 +- .../showcase/codegen/generators/queries.ts | 3 +- .../showcase/codegen/generators/routes.ts | 5 +- .../codegen/templates/routes-index.ts | 1 - .../showcase/codegen/templates/view-decl.ts | 11 +- .../generated/ts/Subscriber.queries.ts | 59 ++------- .../generated/ts/Subscriber.routes.ts | 31 +++-- examples/showcase/generated/ts/Subscriber.ts | 68 +++------- examples/showcase/inline/deep-currency.txt | 8 +- examples/showcase/inline/ts-entity.txt | 19 ++- examples/showcase/site-payload.json | 20 +-- .../expected/Author.routes.hono.ts | 6 +- scripts/check-peer-ranges.ts | 4 +- server/typescript/packages/cli/README.md | 2 +- .../src/generators/angular-form.ts | 3 +- .../src/generators/angular-grid.ts | 3 +- .../src/generators/angular-service.ts | 3 +- .../src/generators/barrel.ts | 3 +- .../src/reference/grid-hook.ts | 7 +- .../codegen-ts-tanstack/src/reference/grid.ts | 3 +- .../src/reference/hooks.ts | 11 +- .../src/tanstack-grid-hook.ts | 8 +- .../codegen-ts-tanstack/src/tanstack-grid.ts | 4 +- .../codegen-ts-tanstack/src/tanstack-query.ts | 12 +- .../grid-filter/Subscriber.grid.ts | 20 +-- .../__snapshots__/multi-grid/Program.grid.ts | 30 ++--- .../single-entity/Subscriber.grid.ts | 24 +--- .../packages/codegen-ts/package.json | 2 - .../packages/codegen-ts/src/format.ts | 57 ++------- .../packages/codegen-ts/src/generator.ts | 2 +- .../codegen-ts/src/generators/barrel.ts | 5 +- .../src/generators/callable-file.ts | 3 +- .../codegen-ts/src/generators/entity-file.ts | 5 +- .../codegen-ts/src/generators/queries-file.ts | 3 +- .../src/generators/report-export-file.ts | 5 +- .../src/generators/routes-file-hono.ts | 5 +- .../codegen-ts/src/generators/routes-file.ts | 5 +- .../packages/codegen-ts/src/index.ts | 1 + .../codegen-ts/src/reference/barrel.ts | 5 +- .../codegen-ts/src/reference/callable.ts | 3 +- .../codegen-ts/src/reference/entity.ts | 5 +- .../codegen-ts/src/reference/queries.ts | 3 +- .../codegen-ts/src/reference/report-export.ts | 5 +- .../codegen-ts/src/reference/routes-hono.ts | 7 +- .../codegen-ts/src/reference/routes.ts | 5 +- .../src/templates/routes-file-hono.ts | 2 - .../codegen-ts/src/templates/routes-index.ts | 1 - .../codegen-ts/src/templates/view-decl.ts | 11 +- .../packages/codegen-ts/test/format.test.ts | 29 +++-- .../__snapshots__/package/Tag.queries.ts | 46 ++----- .../__snapshots__/package/Tag.routes.ts | 9 +- .../test/golden/__snapshots__/package/Tag.ts | 45 ++----- .../package/shop/commerce/Order.queries.ts | 67 ++-------- .../package/shop/commerce/Order.routes.ts | 9 +- .../package/shop/commerce/Order.ts | 43 ++----- .../package/shop/commerce/Product.queries.ts | 62 ++------- .../package/shop/commerce/Product.ts | 38 ++---- .../package/shop/users/Customer.queries.ts | 52 ++------ .../package/shop/users/Customer.ts | 17 +-- .../postgres/Exercise.queries.ts | 61 ++------- .../golden/__snapshots__/postgres/Exercise.ts | 38 ++---- .../__snapshots__/postgres/Program.queries.ts | 46 ++----- .../__snapshots__/postgres/Program.routes.ts | 10 +- .../golden/__snapshots__/postgres/Program.ts | 69 +++------- .../postgres/Purchase.queries.ts | 81 +++--------- .../__snapshots__/postgres/Purchase.routes.ts | 8 +- .../golden/__snapshots__/postgres/Purchase.ts | 79 ++++-------- .../postgres/Subscriber.queries.ts | 48 ++----- .../postgres/Subscriber.routes.ts | 9 +- .../__snapshots__/postgres/Subscriber.ts | 59 +++------ .../__snapshots__/postgres/Tag.queries.ts | 30 +---- .../__snapshots__/postgres/Tag.routes.ts | 9 +- .../test/golden/__snapshots__/postgres/Tag.ts | 27 +--- .../__snapshots__/postgres/Video.queries.ts | 51 ++------ .../__snapshots__/postgres/Video.routes.ts | 9 +- .../golden/__snapshots__/postgres/Video.ts | 56 ++------- .../__snapshots__/postgres/Week.queries.ts | 40 ++---- .../__snapshots__/postgres/Week.routes.ts | 9 +- .../golden/__snapshots__/postgres/Week.ts | 45 ++----- .../__snapshots__/postgres/Workout.queries.ts | 56 ++------- .../golden/__snapshots__/postgres/Workout.ts | 41 ++---- .../postgres/WorkoutEvent.queries.ts | 83 +++--------- .../postgres/WorkoutEvent.routes.ts | 8 +- .../__snapshots__/postgres/WorkoutEvent.ts | 89 ++++--------- .../__snapshots__/sqlite/Exercise.queries.ts | 67 ++-------- .../golden/__snapshots__/sqlite/Exercise.ts | 32 ++--- .../__snapshots__/sqlite/Program.queries.ts | 52 ++------ .../__snapshots__/sqlite/Program.routes.ts | 10 +- .../golden/__snapshots__/sqlite/Program.ts | 59 +++------ .../__snapshots__/sqlite/Purchase.queries.ts | 87 +++---------- .../__snapshots__/sqlite/Purchase.routes.ts | 8 +- .../golden/__snapshots__/sqlite/Purchase.ts | 75 ++++------- .../sqlite/Subscriber.queries.ts | 54 ++------ .../__snapshots__/sqlite/Subscriber.routes.ts | 9 +- .../golden/__snapshots__/sqlite/Subscriber.ts | 51 +++----- .../__snapshots__/sqlite/Tag.queries.ts | 36 +----- .../golden/__snapshots__/sqlite/Tag.routes.ts | 9 +- .../test/golden/__snapshots__/sqlite/Tag.ts | 23 +--- .../__snapshots__/sqlite/Video.queries.ts | 57 ++------- .../__snapshots__/sqlite/Video.routes.ts | 9 +- .../test/golden/__snapshots__/sqlite/Video.ts | 51 ++------ .../__snapshots__/sqlite/Week.queries.ts | 46 ++----- .../__snapshots__/sqlite/Week.routes.ts | 9 +- .../test/golden/__snapshots__/sqlite/Week.ts | 40 ++---- .../__snapshots__/sqlite/Workout.queries.ts | 62 ++------- .../golden/__snapshots__/sqlite/Workout.ts | 36 ++---- .../sqlite/WorkoutEvent.queries.ts | 89 +++---------- .../sqlite/WorkoutEvent.routes.ts | 8 +- .../__snapshots__/sqlite/WorkoutEvent.ts | 85 ++++--------- .../test/naming/name-claims.test.ts | 4 +- .../test/tph-reference-target.test.ts | 2 +- .../test/typed-create-compile.test.ts | 4 +- .../test-generators/src/generators/barrel.ts | 5 +- .../test-generators/src/generators/entity.ts | 5 +- .../test-generators/src/generators/queries.ts | 3 +- .../src/generators/report-export.ts | 5 +- .../test-generators/src/generators/routes.ts | 5 +- .../src/templates/routes-index.ts | 1 - .../src/templates/view-decl.ts | 11 +- 147 files changed, 982 insertions(+), 2959 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a7ba7d7fc..7bed2eaa15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -145,6 +145,16 @@ Each item below is described in full under Security, Added, Changed or Fixed; th integer. - **C# and Java: a names class no longer extends its base's** when that would make a base constant that is not a column of its own table reachable through it. It is emitted complete instead. +- **TypeScript generation runs no formatter.** `meta gen` used to pass every generated `.ts` file + through Biome after the template had laid it out; it no longer does, so `@metaobjectsdev/codegen-ts` + no longer depends on `@biomejs/js-api` or `@biomejs/wasm-nodejs`. Each file keeps the layout its + generator writes (the ts-poet printer's 120 columns, where a template used it), so the **first + `meta gen` rewrites most generated files once, in layout only**; a hand edit in a generated + file meets the three-way merge against a base with the new layout. The Hono routes no longer + carry a `// biome-ignore` line above `registerAllRoutes` and each `mount...Routes` function; a + project that lints generated code with Biome adds its own ignore. `formatTs` is still exported from + `@metaobjectsdev/codegen-ts` and now returns its input unchanged, so a generator ejected in 1.2 + keeps loading and running. Run your formatter over the generated tree if you want your layout. - **`metamodelVersion` is `1.3`.** Upgrade every port together. ### Security @@ -1710,7 +1720,7 @@ Each item below is described in full under Security, Added, Changed or Fixed; th - **`@metaobjectsdev/cli` no longer installs the native Biome binary.** `codegen-ts-react`, `codegen-ts-tanstack` and the source-only `codegen-ts-angular` declared `@biomejs/biome` as a peer dependency, which npm installs automatically, so every CLI install carried the ~94 MB - `@biomejs/cli-` binary that nothing runs: codegen formats through the WebAssembly + `@biomejs/cli-` binary that nothing runs: the CLI used the WebAssembly build (`@biomejs/wasm-nodejs`). The peer is gone (it stays a devDependency for this repo's own lint gate), and a fresh npm install of the CLI drops from 245 MB to 151 MB of `node_modules`. `scripts/check-peer-ranges.ts` now fails a publishable package that requires `@biomejs/biome` diff --git a/bun.lock b/bun.lock index 985f139383..be56dbadf8 100644 --- a/bun.lock +++ b/bun.lock @@ -219,8 +219,6 @@ "name": "@metaobjectsdev/codegen-ts", "version": "1.3.0", "dependencies": { - "@biomejs/js-api": "^0.7.0", - "@biomejs/wasm-nodejs": "^1.9.4", "@dprint/formatter": "^0.6.0", "@dprint/typescript": "0.87.1", "@metaobjectsdev/docs-site": "workspace:*", diff --git a/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json b/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json index c67f9bf9ad..b960c50d96 100644 --- a/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json +++ b/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json @@ -5,22 +5,22 @@ "sourceNode": "acme::learn::Author" }, "src/generated/Author.queries.ts": { - "hash": "42cc1ab2fd442559e1e9c5c3f14978f306efcda5472f8b5370d3339753e5a36f", + "hash": "bea4d154f02ed1b93679acde9ece817be80c625b65f5b4efa2d6aaba712b9185", "generatedBy": "queries-file", "sourceNode": "acme::learn::Author" }, "src/generated/Author.routes.ts": { - "hash": "38d9a39b2fc93dc63ba0bc11d91d151f2a24b0af808a10dfdddf61a2d58356de", + "hash": "777c863287967d273a91afc4c1b706ab87c6c178fb995fe911ffce3360b53747", "generatedBy": "routes-file", "sourceNode": "acme::learn::Author" }, "src/generated/Author.ts": { - "hash": "36f28e09c3633848bf3bdb45372e03ae8b036792dec05f503a6f0d3abc1bb1cc", + "hash": "a1669e4eec814446e5da4561636312698cce75d2ee5c8afd1d38016a616d2f98", "generatedBy": "entity-file", "sourceNode": "acme::learn::Author" }, "src/generated/InstructorProfile.ts": { - "hash": "2643b88401edf303789461d7d05bafd7cb1979b0ff19c27958d156192265986a", + "hash": "3559df25112ecb00911c2668a2fce07770b213fee9455fce80906162814b2c17", "generatedBy": "entity-file", "sourceNode": "acme::learn::InstructorProfile" }, @@ -30,17 +30,17 @@ "sourceNode": "acme::learn::Lesson" }, "src/generated/Lesson.queries.ts": { - "hash": "bc8e9bff3cb70c2c47ecfd07619f90d3f26a3981aca8ce6828f75e2a80fb9273", + "hash": "d6fa0b0c29b65afd52e69423e79dc478b3dcde505fac55bca7057cb00f46eb1a", "generatedBy": "queries-file", "sourceNode": "acme::learn::Lesson" }, "src/generated/Lesson.routes.ts": { - "hash": "a706159a09e459f44f1dd0721cf26320862768a4305363d94cf66b5fb8b5ae2a", + "hash": "b57f413c9b5582fee2cf9150064f879d106b0e94c0b4e75448b0a1fce3e7e708", "generatedBy": "routes-file", "sourceNode": "acme::learn::Lesson" }, "src/generated/Lesson.ts": { - "hash": "404b7d27b2ec7a6158c6915dbe289c09e36b8fafe8ed82b14871a3bbfa117db8", + "hash": "c699a4d4a0584e9206d7562ea16116c34c5dc85ee4027acaf9cb0b01d2222f06", "generatedBy": "entity-file", "sourceNode": "acme::learn::Lesson" }, @@ -50,17 +50,17 @@ "sourceNode": "acme::learn::Program" }, "src/generated/Program.queries.ts": { - "hash": "07bde6eda6ec265f3b9b61b73b379ed2a066a9b852ecbda2c6bf7ee5d5d079cf", + "hash": "d0b4b7d598cf4da0c7200e78198cf81fc807edf5563f83028b31a01b1da0288b", "generatedBy": "queries-file", "sourceNode": "acme::learn::Program" }, "src/generated/Program.routes.ts": { - "hash": "c0b0b5cf1761371480aa90d613c5170212b4b4ef63fd265f1362ff4051b50af9", + "hash": "a0b184a3475fbe3c5f06cc88007a76fa298e375f4c1be8b6037a781f2aef7860", "generatedBy": "routes-file", "sourceNode": "acme::learn::Program" }, "src/generated/Program.ts": { - "hash": "a658aad738aa33578fa5e5091494137f0268ea497a6daf5c61422861cdf04806", + "hash": "95c5f5a951d1b219b4f3a4cef6dfc5fc0ea4612c3b18529fc3defaf27aa7e952", "generatedBy": "entity-file", "sourceNode": "acme::learn::Program" }, @@ -71,17 +71,17 @@ "sourceNode": "acme::learn::ProgramDescriptionPayload" }, "src/generated/ProgramSummary.queries.ts": { - "hash": "743e8ce74eee85bb821cf3d909957fae630085fb1f5a7567dd6bfdcae4364910", + "hash": "8902cbac50396109867e90d2e973d850e0d1e211d9d2f21c0e5f4b2882fd0dd9", "generatedBy": "queries-file", "sourceNode": "acme::learn::ProgramSummary" }, "src/generated/ProgramSummary.routes.ts": { - "hash": "995e893a6b21e65d7bc031761c18bb7bb0c790abb31cb72546bf95573c980099", + "hash": "3aa58a1722e50378410e05e43e797b67f7ef80ab16ec0bc6711c222787a16578", "generatedBy": "routes-file", "sourceNode": "acme::learn::ProgramSummary" }, "src/generated/ProgramSummary.ts": { - "hash": "181f48ed374dfdf2f5b3213e0064833f071fd7029ed9357a6eef764616c2429c", + "hash": "615eb82032aaf686bc3e5b1484bf2b70174ded81da0310c5a6939e6fdb33bc8d", "generatedBy": "entity-file", "sourceNode": "acme::learn::ProgramSummary" }, @@ -91,22 +91,22 @@ "sourceNode": "acme::learn::Purchase" }, "src/generated/Purchase.queries.ts": { - "hash": "ae7896ebdf3a57332e2c79dc9dd99fef9547054371547d6a469a752a7fc64ad6", + "hash": "9527a9cae7157415d78c64d21164779272d731827efa807505dc3552728be1e9", "generatedBy": "queries-file", "sourceNode": "acme::learn::Purchase" }, "src/generated/Purchase.routes.ts": { - "hash": "7590c063acdabcd86eec67d3d8abc6390dde576aca733944dbb1edaf1dfde5bb", + "hash": "9d634c477225b01f3873815e01423f8ae06673830b4f63f1c19df4e3222dda3f", "generatedBy": "routes-file", "sourceNode": "acme::learn::Purchase" }, "src/generated/Purchase.ts": { - "hash": "fa88def0af1a85b18a1d9d7bb99588f0d71273ce0ee4ce633615ab0724a6bf69", + "hash": "ee57e04fa03ff23675e1a80be5beb984fee268b423ac1ecd80452d857a22d30a", "generatedBy": "entity-file", "sourceNode": "acme::learn::Purchase" }, "src/generated/SyllabusSection.ts": { - "hash": "655f1fdd3c2f104fe48e8fb9a4147c3977a820f82e2b0a6ce1db8e4bd1b3ca2c", + "hash": "d57e6668f79f6577986b2558fe57badc3f87ce8e5d55340f3063c3db57d7d367", "generatedBy": "entity-file", "sourceNode": "acme::learn::SyllabusSection" } diff --git a/examples/advanced-modeling/codegen/generators/barrel.ts b/examples/advanced-modeling/codegen/generators/barrel.ts index 2c82677ac3..001cf7953d 100644 --- a/examples/advanced-modeling/codegen/generators/barrel.ts +++ b/examples/advanced-modeling/codegen/generators/barrel.ts @@ -24,7 +24,6 @@ import { type ExtStyle, type ResolvedTarget, barrelModuleSpecifier, - formatTs, GENERATED_HEADER, GENERATED_EDIT_NOTE, effectivePackage, @@ -66,14 +65,12 @@ export const barrel = function barrel(opts?: BarrelOpts): Generator { for (const e of entities) claimBarrelNames(ctx, e); return { path: "index.ts", - content: await formatTs( - renderBarrel( + content: renderBarrel( entities.map((e) => ({ name: e.name, package: effectivePackage(e) })), rc.extStyle, rc.selfTarget, rc.entityModuleTarget, ), - ), }; }), }; diff --git a/examples/advanced-modeling/codegen/generators/entity.ts b/examples/advanced-modeling/codegen/generators/entity.ts index 926da1c687..4931111a28 100644 --- a/examples/advanced-modeling/codegen/generators/entity.ts +++ b/examples/advanced-modeling/codegen/generators/entity.ts @@ -54,7 +54,6 @@ import { isWriteThrough, isAbstract, hasWritableRdbSource, - formatTs, ownedRuntimeImport, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, @@ -188,7 +187,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), - content: await formatTs(renderEntity(entity, renderContext, { allowlists })), + content: renderEntity(entity, renderContext, { allowlists }), }; }); @@ -209,7 +208,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator ctx.select !== undefined ? { select: ctx.select } : undefined, ); if (sharedEnums !== null) { - files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: await formatTs(sharedEnums) }); + files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: sharedEnums }); } return files; }, diff --git a/examples/advanced-modeling/codegen/generators/queries.ts b/examples/advanced-modeling/codegen/generators/queries.ts index 8d03e08142..44617b4c61 100644 --- a/examples/advanced-modeling/codegen/generators/queries.ts +++ b/examples/advanced-modeling/codegen/generators/queries.ts @@ -43,7 +43,6 @@ import { isProjection, isWriteThrough, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, GENERATED_HEADER, @@ -173,7 +172,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), - content: await formatTs(renderQueries(entity, ctx.renderContext)), + content: renderQueries(entity, ctx.renderContext), }; }), }; diff --git a/examples/advanced-modeling/codegen/generators/routes.ts b/examples/advanced-modeling/codegen/generators/routes.ts index 16837743da..3117986622 100644 --- a/examples/advanced-modeling/codegen/generators/routes.ts +++ b/examples/advanced-modeling/codegen/generators/routes.ts @@ -73,7 +73,6 @@ import { writeDeniedColumnsLine, knownFieldsLine, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -770,7 +769,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), - content: await formatTs(renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); const generator: Generator = { @@ -796,7 +795,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("fastify"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "fastify")), + content: renderRoutesIndex(matched, ctx.renderContext, "fastify"), }]; }, }; diff --git a/examples/advanced-modeling/codegen/templates/routes-index.ts b/examples/advanced-modeling/codegen/templates/routes-index.ts index e9969b576f..2f0608864b 100644 --- a/examples/advanced-modeling/codegen/templates/routes-index.ts +++ b/examples/advanced-modeling/codegen/templates/routes-index.ts @@ -55,7 +55,6 @@ export function renderRoutesIndex( " * on the mount paths before calling this. An entity that needs a row-ownership rule", " * should not be registered open: narrow its routes with `expose` or hand-write them.", " */", - "// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables", "export function registerAllRoutes(app: Hono, deps: { db: unknown }): void {", ...sorted.map((e) => ` ${handler(e)}(app, deps);`), "}", diff --git a/examples/advanced-modeling/codegen/templates/view-decl.ts b/examples/advanced-modeling/codegen/templates/view-decl.ts index 9770bc091d..3dd02b2329 100644 --- a/examples/advanced-modeling/codegen/templates/view-decl.ts +++ b/examples/advanced-modeling/codegen/templates/view-decl.ts @@ -111,7 +111,7 @@ function viewColumnLine( : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 - ? `, ${JSON.stringify(spec.fnOptions)}` + ? `, ${optionsLiteral(spec.fnOptions)}` : ""; // #204 — of the table modifiers, only `.array()` (postgres native array element // typing) and `.notNull()` (shapes the SELECT type) carry to an existing view; @@ -252,3 +252,12 @@ export function renderViewReadZodObject(fields: readonly MetaField[], opts: View ${joinCode(lines, { on: ",\n" })} })`; } + +/** A column's options as a JS object literal: `{ length: 200 }`, not JSON's `{ "length": 200 }`. */ +function optionsLiteral(options: Record): string { + const entries = Object.entries(options).map(([key, value]) => { + const name = /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key); + return `${name}: ${JSON.stringify(value)}`; + }); + return `{ ${entries.join(", ")} }`; +} diff --git a/examples/advanced-modeling/src/generated/Author.queries.ts b/examples/advanced-modeling/src/generated/Author.queries.ts index b365185b65..e19d0d8624 100644 --- a/examples/advanced-modeling/src/generated/Author.queries.ts +++ b/examples/advanced-modeling/src/generated/Author.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Author, - AuthorInsertSchema, - type AuthorPatch, - authors, - AuthorUpdateSchema, -} from "./Author"; -export async function findAuthorById( - db: Db, - id: string, -): Promise { - const [author] = await db - .select() - .from(authors) - .where(eq(authors.id, id)) - .limit(1); +import { type Author, AuthorInsertSchema, type AuthorPatch, authors, AuthorUpdateSchema } from "./Author"; +export async function findAuthorById(db: Db, id: string): Promise { + const [author] = await db.select().from(authors).where(eq(authors.id, id)).limit(1); return author ?? null; } -export async function listAuthors( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listAuthors(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(authors).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,38 +22,24 @@ export async function listAuthors( } return q; } -export async function createAuthor( - db: Db, - data: z.input, -): Promise { +export async function createAuthor(db: Db, data: z.input): Promise { const validated = AuthorInsertSchema.parse(data); const [author] = await db.insert(authors).values(validated).returning(); return author!; } -export async function updateAuthor( - db: Db, - id: string, - patch: AuthorPatch, -): Promise { +export async function updateAuthor(db: Db, id: string, patch: AuthorPatch): Promise { const validated = AuthorUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findAuthorById(db, id); } - const [author] = await db - .update(authors) - .set(validated) - .where(eq(authors.id, id)) - .returning(); + const [author] = await db.update(authors).set(validated).where(eq(authors.id, id)).returning(); return author ?? null; } export async function deleteAuthorById(db: Db, id: string): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(authors) - .where(eq(authors.id, id)) - .returning(); + const deleted = await db.delete(authors).where(eq(authors.id, id)).returning(); return deleted.length > 0; } diff --git a/examples/advanced-modeling/src/generated/Author.routes.ts b/examples/advanced-modeling/src/generated/Author.routes.ts index e2a9645ce0..d61cfcb331 100644 --- a/examples/advanced-modeling/src/generated/Author.routes.ts +++ b/examples/advanced-modeling/src/generated/Author.routes.ts @@ -35,21 +35,18 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function authorRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Author.$path, - db, - table: authors, - insertSchema: AuthorInsertSchema, - updateSchema: AuthorUpdateSchema, - filterAllowlist: AuthorFilterAllowlist, - sortAllowlist: AuthorSortAllowlist, - dialect: "postgres", - knownFields: ["id", "name", "email", "bio"], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Author.$path, + db, + table: authors, + insertSchema: AuthorInsertSchema, + updateSchema: AuthorUpdateSchema, + filterAllowlist: AuthorFilterAllowlist, + sortAllowlist: AuthorSortAllowlist, + dialect: "postgres", + knownFields: ["id", "name", "email", "bio"], + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/Author.ts b/examples/advanced-modeling/src/generated/Author.ts index 94dd4d81e7..68e7d8db5b 100644 --- a/examples/advanced-modeling/src/generated/Author.ts +++ b/examples/advanced-modeling/src/generated/Author.ts @@ -22,12 +22,7 @@ export const AuthorInsertSchema = z.object({ export const AuthorUpdateSchema = z.object({ name: z.string().min(1).max(120).optional(), - email: z - .string() - .min(1) - .max(320) - .regex(new RegExp("^(?:[^@]+@[^@]+)$")) - .optional(), + email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")).optional(), bio: z.string().max(500).optional().nullable(), }); @@ -71,10 +66,7 @@ export const Author = { label: "Name", view: "text", htmlType: "text", - rules: { - required: "Name is required", - maxLength: { value: 120, message: "Must be 120 characters or fewer" }, - }, + rules: { required: "Name is required", maxLength: { value: 120, message: "Must be 120 characters or fewer" } }, }, email: { name: "email", diff --git a/examples/advanced-modeling/src/generated/InstructorProfile.ts b/examples/advanced-modeling/src/generated/InstructorProfile.ts index 4ee0b9bb91..169c326d7b 100644 --- a/examples/advanced-modeling/src/generated/InstructorProfile.ts +++ b/examples/advanced-modeling/src/generated/InstructorProfile.ts @@ -34,17 +34,13 @@ export const InstructorProfile = { label: "Bio", view: "text", htmlType: "text", - rules: { - maxLength: { value: 2000, message: "Must be 2000 characters or fewer" }, - }, + rules: { maxLength: { value: 2000, message: "Must be 2000 characters or fewer" } }, }, credentialsSummary: { name: "credentialsSummary", label: "Credentials Summary", view: "text", htmlType: "text", - rules: { - maxLength: { value: 300, message: "Must be 300 characters or fewer" }, - }, + rules: { maxLength: { value: 300, message: "Must be 300 characters or fewer" } }, }, } as const; diff --git a/examples/advanced-modeling/src/generated/Lesson.queries.ts b/examples/advanced-modeling/src/generated/Lesson.queries.ts index 787d1dfaf5..1f01305eae 100644 --- a/examples/advanced-modeling/src/generated/Lesson.queries.ts +++ b/examples/advanced-modeling/src/generated/Lesson.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Lesson, - LessonInsertSchema, - type LessonPatch, - lessons, - LessonUpdateSchema, -} from "./Lesson"; -export async function findLessonById( - db: Db, - id: string, -): Promise { - const [lesson] = await db - .select() - .from(lessons) - .where(eq(lessons.id, id)) - .limit(1); +import { type Lesson, LessonInsertSchema, type LessonPatch, lessons, LessonUpdateSchema } from "./Lesson"; +export async function findLessonById(db: Db, id: string): Promise { + const [lesson] = await db.select().from(lessons).where(eq(lessons.id, id)).limit(1); return lesson ?? null; } -export async function listLessons( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listLessons(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(lessons).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,57 +22,34 @@ export async function listLessons( } return q; } -export async function createLesson( - db: Db, - data: z.input, -): Promise { +export async function createLesson(db: Db, data: z.input): Promise { const validated = LessonInsertSchema.parse(data); const [lesson] = await db.insert(lessons).values(validated).returning(); return lesson!; } -export async function updateLesson( - db: Db, - id: string, - patch: LessonPatch, -): Promise { +export async function updateLesson(db: Db, id: string, patch: LessonPatch): Promise { const validated = LessonUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findLessonById(db, id); } - const [lesson] = await db - .update(lessons) - .set(validated) - .where(eq(lessons.id, id)) - .returning(); + const [lesson] = await db.update(lessons).set(validated).where(eq(lessons.id, id)).returning(); return lesson ?? null; } export async function deleteLessonById(db: Db, id: string): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(lessons) - .where(eq(lessons.id, id)) - .returning(); + const deleted = await db.delete(lessons).where(eq(lessons.id, id)).returning(); return deleted.length > 0; } -export async function findLessonsByProgram( - db: Db, - programId: string, -): Promise { +export async function findLessonsByProgram(db: Db, programId: string): Promise { return db.select().from(lessons).where(eq(lessons.programId, programId)); } -export async function findLessonsByProgramIn( - db: Db, - programIds: string[], -): Promise { +export async function findLessonsByProgramIn(db: Db, programIds: string[]): Promise { if (programIds.length === 0) { return []; } - return db - .select() - .from(lessons) - .where(inArray(lessons.programId, programIds)); + return db.select().from(lessons).where(inArray(lessons.programId, programIds)); } diff --git a/examples/advanced-modeling/src/generated/Lesson.routes.ts b/examples/advanced-modeling/src/generated/Lesson.routes.ts index 3faa54390e..c5da461295 100644 --- a/examples/advanced-modeling/src/generated/Lesson.routes.ts +++ b/examples/advanced-modeling/src/generated/Lesson.routes.ts @@ -35,21 +35,18 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function lessonRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Lesson.$path, - db, - table: lessons, - insertSchema: LessonInsertSchema, - updateSchema: LessonUpdateSchema, - filterAllowlist: LessonFilterAllowlist, - sortAllowlist: LessonSortAllowlist, - dialect: "postgres", - knownFields: ["id", "programId", "title", "position"], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Lesson.$path, + db, + table: lessons, + insertSchema: LessonInsertSchema, + updateSchema: LessonUpdateSchema, + filterAllowlist: LessonFilterAllowlist, + sortAllowlist: LessonSortAllowlist, + dialect: "postgres", + knownFields: ["id", "programId", "title", "position"], + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/Lesson.ts b/examples/advanced-modeling/src/generated/Lesson.ts index c337e0ca25..025a7ab641 100644 --- a/examples/advanced-modeling/src/generated/Lesson.ts +++ b/examples/advanced-modeling/src/generated/Lesson.ts @@ -2,21 +2,13 @@ // Source metadata: Lesson (Lesson) // Extend in your own module (e.g. Lesson.extra.ts) — nothing imports it for you. import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { - type AnyPgColumn, - integer, - pgTable, - uuid, - varchar, -} from "drizzle-orm/pg-core"; +import { type AnyPgColumn, integer, pgTable, uuid, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; import { programs } from "./Program"; export const lessons = pgTable("lessons", { id: uuid("id").primaryKey().defaultRandom(), - programId: uuid("program_id") - .notNull() - .references((): AnyPgColumn => programs.id), + programId: uuid("program_id").notNull().references((): AnyPgColumn => programs.id), title: varchar("title", { length: 200 }).notNull(), position: integer("position").notNull(), }); @@ -24,24 +16,19 @@ export type Lesson = InferSelectModel; export type LessonInsert = InferInsertModel; export type LessonUpdate = Partial; export const LessonInsertSchema = z.object({ - programId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ), + programId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ), title: z.string().min(1).max(200), position: z.number().int(), }); export const LessonUpdateSchema = z.object({ - programId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ) - .optional(), + programId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ).optional(), title: z.string().min(1).max(200).optional(), position: z.number().int().optional(), }); @@ -93,10 +80,7 @@ export const Lesson = { label: "Title", view: "text", htmlType: "text", - rules: { - required: "Title is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, + rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, position: { name: "position", diff --git a/examples/advanced-modeling/src/generated/Program.queries.ts b/examples/advanced-modeling/src/generated/Program.queries.ts index 55c228b3fe..cad3c64d26 100644 --- a/examples/advanced-modeling/src/generated/Program.queries.ts +++ b/examples/advanced-modeling/src/generated/Program.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Program, - ProgramInsertSchema, - type ProgramPatch, - programs, - ProgramUpdateSchema, -} from "./Program"; -export async function findProgramById( - db: Db, - id: string, -): Promise { - const [program] = await db - .select() - .from(programs) - .where(eq(programs.id, id)) - .limit(1); +import { type Program, ProgramInsertSchema, type ProgramPatch, programs, ProgramUpdateSchema } from "./Program"; +export async function findProgramById(db: Db, id: string): Promise { + const [program] = await db.select().from(programs).where(eq(programs.id, id)).limit(1); return program ?? null; } -export async function listPrograms( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(programs).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,57 +22,34 @@ export async function listPrograms( } return q; } -export async function createProgram( - db: Db, - data: z.input, -): Promise { +export async function createProgram(db: Db, data: z.input): Promise { const validated = ProgramInsertSchema.parse(data); const [program] = await db.insert(programs).values(validated).returning(); return program!; } -export async function updateProgram( - db: Db, - id: string, - patch: ProgramPatch, -): Promise { +export async function updateProgram(db: Db, id: string, patch: ProgramPatch): Promise { const validated = ProgramUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findProgramById(db, id); } - const [program] = await db - .update(programs) - .set(validated) - .where(eq(programs.id, id)) - .returning(); + const [program] = await db.update(programs).set(validated).where(eq(programs.id, id)).returning(); return program ?? null; } export async function deleteProgramById(db: Db, id: string): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(programs) - .where(eq(programs.id, id)) - .returning(); + const deleted = await db.delete(programs).where(eq(programs.id, id)).returning(); return deleted.length > 0; } -export async function findProgramsByAuthor( - db: Db, - authorId: string, -): Promise { +export async function findProgramsByAuthor(db: Db, authorId: string): Promise { return db.select().from(programs).where(eq(programs.authorId, authorId)); } -export async function findProgramsByAuthorIn( - db: Db, - authorIds: string[], -): Promise { +export async function findProgramsByAuthorIn(db: Db, authorIds: string[]): Promise { if (authorIds.length === 0) { return []; } - return db - .select() - .from(programs) - .where(inArray(programs.authorId, authorIds)); + return db.select().from(programs).where(inArray(programs.authorId, authorIds)); } diff --git a/examples/advanced-modeling/src/generated/Program.routes.ts b/examples/advanced-modeling/src/generated/Program.routes.ts index 4f9df9c3cd..d7f53b2bd5 100644 --- a/examples/advanced-modeling/src/generated/Program.routes.ts +++ b/examples/advanced-modeling/src/generated/Program.routes.ts @@ -35,31 +35,28 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function programRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Program.$path, - db, - table: programs, - insertSchema: ProgramInsertSchema, - updateSchema: ProgramUpdateSchema, - filterAllowlist: ProgramFilterAllowlist, - sortAllowlist: ProgramSortAllowlist, - dialect: "postgres", - knownFields: [ - "id", - "title", - "status", - "summary", - "priceCents", - "coverKey", - "authorId", - "syllabus", - "instructorProfile", - ], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Program.$path, + db, + table: programs, + insertSchema: ProgramInsertSchema, + updateSchema: ProgramUpdateSchema, + filterAllowlist: ProgramFilterAllowlist, + sortAllowlist: ProgramSortAllowlist, + dialect: "postgres", + knownFields: [ + "id", + "title", + "status", + "summary", + "priceCents", + "coverKey", + "authorId", + "syllabus", + "instructorProfile", + ], + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/Program.ts b/examples/advanced-modeling/src/generated/Program.ts index 3479546516..601e7ff873 100644 --- a/examples/advanced-modeling/src/generated/Program.ts +++ b/examples/advanced-modeling/src/generated/Program.ts @@ -2,51 +2,23 @@ // Source metadata: Program (Program) // Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you. import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; -import { - type AnyPgColumn, - bigint, - check, - jsonb, - pgTable, - text, - uuid, - varchar, -} from "drizzle-orm/pg-core"; +import { type AnyPgColumn, bigint, check, jsonb, pgTable, text, uuid, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; import { authors } from "./Author"; -import { - type InstructorProfile, - InstructorProfileInsertSchema, -} from "./InstructorProfile"; -import { - type SyllabusSection, - SyllabusSectionInsertSchema, -} from "./SyllabusSection"; +import { type InstructorProfile, InstructorProfileInsertSchema } from "./InstructorProfile"; +import { type SyllabusSection, SyllabusSectionInsertSchema } from "./SyllabusSection"; -export const programs = pgTable( - "programs", - { - id: uuid("id").primaryKey().defaultRandom(), - title: varchar("title", { length: 200 }).notNull(), - status: text("status", { - enum: ["draft", "published", "archived"] as const, - }), - summary: varchar("summary", { length: 2000 }), - priceCents: bigint("price_cents", { mode: "number" }), - coverKey: varchar("cover_key", { length: 80 }), - authorId: uuid("author_id") - .notNull() - .references((): AnyPgColumn => authors.id), - syllabus: jsonb("syllabus").$type(), - instructorProfile: jsonb("instructor_profile").$type(), - }, - (table) => [ - check( - "programs_status_chk", - sql`status IN ('draft', 'published', 'archived')`, - ), - ], -); +export const programs = pgTable("programs", { + id: uuid("id").primaryKey().defaultRandom(), + title: varchar("title", { length: 200 }).notNull(), + status: text("status", { enum: ["draft", "published", "archived"] as const }), + summary: varchar("summary", { length: 2000 }), + priceCents: bigint("price_cents", { mode: "number" }), + coverKey: varchar("cover_key", { length: 80 }), + authorId: uuid("author_id").notNull().references((): AnyPgColumn => authors.id), + syllabus: jsonb("syllabus").$type(), + instructorProfile: jsonb("instructor_profile").$type(), +}, (table) => [check("programs_status_chk", sql`status IN ('draft', 'published', 'archived')`)]); export type Program = InferSelectModel; export type ProgramInsert = InferInsertModel; export type ProgramUpdate = Partial; @@ -58,12 +30,10 @@ export const ProgramInsertSchema = z.object({ summary: z.string().max(2000).optional(), priceCents: z.number().int().optional(), coverKey: z.string().max(80).optional(), - authorId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ), + authorId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ), syllabus: z.array(SyllabusSectionInsertSchema).optional(), instructorProfile: InstructorProfileInsertSchema.optional(), }); @@ -74,13 +44,10 @@ export const ProgramUpdateSchema = z.object({ summary: z.string().max(2000).optional().nullable(), priceCents: z.number().int().optional().nullable(), coverKey: z.string().max(80).optional().nullable(), - authorId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ) - .optional(), + authorId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ).optional(), syllabus: z.array(SyllabusSectionInsertSchema).optional().nullable(), instructorProfile: InstructorProfileInsertSchema.optional().nullable(), }); @@ -125,39 +92,21 @@ export const Program = { label: "Title", view: "text", htmlType: "text", - rules: { - required: "Title is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, - }, - status: { - name: "status", - label: "Status", - view: "dropdown", - options: ["draft", "published", "archived"] as const, + rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, + status: { name: "status", label: "Status", view: "dropdown", options: ["draft", "published", "archived"] as const }, summary: { name: "summary", label: "Summary", view: "textarea", - rules: { - maxLength: { value: 2000, message: "Must be 2000 characters or fewer" }, - }, - }, - priceCents: { - name: "priceCents", - label: "Price Cents", - view: "currency", - currency: "USD", - locale: "en-US", + rules: { maxLength: { value: 2000, message: "Must be 2000 characters or fewer" } }, }, + priceCents: { name: "priceCents", label: "Price Cents", view: "currency", currency: "USD", locale: "en-US" }, coverKey: { name: "coverKey", label: "Cover Key", view: "image", - rules: { - maxLength: { value: 80, message: "Must be 80 characters or fewer" }, - }, + rules: { maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, }, authorId: { name: "authorId", @@ -166,18 +115,8 @@ export const Program = { htmlType: "text", rules: { required: "Author Id is required" }, }, - syllabus: { - name: "syllabus", - label: "Syllabus", - view: "text", - htmlType: "text", - }, - instructorProfile: { - name: "instructorProfile", - label: "Instructor Profile", - view: "text", - htmlType: "text", - }, + syllabus: { name: "syllabus", label: "Syllabus", view: "text", htmlType: "text" }, + instructorProfile: { name: "instructorProfile", label: "Instructor Profile", view: "text", htmlType: "text" }, } as const; import type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; diff --git a/examples/advanced-modeling/src/generated/ProgramSummary.queries.ts b/examples/advanced-modeling/src/generated/ProgramSummary.queries.ts index 2d3fcf25a3..02040e061f 100644 --- a/examples/advanced-modeling/src/generated/ProgramSummary.queries.ts +++ b/examples/advanced-modeling/src/generated/ProgramSummary.queries.ts @@ -7,15 +7,8 @@ import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; import { type ProgramSummary, programSummaryView } from "./ProgramSummary"; -export async function findProgramSummaryById( - db: Db, - id: string, -): Promise { - const [row] = await db - .select() - .from(programSummaryView) - .where(eq(programSummaryView.id, id)) - .limit(1); +export async function findProgramSummaryById(db: Db, id: string): Promise { + const [row] = await db.select().from(programSummaryView).where(eq(programSummaryView.id, id)).limit(1); return row ?? null; } diff --git a/examples/advanced-modeling/src/generated/ProgramSummary.routes.ts b/examples/advanced-modeling/src/generated/ProgramSummary.routes.ts index 1050e44196..e2e18e3d9a 100644 --- a/examples/advanced-modeling/src/generated/ProgramSummary.routes.ts +++ b/examples/advanced-modeling/src/generated/ProgramSummary.routes.ts @@ -31,18 +31,15 @@ import { mountReadOnlyCrudRoutes } from "../../codegen/runtime/drizzle-fastify/i * mount. Hand-write those reads rather than exposing this one open. */ export async function programSummaryRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountReadOnlyCrudRoutes({ - fastify: instance, - path: ProgramSummary.$path, - db, - view: programSummaryView, - filterAllowlist: ProgramSummaryFilterAllowlist, - sortAllowlist: ProgramSummarySortAllowlist, - dialect: "postgres", - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountReadOnlyCrudRoutes({ + fastify: instance, + path: ProgramSummary.$path, + db, + view: programSummaryView, + filterAllowlist: ProgramSummaryFilterAllowlist, + sortAllowlist: ProgramSummarySortAllowlist, + dialect: "postgres", + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/ProgramSummary.ts b/examples/advanced-modeling/src/generated/ProgramSummary.ts index 5d2aa001af..1576fe2edd 100644 --- a/examples/advanced-modeling/src/generated/ProgramSummary.ts +++ b/examples/advanced-modeling/src/generated/ProgramSummary.ts @@ -1,13 +1,6 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: ProgramSummary (ProgramSummary) -import { - bigint, - boolean, - pgView, - text, - uuid, - varchar, -} from "drizzle-orm/pg-core"; +import { bigint, boolean, pgView, text, uuid, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; // View declaration — Drizzle uses this for typed SELECT queries. @@ -36,18 +29,8 @@ export const ProgramSummary = { $path: "/program_summaries", id: { name: "id", label: "Id", view: "text", dbCol: "id" }, title: { name: "title", label: "Title", view: "text", dbCol: "title" }, - authorName: { - name: "authorName", - label: "Author Name", - view: "text", - dbCol: "author_name", - }, - lessonCount: { - name: "lessonCount", - label: "Lesson Count", - view: "number", - dbCol: "lesson_count", - }, + authorName: { name: "authorName", label: "Author Name", view: "text", dbCol: "author_name" }, + lessonCount: { name: "lessonCount", label: "Lesson Count", view: "number", dbCol: "lesson_count" }, completedRevenueCents: { name: "completedRevenueCents", label: "Completed Revenue Cents", @@ -56,17 +39,11 @@ export const ProgramSummary = { currency: "USD", locale: "en-US", }, - hasCoverArt: { - name: "hasCoverArt", - label: "Has Cover Art", - view: "checkbox", - dbCol: "has_cover_art", - }, + hasCoverArt: { name: "hasCoverArt", label: "Has Cover Art", view: "checkbox", dbCol: "has_cover_art" }, } as const; import type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; -export const ProgramSummaryFilterAllowlist = - {} as const satisfies FilterAllowlist; +export const ProgramSummaryFilterAllowlist = {} as const satisfies FilterAllowlist; import type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; export const ProgramSummarySortAllowlist = {} as const satisfies SortAllowlist; diff --git a/examples/advanced-modeling/src/generated/Purchase.queries.ts b/examples/advanced-modeling/src/generated/Purchase.queries.ts index 85fa7e2c92..8d125b9e21 100644 --- a/examples/advanced-modeling/src/generated/Purchase.queries.ts +++ b/examples/advanced-modeling/src/generated/Purchase.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Purchase, - PurchaseInsertSchema, - type PurchasePatch, - purchases, - PurchaseUpdateSchema, -} from "./Purchase"; -export async function findPurchaseById( - db: Db, - id: string, -): Promise { - const [purchase] = await db - .select() - .from(purchases) - .where(eq(purchases.id, id)) - .limit(1); +import { type Purchase, PurchaseInsertSchema, type PurchasePatch, purchases, PurchaseUpdateSchema } from "./Purchase"; +export async function findPurchaseById(db: Db, id: string): Promise { + const [purchase] = await db.select().from(purchases).where(eq(purchases.id, id)).limit(1); return purchase ?? null; } -export async function listPurchases( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listPurchases(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(purchases).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,57 +22,34 @@ export async function listPurchases( } return q; } -export async function createPurchase( - db: Db, - data: z.input, -): Promise { +export async function createPurchase(db: Db, data: z.input): Promise { const validated = PurchaseInsertSchema.parse(data); const [purchase] = await db.insert(purchases).values(validated).returning(); return purchase!; } -export async function updatePurchase( - db: Db, - id: string, - patch: PurchasePatch, -): Promise { +export async function updatePurchase(db: Db, id: string, patch: PurchasePatch): Promise { const validated = PurchaseUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findPurchaseById(db, id); } - const [purchase] = await db - .update(purchases) - .set(validated) - .where(eq(purchases.id, id)) - .returning(); + const [purchase] = await db.update(purchases).set(validated).where(eq(purchases.id, id)).returning(); return purchase ?? null; } export async function deletePurchaseById(db: Db, id: string): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(purchases) - .where(eq(purchases.id, id)) - .returning(); + const deleted = await db.delete(purchases).where(eq(purchases.id, id)).returning(); return deleted.length > 0; } -export async function findPurchasesByProgram( - db: Db, - programId: string, -): Promise { +export async function findPurchasesByProgram(db: Db, programId: string): Promise { return db.select().from(purchases).where(eq(purchases.programId, programId)); } -export async function findPurchasesByProgramIn( - db: Db, - programIds: string[], -): Promise { +export async function findPurchasesByProgramIn(db: Db, programIds: string[]): Promise { if (programIds.length === 0) { return []; } - return db - .select() - .from(purchases) - .where(inArray(purchases.programId, programIds)); + return db.select().from(purchases).where(inArray(purchases.programId, programIds)); } diff --git a/examples/advanced-modeling/src/generated/Purchase.routes.ts b/examples/advanced-modeling/src/generated/Purchase.routes.ts index 767fac818a..e76a7d187f 100644 --- a/examples/advanced-modeling/src/generated/Purchase.routes.ts +++ b/examples/advanced-modeling/src/generated/Purchase.routes.ts @@ -35,27 +35,18 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function purchaseRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Purchase.$path, - db, - table: purchases, - insertSchema: PurchaseInsertSchema, - updateSchema: PurchaseUpdateSchema, - filterAllowlist: PurchaseFilterAllowlist, - sortAllowlist: PurchaseSortAllowlist, - dialect: "postgres", - knownFields: [ - "id", - "programId", - "amountCents", - "status", - "purchasedAt", - ], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Purchase.$path, + db, + table: purchases, + insertSchema: PurchaseInsertSchema, + updateSchema: PurchaseUpdateSchema, + filterAllowlist: PurchaseFilterAllowlist, + sortAllowlist: PurchaseSortAllowlist, + dialect: "postgres", + knownFields: ["id", "programId", "amountCents", "status", "purchasedAt"], + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/Purchase.ts b/examples/advanced-modeling/src/generated/Purchase.ts index 5e1ecd53ac..3ac361e202 100644 --- a/examples/advanced-modeling/src/generated/Purchase.ts +++ b/examples/advanced-modeling/src/generated/Purchase.ts @@ -2,41 +2,17 @@ // Source metadata: Purchase (Purchase) // Extend in your own module (e.g. Purchase.extra.ts) — nothing imports it for you. import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; -import { - type AnyPgColumn, - bigint, - check, - pgTable, - text, - timestamp, - uuid, -} from "drizzle-orm/pg-core"; +import { type AnyPgColumn, bigint, check, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"; import { z } from "zod"; import { programs } from "./Program"; -export const purchases = pgTable( - "purchases", - { - id: uuid("id").primaryKey().defaultRandom(), - programId: uuid("program_id") - .notNull() - .references((): AnyPgColumn => programs.id), - amountCents: bigint("amount_cents", { mode: "number" }), - status: text("status", { - enum: ["pending", "completed", "refunded"] as const, - }), - purchasedAt: timestamp("purchased_at", { - mode: "string", - withTimezone: true, - }), - }, - (table) => [ - check( - "purchases_status_chk", - sql`status IN ('pending', 'completed', 'refunded')`, - ), - ], -); +export const purchases = pgTable("purchases", { + id: uuid("id").primaryKey().defaultRandom(), + programId: uuid("program_id").notNull().references((): AnyPgColumn => programs.id), + amountCents: bigint("amount_cents", { mode: "number" }), + status: text("status", { enum: ["pending", "completed", "refunded"] as const }), + purchasedAt: timestamp("purchased_at", { mode: "string", withTimezone: true }), +}, (table) => [check("purchases_status_chk", sql`status IN ('pending', 'completed', 'refunded')`)]); export type Purchase = InferSelectModel; export type PurchaseInsert = InferInsertModel; export type PurchaseUpdate = Partial; @@ -49,10 +25,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -61,49 +35,33 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const PurchaseInsertSchema = z.object({ - programId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ), + programId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ), amountCents: z.number().int().optional(), status: z.enum(["pending", "completed", "refunded"]).optional(), - purchasedAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + purchasedAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); export const PurchaseUpdateSchema = z.object({ - programId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ) - .optional(), + programId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ).optional(), amountCents: z.number().int().optional().nullable(), status: z.enum(["pending", "completed", "refunded"]).optional().nullable(), - purchasedAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional() - .nullable(), + purchasedAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional().nullable(), }); /** Typed create shape for Purchase: the insert schema's INPUT (pre-transform) type. A @@ -148,25 +106,9 @@ export const Purchase = { htmlType: "text", rules: { required: "Program Id is required" }, }, - amountCents: { - name: "amountCents", - label: "Amount Cents", - view: "currency", - currency: "USD", - locale: "en-US", - }, - status: { - name: "status", - label: "Status", - view: "dropdown", - options: ["pending", "completed", "refunded"] as const, - }, - purchasedAt: { - name: "purchasedAt", - label: "Purchased At", - view: "date", - htmlType: "datetime-local", - }, + amountCents: { name: "amountCents", label: "Amount Cents", view: "currency", currency: "USD", locale: "en-US" }, + status: { name: "status", label: "Status", view: "dropdown", options: ["pending", "completed", "refunded"] as const }, + purchasedAt: { name: "purchasedAt", label: "Purchased At", view: "date", htmlType: "datetime-local" }, } as const; import type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; diff --git a/examples/advanced-modeling/src/generated/SyllabusSection.ts b/examples/advanced-modeling/src/generated/SyllabusSection.ts index ae049c1ad0..74f353ccd0 100644 --- a/examples/advanced-modeling/src/generated/SyllabusSection.ts +++ b/examples/advanced-modeling/src/generated/SyllabusSection.ts @@ -24,19 +24,14 @@ export const SyllabusSection = { label: "Heading", view: "text", htmlType: "text", - rules: { - required: "Heading is required", - maxLength: { value: 120, message: "Must be 120 characters or fewer" }, - }, + rules: { required: "Heading is required", maxLength: { value: 120, message: "Must be 120 characters or fewer" } }, }, summary: { name: "summary", label: "Summary", view: "text", htmlType: "text", - rules: { - maxLength: { value: 500, message: "Must be 500 characters or fewer" }, - }, + rules: { maxLength: { value: 500, message: "Must be 500 characters or fewer" } }, }, orderIndex: { name: "orderIndex", diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json index 1c71c30927..774179acca 100644 --- a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json +++ b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json @@ -10,17 +10,17 @@ "generated/python/subscriber_names.py": "269637a02bf9b46f55658b58cb42f83196c03a877e1e2101337847fd406c1561", "generated/python/subscriber_router.py": "16502ff815bf9ae29c7dba4700d0465d06058a9fd7ea8db5f98334d52d284851", "generated/ts/Subscriber.queries.ts": { - "hash": "9f1a459c57fafc98bf074b4443b506d4a1e7023ed188f293021ae89c298d4562", + "hash": "63adba7ac4415f5e9962c4da100ffd97816524580a513e8350d14bc7a9f3507c", "generatedBy": "queries-file", "sourceNode": "acme::Subscriber" }, "generated/ts/Subscriber.routes.ts": { - "hash": "f76f592c98bd0ac5c07c4fe9c26cd88659793141e6620310dc725c7edcf68099", + "hash": "c26d2e8e146c5e310fabefa16d1a413109716544a3f817f20f4536cf09e2585e", "generatedBy": "routes-file", "sourceNode": "acme::Subscriber" }, "generated/ts/Subscriber.ts": { - "hash": "a78c17f915222ee108290c28468313d77f77b5cff438f485324409302e389a96", + "hash": "760b3d76d100d05f289070ce483f63ee022a3c6fc8d6356e691e4d17f0593734", "generatedBy": "entity-file", "sourceNode": "acme::Subscriber" }, diff --git a/examples/showcase/codegen/generators/barrel.ts b/examples/showcase/codegen/generators/barrel.ts index 2c82677ac3..001cf7953d 100644 --- a/examples/showcase/codegen/generators/barrel.ts +++ b/examples/showcase/codegen/generators/barrel.ts @@ -24,7 +24,6 @@ import { type ExtStyle, type ResolvedTarget, barrelModuleSpecifier, - formatTs, GENERATED_HEADER, GENERATED_EDIT_NOTE, effectivePackage, @@ -66,14 +65,12 @@ export const barrel = function barrel(opts?: BarrelOpts): Generator { for (const e of entities) claimBarrelNames(ctx, e); return { path: "index.ts", - content: await formatTs( - renderBarrel( + content: renderBarrel( entities.map((e) => ({ name: e.name, package: effectivePackage(e) })), rc.extStyle, rc.selfTarget, rc.entityModuleTarget, ), - ), }; }), }; diff --git a/examples/showcase/codegen/generators/entity.ts b/examples/showcase/codegen/generators/entity.ts index 926da1c687..4931111a28 100644 --- a/examples/showcase/codegen/generators/entity.ts +++ b/examples/showcase/codegen/generators/entity.ts @@ -54,7 +54,6 @@ import { isWriteThrough, isAbstract, hasWritableRdbSource, - formatTs, ownedRuntimeImport, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, @@ -188,7 +187,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), - content: await formatTs(renderEntity(entity, renderContext, { allowlists })), + content: renderEntity(entity, renderContext, { allowlists }), }; }); @@ -209,7 +208,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator ctx.select !== undefined ? { select: ctx.select } : undefined, ); if (sharedEnums !== null) { - files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: await formatTs(sharedEnums) }); + files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: sharedEnums }); } return files; }, diff --git a/examples/showcase/codegen/generators/queries.ts b/examples/showcase/codegen/generators/queries.ts index 8d03e08142..44617b4c61 100644 --- a/examples/showcase/codegen/generators/queries.ts +++ b/examples/showcase/codegen/generators/queries.ts @@ -43,7 +43,6 @@ import { isProjection, isWriteThrough, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, GENERATED_HEADER, @@ -173,7 +172,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), - content: await formatTs(renderQueries(entity, ctx.renderContext)), + content: renderQueries(entity, ctx.renderContext), }; }), }; diff --git a/examples/showcase/codegen/generators/routes.ts b/examples/showcase/codegen/generators/routes.ts index 16837743da..3117986622 100644 --- a/examples/showcase/codegen/generators/routes.ts +++ b/examples/showcase/codegen/generators/routes.ts @@ -73,7 +73,6 @@ import { writeDeniedColumnsLine, knownFieldsLine, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -770,7 +769,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), - content: await formatTs(renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); const generator: Generator = { @@ -796,7 +795,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("fastify"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "fastify")), + content: renderRoutesIndex(matched, ctx.renderContext, "fastify"), }]; }, }; diff --git a/examples/showcase/codegen/templates/routes-index.ts b/examples/showcase/codegen/templates/routes-index.ts index e9969b576f..2f0608864b 100644 --- a/examples/showcase/codegen/templates/routes-index.ts +++ b/examples/showcase/codegen/templates/routes-index.ts @@ -55,7 +55,6 @@ export function renderRoutesIndex( " * on the mount paths before calling this. An entity that needs a row-ownership rule", " * should not be registered open: narrow its routes with `expose` or hand-write them.", " */", - "// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables", "export function registerAllRoutes(app: Hono, deps: { db: unknown }): void {", ...sorted.map((e) => ` ${handler(e)}(app, deps);`), "}", diff --git a/examples/showcase/codegen/templates/view-decl.ts b/examples/showcase/codegen/templates/view-decl.ts index 9770bc091d..3dd02b2329 100644 --- a/examples/showcase/codegen/templates/view-decl.ts +++ b/examples/showcase/codegen/templates/view-decl.ts @@ -111,7 +111,7 @@ function viewColumnLine( : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 - ? `, ${JSON.stringify(spec.fnOptions)}` + ? `, ${optionsLiteral(spec.fnOptions)}` : ""; // #204 — of the table modifiers, only `.array()` (postgres native array element // typing) and `.notNull()` (shapes the SELECT type) carry to an existing view; @@ -252,3 +252,12 @@ export function renderViewReadZodObject(fields: readonly MetaField[], opts: View ${joinCode(lines, { on: ",\n" })} })`; } + +/** A column's options as a JS object literal: `{ length: 200 }`, not JSON's `{ "length": 200 }`. */ +function optionsLiteral(options: Record): string { + const entries = Object.entries(options).map(([key, value]) => { + const name = /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key); + return `${name}: ${JSON.stringify(value)}`; + }); + return `{ ${entries.join(", ")} }`; +} diff --git a/examples/showcase/generated/ts/Subscriber.queries.ts b/examples/showcase/generated/ts/Subscriber.queries.ts index caa8047243..93325d905a 100644 --- a/examples/showcase/generated/ts/Subscriber.queries.ts +++ b/examples/showcase/generated/ts/Subscriber.queries.ts @@ -5,11 +5,7 @@ import { eq } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; import { type Subscriber, @@ -19,21 +15,11 @@ import { subscribers, SubscriberUpdateSchema, } from "./Subscriber"; -export async function findSubscriberById( - db: Db, - id: number, -): Promise { - const [subscriber] = await db - .select() - .from(subscribers) - .where(eq(subscribers.id, id)) - .limit(1); +export async function findSubscriberById(db: Db, id: number): Promise { + const [subscriber] = await db.select().from(subscribers).where(eq(subscribers.id, id)).limit(1); return subscriber ?? null; } -export async function listSubscribers( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listSubscribers(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(subscribers).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -43,15 +29,9 @@ export async function listSubscribers( } return q; } -export async function createSubscriber( - db: Db, - data: z.input, -): Promise { +export async function createSubscriber(db: Db, data: z.input): Promise { const validated = SubscriberInsertSchema.parse(data); - const [subscriber] = await db - .insert(subscribers) - .values(validated) - .returning(); + const [subscriber] = await db.insert(subscribers).values(validated).returning(); return subscriber!; } export async function insertPreservingSubscriber( @@ -59,39 +39,22 @@ export async function insertPreservingSubscriber( data: z.input, ): Promise { const validated = SubscriberInsertPreservingSchema.parse(data); - const [subscriber] = await db - .insert(subscribers) - .values(validated) - .returning(); + const [subscriber] = await db.insert(subscribers).values(validated).returning(); return subscriber!; } -export async function updateSubscriber( - db: Db, - id: number, - patch: SubscriberPatch, -): Promise { +export async function updateSubscriber(db: Db, id: number, patch: SubscriberPatch): Promise { const validated = SubscriberUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findSubscriberById(db, id); } - const [subscriber] = await db - .update(subscribers) - .set(validated) - .where(eq(subscribers.id, id)) - .returning(); + const [subscriber] = await db.update(subscribers).set(validated).where(eq(subscribers.id, id)).returning(); return subscriber ?? null; } -export async function deleteSubscriberById( - db: Db, - id: number, -): Promise { +export async function deleteSubscriberById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(subscribers) - .where(eq(subscribers.id, id)) - .returning(); + const deleted = await db.delete(subscribers).where(eq(subscribers.id, id)).returning(); return deleted.length > 0; } diff --git a/examples/showcase/generated/ts/Subscriber.routes.ts b/examples/showcase/generated/ts/Subscriber.routes.ts index efd2cb12ee..c4b84b3775 100644 --- a/examples/showcase/generated/ts/Subscriber.routes.ts +++ b/examples/showcase/generated/ts/Subscriber.routes.ts @@ -35,21 +35,18 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function subscriberRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Subscriber.$path, - db, - table: subscribers, - insertSchema: SubscriberInsertSchema, - updateSchema: SubscriberUpdateSchema, - filterAllowlist: SubscriberFilterAllowlist, - sortAllowlist: SubscriberSortAllowlist, - dialect: "sqlite", - knownFields: ["id", "email", "name", "status", "createdAt"], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Subscriber.$path, + db, + table: subscribers, + insertSchema: SubscriberInsertSchema, + updateSchema: SubscriberUpdateSchema, + filterAllowlist: SubscriberFilterAllowlist, + sortAllowlist: SubscriberSortAllowlist, + dialect: "sqlite", + knownFields: ["id", "email", "name", "status", "createdAt"], + }); + }, { prefix: "/api" }); } diff --git a/examples/showcase/generated/ts/Subscriber.ts b/examples/showcase/generated/ts/Subscriber.ts index 68907c6ce7..61079d18dc 100644 --- a/examples/showcase/generated/ts/Subscriber.ts +++ b/examples/showcase/generated/ts/Subscriber.ts @@ -5,24 +5,13 @@ import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; import { check, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; import { z } from "zod"; -export const subscribers = sqliteTable( - "subscribers", - { - id: integer("id").primaryKey({ autoIncrement: true }), - email: text("email").notNull(), - name: text("name"), - status: text("status", { - enum: ["active", "paused", "cancelled"] as const, - }).notNull(), - createdAt: text("created_at").$defaultFn(() => new Date().toISOString()), - }, - (table) => [ - check( - "subscribers_status_chk", - sql`status IN ('active', 'paused', 'cancelled')`, - ), - ], -); +export const subscribers = sqliteTable("subscribers", { + id: integer("id").primaryKey({ autoIncrement: true }), + email: text("email").notNull(), + name: text("name"), + status: text("status", { enum: ["active", "paused", "cancelled"] as const }).notNull(), + createdAt: text("created_at").$defaultFn(() => new Date().toISOString()), +}, (table) => [check("subscribers_status_chk", sql`status IN ('active', 'paused', 'cancelled')`)]); export type Subscriber = InferSelectModel; export type SubscriberInsert = InferInsertModel; export type SubscriberUpdate = Partial; @@ -35,10 +24,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -47,19 +34,14 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const SubscriberInsertSchema = z.object({ email: z.string().min(1).max(320), name: z.string().optional(), status: z.enum(["active", "paused", "cancelled"]), - createdAt: z - .string() - .optional() - .transform(() => new Date().toISOString()), + createdAt: z.string().optional().transform(() => new Date().toISOString()), }); export const SubscriberUpdateSchema = z.object({ @@ -84,20 +66,14 @@ export const SubscriberInsertPreservingSchema = z.object({ email: z.string().min(1).max(320), name: z.string().optional(), status: z.enum(["active", "paused", "cancelled"]), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); /** Typed input of `insertPreservingSubscriber` — SubscriberInsertPreservingSchema's pre-transform shape. */ -export type SubscriberCreatePreserving = z.input< - typeof SubscriberInsertPreservingSchema ->; +export type SubscriberCreatePreserving = z.input; /** * Metadata constants for Subscriber. * @@ -130,10 +106,7 @@ export const Subscriber = { label: "Email", view: "text", htmlType: "text", - rules: { - required: "Email is required", - maxLength: { value: 320, message: "Must be 320 characters or fewer" }, - }, + rules: { required: "Email is required", maxLength: { value: 320, message: "Must be 320 characters or fewer" } }, }, name: { name: "name", label: "Name", view: "text", htmlType: "text" }, status: { @@ -143,12 +116,7 @@ export const Subscriber = { rules: { required: "Status is required" }, options: ["active", "paused", "cancelled"] as const, }, - createdAt: { - name: "createdAt", - label: "Created At", - view: "date", - htmlType: "datetime-local", - }, + createdAt: { name: "createdAt", label: "Created At", view: "date", htmlType: "datetime-local" }, } as const; import type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; diff --git a/examples/showcase/inline/deep-currency.txt b/examples/showcase/inline/deep-currency.txt index 43a89436d5..c05418fd13 100644 --- a/examples/showcase/inline/deep-currency.txt +++ b/examples/showcase/inline/deep-currency.txt @@ -1,7 +1 @@ - priceCents: { - name: "priceCents", - label: "Price Cents", - view: "currency", - currency: "USD", - locale: "en-US", - }, + priceCents: { name: "priceCents", label: "Price Cents", view: "currency", currency: "USD", locale: "en-US" }, diff --git a/examples/showcase/inline/ts-entity.txt b/examples/showcase/inline/ts-entity.txt index 4747cfe1d0..e43fc0a083 100644 --- a/examples/showcase/inline/ts-entity.txt +++ b/examples/showcase/inline/ts-entity.txt @@ -1,16 +1,11 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -export const subscribers = sqliteTable( - "subscribers", - { - id: integer("id").primaryKey({ autoIncrement: true }), - email: text("email").notNull(), - name: text("name"), - status: text("status", { - enum: ["active", "paused", "cancelled"] as const, - }).notNull(), - createdAt: text("created_at").$defaultFn(() => new Date().toISOString()), - }, -); +export const subscribers = sqliteTable("subscribers", { + id: integer("id").primaryKey({ autoIncrement: true }), + email: text("email").notNull(), + name: text("name"), + status: text("status", { enum: ["active", "paused", "cancelled"] as const }).notNull(), + createdAt: text("created_at").$defaultFn(() => new Date().toISOString()), +}, (table) => [check("subscribers_status_chk", sql`status IN ('active', 'paused', 'cancelled')`)]); export type Subscriber = InferSelectModel; export type SubscriberInsert = InferInsertModel; export const SubscriberInsertSchema = z.object({ diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index de8940334c..1ba85b43c7 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -20,9 +20,9 @@ }, "ts-entity": { "lang": "ts", - "inline": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n…\nexport const subscribers = sqliteTable(\n "subscribers",\n {\n id: integer("id").primaryKey({ autoIncrement: true }),\n email: text("email").notNull(),\n name: text("name"),\n status: text("status", {\n enum: ["active", "paused", "cancelled"] as const,\n }).notNull(),\n createdAt: text("created_at").$defaultFn(() => new Date().toISOString()),\n },\n…\n);\nexport type Subscriber = InferSelectModel<typeof subscribers>;\nexport type SubscriberInsert = InferInsertModel<typeof subscribers>;\n…\nexport const SubscriberInsertSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n…\n});\n…", - "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Subscriber (Subscriber)\n// Extend in your own module (e.g. Subscriber.extra.ts) — nothing imports it for you.\nimport { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm";\nimport { check, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";\nimport { z } from "zod";\n\nexport const subscribers = sqliteTable(\n "subscribers",\n {\n id: integer("id").primaryKey({ autoIncrement: true }),\n email: text("email").notNull(),\n name: text("name"),\n status: text("status", {\n enum: ["active", "paused", "cancelled"] as const,\n }).notNull(),\n createdAt: text("created_at").$defaultFn(() => new Date().toISOString()),\n },\n (table) => [\n check(\n "subscribers_status_chk",\n sql`status IN ('active', 'paused', 'cancelled')`,\n ),\n ],\n);\nexport type Subscriber = InferSelectModel<typeof subscribers>;\nexport type SubscriberInsert = InferInsertModel<typeof subscribers>;\nexport type SubscriberUpdate = Partial<SubscriberInsert>;\nexport type SubscriberStatus = "active" | "paused" | "cancelled";\nexport const SubscriberStatusEnum = z.enum(["active", "paused", "cancelled"]);\n/** A field.timestamp instant in UTC (`YYYY-MM-DDTHH:MM:SS[.fff]Z`): a value already spelled so is kept\n * as sent, an offset is applied, a zoneless value is UTC and a date alone is midnight UTC.\n * SQLite/D1 compare timestamps as text, so instants are stored in UTC. Generated. */\nfunction utcIsoTimestamp(v: string): string {\n if (/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$/.test(v)) {\n return v;\n }\n const m =\n /^(\\d{4}-\\d{2}-\\d{2})(?:[Tt ](\\d{2}:\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?(?:([Zz])|([+-]\\d{2}):?(\\d{2})?)?)?$/.exec(\n v,\n );\n if (m === null) {\n return v;\n }\n const t = Date.parse(\n `${m[1]}T${m[2] ?? "00:00"}:${m[3] ?? "00"}.${(m[4] ?? "").slice(0, 3).padEnd(3, "0")}${\n m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}`\n }`,\n );\n return Number.isNaN(t)\n ? v\n : new Date(t).toISOString().replace(/\\.?0+Z$/, "Z");\n}\n\nexport const SubscriberInsertSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n createdAt: z\n .string()\n .optional()\n .transform(() => new Date().toISOString()),\n});\n\nexport const SubscriberUpdateSchema = z.object({\n email: z.string().min(1).max(320).optional(),\n name: z.string().optional().nullable(),\n status: z.enum(["active", "paused", "cancelled"]).optional(),\n});\n\n/** Typed create shape for Subscriber: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createSubscriber` call site;\n * the schema still validates at runtime. */\nexport type SubscriberCreate = z.input<typeof SubscriberInsertSchema>;\n\n/** Typed patch shape for Subscriber: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateSubscriber` call site. */\nexport type SubscriberPatch = z.input<typeof SubscriberUpdateSchema>;\n\n/** Insert-shape for import / restore / replication of Subscriber: identical to\n * SubscriberInsertSchema, but the @autoSet timestamp columns are written VERBATIM\n * (no create-time now() stamp) so the caller's original values are preserved. */\nexport const SubscriberInsertPreservingSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n createdAt: z\n .string()\n .regex(\n /^(?:\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|02-(?:0[1-9]|1\\d|2[0-8]))|(?:\\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:[Zz]|[+-](?:[01]\\d|2[0-3])(?::?[0-5]\\d)?)?)?$/,\n "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])",\n )\n .transform(utcIsoTimestamp)\n .optional(),\n});\n\n/** Typed input of `insertPreservingSubscriber` — SubscriberInsertPreservingSchema's pre-transform shape. */\nexport type SubscriberCreatePreserving = z.input<\n typeof SubscriberInsertPreservingSchema\n>;\n/**\n * Metadata constants for Subscriber.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Subscriber, SubscriberInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Subscriber = {\n $entity: "Subscriber",\n $table: "subscribers",\n $path: "/subscribers",\n id: { name: "id", label: "Id", view: "number", htmlType: "number" },\n email: {\n name: "email",\n label: "Email",\n view: "text",\n htmlType: "text",\n rules: {\n required: "Email is required",\n maxLength: { value: 320, message: "Must be 320 characters or fewer" },\n },\n },\n name: { name: "name", label: "Name", view: "text", htmlType: "text" },\n status: {\n name: "status",\n label: "Status",\n view: "dropdown",\n rules: { required: "Status is required" },\n options: ["active", "paused", "cancelled"] as const,\n },\n createdAt: {\n name: "createdAt",\n label: "Created At",\n view: "date",\n htmlType: "datetime-local",\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const SubscriberFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const SubscriberSortAllowlist = {} as const satisfies SortAllowlist;\nexport type SubscriberFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: SubscriberFilter[];\n and?: SubscriberFilter[];\n};\n", - "lineCount": 165 + "inline": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n…\nexport const subscribers = sqliteTable("subscribers", {\n id: integer("id").primaryKey({ autoIncrement: true }),\n email: text("email").notNull(),\n name: text("name"),\n status: text("status", { enum: ["active", "paused", "cancelled"] as const }).notNull(),\n createdAt: text("created_at").$defaultFn(() => new Date().toISOString()),\n}, (table) => [check("subscribers_status_chk", sql`status IN ('active', 'paused', 'cancelled')`)]);\nexport type Subscriber = InferSelectModel<typeof subscribers>;\nexport type SubscriberInsert = InferInsertModel<typeof subscribers>;\n…\nexport const SubscriberInsertSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n…\n});\n…", + "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Subscriber (Subscriber)\n// Extend in your own module (e.g. Subscriber.extra.ts) — nothing imports it for you.\nimport { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm";\nimport { check, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";\nimport { z } from "zod";\n\nexport const subscribers = sqliteTable("subscribers", {\n id: integer("id").primaryKey({ autoIncrement: true }),\n email: text("email").notNull(),\n name: text("name"),\n status: text("status", { enum: ["active", "paused", "cancelled"] as const }).notNull(),\n createdAt: text("created_at").$defaultFn(() => new Date().toISOString()),\n}, (table) => [check("subscribers_status_chk", sql`status IN ('active', 'paused', 'cancelled')`)]);\nexport type Subscriber = InferSelectModel<typeof subscribers>;\nexport type SubscriberInsert = InferInsertModel<typeof subscribers>;\nexport type SubscriberUpdate = Partial<SubscriberInsert>;\nexport type SubscriberStatus = "active" | "paused" | "cancelled";\nexport const SubscriberStatusEnum = z.enum(["active", "paused", "cancelled"]);\n/** A field.timestamp instant in UTC (`YYYY-MM-DDTHH:MM:SS[.fff]Z`): a value already spelled so is kept\n * as sent, an offset is applied, a zoneless value is UTC and a date alone is midnight UTC.\n * SQLite/D1 compare timestamps as text, so instants are stored in UTC. Generated. */\nfunction utcIsoTimestamp(v: string): string {\n if (/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$/.test(v)) {\n return v;\n }\n const m = /^(\\d{4}-\\d{2}-\\d{2})(?:[Tt ](\\d{2}:\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?(?:([Zz])|([+-]\\d{2}):?(\\d{2})?)?)?$/\n .exec(v);\n if (m === null) {\n return v;\n }\n const t = Date.parse(\n `${m[1]}T${m[2] ?? "00:00"}:${m[3] ?? "00"}.${(m[4] ?? "").slice(0, 3).padEnd(3, "0")}${\n m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}`\n }`,\n );\n return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\\.?0+Z$/, "Z");\n}\n\nexport const SubscriberInsertSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n createdAt: z.string().optional().transform(() => new Date().toISOString()),\n});\n\nexport const SubscriberUpdateSchema = z.object({\n email: z.string().min(1).max(320).optional(),\n name: z.string().optional().nullable(),\n status: z.enum(["active", "paused", "cancelled"]).optional(),\n});\n\n/** Typed create shape for Subscriber: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createSubscriber` call site;\n * the schema still validates at runtime. */\nexport type SubscriberCreate = z.input<typeof SubscriberInsertSchema>;\n\n/** Typed patch shape for Subscriber: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateSubscriber` call site. */\nexport type SubscriberPatch = z.input<typeof SubscriberUpdateSchema>;\n\n/** Insert-shape for import / restore / replication of Subscriber: identical to\n * SubscriberInsertSchema, but the @autoSet timestamp columns are written VERBATIM\n * (no create-time now() stamp) so the caller's original values are preserved. */\nexport const SubscriberInsertPreservingSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n createdAt: z.string().regex(\n /^(?:\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|02-(?:0[1-9]|1\\d|2[0-8]))|(?:\\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:[Zz]|[+-](?:[01]\\d|2[0-3])(?::?[0-5]\\d)?)?)?$/,\n "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])",\n ).transform(utcIsoTimestamp).optional(),\n});\n\n/** Typed input of `insertPreservingSubscriber` — SubscriberInsertPreservingSchema's pre-transform shape. */\nexport type SubscriberCreatePreserving = z.input<typeof SubscriberInsertPreservingSchema>;\n/**\n * Metadata constants for Subscriber.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Subscriber, SubscriberInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Subscriber = {\n $entity: "Subscriber",\n $table: "subscribers",\n $path: "/subscribers",\n id: { name: "id", label: "Id", view: "number", htmlType: "number" },\n email: {\n name: "email",\n label: "Email",\n view: "text",\n htmlType: "text",\n rules: { required: "Email is required", maxLength: { value: 320, message: "Must be 320 characters or fewer" } },\n },\n name: { name: "name", label: "Name", view: "text", htmlType: "text" },\n status: {\n name: "status",\n label: "Status",\n view: "dropdown",\n rules: { required: "Status is required" },\n options: ["active", "paused", "cancelled"] as const,\n },\n createdAt: { name: "createdAt", label: "Created At", view: "date", htmlType: "datetime-local" },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const SubscriberFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const SubscriberSortAllowlist = {} as const satisfies SortAllowlist;\nexport type SubscriberFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: SubscriberFilter[];\n and?: SubscriberFilter[];\n};\n", + "lineCount": 133 }, "python-model": { "lang": "python", @@ -87,20 +87,20 @@ "deep-validators": { "lang": "ts", "inline": "…\nexport const AuthorInsertSchema = z.object({\n name: z.string().min(1).max(120),\n email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")),\n bio: z.string().max(500).optional(),\n});\n…", - "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Author (Author)\n// Extend in your own module (e.g. Author.extra.ts) — nothing imports it for you.\nimport type { InferInsertModel, InferSelectModel } from "drizzle-orm";\nimport { pgTable, uuid, varchar } from "drizzle-orm/pg-core";\nimport { z } from "zod";\n\nexport const authors = pgTable("authors", {\n id: uuid("id").primaryKey().defaultRandom(),\n name: varchar("name", { length: 120 }).notNull(),\n email: varchar("email", { length: 320 }).notNull(),\n bio: varchar("bio", { length: 2000 }),\n});\nexport type Author = InferSelectModel<typeof authors>;\nexport type AuthorInsert = InferInsertModel<typeof authors>;\nexport type AuthorUpdate = Partial<AuthorInsert>;\nexport const AuthorInsertSchema = z.object({\n name: z.string().min(1).max(120),\n email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")),\n bio: z.string().max(500).optional(),\n});\n\nexport const AuthorUpdateSchema = z.object({\n name: z.string().min(1).max(120).optional(),\n email: z\n .string()\n .min(1)\n .max(320)\n .regex(new RegExp("^(?:[^@]+@[^@]+)$"))\n .optional(),\n bio: z.string().max(500).optional().nullable(),\n});\n\n/** Typed create shape for Author: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createAuthor` call site;\n * the schema still validates at runtime. */\nexport type AuthorCreate = z.input<typeof AuthorInsertSchema>;\n\n/** Typed patch shape for Author: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateAuthor` call site. */\nexport type AuthorPatch = z.input<typeof AuthorUpdateSchema>;\n/**\n * Metadata constants for Author.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Author, AuthorInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Author = {\n $entity: "Author",\n $table: "authors",\n $path: "/authors",\n id: { name: "id", label: "Id", view: "text", htmlType: "text" },\n name: {\n name: "name",\n label: "Name",\n view: "text",\n htmlType: "text",\n rules: {\n required: "Name is required",\n maxLength: { value: 120, message: "Must be 120 characters or fewer" },\n },\n },\n email: {\n name: "email",\n label: "Email",\n view: "text",\n htmlType: "text",\n rules: {\n pattern: { value: /[^@]+@[^@]+/, message: "Invalid format" },\n required: "Email is required",\n maxLength: { value: 320, message: "Must be 320 characters or fewer" },\n },\n },\n bio: {\n name: "bio",\n label: "Bio",\n view: "text",\n htmlType: "text",\n rules: {\n minLength: { value: 0, message: "Must be at least 0 characters" },\n maxLength: { value: 500, message: "Must be 500 characters or fewer" },\n },\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const AuthorFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const AuthorSortAllowlist = {} as const satisfies SortAllowlist;\nexport type AuthorFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: AuthorFilter[];\n and?: AuthorFilter[];\n};\n", - "lineCount": 113 + "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Author (Author)\n// Extend in your own module (e.g. Author.extra.ts) — nothing imports it for you.\nimport type { InferInsertModel, InferSelectModel } from "drizzle-orm";\nimport { pgTable, uuid, varchar } from "drizzle-orm/pg-core";\nimport { z } from "zod";\n\nexport const authors = pgTable("authors", {\n id: uuid("id").primaryKey().defaultRandom(),\n name: varchar("name", { length: 120 }).notNull(),\n email: varchar("email", { length: 320 }).notNull(),\n bio: varchar("bio", { length: 2000 }),\n});\nexport type Author = InferSelectModel<typeof authors>;\nexport type AuthorInsert = InferInsertModel<typeof authors>;\nexport type AuthorUpdate = Partial<AuthorInsert>;\nexport const AuthorInsertSchema = z.object({\n name: z.string().min(1).max(120),\n email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")),\n bio: z.string().max(500).optional(),\n});\n\nexport const AuthorUpdateSchema = z.object({\n name: z.string().min(1).max(120).optional(),\n email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")).optional(),\n bio: z.string().max(500).optional().nullable(),\n});\n\n/** Typed create shape for Author: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createAuthor` call site;\n * the schema still validates at runtime. */\nexport type AuthorCreate = z.input<typeof AuthorInsertSchema>;\n\n/** Typed patch shape for Author: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateAuthor` call site. */\nexport type AuthorPatch = z.input<typeof AuthorUpdateSchema>;\n/**\n * Metadata constants for Author.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Author, AuthorInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Author = {\n $entity: "Author",\n $table: "authors",\n $path: "/authors",\n id: { name: "id", label: "Id", view: "text", htmlType: "text" },\n name: {\n name: "name",\n label: "Name",\n view: "text",\n htmlType: "text",\n rules: { required: "Name is required", maxLength: { value: 120, message: "Must be 120 characters or fewer" } },\n },\n email: {\n name: "email",\n label: "Email",\n view: "text",\n htmlType: "text",\n rules: {\n pattern: { value: /[^@]+@[^@]+/, message: "Invalid format" },\n required: "Email is required",\n maxLength: { value: 320, message: "Must be 320 characters or fewer" },\n },\n },\n bio: {\n name: "bio",\n label: "Bio",\n view: "text",\n htmlType: "text",\n rules: {\n minLength: { value: 0, message: "Must be at least 0 characters" },\n maxLength: { value: 500, message: "Must be 500 characters or fewer" },\n },\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const AuthorFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const AuthorSortAllowlist = {} as const satisfies SortAllowlist;\nexport type AuthorFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: AuthorFilter[];\n and?: AuthorFilter[];\n};\n", + "lineCount": 105 }, "deep-currency": { "lang": "ts", - "inline": "…\n priceCents: {\n name: "priceCents",\n label: "Price Cents",\n view: "currency",\n currency: "USD",\n locale: "en-US",\n },\n…", - "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Program (Program)\n// Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you.\nimport { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm";\nimport {\n type AnyPgColumn,\n bigint,\n check,\n jsonb,\n pgTable,\n text,\n uuid,\n varchar,\n} from "drizzle-orm/pg-core";\nimport { z } from "zod";\nimport { authors } from "./Author";\nimport {\n type InstructorProfile,\n InstructorProfileInsertSchema,\n} from "./InstructorProfile";\nimport {\n type SyllabusSection,\n SyllabusSectionInsertSchema,\n} from "./SyllabusSection";\n\nexport const programs = pgTable(\n "programs",\n {\n id: uuid("id").primaryKey().defaultRandom(),\n title: varchar("title", { length: 200 }).notNull(),\n status: text("status", {\n enum: ["draft", "published", "archived"] as const,\n }),\n summary: varchar("summary", { length: 2000 }),\n priceCents: bigint("price_cents", { mode: "number" }),\n coverKey: varchar("cover_key", { length: 80 }),\n authorId: uuid("author_id")\n .notNull()\n .references((): AnyPgColumn => authors.id),\n syllabus: jsonb("syllabus").$type<SyllabusSection[]>(),\n instructorProfile: jsonb("instructor_profile").$type<InstructorProfile>(),\n },\n (table) => [\n check(\n "programs_status_chk",\n sql`status IN ('draft', 'published', 'archived')`,\n ),\n ],\n);\nexport type Program = InferSelectModel<typeof programs>;\nexport type ProgramInsert = InferInsertModel<typeof programs>;\nexport type ProgramUpdate = Partial<ProgramInsert>;\nexport type ProgramStatus = "draft" | "published" | "archived";\nexport const ProgramStatusEnum = z.enum(["draft", "published", "archived"]);\nexport const ProgramInsertSchema = z.object({\n title: z.string().min(1).max(200),\n status: z.enum(["draft", "published", "archived"]).optional(),\n summary: z.string().max(2000).optional(),\n priceCents: z.number().int().optional(),\n coverKey: z.string().max(80).optional(),\n authorId: z\n .string()\n .regex(\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,\n "Invalid uuid",\n ),\n syllabus: z.array(SyllabusSectionInsertSchema).optional(),\n instructorProfile: InstructorProfileInsertSchema.optional(),\n});\n\nexport const ProgramUpdateSchema = z.object({\n title: z.string().min(1).max(200).optional(),\n status: z.enum(["draft", "published", "archived"]).optional().nullable(),\n summary: z.string().max(2000).optional().nullable(),\n priceCents: z.number().int().optional().nullable(),\n coverKey: z.string().max(80).optional().nullable(),\n authorId: z\n .string()\n .regex(\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,\n "Invalid uuid",\n )\n .optional(),\n syllabus: z.array(SyllabusSectionInsertSchema).optional().nullable(),\n instructorProfile: InstructorProfileInsertSchema.optional().nullable(),\n});\n\n/** Typed create shape for Program: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createProgram` call site;\n * the schema still validates at runtime. */\nexport type ProgramCreate = z.input<typeof ProgramInsertSchema>;\n\n/** Typed patch shape for Program: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateProgram` call site. */\nexport type ProgramPatch = z.input<typeof ProgramUpdateSchema>;\n/**\n * Metadata constants for Program.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Program, ProgramInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Program = {\n $entity: "Program",\n $table: "programs",\n $path: "/programs",\n id: { name: "id", label: "Id", view: "text", htmlType: "text" },\n title: {\n name: "title",\n label: "Title",\n view: "text",\n htmlType: "text",\n rules: {\n required: "Title is required",\n maxLength: { value: 200, message: "Must be 200 characters or fewer" },\n },\n },\n status: {\n name: "status",\n label: "Status",\n view: "dropdown",\n options: ["draft", "published", "archived"] as const,\n },\n summary: {\n name: "summary",\n label: "Summary",\n view: "textarea",\n rules: {\n maxLength: { value: 2000, message: "Must be 2000 characters or fewer" },\n },\n },\n priceCents: {\n name: "priceCents",\n label: "Price Cents",\n view: "currency",\n currency: "USD",\n locale: "en-US",\n },\n coverKey: {\n name: "coverKey",\n label: "Cover Key",\n view: "image",\n rules: {\n maxLength: { value: 80, message: "Must be 80 characters or fewer" },\n },\n },\n authorId: {\n name: "authorId",\n label: "Author Id",\n view: "text",\n htmlType: "text",\n rules: { required: "Author Id is required" },\n },\n syllabus: {\n name: "syllabus",\n label: "Syllabus",\n view: "text",\n htmlType: "text",\n },\n instructorProfile: {\n name: "instructorProfile",\n label: "Instructor Profile",\n view: "text",\n htmlType: "text",\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSortAllowlist = {} as const satisfies SortAllowlist;\nexport type ProgramFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: ProgramFilter[];\n and?: ProgramFilter[];\n};\n", - "lineCount": 194 + "inline": "…\n priceCents: { name: "priceCents", label: "Price Cents", view: "currency", currency: "USD", locale: "en-US" },\n…", + "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Program (Program)\n// Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you.\nimport { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm";\nimport { type AnyPgColumn, bigint, check, jsonb, pgTable, text, uuid, varchar } from "drizzle-orm/pg-core";\nimport { z } from "zod";\nimport { authors } from "./Author";\nimport { type InstructorProfile, InstructorProfileInsertSchema } from "./InstructorProfile";\nimport { type SyllabusSection, SyllabusSectionInsertSchema } from "./SyllabusSection";\n\nexport const programs = pgTable("programs", {\n id: uuid("id").primaryKey().defaultRandom(),\n title: varchar("title", { length: 200 }).notNull(),\n status: text("status", { enum: ["draft", "published", "archived"] as const }),\n summary: varchar("summary", { length: 2000 }),\n priceCents: bigint("price_cents", { mode: "number" }),\n coverKey: varchar("cover_key", { length: 80 }),\n authorId: uuid("author_id").notNull().references((): AnyPgColumn => authors.id),\n syllabus: jsonb("syllabus").$type<SyllabusSection[]>(),\n instructorProfile: jsonb("instructor_profile").$type<InstructorProfile>(),\n}, (table) => [check("programs_status_chk", sql`status IN ('draft', 'published', 'archived')`)]);\nexport type Program = InferSelectModel<typeof programs>;\nexport type ProgramInsert = InferInsertModel<typeof programs>;\nexport type ProgramUpdate = Partial<ProgramInsert>;\nexport type ProgramStatus = "draft" | "published" | "archived";\nexport const ProgramStatusEnum = z.enum(["draft", "published", "archived"]);\nexport const ProgramInsertSchema = z.object({\n title: z.string().min(1).max(200),\n status: z.enum(["draft", "published", "archived"]).optional(),\n summary: z.string().max(2000).optional(),\n priceCents: z.number().int().optional(),\n coverKey: z.string().max(80).optional(),\n authorId: z.string().regex(\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,\n "Invalid uuid",\n ),\n syllabus: z.array(SyllabusSectionInsertSchema).optional(),\n instructorProfile: InstructorProfileInsertSchema.optional(),\n});\n\nexport const ProgramUpdateSchema = z.object({\n title: z.string().min(1).max(200).optional(),\n status: z.enum(["draft", "published", "archived"]).optional().nullable(),\n summary: z.string().max(2000).optional().nullable(),\n priceCents: z.number().int().optional().nullable(),\n coverKey: z.string().max(80).optional().nullable(),\n authorId: z.string().regex(\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,\n "Invalid uuid",\n ).optional(),\n syllabus: z.array(SyllabusSectionInsertSchema).optional().nullable(),\n instructorProfile: InstructorProfileInsertSchema.optional().nullable(),\n});\n\n/** Typed create shape for Program: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createProgram` call site;\n * the schema still validates at runtime. */\nexport type ProgramCreate = z.input<typeof ProgramInsertSchema>;\n\n/** Typed patch shape for Program: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateProgram` call site. */\nexport type ProgramPatch = z.input<typeof ProgramUpdateSchema>;\n/**\n * Metadata constants for Program.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Program, ProgramInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Program = {\n $entity: "Program",\n $table: "programs",\n $path: "/programs",\n id: { name: "id", label: "Id", view: "text", htmlType: "text" },\n title: {\n name: "title",\n label: "Title",\n view: "text",\n htmlType: "text",\n rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } },\n },\n status: { name: "status", label: "Status", view: "dropdown", options: ["draft", "published", "archived"] as const },\n summary: {\n name: "summary",\n label: "Summary",\n view: "textarea",\n rules: { maxLength: { value: 2000, message: "Must be 2000 characters or fewer" } },\n },\n priceCents: { name: "priceCents", label: "Price Cents", view: "currency", currency: "USD", locale: "en-US" },\n coverKey: {\n name: "coverKey",\n label: "Cover Key",\n view: "image",\n rules: { maxLength: { value: 80, message: "Must be 80 characters or fewer" } },\n },\n authorId: {\n name: "authorId",\n label: "Author Id",\n view: "text",\n htmlType: "text",\n rules: { required: "Author Id is required" },\n },\n syllabus: { name: "syllabus", label: "Syllabus", view: "text", htmlType: "text" },\n instructorProfile: { name: "instructorProfile", label: "Instructor Profile", view: "text", htmlType: "text" },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSortAllowlist = {} as const satisfies SortAllowlist;\nexport type ProgramFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: ProgramFilter[];\n and?: ProgramFilter[];\n};\n", + "lineCount": 133 }, "deep-projection": { "lang": "ts", "inline": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n…\n// View declaration — Drizzle uses this for typed SELECT queries.\n// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle\n// not to attempt DDL for this declaration.\nexport const programSummaryView = pgView("v_program_summary", {\n id: uuid("id").notNull(),\n title: varchar("title", { length: 200 }).notNull(),\n authorName: text("author_name"),\n lessonCount: bigint("lesson_count", { mode: "number" }),\n completedRevenueCents: bigint("completed_revenue_cents", { mode: "number" }),\n hasCoverArt: boolean("has_cover_art"),\n}).existing();\nexport const ProgramSummarySchema = z.object({\n id: z.string(),\n title: z.string(),\n authorName: z.string().nullable(),\n lessonCount: z.number().int().nullable(),\n completedRevenueCents: z.number().int().nullable(),\n hasCoverArt: z.boolean().nullable(),\n});\n…", - "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: ProgramSummary (ProgramSummary)\nimport {\n bigint,\n boolean,\n pgView,\n text,\n uuid,\n varchar,\n} from "drizzle-orm/pg-core";\nimport { z } from "zod";\n\n// View declaration — Drizzle uses this for typed SELECT queries.\n// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle\n// not to attempt DDL for this declaration.\nexport const programSummaryView = pgView("v_program_summary", {\n id: uuid("id").notNull(),\n title: varchar("title", { length: 200 }).notNull(),\n authorName: text("author_name"),\n lessonCount: bigint("lesson_count", { mode: "number" }),\n completedRevenueCents: bigint("completed_revenue_cents", { mode: "number" }),\n hasCoverArt: boolean("has_cover_art"),\n}).existing();\nexport const ProgramSummarySchema = z.object({\n id: z.string(),\n title: z.string(),\n authorName: z.string().nullable(),\n lessonCount: z.number().int().nullable(),\n completedRevenueCents: z.number().int().nullable(),\n hasCoverArt: z.boolean().nullable(),\n});\nexport type ProgramSummary = z.infer<typeof ProgramSummarySchema>;\nexport const ProgramSummary = {\n $entity: "ProgramSummary",\n $view: "v_program_summary",\n $path: "/program_summaries",\n id: { name: "id", label: "Id", view: "text", dbCol: "id" },\n title: { name: "title", label: "Title", view: "text", dbCol: "title" },\n authorName: {\n name: "authorName",\n label: "Author Name",\n view: "text",\n dbCol: "author_name",\n },\n lessonCount: {\n name: "lessonCount",\n label: "Lesson Count",\n view: "number",\n dbCol: "lesson_count",\n },\n completedRevenueCents: {\n name: "completedRevenueCents",\n label: "Completed Revenue Cents",\n view: "currency",\n dbCol: "completed_revenue_cents",\n currency: "USD",\n locale: "en-US",\n },\n hasCoverArt: {\n name: "hasCoverArt",\n label: "Has Cover Art",\n view: "checkbox",\n dbCol: "has_cover_art",\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSummaryFilterAllowlist =\n {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSummarySortAllowlist = {} as const satisfies SortAllowlist;\nexport type ProgramSummaryFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: ProgramSummaryFilter[];\n and?: ProgramSummaryFilter[];\n};\n", - "lineCount": 79 + "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: ProgramSummary (ProgramSummary)\nimport { bigint, boolean, pgView, text, uuid, varchar } from "drizzle-orm/pg-core";\nimport { z } from "zod";\n\n// View declaration — Drizzle uses this for typed SELECT queries.\n// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle\n// not to attempt DDL for this declaration.\nexport const programSummaryView = pgView("v_program_summary", {\n id: uuid("id").notNull(),\n title: varchar("title", { length: 200 }).notNull(),\n authorName: text("author_name"),\n lessonCount: bigint("lesson_count", { mode: "number" }),\n completedRevenueCents: bigint("completed_revenue_cents", { mode: "number" }),\n hasCoverArt: boolean("has_cover_art"),\n}).existing();\nexport const ProgramSummarySchema = z.object({\n id: z.string(),\n title: z.string(),\n authorName: z.string().nullable(),\n lessonCount: z.number().int().nullable(),\n completedRevenueCents: z.number().int().nullable(),\n hasCoverArt: z.boolean().nullable(),\n});\nexport type ProgramSummary = z.infer<typeof ProgramSummarySchema>;\nexport const ProgramSummary = {\n $entity: "ProgramSummary",\n $view: "v_program_summary",\n $path: "/program_summaries",\n id: { name: "id", label: "Id", view: "text", dbCol: "id" },\n title: { name: "title", label: "Title", view: "text", dbCol: "title" },\n authorName: { name: "authorName", label: "Author Name", view: "text", dbCol: "author_name" },\n lessonCount: { name: "lessonCount", label: "Lesson Count", view: "number", dbCol: "lesson_count" },\n completedRevenueCents: {\n name: "completedRevenueCents",\n label: "Completed Revenue Cents",\n view: "currency",\n dbCol: "completed_revenue_cents",\n currency: "USD",\n locale: "en-US",\n },\n hasCoverArt: { name: "hasCoverArt", label: "Has Cover Art", view: "checkbox", dbCol: "has_cover_art" },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSummaryFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSummarySortAllowlist = {} as const satisfies SortAllowlist;\nexport type ProgramSummaryFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: ProgramSummaryFilter[];\n and?: ProgramSummaryFilter[];\n};\n", + "lineCount": 56 } } } diff --git a/fixtures/conformance/routes-file-hono-basic/expected/Author.routes.hono.ts b/fixtures/conformance/routes-file-hono-basic/expected/Author.routes.hono.ts index 78746992c5..1dee1424a1 100644 --- a/fixtures/conformance/routes-file-hono-basic/expected/Author.routes.hono.ts +++ b/fixtures/conformance/routes-file-hono-basic/expected/Author.routes.hono.ts @@ -30,11 +30,7 @@ import type { Hono } from "hono"; * mount. Hand-write those verbs and narrow this file with * routesFileHono({ expose: ["list", "get"] }) rather than mounting them open. */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables -export function registerAuthorRoutes( - app: Hono, - deps: { db: unknown }, -): void { +export function registerAuthorRoutes(app: Hono, deps: { db: unknown }): void { mountCrudRoutes({ app, path: Author.$path, diff --git a/scripts/check-peer-ranges.ts b/scripts/check-peer-ranges.ts index cbc6800ad8..9036a81b28 100755 --- a/scripts/check-peer-ranges.ts +++ b/scripts/check-peer-ranges.ts @@ -33,8 +33,8 @@ * declaration lands it in every `@metaobjectsdev/cli` install: * * - the native Biome formatter (`@biomejs/biome`, which pulls a ~94 MB per-platform - * `@biomejs/cli-*` binary). Codegen formats through the WebAssembly build - * (`@biomejs/wasm-nodejs` + `@biomejs/js-api`, see `codegen-ts/src/format.ts`). + * `@biomejs/cli-*` binary). Generation runs no formatter; the CLI's owned-copy + * comparison uses the WebAssembly build (`@biomejs/wasm-nodejs` + `@biomejs/js-api`). * - `dprint-node` (~25 MB: all seven platform binaries in one package) and `ts-poet`, * which `require`s it on load. codegen-ts vendors the printer (`codegen-ts/src/poet.ts`) * and runs dprint as WebAssembly (`@dprint/typescript`). diff --git a/server/typescript/packages/cli/README.md b/server/typescript/packages/cli/README.md index 0487342c55..c12c46e5a0 100644 --- a/server/typescript/packages/cli/README.md +++ b/server/typescript/packages/cli/README.md @@ -28,7 +28,7 @@ bun run build:binary # → dist/meta (compiled for the build host's OS/ar ./dist/meta --help ``` -The build externalizes two optional Biome WASM backends (`@biomejs/wasm-bundler`, `@biomejs/wasm-web`) that the CLI never loads — codegen formats through the Node WebAssembly backend (`@biomejs/wasm-nodejs`), and the native Biome binary is not installed with the CLI. +The build externalizes two optional Biome WASM backends (`@biomejs/wasm-bundler`, `@biomejs/wasm-web`) that the CLI never loads — the owned-copy comparison uses the Node WebAssembly backend (`@biomejs/wasm-nodejs`), generation runs no formatter, and the native Biome binary is not installed with the CLI. ### Cross-compiling for other platforms diff --git a/server/typescript/packages/codegen-ts-angular/src/generators/angular-form.ts b/server/typescript/packages/codegen-ts-angular/src/generators/angular-form.ts index 30b46d12eb..e863523bb2 100644 --- a/server/typescript/packages/codegen-ts-angular/src/generators/angular-form.ts +++ b/server/typescript/packages/codegen-ts-angular/src/generators/angular-form.ts @@ -3,7 +3,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, entityOutputPath, servesWriteApi, isProjection, @@ -49,7 +48,7 @@ export const angularFormFile = function angularFormFile( } return { path: entityOutputPath(ctx.renderContext.outputLayout, effectivePackage(entity), `${entity.name}.form.component.ts`), - content: await formatTs(renderFormFile(entity, ctx.renderContext)), + content: renderFormFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts-angular/src/generators/angular-grid.ts b/server/typescript/packages/codegen-ts-angular/src/generators/angular-grid.ts index 30c4f2d2fa..37ffecba46 100644 --- a/server/typescript/packages/codegen-ts-angular/src/generators/angular-grid.ts +++ b/server/typescript/packages/codegen-ts-angular/src/generators/angular-grid.ts @@ -4,7 +4,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, entityOutputPath, servesClientTier, effectivePackage, @@ -52,7 +51,7 @@ export const angularGridFile = function angularGridFile( } return { path: entityOutputPath(ctx.renderContext.outputLayout, effectivePackage(entity), `${entity.name}.grid.component.ts`), - content: await formatTs(renderGridFile(entity, ctx.renderContext)), + content: renderGridFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts-angular/src/generators/angular-service.ts b/server/typescript/packages/codegen-ts-angular/src/generators/angular-service.ts index 908549ceba..85ea04ee3e 100644 --- a/server/typescript/packages/codegen-ts-angular/src/generators/angular-service.ts +++ b/server/typescript/packages/codegen-ts-angular/src/generators/angular-service.ts @@ -3,7 +3,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, entityOutputPath, servesClientTier, effectivePackage, @@ -45,7 +44,7 @@ export const angularServiceFile = function angularServiceFile( } return { path: entityOutputPath(ctx.renderContext.outputLayout, effectivePackage(entity), `${entity.name}.service.ts`), - content: await formatTs(renderServiceFile(entity, ctx.renderContext)), + content: renderServiceFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts-angular/src/generators/barrel.ts b/server/typescript/packages/codegen-ts-angular/src/generators/barrel.ts index 635ffb4bf5..6faefd6d6c 100644 --- a/server/typescript/packages/codegen-ts-angular/src/generators/barrel.ts +++ b/server/typescript/packages/codegen-ts-angular/src/generators/barrel.ts @@ -3,7 +3,6 @@ import { oncePerRun, type Generator, type GeneratorFactory, - formatTs, packageToPath, servesClientTier, servesWriteApi, @@ -65,7 +64,7 @@ export const barrel = function barrel(opts?: AngularBarrelOpts): Generator { const content = `// ${GENERATED_HEADER}-angular — ${GENERATED_EDIT_NOTE}\n${lines.join("\n")}\n`; return { path: "index.ts", - content: await formatTs(content), + content: content, }; }), }; diff --git a/server/typescript/packages/codegen-ts-tanstack/src/reference/grid-hook.ts b/server/typescript/packages/codegen-ts-tanstack/src/reference/grid-hook.ts index 47351e8cfd..2867201e78 100644 --- a/server/typescript/packages/codegen-ts-tanstack/src/reference/grid-hook.ts +++ b/server/typescript/packages/codegen-ts-tanstack/src/reference/grid-hook.ts @@ -27,7 +27,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, entityOutputPath, servesClientTier, withClientDirective, @@ -123,11 +122,11 @@ export const tanstackGridHook = function tanstackGridHook(opts?: TanstackGridHoo return [{ path: entityOutputPath(ctx.renderContext.outputLayout, pkg, entityMetaFileName(entity.name)), - content: await formatTs(renderEntityMetaFile( + content: renderEntityMetaFile( entity, ctx.renderContext.apiPrefix, namesConstArg(metaNames), - )), + ), }, { path: entityOutputPath( ctx.renderContext.outputLayout, @@ -135,7 +134,7 @@ export const tanstackGridHook = function tanstackGridHook(opts?: TanstackGridHoo `${entity.name}.grid.ts`, ), content: withClientDirective( - await formatTs(renderGridHookFile(entity, ctx.renderContext)), + renderGridHookFile(entity, ctx.renderContext), ctx.renderContext.clientDirective, ), }]; diff --git a/server/typescript/packages/codegen-ts-tanstack/src/reference/grid.ts b/server/typescript/packages/codegen-ts-tanstack/src/reference/grid.ts index 136b98a0ae..1cb3916f61 100644 --- a/server/typescript/packages/codegen-ts-tanstack/src/reference/grid.ts +++ b/server/typescript/packages/codegen-ts-tanstack/src/reference/grid.ts @@ -27,7 +27,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, entityOutputPath, servesClientTier, withClientDirective, @@ -95,7 +94,7 @@ export const tanstackGrid = function tanstackGrid(opts?: TanstackGridOpts): Gene return { path: entityOutputPath(ctx.renderContext.outputLayout, effectivePackage(entity), `${entity.name}.columns.tsx`), content: withClientDirective( - await formatTs(renderColumnsFile(entity, ctx.renderContext)), + renderColumnsFile(entity, ctx.renderContext), ctx.renderContext.clientDirective, ), }; diff --git a/server/typescript/packages/codegen-ts-tanstack/src/reference/hooks.ts b/server/typescript/packages/codegen-ts-tanstack/src/reference/hooks.ts index 33988efe85..fad80fffb7 100644 --- a/server/typescript/packages/codegen-ts-tanstack/src/reference/hooks.ts +++ b/server/typescript/packages/codegen-ts-tanstack/src/reference/hooks.ts @@ -25,7 +25,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, entityOutputPath, servesClientHooks, withClientDirective, @@ -95,18 +94,18 @@ export const tanstackQuery = function tanstackQuery(opts?: TanstackQueryOpts): G const metaFile = { path: entityOutputPath(ctx.renderContext.outputLayout, pkg, entityMetaFileName(entity.name)), - content: await formatTs(renderEntityMetaFile( + content: renderEntityMetaFile( entity, ctx.renderContext.apiPrefix, namesConstArg(metaNames), - )), + ), }; return [metaFile, { path: entityOutputPath(ctx.renderContext.outputLayout, pkg, `${entity.name}.hooks.ts`), - // Outside formatTs deliberately: the directive must stay the module's first - // token, and a formatter is entitled to move a leading string expression. + // The directive must stay the module's first + // token; an adopter's formatter keeps a leading string expression where it is. content: withClientDirective( - await formatTs(renderHooksFile(entity, ctx.renderContext)), + renderHooksFile(entity, ctx.renderContext), ctx.renderContext.clientDirective, ), }]; diff --git a/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid-hook.ts b/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid-hook.ts index a83ce11e9f..887f504942 100644 --- a/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid-hook.ts +++ b/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid-hook.ts @@ -1,5 +1,5 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; -import { perEntity, type Generator, type GeneratorFactory, formatTs, entityOutputPath, entityMetaFileName, renderEntityMetaFile, servesClientTier, isTphSubtype, +import { perEntity, type Generator, type GeneratorFactory, entityOutputPath, entityMetaFileName, renderEntityMetaFile, servesClientTier, isTphSubtype, withClientDirective, namesRef, namesConstArg, effectivePackage, } from "@metaobjectsdev/codegen-ts"; @@ -86,11 +86,11 @@ export const tanstackGridHook = function tanstackGridHook(opts?: TanstackGridHoo return [{ path: entityOutputPath(ctx.renderContext.outputLayout, pkg, entityMetaFileName(entity.name)), - content: await formatTs(renderEntityMetaFile( + content: renderEntityMetaFile( entity, ctx.renderContext.apiPrefix, namesConstArg(metaNames), - )), + ), }, { path: entityOutputPath( ctx.renderContext.outputLayout, @@ -98,7 +98,7 @@ export const tanstackGridHook = function tanstackGridHook(opts?: TanstackGridHoo `${entity.name}.grid.ts`, ), content: withClientDirective( - await formatTs(renderGridHookFile(entity, ctx.renderContext)), + renderGridHookFile(entity, ctx.renderContext), ctx.renderContext.clientDirective, ), }]; diff --git a/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid.ts b/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid.ts index 95cd1ab141..7383286e8b 100644 --- a/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid.ts +++ b/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid.ts @@ -1,5 +1,5 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; -import { perEntity, type Generator, type GeneratorFactory, formatTs, entityOutputPath, servesClientTier, isTphSubtype, +import { perEntity, type Generator, type GeneratorFactory, entityOutputPath, servesClientTier, isTphSubtype, withClientDirective, effectivePackage, } from "@metaobjectsdev/codegen-ts"; @@ -64,7 +64,7 @@ export const tanstackGrid = function tanstackGrid(opts?: TanstackGridOpts): Gene return { path: entityOutputPath(ctx.renderContext.outputLayout, effectivePackage(entity), `${entity.name}.columns.tsx`), content: withClientDirective( - await formatTs(renderColumnsFile(entity, ctx.renderContext)), + renderColumnsFile(entity, ctx.renderContext), ctx.renderContext.clientDirective, ), }; diff --git a/server/typescript/packages/codegen-ts-tanstack/src/tanstack-query.ts b/server/typescript/packages/codegen-ts-tanstack/src/tanstack-query.ts index 982291e69a..1421a48e94 100644 --- a/server/typescript/packages/codegen-ts-tanstack/src/tanstack-query.ts +++ b/server/typescript/packages/codegen-ts-tanstack/src/tanstack-query.ts @@ -1,5 +1,5 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; -import { perEntity, type Generator, type GeneratorFactory, formatTs, entityOutputPath, entityMetaFileName, renderEntityMetaFile, servesClientHooks, isTphSubtype, +import { perEntity, type Generator, type GeneratorFactory, entityOutputPath, entityMetaFileName, renderEntityMetaFile, servesClientHooks, isTphSubtype, withClientDirective, namesRef, namesConstArg, effectivePackage, } from "@metaobjectsdev/codegen-ts"; @@ -60,18 +60,18 @@ export const tanstackQuery = function tanstackQuery(opts?: TanstackQueryOpts): G const metaFile = { path: entityOutputPath(ctx.renderContext.outputLayout, pkg, entityMetaFileName(entity.name)), - content: await formatTs(renderEntityMetaFile( + content: renderEntityMetaFile( entity, ctx.renderContext.apiPrefix, namesConstArg(metaNames), - )), + ), }; return [metaFile, { path: entityOutputPath(ctx.renderContext.outputLayout, pkg, `${entity.name}.hooks.ts`), - // Outside formatTs deliberately: the directive must stay the module's first - // token, and a formatter is entitled to move a leading string expression. + // The directive must stay the module's first + // token; an adopter's formatter keeps a leading string expression where it is. content: withClientDirective( - await formatTs(renderHooksFile(entity, ctx.renderContext)), + renderHooksFile(entity, ctx.renderContext), ctx.renderContext.clientDirective, ), }]; diff --git a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/grid-filter/Subscriber.grid.ts b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/grid-filter/Subscriber.grid.ts index d8b5615b04..c84bc29fed 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/grid-filter/Subscriber.grid.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/grid-filter/Subscriber.grid.ts @@ -6,19 +6,12 @@ import { subscriberActiveFilter } from "./Subscriber.columns"; import { buildFilterQs } from "@metaobjectsdev/runtime-web"; import { useEntityPathFetcher } from "@metaobjectsdev/tanstack"; import { useQuery } from "@tanstack/react-query"; -import type { - ColumnFiltersState, - PaginationState, - SortingState, -} from "@tanstack/react-table"; +import type { ColumnFiltersState, PaginationState, SortingState } from "@tanstack/react-table"; import { useMemo, useState } from "react"; export function useSubscriberActiveGrid() { const [sorting, setSorting] = useState([]); - const [pagination, setPagination] = useState({ - pageIndex: 0, - pageSize: 25, - }); + const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 25 }); const [columnFilters, setColumnFilters] = useState([]); const [search, setSearch] = useState(""); @@ -30,9 +23,7 @@ export function useSubscriberActiveGrid() { filterObj[f.id] = f.value as unknown; } const sortEntry = sorting[0]; - const sort = sortEntry - ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` - : undefined; + const sort = sortEntry ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` : undefined; return buildFilterQs({ ...filterObj, ...(sort !== undefined ? { sort } : {}), @@ -45,10 +36,7 @@ export function useSubscriberActiveGrid() { const query = useQuery<{ rows: SubscriberRow[]; total: number }>({ queryKey: ["subscriber", "grid", "active", qs], - queryFn: () => - fetcher<{ rows: SubscriberRow[]; total: number }>( - `${Subscriber.$path}?${qs}`, - ), + queryFn: () => fetcher<{ rows: SubscriberRow[]; total: number }>(`${Subscriber.$path}?${qs}`), }); return { diff --git a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/multi-grid/Program.grid.ts b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/multi-grid/Program.grid.ts index ead5c11f9f..1abb35cf34 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/multi-grid/Program.grid.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/multi-grid/Program.grid.ts @@ -5,19 +5,12 @@ import { Program } from "./Program.meta"; import { buildFilterQs } from "@metaobjectsdev/runtime-web"; import { useEntityPathFetcher } from "@metaobjectsdev/tanstack"; import { useQuery } from "@tanstack/react-query"; -import type { - ColumnFiltersState, - PaginationState, - SortingState, -} from "@tanstack/react-table"; +import type { ColumnFiltersState, PaginationState, SortingState } from "@tanstack/react-table"; import { useMemo, useState } from "react"; export function useProgramDefaultGrid() { const [sorting, setSorting] = useState([]); - const [pagination, setPagination] = useState({ - pageIndex: 0, - pageSize: 25, - }); + const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 25 }); const [columnFilters, setColumnFilters] = useState([]); const [search, setSearch] = useState(""); @@ -29,9 +22,7 @@ export function useProgramDefaultGrid() { filterObj[f.id] = f.value as unknown; } const sortEntry = sorting[0]; - const sort = sortEntry - ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` - : undefined; + const sort = sortEntry ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` : undefined; return buildFilterQs({ ...filterObj, ...(sort !== undefined ? { sort } : {}), @@ -44,8 +35,7 @@ export function useProgramDefaultGrid() { const query = useQuery<{ rows: ProgramRow[]; total: number }>({ queryKey: ["program", "grid", "default", qs], - queryFn: () => - fetcher<{ rows: ProgramRow[]; total: number }>(`${Program.$path}?${qs}`), + queryFn: () => fetcher<{ rows: ProgramRow[]; total: number }>(`${Program.$path}?${qs}`), }); return { @@ -63,10 +53,7 @@ export function useProgramDefaultGrid() { } export function useProgramCompactGrid() { const [sorting, setSorting] = useState([]); - const [pagination, setPagination] = useState({ - pageIndex: 0, - pageSize: 50, - }); + const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 50 }); const [columnFilters, setColumnFilters] = useState([]); const [search, setSearch] = useState(""); @@ -78,9 +65,7 @@ export function useProgramCompactGrid() { filterObj[f.id] = f.value as unknown; } const sortEntry = sorting[0]; - const sort = sortEntry - ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` - : undefined; + const sort = sortEntry ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` : undefined; return buildFilterQs({ ...filterObj, ...(sort !== undefined ? { sort } : {}), @@ -93,8 +78,7 @@ export function useProgramCompactGrid() { const query = useQuery<{ rows: ProgramRow[]; total: number }>({ queryKey: ["program", "grid", "compact", qs], - queryFn: () => - fetcher<{ rows: ProgramRow[]; total: number }>(`${Program.$path}?${qs}`), + queryFn: () => fetcher<{ rows: ProgramRow[]; total: number }>(`${Program.$path}?${qs}`), }); return { diff --git a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/single-entity/Subscriber.grid.ts b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/single-entity/Subscriber.grid.ts index a8497c2fd2..2c3b31f50f 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/single-entity/Subscriber.grid.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/single-entity/Subscriber.grid.ts @@ -5,21 +5,12 @@ import { Subscriber } from "./Subscriber.meta"; import { buildFilterQs } from "@metaobjectsdev/runtime-web"; import { useEntityPathFetcher } from "@metaobjectsdev/tanstack"; import { useQuery } from "@tanstack/react-query"; -import type { - ColumnFiltersState, - PaginationState, - SortingState, -} from "@tanstack/react-table"; +import type { ColumnFiltersState, PaginationState, SortingState } from "@tanstack/react-table"; import { useMemo, useState } from "react"; export function useSubscriberDefaultGrid() { - const [sorting, setSorting] = useState([ - { id: "createdAt", desc: true }, - ]); - const [pagination, setPagination] = useState({ - pageIndex: 0, - pageSize: 25, - }); + const [sorting, setSorting] = useState([{ id: "createdAt", desc: true }]); + const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 25 }); const [columnFilters, setColumnFilters] = useState([]); const [search, setSearch] = useState(""); @@ -31,9 +22,7 @@ export function useSubscriberDefaultGrid() { filterObj[f.id] = f.value as unknown; } const sortEntry = sorting[0]; - const sort = sortEntry - ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` - : undefined; + const sort = sortEntry ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` : undefined; return buildFilterQs({ ...filterObj, ...(sort !== undefined ? { sort } : {}), @@ -46,10 +35,7 @@ export function useSubscriberDefaultGrid() { const query = useQuery<{ rows: SubscriberRow[]; total: number }>({ queryKey: ["subscriber", "grid", "default", qs], - queryFn: () => - fetcher<{ rows: SubscriberRow[]; total: number }>( - `${Subscriber.$path}?${qs}`, - ), + queryFn: () => fetcher<{ rows: SubscriberRow[]; total: number }>(`${Subscriber.$path}?${qs}`), }); return { diff --git a/server/typescript/packages/codegen-ts/package.json b/server/typescript/packages/codegen-ts/package.json index 723edd2e6e..8b0b07f397 100644 --- a/server/typescript/packages/codegen-ts/package.json +++ b/server/typescript/packages/codegen-ts/package.json @@ -143,8 +143,6 @@ "@metaobjectsdev/docs-site": "workspace:*", "@metaobjectsdev/render": "workspace:*", "@metaobjectsdev/migrate-ts": "workspace:*", - "@biomejs/js-api": "^0.7.0", - "@biomejs/wasm-nodejs": "^1.9.4", "@toon-format/toon": "^2.3.0", "@dprint/formatter": "^0.6.0", "@dprint/typescript": "0.87.1" diff --git a/server/typescript/packages/codegen-ts/src/format.ts b/server/typescript/packages/codegen-ts/src/format.ts index 8e68172770..9e46d28a3f 100644 --- a/server/typescript/packages/codegen-ts/src/format.ts +++ b/server/typescript/packages/codegen-ts/src/format.ts @@ -1,50 +1,17 @@ -// Biome formatter integration. Used by generate() to format rendered TS before write. -// Per design §11: format errors are warnings, not throws. - -import { Biome, Distribution } from "@biomejs/js-api"; - -// Cache the Promise (not the resolved instance) so concurrent first calls -// share the same in-flight Biome.create() rather than racing to spawn two. -let _biomePromise: Promise | undefined; - -function getBiome(): Promise { - if (!_biomePromise) { - _biomePromise = Biome.create({ distribution: Distribution.NODE }).then((biome) => { - biome.applyConfiguration({ - formatter: { enabled: true, indentStyle: "space", indentWidth: 2 }, - javascript: { formatter: { quoteStyle: "double", semicolons: "always" } }, - }); - return biome; - }); - } - return _biomePromise; -} +// `formatTs` is a no-op kept only so an owned 1.2 generator copy still loads. +// +// Until 1.3.0 every reference generator piped its rendered text through Biome before it +// was written. Generation no longer runs a formatter: each generator writes the layout it +// means (the templates and `TsWriter`), and the adopter's own formatter owns the rest. A +// generator copied out with `meta eject` in 1.2 imports this name from the package entry, +// so the export stays and returns its input unchanged. A copy that wants a formatter calls +// the one it already depends on. /** - * Summarize Biome diagnostics into a single human-readable line, without - * dumping the raw diagnostic objects (which produce "[Object ...]" / - * "source: null" noise when stringified by console). + * Returns `content` unchanged. + * + * @deprecated Generation runs no formatter. A generator that wants one calls its own. */ -function summarizeDiagnostics(diagnostics: ReadonlyArray): string { - const count = diagnostics.length; - const first = diagnostics[0] as { description?: string; message?: string } | undefined; - const firstMsg = first?.description ?? first?.message ?? "(no description)"; - return count === 1 - ? `1 diagnostic: ${firstMsg}` - : `${count} diagnostics; first: ${firstMsg}`; -} - export async function formatTs(content: string): Promise { - try { - const biome = await getBiome(); - const result = biome.formatContent(content, { filePath: "in-memory.ts" }); - if (result.diagnostics.length > 0) { - console.warn(`[codegen-ts] Biome formatter: ${summarizeDiagnostics(result.diagnostics)}`); - return content; - } - return result.content; - } catch (err) { - console.warn(`[codegen-ts] Biome formatter error: ${(err as Error).message}`); - return content; - } + return content; } diff --git a/server/typescript/packages/codegen-ts/src/generator.ts b/server/typescript/packages/codegen-ts/src/generator.ts index 3c6debf9f2..b6a2d2ea7c 100644 --- a/server/typescript/packages/codegen-ts/src/generator.ts +++ b/server/typescript/packages/codegen-ts/src/generator.ts @@ -14,7 +14,7 @@ export interface EmittedFile { path: string; /** The file's final contents, in any format — TypeScript, JSON, YAML, SQL, Markdown. * The runner writes it as given: it neither formats it nor adds a header, so a - * generator that wants either does it itself (`formatTs`, `GENERATED_HEADER`). */ + * generator that wants a header does it itself (`GENERATED_HEADER`). */ content: string; /** Set by the runner from generator.name — generators should not set this. */ generatedBy?: string; diff --git a/server/typescript/packages/codegen-ts/src/generators/barrel.ts b/server/typescript/packages/codegen-ts/src/generators/barrel.ts index 1638d0572c..4f324627ac 100644 --- a/server/typescript/packages/codegen-ts/src/generators/barrel.ts +++ b/server/typescript/packages/codegen-ts/src/generators/barrel.ts @@ -1,6 +1,5 @@ import { oncePerRun, type Generator, type GeneratorFactory } from "../generator.js"; import { renderBarrel } from "../templates/barrel.js"; -import { formatTs } from "../format.js"; import { effectivePackage } from "../docs-paths.js"; import { claimBarrelNames } from "../naming/name-claims.js"; @@ -16,14 +15,12 @@ export const barrel = function barrel(opts?: BarrelOpts): Generator { for (const e of entities) claimBarrelNames(ctx, e); return { path: "index.ts", - content: await formatTs( - renderBarrel( + content: renderBarrel( entities.map((e) => ({ name: e.name, package: effectivePackage(e) })), ctx.renderContext!.extStyle, ctx.renderContext!.selfTarget, ctx.renderContext!.entityModuleTarget, ), - ), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/generators/callable-file.ts b/server/typescript/packages/codegen-ts/src/generators/callable-file.ts index f4500bd408..f33d1799e8 100644 --- a/server/typescript/packages/codegen-ts/src/generators/callable-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/callable-file.ts @@ -9,7 +9,6 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; import { perEntity, type Generator, type GeneratorFactory } from "../generator.js"; import { renderCallableFile, isCallableEntity } from "../templates/callable-file.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; @@ -34,7 +33,7 @@ export const callableFile = function callableFile(opts?: CallableFileOpts): Gene effectivePackage(entity), `${entity.name}.callable.ts`, ), - content: await formatTs(renderCallableFile(entity, ctx.renderContext)), + content: renderCallableFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/generators/entity-file.ts b/server/typescript/packages/codegen-ts/src/generators/entity-file.ts index d6eb4e4eb7..1d4c3f8534 100644 --- a/server/typescript/packages/codegen-ts/src/generators/entity-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/entity-file.ts @@ -2,7 +2,6 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; import { perEntity, type EmittedFile, type GenContext, type Generator, type GeneratorFactory } from "../generator.js"; import { renderEntityFile } from "../templates/entity-file.js"; import { renderSharedEnumsFile, SHARED_ENUMS_BASENAME } from "../templates/enums-file.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { isAbstract } from "../instance-artifacts.js"; import { effectivePackage } from "../docs-paths.js"; @@ -45,7 +44,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), - content: await formatTs(renderEntityFile(entity, ctx.renderContext, { allowlists })), + content: renderEntityFile(entity, ctx.renderContext, { allowlists }), }; }); @@ -67,7 +66,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator if (sharedEnums !== null) { files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, - content: await formatTs(sharedEnums), + content: sharedEnums, }); } return files; diff --git a/server/typescript/packages/codegen-ts/src/generators/queries-file.ts b/server/typescript/packages/codegen-ts/src/generators/queries-file.ts index 94debcf794..a9fc2e300c 100644 --- a/server/typescript/packages/codegen-ts/src/generators/queries-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/queries-file.ts @@ -3,7 +3,6 @@ import { perEntity, type Generator, type GeneratorFactory } from "../generator.j import { renderQueriesFile } from "../templates/queries-file.js"; import { isTphSubtype } from "../tph.js"; import { servesReadApi } from "../api-surface.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; import { claimModuleNames } from "../naming/name-claims.js"; @@ -52,7 +51,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), - content: await formatTs(renderQueriesFile(entity, ctx.renderContext)), + content: renderQueriesFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts b/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts index 347504b4cd..1065766bce 100644 --- a/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts @@ -2,7 +2,6 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; import type { Generator, GenContext, EmittedFile } from "../generator.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; -import { formatTs } from "../format.js"; import { isReport } from "../source-detect.js"; import { DEFAULT_EXPORT_MAX_ROWS, DEFAULT_XML_NULLS, EXPORT_WRITERS_BASENAME, @@ -58,14 +57,14 @@ export function reportExport(opts?: ReportExportOpts): Generator { const reports = ctx.entities.filter(ctx.matches).filter(isReport); if (reports.length === 0) return []; const out: EmittedFile[] = [ - { path: `${EXPORT_WRITERS_BASENAME}.ts`, content: await formatTs(renderExportWriters(emit)) }, + { path: `${EXPORT_WRITERS_BASENAME}.ts`, content: renderExportWriters(emit) }, ]; // One module per report `meta gen ` named; the writers above serve them all. for (const report of reports.filter((r) => ctx.selected?.(r) ?? true)) { const pkg = effectivePackage(report); out.push({ path: entityOutputPath(layout, pkg, `${report.name}.export.ts`), - content: await formatTs(renderReportExportModule(report, { selfTarget, pkg, extStyle }, emit)), + content: renderReportExportModule(report, { selfTarget, pkg, extStyle }, emit), }); } return out; diff --git a/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts b/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts index 2c5956e61c..eaf551807d 100644 --- a/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts +++ b/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts @@ -3,7 +3,6 @@ import { perEntity, type Generator, type GeneratorFactory } from "../generator.j import { renderRoutesFileHono } from "../templates/routes-file-hono.js"; import { servesReadApi } from "../api-surface.js"; import { renderRoutesIndex, routesIndexFileName } from "../templates/routes-index.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { isTphSubtype } from "../tph.js"; import { resolveExpose, type ExposeOption } from "../routes-expose.js"; @@ -105,7 +104,7 @@ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts) if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("hono"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "hono")), + content: renderRoutesIndex(matched, ctx.renderContext, "hono"), }]; }, }; @@ -120,7 +119,7 @@ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts) effectivePackage(entity), `${entity.name}.routes.hono.ts`, ), - content: await formatTs(renderRoutesFileHono(entity, ctx.renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutesFileHono(entity, ctx.renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); if (opts?.target) { diff --git a/server/typescript/packages/codegen-ts/src/generators/routes-file.ts b/server/typescript/packages/codegen-ts/src/generators/routes-file.ts index f0a871f20a..cef0c6d9f5 100644 --- a/server/typescript/packages/codegen-ts/src/generators/routes-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/routes-file.ts @@ -4,7 +4,6 @@ import { renderRoutesFile } from "../templates/routes-file.js"; import { isTphSubtype } from "../tph.js"; import { servesReadApi } from "../api-surface.js"; import { renderRoutesIndex, routesIndexFileName } from "../templates/routes-index.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { resolveExpose, type ExposeOption } from "../routes-expose.js"; import { effectivePackage } from "../docs-paths.js"; @@ -63,7 +62,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator claimRouteSegment(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), - content: await formatTs(renderRoutesFile(entity, ctx.renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutesFile(entity, ctx.renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); const generator: Generator = { @@ -83,7 +82,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("fastify"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "fastify")), + content: renderRoutesIndex(matched, ctx.renderContext, "fastify"), }]; }, }; diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts index e15436e26b..4cb6741bb4 100644 --- a/server/typescript/packages/codegen-ts/src/index.ts +++ b/server/typescript/packages/codegen-ts/src/index.ts @@ -112,6 +112,7 @@ export { CodegenError } from "./errors.js"; export { GENERATED_HEADER, GENERATED_EDIT_NOTE, NAMES_FILE_SUFFIX, DEFAULT_OUT_DIR, RETIRED_CODEGEN_ATTRS, sidecarLine, type RetiredCodegenAttr } from "./constants.js"; export { warnRetiredCodegenAttrs } from "./retired-codegen-attrs.js"; +// Kept so a generator copied out in 1.2 still loads; generation runs no formatter (format.ts). export { formatTs } from "./format.js"; export { pluralize, columnNameFromField, tableNameFromEntity, viewNameFromProjection, routesHandlerName, hookListNameSegment } from "./naming.js"; diff --git a/server/typescript/packages/codegen-ts/src/reference/barrel.ts b/server/typescript/packages/codegen-ts/src/reference/barrel.ts index 2c82677ac3..001cf7953d 100644 --- a/server/typescript/packages/codegen-ts/src/reference/barrel.ts +++ b/server/typescript/packages/codegen-ts/src/reference/barrel.ts @@ -24,7 +24,6 @@ import { type ExtStyle, type ResolvedTarget, barrelModuleSpecifier, - formatTs, GENERATED_HEADER, GENERATED_EDIT_NOTE, effectivePackage, @@ -66,14 +65,12 @@ export const barrel = function barrel(opts?: BarrelOpts): Generator { for (const e of entities) claimBarrelNames(ctx, e); return { path: "index.ts", - content: await formatTs( - renderBarrel( + content: renderBarrel( entities.map((e) => ({ name: e.name, package: effectivePackage(e) })), rc.extStyle, rc.selfTarget, rc.entityModuleTarget, ), - ), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/reference/callable.ts b/server/typescript/packages/codegen-ts/src/reference/callable.ts index 2faeaf9c8a..4cc0b17a8d 100644 --- a/server/typescript/packages/codegen-ts/src/reference/callable.ts +++ b/server/typescript/packages/codegen-ts/src/reference/callable.ts @@ -31,7 +31,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -61,7 +60,7 @@ export const callableFile = function callableFile(opts?: CallableFileOpts): Gene effectivePackage(entity), `${entity.name}.callable.ts`, ), - content: await formatTs(renderCallableFile(entity, ctx.renderContext)), + content: renderCallableFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/reference/entity.ts b/server/typescript/packages/codegen-ts/src/reference/entity.ts index 926da1c687..4931111a28 100644 --- a/server/typescript/packages/codegen-ts/src/reference/entity.ts +++ b/server/typescript/packages/codegen-ts/src/reference/entity.ts @@ -54,7 +54,6 @@ import { isWriteThrough, isAbstract, hasWritableRdbSource, - formatTs, ownedRuntimeImport, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, @@ -188,7 +187,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), - content: await formatTs(renderEntity(entity, renderContext, { allowlists })), + content: renderEntity(entity, renderContext, { allowlists }), }; }); @@ -209,7 +208,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator ctx.select !== undefined ? { select: ctx.select } : undefined, ); if (sharedEnums !== null) { - files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: await formatTs(sharedEnums) }); + files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: sharedEnums }); } return files; }, diff --git a/server/typescript/packages/codegen-ts/src/reference/queries.ts b/server/typescript/packages/codegen-ts/src/reference/queries.ts index 8d03e08142..44617b4c61 100644 --- a/server/typescript/packages/codegen-ts/src/reference/queries.ts +++ b/server/typescript/packages/codegen-ts/src/reference/queries.ts @@ -43,7 +43,6 @@ import { isProjection, isWriteThrough, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, GENERATED_HEADER, @@ -173,7 +172,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), - content: await formatTs(renderQueries(entity, ctx.renderContext)), + content: renderQueries(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/reference/report-export.ts b/server/typescript/packages/codegen-ts/src/reference/report-export.ts index 77ec25579c..0b6a881dca 100644 --- a/server/typescript/packages/codegen-ts/src/reference/report-export.ts +++ b/server/typescript/packages/codegen-ts/src/reference/report-export.ts @@ -29,7 +29,6 @@ import { effectivePackage, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, - formatTs, isCredentialField, isReport, relativeModuleSpecifier, @@ -247,14 +246,14 @@ export function reportExport(opts?: ReportExportOpts): Generator { const reports = ctx.entities.filter(ctx.matches).filter(isReport); if (reports.length === 0) return []; const out: EmittedFile[] = [ - { path: `${EXPORT_WRITERS_BASENAME}.ts`, content: await formatTs(renderExportWriters(emit)) }, + { path: `${EXPORT_WRITERS_BASENAME}.ts`, content: renderExportWriters(emit) }, ]; // One module per report `meta gen ` named; the writers above serve them all. for (const report of reports.filter((r) => ctx.selected?.(r) ?? true)) { const pkg = effectivePackage(report); out.push({ path: entityOutputPath(layout, pkg, `${report.name}.export.ts`), - content: await formatTs(renderReportExportModule(report, { selfTarget, pkg, extStyle }, emit)), + content: renderReportExportModule(report, { selfTarget, pkg, extStyle }, emit), }); } return out; diff --git a/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts b/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts index 10910a4297..e61313e354 100644 --- a/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts +++ b/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts @@ -63,7 +63,6 @@ import { writeDeniedColumnsLine, knownFieldsLine, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -183,7 +182,6 @@ import { * ${runtimeSpec}. ${authSeamJsDoc({ framework: "hono", handlerName, mountPathExpr: authPathExpr, narrowable: false })} */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables export function ${handlerName}(app: ${HonoSym}, deps: { db: unknown }): void { ${mountReadOnlyCrudRoutesSym}({ app, @@ -238,7 +236,6 @@ import { * (auth, side effects, etc.). ${authSeamJsDoc({ framework: "hono", handlerName, mountPathExpr: authPathExpr, narrowable: true })} */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables export function ${handlerName}(app: ${HonoSym}, deps: { db: unknown }): void { ${mountCrudRoutesSym}({ app, @@ -338,7 +335,7 @@ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts) if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("hono"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "hono")), + content: renderRoutesIndex(matched, ctx.renderContext, "hono"), }]; }, }; @@ -358,7 +355,7 @@ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts) effectivePackage(entity), `${entity.name}.routes.hono.ts`, ), - content: await formatTs(renderRoutesHono(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutesHono(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); if (opts?.target) { diff --git a/server/typescript/packages/codegen-ts/src/reference/routes.ts b/server/typescript/packages/codegen-ts/src/reference/routes.ts index 16837743da..3117986622 100644 --- a/server/typescript/packages/codegen-ts/src/reference/routes.ts +++ b/server/typescript/packages/codegen-ts/src/reference/routes.ts @@ -73,7 +73,6 @@ import { writeDeniedColumnsLine, knownFieldsLine, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -770,7 +769,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), - content: await formatTs(renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); const generator: Generator = { @@ -796,7 +795,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("fastify"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "fastify")), + content: renderRoutesIndex(matched, ctx.renderContext, "fastify"), }]; }, }; diff --git a/server/typescript/packages/codegen-ts/src/templates/routes-file-hono.ts b/server/typescript/packages/codegen-ts/src/templates/routes-file-hono.ts index 6c00f30691..8231b343b2 100644 --- a/server/typescript/packages/codegen-ts/src/templates/routes-file-hono.ts +++ b/server/typescript/packages/codegen-ts/src/templates/routes-file-hono.ts @@ -135,7 +135,6 @@ import { * ${runtimeSpec}. ${authSeamJsDoc({ framework: "hono", handlerName, mountPathExpr: authPathExpr, narrowable: false })} */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables export function ${handlerName}(app: ${HonoSym}, deps: { db: unknown }): void { ${mountReadOnlyCrudRoutesSym}({ app, @@ -190,7 +189,6 @@ import { * (auth, side effects, etc.). ${authSeamJsDoc({ framework: "hono", handlerName, mountPathExpr: authPathExpr, narrowable: true })} */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables export function ${handlerName}(app: ${HonoSym}, deps: { db: unknown }): void { ${mountCrudRoutesSym}({ app, diff --git a/server/typescript/packages/codegen-ts/src/templates/routes-index.ts b/server/typescript/packages/codegen-ts/src/templates/routes-index.ts index 40918d6c70..a36408aa23 100644 --- a/server/typescript/packages/codegen-ts/src/templates/routes-index.ts +++ b/server/typescript/packages/codegen-ts/src/templates/routes-index.ts @@ -55,7 +55,6 @@ export function renderRoutesIndex( " * on the mount paths before calling this. An entity that needs a row-ownership rule", " * should not be registered open: narrow its routes with `expose` or hand-write them.", " */", - "// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables", "export function registerAllRoutes(app: Hono, deps: { db: unknown }): void {", ...sorted.map((e) => ` ${handler(e)}(app, deps);`), "}", diff --git a/server/typescript/packages/codegen-ts/src/templates/view-decl.ts b/server/typescript/packages/codegen-ts/src/templates/view-decl.ts index 01f3ef64e9..e039ce477f 100644 --- a/server/typescript/packages/codegen-ts/src/templates/view-decl.ts +++ b/server/typescript/packages/codegen-ts/src/templates/view-decl.ts @@ -111,7 +111,7 @@ function viewColumnLine( : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 - ? `, ${JSON.stringify(spec.fnOptions)}` + ? `, ${optionsLiteral(spec.fnOptions)}` : ""; // #204 — of the table modifiers, only `.array()` (postgres native array element // typing) and `.notNull()` (shapes the SELECT type) carry to an existing view; @@ -252,3 +252,12 @@ export function renderViewReadZodObject(fields: readonly MetaField[], opts: View ${joinCode(lines, { on: ",\n" })} })`; } + +/** A column's options as a JS object literal: `{ length: 200 }`, not JSON's `{ "length": 200 }`. */ +function optionsLiteral(options: Record): string { + const entries = Object.entries(options).map(([key, value]) => { + const name = /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key); + return `${name}: ${JSON.stringify(value)}`; + }); + return `{ ${entries.join(", ")} }`; +} diff --git a/server/typescript/packages/codegen-ts/test/format.test.ts b/server/typescript/packages/codegen-ts/test/format.test.ts index 62b643b6fd..5155e62e3c 100644 --- a/server/typescript/packages/codegen-ts/test/format.test.ts +++ b/server/typescript/packages/codegen-ts/test/format.test.ts @@ -1,19 +1,28 @@ import { describe, test, expect } from "bun:test"; import { formatTs } from "../src/format.js"; +import { formatTs as formatTsFromEntry } from "../src/index.js"; +// Generation runs no formatter. `formatTs` stays exported only so a generator copied out +// with `meta eject` in 1.2 (which imports it from the package entry) still loads. describe("formatTs", () => { - test("formats unformatted TS into idiomatic Biome style", async () => { + test("is exported from the package entry, for owned 1.2 generator copies", () => { + expect(formatTsFromEntry).toBe(formatTs); + }); + + test("returns its input unchanged", async () => { const ugly = "import {x} from'y';export const a={b:1,c:2}"; - const formatted = await formatTs(ugly); - expect(formatted).not.toBe(ugly); - expect(formatted).toContain("import"); - expect(formatted.length).toBeGreaterThan(ugly.length); + expect(await formatTs(ugly)).toBe(ugly); }); - test("returns input unchanged on Biome error (with warning logged)", async () => { - const broken = "import { from 'x';"; // syntax error - const formatted = await formatTs(broken); - // Per design §11: format error → log warning, return unformatted - expect(typeof formatted).toBe("string"); + test("returns invalid TypeScript unchanged, with nothing logged", async () => { + const warnings: unknown[] = []; + const warn = console.warn; + console.warn = (...args: unknown[]) => warnings.push(args); + try { + expect(await formatTs("import { from 'x';")).toBe("import { from 'x';"); + } finally { + console.warn = warn; + } + expect(warnings).toEqual([]); }); }); diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.queries.ts index c28721fad7..0041f533ab 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.queries.ts @@ -5,27 +5,14 @@ import { eq, inArray } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; -import { - type Tag, - TagInsertSchema, - type TagPatch, - tags, - TagUpdateSchema, -} from "./Tag"; +import { type Tag, TagInsertSchema, type TagPatch, tags, TagUpdateSchema } from "./Tag"; export async function findTagById(db: Db, id: number): Promise { const [tag] = await db.select().from(tags).where(eq(tags.id, id)).limit(1); return tag ?? null; } -export async function listTags( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listTags(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(tags).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -35,30 +22,19 @@ export async function listTags( } return q; } -export async function createTag( - db: Db, - data: z.input, -): Promise { +export async function createTag(db: Db, data: z.input): Promise { const validated = TagInsertSchema.parse(data); const [tag] = await db.insert(tags).values(validated).returning(); return tag!; } -export async function updateTag( - db: Db, - id: number, - patch: TagPatch, -): Promise { +export async function updateTag(db: Db, id: number, patch: TagPatch): Promise { const validated = TagUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findTagById(db, id); } - const [tag] = await db - .update(tags) - .set(validated) - .where(eq(tags.id, id)) - .returning(); + const [tag] = await db.update(tags).set(validated).where(eq(tags.id, id)).returning(); return tag ?? null; } export async function deleteTagById(db: Db, id: number): Promise { @@ -67,17 +43,11 @@ export async function deleteTagById(db: Db, id: number): Promise { const deleted = await db.delete(tags).where(eq(tags.id, id)).returning(); return deleted.length > 0; } -export async function findTagsByCustomer( - db: Db, - customerId: number, -): Promise { +export async function findTagsByCustomer(db: Db, customerId: number): Promise { return db.select().from(tags).where(eq(tags.customerId, customerId)); } -export async function findTagsByCustomerIn( - db: Db, - customerIds: number[], -): Promise { +export async function findTagsByCustomerIn(db: Db, customerIds: number[]): Promise { if (customerIds.length === 0) { return []; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.routes.ts index c427da5bcc..9659dd6b2a 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.routes.ts @@ -2,14 +2,7 @@ // Source metadata: Tag (Tag) // Extend in your own module (e.g. Tag.extra.ts) — nothing imports it for you. import { db } from "../db"; -import { - Tag, - TagFilterAllowlist, - TagInsertSchema, - tags, - TagSortAllowlist, - TagUpdateSchema, -} from "./Tag"; +import { Tag, TagFilterAllowlist, TagInsertSchema, tags, TagSortAllowlist, TagUpdateSchema } from "./Tag"; import { mountCrudRoutes } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; import type { FastifyInstance } from "fastify"; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.ts index e403eda9de..a1cdad130f 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.ts @@ -1,17 +1,8 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Tag (Tag) // Extend in your own module (e.g. Tag.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnySQLiteColumn, - integer, - sqliteTable, - text, -} from "drizzle-orm/sqlite-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnySQLiteColumn, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; import { z } from "zod"; import { TagNames } from "./Tag.names"; import { customers } from "./shop/users/Customer"; @@ -19,23 +10,16 @@ import { customers } from "./shop/users/Customer"; export const tags = sqliteTable(TagNames.sources.primary.table, { id: integer(TagNames.fields.id.column).primaryKey({ autoIncrement: true }), label: text(TagNames.fields.label.column).notNull(), - customerId: integer(TagNames.fields.customerId.column) - .notNull() - .references((): AnySQLiteColumn => customers.id), + customerId: integer(TagNames.fields.customerId.column).notNull().references((): AnySQLiteColumn => customers.id), }); -export const tagsRelations = relations(tags, ({ one }) => ({ - customer: one(customers, { - fields: [tags.customerId], - references: [customers.id], - }), -})); +export const tagsRelations = relations( + tags, + ({ one }) => ({ customer: one(customers, { fields: [tags.customerId], references: [customers.id] }) }), +); export type Tag = InferSelectModel; export type TagInsert = InferInsertModel; export type TagUpdate = Partial; -export const TagInsertSchema = z.object({ - label: z.string().min(1).max(100), - customerId: z.number().int(), -}); +export const TagInsertSchema = z.object({ label: z.string().min(1).max(100), customerId: z.number().int() }); export const TagUpdateSchema = z.object({ label: z.string().min(1).max(100).optional(), @@ -82,10 +66,7 @@ export const Tag = { label: "Label", view: "text", htmlType: "text", - rules: { - required: "Label is required", - maxLength: { value: 100, message: "Must be 100 characters or fewer" }, - }, + rules: { required: "Label is required", maxLength: { value: 100, message: "Must be 100 characters or fewer" } }, }, customerId: { name: "customerId", @@ -101,10 +82,4 @@ export const TagFilterAllowlist = {} as const satisfies FilterAllowlist; import type { SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; export const TagSortAllowlist = {} as const satisfies SortAllowlist; -export type TagFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: TagFilter[]; - and?: TagFilter[]; -}; +export type TagFilter = { limit?: number; offset?: number; sort?: string; or?: TagFilter[]; and?: TagFilter[] }; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.queries.ts index 559cb87f7c..bcfbfe2d2a 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.queries.ts @@ -5,31 +5,14 @@ import { eq, inArray } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; -import { - type Order, - OrderInsertSchema, - type OrderPatch, - orders, - OrderUpdateSchema, -} from "./Order"; +import { type Order, OrderInsertSchema, type OrderPatch, orders, OrderUpdateSchema } from "./Order"; export async function findOrderById(db: Db, id: number): Promise { - const [order] = await db - .select() - .from(orders) - .where(eq(orders.id, id)) - .limit(1); + const [order] = await db.select().from(orders).where(eq(orders.id, id)).limit(1); return order ?? null; } -export async function listOrders( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listOrders(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(orders).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -39,30 +22,19 @@ export async function listOrders( } return q; } -export async function createOrder( - db: Db, - data: z.input, -): Promise { +export async function createOrder(db: Db, data: z.input): Promise { const validated = OrderInsertSchema.parse(data); const [order] = await db.insert(orders).values(validated).returning(); return order!; } -export async function updateOrder( - db: Db, - id: number, - patch: OrderPatch, -): Promise { +export async function updateOrder(db: Db, id: number, patch: OrderPatch): Promise { const validated = OrderUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findOrderById(db, id); } - const [order] = await db - .update(orders) - .set(validated) - .where(eq(orders.id, id)) - .returning(); + const [order] = await db.update(orders).set(validated).where(eq(orders.id, id)).returning(); return order ?? null; } export async function deleteOrderById(db: Db, id: number): Promise { @@ -71,36 +43,21 @@ export async function deleteOrderById(db: Db, id: number): Promise { const deleted = await db.delete(orders).where(eq(orders.id, id)).returning(); return deleted.length > 0; } -export async function findOrdersByCustomer( - db: Db, - customerId: number, -): Promise { +export async function findOrdersByCustomer(db: Db, customerId: number): Promise { return db.select().from(orders).where(eq(orders.customerId, customerId)); } -export async function findOrdersByCustomerIn( - db: Db, - customerIds: number[], -): Promise { +export async function findOrdersByCustomerIn(db: Db, customerIds: number[]): Promise { if (customerIds.length === 0) { return []; } - return db - .select() - .from(orders) - .where(inArray(orders.customerId, customerIds)); + return db.select().from(orders).where(inArray(orders.customerId, customerIds)); } -export async function findOrdersByProduct( - db: Db, - productId: number, -): Promise { +export async function findOrdersByProduct(db: Db, productId: number): Promise { return db.select().from(orders).where(eq(orders.productId, productId)); } -export async function findOrdersByProductIn( - db: Db, - productIds: number[], -): Promise { +export async function findOrdersByProductIn(db: Db, productIds: number[]): Promise { if (productIds.length === 0) { return []; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.routes.ts index 6fe09bbd7a..0e3a90eb9c 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.routes.ts @@ -2,14 +2,7 @@ // Source metadata: Order (shop::commerce::Order) // Extend in your own module (e.g. Order.extra.ts) — nothing imports it for you. import { db } from "../../../db"; -import { - Order, - OrderFilterAllowlist, - OrderInsertSchema, - orders, - OrderSortAllowlist, - OrderUpdateSchema, -} from "./Order"; +import { Order, OrderFilterAllowlist, OrderInsertSchema, orders, OrderSortAllowlist, OrderUpdateSchema } from "./Order"; import { mountCrudRoutes } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; import type { FastifyInstance } from "fastify"; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.ts index c3b8a0b08e..679dc1380b 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.ts @@ -1,16 +1,8 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Order (shop::commerce::Order) // Extend in your own module (e.g. Order.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnySQLiteColumn, - integer, - sqliteTable, -} from "drizzle-orm/sqlite-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnySQLiteColumn, integer, sqliteTable } from "drizzle-orm/sqlite-core"; import { z } from "zod"; import { customers } from "../users/Customer"; import { OrderNames } from "./Order.names"; @@ -18,24 +10,17 @@ import { products } from "./Product"; export const orders = sqliteTable(OrderNames.sources.primary.table, { id: integer(OrderNames.fields.id.column).primaryKey({ autoIncrement: true }), - customerId: integer(OrderNames.fields.customerId.column) - .notNull() - .references((): AnySQLiteColumn => customers.id), - productId: integer(OrderNames.fields.productId.column) - .notNull() - .references((): AnySQLiteColumn => products.id), + customerId: integer(OrderNames.fields.customerId.column).notNull().references((): AnySQLiteColumn => customers.id), + productId: integer(OrderNames.fields.productId.column).notNull().references((): AnySQLiteColumn => products.id), quantity: integer(OrderNames.fields.quantity.column).notNull(), }); -export const ordersRelations = relations(orders, ({ one }) => ({ - customer: one(customers, { - fields: [orders.customerId], - references: [customers.id], +export const ordersRelations = relations( + orders, + ({ one }) => ({ + customer: one(customers, { fields: [orders.customerId], references: [customers.id] }), + product: one(products, { fields: [orders.productId], references: [products.id] }), }), - product: one(products, { - fields: [orders.productId], - references: [products.id], - }), -})); +); export type Order = InferSelectModel; export type OrderInsert = InferInsertModel; export type OrderUpdate = Partial; @@ -114,10 +99,4 @@ export const OrderFilterAllowlist = {} as const satisfies FilterAllowlist; import type { SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; export const OrderSortAllowlist = {} as const satisfies SortAllowlist; -export type OrderFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: OrderFilter[]; - and?: OrderFilter[]; -}; +export type OrderFilter = { limit?: number; offset?: number; sort?: string; or?: OrderFilter[]; and?: OrderFilter[] }; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.queries.ts index 5dac95be94..35f904c45e 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.queries.ts @@ -5,34 +5,14 @@ import { eq, inArray } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; -import { - type Product, - ProductInsertSchema, - type ProductPatch, - products, - ProductUpdateSchema, -} from "./Product"; -export async function findProductById( - db: Db, - id: number, -): Promise { - const [product] = await db - .select() - .from(products) - .where(eq(products.id, id)) - .limit(1); +import { type Product, ProductInsertSchema, type ProductPatch, products, ProductUpdateSchema } from "./Product"; +export async function findProductById(db: Db, id: number): Promise { + const [product] = await db.select().from(products).where(eq(products.id, id)).limit(1); return product ?? null; } -export async function listProducts( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listProducts(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(products).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -42,52 +22,32 @@ export async function listProducts( } return q; } -export async function createProduct( - db: Db, - data: z.input, -): Promise { +export async function createProduct(db: Db, data: z.input): Promise { const validated = ProductInsertSchema.parse(data); const [product] = await db.insert(products).values(validated).returning(); return product!; } -export async function updateProduct( - db: Db, - id: number, - patch: ProductPatch, -): Promise { +export async function updateProduct(db: Db, id: number, patch: ProductPatch): Promise { const validated = ProductUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findProductById(db, id); } - const [product] = await db - .update(products) - .set(validated) - .where(eq(products.id, id)) - .returning(); + const [product] = await db.update(products).set(validated).where(eq(products.id, id)).returning(); return product ?? null; } export async function deleteProductById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(products) - .where(eq(products.id, id)) - .returning(); + const deleted = await db.delete(products).where(eq(products.id, id)).returning(); return deleted.length > 0; } -export async function findProductsByTag( - db: Db, - tagId: number, -): Promise { +export async function findProductsByTag(db: Db, tagId: number): Promise { return db.select().from(products).where(eq(products.tagId, tagId)); } -export async function findProductsByTagIn( - db: Db, - tagIds: number[], -): Promise { +export async function findProductsByTagIn(db: Db, tagIds: number[]): Promise { if (tagIds.length === 0) { return []; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.ts index 9a0149a188..3ab0fea323 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.ts @@ -1,40 +1,25 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Product (shop::commerce::Product) // Extend in your own module (e.g. Product.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnySQLiteColumn, - integer, - sqliteTable, - text, -} from "drizzle-orm/sqlite-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnySQLiteColumn, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; import { z } from "zod"; import { tags } from "../../Tag"; import { ProductNames } from "./Product.names"; export const products = sqliteTable(ProductNames.sources.primary.table, { - id: integer(ProductNames.fields.id.column).primaryKey({ - autoIncrement: true, - }), + id: integer(ProductNames.fields.id.column).primaryKey({ autoIncrement: true }), name: text(ProductNames.fields.name.column).notNull(), - tagId: integer(ProductNames.fields.tagId.column) - .notNull() - .references((): AnySQLiteColumn => tags.id), + tagId: integer(ProductNames.fields.tagId.column).notNull().references((): AnySQLiteColumn => tags.id), }); -export const productsRelations = relations(products, ({ one }) => ({ - tag: one(tags, { fields: [products.tagId], references: [tags.id] }), -})); +export const productsRelations = relations( + products, + ({ one }) => ({ tag: one(tags, { fields: [products.tagId], references: [tags.id] }) }), +); export type Product = InferSelectModel; export type ProductInsert = InferInsertModel; export type ProductUpdate = Partial; -export const ProductInsertSchema = z.object({ - name: z.string().min(1).max(200), - tagId: z.number().int(), -}); +export const ProductInsertSchema = z.object({ name: z.string().min(1).max(200), tagId: z.number().int() }); export const ProductUpdateSchema = z.object({ name: z.string().min(1).max(200).optional(), @@ -81,10 +66,7 @@ export const Product = { label: "Name", view: "text", htmlType: "text", - rules: { - required: "Name is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, + rules: { required: "Name is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, tagId: { name: "tagId", diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.queries.ts index 89fe94c91f..788988abeb 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.queries.ts @@ -5,34 +5,14 @@ import { eq } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; -import { - type Customer, - CustomerInsertSchema, - type CustomerPatch, - customers, - CustomerUpdateSchema, -} from "./Customer"; -export async function findCustomerById( - db: Db, - id: number, -): Promise { - const [customer] = await db - .select() - .from(customers) - .where(eq(customers.id, id)) - .limit(1); +import { type Customer, CustomerInsertSchema, type CustomerPatch, customers, CustomerUpdateSchema } from "./Customer"; +export async function findCustomerById(db: Db, id: number): Promise { + const [customer] = await db.select().from(customers).where(eq(customers.id, id)).limit(1); return customer ?? null; } -export async function listCustomers( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listCustomers(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(customers).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -42,38 +22,24 @@ export async function listCustomers( } return q; } -export async function createCustomer( - db: Db, - data: z.input, -): Promise { +export async function createCustomer(db: Db, data: z.input): Promise { const validated = CustomerInsertSchema.parse(data); const [customer] = await db.insert(customers).values(validated).returning(); return customer!; } -export async function updateCustomer( - db: Db, - id: number, - patch: CustomerPatch, -): Promise { +export async function updateCustomer(db: Db, id: number, patch: CustomerPatch): Promise { const validated = CustomerUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findCustomerById(db, id); } - const [customer] = await db - .update(customers) - .set(validated) - .where(eq(customers.id, id)) - .returning(); + const [customer] = await db.update(customers).set(validated).where(eq(customers.id, id)).returning(); return customer ?? null; } export async function deleteCustomerById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(customers) - .where(eq(customers.id, id)) - .returning(); + const deleted = await db.delete(customers).where(eq(customers.id, id)).returning(); return deleted.length > 0; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.ts index cae74ba52f..ba7db33bb8 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.ts @@ -7,21 +7,15 @@ import { z } from "zod"; import { CustomerNames } from "./Customer.names"; export const customers = sqliteTable(CustomerNames.sources.primary.table, { - id: integer(CustomerNames.fields.id.column).primaryKey({ - autoIncrement: true, - }), + id: integer(CustomerNames.fields.id.column).primaryKey({ autoIncrement: true }), email: text(CustomerNames.fields.email.column).notNull(), }); export type Customer = InferSelectModel; export type CustomerInsert = InferInsertModel; export type CustomerUpdate = Partial; -export const CustomerInsertSchema = z.object({ - email: z.string().min(1).max(255), -}); +export const CustomerInsertSchema = z.object({ email: z.string().min(1).max(255) }); -export const CustomerUpdateSchema = z.object({ - email: z.string().min(1).max(255).optional(), -}); +export const CustomerUpdateSchema = z.object({ email: z.string().min(1).max(255).optional() }); /** Typed create shape for Customer: the insert schema's INPUT (pre-transform) type. A * renamed/dropped/misspelt field is a compile error at every `createCustomer` call site; @@ -63,10 +57,7 @@ export const Customer = { label: "Email", view: "text", htmlType: "text", - rules: { - required: "Email is required", - maxLength: { value: 255, message: "Must be 255 characters or fewer" }, - }, + rules: { required: "Email is required", maxLength: { value: 255, message: "Must be 255 characters or fewer" } }, }, } as const; import type { FilterAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.queries.ts index f3e8bda7c5..f4b4ee53ee 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Exercise, - ExerciseInsertSchema, - type ExercisePatch, - exercises, - ExerciseUpdateSchema, -} from "./Exercise"; -export async function findExerciseById( - db: Db, - id: number, -): Promise { - const [exercise] = await db - .select() - .from(exercises) - .where(eq(exercises.id, id)) - .limit(1); +import { type Exercise, ExerciseInsertSchema, type ExercisePatch, exercises, ExerciseUpdateSchema } from "./Exercise"; +export async function findExerciseById(db: Db, id: number): Promise { + const [exercise] = await db.select().from(exercises).where(eq(exercises.id, id)).limit(1); return exercise ?? null; } -export async function listExercises( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listExercises(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(exercises).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,57 +22,34 @@ export async function listExercises( } return q; } -export async function createExercise( - db: Db, - data: z.input, -): Promise { +export async function createExercise(db: Db, data: z.input): Promise { const validated = ExerciseInsertSchema.parse(data); const [exercise] = await db.insert(exercises).values(validated).returning(); return exercise!; } -export async function updateExercise( - db: Db, - id: number, - patch: ExercisePatch, -): Promise { +export async function updateExercise(db: Db, id: number, patch: ExercisePatch): Promise { const validated = ExerciseUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findExerciseById(db, id); } - const [exercise] = await db - .update(exercises) - .set(validated) - .where(eq(exercises.id, id)) - .returning(); + const [exercise] = await db.update(exercises).set(validated).where(eq(exercises.id, id)).returning(); return exercise ?? null; } export async function deleteExerciseById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(exercises) - .where(eq(exercises.id, id)) - .returning(); + const deleted = await db.delete(exercises).where(eq(exercises.id, id)).returning(); return deleted.length > 0; } -export async function findExercisesByWorkout( - db: Db, - workoutId: number, -): Promise { +export async function findExercisesByWorkout(db: Db, workoutId: number): Promise { return db.select().from(exercises).where(eq(exercises.workoutId, workoutId)); } -export async function findExercisesByWorkoutIn( - db: Db, - workoutIds: number[], -): Promise { +export async function findExercisesByWorkoutIn(db: Db, workoutIds: number[]): Promise { if (workoutIds.length === 0) { return []; } - return db - .select() - .from(exercises) - .where(inArray(exercises.workoutId, workoutIds)); + return db.select().from(exercises).where(inArray(exercises.workoutId, workoutIds)); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.ts index e2770d23c9..b06b1cd536 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.ts @@ -1,40 +1,23 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Exercise (Exercise) // Extend in your own module (e.g. Exercise.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnyPgColumn, - bigint, - integer, - pgTable, - text, - varchar, -} from "drizzle-orm/pg-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnyPgColumn, bigint, integer, pgTable, text, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; import { workouts } from "./Workout"; export const exercises = pgTable("exercises", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), - workoutId: bigint("workout_id", { mode: "number" }) - .notNull() - .references((): AnyPgColumn => workouts.id), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + workoutId: bigint("workout_id", { mode: "number" }).notNull().references((): AnyPgColumn => workouts.id), name: varchar("name", { length: 200 }).notNull(), sets: integer("sets"), reps: integer("reps"), notes: text("notes"), }); -export const exercisesRelations = relations(exercises, ({ one }) => ({ - workout: one(workouts, { - fields: [exercises.workoutId], - references: [workouts.id], - }), -})); +export const exercisesRelations = relations( + exercises, + ({ one }) => ({ workout: one(workouts, { fields: [exercises.workoutId], references: [workouts.id] }) }), +); export type Exercise = InferSelectModel; export type ExerciseInsert = InferInsertModel; export type ExerciseUpdate = Partial; @@ -101,10 +84,7 @@ export const Exercise = { label: "Name", view: "text", htmlType: "text", - rules: { - required: "Name is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, + rules: { required: "Name is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, sets: { name: "sets", label: "Sets", view: "number", htmlType: "number" }, reps: { name: "reps", label: "Reps", view: "number", htmlType: "number" }, diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.queries.ts index 41d300bf52..885445757e 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Program, - ProgramInsertSchema, - type ProgramPatch, - programs, - ProgramUpdateSchema, -} from "./Program"; -export async function findProgramById( - db: Db, - id: number, -): Promise { - const [program] = await db - .select() - .from(programs) - .where(eq(programs.id, id)) - .limit(1); +import { type Program, ProgramInsertSchema, type ProgramPatch, programs, ProgramUpdateSchema } from "./Program"; +export async function findProgramById(db: Db, id: number): Promise { + const [program] = await db.select().from(programs).where(eq(programs.id, id)).limit(1); return program ?? null; } -export async function listPrograms( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(programs).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,38 +22,24 @@ export async function listPrograms( } return q; } -export async function createProgram( - db: Db, - data: z.input, -): Promise { +export async function createProgram(db: Db, data: z.input): Promise { const validated = ProgramInsertSchema.parse(data); const [program] = await db.insert(programs).values(validated).returning(); return program!; } -export async function updateProgram( - db: Db, - id: number, - patch: ProgramPatch, -): Promise { +export async function updateProgram(db: Db, id: number, patch: ProgramPatch): Promise { const validated = ProgramUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findProgramById(db, id); } - const [program] = await db - .update(programs) - .set(validated) - .where(eq(programs.id, id)) - .returning(); + const [program] = await db.update(programs).set(validated).where(eq(programs.id, id)).returning(); return program ?? null; } export async function deleteProgramById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(programs) - .where(eq(programs.id, id)) - .returning(); + const deleted = await db.delete(programs).where(eq(programs.id, id)).returning(); return deleted.length > 0; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.routes.ts index d9389baea0..1acd334a76 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.routes.ts @@ -45,14 +45,6 @@ export async function programRoutes(fastify: FastifyInstance) { filterAllowlist: ProgramFilterAllowlist, sortAllowlist: ProgramSortAllowlist, dialect: "postgres", - knownFields: [ - "id", - "slug", - "title", - "description", - "priceCents", - "isPublished", - "createdAt", - ], + knownFields: ["id", "slug", "title", "description", "priceCents", "isPublished", "createdAt"], }); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.ts index aeffbeb30b..9432ac4f35 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.ts @@ -2,29 +2,17 @@ // Source metadata: Program (Program) // Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you. import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { - bigint, - boolean, - integer, - pgTable, - text, - timestamp, - varchar, -} from "drizzle-orm/pg-core"; +import { bigint, boolean, integer, pgTable, text, timestamp, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; export const programs = pgTable("programs", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), slug: varchar("slug", { length: 100 }).notNull().unique(), title: varchar("title", { length: 200 }).notNull(), description: text("description"), priceCents: integer("price_cents").notNull(), isPublished: boolean("is_published").notNull().default(false), - createdAt: timestamp("created_at", { mode: "string", withTimezone: true }) - .notNull() - .defaultNow(), + createdAt: timestamp("created_at", { mode: "string", withTimezone: true }).notNull().defaultNow(), }); export type Program = InferSelectModel; export type ProgramInsert = InferInsertModel; @@ -36,10 +24,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -48,9 +34,7 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const ProgramInsertSchema = z.object({ @@ -59,14 +43,10 @@ export const ProgramInsertSchema = z.object({ description: z.string().optional(), priceCents: z.number().int(), isPublished: z.boolean().optional(), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); export const ProgramUpdateSchema = z.object({ @@ -75,14 +55,10 @@ export const ProgramUpdateSchema = z.object({ description: z.string().optional().nullable(), priceCents: z.number().int().optional(), isPublished: z.boolean().optional(), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); /** Typed create shape for Program: the insert schema's INPUT (pre-transform) type. A @@ -125,27 +101,16 @@ export const Program = { label: "Slug", view: "text", htmlType: "text", - rules: { - required: "Slug is required", - maxLength: { value: 100, message: "Must be 100 characters or fewer" }, - }, + rules: { required: "Slug is required", maxLength: { value: 100, message: "Must be 100 characters or fewer" } }, }, title: { name: "title", label: "Title", view: "text", htmlType: "text", - rules: { - required: "Title is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, - }, - description: { - name: "description", - label: "Description", - view: "text", - htmlType: "text", + rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, + description: { name: "description", label: "Description", view: "text", htmlType: "text" }, priceCents: { name: "priceCents", label: "Price Cents", diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.queries.ts index ec01f4c9d5..905dbdf2e3 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Purchase, - PurchaseInsertSchema, - type PurchasePatch, - purchases, - PurchaseUpdateSchema, -} from "./Purchase"; -export async function findPurchaseById( - db: Db, - id: number, -): Promise { - const [purchase] = await db - .select() - .from(purchases) - .where(eq(purchases.id, id)) - .limit(1); +import { type Purchase, PurchaseInsertSchema, type PurchasePatch, purchases, PurchaseUpdateSchema } from "./Purchase"; +export async function findPurchaseById(db: Db, id: number): Promise { + const [purchase] = await db.select().from(purchases).where(eq(purchases.id, id)).limit(1); return purchase ?? null; } -export async function listPurchases( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listPurchases(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(purchases).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,79 +22,44 @@ export async function listPurchases( } return q; } -export async function createPurchase( - db: Db, - data: z.input, -): Promise { +export async function createPurchase(db: Db, data: z.input): Promise { const validated = PurchaseInsertSchema.parse(data); const [purchase] = await db.insert(purchases).values(validated).returning(); return purchase!; } -export async function updatePurchase( - db: Db, - id: number, - patch: PurchasePatch, -): Promise { +export async function updatePurchase(db: Db, id: number, patch: PurchasePatch): Promise { const validated = PurchaseUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findPurchaseById(db, id); } - const [purchase] = await db - .update(purchases) - .set(validated) - .where(eq(purchases.id, id)) - .returning(); + const [purchase] = await db.update(purchases).set(validated).where(eq(purchases.id, id)).returning(); return purchase ?? null; } export async function deletePurchaseById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(purchases) - .where(eq(purchases.id, id)) - .returning(); + const deleted = await db.delete(purchases).where(eq(purchases.id, id)).returning(); return deleted.length > 0; } -export async function findPurchasesBySubscriber( - db: Db, - subscriberId: number, -): Promise { - return db - .select() - .from(purchases) - .where(eq(purchases.subscriberId, subscriberId)); +export async function findPurchasesBySubscriber(db: Db, subscriberId: number): Promise { + return db.select().from(purchases).where(eq(purchases.subscriberId, subscriberId)); } -export async function findPurchasesBySubscriberIn( - db: Db, - subscriberIds: number[], -): Promise { +export async function findPurchasesBySubscriberIn(db: Db, subscriberIds: number[]): Promise { if (subscriberIds.length === 0) { return []; } - return db - .select() - .from(purchases) - .where(inArray(purchases.subscriberId, subscriberIds)); + return db.select().from(purchases).where(inArray(purchases.subscriberId, subscriberIds)); } -export async function findPurchasesByProgram( - db: Db, - programId: number, -): Promise { +export async function findPurchasesByProgram(db: Db, programId: number): Promise { return db.select().from(purchases).where(eq(purchases.programId, programId)); } -export async function findPurchasesByProgramIn( - db: Db, - programIds: number[], -): Promise { +export async function findPurchasesByProgramIn(db: Db, programIds: number[]): Promise { if (programIds.length === 0) { return []; } - return db - .select() - .from(purchases) - .where(inArray(purchases.programId, programIds)); + return db.select().from(purchases).where(inArray(purchases.programId, programIds)); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.routes.ts index 02caa5ee14..379b7a60b1 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.routes.ts @@ -45,12 +45,6 @@ export async function purchaseRoutes(fastify: FastifyInstance) { filterAllowlist: PurchaseFilterAllowlist, sortAllowlist: PurchaseSortAllowlist, dialect: "postgres", - knownFields: [ - "id", - "subscriberId", - "programId", - "amountCents", - "purchasedAt", - ], + knownFields: ["id", "subscriberId", "programId", "amountCents", "purchasedAt"], }); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.ts index f74457a592..4e68280019 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.ts @@ -1,47 +1,26 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Purchase (Purchase) // Extend in your own module (e.g. Purchase.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnyPgColumn, - bigint, - integer, - pgTable, - timestamp, -} from "drizzle-orm/pg-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnyPgColumn, bigint, integer, pgTable, timestamp } from "drizzle-orm/pg-core"; import { z } from "zod"; import { programs } from "./Program"; import { subscribers } from "./Subscriber"; export const purchases = pgTable("purchases", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), - subscriberId: bigint("subscriber_id", { mode: "number" }) - .notNull() - .references((): AnyPgColumn => subscribers.id), - programId: bigint("program_id", { mode: "number" }) - .notNull() - .references((): AnyPgColumn => programs.id), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + subscriberId: bigint("subscriber_id", { mode: "number" }).notNull().references((): AnyPgColumn => subscribers.id), + programId: bigint("program_id", { mode: "number" }).notNull().references((): AnyPgColumn => programs.id), amountCents: integer("amount_cents").notNull(), - purchasedAt: timestamp("purchased_at", { mode: "string", withTimezone: true }) - .notNull() - .defaultNow(), + purchasedAt: timestamp("purchased_at", { mode: "string", withTimezone: true }).notNull().defaultNow(), }); -export const purchasesRelations = relations(purchases, ({ one }) => ({ - subscriber: one(subscribers, { - fields: [purchases.subscriberId], - references: [subscribers.id], +export const purchasesRelations = relations( + purchases, + ({ one }) => ({ + subscriber: one(subscribers, { fields: [purchases.subscriberId], references: [subscribers.id] }), + program: one(programs, { fields: [purchases.programId], references: [programs.id] }), }), - program: one(programs, { - fields: [purchases.programId], - references: [programs.id], - }), -})); +); export type Purchase = InferSelectModel; export type PurchaseInsert = InferInsertModel; export type PurchaseUpdate = Partial; @@ -52,10 +31,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -64,37 +41,27 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const PurchaseInsertSchema = z.object({ subscriberId: z.number().int(), programId: z.number().int(), amountCents: z.number().int(), - purchasedAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + purchasedAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); export const PurchaseUpdateSchema = z.object({ subscriberId: z.number().int().optional(), programId: z.number().int().optional(), amountCents: z.number().int().optional(), - purchasedAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + purchasedAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); /** Typed create shape for Purchase: the insert schema's INPUT (pre-transform) type. A diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.queries.ts index aa17a0b323..b91662c023 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.queries.ts @@ -14,21 +14,11 @@ import { subscribers, SubscriberUpdateSchema, } from "./Subscriber"; -export async function findSubscriberById( - db: Db, - id: number, -): Promise { - const [subscriber] = await db - .select() - .from(subscribers) - .where(eq(subscribers.id, id)) - .limit(1); +export async function findSubscriberById(db: Db, id: number): Promise { + const [subscriber] = await db.select().from(subscribers).where(eq(subscribers.id, id)).limit(1); return subscriber ?? null; } -export async function listSubscribers( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listSubscribers(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(subscribers).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,44 +28,24 @@ export async function listSubscribers( } return q; } -export async function createSubscriber( - db: Db, - data: z.input, -): Promise { +export async function createSubscriber(db: Db, data: z.input): Promise { const validated = SubscriberInsertSchema.parse(data); - const [subscriber] = await db - .insert(subscribers) - .values(validated) - .returning(); + const [subscriber] = await db.insert(subscribers).values(validated).returning(); return subscriber!; } -export async function updateSubscriber( - db: Db, - id: number, - patch: SubscriberPatch, -): Promise { +export async function updateSubscriber(db: Db, id: number, patch: SubscriberPatch): Promise { const validated = SubscriberUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findSubscriberById(db, id); } - const [subscriber] = await db - .update(subscribers) - .set(validated) - .where(eq(subscribers.id, id)) - .returning(); + const [subscriber] = await db.update(subscribers).set(validated).where(eq(subscribers.id, id)).returning(); return subscriber ?? null; } -export async function deleteSubscriberById( - db: Db, - id: number, -): Promise { +export async function deleteSubscriberById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(subscribers) - .where(eq(subscribers.id, id)) - .returning(); + const deleted = await db.delete(subscribers).where(eq(subscribers.id, id)).returning(); return deleted.length > 0; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.routes.ts index 5b0664743b..5f8729600d 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.routes.ts @@ -45,13 +45,6 @@ export async function subscriberRoutes(fastify: FastifyInstance) { filterAllowlist: SubscriberFilterAllowlist, sortAllowlist: SubscriberSortAllowlist, dialect: "postgres", - knownFields: [ - "id", - "email", - "firstName", - "lastName", - "subscribed", - "createdAt", - ], + knownFields: ["id", "email", "firstName", "lastName", "subscribed", "createdAt"], }); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.ts index dee5dcdb18..125d01af10 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.ts @@ -2,26 +2,16 @@ // Source metadata: Subscriber (Subscriber) // Extend in your own module (e.g. Subscriber.extra.ts) — nothing imports it for you. import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { - bigint, - boolean, - pgTable, - timestamp, - varchar, -} from "drizzle-orm/pg-core"; +import { bigint, boolean, pgTable, timestamp, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; export const subscribers = pgTable("subscribers", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), email: varchar("email", { length: 255 }).notNull().unique(), firstName: varchar("first_name", { length: 100 }).notNull(), lastName: varchar("last_name", { length: 100 }), subscribed: boolean("subscribed").notNull().default(true), - createdAt: timestamp("created_at", { mode: "string", withTimezone: true }) - .notNull() - .defaultNow(), + createdAt: timestamp("created_at", { mode: "string", withTimezone: true }).notNull().defaultNow(), }); export type Subscriber = InferSelectModel; export type SubscriberInsert = InferInsertModel; @@ -33,10 +23,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -45,9 +33,7 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const SubscriberInsertSchema = z.object({ @@ -55,14 +41,10 @@ export const SubscriberInsertSchema = z.object({ firstName: z.string().min(1).max(100), lastName: z.string().max(100).optional(), subscribed: z.boolean().optional(), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); export const SubscriberUpdateSchema = z.object({ @@ -70,14 +52,10 @@ export const SubscriberUpdateSchema = z.object({ firstName: z.string().min(1).max(100).optional(), lastName: z.string().max(100).optional().nullable(), subscribed: z.boolean().optional(), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); /** Typed create shape for Subscriber: the insert schema's INPUT (pre-transform) type. A @@ -120,10 +98,7 @@ export const Subscriber = { label: "Email", view: "text", htmlType: "text", - rules: { - required: "Email is required", - maxLength: { value: 255, message: "Must be 255 characters or fewer" }, - }, + rules: { required: "Email is required", maxLength: { value: 255, message: "Must be 255 characters or fewer" } }, }, firstName: { name: "firstName", @@ -140,9 +115,7 @@ export const Subscriber = { label: "Last Name", view: "text", htmlType: "text", - rules: { - maxLength: { value: 100, message: "Must be 100 characters or fewer" }, - }, + rules: { maxLength: { value: 100, message: "Must be 100 characters or fewer" } }, }, subscribed: { name: "subscribed", diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.queries.ts index 3141474717..64c6e754a7 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.queries.ts @@ -7,21 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Tag, - TagInsertSchema, - type TagPatch, - tags, - TagUpdateSchema, -} from "./Tag"; +import { type Tag, TagInsertSchema, type TagPatch, tags, TagUpdateSchema } from "./Tag"; export async function findTagById(db: Db, id: number): Promise { const [tag] = await db.select().from(tags).where(eq(tags.id, id)).limit(1); return tag ?? null; } -export async function listTags( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listTags(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(tags).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -31,30 +22,19 @@ export async function listTags( } return q; } -export async function createTag( - db: Db, - data: z.input, -): Promise { +export async function createTag(db: Db, data: z.input): Promise { const validated = TagInsertSchema.parse(data); const [tag] = await db.insert(tags).values(validated).returning(); return tag!; } -export async function updateTag( - db: Db, - id: number, - patch: TagPatch, -): Promise { +export async function updateTag(db: Db, id: number, patch: TagPatch): Promise { const validated = TagUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findTagById(db, id); } - const [tag] = await db - .update(tags) - .set(validated) - .where(eq(tags.id, id)) - .returning(); + const [tag] = await db.update(tags).set(validated).where(eq(tags.id, id)).returning(); return tag ?? null; } export async function deleteTagById(db: Db, id: number): Promise { diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.routes.ts index 8dc41fe210..fd85d72620 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.routes.ts @@ -2,14 +2,7 @@ // Source metadata: Tag (Tag) // Extend in your own module (e.g. Tag.extra.ts) — nothing imports it for you. import { db } from "~/server/db"; -import { - Tag, - TagFilterAllowlist, - TagInsertSchema, - tags, - TagSortAllowlist, - TagUpdateSchema, -} from "./Tag"; +import { Tag, TagFilterAllowlist, TagInsertSchema, tags, TagSortAllowlist, TagUpdateSchema } from "./Tag"; import { mountCrudRoutes } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; import type { FastifyInstance } from "fastify"; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.ts index 45b9c2c043..b6da2f7b23 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.ts @@ -6,19 +6,14 @@ import { bigint, pgTable, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; export const tags = pgTable("tags", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), name: varchar("name", { length: 50 }).notNull().unique(), slug: varchar("slug", { length: 50 }).notNull().unique(), }); export type Tag = InferSelectModel; export type TagInsert = InferInsertModel; export type TagUpdate = Partial; -export const TagInsertSchema = z.object({ - name: z.string().min(1).max(50), - slug: z.string().min(1).max(50), -}); +export const TagInsertSchema = z.object({ name: z.string().min(1).max(50), slug: z.string().min(1).max(50) }); export const TagUpdateSchema = z.object({ name: z.string().min(1).max(50).optional(), @@ -65,20 +60,14 @@ export const Tag = { label: "Name", view: "text", htmlType: "text", - rules: { - required: "Name is required", - maxLength: { value: 50, message: "Must be 50 characters or fewer" }, - }, + rules: { required: "Name is required", maxLength: { value: 50, message: "Must be 50 characters or fewer" } }, }, slug: { name: "slug", label: "Slug", view: "text", htmlType: "text", - rules: { - required: "Slug is required", - maxLength: { value: 50, message: "Must be 50 characters or fewer" }, - }, + rules: { required: "Slug is required", maxLength: { value: 50, message: "Must be 50 characters or fewer" } }, }, } as const; import type { FilterAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; @@ -87,10 +76,4 @@ export const TagFilterAllowlist = {} as const satisfies FilterAllowlist; import type { SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; export const TagSortAllowlist = {} as const satisfies SortAllowlist; -export type TagFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: TagFilter[]; - and?: TagFilter[]; -}; +export type TagFilter = { limit?: number; offset?: number; sort?: string; or?: TagFilter[]; and?: TagFilter[] }; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Video.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Video.queries.ts index 5f5fe10e72..d56c7f45b5 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Video.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Video.queries.ts @@ -7,25 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Video, - VideoInsertSchema, - type VideoPatch, - videos, - VideoUpdateSchema, -} from "./Video"; +import { type Video, VideoInsertSchema, type VideoPatch, videos, VideoUpdateSchema } from "./Video"; export async function findVideoById(db: Db, id: number): Promise