@better-schemic/core 0.1.0-alpha.1
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.
- package/LICENSE +21 -0
- package/README.md +40 -0
- package/lib/authoring.d.ts +114 -0
- package/lib/authoring.js +242 -0
- package/lib/authoring.js.map +1 -0
- package/lib/chunk-26D7WX7Q.js +31 -0
- package/lib/chunk-26D7WX7Q.js.map +1 -0
- package/lib/chunk-IUPOUD4L.js +330 -0
- package/lib/chunk-IUPOUD4L.js.map +1 -0
- package/lib/chunk-LC3VHUM2.js +56 -0
- package/lib/chunk-LC3VHUM2.js.map +1 -0
- package/lib/chunk-RSGP7GVO.js +252 -0
- package/lib/chunk-RSGP7GVO.js.map +1 -0
- package/lib/client-HZF4ZWGO.js +13 -0
- package/lib/client-HZF4ZWGO.js.map +1 -0
- package/lib/config-BYh7WA4P.d.ts +259 -0
- package/lib/config.d.ts +2 -0
- package/lib/config.js +27 -0
- package/lib/config.js.map +1 -0
- package/lib/driver-LVldBEhS.d.ts +818 -0
- package/lib/driver.d.ts +151 -0
- package/lib/driver.js +47 -0
- package/lib/driver.js.map +1 -0
- package/lib/index.d.ts +154 -0
- package/lib/index.js +758 -0
- package/lib/index.js.map +1 -0
- package/lib/query.d.ts +81 -0
- package/lib/query.js +30 -0
- package/lib/query.js.map +1 -0
- package/lib/secrets-BETi5p8g.d.ts +26 -0
- package/lib/testing.d.ts +99 -0
- package/lib/testing.js +212 -0
- package/lib/testing.js.map +1 -0
- package/package.json +102 -0
- package/src/authoring.ts +360 -0
- package/src/cli-kit/config.ts +226 -0
- package/src/cli-kit/diff.ts +273 -0
- package/src/cli-kit/filter.ts +159 -0
- package/src/cli-kit/merge.ts +380 -0
- package/src/cli-kit/meta.ts +123 -0
- package/src/cli-kit/pager.ts +42 -0
- package/src/cli-kit/schema.ts +214 -0
- package/src/cli-kit/style.ts +24 -0
- package/src/client.ts +244 -0
- package/src/config.ts +199 -0
- package/src/connection.ts +120 -0
- package/src/driver/driver.ts +413 -0
- package/src/driver/index.ts +31 -0
- package/src/driver/portable-ir.ts +51 -0
- package/src/driver/portable.ts +124 -0
- package/src/driver/sdk.ts +73 -0
- package/src/index.ts +185 -0
- package/src/kind/index.ts +28 -0
- package/src/kind/plan.ts +412 -0
- package/src/kind/registry.ts +270 -0
- package/src/query/call.ts +21 -0
- package/src/query/codec.ts +33 -0
- package/src/query/index.ts +22 -0
- package/src/query/project.ts +25 -0
- package/src/query/ref.ts +32 -0
- package/src/query.ts +5 -0
- package/src/secrets.ts +61 -0
- package/src/seed.ts +14 -0
- package/src/testing.ts +402 -0
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
// src/kind/plan.ts
|
|
2
|
+
var refKey = (r) => `${r.kind}:${r.name}`;
|
|
3
|
+
function orderObjects(nodes, ordinalOf) {
|
|
4
|
+
const byKey2 = new Map(nodes.map((n) => [refKey(n), n]));
|
|
5
|
+
const indeg = new Map(nodes.map((n) => [refKey(n), 0]));
|
|
6
|
+
const dependents = /* @__PURE__ */ new Map();
|
|
7
|
+
for (const n of nodes)
|
|
8
|
+
for (const d of n.deps) {
|
|
9
|
+
if (!byKey2.has(refKey(d))) continue;
|
|
10
|
+
indeg.set(refKey(n), (indeg.get(refKey(n)) ?? 0) + 1);
|
|
11
|
+
const list = dependents.get(refKey(d)) ?? [];
|
|
12
|
+
list.push(refKey(n));
|
|
13
|
+
dependents.set(refKey(d), list);
|
|
14
|
+
}
|
|
15
|
+
const out = [];
|
|
16
|
+
const done = /* @__PURE__ */ new Set();
|
|
17
|
+
let group;
|
|
18
|
+
while (out.length < nodes.length) {
|
|
19
|
+
const ready = nodes.filter(
|
|
20
|
+
(n) => !done.has(refKey(n)) && indeg.get(refKey(n)) === 0
|
|
21
|
+
);
|
|
22
|
+
if (ready.length === 0)
|
|
23
|
+
throw new Error(
|
|
24
|
+
`dependency cycle among: ${nodes.filter((n) => !done.has(refKey(n))).map(refKey).join(", ")}`
|
|
25
|
+
);
|
|
26
|
+
ready.sort((a, b) => {
|
|
27
|
+
const ao = a.owner && refKey(a.owner) === group ? 0 : 1;
|
|
28
|
+
const bo = b.owner && refKey(b.owner) === group ? 0 : 1;
|
|
29
|
+
return ao - bo || ordinalOf(a.kind) - ordinalOf(b.kind) || refKey(a).localeCompare(refKey(b));
|
|
30
|
+
});
|
|
31
|
+
const next = ready[0];
|
|
32
|
+
out.push(next);
|
|
33
|
+
done.add(refKey(next));
|
|
34
|
+
if (!next.owner) group = refKey(next);
|
|
35
|
+
for (const dep of dependents.get(refKey(next)) ?? [])
|
|
36
|
+
indeg.set(dep, (indeg.get(dep) ?? 1) - 1);
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
function lowerSchema(registry, defs) {
|
|
41
|
+
const out = [];
|
|
42
|
+
for (const d of defs) {
|
|
43
|
+
const engine = registry.engine(d.kind);
|
|
44
|
+
if (engine) out.push(engine.lower(d));
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
function snapshotKinds(schema, registry) {
|
|
49
|
+
const kinds = {};
|
|
50
|
+
for (const o of schema) {
|
|
51
|
+
if (registry?.isExcludedFromMigrations(o)) continue;
|
|
52
|
+
const bucket = kinds[o.kind] ?? [];
|
|
53
|
+
bucket.push(o);
|
|
54
|
+
kinds[o.kind] = bucket;
|
|
55
|
+
}
|
|
56
|
+
return { kinds };
|
|
57
|
+
}
|
|
58
|
+
function snapshotObjects(snap) {
|
|
59
|
+
return Object.values(snap.kinds).flat();
|
|
60
|
+
}
|
|
61
|
+
var canonicalOf = (engine, p) => engine.canonical?.(p) ?? engine.emit(p).join("\n");
|
|
62
|
+
var orderNodeOf = (engine, portable) => ({
|
|
63
|
+
kind: portable.kind,
|
|
64
|
+
name: portable.name,
|
|
65
|
+
deps: engine.deps?.(portable) ?? [],
|
|
66
|
+
owner: engine.owner?.(portable)
|
|
67
|
+
});
|
|
68
|
+
var itemKey = (n) => `${n.kind}:${n.owner?.name ?? ""}:${n.name}`;
|
|
69
|
+
var itemTable = (n) => n.owner?.name ?? n.name;
|
|
70
|
+
var byKey = (schema) => new Map(schema.map((o) => [refKey(o), o]));
|
|
71
|
+
function orderedChanges(registry, prev, next) {
|
|
72
|
+
const prevByKey = byKey(prev);
|
|
73
|
+
const nextByKey = byKey(next);
|
|
74
|
+
const changes = [];
|
|
75
|
+
for (const k of /* @__PURE__ */ new Set([...prevByKey.keys(), ...nextByKey.keys()])) {
|
|
76
|
+
const p = prevByKey.get(k);
|
|
77
|
+
const n = nextByKey.get(k);
|
|
78
|
+
const portable = n ?? p;
|
|
79
|
+
if (!portable) continue;
|
|
80
|
+
if (registry.isExcludedFromMigrations(portable)) continue;
|
|
81
|
+
const engine = registry.engine(portable.kind);
|
|
82
|
+
if (!engine) continue;
|
|
83
|
+
const node = orderNodeOf(engine, portable);
|
|
84
|
+
if (p && !n) changes.push({ op: "remove", prev: p, ...node });
|
|
85
|
+
else if (!p && n) changes.push({ op: "add", next: n, ...node });
|
|
86
|
+
else if (p && n && canonicalOf(engine, p) !== canonicalOf(engine, n))
|
|
87
|
+
changes.push({ op: "change", prev: p, next: n, ...node });
|
|
88
|
+
}
|
|
89
|
+
const ord = (kind) => registry.ordinal(kind);
|
|
90
|
+
return {
|
|
91
|
+
nonRemoves: orderObjects(
|
|
92
|
+
changes.filter((c) => c.op !== "remove"),
|
|
93
|
+
ord
|
|
94
|
+
),
|
|
95
|
+
removes: orderObjects(
|
|
96
|
+
changes.filter((c) => c.op === "remove"),
|
|
97
|
+
ord
|
|
98
|
+
)
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
var overwriteUp = (engine, a, b) => engine.overwrite?.(a, b) ?? [...engine.remove(a), ...engine.emit(b)];
|
|
102
|
+
function planKinds(registry, prev, next) {
|
|
103
|
+
const { nonRemoves, removes } = orderedChanges(registry, prev, next);
|
|
104
|
+
const up = [];
|
|
105
|
+
const down = [];
|
|
106
|
+
for (const c of nonRemoves) {
|
|
107
|
+
const e = registry.engine(c.kind);
|
|
108
|
+
if (!e) continue;
|
|
109
|
+
if (c.op === "add" && c.next) up.push(...e.emit(c.next));
|
|
110
|
+
else if (c.op === "change" && c.prev && c.next)
|
|
111
|
+
up.push(...overwriteUp(e, c.prev, c.next));
|
|
112
|
+
}
|
|
113
|
+
for (const c of [...removes].reverse()) {
|
|
114
|
+
const e = registry.engine(c.kind);
|
|
115
|
+
if (e && c.prev) up.push(...e.remove(c.prev));
|
|
116
|
+
}
|
|
117
|
+
for (const c of removes) {
|
|
118
|
+
const e = registry.engine(c.kind);
|
|
119
|
+
if (e && c.prev) down.push(...e.emit(c.prev));
|
|
120
|
+
}
|
|
121
|
+
for (const c of [...nonRemoves].reverse()) {
|
|
122
|
+
const e = registry.engine(c.kind);
|
|
123
|
+
if (!e) continue;
|
|
124
|
+
if (c.op === "add" && c.next) down.push(...e.remove(c.next));
|
|
125
|
+
else if (c.op === "change" && c.prev && c.next)
|
|
126
|
+
down.push(...overwriteUp(e, c.next, c.prev));
|
|
127
|
+
}
|
|
128
|
+
return { up, down };
|
|
129
|
+
}
|
|
130
|
+
function diffItems(registry, nonRemoves, removes) {
|
|
131
|
+
const items = [];
|
|
132
|
+
const push = (c) => {
|
|
133
|
+
const e = registry.engine(c.kind);
|
|
134
|
+
if (!e) return;
|
|
135
|
+
if (e.displayItems) {
|
|
136
|
+
items.push(...e.displayItems(c.prev, c.next));
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const base = { key: itemKey(c), table: itemTable(c), kind: c.kind };
|
|
140
|
+
if (c.op === "add" && c.next)
|
|
141
|
+
items.push({ ...base, op: "add", ddl: e.emit(c.next).join("\n") });
|
|
142
|
+
else if (c.op === "remove" && c.prev)
|
|
143
|
+
items.push({
|
|
144
|
+
...base,
|
|
145
|
+
op: "remove",
|
|
146
|
+
ddl: e.remove(c.prev).join("\n"),
|
|
147
|
+
old: e.emit(c.prev).join("\n")
|
|
148
|
+
});
|
|
149
|
+
else if (c.op === "change" && c.prev && c.next)
|
|
150
|
+
items.push({
|
|
151
|
+
...base,
|
|
152
|
+
op: "change",
|
|
153
|
+
before: e.emit(c.prev).join("\n"),
|
|
154
|
+
after: e.emit(c.next).join("\n")
|
|
155
|
+
});
|
|
156
|
+
};
|
|
157
|
+
for (const c of nonRemoves) push(c);
|
|
158
|
+
for (const c of [...removes].reverse()) push(c);
|
|
159
|
+
return items;
|
|
160
|
+
}
|
|
161
|
+
function buildKindDiff(registry, prev, next) {
|
|
162
|
+
const { nonRemoves, removes } = orderedChanges(registry, prev, next);
|
|
163
|
+
const { up, down } = planKinds(registry, prev, next);
|
|
164
|
+
const full = orderedSchema(registry, next).flatMap(
|
|
165
|
+
({ engine, portable, node }) => {
|
|
166
|
+
if (engine.displayItems)
|
|
167
|
+
return engine.displayItems(void 0, portable).map((it) => ({
|
|
168
|
+
key: it.key,
|
|
169
|
+
table: it.table,
|
|
170
|
+
ddl: it.op === "add" ? it.ddl : ""
|
|
171
|
+
}));
|
|
172
|
+
return [
|
|
173
|
+
{
|
|
174
|
+
key: itemKey(node),
|
|
175
|
+
table: itemTable(node),
|
|
176
|
+
ddl: engine.emit(portable).join("\n")
|
|
177
|
+
}
|
|
178
|
+
];
|
|
179
|
+
}
|
|
180
|
+
);
|
|
181
|
+
return { up, down, items: diffItems(registry, nonRemoves, removes), full };
|
|
182
|
+
}
|
|
183
|
+
function orderedSchema(registry, schema) {
|
|
184
|
+
const items = schema.flatMap((portable) => {
|
|
185
|
+
const engine = registry.engine(portable.kind);
|
|
186
|
+
return engine ? [{ engine, portable, node: orderNodeOf(engine, portable) }] : [];
|
|
187
|
+
});
|
|
188
|
+
const pos = new Map(
|
|
189
|
+
orderObjects(
|
|
190
|
+
items.map((i) => i.node),
|
|
191
|
+
(k) => registry.ordinal(k)
|
|
192
|
+
).map((n, i) => [itemKey(n), i])
|
|
193
|
+
);
|
|
194
|
+
return items.sort(
|
|
195
|
+
(a, b) => (pos.get(itemKey(a.node)) ?? 0) - (pos.get(itemKey(b.node)) ?? 0)
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
function emitKinds(registry, schema) {
|
|
199
|
+
const managed = schema.filter(
|
|
200
|
+
(o) => !registry.isExcludedFromMigrations(o)
|
|
201
|
+
);
|
|
202
|
+
return orderedSchema(registry, managed).flatMap(
|
|
203
|
+
({ engine, portable }) => engine.emit(portable)
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
async function introspectKinds(registry, conn) {
|
|
207
|
+
const out = [];
|
|
208
|
+
for (const [kind, engine] of registry.entries()) {
|
|
209
|
+
if (!engine.introspect) continue;
|
|
210
|
+
if (registry.skipsIntrospection(kind)) continue;
|
|
211
|
+
out.push(...await engine.introspect(conn));
|
|
212
|
+
}
|
|
213
|
+
return out;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// src/kind/registry.ts
|
|
217
|
+
function capitalize(s) {
|
|
218
|
+
return s ? s[0].toUpperCase() + s.slice(1) : s;
|
|
219
|
+
}
|
|
220
|
+
function pluralize(s) {
|
|
221
|
+
if (/[^aeiou]y$/i.test(s)) return `${s.slice(0, -1)}ies`;
|
|
222
|
+
if (/(s|x|z|ch|sh)$/i.test(s)) return `${s}es`;
|
|
223
|
+
return `${s}s`;
|
|
224
|
+
}
|
|
225
|
+
function slugify(s) {
|
|
226
|
+
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
227
|
+
}
|
|
228
|
+
var KindRegistry = class {
|
|
229
|
+
// Heterogeneous kinds erase at the engine seam (engine ops are structural); the AUTHORING side
|
|
230
|
+
// keeps full types via `define`'s `Build` passthrough.
|
|
231
|
+
// biome-ignore lint/suspicious/noExplicitAny: the engine seam is intentionally type-erased.
|
|
232
|
+
kinds = /* @__PURE__ */ new Map();
|
|
233
|
+
/**
|
|
234
|
+
* Register a KIND. `build` is the driver's own authoring entry — ANY shape/chain — and its type
|
|
235
|
+
* flows through unchanged (type-safety + DX are the driver's to design). The engine fns give core
|
|
236
|
+
* the generic behavior. Registration ORDER is the kind's ordinal (the stable tie-break among
|
|
237
|
+
* independent objects in {@link orderObjects}), so register coarse-to-fine (table before index).
|
|
238
|
+
*/
|
|
239
|
+
define(spec) {
|
|
240
|
+
this.kinds.set(spec.name, spec);
|
|
241
|
+
return spec.build;
|
|
242
|
+
}
|
|
243
|
+
/** The engine for `kind`, or undefined if no such kind is registered. */
|
|
244
|
+
// biome-ignore lint/suspicious/noExplicitAny: the engine erases at this seam (see `kinds`).
|
|
245
|
+
engine(kind) {
|
|
246
|
+
return this.kinds.get(kind);
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Is this PORTABLE OBJECT UNMANAGED by the migration pipeline (its engine set
|
|
250
|
+
* {@link KindEngine.excludeFromMigrations})? The snapshot/diff/emit spine skips such objects — see
|
|
251
|
+
* the flag's docs. The OBJECT is required: a per-object predicate can't be evaluated without it, and
|
|
252
|
+
* defaulting to "managed" would let a key-bearing object slip into a migration. An unregistered kind
|
|
253
|
+
* is treated as managed (false), so a stray object never gets silently dropped by a typo.
|
|
254
|
+
*/
|
|
255
|
+
isExcludedFromMigrations(portable) {
|
|
256
|
+
const flag = this.kinds.get(portable.kind)?.excludeFromMigrations;
|
|
257
|
+
return typeof flag === "function" ? flag(portable) : flag === true;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Whether `kind` is STATICALLY excluded from migrations (`excludeFromMigrations === true`), so even
|
|
261
|
+
* introspection skips it. A per-object PREDICATE can't be decided without an object: introspection
|
|
262
|
+
* runs for the kind, and the diff/snapshot/emit choke points filter by object afterwards.
|
|
263
|
+
*/
|
|
264
|
+
skipsIntrospection(kind) {
|
|
265
|
+
return this.kinds.get(kind)?.excludeFromMigrations === true;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* A kind's resolved presentation — `label`/`plural`/`folder`, with defaults derived from the kind
|
|
269
|
+
* name for whatever the driver left unset. Works for unregistered display sub-kinds too (e.g. the
|
|
270
|
+
* `"field"` items a table's `displayItems` emits) — they just get the name-derived defaults.
|
|
271
|
+
*/
|
|
272
|
+
display(kind) {
|
|
273
|
+
const d = this.kinds.get(kind)?.display ?? {};
|
|
274
|
+
const label = d.label ?? capitalize(kind);
|
|
275
|
+
const plural = d.plural ?? pluralize(label);
|
|
276
|
+
return { label, plural, folder: d.folder ?? slugify(plural) };
|
|
277
|
+
}
|
|
278
|
+
/** Registered kind names, in registration order (== ordinal order). */
|
|
279
|
+
names() {
|
|
280
|
+
return [...this.kinds.keys()];
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* A kind's ORDINAL = its registration index. Used ONLY as a tie-break among objects with no
|
|
284
|
+
* dependency relation, so independent objects come out stably layered (readability); it never
|
|
285
|
+
* overrides the dependency graph. An unknown kind sorts last.
|
|
286
|
+
*/
|
|
287
|
+
ordinal(kind) {
|
|
288
|
+
const i = this.names().indexOf(kind);
|
|
289
|
+
return i === -1 ? Number.MAX_SAFE_INTEGER : i;
|
|
290
|
+
}
|
|
291
|
+
/** [name, engine] pairs in registration order — the spine iterates these. */
|
|
292
|
+
// biome-ignore lint/suspicious/noExplicitAny: the engine erases at this seam (see `kinds`).
|
|
293
|
+
entries() {
|
|
294
|
+
return [...this.kinds.entries()];
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
// src/driver/driver.ts
|
|
299
|
+
var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@better-schemic/core.driverRegistry");
|
|
300
|
+
var REGISTRY = globalThis[REGISTRY_KEY] ??= /* @__PURE__ */ new Map();
|
|
301
|
+
function registerDriver(driver) {
|
|
302
|
+
REGISTRY.set(driver.name, driver);
|
|
303
|
+
}
|
|
304
|
+
function getDriver(name) {
|
|
305
|
+
const d = REGISTRY.get(name);
|
|
306
|
+
if (!d) {
|
|
307
|
+
const known = [...REGISTRY.keys()].join(", ") || "(none registered)";
|
|
308
|
+
throw new Error(`Unknown database driver "${name}". Registered: ${known}.`);
|
|
309
|
+
}
|
|
310
|
+
return d;
|
|
311
|
+
}
|
|
312
|
+
function driverNames() {
|
|
313
|
+
return [...REGISTRY.keys()];
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export {
|
|
317
|
+
orderObjects,
|
|
318
|
+
lowerSchema,
|
|
319
|
+
snapshotKinds,
|
|
320
|
+
snapshotObjects,
|
|
321
|
+
planKinds,
|
|
322
|
+
buildKindDiff,
|
|
323
|
+
emitKinds,
|
|
324
|
+
introspectKinds,
|
|
325
|
+
KindRegistry,
|
|
326
|
+
registerDriver,
|
|
327
|
+
getDriver,
|
|
328
|
+
driverNames
|
|
329
|
+
};
|
|
330
|
+
//# sourceMappingURL=chunk-IUPOUD4L.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/kind/plan.ts","../src/kind/registry.ts","../src/driver/driver.ts"],"sourcesContent":["// The GENERIC migration spine over a {@link KindRegistry} — core's kind-blind orchestration. It\n// classifies each portable object as add/change/remove, ORDERS them across kinds by a dependency\n// graph, and emits up/down DDL + the display {@link Diff}. It never names a kind: every kind-specific\n// decision is delegated to that kind's {@link KindEngine}.\n//\n// The spine works on PORTABLE objects (both sides already lowered), exactly like the fixed-slot\n// `Driver.diff(prev, next)`: the stored snapshot IS portable, and the authoring side is lowered once\n// via {@link lowerSchema}. So `prev` is a snapshot, `next` is `lowerSchema(registry, defs)`.\n//\n// Cross-kind ordering is the load-bearing part (docs/kind-registry.md §7.1). THREE layers:\n// 1. dependency GRAPH + topological sort -> CORRECTNESS (an object emits after everything it deps on)\n// 2. kind ORDINAL (registration order) -> stable TIE-BREAK among independent objects (layering)\n// 3. OWNER clustering -> READABILITY (an index right after its table)\n// A per-kind ordinal ALONE is wrong: a table's event can call a function, so the function must emit\n// BEFORE the table — a function-before-table the graph handles and an ordinal cannot. Drops reverse it.\n\n// NOTE: `Diff`/`DiffItem` are a type-only import (erased at compile — no runtime cli->kind coupling),\n// the same arrangement as ./driver/portable-diff.ts.\nimport type { Diff, DiffItem } from \"../cli-kit/diff\";\nimport type {\n Definable,\n KindEngine,\n KindRegistry,\n PortableObject,\n Ref,\n} from \"./registry\";\n\nconst refKey = (r: Ref) => `${r.kind}:${r.name}`;\n\n/** A node in the dependency graph: identity + the edges/owner used to order it. */\nexport interface OrderNode {\n readonly kind: string;\n readonly name: string;\n /** Objects this node must come AFTER (only intra-set refs constrain; external refs are ignored). */\n readonly deps: Ref[];\n /** Owning object to cluster next to (readability tie-break only; never overrides `deps`). */\n readonly owner?: Ref;\n}\n\n/**\n * Kahn's topological sort with two presentation tweaks among the nodes whose deps are all satisfied:\n * prefer one OWNED by the currently-open cluster (so a table's children follow it), then lowest\n * (kind-ordinal, then name). Correctness (deps) always wins — an owned/low-ordinal node can't jump a\n * dependency. A genuine cycle throws (a named error). Refs to nodes outside `nodes` are ignored (an\n * object may depend on something untouched by this diff — it already exists / isn't changing).\n */\nexport function orderObjects<T extends OrderNode>(\n nodes: T[],\n ordinalOf: (kind: string) => number,\n): T[] {\n const byKey = new Map(nodes.map((n) => [refKey(n), n]));\n const indeg = new Map<string, number>(nodes.map((n) => [refKey(n), 0]));\n const dependents = new Map<string, string[]>();\n for (const n of nodes)\n for (const d of n.deps) {\n if (!byKey.has(refKey(d))) continue; // external dep -> not a constraint within this set\n indeg.set(refKey(n), (indeg.get(refKey(n)) ?? 0) + 1);\n const list = dependents.get(refKey(d)) ?? [];\n list.push(refKey(n));\n dependents.set(refKey(d), list);\n }\n\n const out: T[] = [];\n const done = new Set<string>();\n let group: string | undefined; // the last unowned node emitted == the open cluster\n while (out.length < nodes.length) {\n const ready = nodes.filter(\n (n) => !done.has(refKey(n)) && indeg.get(refKey(n)) === 0,\n );\n if (ready.length === 0)\n throw new Error(\n `dependency cycle among: ${nodes\n .filter((n) => !done.has(refKey(n)))\n .map(refKey)\n .join(\", \")}`,\n );\n ready.sort((a, b) => {\n const ao = a.owner && refKey(a.owner) === group ? 0 : 1; // prefer the open cluster\n const bo = b.owner && refKey(b.owner) === group ? 0 : 1;\n return (\n ao - bo ||\n ordinalOf(a.kind) - ordinalOf(b.kind) ||\n refKey(a).localeCompare(refKey(b))\n );\n });\n const next = ready[0];\n out.push(next);\n done.add(refKey(next));\n if (!next.owner) group = refKey(next); // a top-level object opens a new cluster\n for (const dep of dependents.get(refKey(next)) ?? [])\n indeg.set(dep, (indeg.get(dep) ?? 1) - 1);\n }\n return out;\n}\n\n// --- lowering + snapshot ------------------------------------------------------------------------\n\n/**\n * Author -> portable: lower each definable through its kind's engine (skipping unregistered kinds).\n * The single place authoring becomes portable; everything downstream (diff/emit/snapshot) is portable.\n */\nexport function lowerSchema(\n registry: KindRegistry,\n defs: Definable[],\n): PortableObject[] {\n const out: PortableObject[] = [];\n for (const d of defs) {\n const engine = registry.engine(d.kind);\n if (engine) out.push(engine.lower(d));\n }\n return out;\n}\n\n/**\n * The registry SNAPSHOT — portable objects grouped by kind. The open, generic replacement for\n * `PortableDb`'s fixed slots; serializes as plain JSON (it is plain data). Pre-launch: the format is\n * free to change, no version migration.\n */\nexport interface KindSnapshot {\n kinds: Record<string, PortableObject[]>;\n}\n\n/**\n * Group a flat portable schema into a snapshot (by kind). Pass `registry` to DROP kinds/objects\n * marked {@link KindEngine.excludeFromMigrations} (e.g. SurrealDB key-bearing access) so unmanaged,\n * secret-bearing objects never enter a snapshot / migration. Omit it to snapshot every object\n * unchanged.\n */\nexport function snapshotKinds(\n schema: PortableObject[],\n registry?: KindRegistry,\n): KindSnapshot {\n const kinds: Record<string, PortableObject[]> = {};\n for (const o of schema) {\n if (registry?.isExcludedFromMigrations(o)) continue;\n const bucket = kinds[o.kind] ?? [];\n bucket.push(o);\n kinds[o.kind] = bucket;\n }\n return { kinds };\n}\n\n/** Flatten a snapshot back into a portable schema (the inverse of {@link snapshotKinds}). */\nexport function snapshotObjects(snap: KindSnapshot): PortableObject[] {\n return Object.values(snap.kinds).flat();\n}\n\n// --- diff / plan --------------------------------------------------------------------------------\n\n/** One classified object change, carrying its ordering metadata + the portable sides for DDL. */\ninterface Change extends OrderNode {\n readonly op: \"add\" | \"change\" | \"remove\";\n readonly prev?: PortableObject;\n readonly next?: PortableObject;\n}\n\n/** An up/down DDL program (each a list of statements). */\nexport interface KindPlan {\n up: string[];\n down: string[];\n}\n\n/** The canonical change-detection key for an object — the kind's `canonical`, else its emitted DDL. */\nconst canonicalOf = (engine: KindEngine, p: PortableObject): string =>\n engine.canonical?.(p) ?? engine.emit(p).join(\"\\n\");\n\nconst orderNodeOf = (\n engine: KindEngine,\n portable: PortableObject,\n): OrderNode => ({\n kind: portable.kind,\n name: portable.name,\n deps: engine.deps?.(portable) ?? [],\n owner: engine.owner?.(portable),\n});\n\n/** Display identity: `kind:owner:name` (owner blank for a top-level object) + the display owner. */\nconst itemKey = (n: OrderNode) => `${n.kind}:${n.owner?.name ?? \"\"}:${n.name}`;\nconst itemTable = (n: OrderNode) => n.owner?.name ?? n.name;\n\nconst byKey = (schema: PortableObject[]) =>\n new Map(schema.map((o) => [refKey(o), o]));\n\n/**\n * Classify both sides into ordered add/change/remove sets — the shared core of plan + diff. A `change`\n * is two objects of the same key whose emitted DDL differs (same test as the fixed-slot engine). Each\n * class is topologically ordered parent-first; the caller reverses one class for drops/inversion.\n */\nfunction orderedChanges(\n registry: KindRegistry,\n prev: PortableObject[],\n next: PortableObject[],\n): { nonRemoves: Change[]; removes: Change[] } {\n const prevByKey = byKey(prev);\n const nextByKey = byKey(next);\n const changes: Change[] = [];\n for (const k of new Set([...prevByKey.keys(), ...nextByKey.keys()])) {\n const p = prevByKey.get(k);\n const n = nextByKey.get(k);\n const portable = n ?? p;\n if (!portable) continue;\n // Migration-unmanaged kinds/objects (e.g. key-bearing access) never diff — they're reconciled\n // out-of-band by driver commands, so they must not appear in gen/migrate/diff-live output.\n // Central choke point (a per-object predicate is fed the object that would be emitted).\n if (registry.isExcludedFromMigrations(portable)) continue;\n const engine = registry.engine(portable.kind);\n if (!engine) continue;\n const node = orderNodeOf(engine, portable);\n if (p && !n) changes.push({ op: \"remove\", prev: p, ...node });\n else if (!p && n) changes.push({ op: \"add\", next: n, ...node });\n else if (p && n && canonicalOf(engine, p) !== canonicalOf(engine, n))\n changes.push({ op: \"change\", prev: p, next: n, ...node });\n }\n const ord = (kind: string) => registry.ordinal(kind);\n return {\n nonRemoves: orderObjects(\n changes.filter((c) => c.op !== \"remove\"),\n ord,\n ),\n removes: orderObjects(\n changes.filter((c) => c.op === \"remove\"),\n ord,\n ),\n };\n}\n\nconst overwriteUp = (\n engine: KindEngine,\n a: PortableObject,\n b: PortableObject,\n): string[] =>\n engine.overwrite?.(a, b) ?? [...engine.remove(a), ...engine.emit(b)];\n\n/**\n * Diff two portable schema states into an executable up/down program, generically over the registry.\n *\n * `up` runs creates/changes parent-first (the dependency graph) then drops child-first; `down` is the\n * mirror: recreate drops parent-first, then undo creates/changes child-first. We invert PER OBJECT (not\n * by reversing the flat DDL list) so a kind's multi-line block — a table emitted with its fields —\n * keeps its internal order in both directions.\n */\nexport function planKinds(\n registry: KindRegistry,\n prev: PortableObject[],\n next: PortableObject[],\n): KindPlan {\n const { nonRemoves, removes } = orderedChanges(registry, prev, next);\n const up: string[] = [];\n const down: string[] = [];\n for (const c of nonRemoves) {\n const e = registry.engine(c.kind);\n if (!e) continue;\n if (c.op === \"add\" && c.next) up.push(...e.emit(c.next));\n else if (c.op === \"change\" && c.prev && c.next)\n up.push(...overwriteUp(e, c.prev, c.next));\n }\n for (const c of [...removes].reverse()) {\n const e = registry.engine(c.kind); // drops child-first\n if (e && c.prev) up.push(...e.remove(c.prev));\n }\n for (const c of removes) {\n const e = registry.engine(c.kind); // recreate dropped objects parent-first\n if (e && c.prev) down.push(...e.emit(c.prev));\n }\n for (const c of [...nonRemoves].reverse()) {\n const e = registry.engine(c.kind); // undo creates/changes child-first\n if (!e) continue;\n if (c.op === \"add\" && c.next) down.push(...e.remove(c.next));\n else if (c.op === \"change\" && c.prev && c.next)\n down.push(...overwriteUp(e, c.next, c.prev));\n }\n return { up, down };\n}\n\n/**\n * Display items for a change set, in up order (creates/changes parent-first, drops child-first). A kind\n * with `displayItems` decomposes into FINE-grained sub-items (per-field, each carrying its `table` so\n * the display groups them under it); otherwise it falls back to ONE whole-object item.\n */\nfunction diffItems(\n registry: KindRegistry,\n nonRemoves: Change[],\n removes: Change[],\n): DiffItem[] {\n const items: DiffItem[] = [];\n const push = (c: Change) => {\n const e = registry.engine(c.kind);\n if (!e) return;\n if (e.displayItems) {\n items.push(...e.displayItems(c.prev, c.next));\n return;\n }\n const base = { key: itemKey(c), table: itemTable(c), kind: c.kind };\n if (c.op === \"add\" && c.next)\n items.push({ ...base, op: \"add\", ddl: e.emit(c.next).join(\"\\n\") });\n else if (c.op === \"remove\" && c.prev)\n items.push({\n ...base,\n op: \"remove\",\n ddl: e.remove(c.prev).join(\"\\n\"),\n old: e.emit(c.prev).join(\"\\n\"),\n });\n else if (c.op === \"change\" && c.prev && c.next)\n items.push({\n ...base,\n op: \"change\",\n before: e.emit(c.prev).join(\"\\n\"),\n after: e.emit(c.next).join(\"\\n\"),\n });\n };\n for (const c of nonRemoves) push(c);\n for (const c of [...removes].reverse()) push(c);\n return items;\n}\n\n/**\n * The full {@link Diff} the CLI + migration model consume — up/down DDL + per-object display items +\n * the whole desired schema (`full`, for `--full`). This is what a driver's `Driver.diff` returns once\n * its kinds are on the registry (the generic counterpart of the fixed-slot `buildDiff`). Source-file\n * linkage on the items is attached by the caller (the snapshot's `files` map), so `file` is left unset.\n */\nexport function buildKindDiff(\n registry: KindRegistry,\n prev: PortableObject[],\n next: PortableObject[],\n): Diff {\n const { nonRemoves, removes } = orderedChanges(registry, prev, next);\n const { up, down } = planKinds(registry, prev, next);\n // `full` mirrors the items' granularity: a kind with `displayItems` projects its object as per-\n // sub-object adds (displayItems(undefined, portable)); otherwise one whole-object entry.\n const full = orderedSchema(registry, next).flatMap(\n ({ engine, portable, node }) => {\n if (engine.displayItems)\n return engine.displayItems(undefined, portable).map((it) => ({\n key: it.key,\n table: it.table,\n ddl: it.op === \"add\" ? it.ddl : \"\",\n }));\n return [\n {\n key: itemKey(node),\n table: itemTable(node),\n ddl: engine.emit(portable).join(\"\\n\"),\n },\n ];\n },\n );\n return { up, down, items: diffItems(registry, nonRemoves, removes), full };\n}\n\n/** Lower-already portable schema, topologically ordered, paired with each object's engine + node. */\nfunction orderedSchema(\n registry: KindRegistry,\n schema: PortableObject[],\n): { engine: KindEngine; portable: PortableObject; node: OrderNode }[] {\n const items = schema.flatMap((portable) => {\n const engine = registry.engine(portable.kind);\n return engine\n ? [{ engine, portable, node: orderNodeOf(engine, portable) }]\n : [];\n });\n const pos = new Map(\n orderObjects(\n items.map((i) => i.node),\n (k) => registry.ordinal(k),\n ).map((n, i) => [itemKey(n), i]),\n );\n return items.sort(\n (a, b) => (pos.get(itemKey(a.node)) ?? 0) - (pos.get(itemKey(b.node)) ?? 0),\n );\n}\n\n/**\n * Fresh-apply DDL for a portable schema: every object created, ordered across kinds by the graph.\n * (The `up` of a diff from an empty state.) Lower authoring first via {@link lowerSchema}.\n */\nexport function emitKinds(\n registry: KindRegistry,\n schema: PortableObject[],\n): string[] {\n // Skip migration-unmanaged kinds/objects (e.g. key-bearing access) — they're applied out-of-band\n // by driver commands.\n const managed = schema.filter(\n (o) => !registry.isExcludedFromMigrations(o),\n );\n return orderedSchema(registry, managed).flatMap(({ engine, portable }) =>\n engine.emit(portable),\n );\n}\n\n/**\n * Reverse direction, fanned out across kinds: introspect every introspectable kind off one live\n * connection and flatten into portable objects. The RESOLUTION of \"per-kind vs one driver read\":\n * the contract is per-kind ({@link KindEngine.introspect}), but a driver backs all of its kinds with\n * ONE shared (memoized) read of `conn` and slices out each kind's objects — so the fan-out here costs\n * a single round-trip, not N. A kind without `introspect` contributes nothing (not introspectable).\n */\nexport async function introspectKinds(\n registry: KindRegistry,\n conn: unknown,\n): Promise<PortableObject[]> {\n const out: PortableObject[] = [];\n for (const [kind, engine] of registry.entries()) {\n if (!engine.introspect) continue;\n // Skip STATICALLY migration-unmanaged kinds so the live side never phantom-diffs against a\n // schema that (by design) excludes them. A per-object predicate can't be evaluated without the\n // object — introspection still runs, and the diff choke point filters by object afterwards.\n if (registry.skipsIntrospection(kind)) continue;\n out.push(...(await engine.introspect(conn)));\n }\n return out;\n}\n","// The KIND REGISTRY — core-v2's generic, open replacement for the fixed object-kind slots.\n//\n// Today `PortableDb` hard-codes the object kinds a schema may contain (`tables`/`functions`/\n// `accesses`/`natives`) and the Driver's whole-DB methods switch on those slots. The kind registry\n// turns the slots into a REGISTRY a driver populates: each driver registers KINDS, and every kind\n// brings (a) its OWN authoring builder — any shape/chain it likes, fully typed — and (b) its engine\n// behavior (`lower`/`emit`/`remove`/`overwrite`/`deps`/`owner`/`introspect`) over THAT kind's objects.\n// Core orchestrates generically over the registry (see ./plan.ts) and never names a kind.\n//\n// What stays in core is the field/type VOCABULARY (`SFieldBase`, the Zod-drop-in `s.*`, `PortableType`,\n// codecs) — the substrate every kind builds on. Fields/types are NOT a kind: a table HAS fields, a\n// function's args ARE fields, an index REFERENCES fields. See docs/kind-registry.md.\n//\n// The registry is PER-DRIVER, not a module global: a driver builds one `KindRegistry` and registers\n// its kinds into it.\n\n/**\n * An authored definable, tagged with the KIND that owns it. Core dispatches on `kind` alone — every\n * other field is the kind's own business, handed straight to {@link KindEngine.lower}. This is the\n * neutral upper bound for a kind's authoring-object type (a driver's concrete `TableDef`/`FnDef` is a\n * structural subtype).\n */\nexport interface Definable {\n readonly kind: string;\n readonly name: string;\n}\n\n/**\n * A kind's PORTABLE object — the dialect-independent data shape core stores + diffs. A kind chooses\n * how structured this is: a table's portable form carries fields/indexes (so core can field-level\n * diff it); an opaque kind (function/access) carries a neutral identity + a `native` payload it\n * round-trips. Either way it is tagged with `kind`/`name` for cross-kind dispatch + ordering.\n */\nexport interface PortableObject {\n readonly kind: string;\n readonly name: string;\n}\n\n/** A reference to another object in the schema graph — the unit of cross-kind dependency ordering. */\nexport interface Ref {\n readonly kind: string;\n readonly name: string;\n}\n\n// `DiffItem` is a type-only import (erased at compile) — the display contract the `displayItems` hook\n// produces; no runtime cli->kind coupling, same arrangement as ./plan.ts.\nimport type { DiffItem } from \"../cli-kit/diff\";\n\n/**\n * What core needs to orchestrate ONE kind generically — it never inspects the specifics. The\n * change-vocabulary (`emit`/`remove`/`overwrite`) mirrors the Driver contract's, so a kind's behavior\n * is parity-checkable against the fixed-slot engine. `A` is the kind's authoring object, `P` its\n * portable object; both are opaque to core beyond the {@link Definable}/{@link PortableObject} bounds.\n */\nexport interface KindEngine<\n A extends Definable = Definable,\n P extends PortableObject = PortableObject,\n> {\n /** Authoring object -> this kind's portable object (normalized; both lowerings must converge here). */\n lower(authored: A): P;\n /** CREATE DDL for one portable object (a fresh apply / migration `up` for an added object). */\n emit(portable: P): string[];\n /** DROP DDL for one portable object (`up` for a removed object, `down` for an added one). */\n remove(portable: P): string[];\n /**\n * In-place CHANGE DDL taking `prev` to `next` (the dialect's ALTER/OVERWRITE). The spine calls\n * `overwrite(next, prev)` to roll a change back. A kind with no in-place form recreates: implement\n * as `[...remove(prev), ...emit(next)]`. Default (omitted) = recreate via emit(next).\n */\n overwrite?(prev: P, next: P): string[];\n /**\n * The CANONICAL change-detection key: the spine treats prev/next of the same object as a CHANGE iff\n * their `canonical` differs. Default (omitted) = `emit(portable).join(\"\\n\")` — so a kind whose `emit`\n * is already its canonical form needs nothing. Override when `emit` is FAITHFUL but some clauses must\n * be EXCLUDED from equality — because the DB rewrites them on read (a cast suffix like `'x'::text`,\n * added parens like `(a>0)`) or never introspects them (a COMMENT, an index) — so a faithful `emit` would phantom-diff a\n * freshly-applied schema against `introspect`. Return `emit` MINUS those clauses: they stay create-time\n * faithful in `emit`, but don't count as changes. `canonical(a) === canonical(b)` MUST mean \"no\n * migration needed\". Affects ONLY classification; `emit`/`overwrite` (the DDL) are unaffected.\n */\n canonical?(portable: P): string;\n /**\n * Fine-grained DISPLAY items for a change of this object — so `better-schemic diff` shows per-SUB-OBJECT\n * changes (a table decomposes into per-FIELD items: `field:user:name` changed), each carrying its\n * owner `table` so the display GROUPS them hierarchically under it, instead of one coarse whole-object\n * item. Called `(prev, next)`: a change diffs the two; `(undefined, next)` lists the object's\n * sub-items as adds — the `--full` projection core uses for the full desired-state view. Default\n * (omitted) = ONE whole-object item. DISPLAY ONLY — never affects up/down DDL (that is\n * `emit`/`overwrite`); a structured driver reuses the per-field diff it already computes. Leave\n * `DiffItem.file` unset (the caller attaches source linkage).\n */\n displayItems?(prev: P | undefined, next: P | undefined): DiffItem[];\n /**\n * Objects this one must be emitted AFTER — the cross-kind dependency edges (a field/index -> its\n * table; an edge table -> its in/out tables; an event -> its table + any function it calls). Drives\n * the topological sort in ./plan.ts. Omitted = no dependencies.\n */\n deps?(portable: P): Ref[];\n /**\n * The owning object to CLUSTER next to in the emitted order (an index's table) — readability only,\n * never overrides {@link deps}. Omitted = a top-level object.\n */\n owner?(portable: P): Ref | undefined;\n /**\n * The STRUCTURAL container this object is nested within (an index's/field's table) — used for\n * ADDRESSING and grouping (the CLI's dotted `parent.child`, e.g. `sc index info user.email_idx`) and\n * distinct from {@link owner}, which is a DISPLAY choice (diff clustering). A kind may declare `parent`\n * (it IS nested) while declining `owner` (it doesn't want per-parent diff clustering), or vice versa.\n * The CLI resolves a nesting address as `parent ?? owner` (so a kind that only sets `owner` still\n * addresses dotted). Omitted (and no `owner`) = a top-level object, addressed by its bare name.\n */\n parent?(portable: P): Ref | undefined;\n /**\n * Live connection -> all portable objects of THIS kind (the reverse direction). Introspection is\n * often one `INFO`/catalog read yielding every kind at once; a driver backs all of its kinds'\n * `introspect` with one shared (memoized) read and slices out this kind's objects. Omitted -> this\n * kind isn't introspectable (diff/emit still work from authored state).\n */\n introspect?(conn: unknown): Promise<P[]>;\n /**\n * How this kind is PRESENTED — its human labels and the folder its objects render into. All optional\n * with sensible defaults off the kind name (see {@link KindRegistry.display}), so a kind only declares\n * what the defaults get wrong (e.g. `plural: \"Indexes\"`, or `folder: \"access\"`). DISPLAY ONLY.\n */\n display?: KindDisplay;\n /**\n * UNMANAGED by the migration pipeline: when `true`, objects of this kind are EXCLUDED from\n * snapshot / diff / gen AND from the introspect-compare — so they never enter a migration file nor\n * phantom-diff. For a kind whose lifecycle doesn't fit committed migrations: e.g. SurrealDB\n * `DEFINE ACCESS`, which carries a secret the DB redacts on introspection (can't round-trip) and\n * rotates on its own cadence. Such a kind is managed OUT-OF-BAND via the driver's own commands\n * (`sc <kind> …`). `emit`/`lower` still work (a driver command may use them); only the automatic\n * migration lifecycle skips it. Omitted/false = a normal, migration-managed kind.\n *\n * A PREDICATE form (`(portable) => boolean`) decides PER OBJECT — for a kind whose objects are\n * managed only when they round-trip cleanly (e.g. SurrealDB access: key-free defs are manageable,\n * key-bearing/redacted ones are not). The object is REQUIRED by\n * {@link KindRegistry.isExcludedFromMigrations}; only a boolean `true` also skips introspection\n * ({@link KindRegistry.skipsIntrospection}) — a predicate can't be decided there.\n */\n excludeFromMigrations?: boolean | ((portable: PortableObject) => boolean);\n}\n\n/** Per-kind presentation metadata (labels + output folder). All optional; core fills defaults. */\nexport interface KindDisplay {\n /** Title-Case singular, e.g. `\"Table\"`, `\"Field\"`. Default: the kind name, capitalized. */\n label?: string;\n /** Title-Case plural, e.g. `\"Tables\"`, `\"Indexes\"`. Default: the English plural of `label`. */\n plural?: string;\n /** The directory this kind's objects render into. Default: the lowercase slug of `plural`. */\n folder?: string;\n}\n\n/** A kind's resolved presentation — every field filled (the shape {@link KindRegistry.display} returns). */\nexport type ResolvedDisplay = Required<KindDisplay>;\n\n/** A kind's full spec: its `name`, its `build` (the driver's authoring entry), and its engine. */\nexport type KindSpec<\n Build extends (...args: never[]) => unknown,\n A extends Definable,\n P extends PortableObject,\n> = { name: string; build: Build } & KindEngine<A, P>;\n\n/** `\"table\"` -> `\"Table\"`. */\nfunction capitalize(s: string): string {\n return s ? s[0].toUpperCase() + s.slice(1) : s;\n}\n\n/** A plain English pluralizer for kind labels: `Index` -> `Indexes`, `Policy` -> `Policies`. */\nfunction pluralize(s: string): string {\n if (/[^aeiou]y$/i.test(s)) return `${s.slice(0, -1)}ies`;\n if (/(s|x|z|ch|sh)$/i.test(s)) return `${s}es`;\n return `${s}s`;\n}\n\n/** `\"Tables\"` -> `\"tables\"`; collapses non-alphanumerics to single dashes (a filesystem-safe folder). */\nfunction slugify(s: string): string {\n return s\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\n\n/**\n * A driver's set of registered kinds + the generic behavior the spine reads off them. Built once per\n * driver; `define` registers a kind and returns the driver's OWN `build` function UNCHANGED — so the\n * driver writes `export const defineTable = registry.define({ name: \"table\", build, ...engine })` and\n * keeps full type-safety + DX (TS preserves a generic `build`'s parameters across the passthrough).\n */\nexport class KindRegistry {\n // Heterogeneous kinds erase at the engine seam (engine ops are structural); the AUTHORING side\n // keeps full types via `define`'s `Build` passthrough.\n // biome-ignore lint/suspicious/noExplicitAny: the engine seam is intentionally type-erased.\n private readonly kinds = new Map<string, KindEngine<any, any>>();\n\n /**\n * Register a KIND. `build` is the driver's own authoring entry — ANY shape/chain — and its type\n * flows through unchanged (type-safety + DX are the driver's to design). The engine fns give core\n * the generic behavior. Registration ORDER is the kind's ordinal (the stable tie-break among\n * independent objects in {@link orderObjects}), so register coarse-to-fine (table before index).\n */\n define<\n Build extends (...args: never[]) => unknown,\n A extends Definable,\n P extends PortableObject,\n >(spec: KindSpec<Build, A, P>): Build {\n this.kinds.set(spec.name, spec);\n return spec.build;\n }\n\n /** The engine for `kind`, or undefined if no such kind is registered. */\n // biome-ignore lint/suspicious/noExplicitAny: the engine erases at this seam (see `kinds`).\n engine(kind: string): KindEngine<any, any> | undefined {\n return this.kinds.get(kind);\n }\n\n /**\n * Is this PORTABLE OBJECT UNMANAGED by the migration pipeline (its engine set\n * {@link KindEngine.excludeFromMigrations})? The snapshot/diff/emit spine skips such objects — see\n * the flag's docs. The OBJECT is required: a per-object predicate can't be evaluated without it, and\n * defaulting to \"managed\" would let a key-bearing object slip into a migration. An unregistered kind\n * is treated as managed (false), so a stray object never gets silently dropped by a typo.\n */\n isExcludedFromMigrations(portable: PortableObject): boolean {\n const flag = this.kinds.get(portable.kind)?.excludeFromMigrations;\n return typeof flag === \"function\" ? flag(portable) : flag === true;\n }\n\n /**\n * Whether `kind` is STATICALLY excluded from migrations (`excludeFromMigrations === true`), so even\n * introspection skips it. A per-object PREDICATE can't be decided without an object: introspection\n * runs for the kind, and the diff/snapshot/emit choke points filter by object afterwards.\n */\n skipsIntrospection(kind: string): boolean {\n return this.kinds.get(kind)?.excludeFromMigrations === true;\n }\n\n /**\n * A kind's resolved presentation — `label`/`plural`/`folder`, with defaults derived from the kind\n * name for whatever the driver left unset. Works for unregistered display sub-kinds too (e.g. the\n * `\"field\"` items a table's `displayItems` emits) — they just get the name-derived defaults.\n */\n display(kind: string): ResolvedDisplay {\n const d = this.kinds.get(kind)?.display ?? {};\n const label = d.label ?? capitalize(kind);\n const plural = d.plural ?? pluralize(label);\n return { label, plural, folder: d.folder ?? slugify(plural) };\n }\n\n /** Registered kind names, in registration order (== ordinal order). */\n names(): string[] {\n return [...this.kinds.keys()];\n }\n\n /**\n * A kind's ORDINAL = its registration index. Used ONLY as a tie-break among objects with no\n * dependency relation, so independent objects come out stably layered (readability); it never\n * overrides the dependency graph. An unknown kind sorts last.\n */\n ordinal(kind: string): number {\n const i = this.names().indexOf(kind);\n return i === -1 ? Number.MAX_SAFE_INTEGER : i;\n }\n\n /** [name, engine] pairs in registration order — the spine iterates these. */\n // biome-ignore lint/suspicious/noExplicitAny: the engine erases at this seam (see `kinds`).\n entries(): [string, KindEngine<any, any>][] {\n return [...this.kinds.entries()];\n }\n}\n","// The DRIVER interface — the dialect seam (see docs/MULTI-DB-SPIKE.md).\n//\n// Everything dialect-specific lives behind a `Driver`: lowering authoring to the Struct-IR, emitting\n// DDL, introspecting a live DB, normalizing to a canonical form, and executing. Everything ABOVE the\n// driver (the diff algorithm, the magicast TS-merge, the migration model, the CLI shell) stays\n// dialect-free and calls these ops.\n//\n// The connection type is a driver-private parameter `Conn`: the orchestration treats it opaquely and\n// only ever hands it back to the SAME driver. So the Surreal driver is `Driver<Surreal>`, and core\n// never sees the concrete type. The AUTHORING\n// types (`Tbl`/`Def`) are driver-private the same way — opaque to core beyond the neutral\n// `Authored`/`AuthoredDef` bounds — so the neutral engine never names a dialect's concrete builder\n// (`TableDef`/`StandaloneDef`).\n\nimport type { ResolvedConfig } from \"../cli-kit/config\";\nimport type { Diff } from \"../cli-kit/diff\";\nimport type { Filter } from \"../cli-kit/filter\";\nimport type { PullPlan } from \"../cli-kit/merge\";\nimport type { Definable, KindRegistry, PortableObject } from \"../kind\";\nimport type { SecretProvider, SecretRef } from \"../secrets\";\n\n/**\n * The dialect-NEUTRAL authoring contract — the only structure the orchestration reads off an\n * authored object (everything else is opaque and handed straight to {@link Driver.explode}). A table\n * contributes just its `name`; this is the upper bound for a driver's table-authoring type. The\n * Surreal `TableDef` is a structural subtype, as is any future dialect's table builder.\n */\nexport interface Authored {\n readonly name: string;\n}\n\n/**\n * The neutral contract for a standalone (non-table) authored object — an event/function/access. It\n * adds a `kind` discriminant and, for objects owned by a table (e.g. an event), the owner `table`\n * name (so the snapshot can file-link a child object under its parent). The Surreal `StandaloneDef`\n * union is a structural subtype.\n */\nexport interface AuthoredDef extends Authored {\n readonly kind: string;\n readonly table?: string;\n}\n\n/**\n * A single emitted DDL statement, structured: object identity (`kind`/`name`/`table`) + the dialect\n * `ddl` string, plus an optional clause map (each value an `ALTER … <set>` form) for dialects that\n * diff clause-level. `kind` is a dialect-defined string the orchestration treats opaquely — the\n * SurrealDB `DefineStatement` (with its fixed kind union) is a structural subtype of this.\n */\nexport interface Statement {\n kind: string;\n name: string;\n table?: string;\n ddl: string;\n clauses?: Record<string, string>;\n /**\n * Apply-time secret bindings for this statement's `$param` placeholders — `param` name ->\n * a write-only {@link SecretRef}. Collected into {@link Diff.bindings}; the value never lives here\n * (resolved at apply through a `SecretProvider`). See {@link Diff.bindings}.\n */\n bindings?: Record<string, SecretRef>;\n}\n\n/** Options for {@link Driver.emit} — mirrors the existing `DefineOptions` (e.g. IF NOT EXISTS). */\nexport interface EmitOptions {\n ifNotExists?: boolean;\n overwrite?: boolean;\n}\n\n/** Options for {@link Driver.apply}. */\nexport interface ApplyOptions {\n /**\n * Run the whole batch atomically. `migrate` wraps up/down + `_migrations` bookkeeping in one\n * transaction; a driver that can't MUST surface that (the migration model degrades to best-effort).\n */\n transactional?: boolean;\n}\n\n/** Per-connection overrides (url/namespace/credentials) — superset across dialects. */\nexport interface ConnectionOverrides {\n url?: string;\n namespace?: string;\n database?: string;\n username?: string;\n password?: string;\n authLevel?: string;\n}\n\n/** The direction a migration is applied in. */\nexport type MigrationDirection = \"up\" | \"down\";\n\n/** A migration's bookkeeping identity, recorded in the migrations-tracking table. */\nexport interface MigrationRecord {\n tag: string;\n file: string;\n /** sha of the migration file at apply time (drift detection). */\n checksum: string;\n}\n\n/**\n * The apply-time, dialect-specific half of the migration runner. The orchestration (which\n * migrations are pending, ordering, the lock-then-loop) stays driver-neutral in cli/migrate.ts;\n * this capability owns the SQL: the tracking table, the applied-records, the advisory lock, and the\n * atomic apply+record. A driver WITHOUT it can't run migrations (diff/gen still work). `Conn` is the\n * driver's own connection type.\n */\nexport interface MigrationStore<Conn = unknown> {\n /** This dialect's migration-file extension, e.g. `\".surql\"` (SurrealDB). */\n readonly extension: string;\n /** Render a diff as this dialect's migration-file body (e.g. SurrealQL `IF $direction` up/down). */\n render(tag: string, diff: Diff): string;\n /** Ensure the migrations-tracking table exists. */\n ensure(conn: Conn, table: string): Promise<void>;\n /** Applied migrations: tag -> checksum recorded at apply time. */\n applied(conn: Conn, table: string): Promise<Map<string, string>>;\n /**\n * Apply one migration's `up`/`down` PROGRAM plus its bookkeeping write atomically: on `up` record\n * the migration, on `down` erase it — so the record is written iff the DDL actually applied.\n */\n apply(\n conn: Conn,\n table: string,\n m: {\n content: string;\n direction: MigrationDirection;\n record: MigrationRecord;\n },\n ): Promise<void>;\n /** Record a migration as applied WITHOUT running its DDL (baseline of an existing DB). */\n record(conn: Conn, table: string, record: MigrationRecord): Promise<void>;\n /** Drop all applied records (baseline-squash reconcile). */\n clear(conn: Conn, table: string): Promise<void>;\n /** Take an advisory lock so two runs can't race — throws if already held. */\n lock(conn: Conn, table: string): Promise<void>;\n /** Release the advisory lock (idempotent). */\n unlock(conn: Conn, table: string): Promise<void>;\n}\n\n/**\n * An OPTIONAL throwaway-instance capability for round-trip canonicalization and `sz check`'s\n * migration replay. Absent -> `check`/replay-verification is degraded/unavailable (diff/apply still\n * work, since a kind's `lower`/`introspectAll` already canonicalize).\n */\nexport interface ShadowCapability<Conn> {\n /** Apply `ddl` to a fresh scratch DB, introspect it back to portable objects, then drop it. */\n roundTrip(\n conn: Conn,\n config: ResolvedConfig,\n ddl: string,\n ): Promise<PortableObject[]>;\n /** Spin up a fully-isolated ephemeral instance (for migration replay). Caller must `stop()`. */\n ephemeral?(): Promise<{ conn: Conn; stop: () => Promise<void> }>;\n}\n\n/**\n * User-defined DB functions — the `.call` side of the query layer's (B) surface (DB functions as code).\n * `invoke` calls a defined function by name with already-encoded args and returns the function's RAW\n * result (the driver extracts it from its own response shape — surreal `RETURN fn::name($a)` yields the\n * value; a row-returning call yields a row set). The caller decodes that raw value through the\n * function's `.returns(R)` schema via `callFunction` in `@better-schemic/core/query`. A defined function still\n * emits/migrates via the schema engine regardless; this capability only adds INVOCATION.\n */\nexport interface CallableFunctions<Conn = unknown> {\n invoke(\n conn: Conn,\n name: string,\n args: Record<string, unknown>,\n ): Promise<unknown>;\n}\n\n// --- driver-contributed CLI commands -----------------------------------------------------------\n// A driver may contribute dialect-specific commands invoked as `sc <kind> <verb> [args]` (e.g. surreal\n// `sc access rotate <name>`). CORE provides only the general\n// mechanism: it discovers `driver.commands`, registers each, parses argv against `args`, resolves the\n// connection, and dispatches to `run` with a {@link CommandContext}. The DRIVER owns the dialect logic\n// and the meaning of each kind/verb/arg — core never names one. Depth is fixed at kind/verb.\n\n/** A declared argument for a {@link DriverCommand} — used for parsing + `--help`. */\nexport interface CommandArgs {\n /**\n * Positional args, in order. Core collects ALL positional tokens into a list (incl. raw `key=value`)\n * and the driver interprets + validates arity; mark the last `variadic` for \"one or more\".\n */\n positionals?: readonly {\n name: string;\n required?: boolean;\n variadic?: boolean;\n help?: string;\n }[];\n /** Named flags. `value: true` takes a value (`--user U`); otherwise it's a boolean (`--dry-run`). */\n flags?: readonly {\n name: string;\n value?: boolean;\n required?: boolean;\n help?: string;\n }[];\n}\n\n/** argv parsed against a command's {@link CommandArgs}: positional tokens (driver-interpreted) + flags. */\nexport interface ParsedCommandArgs {\n /** Every positional token in order (incl. raw `key=value`); the driver interprets them. */\n positionals: string[];\n /** Flags: a value-flag -> its string, a boolean flag -> `true`, an absent flag -> `undefined`. */\n flags: Record<string, string | boolean | undefined>;\n}\n\n/** Output + input helpers core hands a command (so a driver never touches stdio directly). */\nexport interface CommandIo {\n ok(message: string): void;\n fail(message: string): void;\n info(message: string): void;\n /** Prompt for a line of input (`hidden` masks it) — for a sensitive value not passed inline (no shell-history leak). */\n prompt(question: string, opts?: { hidden?: boolean }): Promise<string>;\n}\n\n/** The context core hands a {@link DriverCommand.run}: a connected db + the resolved config + io + secrets. */\nexport interface CommandContext<Conn = unknown> {\n conn: Conn;\n config: ResolvedConfig;\n io: CommandIo;\n /** The configured secret provider (default reads `process.env`) for resolving {@link SecretRef}s. */\n secrets: SecretProvider;\n}\n\n/**\n * A driver-contributed CLI command — `sc <kind> <verb> [args]`. Core dispatches; the driver owns the\n * dialect logic in {@link run}. The driver validates positional arity itself (core only collects them).\n */\nexport interface DriverCommand<Conn = unknown> {\n /** Kind namespace — `sc <kind> …` (e.g. `\"access\"`, `\"table\"`). */\n kind: string;\n /** Verb under the kind — `sc <kind> <verb>` (e.g. `\"rotate\"`, `\"check\"`, `\"find\"`). */\n verb: string;\n /** One-line help shown in the command listing. */\n summary: string;\n /** Declared args for parsing + `--help`. */\n args?: CommandArgs;\n run(ctx: CommandContext<Conn>, args: ParsedCommandArgs): Promise<void>;\n}\n\n/**\n * A database dialect, expressed as a SET OF KINDS (core-v2). The driver registers its object kinds on\n * `registry`; core orchestrates schema ops GENERICALLY over it (`lowerSchema`/`buildKindDiff`/\n * `emitKinds`/`orderObjects`) — it never names a kind. The driver owns only what isn't generic: the\n * authoring -> kinded `explode`, a single-read `introspectAll`, the connection lifecycle, and the\n * dialect-specific command capabilities. The field/type substrate (`PortableType`/`s.*`) stays core.\n * See docs/kind-registry-flip-plan.md.\n */\nexport interface Driver<\n Conn = unknown,\n Tbl extends Authored = Authored,\n Def extends AuthoredDef = AuthoredDef,\n> {\n readonly name: string;\n\n // --- kind registry (the schema engine) -----------------------------------------------------\n /** This driver's registered KINDS. Core runs lower/diff/emit/order generically over it. */\n readonly registry: KindRegistry;\n /**\n * Authoring (loaded `defineTable`/standalone defs) -> kinded {@link Definable}s. The driver-side\n * fan-out: one inline-authored table explodes into `[table, ...index, ...event/constraint]`, each\n * tagged with its `kind`. Core then lowers via `lowerSchema(registry, explode(...))` — so\n * `KindEngine.lower` stays 1:1 and the contract needs no explode hook.\n */\n explode(tables: Tbl[], defs: Def[]): Definable[];\n /**\n * Live connection -> ALL portable objects, fanned across kinds from ONE read (INFO STRUCTURE /\n * the system catalog). Must canonicalize IDENTICALLY to lowering (a clean apply round-trips to a zero diff)\n * and be COMPLETE (return every diffable kind, else presence-phantom-diffs). `exclude` skips tables\n * by name.\n */\n introspectAll(conn: Conn, exclude?: Set<string>): Promise<PortableObject[]>;\n\n // --- execution -----------------------------------------------------------------------------\n connect(config: ResolvedConfig, over?: ConnectionOverrides): Promise<Conn>;\n apply(conn: Conn, statements: string[], opts?: ApplyOptions): Promise<void>;\n /** Tear down a connection opened by {@link connect} (the orchestration owns the lifecycle). */\n close(conn: Conn): Promise<void>;\n\n // --- optional capabilities -----------------------------------------------------------------\n readonly shadow?: ShadowCapability<Conn>;\n /** Apply-time migration bookkeeping. Absent -> this driver can't run migrations (diff/gen still do). */\n readonly migrations?: MigrationStore<Conn>;\n\n // --- optional COMMAND capabilities ---------------------------------------------------------\n // The dialect-agnostic CLI routes each schema-syncing command through one of these. A driver that\n // omits a capability makes that command unavailable on it — the CLI never hardcodes `if surreal`.\n\n /**\n * Diff the LIVE database against the loaded schema into executable up/down DDL. Owns every\n * dialect-specific normalization and apply-time fixup (Surreal: a shadow-DB round-trip to cancel\n * formatting noise, the redacted-access-key swap, and the implicit-wildcard OVERWRITE re-mark), so\n * the result is safe to apply as-is. Backs `diff --live`, `push`, and the baseline reconcile.\n */\n diffLive?(conn: Conn, config: ResolvedConfig, filter: Filter): Promise<Diff>;\n /** Reduce a live diff (from {@link diffLive}) to the statements `push` applies; `prune: false` keeps removals. */\n syncPlan?(diff: Diff, prune?: boolean): string[];\n /**\n * Dialect-specific CLI commands invoked as `sc <kind> <verb> [args]` — e.g. surreal `access rotate`.\n * Core discovers + dispatches them generically (see {@link DriverCommand});\n * it never names a kind/verb. Absent -> this driver contributes no extra commands.\n */\n readonly commands?: readonly DriverCommand<Conn>[];\n /**\n * Render portable objects to per-file source in THIS dialect's `s.*` syntax, filtered — the codegen\n * behind the offline `diff --ts` and `pull`. Takes `PortableObject[]` (this driver's own portable\n * shape): `diff --ts` renders the SNAPSHOT side (stored portable) and the DESIRED side\n * (`lowerSchema(explode(...))`) at MATCHING fidelity so an in-sync schema yields identical files;\n * `pull` renders the introspected DB. The driver re-derives its structured form from the portable\n * objects (parsing its own DDL where needed — docs/kind-registry-flip-plan.md §6b). `single` (a file\n * key) folds everything into one module; otherwise `fileFor` maps each object to its own file.\n */\n renderSchema?(\n objects: PortableObject[],\n filter: Filter,\n fileFor: (kind: string, name: string) => string,\n single?: string,\n ): Map<string, string>;\n /**\n * The two sides of `diff --ts --live` rendered to per-file source: the live DB (`current`) and the\n * declared schema (`desired`), both normalized through the dialect so an unchanged schema yields\n * identical files.\n */\n diffTsLive?(\n conn: Conn,\n config: ResolvedConfig,\n filter: Filter,\n fileFor: (kind: string, name: string) => string,\n single?: string,\n ): Promise<{ current: Map<string, string>; desired: Map<string, string> }>;\n /**\n * Replay every migration into a throwaway engine and diff the result against the schema (`check`).\n * Owns ephemeral-engine selection + setup; `log` receives progress lines. Needs a {@link shadow}-\n * class capability. An empty diff means the migrations reproduce the schema.\n */\n checkReplay?(\n config: ResolvedConfig,\n over: ConnectionOverrides,\n filter: Filter,\n log: (msg: string) => void,\n ): Promise<Diff>;\n /** Introspect the live DB and plan schema-file codegen (`pull`); writing is the neutral `applyPull`. */\n planPull?(\n conn: Conn,\n config: ResolvedConfig,\n opts: { filter: Filter; keepLocal?: boolean },\n ): Promise<PullPlan>;\n /** A human-readable server identity for `doctor` (e.g. \"SurrealDB 3.1.3\"); throws if unreachable. */\n serverInfo?(conn: Conn): Promise<string>;\n /**\n * Run a raw READ query and return rows — for connection RESOLVERS (a multi-connection resolver's\n * `ctx.connections.<name>.query(...)`) and `seed`. The `sql` is this dialect's query language; the\n * orchestration treats the rows opaquely. Absent -> a resolver can't read from this connection.\n */\n query?<T = unknown>(\n conn: Conn,\n sql: string,\n vars?: Record<string, unknown>,\n ): Promise<T[]>;\n /**\n * User-defined DB functions ((B) of the query layer) — invoke a defined function + decode the result.\n * Absent -> no `.call()` surface on this driver (the function still emits/migrates). See\n * {@link CallableFunctions}.\n */\n readonly callable?: CallableFunctions<Conn>;\n /**\n * The dialect-specific files `better-schemic init` scaffolds, keyed by project-relative path: a\n * connections-only `better-schemic.config.ts` (using this driver's `<driver>Connection` factory), a sample\n * schema module in this dialect's `s.*`, a seed stub, a `.env.example`, … The CLI writes them\n * verbatim (never overwriting) alongside the dialect-neutral migration snapshot it records itself.\n * Absent -> `better-schemic init` can't scaffold a project for this driver.\n */\n initScaffold?(): Record<string, string>;\n /**\n * Scaffold a NEW entity file's contents — the starter `s.*` / `define*` module for an object of\n * `kind` named `name` (e.g. `(\"table\", \"user\")` -> a `defineTable(\"user\", { … })` module in this\n * dialect's authoring). Returns the file text; the CLI writes it under the kind's\n * {@link KindRegistry.display} folder. THROW for a kind this driver can't author (the CLI surfaces\n * the message). Absent -> `better-schemic new` is unavailable for this driver.\n */\n scaffoldEntity?(kind: string, name: string): string;\n}\n\n// --- Registry -----------------------------------------------------------------------------------\n\n// Shared across every loaded copy of `@better-schemic/core` so the registry is process-global — the CLI run\n// via `bunx` resolves its own core, while a driver loaded from the user's project resolves the\n// project's core; without sharing, the driver self-registers in one Map and the CLI reads an empty\n// one. Keyed by a REGISTERED symbol (`Symbol.for`) — same key in every instance, but no string-keyed\n// `globalThis` pollution and namespaced so it can't collide.\nconst REGISTRY_KEY = Symbol.for(\"@better-schemic/core.driverRegistry\");\nconst REGISTRY: Map<string, Driver<unknown>> = ((\n globalThis as Record<symbol, Map<string, Driver<unknown>> | undefined>\n)[REGISTRY_KEY] ??= new Map<string, Driver<unknown>>());\n\n/** Register a driver under its `name` (idempotent; last write wins). */\nexport function registerDriver(driver: Driver<unknown>): void {\n REGISTRY.set(driver.name, driver);\n}\n\n/** Look up a registered driver, or throw with the list of known names. */\nexport function getDriver(name: string): Driver<unknown> {\n const d = REGISTRY.get(name);\n if (!d) {\n const known = [...REGISTRY.keys()].join(\", \") || \"(none registered)\";\n throw new Error(`Unknown database driver \"${name}\". Registered: ${known}.`);\n }\n return d;\n}\n\n/** All registered driver names (for help text / config validation). */\nexport function driverNames(): string[] {\n return [...REGISTRY.keys()];\n}\n"],"mappings":";AA2BA,IAAM,SAAS,CAAC,MAAW,GAAG,EAAE,IAAI,IAAI,EAAE,IAAI;AAmBvC,SAAS,aACd,OACA,WACK;AACL,QAAMA,SAAQ,IAAI,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;AACtD,QAAM,QAAQ,IAAI,IAAoB,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;AACtE,QAAM,aAA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AAS,KAAK,CAAC;AAC5B;","names":["byKey"]}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// src/connection.ts
|
|
2
|
+
function connectionEntry(driver, input, extras) {
|
|
3
|
+
return {
|
|
4
|
+
__betterSchemic: "connection",
|
|
5
|
+
driver,
|
|
6
|
+
...extras?.client ? { client: extras.client } : {},
|
|
7
|
+
...extras?.label ? { label: extras.label } : {},
|
|
8
|
+
async resolve(ctx, args) {
|
|
9
|
+
const out = typeof input === "function" ? await input(ctx, args) : input;
|
|
10
|
+
return Array.isArray(out) ? out : [out];
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
function isConnectionEntry(v) {
|
|
15
|
+
return typeof v === "object" && v !== null && v.__betterSchemic === "connection";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// src/driver/portable.ts
|
|
19
|
+
var scalar = (name) => ({
|
|
20
|
+
t: "scalar",
|
|
21
|
+
name
|
|
22
|
+
});
|
|
23
|
+
var literal = (value) => ({
|
|
24
|
+
t: "literal",
|
|
25
|
+
value
|
|
26
|
+
});
|
|
27
|
+
var option = (inner) => inner.t === "scalar" && inner.name === "any" ? inner : { t: "option", inner };
|
|
28
|
+
var nullable = (inner) => {
|
|
29
|
+
if (inner.t === "scalar" && inner.name === "any") return inner;
|
|
30
|
+
if (inner.t === "option")
|
|
31
|
+
return { t: "option", inner: nullable(inner.inner) };
|
|
32
|
+
return { t: "nullable", inner };
|
|
33
|
+
};
|
|
34
|
+
var array = (elem, size) => ({
|
|
35
|
+
t: "array",
|
|
36
|
+
elem,
|
|
37
|
+
...size !== void 0 ? { size } : {}
|
|
38
|
+
});
|
|
39
|
+
var union = (members) => members.length === 1 ? members[0] : { t: "union", members };
|
|
40
|
+
var record = (tables) => ({
|
|
41
|
+
t: "record",
|
|
42
|
+
tables
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
export {
|
|
46
|
+
connectionEntry,
|
|
47
|
+
isConnectionEntry,
|
|
48
|
+
scalar,
|
|
49
|
+
literal,
|
|
50
|
+
option,
|
|
51
|
+
nullable,
|
|
52
|
+
array,
|
|
53
|
+
union,
|
|
54
|
+
record
|
|
55
|
+
};
|
|
56
|
+
//# sourceMappingURL=chunk-LC3VHUM2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/connection.ts","../src/driver/portable.ts"],"sourcesContent":["// The neutral MULTI-CONNECTION contract (design: docs/MULTI-CONNECTION.md). A project's config maps\n// names to CONNECTIONS; each is produced by a per-driver `<driver>Connection(...)` factory that wraps\n// {@link connectionEntry} with its own typed connection shape. Everything here is dialect-free — the\n// CLI reads only these neutral fields; driver-specific connection params ride on the driver's own\n// config type. The resolution engine (lazy DAG, fan-out, addressing) lives in the CLI layer.\n\n// Type-only (erased): the resolved per-connection config a factory-embedded `client` opener receives.\nimport type { ResolvedConfig } from \"./cli-kit/config\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/** Minimal Standard Schema v1 surface — what a connection's `args` schema must expose. */\nexport interface StandardSchemaLike {\n \"~standard\": {\n validate(\n value: unknown,\n ): MaybePromise<\n { value: unknown } | { issues: readonly { message: string }[] }\n >;\n };\n}\n\n/** The dialect-neutral fields the orchestration reads off every connection config. */\nexport interface ConnectionConfigBase {\n /** Schema dir (the desired state + its migration files/snapshot). Shared dir = shared schema. */\n schema: string;\n /** Optional DISPLAY label for this config within a bulk (array) resolution — reporting/logs only. */\n key?: string;\n /** Migrations dir override; defaults relative to `schema`. */\n migrations?: string;\n}\n\n/** A live, queryable handle to ANOTHER (already-resolved) connection, for use inside a resolver. */\nexport interface ResolvedConnectionHandle {\n query<T = unknown>(sql: string, vars?: Record<string, unknown>): Promise<T[]>;\n}\n\n/**\n * What a connection RESOLVER receives. `connections` is a LAZY proxy of the other connections —\n * touching one resolves + connects it on demand (so the dependency graph falls out of access; cycles\n * error). `args` are CLI `--arg k=v` values (so a resolver can yield a SUBSET without resolving all).\n */\nexport interface ResolveContext {\n connections: Record<string, ResolvedConnectionHandle>;\n env: NodeJS.ProcessEnv;\n}\n\n/**\n * The opaque, branded output of a `<driver>Connection(...)` factory — the only thing `defineConfig`'s\n * `connections` map accepts. Never hand-authored. `driver` is the package the CLI dynamically loads;\n * `resolve` always normalizes to an ARRAY (a single connection -> one element, a collection -> many).\n */\nexport interface ConnectionEntry<Client = unknown, Args = undefined> {\n readonly __betterSchemic: \"connection\";\n readonly driver: string;\n resolve(ctx: ResolveContext, args?: Args): Promise<ConnectionConfigBase[]>;\n /**\n * Lazily open this connection's bound ORM CLIENT for a resolved config — embedded by the driver\n * factory (with a lazy `import()` of its own client module, so authoring a config never pulls the\n * engine). This is what powers the typed `config.connect(name)` on `defineConfig`'s return.\n */\n client?(config: ResolvedConfig): Promise<Client>;\n /**\n * Dialect-specific DISPLAY identity for a resolved config (bulk reporting / errors / logs) —\n * e.g. surreal `ns/db`. Precedence: config `key` > this hook > positional `name[i]`.\n */\n label?(config: ResolvedConfig): string;\n /** PHANTOM (never assigned) — anchors `Client`/`Args` so `config.connect` can infer them per entry. */\n readonly __types?: { client: Client; args: Args };\n}\n\n/** Cross-driver erasure of the entry generics (like `AnyField`) — the shape neutral maps hold. */\n// biome-ignore lint/suspicious/noExplicitAny: cross-driver erasure of the per-entry client/args types.\nexport type AnyConnectionEntry = ConnectionEntry<any, any>;\n\n/** A connection factory's input: a static config, or a resolver yielding one config or a keyed collection. */\nexport type ConnectionInput<C extends ConnectionConfigBase, Args = undefined> =\n | C\n | ((ctx: ResolveContext, args: Args) => MaybePromise<C | C[]>);\n\n/**\n * Build a {@link ConnectionEntry} from a driver tag + a static config or resolver — the primitive each\n * driver package wraps in its typed `<driver>Connection(...)` factory (which fixes `C` to the driver's\n * own connection shape and overloads the array form to require `key`). Returns a branded entry whose\n * `resolve` always yields an array. `extras` carries the factory-embedded client opener (for\n * `config.connect`) and the optional args schema.\n */\nexport function connectionEntry<\n C extends ConnectionConfigBase,\n Client = unknown,\n Args = undefined,\n>(\n driver: string,\n input: ConnectionInput<C, Args>,\n extras?: {\n client?: (config: ResolvedConfig) => Promise<Client>;\n label?: (config: ResolvedConfig) => string;\n },\n): ConnectionEntry<Client, Args> {\n return {\n __betterSchemic: \"connection\",\n driver,\n ...(extras?.client ? { client: extras.client } : {}),\n ...(extras?.label ? { label: extras.label } : {}),\n async resolve(ctx, args) {\n const out =\n typeof input === \"function\" ? await input(ctx, args as Args) : input;\n return Array.isArray(out) ? out : [out];\n },\n };\n}\n\n/** Type guard: is a `connections` map value a real factory output (vs a stray object)? */\nexport function isConnectionEntry(v: unknown): v is ConnectionEntry {\n return (\n typeof v === \"object\" &&\n v !== null &&\n (v as { __betterSchemic?: unknown }).__betterSchemic === \"connection\"\n );\n}\n","// The PORTABLE TYPE MODEL — the keystone of multi-DB support (see docs/MULTI-DB-SPIKE.md).\n//\n// Today the Struct-IR carries a field's type as a SurrealQL type-expression STRING\n// (`StructField.kind`, e.g. `option<int>`, `array<record<user>, 3>`). That string is a dialect leak:\n// equality and rendering both have to understand SurrealQL grammar. This module defines the\n// dialect-INDEPENDENT replacement — a structured type that every driver translates to/from.\n//\n// STATUS (Milestone 1): defined but NOT yet wired into `StructField`. Milestone 2 replaces\n// `kind: string` with `type: PortableType`, makes `inferField` (src/ddl.ts) produce it, and flips\n// diff equality to a structured deep-compare over the normalized IR. Until then this is the target\n// shape, kept in code so the Surreal driver's `emitType`/`parseType` can be built against it.\n\n/**\n * The portable scalar set — the common denominator every driver maps to a concrete column type and\n * back. A driver MAY reject scalars it cannot represent (and authoring can pin a richer DB-native\n * type via `{ t: \"native\" }`). Names are lowercase and dialect-neutral.\n */\nexport type ScalarName =\n | \"any\"\n | \"bool\"\n | \"string\"\n | \"int\"\n | \"float\"\n | \"decimal\"\n | \"number\" // a numeric whose int/float/decimal-ness is unconstrained\n | \"datetime\"\n | \"duration\"\n | \"uuid\"\n | \"bytes\"\n | \"null\"; // the unit type of SQL NULL / Surreal `null` (distinct from `option`'s absence)\n\n/**\n * A dialect-independent field type. Drivers translate this to their own type expression (`emitType`)\n * and parse their introspection back into it (`parseType`). `option` and `nullable` are ORTHOGONAL\n * and BOTH equality-relevant — see the note on `nullable` below; never collapse them.\n */\nexport type PortableType =\n /** A primitive scalar. */\n | { t: \"scalar\"; name: ScalarName }\n /** A literal value type, e.g. the `'active'` in `'active' | 'archived'`. */\n | { t: \"literal\"; value: string | number | boolean }\n /**\n * The field may be ABSENT / NONE (Surreal `option<T>`; SQL \"column omitted / has a DEFAULT\").\n * Orthogonal to `nullable`.\n */\n | { t: \"option\"; inner: PortableType }\n /**\n * The field may be NULL (Surreal `T | null`; SQL `NULL` vs `NOT NULL`). Orthogonal to `option`:\n * `option<T>`, `T | null`, and `option<T | null>` are THREE DISTINCT types. `normalize()` folds\n * `nullable(option(X))` -> `option(nullable(X))` so `.optional().nullable()` ≡ `.nullish()`.\n */\n | { t: \"nullable\"; inner: PortableType }\n /** An ordered, possibly length-bounded list. */\n | { t: \"array\"; elem: PortableType; size?: number }\n /** A set (distinct elements), possibly length-bounded. */\n | { t: \"set\"; elem: PortableType; size?: number }\n /** A discriminated/plain union. `normalize()` keeps `members` canonically sorted. */\n | { t: \"union\"; members: PortableType[] }\n /** A nested object/record literal. `flexible` allows undeclared keys (Surreal FLEXIBLE). */\n | { t: \"object\"; fields: Record<string, PortableType>; flexible?: boolean }\n /**\n * A link to a row in one of `tables` (Surreal `record<a | b>`; SQL foreign key). The id-VALUE type\n * is intentionally NOT modelled here — the DDL never encodes it; it lives App/Wire-side (TS-only).\n */\n | { t: \"record\"; tables: string[] }\n /** A geometry type (Surreal-native; PostGIS or unsupported elsewhere). */\n | { t: \"geometry\"; kind: GeometryKind }\n /** The bottom type (no value). */\n | { t: \"never\" }\n /**\n * An escape hatch for a DB-specific type with no portable meaning (a full-text vector type, etc.). Carries\n * the owning driver `db` so a schema authored for one DB can't silently typecheck against another.\n * `params` carries the type's parameters for parameterized natives — `numeric(p,s)`, `varchar(n)`,\n * `timestamp(p)` — so a driver round-trips `numeric(10,2)` exactly. Order matters; ignored when empty.\n */\n | { t: \"native\"; db: string; name: string; params?: (string | number)[] };\n\nexport type GeometryKind =\n | \"feature\"\n | \"point\"\n | \"line\"\n | \"polygon\"\n | \"multipoint\"\n | \"multiline\"\n | \"multipolygon\"\n | \"collection\";\n\n// --- Constructors (ergonomic, and a single place to enforce the fold invariants) ----------------\n\nexport const scalar = (name: ScalarName): PortableType => ({\n t: \"scalar\",\n name,\n});\nexport const literal = (value: string | number | boolean): PortableType => ({\n t: \"literal\",\n value,\n});\n\n/** `option<T>` — but `option<any>` collapses to `any` (any already admits NONE), matching ddl.ts. */\nexport const option = (inner: PortableType): PortableType =>\n inner.t === \"scalar\" && inner.name === \"any\" ? inner : { t: \"option\", inner };\n\n/**\n * `T | null` — with the fold rule `nullable(option(X))` -> `option(nullable(X))` so\n * `.optional().nullable()` ≡ `.nullish()`, and `nullable(any)` collapses to `any`.\n */\nexport const nullable = (inner: PortableType): PortableType => {\n if (inner.t === \"scalar\" && inner.name === \"any\") return inner;\n if (inner.t === \"option\")\n return { t: \"option\", inner: nullable(inner.inner) };\n return { t: \"nullable\", inner };\n};\n\nexport const array = (elem: PortableType, size?: number): PortableType => ({\n t: \"array\",\n elem,\n ...(size !== undefined ? { size } : {}),\n});\nexport const union = (members: PortableType[]): PortableType =>\n members.length === 1 ? members[0] : { t: \"union\", members };\nexport const record = (tables: string[]): PortableType => ({\n t: \"record\",\n tables,\n});\n"],"mappings":";AAuFO,SAAS,gBAKd,QACA,OACA,QAI+B;AAC/B,SAAO;AAAA,IACL,iBAAiB;AAAA,IACjB;AAAA,IACA,GAAI,QAAQ,SAAS,EAAE,QAAQ,OAAO,OAAO,IAAI,CAAC;AAAA,IAClD,GAAI,QAAQ,QAAQ,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;AAAA,IAC/C,MAAM,QAAQ,KAAK,MAAM;AACvB,YAAM,MACJ,OAAO,UAAU,aAAa,MAAM,MAAM,KAAK,IAAY,IAAI;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