From 79e32f532597b48b5a0d90f9cb1346aa86fb10ad Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 19 Nov 2026 19:41:58 -0500 Subject: [PATCH 1/5] feat(examples): add a metadata-driven grid, form and route mount in TypeScript examples/dynamic-grid serves and renders every entity of a model from the metadata loaded at runtime, with no code generated per entity: - and take an entity name and read columns, types, labels, enum members, relationships, validation limits, filter operators and sort from GET /_meta. They reuse EntityGrid, CurrencyInput and the filter query builder from the web client packages. - One Fastify mount serves list, get, create, update and delete for every entity through ObjectManager, on SQLite, with the wire contract of the generated routes: filter and sort allowlists from the model, typed filter values, bound parameters only, unknown-field 400, api.pagination, and no credential field read or written. - The only generated code is the types and name constants; the hand-written business rules are typed against them. - Editing the metadata file reloads the model: the grid, the form and the API change with no regeneration. A change that would lose data is refused. docs/features/metadata-driven-runtime.md measures it against the reference generators on the same five-entity model (1,781 hand-written lines paid once, against 3,629 generated lines that grow by about 726 an entity), gives the per-row cost of the metadata lookups, and lists what the approach cannot do. It is a TypeScript example, not a package, and claims no equivalent in the other ports. Also fixes mountCrudRoutes and mountDeleteRoute in runtime-ts, which answered 500 for DELETE on a missing row; they answer 404 now. The example's suite runs in the ts-unit lane, and the lane map sends a change under examples/dynamic-grid to the TypeScript lanes only. --- CHANGELOG.md | 15 + bun.lock | 75 +++- docs/README.md | 2 + docs/features/metadata-driven-runtime.md | 290 +++++++++++++ .../.metaobjects/.gen-state/.hashes.json | 37 ++ examples/dynamic-grid/.metaobjects/.gitignore | 9 + .../dynamic-grid/.metaobjects/config.json | 7 + examples/dynamic-grid/README.md | 89 ++++ examples/dynamic-grid/bunfig.toml | 2 + examples/dynamic-grid/metaobjects.config.ts | 18 + .../metaobjects/meta.workshop.yaml | 169 ++++++++ examples/dynamic-grid/package.json | 47 ++ examples/dynamic-grid/scripts/measure.ts | 281 ++++++++++++ examples/dynamic-grid/src/client/api.ts | 77 ++++ examples/dynamic-grid/src/client/app.css | 38 ++ examples/dynamic-grid/src/client/app.tsx | 150 +++++++ examples/dynamic-grid/src/client/context.tsx | 28 ++ examples/dynamic-grid/src/client/controls.tsx | 137 ++++++ .../dynamic-grid/src/client/form-values.ts | 191 +++++++++ examples/dynamic-grid/src/client/format.ts | 69 +++ examples/dynamic-grid/src/client/index.html | 13 + examples/dynamic-grid/src/client/main.tsx | 8 + .../dynamic-grid/src/client/meta-form.tsx | 209 +++++++++ .../dynamic-grid/src/client/meta-grid.tsx | 302 +++++++++++++ examples/dynamic-grid/src/client/model.ts | 285 ++++++++++++ .../dynamic-grid/src/client/references.ts | 104 +++++ .../dynamic-grid/src/generated/Address.ts | 51 +++ .../src/generated/Customer.names.ts | 22 + .../dynamic-grid/src/generated/Customer.ts | 27 ++ .../dynamic-grid/src/generated/Part.names.ts | 22 + examples/dynamic-grid/src/generated/Part.ts | 20 + .../src/generated/Technician.names.ts | 21 + .../dynamic-grid/src/generated/Technician.ts | 98 +++++ .../src/generated/WorkOrder.names.ts | 27 ++ .../dynamic-grid/src/generated/WorkOrder.ts | 110 +++++ .../src/generated/WorkOrderLine.names.ts | 22 + .../src/generated/WorkOrderLine.ts | 16 + examples/dynamic-grid/src/served.ts | 16 + examples/dynamic-grid/src/server/app.ts | 32 ++ .../dynamic-grid/src/server/business-rules.ts | 66 +++ .../dynamic-grid/src/server/client-bundle.ts | 27 ++ .../dynamic-grid/src/server/list-query.ts | 358 ++++++++++++++++ examples/dynamic-grid/src/server/main.ts | 71 +++ examples/dynamic-grid/src/server/routes.ts | 300 +++++++++++++ examples/dynamic-grid/src/server/runtime.ts | 132 ++++++ examples/dynamic-grid/src/server/seed.ts | 105 +++++ .../dynamic-grid/src/server/write-checks.ts | 72 ++++ examples/dynamic-grid/test/app.test.tsx | 147 +++++++ examples/dynamic-grid/test/client-helpers.tsx | 79 ++++ examples/dynamic-grid/test/helpers.ts | 85 ++++ examples/dynamic-grid/test/jsdom.d.ts | 7 + .../dynamic-grid/test/list-allowlist.test.ts | 186 ++++++++ .../dynamic-grid/test/live-reload.test.ts | 114 +++++ examples/dynamic-grid/test/meta-form.test.tsx | 404 ++++++++++++++++++ examples/dynamic-grid/test/meta-grid.test.tsx | 218 ++++++++++ .../test/no-sql-from-request.test.ts | 132 ++++++ examples/dynamic-grid/test/pagination.test.ts | 104 +++++ examples/dynamic-grid/test/setup.ts | 10 + .../dynamic-grid/test/write-contract.test.ts | 278 ++++++++++++ examples/dynamic-grid/tsconfig.json | 15 + package.json | 3 +- scripts/ci-lane-map.txt | 1 + scripts/ci-local.sh | 5 + .../packages/runtime-ts/src/fastify/index.ts | 5 +- .../test/fastify/mount-delete.test.ts | 60 +++ 65 files changed, 6116 insertions(+), 4 deletions(-) create mode 100644 docs/features/metadata-driven-runtime.md create mode 100644 examples/dynamic-grid/.metaobjects/.gen-state/.hashes.json create mode 100644 examples/dynamic-grid/.metaobjects/.gitignore create mode 100644 examples/dynamic-grid/.metaobjects/config.json create mode 100644 examples/dynamic-grid/README.md create mode 100644 examples/dynamic-grid/bunfig.toml create mode 100644 examples/dynamic-grid/metaobjects.config.ts create mode 100644 examples/dynamic-grid/metaobjects/meta.workshop.yaml create mode 100644 examples/dynamic-grid/package.json create mode 100644 examples/dynamic-grid/scripts/measure.ts create mode 100644 examples/dynamic-grid/src/client/api.ts create mode 100644 examples/dynamic-grid/src/client/app.css create mode 100644 examples/dynamic-grid/src/client/app.tsx create mode 100644 examples/dynamic-grid/src/client/context.tsx create mode 100644 examples/dynamic-grid/src/client/controls.tsx create mode 100644 examples/dynamic-grid/src/client/form-values.ts create mode 100644 examples/dynamic-grid/src/client/format.ts create mode 100644 examples/dynamic-grid/src/client/index.html create mode 100644 examples/dynamic-grid/src/client/main.tsx create mode 100644 examples/dynamic-grid/src/client/meta-form.tsx create mode 100644 examples/dynamic-grid/src/client/meta-grid.tsx create mode 100644 examples/dynamic-grid/src/client/model.ts create mode 100644 examples/dynamic-grid/src/client/references.ts create mode 100644 examples/dynamic-grid/src/generated/Address.ts create mode 100644 examples/dynamic-grid/src/generated/Customer.names.ts create mode 100644 examples/dynamic-grid/src/generated/Customer.ts create mode 100644 examples/dynamic-grid/src/generated/Part.names.ts create mode 100644 examples/dynamic-grid/src/generated/Part.ts create mode 100644 examples/dynamic-grid/src/generated/Technician.names.ts create mode 100644 examples/dynamic-grid/src/generated/Technician.ts create mode 100644 examples/dynamic-grid/src/generated/WorkOrder.names.ts create mode 100644 examples/dynamic-grid/src/generated/WorkOrder.ts create mode 100644 examples/dynamic-grid/src/generated/WorkOrderLine.names.ts create mode 100644 examples/dynamic-grid/src/generated/WorkOrderLine.ts create mode 100644 examples/dynamic-grid/src/served.ts create mode 100644 examples/dynamic-grid/src/server/app.ts create mode 100644 examples/dynamic-grid/src/server/business-rules.ts create mode 100644 examples/dynamic-grid/src/server/client-bundle.ts create mode 100644 examples/dynamic-grid/src/server/list-query.ts create mode 100644 examples/dynamic-grid/src/server/main.ts create mode 100644 examples/dynamic-grid/src/server/routes.ts create mode 100644 examples/dynamic-grid/src/server/runtime.ts create mode 100644 examples/dynamic-grid/src/server/seed.ts create mode 100644 examples/dynamic-grid/src/server/write-checks.ts create mode 100644 examples/dynamic-grid/test/app.test.tsx create mode 100644 examples/dynamic-grid/test/client-helpers.tsx create mode 100644 examples/dynamic-grid/test/helpers.ts create mode 100644 examples/dynamic-grid/test/jsdom.d.ts create mode 100644 examples/dynamic-grid/test/list-allowlist.test.ts create mode 100644 examples/dynamic-grid/test/live-reload.test.ts create mode 100644 examples/dynamic-grid/test/meta-form.test.tsx create mode 100644 examples/dynamic-grid/test/meta-grid.test.tsx create mode 100644 examples/dynamic-grid/test/no-sql-from-request.test.ts create mode 100644 examples/dynamic-grid/test/pagination.test.ts create mode 100644 examples/dynamic-grid/test/setup.ts create mode 100644 examples/dynamic-grid/test/write-contract.test.ts create mode 100644 examples/dynamic-grid/tsconfig.json create mode 100644 server/typescript/packages/runtime-ts/test/fastify/mount-delete.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 0132e8bd3e..c6099333ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -82,6 +82,16 @@ here.** to build and test it, and the preview scope of `cargo meta`; the crates.io name `cargo-meta` is held by an unrelated crate, so the CLI crate will publish under another name that installs a `cargo-meta` binary (a plan, not a promise). Nothing is published. +- **Example and write-up: metadata-driven grids, forms and routes in TypeScript.** + `examples/dynamic-grid/` serves and renders every entity of a model from the loaded + metadata: one grid component and one form component that take an entity name and read the + rest from `GET /_meta`, and one Fastify mount over `ObjectManager`, on SQLite. The only + generated code is the types and name constants its hand-written business rules use. + Editing the metadata changes the grid, the form and the API with no regeneration. + `docs/features/metadata-driven-runtime.md` measures it against the reference generators + for the same model (1,781 hand-written lines paid once, against 3,629 generated lines + that grow by about 726 an entity), gives the per-row cost of the metadata lookups, and + lists what the approach cannot do. It is an example on the TypeScript port, not a package. ### Changed @@ -96,6 +106,11 @@ here.** ### Fixed +- **Fix, TypeScript: `DELETE` on a missing row answers `404`, not `500`, from the + ObjectManager route mount.** `mountCrudRoutes` and `mountDeleteRoute` in + `@metaobjectsdev/runtime-ts/fastify` called `ObjectManager.delete` in its default mode, which + throws for a row that is not there, so the request ended as `500 {"error":"internal"}`. They + now answer `404 {"error":"not_found"}`, as the update route and the generated routes do. - **Fix, Java, Kotlin and Python: `Names` has no entry for a derived field with no column.** The TypeScript and C# names generators already left out a derived (`origin.*`) field of an entity read from its table; Java, Kotlin and Python still emitted a column constant diff --git a/bun.lock b/bun.lock index 70203375a5..985f139383 100644 --- a/bun.lock +++ b/bun.lock @@ -111,6 +111,43 @@ "@tanstack/react-query", ], }, + "examples/dynamic-grid": { + "name": "@metaobjectsdev/example-dynamic-grid", + "version": "0.0.0", + "dependencies": { + "@hookform/resolvers": "^3.10.0", + "@libsql/kysely-libsql": "^0.4.1", + "@metaobjectsdev/metadata": "workspace:*", + "@metaobjectsdev/migrate-ts": "workspace:*", + "@metaobjectsdev/react": "workspace:*", + "@metaobjectsdev/runtime-ts": "workspace:*", + "@metaobjectsdev/runtime-web": "workspace:*", + "@metaobjectsdev/sdk": "workspace:*", + "@metaobjectsdev/tanstack": "workspace:*", + "@tanstack/react-table": "^8.20.0", + "fastify": "^5.6.2", + "kysely": "^0.27.0", + "qs": "^6.13.0", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "react-hook-form": "^7.54.0", + "zod": "^4.4.3", + }, + "devDependencies": { + "@metaobjectsdev/cli": "workspace:*", + "@metaobjectsdev/codegen-ts": "workspace:*", + "@metaobjectsdev/codegen-ts-react": "workspace:*", + "@metaobjectsdev/codegen-ts-tanstack": "workspace:*", + "@testing-library/dom": "^10.0.0", + "@testing-library/react": "^16.0.0", + "@types/node": "^22.0.0", + "@types/qs": "^6.9.0", + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "jsdom": "^29.1.1", + "typescript": "^5.6.0", + }, + }, "server/typescript/packages/ai-runtime": { "name": "@metaobjectsdev/ai-runtime", "version": "1.3.0", @@ -731,6 +768,8 @@ "@metaobjectsdev/docs-site": ["@metaobjectsdev/docs-site@workspace:server/typescript/packages/docs-site"], + "@metaobjectsdev/example-dynamic-grid": ["@metaobjectsdev/example-dynamic-grid@workspace:examples/dynamic-grid"], + "@metaobjectsdev/forge": ["@metaobjectsdev/forge@workspace:server/typescript/packages/forge"], "@metaobjectsdev/integration-tests": ["@metaobjectsdev/integration-tests@workspace:server/typescript/packages/integration-tests"], @@ -877,6 +916,8 @@ "@types/react": ["@types/react@19.3.0", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="], + "@types/react-dom": ["@types/react-dom@19.3.0", "", { "peerDependencies": { "@types/react": "^19.3.0" } }, "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q=="], + "@types/ws": ["@types/ws@8.18.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w=="], "@visx/curve": ["@visx/curve@4.0.1-alpha.0", "", { "dependencies": { "@visx/vendor": "4.0.0-alpha.0" } }, "sha512-jRu61Uz274pV1zyioXmboyrLutYbnKsgjj4njSGCnhdXj5GkZvZbg+ThDb6oOzoAnJOBRLz4rzPlWvNJOzuVMg=="], @@ -1471,7 +1512,7 @@ "underscore": ["underscore@1.13.8", "", {}, "sha512-DXtD3ZtEQzc7M8m4cXotyHR+FAS18C64asBYY5vqZexfYryNNnDc02W4hKg3rdQuqOYas1jkseX0+nZXjTXnvQ=="], - "undici": ["undici@7.14.0", "", {}, "sha512-Vqs8HTzjpQXZeXdpsfChQTlafcMQaaIwnGwLam1wudSSjlJeQ3bw1j+TLPePgrCnCpUXx7Ba5Pdpf5OBih62NQ=="], + "undici": ["undici@7.30.2", "", {}, "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA=="], "undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="], @@ -1543,12 +1584,42 @@ "@libsql/kysely-libsql/@libsql/client": ["@libsql/client@0.8.1", "", { "dependencies": { "@libsql/core": "^0.8.1", "@libsql/hrana-client": "^0.6.2", "js-base64": "^3.7.5", "libsql": "^0.3.10", "promise-limit": "^2.7.0" } }, "sha512-xGg0F4iTDFpeBZ0r4pA6icGsYa5rG6RAG+i/iLDnpCAnSuTqEWMDdPlVseiq4Z/91lWI9jvvKKiKpovqJ1kZWA=="], + "@metaobjectsdev/cli/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + + "@metaobjectsdev/codegen-ts/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + "@metaobjectsdev/codegen-ts/drizzle-orm": ["drizzle-orm@0.38.4", "", { "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=4", "@electric-sql/pglite": ">=0.2.0", "@libsql/client": ">=0.10.0", "@libsql/client-wasm": ">=0.10.0", "@neondatabase/serverless": ">=0.10.0", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", "@planetscale/database": ">=1", "@prisma/client": "*", "@tidbcloud/serverless": "*", "@types/better-sqlite3": "*", "@types/pg": "*", "@types/react": ">=18", "@types/sql.js": "*", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "better-sqlite3": ">=7", "bun-types": "*", "expo-sqlite": ">=14.0.0", "knex": "*", "kysely": "*", "mysql2": ">=2", "pg": ">=8", "postgres": ">=3", "prisma": "*", "react": ">=18", "sql.js": ">=1", "sqlite3": ">=5" }, "optionalPeers": ["@aws-sdk/client-rds-data", "@cloudflare/workers-types", "@electric-sql/pglite", "@libsql/client", "@libsql/client-wasm", "@neondatabase/serverless", "@op-engineering/op-sqlite", "@opentelemetry/api", "@planetscale/database", "@prisma/client", "@tidbcloud/serverless", "@types/better-sqlite3", "@types/pg", "@types/react", "@types/sql.js", "@vercel/postgres", "@xata.io/client", "better-sqlite3", "bun-types", "expo-sqlite", "knex", "kysely", "mysql2", "pg", "postgres", "prisma", "react", "sql.js", "sqlite3"] }, "sha512-s7/5BpLKO+WJRHspvpqTydxFob8i1vo2rEx4pY6TGY7QSMuUfWUuzaY0DIpXCkgHOo37BaFC+SJQb99dDUXT3Q=="], "@metaobjectsdev/codegen-ts/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], + "@metaobjectsdev/codegen-ts-react/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + + "@metaobjectsdev/codegen-ts-tanstack/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + + "@metaobjectsdev/conformance/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + + "@metaobjectsdev/docs-site/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + + "@metaobjectsdev/metadata/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + + "@metaobjectsdev/migrate-ts/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + + "@metaobjectsdev/react/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + + "@metaobjectsdev/render/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + "@metaobjectsdev/runtime-ts/@libsql/client": ["@libsql/client@0.15.15", "", { "dependencies": { "@libsql/core": "^0.15.14", "@libsql/hrana-client": "^0.7.0", "js-base64": "^3.7.5", "libsql": "^0.5.22", "promise-limit": "^2.7.0" } }, "sha512-twC0hQxPNHPKfeOv3sNT6u2pturQjLcI+CnpTM0SjRpocEGgfiZ7DWKXLNnsothjyJmDqEsBQJ5ztq9Wlu470w=="], + "@metaobjectsdev/runtime-ts/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + + "@metaobjectsdev/runtime-web/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + + "@metaobjectsdev/sdk/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + + "@metaobjectsdev/tanstack/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + + "@metaobjectsdev/test-generators/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + "@prisma/dev/@electric-sql/pglite": ["@electric-sql/pglite@0.4.3", "", {}, "sha512-ichuWTgtd4mOM1G4SpyGJa5trT03lWbMypDV0fUXUCXg5hiHqVAz/bZyV68NqmkLB7WcYmj1RMJVSp8HV/v/ZQ=="], "@prisma/dev/find-my-way": ["find-my-way@9.7.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-querystring": "^1.0.0", "safe-regex2": "^5.0.0" } }, "sha512-f2JHn75x2JlwUwLenZypgczR7YWMb/uO9BvUXtus+JMgkbIkLADd38cI4EiV+OQqrGo1Zlq6V8wnqMJ8e62wUQ=="], @@ -1581,7 +1652,7 @@ "jsdom/lru-cache": ["lru-cache@11.5.3", "", {}, "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg=="], - "jsdom/undici": ["undici@7.30.2", "", {}, "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA=="], + "miniflare/undici": ["undici@7.14.0", "", {}, "sha512-Vqs8HTzjpQXZeXdpsfChQTlafcMQaaIwnGwLam1wudSSjlJeQ3bw1j+TLPePgrCnCpUXx7Ba5Pdpf5OBih62NQ=="], "miniflare/zod": ["zod@3.22.3", "", {}, "sha512-EjIevzuJRiRPbVH4mGc8nApb/lVLKVpmUhAaR5R5doKGfAnGJ6Gr3CViAVjP+4FWSxCsybeWQdcgCtbX+7oZug=="], diff --git a/docs/README.md b/docs/README.md index f09826a23c..df0a41fe2d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -50,6 +50,7 @@ docs/ │ ├── cube-export.md # the cube-model generator: reporting vocabulary as Cube data-model files (FR-044) │ ├── explorer-data.md # explorer.json and its inputs: export --effective, the verify ledger rows, manifest provenance │ ├── explorer-site.md # the model explorer site docsSiteFile() builds from explorer.json +│ ├── metadata-driven-runtime.md # one grid, one form and one route mount for every entity, read from the loaded metadata (TypeScript example, measured) │ └── own-your-codegen.md # scaffold-and-own generator ownership (ADR-0034) └── ports/ # one file per language/framework port ├── typescript.md @@ -92,6 +93,7 @@ this tree is documentation, not the source of truth. | Know which feature is supported in which port today | the capability matrix in the root [`README.md`](../README.md) or the per-port "Capability snapshot" table | | See which conformance fixtures gate each feature (and which port passes which) | [`CONFORMANCE.md`](CONFORMANCE.md) | | See a worked, non-toy model end to end (projections, value objects, TPH, prompt payloads on one runnable spine) | [`../examples/advanced-modeling/`](../examples/advanced-modeling/) | +| Serve and render every entity from the loaded metadata instead of generating a route, grid and form per entity (TypeScript; one grid and one form component, measured against the generators, with what it cannot do) | [`features/metadata-driven-runtime.md`](features/metadata-driven-runtime.md), [`../examples/dynamic-grid/`](../examples/dynamic-grid/) | | Read the canonical spec (target-agnostic) | [`../spec/`](../spec/) | | Find a release recipe (Cloudflare D1, etc.) | [`recipes/`](recipes/) | | Keep drizzle-kit migrations while MetaObjects owns the model | [`recipes/drizzle-kit-migrations.md`](recipes/drizzle-kit-migrations.md) | diff --git a/docs/features/metadata-driven-runtime.md b/docs/features/metadata-driven-runtime.md new file mode 100644 index 0000000000..633b3d89d3 --- /dev/null +++ b/docs/features/metadata-driven-runtime.md @@ -0,0 +1,290 @@ +# Metadata-driven grids, forms and routes (TypeScript) + +Most of MetaObjects turns metadata into code at build time. This page is about the other +way to use the same metadata: load it when the application starts and let one mechanism +serve and render every entity from it, with no code generated per entity. + +[`examples/dynamic-grid/`](../../examples/dynamic-grid/) is a runnable proof of that, in +TypeScript: + +- `` lists any entity. Columns, labels, page size, initial + sort, which fields filter and sort, and with which operators, are read from the model. +- `` creates a row of any entity, and with `id` edits one. + Every control is chosen from the field's metadata. +- One Fastify mount serves `GET`, `POST`, `PATCH`, `PUT` and `DELETE` for every entity, + through `ObjectManager`. + +It is an example, not a package. Nothing on this page ships in `@metaobjectsdev/*`, and it +runs on the TypeScript port only. [What this path cannot do](#what-this-path-cannot-do) +is as much the point of the page as the numbers are. + +## What is generated, and what is not + +The example keeps exactly one kind of generated code: what hand-written logic is typed +against. Its `metaobjects.config.ts` wires two generators and nothing else. + +```ts +export default defineConfig({ + targets: { default: { outDir: "src/generated", outputLayout: "flat", runtime: false } }, + generators: [entityFile(), namesFile()], +}); +``` + +`runtime: false` makes the output contract-only: TypeScript types and Zod schemas, with no +Drizzle table. `namesFile()` adds the name constants. A business rule is then written +against them, so renaming a field in the metadata and regenerating breaks the rule at +compile time, not in production: + +```ts +export const doneNeedsTechnician: WriteRule = ({ entity, next }) => { + if (entity !== WorkOrderNames.name) return []; + const order = next as Partial; + if (order.status !== DONE || (order.technicianId !== undefined && order.technicianId !== null)) return []; + return [{ path: [WorkOrderNames.fields.technicianId.name], code: RULE_DONE_NEEDS_TECHNICIAN, message: "Assign a technician before marking the work order done." }]; +}; +``` + +No route, query helper, hook, grid or form is generated. Those are the layers that say the +same thing for every entity, and they are the ones read from the model at runtime. + +## How it works + +``` +metaobjects/*.yaml ── loadMemory ──> MetaRoot ──┬── ObjectManager (Kysely, SQLite) + ├── one route mount /api/:collection[/:id] + └── GET /api/_meta (the effective model) + │ +browser: loadMetaModel(/_meta) ── buildGrid ── / ── /api/:collection +``` + +**The server** mounts five handlers once, with a `:collection` parameter. Each asks the +loaded model what that collection is: which entity, which fields a body may carry, which +fields a list may be filtered and sorted on, how large a page may be. The handlers read +the current model on every request, so replacing the model needs no route to be registered +again. + +**The browser** fetches [`GET /_meta`](metadata-api.md) and reads it with `loadMetaModel` +and `buildGrid` from `@metaobjectsdev/runtime-web`. The table itself is `EntityGrid` from +`@metaobjectsdev/tanstack`, the same component the generated grids render with. What +differs is where its columns come from. No UI library was added. + +What each component takes from the model: + +| From the metadata | Grid | Form | +|---|---|---| +| `layout.dataGrid` `@columns`, `@pageSize`, `@defaultSortField`, `@defaultSortOrder`, `@filterable` | columns, page size, first sort, whether a filter bar shows | | +| Field subtype | how a cell is drawn (a decimal at its `@scale`, a boolean as Yes or No, an enum as a label) | which control: text, number, decimal text, date, checkbox, select | +| `@filterable` and the subtype's operator band (`opsForField`) | the fields and operators the filter bar offers | | +| `@sortable` | whether a header sorts | | +| `field.enum` `@values` | the filter's choices | the select's options | +| `identity.reference` | the cell shows the row it points at; the filter picks one | a select of the rows it may point at | +| `field.object` to an `object.value` | members joined in one cell | a group of the value object's own controls | +| `field.currency` `@currency`, `view.currency` `@locale` | formatted money | `CurrencyInput`, held in minor units | +| `view.textarea` `@rows` | | a textarea | +| `@required`, `@maxLength`, `validator.numeric` `@min`/`@max`, `@default` | | required marks, input limits, starting values | +| `relationship.*` with `@cardinality: many` | | the related rows listed beside the row being edited | +| `view.password`, `@formExclude` | | no control: no request may set the field | + +## Run it + +```bash +bun install # once, at the repository root +cd examples/dynamic-grid +bun run dev # http://127.0.0.1:4310 +``` + +It needs no database server. The dev server creates a SQLite file in the scratch +directory, brings its schema up to the model, seeds a few rows and removes the file when it +stops. + +Now change the model while the page is open. In `metaobjects/meta.workshop.yaml`, add a +field to `Part` and put it in the grid: + +```yaml + - field.int: { name: warrantyMonths, filterable: true } + # ... + - layout.dataGrid: + columns: [sku, name, unitPriceCents, stockQty, discontinued, warrantyMonths] +``` + +Save. The server reloads the model, adds the column to the scratch database, and the open +page shows the new column, offers it in the filter bar and adds a number input to the +form. `meta gen` was not run and no file under `src/` changed. Restarting the server does +the same from an empty database. + +## Safety + +A route that serves whatever the model declares has to refuse everything the model does +not. The mount answers with the wire contract the generated routes use +([api-contract.md](api-contract.md)): the same paths, status codes and error bodies. Each +rule below has tests in `examples/dynamic-grid/test/`. + +| Rule | Behaviour | Test file | +|---|---|---| +| Filter allowlist | Only a `@filterable` field filters, and only with the operators of its subtype. Anything else is `400 invalid_filter_field` or `invalid_filter_op`, with the allowed list. | `list-allowlist.test.ts` | +| Sort allowlist | Only a sortable field sorts. Anything else is `400 invalid_sort`. | `list-allowlist.test.ts` | +| Typed filter values | A value is read against the field's subtype (a number, a real date, an enum member) before it reaches a query. A bad one is `400 invalid_filter_value`. | `list-allowlist.test.ts` | +| No SQL from request text | Field and table names in SQL come from the model through `ObjectManager`; request values are bound parameters. The test logs every statement and checks hostile request text appears in none of them. | `no-sql-from-request.test.ts` | +| Unknown fields | A body key the entity does not declare is `400 unknown_fields`, before validation, unless the project sets `api.unknownFields: "drop"`. A generated primary key, a credential and a `@formExclude` field are not settable. | `write-contract.test.ts` | +| Credentials | A field with a `view.password` is in no response and is set by no request. | `write-contract.test.ts` | +| Pagination | `api.pagination` `defaultLimit` and `maxLimit` are honoured: an oversized `limit` is `400 limit_too_large`, a bad bound `400 pagination.invalid_value`. | `pagination.test.ts` | +| Validation | The model's validators run on every write, then enum membership, real dates and value-object members, then the hand-written rules. All answer `400 validation` with one issue per field path. | `write-contract.test.ts` | +| Constraint errors | A unique or foreign-key failure is a `409` or `400` that names no table or column. | `write-contract.test.ts` | + +While building this, `DELETE` on a missing row through the `ObjectManager` route mount in +`@metaobjectsdev/runtime-ts/fastify` turned out to answer `500`. That is fixed in the +package (it answers `404`), and the example's mount does the same. + +## Measurement + +Run it yourself: `bun run measure` in the example. It runs the reference generators in +memory on the example's own metadata, counts both sides with one rule (a line is code when +it is not blank and not only a comment), and times the metadata lookups. The sizes are +exact; the timings are medians from one developer machine and move with the machine (two +runs an hour apart put the server's per-row overhead at 6.5 and 7.7 µs). + +### Size, for this model (5 entities and a value object) + +| Metadata-driven path (hand-written once, names no entity) | Files | Lines of code | +|---|---:|---:| +| Server: one route mount, the list contract, write checks, the model and its schema | 6 | 662 | +| Client: the model reader, ``, `` and their controls | 9 | 1119 | +| **The mechanism: paid once, whatever the model** | 15 | 1781 | +| **Generated and kept: types and name constants (`src/generated/`), which grow with the model** | 11 | 390 | + +| Generated path (the reference generators, same model) | Files | Lines of code | +|---|---:|---:| +| `entity`: types, Zod schemas and the Drizzle table | 6 | 1142 | +| `names`: name constants | 5 | 104 | +| `queries`: typed query helpers | 5 | 439 | +| `routes`: Fastify CRUD routes | 5 | 149 | +| `hooks`: TanStack Query hooks | 10 | 800 | +| `grid`: TanStack Table columns | 5 | 188 | +| `grid-hook`: grid state hook | 5 | 298 | +| `form`: React form component | 5 | 503 | +| `barrel`: index.ts | 1 | 6 | +| **Total, all of which grows with the model** | 47 | 3629 | + +| Not in either total | Files | Lines of code | +|---|---:|---:| +| Demo shell: the page, the dev server, seed rows | 7 | 339 | +| Hand-written business rules | 1 | 48 | + +Per entity, the generated path adds about 726 lines in 9.4 files. The metadata-driven path +adds about 78 (its types and name constants) and no hand-written code. The mechanism's +1781 lines are paid once, so the two paths are the same size at about 3 entities, and at +50 entities the generated path is about 36,000 lines against about 5,700. + +Read those numbers with four things in mind: + +- **Nobody types the generated lines.** The comparison is about how much code exists to + read in a diff, review, regenerate and keep in step with the model, not about typing. +- **The 1781 lines are hand-written, here, because no package ships them.** The generated + routes are small (149 lines) because they call helpers in `@metaobjectsdev/runtime-ts`; + the example writes its list contract out in full. Moved into a package, an adopter's + share of the mechanism would be close to zero. +- **The generated total is not a whole application either.** It leaves out the page that + mounts each grid and form and the server file that registers each route, which an + adopter writes per entity. The metadata-driven shell that does both for every entity is + the 150-line `app.tsx` in the "not in either total" table. +- **The two are not feature-identical.** The dynamic grid shows the row a foreign key + points at and has a filter bar; the generated grid shows the key and leaves the filter + UI to the adopter. The generated form validates in the browser with the generated Zod + schema; the dynamic form does not (see below). + +### Cost of reading metadata at runtime + +| What | Cost | Paid | +|---|---|---| +| Server: read and check a list query against the model (two filters, a sort, paging) | 3.0 µs | per request | +| Server: `ObjectManager.findMany`, 1000 rows of 9 columns | 9.52 ms (9.5 µs a row) | per request | +| Server: the same `SELECT` through Kysely with no metadata | 1.80 ms (1.8 µs a row) | per request | +| Server: **metadata overhead per row** (the difference) | **7.7 µs** | per row | +| Browser: build the client model from `/_meta` (5.2 KB of JSON) | 0.17 ms | once per model load | +| Browser: format 1000 rows of 7 columns from field metadata | 0.92 ms (0.9 µs a row) | per page drawn | +| Browser: the same cells as plain `String(value)` | 0.06 ms (0.1 µs a row) | per page drawn | +| Browser: **metadata overhead per row** (the difference) | **0.9 µs** | per row | + +So a page of 25 rows costs about 0.19 ms of metadata work on the server and 0.02 ms in the +browser. That is small beside a database round trip, and it is not nothing for an export of +a million rows (about 8 seconds of it). The "browser" rows were timed in Bun, not in a +browser. The raw `SELECT` returns database values as they are stored (snake-case columns, +`0`/`1` booleans, JSON as text), so part of the difference is work a hand-written query +would also have to do before a client could use the rows. + +One cost is in requests, not microseconds. To show the row a foreign key points at, the +dynamic grid fetches each distinct referenced row on the page once and keeps it for as +long as the model is loaded. The first page of work orders is one list request plus up to +seven lookups (four customers, three technicians). The generated grid shows the key and +makes none. + +## What this path cannot do + +- **No compile-time check on the UI or the route layer.** In the browser a row is + `Record`. A grid layout that names a field the entity does not have + simply has no such column; a generated grid would fail to compile. The generated hooks + give typed rows and typed query keys; this path gives neither. +- **The kept types go stale without `meta gen`.** The page follows a metadata edit at + once, but `src/generated/` does not change until `meta gen` runs. A business rule can be + compiled against a field the running model no longer has. `meta verify --codegen` catches + it; the live reload does not. +- **No ejected customisation.** A generated form can be edited by hand (the three-way merge + keeps the edit) or its generator ejected and changed. Here every entity goes through one + component, so a form that should look different for one entity means writing that screen + by hand, or adding an override mechanism the example does not have. +- **No browser-side validation from the model.** The generated form validates with the + generated Zod schema before sending. No runtime builder turns loaded metadata into that + schema, so the dynamic form checks only that a required field is filled and that a number + is a number, and shows what the server answers. A rejected value costs a round trip. +- **A fixed set of controls.** The form edits `string`, `int`, `long`, `double`, `float`, + `decimal`, `currency`, `boolean`, `date`, `enum`, a value-object `field.object` and a + foreign key. For any other subtype it says "This form has no control for field.x" and + leaves the field out of what it sends. A field that holds a list (`isArray`) is shown in + the grid and gets the same note in the form. +- **Small reference lists only.** A foreign-key select loads the first page of the + referenced entity, at most `api.pagination.maxLimit` rows. A table larger than that needs + a search picker, which is not built. +- **To-many relationships are listed only through a filterable foreign key.** A + many-to-many relationship (`@through`) is not shown. +- **Not the whole surface of the generated API.** The mount serves concrete entities with + a writable source. It does not serve projections or reports, and single-table + inheritance and many-to-many traversal routes, which the generated routes cover, were + not built or tested. +- **Not gated by the cross-port corpus.** The generated routes are run against the shared + api-contract conformance corpus in every port. This mount is tested by the example's own + suite against the same error codes, and by nothing else. +- **The live schema change is a development convenience.** On reload the example applies + additive schema changes to its own throwaway SQLite file and refuses a change that would + lose data. A real database is changed with `meta migrate`, reviewed and committed, and + this page does not suggest otherwise. +- **No authorization.** Everything served is served to everyone. Guards are the + application's to add, as they are for generated routes + ([guarding-generated-routes.md](../recipes/guarding-generated-routes.md)). + +## Other ports + +This was built and tested on the TypeScript port only, and no claim is made that another +port has an equivalent. + +- The browser half reads `/_meta` and the REST contract, which every port serves, plus one + route of the example's own (`/_served`: the collection path of each entity, the model + revision and the pagination limits). It has only been run against the TypeScript server. +- The server half stands on `ObjectManager`. Python, Java and Kotlin have metadata-driven + data access of their own, and nobody has built or tested a dynamic route mount on any of + them. +- **C# has no `ObjectManager`.** Its data access is generated EF Core code and runtime + metadata access is on the roadmap, so there is nothing for a mount like this to stand on. + +## When to use which + +Generate the layer when the code is the product: it is typed end to end, an adopter can +read it, edit it or eject its generator, and it runs with no MetaObjects package installed +for the entity and model code. + +Read the metadata at runtime when the layer is the same for every entity and nobody will +customise it per entity: an admin console, a back-office CRUD screen, a prototype whose +model changes daily. The cost is the list above. + +The example does both at once, which is the arrangement it is meant to show: generated +types and name constants under the hand-written rules, and one metadata-driven mechanism +for everything that is the same for every entity. diff --git a/examples/dynamic-grid/.metaobjects/.gen-state/.hashes.json b/examples/dynamic-grid/.metaobjects/.gen-state/.hashes.json new file mode 100644 index 0000000000..f09b981412 --- /dev/null +++ b/examples/dynamic-grid/.metaobjects/.gen-state/.hashes.json @@ -0,0 +1,37 @@ +{ + "src/generated/Address.ts": { + "hash": "a55aa3c99f720f85bd1339e2e56005b7f51e76400e3c5ddfa73b0306466d3f4b", + "generatedBy": "entity-file", + "sourceNode": "demo::workshop::Address" + }, + "src/generated/Customer.names.ts": "a59e56679a51c1b5ea4edbdea8ff6d27c30dd713f66989cc154d70bb09b53737", + "src/generated/Customer.ts": { + "hash": "29ed46747e82c3cd871345f27351a1fa3fb855712cfc372680e095a12a59a82f", + "generatedBy": "entity-file", + "sourceNode": "demo::workshop::Customer" + }, + "src/generated/Part.names.ts": "d4029bb4b23e7bc046de97ba986e909f8becbcdb91ce9d212561782cb1afa8c4", + "src/generated/Part.ts": { + "hash": "ba246077dfe64e429636c26f8778019071cea24d1012ab68ac9e90b4495538a0", + "generatedBy": "entity-file", + "sourceNode": "demo::workshop::Part" + }, + "src/generated/Technician.names.ts": "f823ad55f98a0faf76d7270693cdf1b3b5ff40ead0807b3857db7903d4a6819d", + "src/generated/Technician.ts": { + "hash": "6950505993d290cfed87f937ccb18c482a3b855314dec92ded3494b8cd731efa", + "generatedBy": "entity-file", + "sourceNode": "demo::workshop::Technician" + }, + "src/generated/WorkOrder.names.ts": "a8af877b82ddd7e5a7d5b8cfe849e5dae68ff95a8e427f02222bf2597388da6e", + "src/generated/WorkOrder.ts": { + "hash": "2464f34a23164740444e62f1ec619e0dea2b843d6a67c9eb46545404785e1308", + "generatedBy": "entity-file", + "sourceNode": "demo::workshop::WorkOrder" + }, + "src/generated/WorkOrderLine.names.ts": "863abcf330aeec349cdf3acf163c87a3e2f13d9b72d776f3c9714ada7e26c5b6", + "src/generated/WorkOrderLine.ts": { + "hash": "33fde848e1e0ad46dd807ed73cc80207885cddcb3789dd3b5810baa5f0fea9bc", + "generatedBy": "entity-file", + "sourceNode": "demo::workshop::WorkOrderLine" + } +} diff --git a/examples/dynamic-grid/.metaobjects/.gitignore b/examples/dynamic-grid/.metaobjects/.gitignore new file mode 100644 index 0000000000..fe926fbc91 --- /dev/null +++ b/examples/dynamic-grid/.metaobjects/.gitignore @@ -0,0 +1,9 @@ +# Gen-state bodies are a second full copy of all generated output — not worth +# committing. The MANIFEST is: `.hashes.json` is the only thing that lets +# `meta gen` tell "this file is exactly what I wrote" from "somebody edited +# this" on a machine that did not generate it (CLAUDE.md, Storage format). +# +# The glob matters. Git will not descend into an excluded DIRECTORY, so a +# negation under `.gen-state/` can never apply — it has to be `.gen-state/*`. +.gen-state/* +!.gen-state/.hashes.json diff --git a/examples/dynamic-grid/.metaobjects/config.json b/examples/dynamic-grid/.metaobjects/config.json new file mode 100644 index 0000000000..0dd0a187c7 --- /dev/null +++ b/examples/dynamic-grid/.metaobjects/config.json @@ -0,0 +1,7 @@ +{ + "schema_version": 1, + "sources": [], + "api": { + "pagination": { "defaultLimit": 10, "maxLimit": 50 } + } +} diff --git a/examples/dynamic-grid/README.md b/examples/dynamic-grid/README.md new file mode 100644 index 0000000000..3e02fb0ed4 --- /dev/null +++ b/examples/dynamic-grid/README.md @@ -0,0 +1,89 @@ +# Dynamic grid: one grid, one form and one route mount for every entity + +A runnable proof that an application can use the loaded metadata at runtime, with no code +generated per entity. + +- `` and `` take an entity + name and read everything else from the model the server serves at `GET /api/_meta`: + columns, types, labels, enum members, relationships, validation limits, filter operators + and sort. +- One Fastify mount (`src/server/routes.ts`) serves every entity through `ObjectManager`. +- The only generated code is what hand-written business logic is typed against: the types + and name constants in `src/generated/`, used by `src/server/business-rules.ts`. + +The write-up, the measurement against the generated path, and the list of what this +approach cannot do are in +[`docs/features/metadata-driven-runtime.md`](../../docs/features/metadata-driven-runtime.md). +This is an example on the TypeScript port. It is not a published package. + +## Run it + +```bash +bun install # once, at the repository root +cd examples/dynamic-grid +bun run dev # http://127.0.0.1:4310 (PORT=... to change it) +``` + +No database server is needed. The dev server creates a SQLite file in the scratch +directory (`$DEV_SCRATCH`, or the system temp directory), seeds it, and removes it when it +stops. + +## Change the model, watch the page change + +With the page open, edit `metaobjects/meta.workshop.yaml`: add a field, add it to a +`layout.dataGrid`'s `columns`, mark a field `filterable`, add an enum member, add an +entity. Save. The server loads the model again and the open page picks it up within a +couple of seconds. `meta gen` is not run and nothing under `src/` changes. + +An edit that would lose data (dropping a column) or a file that does not load is refused: +the server logs why and keeps serving the model it had. + +`bun run gen` regenerates `src/generated/` after a model change, which is what keeps the +business rules' types in step. The page does not need it. + +## The model + +`metaobjects/meta.workshop.yaml` is a small repair workshop: five entities and a value +object. + +| Object | What it exercises | +|---|---| +| `Customer` | a value object (`billingAddress`, an `Address` stored as JSON), an enum, a regex validator, a to-many relationship | +| `Technician` | a decimal (`hourlyRate`, 8 digits, scale 2), a date | +| `Part` | money in minor units with a `view.currency`, a numeric validator, a unique field | +| `WorkOrder` | two enums, two foreign keys, a decimal, long text with a `view.textarea`, a composition | +| `WorkOrderLine` | foreign keys to two entities | + +## Layout + +``` +metaobjects/meta.workshop.yaml the model: the only thing that names an entity +src/generated/ types and name constants (the only generated code) +src/server/ + runtime.ts load the model, sync the scratch schema, reload + routes.ts the one route mount + list-query.ts filter, sort and paging, checked against the model + write-checks.ts enum members, dates, value-object members + business-rules.ts hand-written rules, typed against src/generated/ + main.ts the dev server: serve, seed, watch the metadata +src/client/ + model.ts /_meta as the grid and the form read it + meta-grid.tsx + meta-form.tsx + controls.tsx, form-values.ts one input per field, chosen from its metadata + references.ts the row a foreign key points at + app.tsx the page: a menu of entities, a grid, a form +scripts/measure.ts the numbers in the write-up +test/ server contract tests and component tests +``` + +## Test and measure + +```bash +bun test # the route contract, the grid, the form, live reload +bun run typecheck +bun run measure # sizes against the reference generators, and lookup cost +``` + +The component tests render the real components against the real routes, `ObjectManager` +and a SQLite file, in process. diff --git a/examples/dynamic-grid/bunfig.toml b/examples/dynamic-grid/bunfig.toml new file mode 100644 index 0000000000..8755352e57 --- /dev/null +++ b/examples/dynamic-grid/bunfig.toml @@ -0,0 +1,2 @@ +[test] +preload = ["./test/setup.ts"] diff --git a/examples/dynamic-grid/metaobjects.config.ts b/examples/dynamic-grid/metaobjects.config.ts new file mode 100644 index 0000000000..fa19cf6857 --- /dev/null +++ b/examples/dynamic-grid/metaobjects.config.ts @@ -0,0 +1,18 @@ +import { defineConfig } from "@metaobjectsdev/cli"; +import { entityFile, namesFile } from "@metaobjectsdev/codegen-ts/generators"; + +// The ONLY generated code in this example: what hand-written business logic is typed +// against. `runtime: false` makes the target contract-only: TypeScript types and Zod +// schemas, with no Drizzle table and no route, hook, grid or form. `namesFile()` adds the +// name constants. Everything a user sees is rendered from the loaded metadata instead +// (src/client/), and every route is served from it (src/server/routes.ts). +export default defineConfig({ + outDir: "src/generated", + outputLayout: "flat", + extStyle: "none", + dialect: "sqlite", + targets: { + default: { outDir: "src/generated", outputLayout: "flat", runtime: false }, + }, + generators: [entityFile(), namesFile()], +}); diff --git a/examples/dynamic-grid/metaobjects/meta.workshop.yaml b/examples/dynamic-grid/metaobjects/meta.workshop.yaml new file mode 100644 index 0000000000..0daf866f98 --- /dev/null +++ b/examples/dynamic-grid/metaobjects/meta.workshop.yaml @@ -0,0 +1,169 @@ +# demo::workshop — a small repair-shop model. Nothing below is rendered by generated UI +# code: the grid and the form in src/client/ read this file (served as /_meta) at runtime, +# and the routes in src/server/ read the loaded model on every request. +# +# Edit it and restart `bun run dev` (or just save: the dev server reloads the model) and +# the grid, the form, the filters and the API change with it. Nothing is regenerated. +metadata: + package: demo::workshop + children: + # A value object: no table, no identity. Embedded in Customer as one JSON column. + - object.value: + name: Address + children: + - field.string: { name: street, required: true, maxLength: 120 } + - field.string: { name: city, required: true, maxLength: 80 } + - field.string: { name: postalCode, maxLength: 12 } + + - object.entity: + name: Customer + children: + - source.rdb: { table: customers } + - field.long: { name: id } + - field.string: { name: name, required: true, maxLength: 120, filterable: true } + - field.string: + name: email + maxLength: 320 + filterable: true + children: + - validator.regex: { name: emailFmt, pattern: "[^@\\s]+@[^@\\s]+" } + - field.enum: + name: tier + values: [standard, gold, platinum] + required: true + default: standard + filterable: true + - field.boolean: { name: active, required: true, default: true, filterable: true } + - field.object: { name: billingAddress, objectRef: Address, storage: jsonb } + - identity.primary: { name: pk, fields: id, generation: increment } + - relationship.association: { name: workOrders, objectRef: WorkOrder, cardinality: many } + - layout.dataGrid: + name: default + columns: [name, email, tier, active] + defaultSortField: name + pageSize: 10 + filterable: true + + - object.entity: + name: Technician + children: + - source.rdb: { table: technicians } + - field.long: { name: id } + - field.string: { name: name, required: true, maxLength: 120, filterable: true } + - field.enum: + name: level + values: [apprentice, journeyman, master] + required: true + filterable: true + # A decimal: exact, travels as a string, never through a double. + - field.decimal: + name: hourlyRate + precision: 8 + scale: 2 + required: true + filterable: true + - field.date: { name: hiredOn, filterable: true } + - identity.primary: { name: pk, fields: id, generation: increment } + - layout.dataGrid: + name: default + columns: [name, level, hourlyRate, hiredOn] + defaultSortField: name + pageSize: 10 + filterable: true + + - object.entity: + name: Part + children: + - source.rdb: { table: parts } + - field.long: { name: id } + - field.string: { name: sku, required: true, maxLength: 40, unique: true, filterable: true } + - field.string: { name: name, required: true, maxLength: 160, filterable: true } + - field.currency: + name: unitPriceCents + currency: USD + required: true + filterable: true + children: + - view.currency: { name: display, locale: en-US } + - field.int: + name: stockQty + required: true + default: 0 + filterable: true + children: + - validator.numeric: { name: stockNonNegative, min: 0 } + - field.boolean: { name: discontinued, required: true, default: false, filterable: true } + - identity.primary: { name: pk, fields: id, generation: increment } + - layout.dataGrid: + name: default + columns: [sku, name, unitPriceCents, stockQty, discontinued] + defaultSortField: sku + pageSize: 10 + filterable: true + + - object.entity: + name: WorkOrder + children: + - source.rdb: { table: work_orders } + - field.long: { name: id } + - field.string: { name: title, required: true, maxLength: 160, filterable: true } + - field.enum: + name: status + values: [open, in_progress, blocked, done] + required: true + default: open + filterable: true + - field.enum: + name: priority + values: [low, normal, urgent] + required: true + default: normal + filterable: true + - field.long: { name: customerId, required: true, filterable: true } + - field.long: { name: technicianId, filterable: true } + - field.decimal: { name: estimatedHours, precision: 6, scale: 2, filterable: true } + - field.date: { name: dueOn, filterable: true } + - field.string: + name: notes + maxLength: 2000 + children: + - view.textarea: { rows: 4 } + - identity.primary: { name: pk, fields: id, generation: increment } + - identity.reference: { name: refCustomer, fields: customerId, references: Customer } + - identity.reference: { name: refTechnician, fields: technicianId, references: Technician } + - relationship.composition: + name: lines + objectRef: WorkOrderLine + cardinality: many + onDelete: cascade + - layout.dataGrid: + name: default + columns: [title, status, priority, customerId, technicianId, estimatedHours, dueOn] + defaultSortField: dueOn + defaultSortOrder: desc + pageSize: 10 + filterable: true + + - object.entity: + name: WorkOrderLine + children: + - source.rdb: { table: work_order_lines } + - field.long: { name: id } + - field.long: { name: workOrderId, required: true, filterable: true } + - field.long: { name: partId, required: true, filterable: true } + - field.int: + name: quantity + required: true + default: 1 + filterable: true + children: + - validator.numeric: { name: quantityPositive, min: 1 } + - identity.primary: { name: pk, fields: id, generation: increment } + - identity.reference: { name: refWorkOrder, fields: workOrderId, references: WorkOrder } + - identity.reference: { name: refPart, fields: partId, references: Part } + - layout.dataGrid: + name: default + columns: [workOrderId, partId, quantity] + defaultSortField: workOrderId + pageSize: 10 + filterable: true diff --git a/examples/dynamic-grid/package.json b/examples/dynamic-grid/package.json new file mode 100644 index 0000000000..5741645ef6 --- /dev/null +++ b/examples/dynamic-grid/package.json @@ -0,0 +1,47 @@ +{ + "name": "@metaobjectsdev/example-dynamic-grid", + "version": "0.0.0", + "private": true, + "description": "Proof: one grid, one form and one route mount driven by the loaded metadata at runtime, on ObjectManager and SQLite. No per-entity generated UI or routes.", + "type": "module", + "scripts": { + "dev": "bun src/server/main.ts", + "gen": "meta gen", + "measure": "bun scripts/measure.ts", + "typecheck": "tsc -p tsconfig.json", + "test": "bun test" + }, + "dependencies": { + "@hookform/resolvers": "^3.10.0", + "@libsql/kysely-libsql": "^0.4.1", + "@metaobjectsdev/metadata": "workspace:*", + "@metaobjectsdev/migrate-ts": "workspace:*", + "@metaobjectsdev/react": "workspace:*", + "@metaobjectsdev/runtime-ts": "workspace:*", + "@metaobjectsdev/runtime-web": "workspace:*", + "@metaobjectsdev/sdk": "workspace:*", + "@metaobjectsdev/tanstack": "workspace:*", + "@tanstack/react-table": "^8.20.0", + "fastify": "^5.6.2", + "kysely": "^0.27.0", + "qs": "^6.13.0", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "react-hook-form": "^7.54.0", + "zod": "^4.4.3" + }, + "devDependencies": { + "@metaobjectsdev/cli": "workspace:*", + "@metaobjectsdev/codegen-ts": "workspace:*", + "@metaobjectsdev/codegen-ts-react": "workspace:*", + "@metaobjectsdev/codegen-ts-tanstack": "workspace:*", + "@testing-library/dom": "^10.0.0", + "@testing-library/react": "^16.0.0", + "@types/node": "^22.0.0", + "@types/qs": "^6.9.0", + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "jsdom": "^29.1.1", + "typescript": "^5.6.0" + } +} diff --git a/examples/dynamic-grid/scripts/measure.ts b/examples/dynamic-grid/scripts/measure.ts new file mode 100644 index 0000000000..0d8e570f33 --- /dev/null +++ b/examples/dynamic-grid/scripts/measure.ts @@ -0,0 +1,281 @@ +/** + * `bun run measure`: the numbers in docs/features/metadata-driven-runtime.md. + * + * Two questions, both answered by running code, neither by estimate: + * + * 1. Size. How much code is the metadata-driven path, against what the existing reference + * generators emit for the same model? The generators are run here, in memory, on this + * example's metadata; nothing is written. + * 2. Cost. What does reading metadata at runtime cost, per request and per row? + * + * Prints Markdown. Timings are medians and move with the machine; the sizes do not. + */ +import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, relative, resolve } from "node:path"; +import { defineConfig, runGen } from "@metaobjectsdev/codegen-ts"; +import { barrel, entityFile, namesFile, queriesFile, routesFile } from "@metaobjectsdev/codegen-ts/generators"; +import { formFile } from "@metaobjectsdev/codegen-ts-react"; +import { tanstackGrid, tanstackGridHook, tanstackQuery } from "@metaobjectsdev/codegen-ts-tanstack"; +import type { Generator } from "@metaobjectsdev/codegen-ts"; +import { loadMemory } from "@metaobjectsdev/sdk"; +import { buildClientModel, type ClientModel } from "../src/client/model"; +import { displayValue } from "../src/client/format"; +import { WorkOrderNames } from "../src/generated/WorkOrder.names"; +import type { WorkOrder } from "../src/generated/WorkOrder"; +import { API_PREFIX, buildApp } from "../src/server/app"; +import { readListQuery } from "../src/server/list-query"; +import { openRuntime } from "../src/server/runtime"; +import { seed } from "../src/server/seed"; +import { SERVED_ROUTE_PATH, type ServedInfo } from "../src/served"; + +const PROJECT_DIR = resolve(import.meta.dir, ".."); +const SRC = join(PROJECT_DIR, "src"); + +// --------------------------------------------------------------------------------------- +// Size +// --------------------------------------------------------------------------------------- + +/** Lines that are code: not blank, and not only a comment. The same rule for both sides. */ +function codeLines(text: string): number { + let inBlock = false; + let count = 0; + for (const raw of text.split("\n")) { + const line = raw.trim(); + if (inBlock) { + if (line.includes("*/")) inBlock = false; + continue; + } + if (line === "" || line.startsWith("//")) continue; + if (line.startsWith("/*")) { + if (!line.includes("*/")) inBlock = true; + continue; + } + count++; + } + return count; +} + +interface Size { + readonly files: number; + readonly lines: number; +} +const sizeOf = (texts: readonly string[]): Size => ({ files: texts.length, lines: texts.reduce((sum, text) => sum + codeLines(text), 0) }); +const add = (a: Size, b: Size): Size => ({ files: a.files + b.files, lines: a.lines + b.lines }); +const read = (...parts: string[]): string => readFileSync(join(SRC, ...parts), "utf8"); + +/** + * The metadata-driven path, by what each file is for. Every file under src/ is in exactly + * one group, which `assertEveryFileCounted` checks, so a file added later cannot go missing + * from the table. + */ +const DYNAMIC_GROUPS: readonly { readonly label: string; readonly mechanism: boolean; readonly files: readonly string[] }[] = [ + { + label: "Server: one route mount, the list contract, write checks, the model and its schema", + mechanism: true, + files: ["server/app.ts", "server/routes.ts", "server/list-query.ts", "server/write-checks.ts", "server/runtime.ts", "served.ts"], + }, + { + label: "Client: the model reader, ``, `` and their controls", + mechanism: true, + files: [ + "client/api.ts", "client/model.ts", "client/context.tsx", "client/format.ts", "client/references.ts", + "client/form-values.ts", "client/controls.tsx", "client/meta-grid.tsx", "client/meta-form.tsx", + ], + }, + { + label: "Demo shell: the page, the dev server, seed rows", + mechanism: false, + files: ["client/app.tsx", "client/main.tsx", "client/index.html", "client/app.css", "server/main.ts", "server/client-bundle.ts", "server/seed.ts"], + }, + { label: "Hand-written business rules", mechanism: false, files: ["server/business-rules.ts"] }, +]; + +function filesUnder(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => + entry.isDirectory() ? filesUnder(join(dir, entry.name)) : [relative(SRC, join(dir, entry.name))], + ); +} + +function assertEveryFileCounted(): void { + const counted = new Set(DYNAMIC_GROUPS.flatMap((group) => group.files)); + const uncounted = filesUnder(SRC).filter((file) => !file.startsWith("generated/") && !counted.has(file)); + if (uncounted.length > 0) throw new Error(`src/ files in no measurement group: ${uncounted.join(", ")}`); +} + +/** + * The reference generators that write what the metadata-driven path does at runtime, in + * dependency order: each is run after the ones before it, and its files are the ones the + * run gained. + */ +const GENERATED_STACK: readonly { readonly label: string; readonly generator: () => Generator; readonly kept?: true }[] = [ + { label: "`entity`: types, Zod schemas and the Drizzle table", generator: () => entityFile() }, + { label: "`names`: name constants", generator: () => namesFile(), kept: true }, + { label: "`queries`: typed query helpers", generator: () => queriesFile() }, + { label: "`routes`: Fastify CRUD routes", generator: () => routesFile() }, + { label: "`hooks`: TanStack Query hooks", generator: () => tanstackQuery() }, + { label: "`grid`: TanStack Table columns", generator: () => tanstackGrid() }, + { label: "`grid-hook`: grid state hook", generator: () => tanstackGridHook() }, + { label: "`form`: React form component", generator: () => formFile() }, + { label: "`barrel`: index.ts", generator: () => barrel() }, +]; + +async function generatedSizes(): Promise<{ label: string; size: Size; kept: boolean }[]> { + const metadata = await loadMemory(PROJECT_DIR); + // A dry run renders in memory and touches no file. The directory only gives the run a + // project root that is not this example, whose own generated state it must not read. + const scratch = mkdtempSync(join(process.env["DEV_SCRATCH"] ?? tmpdir(), "dynamic-grid-measure-")); + try { + const seen = new Set(); + const sizes: { label: string; size: Size; kept: boolean }[] = []; + for (let i = 0; i < GENERATED_STACK.length; i++) { + const step = GENERATED_STACK[i]; + if (step === undefined) continue; + const result = await runGen({ + config: defineConfig({ + outDir: "generated", + outputLayout: "flat", + extStyle: "none", + dialect: "sqlite", + dbImport: "../db", + generators: GENERATED_STACK.slice(0, i + 1).map((s) => s.generator()), + }), + metadata, + projectRoot: scratch, + dryRun: true, + }); + const rendered = result.rendered; + if (rendered === undefined) throw new Error("the dry run returned no rendered files"); + const gained = [...rendered].filter(([path]) => !seen.has(path)); + for (const [path] of gained) seen.add(path); + sizes.push({ label: step.label, size: sizeOf(gained.map(([, text]) => text)), kept: step.kept === true }); + } + return sizes; + } finally { + rmSync(scratch, { recursive: true, force: true }); + } +} + +// --------------------------------------------------------------------------------------- +// Cost +// --------------------------------------------------------------------------------------- + +/** The median time of `run`, in milliseconds, over `rounds` timed rounds after a warm-up. */ +async function medianMs(rounds: number, run: () => unknown | Promise): Promise { + for (let i = 0; i < 3; i++) await run(); + const times: number[] = []; + for (let i = 0; i < rounds; i++) { + const started = performance.now(); + await run(); + times.push(performance.now() - started); + } + times.sort((a, b) => a - b); + return times[Math.floor(times.length / 2)] ?? Number.NaN; +} + +const ROWS = 1000; + +async function costs(): Promise { + const runtime = await openRuntime({ projectDir: PROJECT_DIR }); + try { + const { om, served } = runtime.current(); + await seed(om); + const workOrder = served.get("work_orders"); + if (workOrder === undefined) throw new Error("the model serves no work_orders"); + + // A table big enough that a page of it is a real page: copies of one seeded work order. + const template = (await om.findById(WorkOrderNames.name, 1)) as (WorkOrder & { id?: number }) | null; + if (template === null) throw new Error("the seed has no work order 1"); + const { id: _id, ...copy } = template; + await om.createMany(WorkOrderNames.name, Array.from({ length: ROWS }, () => ({ ...copy }))); + + // Server, per request: reading the query against the model (allowlists, operators, values). + const query = { filter: { status: { in: "open,blocked" }, dueOn: { gte: "2026-01-01" } }, sort: "dueOn:desc", limit: "25", offset: "50" }; + const PARSES = 2000; + const parseMs = await medianMs(15, () => { + for (let i = 0; i < PARSES; i++) readListQuery(workOrder, query, undefined); + }); + + // Server, per row: the ObjectManager against the same SELECT written by hand. The + // difference is what resolving columns and codecs from metadata costs. + const table = WorkOrderNames.sources.primary.table; + const omMs = await medianMs(15, () => om.findMany(WorkOrderNames.name, {}, { limit: ROWS })); + const rawMs = await medianMs(15, () => runtime.db.selectFrom(table).selectAll().limit(ROWS).execute()); + + // Client, once per model load, and per cell. (Run here, in Bun, not in a browser.) + const app = buildApp({ runtime }); + const meta: unknown = JSON.parse((await app.inject({ method: "GET", url: `${API_PREFIX}/_meta` })).body); + const metaBytes = Buffer.byteLength(JSON.stringify(meta)); + const info = JSON.parse((await app.inject({ method: "GET", url: `${API_PREFIX}${SERVED_ROUTE_PATH}` })).body) as ServedInfo; + await app.close(); + const buildMs = await medianMs(15, () => buildClientModel(meta, info)); + const model: ClientModel = buildClientModel(meta, info); + const entity = model.entity(WorkOrderNames.name); + if (entity === undefined) throw new Error("the client model has no WorkOrder"); + const rows = await om.findMany(WorkOrderNames.name, {}, { limit: ROWS }); + const columns = entity.grid.columns.flatMap((column) => entity.field(column.field) ?? []); + const cellsMs = await medianMs(15, () => { + for (const row of rows) for (const field of columns) displayValue(field, row[field.name]); + }); + // The same cells with no metadata in the loop: what a generated column's accessor does. + const plainMs = await medianMs(15, () => { + for (const row of rows) for (const field of columns) String(row[field.name] ?? ""); + }); + + const us = (ms: number): string => `${(ms * 1000).toFixed(1)} µs`; + const perRow = (ms: number): string => us(ms / ROWS); + return [ + "| What | Cost | Paid |", + "|---|---|---|", + `| Server: read and check a list query against the model (two filters, a sort, paging) | ${us(parseMs / PARSES)} | per request |`, + `| Server: \`ObjectManager.findMany\`, ${ROWS} rows of 9 columns | ${omMs.toFixed(2)} ms (${perRow(omMs)} a row) | per request |`, + `| Server: the same \`SELECT\` through Kysely with no metadata | ${rawMs.toFixed(2)} ms (${perRow(rawMs)} a row) | per request |`, + `| Server: **metadata overhead per row** (the difference) | **${perRow(omMs - rawMs)}** | per row |`, + `| Browser: build the client model from \`/_meta\` (${(metaBytes / 1024).toFixed(1)} KB of JSON) | ${buildMs.toFixed(2)} ms | once per model load |`, + `| Browser: format ${ROWS} rows of ${columns.length} columns from field metadata | ${cellsMs.toFixed(2)} ms (${perRow(cellsMs)} a row) | per page drawn |`, + `| Browser: the same cells as plain \`String(value)\` | ${plainMs.toFixed(2)} ms (${perRow(plainMs)} a row) | per page drawn |`, + `| Browser: **metadata overhead per row** (the difference) | **${perRow(cellsMs - plainMs)}** | per row |`, + ]; + } finally { + await runtime.close(); + } +} + +// --------------------------------------------------------------------------------------- + +assertEveryFileCounted(); + +const generated = await generatedSizes(); +const keptGenerated = sizeOf(filesUnder(join(SRC, "generated")).map((file) => read(file))); +const dynamic = DYNAMIC_GROUPS.map((group) => ({ ...group, size: sizeOf(group.files.map((file) => read(file))) })); +const mechanism = dynamic.filter((group) => group.mechanism).reduce((sum, group) => add(sum, group.size), { files: 0, lines: 0 }); +const generatedTotal = generated.reduce((sum, row) => add(sum, row.size), { files: 0, lines: 0 }); +// One names file per entity (a value object has types but no names file). +const entityCount = filesUnder(join(SRC, "generated")).filter((file) => file.endsWith(".names.ts")).length; + +const row = (label: string, size: Size): string => `| ${label} | ${size.files} | ${size.lines} |`; +const out: string[] = []; +out.push(`### Size, for this model (${entityCount} entities and a value object)`, ""); +out.push("| Metadata-driven path (hand-written once, names no entity) | Files | Lines of code |", "|---|---:|---:|"); +for (const group of dynamic.filter((g) => g.mechanism)) out.push(row(group.label, group.size)); +out.push(row("**The mechanism: paid once, whatever the model**", mechanism)); +out.push(row("**Generated and kept: types and name constants (`src/generated/`), which grow with the model**", keptGenerated)); +out.push(""); +out.push("| Generated path (the reference generators, same model) | Files | Lines of code |", "|---|---:|---:|"); +for (const item of generated) out.push(row(item.label, item.size)); +out.push(row("**Total, all of which grows with the model**", generatedTotal)); +out.push(""); +out.push("| Not in either total | Files | Lines of code |", "|---|---:|---:|"); +for (const group of dynamic.filter((g) => !g.mechanism)) out.push(row(group.label, group.size)); +out.push(""); +const perObject = generatedTotal.lines / entityCount; +const keptPerObject = keptGenerated.lines / entityCount; +out.push( + `Per entity, the generated path adds about ${Math.round(perObject)} lines in ${(generatedTotal.files / entityCount).toFixed(1)} files; ` + + `the metadata-driven path adds about ${Math.round(keptPerObject)} (its types and name constants) and no hand-written code. ` + + `The mechanism's ${mechanism.lines} lines are paid once, so the two paths are the same size at about ` + + `${Math.ceil(mechanism.lines / (perObject - keptPerObject))} entities.`, +); +out.push("", "### Cost of reading metadata at runtime", ""); +out.push(...(await costs())); +console.log(out.join("\n")); diff --git a/examples/dynamic-grid/src/client/api.ts b/examples/dynamic-grid/src/client/api.ts new file mode 100644 index 0000000000..599d8147f8 --- /dev/null +++ b/examples/dynamic-grid/src/client/api.ts @@ -0,0 +1,77 @@ +/** + * Transport, and the two things every component does with a server answer: read a + * refusal's body, and turn a `validation` 400 into messages keyed by field. + */ +import type { EntityFetcher } from "@metaobjectsdev/runtime-web"; +import { SERVED_ROUTE_PATH, type ServedInfo } from "../served"; +import { buildClientModel, type ClientModel } from "./model"; + +/** A plain row, as the API returns it. */ +export type Row = Record; + +/** The server said no. `body` is its JSON answer, e.g. `{ error: "validation", issues: [...] }`. */ +export class ApiError extends Error { + constructor( + public readonly status: number, + public readonly body: unknown, + ) { + super(`The server answered ${status}: ${JSON.stringify(body)}`); + this.name = "ApiError"; + } +} + +/** `fetch`, as JSON, throwing `ApiError` for any answer that is not a success. */ +export const jsonFetcher: EntityFetcher = async (path: string, init?: RequestInit): Promise => { + const response = await fetch(path, { + ...init, + headers: { ...(init?.body !== undefined ? { "content-type": "application/json" } : {}), ...init?.headers }, + }); + const text = await response.text(); + const body: unknown = text === "" ? undefined : JSON.parse(text); + if (!response.ok) throw new ApiError(response.status, body); + return body as T; +}; + +const META_ROUTE_PATH = "/_meta"; + +/** Fetch the model document and where it is served, and build the browser model from them. */ +export async function loadClientModel(fetcher: EntityFetcher): Promise { + const [document, served] = await Promise.all([fetcher(META_ROUTE_PATH), fetcher(SERVED_ROUTE_PATH)]); + return buildClientModel(document, served); +} + +export async function servedRevision(fetcher: EntityFetcher): Promise { + return (await fetcher(SERVED_ROUTE_PATH)).revision; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** One line a person can read, for a refusal that is not about a particular field. */ +export function describeError(error: unknown): string { + if (!(error instanceof ApiError)) return error instanceof Error ? error.message : String(error); + const body = error.body; + if (!isRecord(body)) return `The server answered ${error.status}.`; + const allowed = Array.isArray(body["allowed"]) ? ` Allowed: ${body["allowed"].join(", ")}.` : ""; + const detail = Object.entries(body) + .filter(([key, value]) => key !== "error" && key !== "allowed" && key !== "issues" && typeof value !== "object") + .map(([key, value]) => `${key} ${String(value)}`) + .join(", "); + return `${String(body["error"])}${detail === "" ? "" : ` (${detail})`}.${allowed}`; +} + +/** + * The issues of a `validation` 400, by field path (`quantity`, `billingAddress.city`), or + * undefined when the error is something else. + */ +export function validationIssues(error: unknown): Map | undefined { + if (!(error instanceof ApiError) || !isRecord(error.body) || !Array.isArray(error.body["issues"])) return undefined; + const byPath = new Map(); + for (const issue of error.body["issues"]) { + if (!isRecord(issue)) continue; + const path = Array.isArray(issue["path"]) ? issue["path"].join(".") : ""; + if (!byPath.has(path)) byPath.set(path, String(issue["message"])); + } + return byPath; +} diff --git a/examples/dynamic-grid/src/client/app.css b/examples/dynamic-grid/src/client/app.css new file mode 100644 index 0000000000..471ed20db9 --- /dev/null +++ b/examples/dynamic-grid/src/client/app.css @@ -0,0 +1,38 @@ +:root { + color-scheme: light dark; + --line: color-mix(in srgb, currentColor 18%, transparent); + --soft: color-mix(in srgb, currentColor 6%, transparent); + --accent: #2f6fde; + font: 15px/1.45 system-ui, sans-serif; +} +body { margin: 0; } +button, input, select, textarea { font: inherit; } +.mo-workspace { display: grid; grid-template-columns: 11rem minmax(0, 1fr); gap: 1.5rem; padding: 1.25rem; align-items: start; } +.mo-workspace:has(> aside) { grid-template-columns: 11rem minmax(0, 1fr) minmax(20rem, 26rem); } +nav { display: grid; gap: 0.25rem; } +nav button { text-align: left; padding: 0.4rem 0.6rem; border: 0; border-radius: 6px; background: none; cursor: pointer; } +nav button[aria-current="page"] { background: var(--soft); font-weight: 600; } +header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; } +h1 { font-size: 1.35rem; margin: 0 0 0.75rem; } +h2 { font-size: 1.1rem; margin: 0 0 0.75rem; } +h3 { font-size: 1rem; margin: 0; } +table { width: 100%; border-collapse: collapse; } +th, td { text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line); white-space: nowrap; } +th { font-weight: 600; user-select: none; } +th[aria-sort] { cursor: pointer; } +tbody tr:hover { background: var(--soft); } +.mo-filters { display: flex; flex-wrap: wrap; gap: 0.4rem; margin-bottom: 0.75rem; align-items: center; } +.mo-chip { border: 1px solid var(--line); border-radius: 999px; background: var(--soft); padding: 0.15rem 0.6rem; cursor: pointer; } +.mo-pagination { display: flex; gap: 0.75rem; align-items: center; margin-top: 0.6rem; } +.mo-count { opacity: 0.7; margin: 0.5rem 0 0; } +aside { border-left: 1px solid var(--line); padding-left: 1.5rem; display: grid; gap: 1.5rem; } +.mo-form { display: grid; gap: 0.75rem; } +.mo-field { display: grid; gap: 0.2rem; } +.mo-field label, legend { font-weight: 600; font-size: 0.9rem; } +.mo-field input:not([type="checkbox"]), .mo-field select, .mo-field textarea { padding: 0.35rem 0.5rem; border: 1px solid var(--line); border-radius: 6px; } +.mo-field [aria-invalid="true"] { border-color: #c62828; } +.mo-group { border: 1px solid var(--line); border-radius: 8px; display: grid; gap: 0.6rem; } +.mo-actions { display: flex; gap: 0.5rem; } +.mo-actions button[type="submit"] { background: var(--accent); color: #fff; border: 0; border-radius: 6px; padding: 0.4rem 0.9rem; } +[role="alert"] { color: #c62828; margin: 0; } +footer { padding: 0.75rem 1.25rem; opacity: 0.7; border-top: 1px solid var(--line); } diff --git a/examples/dynamic-grid/src/client/app.tsx b/examples/dynamic-grid/src/client/app.tsx new file mode 100644 index 0000000000..15275f24cf --- /dev/null +++ b/examples/dynamic-grid/src/client/app.tsx @@ -0,0 +1,150 @@ +/** + * The demo's shell: a menu of the entities the server serves, the grid of the chosen one, + * and the form for the row being created or edited. + * + * It names no entity. The menu is the model's entity list, and `` / `` + * are handed a name from it. Save the metadata file while this page is open and the page + * picks up the new model within a moment (`pollMs`), with nothing regenerated or rebuilt. + */ +import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react"; +import { joinBaseUrl, type EntityFetcher } from "@metaobjectsdev/runtime-web"; +import { EntityFetcherProvider } from "@metaobjectsdev/tanstack"; +import { describeError, jsonFetcher, loadClientModel, servedRevision, type Row } from "./api"; +import { ModelProvider } from "./context"; +import { MetaForm } from "./meta-form"; +import { MetaGrid } from "./meta-grid"; +import type { ClientModel, EntityModel } from "./model"; + +export interface AppProps { + /** Transport. The default is `fetch`. */ + readonly fetcher?: EntityFetcher; + /** Where the API is mounted. */ + readonly baseUrl?: string; + /** How often to ask whether the model changed, in milliseconds. 0 turns it off. */ + readonly pollMs?: number; +} + +/** What the page shows: an entity's list, and optionally one of its rows (or a new one) in the form. */ +interface View { + readonly entity: string; + readonly form?: { readonly id?: string | number; readonly initial?: Row }; +} + +function Workspace({ model }: { readonly model: ClientModel }): ReactNode { + const [view, setView] = useState(undefined); + // Bumped after every write, so the lists on the page fetch again. + const [written, setWritten] = useState(0); + // The chosen entity, or the first one: a reload may have removed the one that was open. + const entity: EntityModel | undefined = (view === undefined ? undefined : model.entity(view.entity)) ?? model.entities[0]; + if (entity === undefined) return

The model serves no entities.

; + const form = view?.entity === entity.name ? view.form : undefined; + const wrote = (): void => setWritten((n) => n + 1); + + return ( +
+ +
+
+

{entity.label}

+ +
+ setView({ entity: entity.name, form: { id: String(row[entity.keyField]) } })} /> +
+ {form !== undefined && ( + + )} +
+ ); +} + +export function App({ fetcher = jsonFetcher, baseUrl = "", pollMs = 1500 }: AppProps): ReactNode { + const [model, setModel] = useState(undefined); + const [failure, setFailure] = useState(undefined); + // The model and revision routes are relative to the API base, like every entity path. + const api = useMemo(() => (path, init) => fetcher(joinBaseUrl(baseUrl, path), init), [fetcher, baseUrl]); + + const load = useCallback(async (): Promise => { + try { + setModel(await loadClientModel(api)); + setFailure(undefined); + } catch (err) { + setFailure(describeError(err)); + } + }, [api]); + + useEffect(() => { + void load(); + }, [load]); + + const revision = model?.revision; + useEffect(() => { + if (pollMs <= 0 || revision === undefined) return; + const timer = setInterval(() => { + servedRevision(api).then( + (served) => { + if (served !== revision) void load(); + }, + // The server is restarting. The next tick asks again. + () => undefined, + ); + }, pollMs); + return () => clearInterval(timer); + }, [api, load, pollMs, revision]); + + if (model === undefined) return

{failure ?? "Loading the model…"}

; + return ( + + + {failure !== undefined &&

{failure}

} + +
+ Model revision {model.revision}. {model.entities.length} entities, rendered from {joinBaseUrl(baseUrl, "/_meta")}. +
+
+
+ ); +} diff --git a/examples/dynamic-grid/src/client/context.tsx b/examples/dynamic-grid/src/client/context.tsx new file mode 100644 index 0000000000..d883503ed6 --- /dev/null +++ b/examples/dynamic-grid/src/client/context.tsx @@ -0,0 +1,28 @@ +/** + * The loaded model, for every component below it. `` gets + * its entity from here by name; the name is the only thing a caller passes. + */ +import { createContext, useContext, type ReactNode } from "react"; +import type { ClientModel, EntityModel } from "./model"; + +const ModelContext = createContext(null); + +export function ModelProvider({ model, children }: { model: ClientModel; children: ReactNode }): ReactNode { + return {children}; +} + +export function useModel(): ClientModel { + const model = useContext(ModelContext); + if (model === null) throw new Error("useModel() was called outside ."); + return model; +} + +/** The named entity, or a thrown error: a name the model does not serve is a bug to surface. */ +export function useEntity(name: string): EntityModel { + const model = useModel(); + const entity = model.entity(name); + if (entity === undefined) { + throw new Error(`The model serves no entity "${name}" (it serves: ${model.entities.map((e) => e.name).join(", ")}).`); + } + return entity; +} diff --git a/examples/dynamic-grid/src/client/controls.tsx b/examples/dynamic-grid/src/client/controls.tsx new file mode 100644 index 0000000000..742063047a --- /dev/null +++ b/examples/dynamic-grid/src/client/controls.tsx @@ -0,0 +1,137 @@ +/** + * One input for one field, chosen and configured from the field's metadata. Shared by the + * form (editing a value) and the grid's filter bar (typing a value to filter by). + */ +import type { ReactNode } from "react"; +import { + FIELD_ATTR_MAX_LENGTH, + VALIDATOR_ATTR_MAX, + VALIDATOR_ATTR_MIN, + VALIDATOR_SUBTYPE_NUMERIC, + VIEW_TEXTAREA_ATTR_ROWS, +} from "@metaobjectsdev/metadata/constants"; +import { CurrencyInput } from "@metaobjectsdev/react"; +import { useModel } from "./context"; +import { currencyCode, currencyLocale, enumLabel } from "./format"; +import type { ControlKind, FormValue } from "./form-values"; +import type { FieldModel } from "./model"; +import { useReferenceOptions } from "./references"; + +export interface FieldInputProps { + readonly field: FieldModel; + readonly kind: Exclude; + readonly value: FormValue; + readonly onChange: (value: FormValue) => void; + readonly id: string; + /** Names the control for assistive technology when no `