better-schemic 0.1.0-beta.5 → 0.1.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +166 -24
  2. package/lib/aot.d.ts +31 -0
  3. package/lib/aot.js +3453 -0
  4. package/lib/aot.js.map +20 -0
  5. package/lib/cli/compile.d.ts +30 -0
  6. package/lib/cli/generate-orm.d.ts +32 -0
  7. package/lib/cli/index.js +275 -88
  8. package/lib/cli/index.js.map +15 -12
  9. package/lib/config.js +2907 -2025
  10. package/lib/config.js.map +24 -21
  11. package/lib/connection.js +2907 -2025
  12. package/lib/connection.js.map +24 -21
  13. package/lib/core/testing.d.ts +0 -114
  14. package/lib/driver.js +49 -46
  15. package/lib/driver.js.map +9 -9
  16. package/lib/index.js +434 -385
  17. package/lib/index.js.map +9 -8
  18. package/lib/orm/index.js +3073 -1977
  19. package/lib/orm/index.js.map +27 -22
  20. package/lib/plugin.d.ts +22 -0
  21. package/lib/plugin.js +18 -0
  22. package/lib/plugin.js.map +10 -0
  23. package/lib/plugins/create-only.js +494 -466
  24. package/lib/plugins/create-only.js.map +8 -8
  25. package/lib/plugins/hard-delete.js +7 -7
  26. package/lib/plugins/hard-delete.js.map +3 -3
  27. package/lib/plugins/policy.d.ts +1 -0
  28. package/lib/plugins/policy.js +654 -0
  29. package/lib/plugins/policy.js.map +15 -0
  30. package/lib/plugins/rules.js +7 -7
  31. package/lib/plugins/rules.js.map +3 -3
  32. package/lib/plugins/soft-delete.js +494 -466
  33. package/lib/plugins/soft-delete.js.map +8 -8
  34. package/lib/plugins/tenant.js +494 -466
  35. package/lib/plugins/tenant.js.map +10 -10
  36. package/lib/plugins/timestamps.js +494 -466
  37. package/lib/plugins/timestamps.js.map +8 -8
  38. package/lib/plugins/zod.js +53 -19
  39. package/lib/plugins/zod.js.map +4 -4
  40. package/lib/query.js +448 -397
  41. package/lib/query.js.map +9 -8
  42. package/lib/surreal/cli/structure.d.ts +0 -5
  43. package/lib/surreal/index.d.ts +3 -1
  44. package/lib/surreal/orm/client.d.ts +29 -19
  45. package/lib/surreal/orm/compiler/graph.d.ts +47 -0
  46. package/lib/surreal/orm/delegate.d.ts +24 -15
  47. package/lib/surreal/orm/describe.d.ts +93 -0
  48. package/lib/surreal/orm/errors.d.ts +6 -1
  49. package/lib/surreal/orm/execute.d.ts +20 -1
  50. package/lib/surreal/orm/graph.d.ts +6 -0
  51. package/lib/surreal/orm/index.d.ts +8 -8
  52. package/lib/surreal/orm/meta.d.ts +1 -1
  53. package/lib/surreal/orm/raw.d.ts +4 -0
  54. package/lib/surreal/orm/results.d.ts +22 -0
  55. package/lib/surreal/orm/semantic.d.ts +78 -0
  56. package/lib/surreal/orm/types/client.d.ts +17 -25
  57. package/lib/surreal/orm/types/select.d.ts +12 -5
  58. package/lib/surreal/orm/types/transaction.d.ts +3 -4
  59. package/lib/surreal/orm/types/write.d.ts +18 -6
  60. package/lib/surreal/plugins/policy.d.ts +46 -0
  61. package/lib/surreal/plugins/tenant-runtime.d.ts +3 -3
  62. package/lib/surreal/plugins/tenant.d.ts +3 -3
  63. package/lib/surreal/pure.d.ts +85 -26
  64. package/lib/surreal/query.d.ts +2 -0
  65. package/lib/surreal/surql/typed-bound.d.ts +33 -0
  66. package/lib/testing.js +2 -170
  67. package/lib/testing.js.map +3 -3
  68. package/package.json +28 -9
  69. package/src/aot.ts +45 -0
  70. package/src/cli/compile.ts +154 -0
  71. package/src/cli/generate-orm.ts +127 -0
  72. package/src/cli/index.ts +63 -0
  73. package/src/core/testing.ts +1 -371
  74. package/src/plugin.ts +35 -0
  75. package/src/plugins/policy.ts +1 -0
  76. package/src/surreal/cli/lower.ts +0 -6
  77. package/src/surreal/cli/pull.ts +2 -10
  78. package/src/surreal/cli/struct.ts +0 -1
  79. package/src/surreal/cli/structure.ts +0 -5
  80. package/src/surreal/cli/surreal-diff.ts +0 -1
  81. package/src/surreal/ddl.ts +4 -15
  82. package/src/surreal/index.ts +22 -0
  83. package/src/surreal/orm/client.ts +127 -63
  84. package/src/surreal/orm/compiler/graph.ts +345 -0
  85. package/src/surreal/orm/delegate.ts +73 -26
  86. package/src/surreal/orm/describe.ts +275 -0
  87. package/src/surreal/orm/errors.ts +15 -14
  88. package/src/surreal/orm/execute.ts +63 -8
  89. package/src/surreal/orm/graph.ts +415 -0
  90. package/src/surreal/orm/index.ts +30 -24
  91. package/src/surreal/orm/meta.ts +1 -1
  92. package/src/surreal/orm/raw.ts +6 -0
  93. package/src/surreal/orm/reads.ts +21 -7
  94. package/src/surreal/orm/results.ts +27 -0
  95. package/src/surreal/orm/semantic.ts +154 -0
  96. package/src/surreal/orm/types/client.ts +30 -48
  97. package/src/surreal/orm/types/select.ts +13 -5
  98. package/src/surreal/orm/types/transaction.ts +2 -7
  99. package/src/surreal/orm/types/write.ts +48 -6
  100. package/src/surreal/orm/writes.ts +10 -1
  101. package/src/surreal/plugins/policy.ts +242 -0
  102. package/src/surreal/plugins/tenant-runtime.ts +3 -3
  103. package/src/surreal/plugins/tenant.ts +3 -3
  104. package/src/surreal/pure.ts +197 -33
  105. package/src/surreal/query.ts +6 -0
  106. package/src/surreal/surql/typed-bound.ts +57 -0
  107. package/lib/surreal/orm/changes.d.ts +0 -22
  108. package/lib/surreal/orm/compiler/live.d.ts +0 -13
  109. package/lib/surreal/orm/live.d.ts +0 -17
  110. package/lib/surreal/orm/types/changes.d.ts +0 -62
  111. package/lib/surreal/orm/types/live.d.ts +0 -95
  112. package/src/surreal/orm/changes.ts +0 -232
  113. package/src/surreal/orm/compiler/live.ts +0 -118
  114. package/src/surreal/orm/live.ts +0 -471
  115. package/src/surreal/orm/types/changes.ts +0 -76
  116. package/src/surreal/orm/types/live.ts +0 -115
package/README.md CHANGED
@@ -31,10 +31,12 @@ replay into — `npm i -D @surrealdb/node`).
31
31
  | `better-schemic/config` | `defineConfig` + `surrealConnection` — the project config |
32
32
  | `better-schemic/orm` | the repository-style ORM client |
33
33
  | `better-schemic/query` | fragments & procedural SurrealQL |
34
- | `better-schemic/plugins/*` | the authoring plugins |
34
+ | `better-schemic/plugins/*` | the authoring + runtime plugins (incl. `plugins/policy`) |
35
35
  | `better-schemic/logger` | the query logger |
36
36
  | `better-schemic/otel` | OpenTelemetry tracing (`createOtelLogger`) |
37
37
  | `better-schemic/driver` | the engine entry (CLI/engine-only — pulls in the DDL emitter) |
38
+ | `better-schemic/aot` | zod-compiler bridge — field unwrapping + identity-preserving compile markers |
39
+ | `better-schemic/plugin` | the Bun build plugin (`betterSchemic()`) that AOT-compiles plain Zod schemas |
38
40
 
39
41
  ## Quick start
40
42
 
@@ -347,7 +349,7 @@ void seeded;
347
349
  // },
348
350
  // where: { likes: { some: { score: { gte: 4 } } } }, // relational filter
349
351
  // });
350
-
352
+ // Typed graph traversal (M19) — multi-hop, single round-trip (see a runnable block below).
351
353
  // Transactions (M4) — `tx` is a full client bound to the managed transaction:
352
354
  const from = await client.transaction(async (tx) => {
353
355
  const user = await tx.users
@@ -357,25 +359,6 @@ const from = await client.transaction(async (tx) => {
357
359
  return user;
358
360
  });
359
361
 
360
- // Live queries (M4) — the ORM compiles the LIVE SELECT (typed where/select/fetch):
361
- const sub = await client.users.live(
362
- { where: { active: true }, diff: true },
363
- (change) => {
364
- if (change.action === "UPDATE") cache.set(change.recordId, change.diff);
365
- },
366
- );
367
- // for await (const change of sub) { … }
368
- await sub.kill(); // or: await client.kill(sub.uuid)
369
-
370
- // Changefeeds (M4) — DEFINE TABLE t CHANGEFEED 1d (INCLUDE ORIGINAL for before/diff):
371
- const sets = await client.changes({ table: "users", since: 0, limit: 100 });
372
- for (const { versionstamp, changes } of sets) {
373
- for (const change of changes) {
374
- if (change.action === "DELETE") cache.delete(change.recordId);
375
- }
376
- void versionstamp; // paginate with `versionstamp + 1`
377
- }
378
-
379
362
  // Escape hatches & admin (M5) — parameterized by default:
380
363
  const rows = await client.$raw<User[]>`SELECT * FROM users WHERE email = ${email}`;
381
364
  const [users, posts] = await client.$query<[User[], Post[]]>`
@@ -632,9 +615,9 @@ is the raw `surrealdb` connection (escape hatch).
632
615
  **Status:** the typed-query arc (M0–M7) is **complete** — reads (M1), writes (M2 —
633
616
  `create`/`insert`/`update`/`patch`/`upsert`/`delete`/`updateEach` plus `relate`/`unrelate` on edge
634
617
  delegates), relations/graphs (M3 — `include` links/edges/`_count`, relational `where`
635
- `is`/`isNot`/`some`/`every`/`none`), transactions/live/changefeeds (M4 — `client.transaction` with
636
- retries and `afterCommit`/`afterRollback`, `live()` + `LiveSubscription` with reconnect, `changes()`),
637
- escape hatches/admin/context (M5 — `$raw`/`$query`/`$unsafe`, `fn`/`api`/`auth`/`info`/`version`/
618
+ `is`/`isNot`/`some`/`every`/`none`), transactions (M4 — `client.transaction` with retries and
619
+ `afterCommit`/`afterRollback`), escape hatches/admin/context (M5 — `$raw`/`$query`/`$unsafe`,
620
+ `fn`/`api`/`auth`/`info`/`version`/
638
621
  `ping`/`export`/`import`, `$withContext` multi-tenant scoping with per-call `context`) and
639
622
  plugins/hooks (M6 — observation `hooks`, `definePlugin` with transforms/typed `operationArgs`/
640
623
  `extendClient`/`extendModel`, plus the official plugins `plugins/rules`, `plugins/zod`,
@@ -649,6 +632,165 @@ milestone plan is in [`ROADMAP.md`](../../ROADMAP.md), and the verified examples
649
632
  runtime SurrealQL). Fragments & procedural SurrealQL (`block()`) stay at
650
633
  `better-schemic/query`.
651
634
 
635
+ ## Typed graph traversal (M19)
636
+
637
+ Multi-hop traversal in a single round-trip, typed against your schema's `relation()` edges:
638
+
639
+ ```ts
640
+ const bought = await client.persons
641
+ .from("person:B")
642
+ .graph((g) =>
643
+ g.out(Bought).in(Bought).out(Bought) // ->bought->product<-bought<-person->bought->product
644
+ .select({ id: true, name: true, price: true })
645
+ .distinct()
646
+ );
647
+ ```
648
+
649
+ Per-hop filters, a final `.where`, callback `.select`, recursion, edge steps and `.match`:
650
+
651
+ ```ts
652
+ const cheap = await client.persons.from("person:B").graph((g) =>
653
+ g.out(Bought, { where: { createdAt: { gte: lastMonth } } })
654
+ .out(Bought)
655
+ .where((p) => p.price.lt(500))
656
+ .select((p) => ({ id: p.id, name: p.name, price: p.price }))
657
+ .distinct()
658
+ );
659
+
660
+ const deep = await client.persons.from("person:B").graph((g) =>
661
+ g.repeat({ min: 1, max: 3 }, (x) => x.out(Bought)).collect()
662
+ );
663
+
664
+ const viaEdge = await client.persons.from("person:B").graph((g) =>
665
+ g.outEdges(Bought).where((e) => e.createdAt.gte(lastMonth)).node().select({ name: true })
666
+ );
667
+
668
+ // tagged template + .match (union member guard):
669
+ const t = await client.persons.from("person:B").traverse`->bought->product`;
670
+ const guarded = await client.persons.from("user:A").graph((g) =>
671
+ g.out(Knows).where((r) => r.match(User, (u) => u.name.eq("x")))
672
+ );
673
+ ```
674
+
675
+ ## The ORM in the age of AI / agents
676
+
677
+ This project does **not** advertise an "AI-native" surface — there is no natural-language→query
678
+ layer, MCP integration or GraphQL endpoint. What it does provide is the boring foundation those
679
+ things need: a typed, auditable contract an agent cannot silently drift away from, plus first-class
680
+ primitives for schema description, dry runs, policies and business semantics.
681
+
682
+ | What an agent needs | Here |
683
+ | --- | --- |
684
+ | **Typed, stable contract / single source of truth** — `table`/`s.*` → Zod codecs → DDL, migrations and `sc pull` back to TypeScript | ✅ Plus `describeSchema()` — a JSON-safe descriptor of tables, fields, constraints, relations, functions and plugin tags |
685
+ | **Bulk + field selection (no N+1)** — `createMany`/`insertMany`/`updateMany`/`upsertMany`/`deleteMany`/`updateEach`/`relateMany`; `select`/`omit`/`value` + `include`; `paginate`, `cursor`, typed graph traversal | ✅ Nested projected `include` is still partial |
686
+ | **Deterministic validation** — Zod `safeEncode` on writes by default, `plugins/zod` for custom schemas, teaching errors instead of silent fallbacks | ✅ |
687
+ | **Composable, auditable queries** — typed `where`, `surql`/`fn.expr` fragments, one round-trip per operation, logger/OTEL spans | ✅ Plus server-free `.toSQL()` on reads and `delegate.$sql.<op>()` for write dry runs; `plugins/policy` for declarative deny/scope/require rules |
688
+ | **Semantic layer** — `defineMetric`/`defineGlossary`/`lineage()` mapping to the existing `aggregate` surface, plus `defineView`/`$computed` | ✅ Authoring-only: no new DDL, no SQL parsing, no fake lineage. GraphQL and AI integrations remain out of scope |
689
+
690
+ ```ts
691
+ import { describeSchema, defineMetric, lineage } from "better-schemic/orm";
692
+ import { definePolicy } from "better-schemic/plugins/policy";
693
+
694
+ // 1. A typed descriptor an agent can read (pure JSON, no DB round-trip).
695
+ const description = describeSchema(schemaDef);
696
+
697
+ // 2. Preview the exact script — no connection, no hooks, no rows.
698
+ const plan = client.users.findMany({ where: { age: { gte: 18 } } }).toSQL();
699
+ const createScript = client.users.$sql.create({ data: { name: "Aeon", age: 30, active: true } });
700
+
701
+ // 3. Declarative authorization, on top of the DB's own permissions.
702
+ const policy = definePolicy(schemaDef, {
703
+ rules: [
704
+ { tables: ["users"], operations: ["delete"], effect: "deny" },
705
+ { tables: ["users"], effect: "scope", filter: { org: "acme" } },
706
+ { tables: ["users"], effect: "require", require: "actor" },
707
+ ],
708
+ });
709
+
710
+ // 4. Business semantics with declared, validated lineage.
711
+ const revenue = defineMetric({
712
+ key: "revenue", from: Order, measure: { op: "sum", field: "amount" },
713
+ dimensions: ["region"],
714
+ });
715
+ const sources = lineage([revenue], schemaDef);
716
+ ```
717
+
718
+ The full mapping — including deliberate non-goals and the exact sections backing each claim — is in
719
+ [`docs/ORM-COVERAGE.md` §12](docs/ORM-COVERAGE.md#12-fit-for-agents--ai).
720
+
721
+ ## Bun AOT (compiled binaries)
722
+
723
+ `bun build --compile --aot` needs object shapes fixed at compile time. Compose schemas with the
724
+ fluent builder instead of spreading a generic type parameter inside a helper — the merge happens
725
+ inside the library (compiled once), and every shape literal stays concrete at the call site:
726
+
727
+ ```ts
728
+ import { s, table } from "better-schemic";
729
+ import { tenant } from "better-schemic/plugins/tenant";
730
+
731
+ const audit = { createdAt: s.datetime().$readonly(), updatedAt: s.datetime() };
732
+ const Customer = table("customer", { name: s.string(), tenant_id: s.recordId("user") })
733
+ .extend(audit)
734
+ .extendIf(false, { deletedAt: s.datetime().optional() })
735
+ .use(tenant(User, { softDelete: true }))
736
+ .index("customer_name_uq", ["name"], { unique: true })
737
+ .stringIds()
738
+ .build();
739
+ ```
740
+
741
+ `TableBuilder` is an alias of `TableDef` — every existing `table(...)` call site keeps working;
742
+ `.build()` is an explicit identity terminal. Presets are idempotent: a column already declared with
743
+ the same type (e.g. `tenant_id`) is not a conflict. For helpers over an unresolved shape use
744
+ `.useUnchecked(preset)` (skips only the collision check, keeps `Name`/`S`) instead of casting to
745
+ `any`.
746
+
747
+ For the client façade, generate STATIC getters from the schema so the AOT compiler sees them in the
748
+ source (the runtime `Object.defineProperty` delegate loop is a slow path):
749
+
750
+ ```sh
751
+ sc generate:orm --out src/db/orm.generated.ts --schema src/db/schema.ts \
752
+ --provider-from ./orm-provider --client getOrmClient
753
+ ```
754
+
755
+ The file ends with `satisfies OrmSurface<typeof schema>`. Also available:
756
+ `createOrmClientFactory({ cache: 'weak' })` (per-connection client cache with `peek`/`dispose`),
757
+ `orm(() => conn, { schema })` (lazy connection), `setClientResolver`/`clientRef` (late binding),
758
+ `TypedBoundQuery`/`surqlWith` (typed raw binds + result rows), `selectQuery(from, allowlist)` (fixed
759
+ row keys from a projection), `s.json<T>()` and `s.regex(source: string, flags?)`.
760
+
761
+ ## AOT validation with zod-compiler
762
+
763
+ `sc compile` wires [zod-compiler](https://github.com/gajus/zod-compiler) into the authoring
764
+ surface. Every `s.*` field is a wrapper around a Zod schema — the command generates a module that
765
+ re-exports each field's underlying schema, lets zod-compiler emit static validators, and writes a
766
+ bootstrap module. zod-compiler **mutates the original schema objects in place**, so the SurrealQL
767
+ metadata, `.shape`, `instanceof`, `z.toJSONSchema()` and the ORM are untouched — only validation
768
+ gets the generated fast path.
769
+
770
+ ```sh
771
+ sc compile
772
+ # → .better-schemic/aot/schemas.compiled.ts (generated validators)
773
+ # → .better-schemic/schema.aot.ts (import this instead of your schema module)
774
+ ```
775
+
776
+ ```ts
777
+ import { Customer } from "./.better-schemic/schema.aot"; // compiled validators installed
778
+ await Customer.decode(row); // DDL/schema unchanged
779
+ ```
780
+
781
+ Use both halves: `sc compile` for authored `s.*` fields, and `better-schemic/plugin` for plain Zod
782
+ schemas in the app (route contracts, DTOs). The plugin wraps `zod-compiler/bun` and is meant for
783
+ `Bun.build({ plugins: [betterSchemic()] })` — including `bun build --compile --aot`:
784
+
785
+ ```ts
786
+ import { betterSchemic } from "better-schemic/plugin";
787
+ await Bun.build({
788
+ entrypoints: ["src/server.ts"],
789
+ plugins: [betterSchemic()],
790
+ compile: true,
791
+ });
792
+ ```
793
+
652
794
  ## Docs
653
795
 
654
796
  Full guides, concepts, and reference live at
package/lib/aot.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * `better-schemic/aot` — the bridge to [zod-compiler](https://github.com/gajus/zod-compiler).
3
+ *
4
+ * `s.*` fields are NOT Zod instances: they are `SField` wrappers holding a Zod schema in
5
+ * `.schema` plus the SurrealQL metadata (`.native`). zod-compiler compiles the UNDERLYING Zod
6
+ * schema in place (identity-preserving), so the wrapper, the DDL metadata, `.shape`, `instanceof`
7
+ * and the ORM all keep working — only validation gets the generated fast path.
8
+ *
9
+ * This module is the public, side-effect-free half. The build-time generation lives in
10
+ * `sc compile` (`src/cli/compile.ts`) and the bundler adapters in `better-schemic/plugin`.
11
+ */
12
+ import type { z } from "zod";
13
+ import { isCompiledSchema } from "zod-compiler";
14
+ import { type AnyField } from "./surreal";
15
+ export type { CompiledSchema } from "zod-compiler";
16
+ export { isCompiledSchema };
17
+ /** Unwrap an authored field to the Zod schema that actually validates it. Raw Zod schemas are
18
+ * accepted too — `Shape` allows them alongside `s.*` fields. */
19
+ export declare function fieldSchemaOf(field: AnyField | z.ZodType): z.ZodType;
20
+ /**
21
+ * Dev-time marker (no generated fast path yet): tags a field's Zod schema so zod-compiler's
22
+ * `check` can see it, preserving identity. Run `sc compile` for the real AOT code.
23
+ */
24
+ export declare function markFieldCompiled(field: AnyField | z.ZodType): z.ZodType;
25
+ /** Whether a field's underlying Zod schema has gone through zod-compiler. */
26
+ export declare function isFieldCompiled(field: AnyField | z.ZodType): boolean;
27
+ /**
28
+ * Compile a field's Zod schema IN PROCESS (dev/JIT fallback — identity-preserving).
29
+ * Prefer `sc compile`, which emits static validators with no `new Function` at runtime.
30
+ */
31
+ export declare function compileField(field: AnyField | z.ZodType): z.ZodType;