@rebasepro/codegen 0.30.1 → 0.31.0-canary.g59cd6fd

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/dist/index.es.js CHANGED
@@ -1,5 +1,5 @@
1
- import { getDeclaredSubcollections } from "@rebasepro/types";
2
- import { effectiveAccess, fieldKeyForColumn, findRelation, isRelationRequired, resolveCollectionRelations, restrictedFieldNames, sortCollectionsBySlug, toCamelCase, toCollectionAccessor, toPascalCase, toSafeIdentifier } from "@rebasepro/common";
1
+ import { isNumericColumnType, isTemporalColumnType } from "@rebasepro/types";
2
+ import { sortCollectionsBySlug, toCamelCase, toPascalCase, toSafeIdentifier, toTableAccessor } from "@rebasepro/common";
3
3
  //#region src/utils.ts
4
4
  /**
5
5
  * Indent a block of text by a given number of spaces
@@ -16,7 +16,9 @@ function indent(text, spaces) {
16
16
  * Thrown rather than emitted. The generator used to concatenate whatever it was
17
17
  * given, so a slug that collided with another one, or that was not an
18
18
  * identifier, produced a file that either failed to compile or — worse —
19
- * compiled while quietly routing one collection to another's slug.
19
+ * compiled while quietly routing one table to another's slug.
20
+ *
21
+ * @group SDK generation
20
22
  */
21
23
  var CodegenError = class extends Error {
22
24
  constructor(message) {
@@ -29,7 +31,7 @@ var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
29
31
  * A property name for the emitted TypeScript: verbatim when it is a valid
30
32
  * identifier, quoted otherwise.
31
33
  *
32
- * Every key that reaches the output goes through here. Column names are not
34
+ * Every key that reaches the output goes through here. Column keys are not
33
35
  * required to be identifiers — `"order"`, `"user id"`, a quoted Postgres
34
36
  * identifier — and the previous behaviour of camel-casing them into shape
35
37
  * renamed the column in the type while the wire kept the original, so the
@@ -43,247 +45,298 @@ function emitKey(key) {
43
45
  *
44
46
  * `"${value}"` was the previous form. A value containing a quote closed the
45
47
  * literal early, which at best broke the file and at worst let a slug from a
46
- * remote contract inject top-level statements into a file the developer
48
+ * remote schema inject top-level statements into a file the developer
47
49
  * compiles and bundles.
48
50
  */
49
51
  function emitString(value) {
50
52
  return JSON.stringify(value);
51
53
  }
52
- /** The `id`s of an enum declared as an array, an array of `{ id }`, or an object map. */
53
- function enumIds(raw) {
54
- if (Array.isArray(raw)) return raw.map((entry) => entry && typeof entry === "object" ? entry.id : entry);
55
- if (raw && typeof raw === "object") return Object.keys(raw);
56
- return [];
54
+ var GEOPOINT_TYPE = "{ latitude: number; longitude: number; }";
55
+ /** A closed value set as a union of literals: strings escaped, numbers only when every value is one. */
56
+ function literalUnion(values, numeric) {
57
+ if (values.length === 0) return void 0;
58
+ if (numeric) {
59
+ const numbers = values.map(Number);
60
+ if (numbers.some((n) => !Number.isFinite(n))) return void 0;
61
+ return numbers.map((n) => String(n)).join(" | ");
62
+ }
63
+ return values.map((v) => emitString(String(v))).join(" | ");
57
64
  }
58
- function propertyToTypeScriptType(prop) {
59
- switch (prop.type) {
60
- case "string": {
61
- const sp = prop;
62
- if (sp.enum) {
63
- const ids = enumIds(sp.enum);
64
- if (ids.length === 0) return "string";
65
- return ids.map((v) => emitString(String(v))).join(" | ");
66
- }
67
- return "string";
68
- }
69
- case "number": {
70
- const np = prop;
71
- if (np.enum) {
72
- const ids = enumIds(np.enum);
73
- const numbers = ids.map(Number);
74
- if (ids.length === 0 || numbers.some((n) => !Number.isFinite(n))) return "number";
75
- return numbers.map((n) => String(n)).join(" | ");
76
- }
77
- return "number";
78
- }
65
+ /**
66
+ * The TypeScript type of a value of one Postgres type, as the wire serves it.
67
+ *
68
+ * A Postgres enum and a `.oneOf()` set are literal unions; a timestamp, a date
69
+ * and a time are ISO strings; `bytea` is base64; a vector is its numbers; a
70
+ * type Rebase serves but does not create (`other`) is `unknown`.
71
+ */
72
+ function scalarType(type, oneOf) {
73
+ if (type.kind === "enum") return literalUnion(type.values, false) ?? "string";
74
+ if (isNumericColumnType(type)) return (oneOf && literalUnion(oneOf, true)) ?? "number";
75
+ switch (type.kind) {
76
+ case "text":
77
+ case "varchar":
78
+ case "char":
79
+ case "uuid": return (oneOf && literalUnion(oneOf, false)) ?? "string";
79
80
  case "boolean": return "boolean";
80
- case "date": return "string";
81
- case "geopoint": return "{ latitude: number; longitude: number; }";
82
- case "reference": return "string | number";
83
- case "relation": return "string | number";
84
- case "map": {
85
- const mapProp = prop;
86
- if (mapProp.properties) return `{ ${Object.entries(mapProp.properties).map(([k, v]) => {
87
- const child = v;
88
- const optional = !child.validation?.required;
89
- const type = propertyToTypeScriptType(child);
90
- return `${emitKey(k)}${optional ? "?" : ""}: ${optional ? `${type} | null` : type};`;
91
- }).join(" ")} }`;
92
- return "Record<string, unknown>";
93
- }
94
- case "array": {
95
- const arrProp = prop;
96
- if (arrProp.of) return `Array<${propertyToTypeScriptType(arrProp.of)}>`;
97
- return "Array<unknown>";
98
- }
81
+ case "timestamptz":
82
+ case "date":
83
+ case "time": return "string";
99
84
  case "vector": return "number[]";
100
- case "binary": return "string";
85
+ case "bytea": return "string";
86
+ case "json":
87
+ case "jsonb": return "Record<string, unknown>";
101
88
  default: return "unknown";
102
89
  }
103
90
  }
104
91
  /**
105
- * Unwrap a relation target that arrived as a module namespace rather than the
106
- * collection itself — `target: () => import("./authors")` is a common slip.
92
+ * The TypeScript type of a JSON document, from the shape the table declares.
93
+ *
94
+ * An object types its declared fields — a field the shape does not mark
95
+ * `required` may be absent or null — and an open object (`additional`) with no
96
+ * declared field is a record. A typed block list (`json.oneOf`) is the union of
97
+ * its blocks, each a `{ <typeField>: "<variant>"; <valueField>: … }`.
107
98
  */
108
- function resolveTargetCollection(relation) {
109
- try {
110
- let target = relation.target();
111
- if (target && (target.default || target.__esModule)) target = target.default ?? target;
112
- return target;
113
- } catch {
114
- return;
99
+ function jsonType(shape) {
100
+ switch (shape.kind) {
101
+ case "string": return (shape.oneOf && literalUnion(shape.oneOf, false)) ?? "string";
102
+ case "number": return (shape.oneOf && literalUnion(shape.oneOf, true)) ?? "number";
103
+ case "boolean": return "boolean";
104
+ case "date": return "string";
105
+ case "geopoint": return GEOPOINT_TYPE;
106
+ case "object": {
107
+ const entries = Object.entries(shape.fields);
108
+ if (entries.length === 0 && shape.additional) return "Record<string, unknown>";
109
+ return `{ ${entries.map(([key, field]) => {
110
+ const optional = !field.required;
111
+ const type = jsonType(field);
112
+ return `${emitKey(key)}${optional ? "?" : ""}: ${optional ? `${type} | null` : type};`;
113
+ }).join(" ")} }`;
114
+ }
115
+ case "array": return `Array<${jsonType(shape.of)}>`;
116
+ case "oneOf": {
117
+ const variants = Object.entries(shape.variants);
118
+ if (variants.length === 0 || shape.typeField === shape.valueField) return "unknown";
119
+ return variants.map(([name, variant]) => `{ ${emitKey(shape.typeField)}: ${emitString(name)}; ${emitKey(shape.valueField)}: ${jsonType(variant)}; }`).join(" | ");
120
+ }
121
+ default: return "unknown";
115
122
  }
116
123
  }
117
- /** The TypeScript type of a foreign key: whatever the target's primary key is. */
118
- function foreignKeyType(relation) {
119
- const target = resolveTargetCollection(relation);
120
- if (!target?.properties) return "string | number";
121
- const idProp = Object.entries(target.properties).find(([_, p]) => p.isId);
122
- if (!idProp) return "string | number";
123
- return idProp[1].type === "number" ? "number" : "string";
124
+ /** The TypeScript type of a column's value on a read. */
125
+ function columnType(column) {
126
+ if (column.semantic === "geopoint") return GEOPOINT_TYPE;
127
+ if (column.json && (column.type.kind === "json" || column.type.kind === "jsonb")) return jsonType(column.json);
128
+ if (column.type.kind === "array") return `Array<${scalarType(column.type.of, column.element?.oneOf)}>`;
129
+ return scalarType(column.type, column.oneOf);
124
130
  }
125
131
  /**
126
- * The property's `isId`, on the property kinds that declare one.
127
- *
128
- * `Property` is a union and only `StringProperty`, `NumberProperty` and
129
- * `DateProperty` carry `isId`, so it cannot be read off the union directly — which is what
130
- * double-casting `prop` to `Record<string, unknown>` was for, twice. The union
131
- * discriminates on `type`, so narrowing gets there with no claim at all, and
132
- * with the declared type (`boolean | "manual" | "uuid" | string`) intact
133
- * instead of flattened to `unknown`.
132
+ * The TypeScript type of a key: `number` for a numeric column, `string` for
133
+ * every other — what a foreign key, a link written by the relation's name and
134
+ * a to-many membership hold.
134
135
  */
135
- function declaredIsId(prop) {
136
- return prop.type === "string" || prop.type === "number" || prop.type === "date" ? prop.isId : void 0;
137
- }
138
- /** Whether a property is the collection's primary key. */
139
- function isPrimaryKey(prop) {
140
- return Boolean(declaredIsId(prop));
136
+ function keyType(column) {
137
+ if (!column) return "string | number";
138
+ return isNumericColumnType(column.type) ? "number" : "string";
141
139
  }
142
140
  /**
143
- * Whether the server assigns this primary key, so a write does not have to.
144
- * `true` and `"manual"` both mean the caller supplies it.
141
+ * A column's type on a write: its own type (a temporal column also as a
142
+ * `Date`), or `null` too when it is nullable.
143
+ *
144
+ * `Row` has typed a nullable column `T | null` for a while; its write twins
145
+ * did not, so the one way to clear a value — `update(id, { publishedAt: null })`,
146
+ * `{ authorId: null }` to unassign, the edit-form round trip of a row that came
147
+ * back with nulls in it — was a compile error the server would have accepted.
148
+ * A primary key is never null.
145
149
  */
146
- function isAutoAssignedId(prop) {
147
- const isId = declaredIsId(prop);
148
- return Boolean(isId) && isId !== "manual" && isId !== true;
150
+ function writableType(column, tsType) {
151
+ const written = isTemporalColumnType(column.type) ? `${tsType} | Date` : tsType;
152
+ return column.nullable ? `${written} | null` : written;
149
153
  }
150
154
  /**
151
- * The type an *included* relation arrives as: the target's own row, inlined.
152
- *
153
- * This is what the read pipeline actually serves — `toRestRow` puts the
154
- * target's flat columns where the relation was, and the SDK and the HTTP API
155
- * both go through it. It is deliberately *not* a `{ __type: "relation" }`
156
- * envelope: that shape is the admin's view-model and never reaches a
157
- * developer's `find()`.
158
- *
159
- * Falls back to an open record when the target is not part of this generation
160
- * run, since there is no `Row` to point at.
155
+ * Whether a create may leave the column out: it may be null, or the database
156
+ * or the server fills it — a default of any kind (a literal, SQL, a random
157
+ * uuid, an identity, one the database owns), a serial, a stamp.
161
158
  */
162
- function includedRelationType(relation, accessors) {
163
- const slug = resolveTargetCollection(relation)?.slug ?? relation.targetSlug;
164
- const accessor = slug ? accessors.get(slug) : void 0;
165
- const rowType = accessor ? `Database[${emitString(accessor)}]["Row"]` : "Record<string, unknown>";
166
- const pivot = relation.kind === "manyToMany" ? pivotType(relation.through.properties, "read") : void 0;
167
- const elementType = pivot ? `${rowType} & { _pivot?: ${pivot} }` : rowType;
168
- return relation.cardinality === "many" ? `Array<${elementType}>` : elementType;
159
+ function insertOptional(column) {
160
+ if (column.nullable) return true;
161
+ if (column.default !== void 0 || column.stamp !== void 0) return true;
162
+ const kind = column.type.kind;
163
+ return kind === "smallserial" || kind === "serial" || kind === "bigserial";
164
+ }
165
+ /** Nobody may read it: `.private()`, or `access({ read: [] })`. */
166
+ function unreadable(column) {
167
+ return column.private === true || column.access?.read?.length === 0;
168
+ }
169
+ /** Nobody may write it: `.private()`, `.readOnly()`, generated, or `access({ write: [] })`. */
170
+ function unwritable(column) {
171
+ return column.private === true || column.readOnly === true || column.generated !== void 0 || column.access?.write?.length === 0;
172
+ }
173
+ /** One emitted `key: type;` line, already indented. */
174
+ function line(key, type, optional) {
175
+ return ` ${emitKey(key)}${optional ? "?" : ""}: ${type};`;
169
176
  }
170
177
  /**
171
178
  * Map every slug to the property name it is reachable under on `client.data`.
172
179
  *
173
180
  * The accessor is a safe identifier because `client.data.myNotes` is the point
174
- * of generating this at all, and `collectionsDictionary` maps it back to the
181
+ * of generating this at all, and `tablesDictionary` maps it back to the
175
182
  * slug the wire uses. Two slugs that safe down to the same identifier cannot
176
183
  * both have it: the interface would not compile, and the dictionary — an object
177
- * literal — would silently keep only the last, routing one collection's reads
178
- * to the other's table. There is no defensible way to pick, so this refuses.
184
+ * literal — would silently keep only the last, routing one table's reads to
185
+ * the other's. There is no defensible way to pick, so this refuses.
179
186
  */
180
- function buildAccessors(collections) {
187
+ function buildAccessors(tables) {
181
188
  const accessors = /* @__PURE__ */ new Map();
182
189
  const bySafeName = /* @__PURE__ */ new Map();
183
- for (const collection of collections) {
184
- const slug = collection.slug;
185
- if (typeof slug !== "string" || slug.length === 0) throw new CodegenError("A collection has no slug, so it has no name to generate a type for. Every collection needs a unique `slug`.");
190
+ for (const table of tables) {
191
+ const slug = table.slug;
192
+ if (typeof slug !== "string" || slug.length === 0) throw new CodegenError("A table has no slug, so it has no name to generate a type for. Every table needs a unique `slug`.");
186
193
  const safe = toSafeIdentifier(slug);
187
194
  if (safe.length === 0) throw new CodegenError(`The slug ${emitString(slug)} has no characters that can form a property name, so it cannot be reached as \`client.data.<name>\`. Use a slug containing letters, digits, underscores or dashes.`);
188
- const accessor = toCollectionAccessor(slug);
189
- if (accessor !== safe) console.warn(`[codegen] The collection ${emitString(slug)} would be \`client.data.${safe}\`, a name the client reserves, so its typed accessor is \`client.data.${accessor}\`. \`client.data.collection(${emitString(slug)})\` reaches it too.`);
195
+ const accessor = toTableAccessor(slug);
196
+ if (accessor !== safe) console.warn(`[codegen] The table ${emitString(slug)} would be \`client.data.${safe}\`, a name the client reserves, so its typed accessor is \`client.data.${accessor}\`. \`client.data.table(${emitString(slug)})\` reaches it too.`);
190
197
  const existing = bySafeName.get(accessor);
191
- if (existing !== void 0) throw new CodegenError(`The collections ${emitString(existing)} and ${emitString(slug)} both generate the accessor "${accessor}", so only one of them could be reached from the generated client and the other's reads would silently go to the wrong table. Rename one of the slugs.`);
198
+ if (existing !== void 0) throw new CodegenError(`The tables ${emitString(existing)} and ${emitString(slug)} both generate the accessor "${accessor}", so only one of them could be reached from the generated client and the other's reads would silently go to the wrong table. Rename one of the slugs.`);
192
199
  bySafeName.set(accessor, slug);
193
200
  accessors.set(slug, accessor);
194
201
  }
195
202
  return accessors;
196
203
  }
204
+ /** The single key column of a table, or its first, for the type a link to it holds. */
205
+ function keyColumnOf(table) {
206
+ if (!table) return void 0;
207
+ const key = table.primaryKey[0];
208
+ return key === void 0 ? void 0 : table.columns.find((column) => column.key === key);
209
+ }
197
210
  /**
198
- * A column's type on a write: its own type (a date also as a `Date`), or
199
- * `null` too when it is not required.
200
- *
201
- * `Row` has typed a non-required column `T | null` for a while; its write twins
202
- * did not, so the one way to clear a value — `update(id, { publishedAt: null })`,
203
- * `{ authorId: null }` to unassign, the edit-form round trip of a row that came
204
- * back with nulls in it — was a compile error the server would have accepted.
205
- * A primary key is never null, required or not.
211
+ * The type a link to a relation's target holds: whatever the target's key is —
212
+ * or, for a target outside this run, whatever the `belongsTo`'s own foreign-key
213
+ * column holds.
206
214
  */
207
- function writableType(prop, tsType) {
208
- const written = prop.type === "date" ? `${tsType} | Date` : tsType;
209
- return prop.validation?.required || isPrimaryKey(prop) ? written : `${written} | null`;
215
+ function targetKeyType(relation, run, plan) {
216
+ const own = relation.kind === "belongsTo" ? plan.byKey.get(relation.localField) : void 0;
217
+ return keyType(keyColumnOf(run.bySlug.get(relation.target)) ?? own);
210
218
  }
211
- /** One emitted `key: type;` line, already indented. */
212
- function line(key, type, optional) {
213
- return ` ${emitKey(key)}${optional ? "?" : ""}: ${type};`;
219
+ /** Two column types that a foreign key may hold between: identical, a serial read as its integer. */
220
+ function sameKeyType(a, b) {
221
+ const plain = (type) => {
222
+ switch (type.kind) {
223
+ case "smallserial": return { kind: "smallint" };
224
+ case "serial": return { kind: "integer" };
225
+ case "bigserial": return { kind: "bigint" };
226
+ default: return type;
227
+ }
228
+ };
229
+ return JSON.stringify(plain(a)) === JSON.stringify(plain(b));
214
230
  }
215
231
  /**
216
- * The keys nobody can reach take off the API surface — in *both* directions.
217
- *
218
- * `excludeFromApi` means one thing: the API surface does not mention this
219
- * property. `Row` already honoured that; `Insert` and `Update` deliberately did
220
- * not, on the reading that the column is stripped from responses rather than
221
- * from writes. That left the generated types as the one place a password hash
222
- * was still named, and it invited a client to send one. The server refuses
223
- * such a field on a write (`VALIDATION_EXCLUDED_FIELDS`), so nothing generated
224
- * advertises it.
225
- *
226
- * Read through `effectiveAccess`, so the flag and its longhand
227
- * `access: { read: [], write: [] }` produce the same file. A *role* rule is
228
- * deliberately not honoured here and `Row` is unchanged by one: a generated type
229
- * is one shape for every caller, and there is no `Row` that is right for both a
230
- * reader who holds `hr` and one who does not. The server is the enforcement
231
- * point; the types describe the surface a caller may name.
232
- *
233
- * Every spelling the server restricts, read from the server's own function
234
- * (`restrictedFieldNames`): the property name, its column name, and — for a
235
- * closed to-one relation — the foreign key that names the same row. Keying on
236
- * the property and column alone, which this used to, kept `authorId` on all
237
- * three types for an `excludeFromApi` `author`, though the server strips it
238
- * from every read and refuses it on every write.
232
+ * The key a foreign-key column is served under when a relation derives it:
233
+ * `author_id` → `authorId`, each later segment keeping its own casing. The
234
+ * same rule as `toWireKey` in `@rebasepro/utils` (which this package does not
235
+ * depend on); used only to recognise such a column, never to name one.
239
236
  */
240
- function excludedApiKeys(collection) {
241
- const unreadable = closedNames(collection, "read");
242
- const unwritable = closedNames(collection, "write");
243
- return new Set([...unreadable].filter((name) => unwritable.has(name)));
237
+ function derivedFieldKey(localKey) {
238
+ const segments = localKey.split(/[-_ ]+/).filter(Boolean);
239
+ if (segments.length <= 1) return localKey;
240
+ return segments.map((segment, index) => index === 0 ? segment.charAt(0).toLowerCase() + segment.slice(1) : segment.charAt(0).toUpperCase() + segment.slice(1)).join("");
244
241
  }
245
242
  /**
246
- * The names nobody may read (or write), as the server judges them: no viewer
247
- * is the trusted plane, which every role-naming rule admits, so what is left
248
- * is exactly the empty rules.
243
+ * Whether a `belongsTo`'s column is nothing but the link: the column the
244
+ * relation would derive (its key the derived key of `localKey`, the target's
245
+ * key type, no rule, default or flag of its own), over a constraint.
249
246
  *
250
- * `restrictedFieldNames` resolves the relations of a closed relation property
251
- * to find its foreign key. When those cannot be resolved — already warned
252
- * about by the caller — the property and column names are still closed.
247
+ * Such a column is listed with the relations, after the table's own columns —
248
+ * where a derived foreign key always is, so declaring the column a relation
249
+ * would derive does not move it in the generated types.
253
250
  */
254
- function closedNames(collection, kind) {
255
- try {
256
- return restrictedFieldNames(collection, void 0, kind).refused;
257
- } catch {
258
- const names = /* @__PURE__ */ new Set();
259
- for (const [key, rawProp] of Object.entries(collection.properties ?? {})) {
260
- const prop = rawProp;
261
- if (effectiveAccess(prop)?.[kind]?.length !== 0) continue;
262
- names.add(key);
263
- if (prop.columnName) names.add(prop.columnName);
264
- }
265
- return names;
251
+ function isLinkOnly(column, relation, run) {
252
+ if (!relation.constraint) return false;
253
+ if (column.derived) return true;
254
+ if (derivedFieldKey(relation.localKey) !== column.key) return false;
255
+ if (column.primaryKey || column.default !== void 0 || column.generated !== void 0 || column.readOnly || column.private) return false;
256
+ if (column.access !== void 0 || column.stamp !== void 0 || column.validate !== void 0 || column.oneOf !== void 0) return false;
257
+ if (column.description !== void 0 || column.storage !== void 0 || column.semantic !== void 0) return false;
258
+ if (column.vectorIndex !== void 0 || column.json !== void 0 || column.element !== void 0 || column.transforms !== void 0) return false;
259
+ const targetKey = keyColumnOf(run.bySlug.get(relation.target));
260
+ return targetKey === void 0 || sameKeyType(column.type, targetKey.type);
261
+ }
262
+ function planTable(table, run) {
263
+ const byKey = new Map(table.columns.map((column) => [column.key, column]));
264
+ const linkColumns = /* @__PURE__ */ new Set();
265
+ const links = [];
266
+ for (const relation of table.relations) {
267
+ if (relation.kind !== "belongsTo") continue;
268
+ const column = byKey.get(relation.localField);
269
+ const listedWithRelation = column !== void 0 && isLinkOnly(column, relation, run);
270
+ if (listedWithRelation && column) linkColumns.add(column.key);
271
+ links.push({
272
+ relation,
273
+ column: listedWithRelation ? column : void 0
274
+ });
275
+ }
276
+ const excluded = /* @__PURE__ */ new Set();
277
+ const unwritableKeys = /* @__PURE__ */ new Set();
278
+ for (const column of table.columns) {
279
+ const closedWrite = unwritable(column);
280
+ if (closedWrite) unwritableKeys.add(column.key);
281
+ if (closedWrite && unreadable(column)) excluded.add(column.key);
282
+ }
283
+ for (const relation of table.relations) {
284
+ if (relation.kind !== "belongsTo") continue;
285
+ if (excluded.has(relation.localField)) excluded.add(relation.name);
286
+ if (unwritableKeys.has(relation.localField)) unwritableKeys.add(relation.name);
266
287
  }
288
+ for (const key of excluded) unwritableKeys.add(key);
289
+ return {
290
+ table,
291
+ columns: table.columns.filter((column) => !linkColumns.has(column.key)),
292
+ links,
293
+ excluded,
294
+ unwritable: unwritableKeys,
295
+ byKey
296
+ };
267
297
  }
268
298
  /**
269
- * The keys nobody may write: `access: { write: [] }`, readable or not.
299
+ * The type an *included* relation arrives as: the target's own row, inlined.
270
300
  *
271
- * Off `Insert` and `Update` for the same reason `excludedApiKeys` takes a
272
- * hidden property off all three — except that a field everyone can read but
273
- * nobody can write stays on `Row`. The server refuses one on any write with
274
- * `VALIDATION_EXCLUDED_FIELDS`, for every caller, `admin` included, so a
275
- * generated `create({ computed })` compiled and could only ever be a 400.
301
+ * This is what the read pipeline actually serves — the target's flat columns
302
+ * where the relation was, through the SDK and the HTTP API alike. It is
303
+ * deliberately *not* a `{ __type: "relation" }` envelope: that shape is the
304
+ * panel's view-model and never reaches a developer's `find()`.
276
305
  *
277
- * A write rule naming *roles* is not this: some caller can write it, and one
278
- * generated shape cannot say which. A closed to-one relation's foreign key is:
279
- * the server refuses `reviewerId` exactly as it refuses `reviewer`.
306
+ * Falls back to an open record when the target is not part of this generation
307
+ * run, since there is no `Row` to point at.
280
308
  */
281
- function unwritableKeys(collection) {
282
- return closedNames(collection, "write");
309
+ function includedRelationType(relation, run) {
310
+ const accessor = run.accessors.get(relation.target);
311
+ const rowType = accessor ? `Database[${emitString(accessor)}]["Row"]` : "Record<string, unknown>";
312
+ const pivot = relation.kind === "manyToMany" ? pivotType(relation.through.pivot, "read") : void 0;
313
+ const elementType = pivot ? `${rowType} & { _pivot?: ${pivot} }` : rowType;
314
+ return relation.cardinality === "many" ? `Array<${elementType}>` : elementType;
283
315
  }
316
+ /**
317
+ * Generate the typed SDK's `database.types.ts` from table descriptors — what
318
+ * `compileTables` produces, `GET /api/schema/tables` serves and introspection
319
+ * reports.
320
+ *
321
+ * Emits `Database` (per table: `Row`, `Insert`, `Update`, `Relations`, `Slug`),
322
+ * `TableName`, `tablesDictionary`, `TablesDictionary` and the
323
+ * `include` helpers `RelationsOf`, `RelationKeys`, `RelationTarget`,
324
+ * `IncludeOptionsFor`, `IncludeFor` and `RowWith`.
325
+ *
326
+ * Deterministic: tables are emitted in slug order whatever order they arrive
327
+ * in, so `rebase doctor` can regenerate in memory and diff against the file.
328
+ *
329
+ * @throws {CodegenError} when two slugs produce one accessor, or a slug has
330
+ * nothing an accessor can be built from.
331
+ *
332
+ * @group SDK generation
333
+ */
284
334
  function generateTypedefs(input) {
285
- const collections = sortCollectionsBySlug(input);
286
- const accessors = buildAccessors(collections);
335
+ const tables = sortCollectionsBySlug(input);
336
+ const run = {
337
+ accessors: buildAccessors(tables),
338
+ bySlug: new Map(tables.map((table) => [table.slug, table]))
339
+ };
287
340
  const lines = [
288
341
  "/**",
289
342
  " * This file was auto-generated by Rebase.",
@@ -292,147 +345,158 @@ function generateTypedefs(input) {
292
345
  "",
293
346
  "export interface Database {"
294
347
  ];
295
- for (const collection of collections) {
296
- const properties = collection.properties ?? {};
297
- let resolvedRelations = {};
298
- try {
299
- resolvedRelations = resolveCollectionRelations(collection);
300
- } catch (e) {
301
- console.warn(`[rebase] Could not resolve the relations of "${collection.slug}", so its generated type has no relation fields and none of their foreign-key columns. This is usually a circular import in the collection files — make sure the target is \`() => otherCollection\` and not evaluated at module load.\n ${e instanceof Error ? e.message : String(e)}`);
348
+ for (const table of tables) {
349
+ const plan = planTable(table, run);
350
+ lines.push(` ${emitKey(run.accessors.get(table.slug))}: {`);
351
+ emitRow(lines, plan, run);
352
+ if (table.kind === "view") {
353
+ lines.push(" Insert: never;");
354
+ lines.push(" Update: never;");
355
+ } else {
356
+ emitInsert(lines, plan, run);
357
+ emitUpdate(lines, plan, run);
302
358
  }
303
- const declared = getDeclaredSubcollections(collection);
304
- let subcollectionCount = 0;
305
- if (declared) try {
306
- subcollectionCount = declared().length;
307
- } catch {
308
- subcollectionCount = -1;
309
- }
310
- if (subcollectionCount !== 0) console.warn(`[rebase] "${collection.slug}" declares ${subcollectionCount < 0 ? "" : `${subcollectionCount} `}subcollection(s), which are not part of the generated Database: they are reached over a nested path (\`data/${collection.slug}/<id>/<relation>\`), not as a top-level accessor. Register a subcollection as a collection of its own if you want a typed accessor for it.`);
311
- lines.push(` ${emitKey(accessors.get(collection.slug))}: {`);
312
- lines.push(" Row: {");
313
- const emittedKeys = /* @__PURE__ */ new Set();
314
- const excluded = excludedApiKeys(collection);
315
- for (const key of excluded) emittedKeys.add(key);
316
- for (const [key, rawProp] of Object.entries(properties)) {
317
- const prop = rawProp;
318
- if (prop.type === "relation") continue;
319
- if (excluded.has(key)) continue;
320
- const tsType = propertyToTypeScriptType(prop);
321
- const isRequired = Boolean(prop.validation?.required) || isPrimaryKey(prop);
322
- lines.push(line(key, isRequired ? tsType : `${tsType} | null`, !isRequired));
323
- emittedKeys.add(key);
324
- }
325
- for (const [relKey, relation] of Object.entries(resolvedRelations)) if (relation.kind === "belongsTo" && relation.localKey) {
326
- const fkKey = fieldKeyForColumn(collection, relation.localKey);
327
- if (emittedKeys.has(fkKey)) continue;
328
- const fkType = foreignKeyType(relation);
329
- const shadowedByInclude = relKey === fkKey;
330
- const tsType = shadowedByInclude ? `${fkType} | ${includedRelationType(relation, accessors)}` : fkType;
331
- const isRequired = isRelationRequired(collection, relation) && !shadowedByInclude;
332
- lines.push(line(fkKey, isRequired ? tsType : `${tsType} | null`, !isRequired));
333
- emittedKeys.add(fkKey);
334
- }
335
- for (const [key, relation] of Object.entries(resolvedRelations)) {
336
- if (emittedKeys.has(key)) continue;
337
- lines.push(line(key, includedRelationType(relation, accessors), true));
338
- emittedKeys.add(key);
339
- }
340
- for (const [key, rawProp] of Object.entries(properties)) {
341
- if (rawProp.type !== "relation") continue;
342
- if (emittedKeys.has(key)) continue;
343
- lines.push(line(key, "Record<string, unknown>", true));
344
- emittedKeys.add(key);
345
- }
346
- lines.push(" };");
347
- lines.push(" Insert: {");
348
- const notWritable = /* @__PURE__ */ new Set([...excluded, ...unwritableKeys(collection)]);
349
- emittedKeys.clear();
350
- for (const key of notWritable) emittedKeys.add(key);
351
- for (const [key, rawProp] of Object.entries(properties)) {
352
- const prop = rawProp;
353
- if (prop.type === "relation") continue;
354
- if (notWritable.has(key)) continue;
355
- const tsType = propertyToTypeScriptType(prop);
356
- const isOptional = !prop.validation?.required || isAutoAssignedId(prop) || Boolean(prop.databaseDefault);
357
- lines.push(line(key, writableType(prop, tsType), isOptional));
358
- emittedKeys.add(key);
359
- }
360
- const eitherSpelling = emitWritableRelations(lines, collection, properties, resolvedRelations, emittedKeys, false);
361
- lines.push(eitherSpelling.length === 0 ? " };" : ` } & ${eitherSpelling.join(" & ")};`);
362
- lines.push(" Update: {");
363
- emittedKeys.clear();
364
- for (const key of notWritable) emittedKeys.add(key);
365
- for (const [key, rawProp] of Object.entries(properties)) {
366
- const prop = rawProp;
367
- if (prop.type === "relation") continue;
368
- if (isPrimaryKey(prop)) continue;
369
- if (notWritable.has(key)) continue;
370
- lines.push(line(key, writableType(prop, propertyToTypeScriptType(prop)), true));
371
- emittedKeys.add(key);
372
- }
373
- emitWritableRelations(lines, collection, properties, resolvedRelations, emittedKeys, true);
374
- lines.push(" };");
375
- const includable = Object.entries(resolvedRelations).filter(([key]) => !excluded.has(key));
376
- if (includable.length === 0) lines.push(" Relations: Record<never, never>;");
377
- else lines.push(" Relations: {");
378
- for (const [key, relation] of includable) {
379
- const slug = resolveTargetCollection(relation)?.slug ?? relation.targetSlug;
380
- const accessor = slug ? accessors.get(slug) : void 0;
381
- lines.push(` ${emitKey(key)}: ${accessor ? emitString(accessor) : "never"};`);
382
- }
383
- if (includable.length > 0) lines.push(" };");
384
- lines.push(` Slug: ${emitString(collection.slug)};`);
359
+ emitRelations(lines, plan, run);
360
+ lines.push(` Slug: ${emitString(table.slug)};`);
385
361
  lines.push(" };");
386
362
  }
387
363
  lines.push("}");
388
364
  lines.push("");
389
- lines.push("export type CollectionName = keyof Database;");
365
+ lines.push("export type TableName = keyof Database;");
390
366
  lines.push("");
391
- lines.push("export const collectionsDictionary = {");
392
- for (const collection of collections) lines.push(` ${emitKey(accessors.get(collection.slug))}: ${emitString(collection.slug)},`);
367
+ lines.push("export const tablesDictionary = {");
368
+ for (const table of tables) lines.push(` ${emitKey(run.accessors.get(table.slug))}: ${emitString(table.slug)},`);
393
369
  lines.push("} as const;");
394
370
  lines.push("");
395
- lines.push("export type CollectionsDictionary = typeof collectionsDictionary;");
371
+ lines.push("export type TablesDictionary = typeof tablesDictionary;");
396
372
  lines.push("");
397
373
  lines.push(...includeHelperLines());
398
374
  return lines.join("\n");
399
375
  }
400
376
  /**
377
+ * `Row` — what a read serves.
378
+ *
379
+ * ## A `belongsTo` has three shapes, and all three are typed
380
+ *
381
+ * 1. **Write** — `Insert`/`Update` accept *either* the foreign key under its
382
+ * own wire name (`{ authorId: 5 }`) or the relation's name
383
+ * (`{ author: 5 }`). Emitted by `emitWritableRelations`.
384
+ * 2. **Read** — a row carries `authorId`. Always: it is a column.
385
+ * 3. **Read with `include`** — the target's own row arrives under `author`.
386
+ * Optional, because it is absent from every read that did not name it; the
387
+ * generated `RowWith` makes it required for a read that did.
388
+ *
389
+ * `fields` narrows which columns a read returns, but a column is optional here
390
+ * only because the value may be null, never because the caller might not have
391
+ * asked for it: a projection is a choice made at one call site.
392
+ */
393
+ function emitRow(lines, plan, run) {
394
+ lines.push(" Row: {");
395
+ const emitted = new Set(plan.excluded);
396
+ for (const column of plan.columns) {
397
+ if (emitted.has(column.key)) continue;
398
+ const type = columnType(column);
399
+ lines.push(line(column.key, column.nullable ? `${type} | null` : type, column.nullable));
400
+ emitted.add(column.key);
401
+ }
402
+ for (const { relation, column } of plan.links) {
403
+ if (!column || emitted.has(column.key)) continue;
404
+ const type = targetKeyType(relation, run, plan);
405
+ lines.push(line(column.key, column.nullable ? `${type} | null` : type, column.nullable));
406
+ emitted.add(column.key);
407
+ }
408
+ for (const relation of plan.table.relations) {
409
+ if (emitted.has(relation.name)) continue;
410
+ lines.push(line(relation.name, includedRelationType(relation, run), true));
411
+ emitted.add(relation.name);
412
+ }
413
+ lines.push(" };");
414
+ }
415
+ /**
416
+ * `Insert` — what `create()` accepts: no hidden column and nothing nobody may
417
+ * write; a column the database or the server fills may be left out.
418
+ */
419
+ function emitInsert(lines, plan, run) {
420
+ lines.push(" Insert: {");
421
+ const emitted = new Set(plan.unwritable);
422
+ for (const column of plan.columns) {
423
+ if (emitted.has(column.key)) continue;
424
+ lines.push(line(column.key, writableType(column, columnType(column)), insertOptional(column)));
425
+ emitted.add(column.key);
426
+ }
427
+ const eitherSpelling = emitWritableRelations(lines, plan, run, emitted, false);
428
+ lines.push(eitherSpelling.length === 0 ? " };" : ` } & ${eitherSpelling.join(" & ")};`);
429
+ }
430
+ /**
431
+ * `Update` — everything optional, and the primary key left out: an update
432
+ * addresses a row by its key, it does not reassign one.
433
+ */
434
+ function emitUpdate(lines, plan, run) {
435
+ lines.push(" Update: {");
436
+ const emitted = new Set(plan.unwritable);
437
+ for (const column of plan.columns) {
438
+ if (column.primaryKey || emitted.has(column.key)) continue;
439
+ lines.push(line(column.key, writableType(column, columnType(column)), true));
440
+ emitted.add(column.key);
441
+ }
442
+ emitWritableRelations(lines, plan, run, emitted, true);
443
+ lines.push(" };");
444
+ }
445
+ /**
446
+ * `Relations` — which relations the table has, and which table each one
447
+ * reaches. Not a shape a read returns: it is the *graph*, and `include` is the
448
+ * one parameter that needs it. `IncludeFor` walks it to constrain an include's
449
+ * keys at every level, and `RowWith` reads it to make an included relation
450
+ * non-optional on the row that comes back.
451
+ *
452
+ * Emitted as the accessor NAME rather than the target's `Row`, so a
453
+ * self-referencing relation is a finite string instead of a type that expands
454
+ * forever. A table with no relations gets `Record<never, never>`, not `{}`,
455
+ * which typescript-eslint's `no-empty-object-type` refuses in every project
456
+ * that lints its generated SDK. A hidden relation is left out: the server
457
+ * answers an include naming one as it answers a typo.
458
+ */
459
+ function emitRelations(lines, plan, run) {
460
+ const includable = plan.table.relations.filter((relation) => !plan.excluded.has(relation.name));
461
+ if (includable.length === 0) {
462
+ lines.push(" Relations: Record<never, never>;");
463
+ return;
464
+ }
465
+ lines.push(" Relations: {");
466
+ for (const relation of includable) {
467
+ const accessor = run.accessors.get(relation.target);
468
+ lines.push(` ${emitKey(relation.name)}: ${accessor ? emitString(accessor) : "never"};`);
469
+ }
470
+ lines.push(" };");
471
+ }
472
+ /**
401
473
  * The `include` type machinery, emitted into the generated file.
402
474
  *
403
475
  * It lives here rather than in `@rebasepro/types` because it is the *graph*
404
- * that makes it work, and the graph only exists once a project's collections
405
- * have been generated. `IncludeSpec` in `@rebasepro/types` is deliberately
406
- * unconstrained — a hand-written row type has no relations in it to check
407
- * against — and these narrow it for a project that does have them.
408
- *
409
- * Two things a caller gets:
476
+ * that makes it work, and the graph only exists once a project's tables have
477
+ * been generated. `IncludeSpec` in `@rebasepro/types` is deliberately
478
+ * unconstrained; these narrow it for a project that has relations.
410
479
  *
411
480
  * - `IncludeFor<"posts">` — an include whose keys are relations that exist,
412
- * recursively, so `include: { comments: { include: { authr: true } } }` is a
413
- * compile error rather than a 400 at runtime.
481
+ * recursively, so a typo is a compile error rather than a 400 at runtime.
414
482
  * - `RowWith<"posts", I>` — the row a read with that include returns, where
415
- * every included relation is **present** rather than optional. `Row` types a
416
- * relation as optional because it is absent from every read that did not ask
417
- * for it; once a read has asked, `row.author.name` should not need a `?.`.
483
+ * every included relation is **present** rather than optional.
418
484
  *
419
485
  * The depth bound matches the server's (`MAX_INCLUDE_DEPTH`), and is spelled as
420
486
  * a decrementing tuple because TypeScript has no arithmetic — `Prev[3]` is `2`.
421
- * Without a bound, a self-referencing relation makes the type infinite and the
422
- * compiler gives up with "type instantiation is excessively deep".
423
487
  */
424
488
  function includeHelperLines() {
425
489
  return [
426
- "/** Which collection each of `A`'s relations reaches. */",
427
- "export type RelationsOf<A extends CollectionName> =",
490
+ "/** Which table each of `A`'s relations reaches. */",
491
+ "export type RelationsOf<A extends TableName> =",
428
492
  " Database[A] extends { Relations: infer R } ? R : Record<string, never>;",
429
493
  "",
430
494
  "/** The names of `A`'s relations. */",
431
- "export type RelationKeys<A extends CollectionName> = keyof RelationsOf<A> & string;",
495
+ "export type RelationKeys<A extends TableName> = keyof RelationsOf<A> & string;",
432
496
  "",
433
- "/** The collection a relation reaches, or `never` when it left this project. */",
434
- "export type RelationTarget<A extends CollectionName, K extends RelationKeys<A>> =",
435
- " RelationsOf<A>[K] extends CollectionName ? RelationsOf<A>[K] : never;",
497
+ "/** The table a relation reaches, or `never` when it left this project. */",
498
+ "export type RelationTarget<A extends TableName, K extends RelationKeys<A>> =",
499
+ " RelationsOf<A>[K] extends TableName ? RelationsOf<A>[K] : never;",
436
500
  "",
437
501
  "/** Counts `IncludeFor` down; TypeScript has no arithmetic. */",
438
502
  "type Prev = [never, 0, 1, 2, 3];",
@@ -440,32 +504,32 @@ function includeHelperLines() {
440
504
  "/**",
441
505
  " * Per-relation options, minus `include` — which `IncludeFor` supplies at",
442
506
  " * the next depth so the nested keys are checked against the *target's*",
443
- " * relations rather than this collection's.",
507
+ " * relations rather than this table's.",
444
508
  " */",
445
- "export interface IncludeOptionsFor<A extends CollectionName, K extends RelationKeys<A>, D extends number> {",
509
+ "export interface IncludeOptionsFor<A extends TableName, K extends RelationKeys<A>, D extends number> {",
446
510
  " limit?: number;",
447
511
  " where?: Record<string, unknown>;",
448
512
  " logical?: unknown;",
449
513
  " orderBy?: unknown;",
450
514
  " fields?: string[];",
451
- " include?: RelationTarget<A, K> extends CollectionName",
515
+ " include?: RelationTarget<A, K> extends TableName",
452
516
  " ? IncludeFor<RelationTarget<A, K>, Prev[D]>",
453
517
  " : never;",
454
518
  "}",
455
519
  "",
456
520
  "/**",
457
- " * An `include` for collection `A`: its relation names, dotted paths, or the",
521
+ " * An `include` for table `A`: its relation names, dotted paths, or the",
458
522
  " * parametrised tree — with every key checked against the relations that",
459
523
  " * actually exist, at every level.",
460
524
  " */",
461
- "export type IncludeFor<A extends CollectionName, D extends number = 3> =",
525
+ "export type IncludeFor<A extends TableName, D extends number = 3> =",
462
526
  " D extends 0",
463
527
  " ? never",
464
528
  " : | readonly (RelationKeys<A> | \"*\")[]",
465
529
  " | { [K in RelationKeys<A>]?: true | IncludeOptionsFor<A, K, D> };",
466
530
  "",
467
531
  "/** The relation names an include asks for at the top level. */",
468
- "type IncludedKeys<A extends CollectionName, I> =",
532
+ "type IncludedKeys<A extends TableName, I> =",
469
533
  " I extends readonly (infer K)[]",
470
534
  " ? Extract<K, RelationKeys<A>>",
471
535
  " : Extract<keyof I, RelationKeys<A>>;",
@@ -479,36 +543,31 @@ function includeHelperLines() {
479
543
  " * to write `row.author?.name` after asking for the author is the type",
480
544
  " * describing a possibility the query already ruled out.",
481
545
  " */",
482
- "export type RowWith<A extends CollectionName, I> =",
546
+ "export type RowWith<A extends TableName, I> =",
483
547
  " Database[A][\"Row\"] & Required<Pick<Database[A][\"Row\"], IncludedKeys<A, I> & keyof Database[A][\"Row\"]>>;",
484
548
  ""
485
549
  ];
486
550
  }
487
551
  /**
488
- * The two ways a write can name a `belongsTo` target, both of which the server
489
- * accepts: the foreign key under its own wire name (`{ authorId: 5 }`, which
490
- * passes through to the `author_id` column untouched) and the relation
491
- * *property* (`{ author: 5 }`, which the write transformer maps onto that
492
- * column).
493
- *
494
- * Only the first was generated, so the documented and idiomatic write shape was
495
- * a type error.
552
+ * Every relation write the server performs, typed.
496
553
  *
497
- * The second form is emitted under the **property key**, not the resolved
498
- * relation name, because that is what the transformer keys off: it looks the
499
- * payload key up in `properties` and only treats it as a relation if what it
500
- * finds there is one. A relation whose `relationName` differs from its property
501
- * key is reachable as the property and not as the name, so emitting the name
502
- * would have offered a key that writes to a column that does not exist.
554
+ * - A `belongsTo` is written under either of two names: its foreign key's wire
555
+ * key (`{ authorId: 5 }`) and the relation's name (`{ author: 5 }`), which
556
+ * the server maps onto the column — the second only over a constraint
557
+ * (`rel.belongsTo(…, { constraint: false })` keeps a bare column, written by
558
+ * its key alone). A **required** `belongsTo` is satisfied by either: on an
559
+ * `Insert` both names go in optional, and the requirement comes back as one
560
+ * returned `({ authorId: T } | { author: T })` for the caller to intersect
561
+ * with the object. Both stay in the object so `keyof Insert` names them.
562
+ * - A `hasOne`, and a single-hop to-one `via`, is written by naming the target
563
+ * row; `null` unlinks it.
564
+ * - A to-many membership (`hasMany`, `manyToMany`, a single-hop to-many `via`)
565
+ * is written as the targets' keys, or `{ id }`, or `{ id, _pivot }` where the
566
+ * junction declares payload columns. A multi-hop `via` is read-only.
503
567
  *
504
- * A **required** `belongsTo` is satisfied by either spelling — the server's
505
- * required check reads both (`write-validation.ts`). Emitting each name as a
506
- * required key made a create name the same row twice to compile. So on an
507
- * `Insert` both names go in optional, and the requirement comes back as one
508
- * returned `({ authorId: T } | { author: T })` for the caller to intersect
509
- * with the object. Both stay in the object so `keyof Insert` still names them.
568
+ * The target's key type is the one `Row` uses for the link.
510
569
  */
511
- function emitWritableRelations(lines, collection, properties, resolvedRelations, emittedKeys, allOptional) {
570
+ function emitWritableRelations(lines, plan, run, emittedKeys, allOptional) {
512
571
  const spellings = /* @__PURE__ */ new Map();
513
572
  const addSpelling = (relation, key) => {
514
573
  if (emittedKeys.has(key)) return;
@@ -516,71 +575,67 @@ function emitWritableRelations(lines, collection, properties, resolvedRelations,
516
575
  if (!keys.includes(key)) keys.push(key);
517
576
  spellings.set(relation, keys);
518
577
  };
519
- for (const relation of Object.values(resolvedRelations)) if (relation.kind === "belongsTo" && relation.localKey) addSpelling(relation, fieldKeyForColumn(collection, relation.localKey));
520
- for (const [key, rawProp] of Object.entries(properties)) {
521
- if (rawProp.type !== "relation") continue;
522
- const relation = findRelation(resolvedRelations, key);
523
- if (relation?.kind === "belongsTo" && relation.localKey) addSpelling(relation, key);
524
- }
578
+ for (const { relation } of plan.links) addSpelling(relation, relation.localField);
579
+ for (const { relation } of plan.links) if (relation.constraint) addSpelling(relation, relation.name);
525
580
  const eitherSpelling = [];
526
581
  const emit = (key, relation) => {
527
582
  if (emittedKeys.has(key)) return;
528
- const required = isRelationRequired(collection, relation);
529
- const type = required ? foreignKeyType(relation) : `${foreignKeyType(relation)} | null`;
583
+ const required = plan.byKey.get(relation.localField)?.nullable === false;
584
+ const type = required ? targetKeyType(relation, run, plan) : `${targetKeyType(relation, run, plan)} | null`;
530
585
  const names = spellings.get(relation) ?? [key];
531
586
  const oneOfSeveral = required && !allOptional && names.length > 1;
532
587
  lines.push(line(key, type, allOptional || !required || oneOfSeveral));
533
588
  emittedKeys.add(key);
534
589
  if (oneOfSeveral && names[0] === key) eitherSpelling.push(`(${names.map((name) => `{ ${emitKey(name)}: ${type} }`).join(" | ")})`);
535
590
  };
536
- for (const relation of Object.values(resolvedRelations)) if (relation.kind === "belongsTo" && relation.localKey) emit(fieldKeyForColumn(collection, relation.localKey), relation);
537
- for (const [key, rawProp] of Object.entries(properties)) {
538
- if (rawProp.type !== "relation") continue;
539
- const relation = findRelation(resolvedRelations, key);
540
- if (relation?.kind === "belongsTo" && relation.localKey) emit(key, relation);
591
+ for (const { relation } of plan.links) emit(relation.localField, relation);
592
+ for (const { relation } of plan.links) if (relation.constraint) emit(relation.name, relation);
593
+ for (const relation of plan.table.relations) {
594
+ if (emittedKeys.has(relation.name)) continue;
595
+ if (!(relation.kind === "hasOne" || relation.kind === "via" && relation.cardinality === "one" && relation.writable)) continue;
596
+ lines.push(line(relation.name, `${targetKeyType(relation, run, plan)} | null`, true));
597
+ emittedKeys.add(relation.name);
541
598
  }
542
- for (const [key, rawProp] of Object.entries(properties)) {
543
- if (rawProp.type !== "relation" || emittedKeys.has(key)) continue;
544
- const relation = findRelation(resolvedRelations, key);
545
- const toOneWritable = relation?.kind === "hasOne" || relation?.kind === "via" && relation.cardinality === "one" && relation.writable;
546
- if (!relation || !toOneWritable) continue;
547
- lines.push(line(key, `${foreignKeyType(relation)} | null`, true));
548
- emittedKeys.add(key);
549
- }
550
- for (const [key, relation] of Object.entries(resolvedRelations)) {
551
- if (relation.cardinality !== "many" || !relation.writable) continue;
552
- if (emittedKeys.has(key)) continue;
553
- const fk = foreignKeyType(relation);
554
- const pivot = relation.kind === "manyToMany" ? pivotType(relation.through.properties, "write") : void 0;
599
+ for (const relation of plan.table.relations) {
600
+ if (relation.cardinality !== "many" || emittedKeys.has(relation.name)) continue;
601
+ if (relation.kind === "via" && !relation.writable) continue;
602
+ const fk = targetKeyType(relation, run, plan);
603
+ const pivot = relation.kind === "manyToMany" ? pivotType(relation.through.pivot, "write") : void 0;
555
604
  const element = `${fk} | { id: ${fk}${pivot ? `; _pivot?: ${pivot}` : ""} }`;
556
- lines.push(line(key, `Array<${element}>`, true));
557
- emittedKeys.add(key);
605
+ lines.push(line(relation.name, `Array<${element}>`, true));
606
+ emittedKeys.add(relation.name);
558
607
  }
559
608
  return eitherSpelling;
560
609
  }
561
610
  /**
562
611
  * The `_pivot` a many-to-many link carries: the junction's payload columns,
563
- * typed as a row's columns are on a read and as a write's on a write. `undefined`
564
- * when the junction declares none, so there is no `_pivot` to name.
612
+ * typed as a row's columns are on a read and as a write's on a write.
613
+ * `undefined` when the junction declares none, so there is no `_pivot` to name.
565
614
  */
566
- function pivotType(pivotProperties, direction) {
567
- const entries = Object.entries(pivotProperties);
568
- if (entries.length === 0) return void 0;
569
- return `{ ${entries.map(([key, rawProp]) => {
570
- const prop = rawProp;
571
- const tsType = propertyToTypeScriptType(prop);
572
- const required = Boolean(prop.validation?.required);
573
- const type = direction === "write" ? writableType(prop, tsType) : required ? tsType : `${tsType} | null`;
574
- return `${emitKey(key)}${required && direction === "read" ? "" : "?"}: ${type};`;
615
+ function pivotType(pivot, direction) {
616
+ if (pivot.length === 0) return void 0;
617
+ return `{ ${pivot.map((column) => {
618
+ const tsType = columnType(column);
619
+ const required = !column.nullable;
620
+ const type = direction === "write" ? writableType(column, tsType) : required ? tsType : `${tsType} | null`;
621
+ return `${emitKey(column.key)}${required && direction === "read" ? "" : "?"}: ${type};`;
575
622
  }).join(" ")} }`;
576
623
  }
577
624
  //#endregion
578
625
  //#region src/index.ts
579
- function generateSDK(collections, options = {}) {
626
+ /**
627
+ * The typed SDK for a set of tables: `database.types.ts` (see
628
+ * {@link generateTypedefs}) and, unless switched off, a README.
629
+ *
630
+ * @param tables The table descriptors, in any order.
631
+ *
632
+ * @group SDK generation
633
+ */
634
+ function generateSDK(tables, options = {}) {
580
635
  const files = [];
581
636
  files.push({
582
637
  path: "database.types.ts",
583
- content: generateTypedefs(collections)
638
+ content: generateTypedefs(tables)
584
639
  });
585
640
  if (options.includeReadme !== false) files.push({
586
641
  path: "README.md",
@@ -598,13 +653,13 @@ function generateSDK(collections, options = {}) {
598
653
  2. Initialize with your generated types:
599
654
  \`\`\`typescript
600
655
  import { createRebaseClient } from '@rebasepro/client';
601
- import { collectionsDictionary, type Database } from './database.types';
656
+ import { tablesDictionary, type Database } from './database.types';
602
657
 
603
658
  const rebase = createRebaseClient<Database>({
604
659
  baseUrl: '${options.baseUrl ?? "http://localhost:3001"}',
605
660
  // Maps each accessor back to the slug the wire uses. Without it a
606
661
  // hyphenated slug is not resolvable from the property name alone.
607
- collections: collectionsDictionary,
662
+ tables: tablesDictionary,
608
663
  });
609
664
 
610
665
  // Property access is the typed surface: rows, filters and sorts are all
@@ -618,16 +673,16 @@ function generateSDK(collections, options = {}) {
618
673
  The generated \`Row\` uses each field's **wire** name — the key it arrives under in
619
674
  JSON — and nothing here renames anything.
620
675
 
621
- - **A declared property is its key in the collection.** A property keyed
622
- \`createdAt\` is \`row.createdAt\`, whatever \`columnName\` says. A column name is
623
- the name of a different thing: where the value lives, not what the API calls it.
676
+ - **A column is its key in \`columns\`.** A column keyed \`createdAt\` is
677
+ \`row.createdAt\`, whatever \`.column()\` says. A column name is the name of a
678
+ different thing: where the value lives, not what the API calls it.
624
679
  - **A foreign key derived from a relation is camelCase**, because that is what
625
680
  the wire carries. A \`belongsTo\` named \`author\` gives you \`row.authorId\`, not
626
681
  the column spelling.
627
- - **A collection accessor is camelCase too** (\`my-notes\` → \`rebase.data.myNotes\`),
628
- which is what \`collectionsDictionary\` maps back to the slug.
629
- A slug whose accessor the client reserves (\`collection\`, \`then\`, \`toJSON\`)
630
- is generated as \`<name>Collection\`: \`rebase.data.collectionCollection\`.
682
+ - **A table accessor is camelCase too** (\`my-notes\` → \`rebase.data.myNotes\`),
683
+ which is what \`tablesDictionary\` maps back to the slug.
684
+ A slug whose accessor the client reserves (\`table\`, \`then\`, \`toJSON\`)
685
+ is generated as \`<name>Table\`: \`rebase.data.tableTable\`.
631
686
 
632
687
  \`where\` and \`orderBy\` are keyed off the same type, so what compiles is what the
633
688
  backend answers to.
@@ -637,22 +692,22 @@ backend answers to.
637
692
  | Type | What it describes |
638
693
  |---|---|
639
694
  | \`Row\` | What a read serves. Nullable columns are \`T \\| null\`; relations appear only when \`include\` names them. |
640
- | \`Insert\` | What \`create()\` accepts. Server-assigned ids are optional; a \`belongsTo\` target may be named either way (\`{ author: 5 }\` or \`{ authorId: 5 }\`). |
695
+ | \`Insert\` | What \`create()\` accepts. A column with a default, an identity or a stamp is optional; a \`belongsTo\` target may be named either way (\`{ author: 5 }\` or \`{ authorId: 5 }\`). A view takes no writes: \`never\`. |
641
696
  | \`Update\` | What \`update()\` accepts. Everything optional, and the primary key is not settable. |
642
697
 
643
- A property marked \`excludeFromApi\` is absent from all three: the API surface
644
- does not mention it, in either direction. The server holds the same line — a
698
+ A column marked \`.private()\` is absent from all three: the API surface does
699
+ not mention it, in either direction. The server holds the same line — a
645
700
  read never serves the column and a write naming it is refused — so this is a
646
701
  guarantee rather than a description, and nothing generated names a password
647
702
  hash.
648
703
 
649
- If you need an untyped escape hatch, \`rebase.data.collection(slug)\` still works —
704
+ If you need an untyped escape hatch, \`rebase.data.table(slug)\` still works —
650
705
  but it is generic over \`Record<string, unknown>\` and gives up everything above.
651
706
  `
652
707
  });
653
708
  return files;
654
709
  }
655
710
  //#endregion
656
- export { CodegenError, generateSDK, generateTypedefs, indent, toCamelCase, toCollectionAccessor, toPascalCase, toSafeIdentifier };
711
+ export { CodegenError, generateSDK, generateTypedefs, indent, toCamelCase, toPascalCase, toSafeIdentifier, toTableAccessor };
657
712
 
658
713
  //# sourceMappingURL=index.es.js.map