@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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","names":[],"sources":["../src/utils.ts","../src/generate-types.ts","../src/index.ts"],"sourcesContent":["/**\n * Utility functions for the SDK generator\n */\n\n/**\n * The naming rules shared with the server's data proxies, which resolve a\n * generated accessor back to its slug: one home, so the two cannot drift.\n */\nexport { toPascalCase, toCamelCase, toSafeIdentifier, toCollectionAccessor } from \"@rebasepro/common\";\n\n/**\n * Indent a block of text by a given number of spaces\n */\nexport function indent(text: string, spaces: number): string {\n const pad = \" \".repeat(spaces);\n return text\n .split(\"\\n\")\n .map(line => (line.trim() ? pad + line : line))\n .join(\"\\n\");\n}\n","import { getDeclaredSubcollections, CollectionConfig, Property, Properties, MapProperty, ArrayProperty, StringProperty, NumberProperty, DateProperty, ResolvedRelation } from \"@rebasepro/types\";\nimport { effectiveAccess, fieldKeyForColumn, findRelation, isRelationRequired, resolveCollectionRelations, restrictedFieldNames, sortCollectionsBySlug } from \"@rebasepro/common\";\nimport { toCollectionAccessor, toSafeIdentifier } from \"./utils\";\n\n/**\n * A schema that cannot be expressed as a valid TypeScript file.\n *\n * Thrown rather than emitted. The generator used to concatenate whatever it was\n * given, so a slug that collided with another one, or that was not an\n * identifier, produced a file that either failed to compile or — worse —\n * compiled while quietly routing one collection to another's slug.\n */\nexport class CodegenError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CodegenError\";\n }\n}\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * A property name for the emitted TypeScript: verbatim when it is a valid\n * identifier, quoted otherwise.\n *\n * Every key that reaches the output goes through here. Column names are not\n * required to be identifiers — `\"order\"`, `\"user id\"`, a quoted Postgres\n * identifier — and the previous behaviour of camel-casing them into shape\n * renamed the column in the type while the wire kept the original, so the\n * generated `Row` described fields that did not exist.\n */\nfunction emitKey(key: string): string {\n return IDENTIFIER.test(key) ? key : JSON.stringify(key);\n}\n\n/**\n * A string literal, escaped.\n *\n * `\"${value}\"` was the previous form. A value containing a quote closed the\n * literal early, which at best broke the file and at worst let a slug from a\n * remote contract inject top-level statements into a file the developer\n * compiles and bundles.\n */\nfunction emitString(value: string): string {\n return JSON.stringify(value);\n}\n\n/** The `id`s of an enum declared as an array, an array of `{ id }`, or an object map. */\nfunction enumIds(raw: unknown): (string | number)[] {\n if (Array.isArray(raw)) {\n return raw.map((entry: string | number | { id: string | number }) =>\n entry && typeof entry === \"object\" ? entry.id : entry);\n }\n if (raw && typeof raw === \"object\") return Object.keys(raw);\n return [];\n}\n\nfunction propertyToTypeScriptType(prop: Property): string {\n switch (prop.type) {\n case \"string\": {\n const sp = prop as StringProperty;\n if (sp.enum) {\n const ids = enumIds(sp.enum);\n if (ids.length === 0) return \"string\";\n return ids.map(v => emitString(String(v))).join(\" | \");\n }\n return \"string\";\n }\n case \"number\": {\n const np = prop as NumberProperty;\n if (np.enum) {\n const ids = enumIds(np.enum);\n const numbers = ids.map(Number);\n // A numeric enum carrying something that is not a number cannot\n // be written as a union of numeric literals. Widening to\n // `number` is imprecise; emitting `NaN | undefined` is invalid.\n if (ids.length === 0 || numbers.some(n => !Number.isFinite(n))) return \"number\";\n return numbers.map(n => String(n)).join(\" | \");\n }\n return \"number\";\n }\n case \"boolean\":\n return \"boolean\";\n case \"date\":\n return \"string\"; // ISO 8601 string over the wire\n case \"geopoint\":\n return \"{ latitude: number; longitude: number; }\";\n case \"reference\":\n return \"string | number\";\n case \"relation\":\n return \"string | number\";\n case \"map\": {\n const mapProp = prop as MapProperty;\n if (mapProp.properties) {\n const inner = Object.entries(mapProp.properties)\n .map(([k, v]) => {\n const child = v as Property;\n // Nested fields carry validation like any other. Emitting\n // them all required claimed a shape the payload does not\n // have to satisfy.\n const optional = !child.validation?.required;\n const type = propertyToTypeScriptType(child);\n return `${emitKey(k)}${optional ? \"?\" : \"\"}: ${optional ? `${type} | null` : type};`;\n })\n .join(\" \");\n return `{ ${inner} }`;\n }\n return \"Record<string, unknown>\";\n }\n case \"array\": {\n const arrProp = prop as ArrayProperty;\n if (arrProp.of) {\n return `Array<${propertyToTypeScriptType(arrProp.of as Property)}>`;\n }\n return \"Array<unknown>\";\n }\n case \"vector\":\n return \"number[]\";\n case \"binary\":\n return \"string\";\n default:\n return \"unknown\";\n }\n}\n\n/**\n * Unwrap a relation target that arrived as a module namespace rather than the\n * collection itself — `target: () => import(\"./authors\")` is a common slip.\n */\nfunction resolveTargetCollection(relation: ResolvedRelation): CollectionConfig | undefined {\n try {\n let target = relation.target() as CollectionConfig & { default?: CollectionConfig; __esModule?: boolean };\n if (target && (target.default || target.__esModule)) {\n target = (target.default ?? target) as typeof target;\n }\n return target;\n } catch {\n return undefined;\n }\n}\n\n/** The TypeScript type of a foreign key: whatever the target's primary key is. */\nfunction foreignKeyType(relation: ResolvedRelation): string {\n const target = resolveTargetCollection(relation);\n if (!target?.properties) return \"string | number\";\n const idProp = Object.entries(target.properties).find(([_, p]) => (p as Record<string, unknown>).isId);\n if (!idProp) return \"string | number\";\n return (idProp[1] as Property).type === \"number\" ? \"number\" : \"string\";\n}\n\n/**\n * The property's `isId`, on the property kinds that declare one.\n *\n * `Property` is a union and only `StringProperty`, `NumberProperty` and\n * `DateProperty` carry `isId`, so it cannot be read off the union directly — which is what\n * double-casting `prop` to `Record<string, unknown>` was for, twice. The union\n * discriminates on `type`, so narrowing gets there with no claim at all, and\n * with the declared type (`boolean | \"manual\" | \"uuid\" | string`) intact\n * instead of flattened to `unknown`.\n */\nfunction declaredIsId(prop: Property): StringProperty[\"isId\"] | NumberProperty[\"isId\"] | DateProperty[\"isId\"] {\n return prop.type === \"string\" || prop.type === \"number\" || prop.type === \"date\" ? prop.isId : undefined;\n}\n\n/** Whether a property is the collection's primary key. */\nfunction isPrimaryKey(prop: Property): boolean {\n return Boolean(declaredIsId(prop));\n}\n\n/**\n * Whether the server assigns this primary key, so a write does not have to.\n * `true` and `\"manual\"` both mean the caller supplies it.\n */\nfunction isAutoAssignedId(prop: Property): boolean {\n const isId = declaredIsId(prop);\n return Boolean(isId) && isId !== \"manual\" && isId !== true;\n}\n\n/**\n * The type an *included* relation arrives as: the target's own row, inlined.\n *\n * This is what the read pipeline actually serves — `toRestRow` puts the\n * target's flat columns where the relation was, and the SDK and the HTTP API\n * both go through it. It is deliberately *not* a `{ __type: \"relation\" }`\n * envelope: that shape is the admin's view-model and never reaches a\n * developer's `find()`.\n *\n * Falls back to an open record when the target is not part of this generation\n * run, since there is no `Row` to point at.\n */\nfunction includedRelationType(\n relation: ResolvedRelation,\n accessors: Map<string, string>\n): string {\n const target = resolveTargetCollection(relation);\n const slug = target?.slug ?? relation.targetSlug;\n const accessor = slug ? accessors.get(slug) : undefined;\n const rowType = accessor\n ? `Database[${emitString(accessor)}][\"Row\"]`\n : \"Record<string, unknown>\";\n // A read of a many-to-many whose junction carries columns serves them on\n // each target as `_pivot` — see `ManyToManyRelation.through.properties`.\n const pivot = relation.kind === \"manyToMany\" ? pivotType(relation.through.properties, \"read\") : undefined;\n const elementType = pivot ? `${rowType} & { _pivot?: ${pivot} }` : rowType;\n return relation.cardinality === \"many\" ? `Array<${elementType}>` : elementType;\n}\n\n/**\n * Map every slug to the property name it is reachable under on `client.data`.\n *\n * The accessor is a safe identifier because `client.data.myNotes` is the point\n * of generating this at all, and `collectionsDictionary` maps it back to the\n * slug the wire uses. Two slugs that safe down to the same identifier cannot\n * both have it: the interface would not compile, and the dictionary — an object\n * literal — would silently keep only the last, routing one collection's reads\n * to the other's table. There is no defensible way to pick, so this refuses.\n */\nfunction buildAccessors(collections: CollectionConfig[]): Map<string, string> {\n const accessors = new Map<string, string>();\n const bySafeName = new Map<string, string>();\n\n for (const collection of collections) {\n const slug = collection.slug;\n if (typeof slug !== \"string\" || slug.length === 0) {\n throw new CodegenError(\n \"A collection has no slug, so it has no name to generate a type for. \" +\n \"Every collection needs a unique `slug`.\"\n );\n }\n\n const safe = toSafeIdentifier(slug);\n if (safe.length === 0) {\n throw new CodegenError(\n `The slug ${emitString(slug)} has no characters that can form a property name, ` +\n \"so it cannot be reached as `client.data.<name>`. Use a slug containing \" +\n \"letters, digits, underscores or dashes.\"\n );\n }\n\n const accessor = toCollectionAccessor(slug);\n if (accessor !== safe) {\n console.warn(\n `[codegen] The collection ${emitString(slug)} would be \\`client.data.${safe}\\`, a name ` +\n `the client reserves, so its typed accessor is \\`client.data.${accessor}\\`. ` +\n `\\`client.data.collection(${emitString(slug)})\\` reaches it too.`\n );\n }\n\n const existing = bySafeName.get(accessor);\n if (existing !== undefined) {\n throw new CodegenError(\n `The collections ${emitString(existing)} and ${emitString(slug)} both generate the ` +\n `accessor \"${accessor}\", so only one of them could be reached from the generated client ` +\n \"and the other's reads would silently go to the wrong table. Rename one of the slugs.\"\n );\n }\n\n bySafeName.set(accessor, slug);\n accessors.set(slug, accessor);\n }\n\n return accessors;\n}\n\n/**\n * A column's type on a write: its own type (a date also as a `Date`), or\n * `null` too when it is not required.\n *\n * `Row` has typed a non-required column `T | null` for a while; its write twins\n * did not, so the one way to clear a value — `update(id, { publishedAt: null })`,\n * `{ authorId: null }` to unassign, the edit-form round trip of a row that came\n * back with nulls in it — was a compile error the server would have accepted.\n * A primary key is never null, required or not.\n */\nfunction writableType(prop: Property, tsType: string): string {\n // A date is written as a `Date` as readily as an ISO string: the client\n // sends it through `JSON.stringify`, which spells it as the ISO string the\n // server stores. `Row` keeps `string`, because that is what a read returns.\n const written = prop.type === \"date\" ? `${tsType} | Date` : tsType;\n return prop.validation?.required || isPrimaryKey(prop) ? written : `${written} | null`;\n}\n\n/** One emitted `key: type;` line, already indented. */\nfunction line(key: string, type: string, optional: boolean): string {\n return ` ${emitKey(key)}${optional ? \"?\" : \"\"}: ${type};`;\n}\n\n/**\n * The keys nobody can reach take off the API surface — in *both* directions.\n *\n * `excludeFromApi` means one thing: the API surface does not mention this\n * property. `Row` already honoured that; `Insert` and `Update` deliberately did\n * not, on the reading that the column is stripped from responses rather than\n * from writes. That left the generated types as the one place a password hash\n * was still named, and it invited a client to send one. The server refuses\n * such a field on a write (`VALIDATION_EXCLUDED_FIELDS`), so nothing generated\n * advertises it.\n *\n * Read through `effectiveAccess`, so the flag and its longhand\n * `access: { read: [], write: [] }` produce the same file. A *role* rule is\n * deliberately not honoured here and `Row` is unchanged by one: a generated type\n * is one shape for every caller, and there is no `Row` that is right for both a\n * reader who holds `hr` and one who does not. The server is the enforcement\n * point; the types describe the surface a caller may name.\n *\n * Every spelling the server restricts, read from the server's own function\n * (`restrictedFieldNames`): the property name, its column name, and — for a\n * closed to-one relation — the foreign key that names the same row. Keying on\n * the property and column alone, which this used to, kept `authorId` on all\n * three types for an `excludeFromApi` `author`, though the server strips it\n * from every read and refuses it on every write.\n */\nfunction excludedApiKeys(collection: CollectionConfig): Set<string> {\n const unreadable = closedNames(collection, \"read\");\n const unwritable = closedNames(collection, \"write\");\n return new Set([...unreadable].filter(name => unwritable.has(name)));\n}\n\n/**\n * The names nobody may read (or write), as the server judges them: no viewer\n * is the trusted plane, which every role-naming rule admits, so what is left\n * is exactly the empty rules.\n *\n * `restrictedFieldNames` resolves the relations of a closed relation property\n * to find its foreign key. When those cannot be resolved — already warned\n * about by the caller — the property and column names are still closed.\n */\nfunction closedNames(collection: CollectionConfig, kind: \"read\" | \"write\"): Set<string> {\n try {\n return restrictedFieldNames(collection, undefined, kind).refused;\n } catch {\n const names = new Set<string>();\n for (const [key, rawProp] of Object.entries((collection.properties ?? {}) as Properties)) {\n const prop = rawProp as Property;\n if (effectiveAccess(prop)?.[kind]?.length !== 0) continue;\n names.add(key);\n if (prop.columnName) names.add(prop.columnName);\n }\n return names;\n }\n}\n\n/**\n * The keys nobody may write: `access: { write: [] }`, readable or not.\n *\n * Off `Insert` and `Update` for the same reason `excludedApiKeys` takes a\n * hidden property off all three — except that a field everyone can read but\n * nobody can write stays on `Row`. The server refuses one on any write with\n * `VALIDATION_EXCLUDED_FIELDS`, for every caller, `admin` included, so a\n * generated `create({ computed })` compiled and could only ever be a 400.\n *\n * A write rule naming *roles* is not this: some caller can write it, and one\n * generated shape cannot say which. A closed to-one relation's foreign key is:\n * the server refuses `reviewerId` exactly as it refuses `reviewer`.\n */\nfunction unwritableKeys(collection: CollectionConfig): Set<string> {\n return closedNames(collection, \"write\");\n}\n\nexport function generateTypedefs(input: CollectionConfig[]): string {\n // Sorted here rather than only in `generate-sdk`: the output is\n // order-dependent and `rebase doctor` regenerates it in memory to diff\n // against the file on disk. While only the writer sorted, a project whose\n // file order differed from its slug order was reported permanently stale.\n const collections = sortCollectionsBySlug(input);\n const accessors = buildAccessors(collections);\n const lines: string[] = [\n \"/**\",\n \" * This file was auto-generated by Rebase.\",\n \" * Do not make direct changes to the file.\",\n \" */\",\n \"\",\n \"export interface Database {\"\n ];\n\n for (const collection of collections) {\n const properties = (collection.properties ?? {}) as Properties;\n\n // Resolve relations\n let resolvedRelations: Record<string, ResolvedRelation> = {};\n try {\n resolvedRelations = resolveCollectionRelations(collection);\n } catch (e) {\n // Swallowed before, which made this the quietest way to ship a\n // wrong type. The foreign-key columns are emitted from the resolved\n // relations rather than from the properties, so losing them drops\n // both the relation fields *and* columns that exist in the\n // database — and the resulting error surfaces in the user's code,\n // typechecking against a `Database` that is missing `author_id`,\n // with nothing pointing back at generation.\n //\n // A target thunk usually throws because of a circular import; the\n // boot-time relation validator names the same cause.\n console.warn(\n `[rebase] Could not resolve the relations of \"${collection.slug}\", so its generated ` +\n \"type has no relation fields and none of their foreign-key columns. This is usually a \" +\n \"circular import in the collection files — make sure the target is `() => otherCollection` \" +\n `and not evaluated at module load.\\n ${e instanceof Error ? e.message : String(e)}`\n );\n }\n\n // Subcollections are collections in their own right and are addressed\n // over a nested path, not as `client.data.<name>`. Generating them here\n // would invent an accessor the client does not serve, so they are\n // skipped — loudly, because doing it silently is how a developer\n // concludes the generator is broken.\n //\n // `getDeclaredSubcollections` rather than a local shape. What stood here\n // declared `subcollections?: unknown[]` and tested it with\n // `Array.isArray` — but the field is `() => CollectionConfig[]`, a thunk,\n // so that test was always false and this warning has never once fired.\n // The two declarations of the same field disagreed, and the\n // double cast between them is what let the wrong one compile.\n //\n // The thunk is called inside the same `try` shape the relation resolver\n // above uses: it exists to defer a circular import, and evaluating it\n // during codegen can throw for exactly that reason. A count that cannot\n // be taken is not worth failing a generate over.\n const declared = getDeclaredSubcollections(collection);\n let subcollectionCount = 0;\n if (declared) {\n try {\n subcollectionCount = declared().length;\n } catch {\n // Declared, but not resolvable from here. Still worth saying.\n subcollectionCount = -1;\n }\n }\n if (subcollectionCount !== 0) {\n console.warn(\n `[rebase] \"${collection.slug}\" declares ${subcollectionCount < 0 ? \"\" : `${subcollectionCount} `}subcollection(s), which are ` +\n \"not part of the generated Database: they are reached over a nested path \" +\n `(\\`data/${collection.slug}/<id>/<relation>\\`), not as a top-level accessor. Register a ` +\n \"subcollection as a collection of its own if you want a typed accessor for it.\"\n );\n }\n\n lines.push(` ${emitKey(accessors.get(collection.slug)!)}: {`);\n\n // ── Row Type ──\n //\n // What a read serves.\n //\n // ## A `belongsTo` has three shapes, and all three are typed\n //\n // One relation, three places it appears, and the wire is not symmetric\n // about it — so the types are not either:\n //\n // 1. **Write** — `Insert`/`Update` accept *either* the foreign key\n // under its own wire name (`{ authorId: 5 }`) or the relation\n // property (`{ author: 5 }`), because the write transformer maps\n // the second onto the first. Emitted by `emitWritableRelations`.\n // 2. **Read** — a row carries `authorId`. Always: it is a column.\n // 3. **Read with `include`** — the target's own row arrives under\n // `author`. Emitted below as optional, because it is absent from\n // every read that did not name it; the generated `RowWith` makes it\n // required for a read that did.\n //\n // The three collapse in exactly one case — a relation named identically\n // to its own foreign key, where 3 is served *over* 2 — handled below.\n //\n // `fields` narrows which columns a read returns, but a column is\n // optional here only because the value may be absent or null, never\n // because the caller might not have asked for it: a projection is a\n // choice made at one call site, and typing every column optional to\n // describe it would make every row unusable everywhere else.\n lines.push(\" Row: {\");\n const emittedKeys = new Set<string>();\n\n // Off the surface entirely — see `excludedApiKeys`. Seeding the emitted\n // set means every later pass (foreign keys, relations, unresolved\n // relations) skips them too, since each of those already refuses to\n // emit a key twice.\n const excluded = excludedApiKeys(collection);\n for (const key of excluded) emittedKeys.add(key);\n\n // 1. Direct properties\n for (const [key, rawProp] of Object.entries(properties)) {\n const prop = rawProp as Property;\n if (prop.type === \"relation\") continue;\n if (excluded.has(key)) continue;\n\n const tsType = propertyToTypeScriptType(prop);\n // A primary key is on every row a read can return, whether or not\n // anyone wrote `validation: { required: true }` next to it —\n // introspection never does, so `row.id` was `string | undefined`\n // for every baas project.\n const isRequired = Boolean(prop.validation?.required) || isPrimaryKey(prop);\n lines.push(line(key, isRequired ? tsType : `${tsType} | null`, !isRequired));\n emittedKeys.add(key);\n }\n\n // 2. FK columns from relations.\n //\n // Emitted under the relation's *wire* name, which is what\n // `fieldKeyForColumn` answers: `localKey` is the database column\n // (`author_id`) and the row arrives keyed `authorId`. Emitting the\n // column, which this used to do, described a key the JSON does not\n // carry and hid the one it does — including from `where` and `orderBy`,\n // which are keyed off this type. The column name is not a second name\n // for the field: it is the name of a different thing.\n for (const [relKey, relation] of Object.entries(resolvedRelations)) {\n if (relation.kind === \"belongsTo\" && relation.localKey) {\n const fkKey = fieldKeyForColumn(collection, relation.localKey);\n if (emittedKeys.has(fkKey)) continue;\n\n const fkType = foreignKeyType(relation);\n\n // A relation addressed by the same name as its own foreign key\n // is served *over* that column when the read includes it: the\n // query nests the target under the relation name, and the\n // scalar it shadows is gone. Both outcomes are real, so the\n // column is typed as both — which is what stops a plain\n // `const id: string = row.author_id` from compiling.\n const shadowedByInclude = relKey === fkKey;\n const tsType = shadowedByInclude\n ? `${fkType} | ${includedRelationType(relation, accessors)}`\n : fkType;\n\n const isRequired = isRelationRequired(collection, relation) && !shadowedByInclude;\n lines.push(line(fkKey, isRequired ? tsType : `${tsType} | null`, !isRequired));\n emittedKeys.add(fkKey);\n }\n }\n\n // 3. Relation fields — the target's own row, inlined.\n //\n // Optional throughout: a relation is only loaded when the read names it\n // in `include`, so it is absent from every other read.\n for (const [key, relation] of Object.entries(resolvedRelations)) {\n if (emittedKeys.has(key)) continue;\n lines.push(line(key, includedRelationType(relation, accessors), true));\n emittedKeys.add(key);\n }\n\n // A `relation` property whose relation could not be resolved — an\n // engine without relation support, or a target that did not load. It is\n // still a column on the row, so it is still typed, just not precisely.\n for (const [key, rawProp] of Object.entries(properties)) {\n if ((rawProp as Property).type !== \"relation\") continue;\n if (emittedKeys.has(key)) continue;\n lines.push(line(key, \"Record<string, unknown>\", true));\n emittedKeys.add(key);\n }\n lines.push(\" };\");\n\n // ── Insert Type ──\n //\n // What `create()` accepts, minus the `excludeFromApi` columns — the\n // property is off the API surface in both directions, so a generated\n // client never names it — and minus every field nobody may write.\n lines.push(\" Insert: {\");\n const notWritable = new Set([...excluded, ...unwritableKeys(collection)]);\n emittedKeys.clear();\n for (const key of notWritable) emittedKeys.add(key);\n\n for (const [key, rawProp] of Object.entries(properties)) {\n const prop = rawProp as Property;\n if (prop.type === \"relation\") continue;\n if (notWritable.has(key)) continue;\n const tsType = propertyToTypeScriptType(prop);\n // A column the database fills (`databaseDefault`) may be left out\n // of a create, as an id the database generates may.\n const isOptional = !prop.validation?.required || isAutoAssignedId(prop) || Boolean(prop.databaseDefault);\n lines.push(line(key, writableType(prop, tsType), isOptional));\n emittedKeys.add(key);\n }\n\n const eitherSpelling = emitWritableRelations(lines, collection, properties, resolvedRelations, emittedKeys, false);\n // A required `belongsTo` written under either of its names: see\n // `emitWritableRelations`. One `& (A | B)` per such relation, so each is\n // satisfied on its own.\n lines.push(eitherSpelling.length === 0 ? \" };\" : ` } & ${eitherSpelling.join(\" & \")};`);\n\n // ── Update Type ──\n //\n // Everything optional, and the primary key left out: an update\n // addresses a row by id, it does not reassign one. Accepting `id` here\n // typechecked `update(id, { id: someoneElses })`.\n lines.push(\" Update: {\");\n emittedKeys.clear();\n for (const key of notWritable) emittedKeys.add(key);\n for (const [key, rawProp] of Object.entries(properties)) {\n const prop = rawProp as Property;\n if (prop.type === \"relation\") continue;\n if (isPrimaryKey(prop)) continue;\n if (notWritable.has(key)) continue;\n lines.push(line(key, writableType(prop, propertyToTypeScriptType(prop)), true));\n emittedKeys.add(key);\n }\n emitWritableRelations(lines, collection, properties, resolvedRelations, emittedKeys, true);\n lines.push(\" };\");\n\n // ── Relations ──\n //\n // Which relations this collection has, and which collection each one\n // reaches. Not a shape a read ever returns — it is the *graph*, and\n // `include` is the one parameter that needs it: `IncludeFor` below\n // walks it to constrain an include's keys to relations that exist, at\n // every level, and `RowWith` reads it to make an included relation\n // non-optional on the row that comes back.\n //\n // Emitted as the accessor NAME rather than the target's `Row`, so a\n // self-referencing or mutually-referencing relation is a finite string\n // instead of a type that expands forever.\n // A collection with no relations gets `Record<never, never>`, not `{}`:\n // the same type for `keyof` (never), but `{}` is what typescript-eslint's\n // recommended `no-empty-object-type` refuses, in every project that\n // lints its generated SDK.\n //\n // An `excludeFromApi` relation is left out: the server answers an\n // include naming one as it answers a typo (`UNKNOWN_RELATION`), so\n // `IncludeFor` must not offer it.\n const includable = Object.entries(resolvedRelations).filter(([key]) => !excluded.has(key));\n if (includable.length === 0) {\n lines.push(\" Relations: Record<never, never>;\");\n } else {\n lines.push(\" Relations: {\");\n }\n for (const [key, relation] of includable) {\n const target = resolveTargetCollection(relation);\n const slug = target?.slug ?? relation.targetSlug;\n const accessor = slug ? accessors.get(slug) : undefined;\n // A target outside this generation run has no accessor to name, so\n // the relation is typed as reaching nothing rather than as reaching\n // something that does not exist.\n lines.push(` ${emitKey(key)}: ${accessor ? emitString(accessor) : \"never\"};`);\n }\n if (includable.length > 0) lines.push(\" };\");\n\n // ── Slug ──\n //\n // The name the wire knows this collection by. The entry is keyed by the\n // accessor (`orderItems`), and the client's typed `collection(slug)`\n // has to get from one to the other: it used to re-derive the accessor\n // from the slug at the type level, handling `-` and nothing else, so\n // `collection(\"order_items\")` — every snake_case table — came back\n // untyped. Written by the one function that chose the accessor, so the\n // two cannot disagree.\n lines.push(` Slug: ${emitString(collection.slug)};`);\n\n lines.push(\" };\");\n }\n\n lines.push(\"}\");\n lines.push(\"\");\n lines.push(\"export type CollectionName = keyof Database;\");\n lines.push(\"\");\n lines.push(\"export const collectionsDictionary = {\");\n for (const collection of collections) {\n lines.push(` ${emitKey(accessors.get(collection.slug)!)}: ${emitString(collection.slug)},`);\n }\n lines.push(\"} as const;\");\n lines.push(\"\");\n // Describes the const above rather than restating its keys. The previous\n // `{ [K in CollectionName]: K }` said every value equalled its key, which is\n // false for any slug that is not already an identifier — `myNotes` maps to\n // `\"my-notes\"` — so the export the CLI tells people to pass did not satisfy\n // its own published type.\n lines.push(\"export type CollectionsDictionary = typeof collectionsDictionary;\");\n lines.push(\"\");\n lines.push(...includeHelperLines());\n\n return lines.join(\"\\n\");\n}\n\n/**\n * The `include` type machinery, emitted into the generated file.\n *\n * It lives here rather than in `@rebasepro/types` because it is the *graph*\n * that makes it work, and the graph only exists once a project's collections\n * have been generated. `IncludeSpec` in `@rebasepro/types` is deliberately\n * unconstrained — a hand-written row type has no relations in it to check\n * against — and these narrow it for a project that does have them.\n *\n * Two things a caller gets:\n *\n * - `IncludeFor<\"posts\">` — an include whose keys are relations that exist,\n * recursively, so `include: { comments: { include: { authr: true } } }` is a\n * compile error rather than a 400 at runtime.\n * - `RowWith<\"posts\", I>` — the row a read with that include returns, where\n * every included relation is **present** rather than optional. `Row` types a\n * relation as optional because it is absent from every read that did not ask\n * for it; once a read has asked, `row.author.name` should not need a `?.`.\n *\n * The depth bound matches the server's (`MAX_INCLUDE_DEPTH`), and is spelled as\n * a decrementing tuple because TypeScript has no arithmetic — `Prev[3]` is `2`.\n * Without a bound, a self-referencing relation makes the type infinite and the\n * compiler gives up with \"type instantiation is excessively deep\".\n */\nfunction includeHelperLines(): string[] {\n return [\n \"/** Which collection each of `A`'s relations reaches. */\",\n \"export type RelationsOf<A extends CollectionName> =\",\n \" Database[A] extends { Relations: infer R } ? R : Record<string, never>;\",\n \"\",\n \"/** The names of `A`'s relations. */\",\n \"export type RelationKeys<A extends CollectionName> = keyof RelationsOf<A> & string;\",\n \"\",\n \"/** The collection a relation reaches, or `never` when it left this project. */\",\n \"export type RelationTarget<A extends CollectionName, K extends RelationKeys<A>> =\",\n \" RelationsOf<A>[K] extends CollectionName ? RelationsOf<A>[K] : never;\",\n \"\",\n \"/** Counts `IncludeFor` down; TypeScript has no arithmetic. */\",\n \"type Prev = [never, 0, 1, 2, 3];\",\n \"\",\n \"/**\",\n \" * Per-relation options, minus `include` — which `IncludeFor` supplies at\",\n \" * the next depth so the nested keys are checked against the *target's*\",\n \" * relations rather than this collection's.\",\n \" */\",\n \"export interface IncludeOptionsFor<A extends CollectionName, K extends RelationKeys<A>, D extends number> {\",\n \" limit?: number;\",\n \" where?: Record<string, unknown>;\",\n \" logical?: unknown;\",\n \" orderBy?: unknown;\",\n \" fields?: string[];\",\n \" include?: RelationTarget<A, K> extends CollectionName\",\n \" ? IncludeFor<RelationTarget<A, K>, Prev[D]>\",\n \" : never;\",\n \"}\",\n \"\",\n \"/**\",\n \" * An `include` for collection `A`: its relation names, dotted paths, or the\",\n \" * parametrised tree — with every key checked against the relations that\",\n \" * actually exist, at every level.\",\n \" */\",\n \"export type IncludeFor<A extends CollectionName, D extends number = 3> =\",\n \" D extends 0\",\n \" ? never\",\n \" : | readonly (RelationKeys<A> | \\\"*\\\")[]\",\n \" | { [K in RelationKeys<A>]?: true | IncludeOptionsFor<A, K, D> };\",\n \"\",\n \"/** The relation names an include asks for at the top level. */\",\n \"type IncludedKeys<A extends CollectionName, I> =\",\n \" I extends readonly (infer K)[]\",\n \" ? Extract<K, RelationKeys<A>>\",\n \" : Extract<keyof I, RelationKeys<A>>;\",\n \"\",\n \"/**\",\n \" * The row a read with include `I` returns: `Row`, with every included\",\n \" * relation made **required**.\",\n \" *\",\n \" * `Row` types a relation as optional because it is absent from every read\",\n \" * that did not name it. Once a read has named it, it is there — and having\",\n \" * to write `row.author?.name` after asking for the author is the type\",\n \" * describing a possibility the query already ruled out.\",\n \" */\",\n \"export type RowWith<A extends CollectionName, I> =\",\n \" Database[A][\\\"Row\\\"] & Required<Pick<Database[A][\\\"Row\\\"], IncludedKeys<A, I> & keyof Database[A][\\\"Row\\\"]>>;\",\n \"\"\n ];\n}\n\n/**\n * The two ways a write can name a `belongsTo` target, both of which the server\n * accepts: the foreign key under its own wire name (`{ authorId: 5 }`, which\n * passes through to the `author_id` column untouched) and the relation\n * *property* (`{ author: 5 }`, which the write transformer maps onto that\n * column).\n *\n * Only the first was generated, so the documented and idiomatic write shape was\n * a type error.\n *\n * The second form is emitted under the **property key**, not the resolved\n * relation name, because that is what the transformer keys off: it looks the\n * payload key up in `properties` and only treats it as a relation if what it\n * finds there is one. A relation whose `relationName` differs from its property\n * key is reachable as the property and not as the name, so emitting the name\n * would have offered a key that writes to a column that does not exist.\n *\n * A **required** `belongsTo` is satisfied by either spelling — the server's\n * required check reads both (`write-validation.ts`). Emitting each name as a\n * required key made a create name the same row twice to compile. So on an\n * `Insert` both names go in optional, and the requirement comes back as one\n * returned `({ authorId: T } | { author: T })` for the caller to intersect\n * with the object. Both stay in the object so `keyof Insert` still names them.\n */\nfunction emitWritableRelations(\n lines: string[],\n collection: CollectionConfig,\n properties: Properties,\n resolvedRelations: Record<string, ResolvedRelation>,\n emittedKeys: Set<string>,\n allOptional: boolean\n): string[] {\n // Every name each `belongsTo` can still be written under, so `emit` knows\n // whether a required one has a second spelling to fall back on.\n const spellings = new Map<ResolvedRelation, string[]>();\n const addSpelling = (relation: ResolvedRelation, key: string): void => {\n if (emittedKeys.has(key)) return;\n const keys = spellings.get(relation) ?? [];\n if (!keys.includes(key)) keys.push(key);\n spellings.set(relation, keys);\n };\n for (const relation of Object.values(resolvedRelations)) {\n if (relation.kind === \"belongsTo\" && relation.localKey) {\n addSpelling(relation, fieldKeyForColumn(collection, relation.localKey));\n }\n }\n for (const [key, rawProp] of Object.entries(properties)) {\n if ((rawProp as Property).type !== \"relation\") continue;\n const relation = findRelation(resolvedRelations, key);\n if (relation?.kind === \"belongsTo\" && relation.localKey) addSpelling(relation, key);\n }\n\n const eitherSpelling: string[] = [];\n // The target's primary key type is the same one `Row` uses. A hardcoded\n // `string | number` here accepted a string for a numeric-keyed target.\n const emit = (key: string, relation: ResolvedRelation): void => {\n if (emittedKeys.has(key)) return;\n const required = isRelationRequired(collection, relation);\n // A foreign key that is not required can be unassigned, which is a\n // write of `null` — see `writableType`.\n const type = required ? foreignKeyType(relation) : `${foreignKeyType(relation)} | null`;\n const names = spellings.get(relation) ?? [key];\n const oneOfSeveral = required && !allOptional && names.length > 1;\n lines.push(line(key, type, allOptional || !required || oneOfSeveral));\n emittedKeys.add(key);\n if (oneOfSeveral && names[0] === key) {\n eitherSpelling.push(`(${names.map(name => `{ ${emitKey(name)}: ${type} }`).join(\" | \")})`);\n }\n };\n\n for (const relation of Object.values(resolvedRelations)) {\n if (relation.kind === \"belongsTo\" && relation.localKey) {\n emit(fieldKeyForColumn(collection, relation.localKey), relation);\n }\n }\n\n for (const [key, rawProp] of Object.entries(properties)) {\n if ((rawProp as Property).type !== \"relation\") continue;\n const relation = findRelation(resolvedRelations, key);\n if (relation?.kind === \"belongsTo\" && relation.localKey) emit(key, relation);\n }\n\n // A `hasOne` is written by naming the target row: the server points the\n // target's foreign key at this row (`inverseRelationUpdates`), and `null`\n // unlinks it. Its resolved relation says `writable: true`, but only\n // `belongsTo` and the to-many kinds were emitted, so the write the server\n // performs was a type error. A single-hop to-one `via` (one step, the\n // target holds the key) is written the same way, by the join-path writer.\n // Keyed by the property, as the second `belongsTo` spelling is: the write\n // transformer only recognises the relation through the property that\n // declares it.\n for (const [key, rawProp] of Object.entries(properties)) {\n if ((rawProp as Property).type !== \"relation\" || emittedKeys.has(key)) continue;\n const relation = findRelation(resolvedRelations, key);\n const toOneWritable = relation?.kind === \"hasOne\"\n || (relation?.kind === \"via\" && relation.cardinality === \"one\" && relation.writable);\n if (!relation || !toOneWritable) continue;\n lines.push(line(key, `${foreignKeyType(relation)} | null`, true));\n emittedKeys.add(key);\n }\n\n // A to-many membership: `hasMany` (the targets' foreign key is pointed at\n // this row) and `manyToMany` (junction rows). The server writes both on a\n // create and an update — bare keys, or `{ id }`, or `{ id, _pivot }` where\n // the junction declares payload columns — but only `belongsTo` was\n // emitted, so the field a read returns could not be written back. A\n // single-hop to-many `via` is written as its one junction's rows and\n // carries no payload; a multi-hop one is read-only (`writable: false`) and\n // stays off.\n for (const [key, relation] of Object.entries(resolvedRelations)) {\n if (relation.cardinality !== \"many\" || !relation.writable) continue;\n if (emittedKeys.has(key)) continue;\n const fk = foreignKeyType(relation);\n const pivot = relation.kind === \"manyToMany\" ? pivotType(relation.through.properties, \"write\") : undefined;\n const element = `${fk} | { id: ${fk}${pivot ? `; _pivot?: ${pivot}` : \"\"} }`;\n lines.push(line(key, `Array<${element}>`, true));\n emittedKeys.add(key);\n }\n\n return eitherSpelling;\n}\n\n/**\n * The `_pivot` a many-to-many link carries: the junction's payload columns,\n * typed as a row's columns are on a read and as a write's on a write. `undefined`\n * when the junction declares none, so there is no `_pivot` to name.\n */\nfunction pivotType(pivotProperties: Properties, direction: \"read\" | \"write\"): string | undefined {\n const entries = Object.entries(pivotProperties);\n if (entries.length === 0) return undefined;\n const fields = entries.map(([key, rawProp]) => {\n const prop = rawProp as Property;\n const tsType = propertyToTypeScriptType(prop);\n const required = Boolean(prop.validation?.required);\n const type = direction === \"write\" ? writableType(prop, tsType) : (required ? tsType : `${tsType} | null`);\n return `${emitKey(key)}${required && direction === \"read\" ? \"\" : \"?\"}: ${type};`;\n });\n return `{ ${fields.join(\" \")} }`;\n}\n","/**\n * @rebasepro/codegen\n *\n * Generates a purely typed Typescript database definition.\n */\n\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { generateTypedefs } from \"./generate-types\";\n\nexport { generateTypedefs, CodegenError } from \"./generate-types\";\nexport { toPascalCase, toCamelCase, toSafeIdentifier, toCollectionAccessor, indent } from \"./utils\";\n\n// ─── Public API ────────────────────────────────────────────────────\n\nexport interface GeneratedFile {\n /** Relative file path within the output directory */\n path: string;\n /** File content */\n content: string;\n}\n\nexport interface GenerateSDKOptions {\n /** Whether to include a README file (default: true) */\n includeReadme?: boolean;\n /**\n * The address the README's example connects to. `rebase generate-sdk`\n * passes the one the project's backend last bound — `rebase dev` derives\n * its port from the project's path, so it is rarely 3001.\n * Default: `http://localhost:3001`.\n */\n baseUrl?: string;\n}\n\nexport function generateSDK(\n collections: CollectionConfig[],\n options: GenerateSDKOptions = {}\n): GeneratedFile[] {\n const files: GeneratedFile[] = [];\n\n files.push({\n path: \"database.types.ts\",\n content: generateTypedefs(collections)\n });\n\n if (options.includeReadme !== false) {\n files.push({\n path: \"README.md\",\n content: `# Rebase SDK\n\n> Auto-generated by \\`rebase generate-sdk\\`. Do not edit manually.\n\n## Usage\n\n1. Install the client package:\n \\`\\`\\`bash\n npm install @rebasepro/client\n \\`\\`\\`\n\n2. Initialize with your generated types:\n \\`\\`\\`typescript\n import { createRebaseClient } from '@rebasepro/client';\n import { collectionsDictionary, type Database } from './database.types';\n\n const rebase = createRebaseClient<Database>({\n baseUrl: '${options.baseUrl ?? \"http://localhost:3001\"}',\n // Maps each accessor back to the slug the wire uses. Without it a\n // hyphenated slug is not resolvable from the property name alone.\n collections: collectionsDictionary,\n });\n\n // Property access is the typed surface: rows, filters and sorts are all\n // checked against the generated Database.\n const { data: users } = await rebase.data.users.find();\n console.log(users[0].email); // flat access — no .values wrapper\n \\`\\`\\`\n\n## Field names are the ones the API serves\n\nThe generated \\`Row\\` uses each field's **wire** name — the key it arrives under in\nJSON — and nothing here renames anything.\n\n- **A declared property is its key in the collection.** A property keyed\n \\`createdAt\\` is \\`row.createdAt\\`, whatever \\`columnName\\` says. A column name is\n the name of a different thing: where the value lives, not what the API calls it.\n- **A foreign key derived from a relation is camelCase**, because that is what\n the wire carries. A \\`belongsTo\\` named \\`author\\` gives you \\`row.authorId\\`, not\n the column spelling.\n- **A collection accessor is camelCase too** (\\`my-notes\\` → \\`rebase.data.myNotes\\`),\n which is what \\`collectionsDictionary\\` maps back to the slug.\n A slug whose accessor the client reserves (\\`collection\\`, \\`then\\`, \\`toJSON\\`)\n is generated as \\`<name>Collection\\`: \\`rebase.data.collectionCollection\\`.\n\n\\`where\\` and \\`orderBy\\` are keyed off the same type, so what compiles is what the\nbackend answers to.\n\n## \\`Row\\` vs \\`Insert\\` vs \\`Update\\`\n\n| Type | What it describes |\n|---|---|\n| \\`Row\\` | What a read serves. Nullable columns are \\`T \\\\| null\\`; relations appear only when \\`include\\` names them. |\n| \\`Insert\\` | What \\`create()\\` accepts. Server-assigned ids are optional; a \\`belongsTo\\` target may be named either way (\\`{ author: 5 }\\` or \\`{ authorId: 5 }\\`). |\n| \\`Update\\` | What \\`update()\\` accepts. Everything optional, and the primary key is not settable. |\n\nA property marked \\`excludeFromApi\\` is absent from all three: the API surface\ndoes not mention it, in either direction. The server holds the same line — a\nread never serves the column and a write naming it is refused — so this is a\nguarantee rather than a description, and nothing generated names a password\nhash.\n\nIf you need an untyped escape hatch, \\`rebase.data.collection(slug)\\` still works —\nbut it is generic over \\`Record<string, unknown>\\` and gives up everything above.\n`\n });\n }\n\n return files;\n}\n"],"mappings":";;;;;;AAaA,SAAgB,OAAO,MAAc,QAAwB;CACzD,MAAM,MAAM,IAAI,OAAO,MAAM;CAC7B,OAAO,KACF,MAAM,IAAI,CAAC,CACX,KAAI,SAAS,KAAK,KAAK,IAAI,MAAM,OAAO,IAAK,CAAC,CAC9C,KAAK,IAAI;AAClB;;;;;;;;;;;ACPA,IAAa,eAAb,cAAkC,MAAM;CACpC,YAAY,SAAiB;EACzB,MAAM,OAAO;EACb,KAAK,OAAO;CAChB;AACJ;AAEA,IAAM,aAAa;;;;;;;;;;;AAYnB,SAAS,QAAQ,KAAqB;CAClC,OAAO,WAAW,KAAK,GAAG,IAAI,MAAM,KAAK,UAAU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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDvD,CAAC;CAGL,OAAO;AACX"}
1
+ {"version":3,"file":"index.es.js","names":[],"sources":["../src/utils.ts","../src/generate-types.ts","../src/index.ts"],"sourcesContent":["/**\n * Utility functions for the SDK generator\n */\n\n/**\n * The naming rules shared with the server's data proxies, which resolve a\n * generated accessor back to its slug: one home, so the two cannot drift.\n */\nexport { toPascalCase, toCamelCase, toSafeIdentifier, toTableAccessor } from \"@rebasepro/common\";\n\n/**\n * Indent a block of text by a given number of spaces\n */\nexport function indent(text: string, spaces: number): string {\n const pad = \" \".repeat(spaces);\n return text\n .split(\"\\n\")\n .map(line => (line.trim() ? pad + line : line))\n .join(\"\\n\");\n}\n","import type { ColumnDescriptor, ColumnType, JsonShape, RelationDescriptor, TableDescriptor } from \"@rebasepro/types\";\nimport { isNumericColumnType, isTemporalColumnType } from \"@rebasepro/types\";\nimport { sortCollectionsBySlug } from \"@rebasepro/common\";\nimport { toTableAccessor, toSafeIdentifier } from \"./utils\";\n\n/**\n * A schema that cannot be expressed as a valid TypeScript file.\n *\n * Thrown rather than emitted. The generator used to concatenate whatever it was\n * given, so a slug that collided with another one, or that was not an\n * identifier, produced a file that either failed to compile or — worse —\n * compiled while quietly routing one table to another's slug.\n *\n * @group SDK generation\n */\nexport class CodegenError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CodegenError\";\n }\n}\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * A property name for the emitted TypeScript: verbatim when it is a valid\n * identifier, quoted otherwise.\n *\n * Every key that reaches the output goes through here. Column keys are not\n * required to be identifiers — `\"order\"`, `\"user id\"`, a quoted Postgres\n * identifier — and the previous behaviour of camel-casing them into shape\n * renamed the column in the type while the wire kept the original, so the\n * generated `Row` described fields that did not exist.\n */\nfunction emitKey(key: string): string {\n return IDENTIFIER.test(key) ? key : JSON.stringify(key);\n}\n\n/**\n * A string literal, escaped.\n *\n * `\"${value}\"` was the previous form. A value containing a quote closed the\n * literal early, which at best broke the file and at worst let a slug from a\n * remote schema inject top-level statements into a file the developer\n * compiles and bundles.\n */\nfunction emitString(value: string): string {\n return JSON.stringify(value);\n}\n\nconst GEOPOINT_TYPE = \"{ latitude: number; longitude: number; }\";\n\n/** A closed value set as a union of literals: strings escaped, numbers only when every value is one. */\nfunction literalUnion(values: readonly (string | number)[], numeric: boolean): string | undefined {\n if (values.length === 0) return undefined;\n if (numeric) {\n const numbers = values.map(Number);\n // A numeric set carrying something that is not a number cannot be\n // written as a union of numeric literals. Widening to `number` is\n // imprecise; emitting `NaN | undefined` is invalid.\n if (numbers.some(n => !Number.isFinite(n))) return undefined;\n return numbers.map(n => String(n)).join(\" | \");\n }\n return values.map(v => emitString(String(v))).join(\" | \");\n}\n\n/**\n * The TypeScript type of a value of one Postgres type, as the wire serves it.\n *\n * A Postgres enum and a `.oneOf()` set are literal unions; a timestamp, a date\n * and a time are ISO strings; `bytea` is base64; a vector is its numbers; a\n * type Rebase serves but does not create (`other`) is `unknown`.\n */\nfunction scalarType(type: ColumnType, oneOf: readonly (string | number)[] | undefined): string {\n if (type.kind === \"enum\") return literalUnion(type.values, false) ?? \"string\";\n if (isNumericColumnType(type)) return (oneOf && literalUnion(oneOf, true)) ?? \"number\";\n switch (type.kind) {\n case \"text\":\n case \"varchar\":\n case \"char\":\n case \"uuid\":\n return (oneOf && literalUnion(oneOf, false)) ?? \"string\";\n case \"boolean\":\n return \"boolean\";\n case \"timestamptz\":\n case \"date\":\n case \"time\":\n return \"string\";\n case \"vector\":\n return \"number[]\";\n case \"bytea\":\n return \"string\";\n case \"json\":\n case \"jsonb\":\n return \"Record<string, unknown>\";\n default:\n return \"unknown\";\n }\n}\n\n/**\n * The TypeScript type of a JSON document, from the shape the table declares.\n *\n * An object types its declared fields — a field the shape does not mark\n * `required` may be absent or null — and an open object (`additional`) with no\n * declared field is a record. A typed block list (`json.oneOf`) is the union of\n * its blocks, each a `{ <typeField>: \"<variant>\"; <valueField>: … }`.\n */\nfunction jsonType(shape: JsonShape): string {\n switch (shape.kind) {\n case \"string\":\n return (shape.oneOf && literalUnion(shape.oneOf, false)) ?? \"string\";\n case \"number\":\n return (shape.oneOf && literalUnion(shape.oneOf, true)) ?? \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"date\":\n return \"string\";\n case \"geopoint\":\n return GEOPOINT_TYPE;\n case \"object\": {\n const entries = Object.entries(shape.fields);\n if (entries.length === 0 && shape.additional) return \"Record<string, unknown>\";\n const inner = entries\n .map(([key, field]) => {\n const optional = !field.required;\n const type = jsonType(field);\n return `${emitKey(key)}${optional ? \"?\" : \"\"}: ${optional ? `${type} | null` : type};`;\n })\n .join(\" \");\n return `{ ${inner} }`;\n }\n case \"array\":\n return `Array<${jsonType(shape.of)}>`;\n case \"oneOf\": {\n const variants = Object.entries(shape.variants);\n // A block whose discriminator and value share a key cannot be\n // written as an object type (a remote schema can say anything).\n if (variants.length === 0 || shape.typeField === shape.valueField) return \"unknown\";\n return variants\n .map(([name, variant]) => `{ ${emitKey(shape.typeField)}: ${emitString(name)}; ${emitKey(shape.valueField)}: ${jsonType(variant)}; }`)\n .join(\" | \");\n }\n default:\n return \"unknown\";\n }\n}\n\n/** The TypeScript type of a column's value on a read. */\nfunction columnType(column: ColumnDescriptor): string {\n if (column.semantic === \"geopoint\") return GEOPOINT_TYPE;\n if (column.json && (column.type.kind === \"json\" || column.type.kind === \"jsonb\")) return jsonType(column.json);\n if (column.type.kind === \"array\") return `Array<${scalarType(column.type.of, column.element?.oneOf)}>`;\n return scalarType(column.type, column.oneOf);\n}\n\n/**\n * The TypeScript type of a key: `number` for a numeric column, `string` for\n * every other — what a foreign key, a link written by the relation's name and\n * a to-many membership hold.\n */\nfunction keyType(column: ColumnDescriptor | undefined): string {\n if (!column) return \"string | number\";\n return isNumericColumnType(column.type) ? \"number\" : \"string\";\n}\n\n/**\n * A column's type on a write: its own type (a temporal column also as a\n * `Date`), or `null` too when it is nullable.\n *\n * `Row` has typed a nullable column `T | null` for a while; its write twins\n * did not, so the one way to clear a value — `update(id, { publishedAt: null })`,\n * `{ authorId: null }` to unassign, the edit-form round trip of a row that came\n * back with nulls in it — was a compile error the server would have accepted.\n * A primary key is never null.\n */\nfunction writableType(column: ColumnDescriptor, tsType: string): string {\n // A temporal value is written as a `Date` as readily as an ISO string: the\n // client sends it through `JSON.stringify`, which spells it as the ISO\n // string the server stores. `Row` keeps `string`, because that is what a\n // read returns.\n const written = isTemporalColumnType(column.type) ? `${tsType} | Date` : tsType;\n return column.nullable ? `${written} | null` : written;\n}\n\n/**\n * Whether a create may leave the column out: it may be null, or the database\n * or the server fills it — a default of any kind (a literal, SQL, a random\n * uuid, an identity, one the database owns), a serial, a stamp.\n */\nfunction insertOptional(column: ColumnDescriptor): boolean {\n if (column.nullable) return true;\n if (column.default !== undefined || column.stamp !== undefined) return true;\n const kind = column.type.kind;\n return kind === \"smallserial\" || kind === \"serial\" || kind === \"bigserial\";\n}\n\n/** Nobody may read it: `.private()`, or `access({ read: [] })`. */\nfunction unreadable(column: ColumnDescriptor): boolean {\n return column.private === true || column.access?.read?.length === 0;\n}\n\n/** Nobody may write it: `.private()`, `.readOnly()`, generated, or `access({ write: [] })`. */\nfunction unwritable(column: ColumnDescriptor): boolean {\n return column.private === true || column.readOnly === true || column.generated !== undefined\n || column.access?.write?.length === 0;\n}\n\n/** One emitted `key: type;` line, already indented. */\nfunction line(key: string, type: string, optional: boolean): string {\n return ` ${emitKey(key)}${optional ? \"?\" : \"\"}: ${type};`;\n}\n\ntype BelongsTo = Extract<RelationDescriptor, { kind: \"belongsTo\" }>;\n\n/** Everything the generator needs to know about the tables of one run. */\ninterface Run {\n accessors: Map<string, string>;\n bySlug: Map<string, TableDescriptor>;\n}\n\n/**\n * Map every slug to the property name it is reachable under on `client.data`.\n *\n * The accessor is a safe identifier because `client.data.myNotes` is the point\n * of generating this at all, and `tablesDictionary` maps it back to the\n * slug the wire uses. Two slugs that safe down to the same identifier cannot\n * both have it: the interface would not compile, and the dictionary — an object\n * literal — would silently keep only the last, routing one table's reads to\n * the other's. There is no defensible way to pick, so this refuses.\n */\nfunction buildAccessors(tables: readonly TableDescriptor[]): Map<string, string> {\n const accessors = new Map<string, string>();\n const bySafeName = new Map<string, string>();\n\n for (const table of tables) {\n const slug = table.slug;\n if (typeof slug !== \"string\" || slug.length === 0) {\n throw new CodegenError(\n \"A table has no slug, so it has no name to generate a type for. \" +\n \"Every table needs a unique `slug`.\"\n );\n }\n\n const safe = toSafeIdentifier(slug);\n if (safe.length === 0) {\n throw new CodegenError(\n `The slug ${emitString(slug)} has no characters that can form a property name, ` +\n \"so it cannot be reached as `client.data.<name>`. Use a slug containing \" +\n \"letters, digits, underscores or dashes.\"\n );\n }\n\n const accessor = toTableAccessor(slug);\n if (accessor !== safe) {\n console.warn(\n `[codegen] The table ${emitString(slug)} would be \\`client.data.${safe}\\`, a name ` +\n `the client reserves, so its typed accessor is \\`client.data.${accessor}\\`. ` +\n `\\`client.data.table(${emitString(slug)})\\` reaches it too.`\n );\n }\n\n const existing = bySafeName.get(accessor);\n if (existing !== undefined) {\n throw new CodegenError(\n `The tables ${emitString(existing)} and ${emitString(slug)} both generate the ` +\n `accessor \"${accessor}\", so only one of them could be reached from the generated client ` +\n \"and the other's reads would silently go to the wrong table. Rename one of the slugs.\"\n );\n }\n\n bySafeName.set(accessor, slug);\n accessors.set(slug, accessor);\n }\n\n return accessors;\n}\n\n/** The single key column of a table, or its first, for the type a link to it holds. */\nfunction keyColumnOf(table: TableDescriptor | undefined): ColumnDescriptor | undefined {\n if (!table) return undefined;\n const key = table.primaryKey[0];\n return key === undefined ? undefined : table.columns.find(column => column.key === key);\n}\n\n/**\n * The type a link to a relation's target holds: whatever the target's key is —\n * or, for a target outside this run, whatever the `belongsTo`'s own foreign-key\n * column holds.\n */\nfunction targetKeyType(relation: RelationDescriptor, run: Run, plan: TablePlan): string {\n const own = relation.kind === \"belongsTo\" ? plan.byKey.get(relation.localField) : undefined;\n return keyType(keyColumnOf(run.bySlug.get(relation.target)) ?? own);\n}\n\n/** Two column types that a foreign key may hold between: identical, a serial read as its integer. */\nfunction sameKeyType(a: ColumnType, b: ColumnType): boolean {\n const plain = (type: ColumnType): ColumnType => {\n switch (type.kind) {\n case \"smallserial\": return { kind: \"smallint\" };\n case \"serial\": return { kind: \"integer\" };\n case \"bigserial\": return { kind: \"bigint\" };\n default: return type;\n }\n };\n return JSON.stringify(plain(a)) === JSON.stringify(plain(b));\n}\n\n/**\n * The key a foreign-key column is served under when a relation derives it:\n * `author_id` → `authorId`, each later segment keeping its own casing. The\n * same rule as `toWireKey` in `@rebasepro/utils` (which this package does not\n * depend on); used only to recognise such a column, never to name one.\n */\nfunction derivedFieldKey(localKey: string): string {\n const segments = localKey.split(/[-_ ]+/).filter(Boolean);\n if (segments.length <= 1) return localKey;\n return segments\n .map((segment, index) => index === 0\n ? segment.charAt(0).toLowerCase() + segment.slice(1)\n : segment.charAt(0).toUpperCase() + segment.slice(1))\n .join(\"\");\n}\n\n/**\n * Whether a `belongsTo`'s column is nothing but the link: the column the\n * relation would derive (its key the derived key of `localKey`, the target's\n * key type, no rule, default or flag of its own), over a constraint.\n *\n * Such a column is listed with the relations, after the table's own columns —\n * where a derived foreign key always is, so declaring the column a relation\n * would derive does not move it in the generated types.\n */\nfunction isLinkOnly(column: ColumnDescriptor, relation: BelongsTo, run: Run): boolean {\n if (!relation.constraint) return false;\n if (column.derived) return true;\n if (derivedFieldKey(relation.localKey) !== column.key) return false;\n if (column.primaryKey || column.default !== undefined || column.generated !== undefined || column.readOnly || column.private) return false;\n if (column.access !== undefined || column.stamp !== undefined || column.validate !== undefined || column.oneOf !== undefined) return false;\n if (column.description !== undefined || column.storage !== undefined || column.semantic !== undefined) return false;\n if (column.vectorIndex !== undefined || column.json !== undefined || column.element !== undefined || column.transforms !== undefined) return false;\n const targetKey = keyColumnOf(run.bySlug.get(relation.target));\n return targetKey === undefined || sameKeyType(column.type, targetKey.type);\n}\n\n/** One table, split the way every block reads it. */\ninterface TablePlan {\n table: TableDescriptor;\n /** The table's own columns, in physical order. */\n columns: ColumnDescriptor[];\n /** Each `belongsTo`, with its foreign-key column when that column is listed with the relations. */\n links: { relation: BelongsTo; column: ColumnDescriptor | undefined }[];\n /** Keys nobody can read or write: off every type. */\n excluded: Set<string>;\n /** Keys nobody may write: off `Insert` and `Update`. */\n unwritable: Set<string>;\n byKey: Map<string, ColumnDescriptor>;\n}\n\nfunction planTable(table: TableDescriptor, run: Run): TablePlan {\n const byKey = new Map(table.columns.map(column => [column.key, column]));\n const linkColumns = new Set<string>();\n const links: TablePlan[\"links\"] = [];\n for (const relation of table.relations) {\n if (relation.kind !== \"belongsTo\") continue;\n const column = byKey.get(relation.localField);\n const listedWithRelation = column !== undefined && isLinkOnly(column, relation, run);\n if (listedWithRelation && column) linkColumns.add(column.key);\n links.push({ relation, column: listedWithRelation ? column : undefined });\n }\n\n // A column nobody may read *and* nobody may write is off the surface in\n // both directions; one nobody may write is off `Insert` and `Update`. A\n // `belongsTo` goes with its foreign-key column: `author: 7` names the same\n // row `authorId: 7` does, and an include of a hidden link would serve it.\n const excluded = new Set<string>();\n const unwritableKeys = new Set<string>();\n for (const column of table.columns) {\n const closedWrite = unwritable(column);\n if (closedWrite) unwritableKeys.add(column.key);\n if (closedWrite && unreadable(column)) excluded.add(column.key);\n }\n for (const relation of table.relations) {\n if (relation.kind !== \"belongsTo\") continue;\n if (excluded.has(relation.localField)) excluded.add(relation.name);\n if (unwritableKeys.has(relation.localField)) unwritableKeys.add(relation.name);\n }\n for (const key of excluded) unwritableKeys.add(key);\n\n return {\n table,\n columns: table.columns.filter(column => !linkColumns.has(column.key)),\n links,\n excluded,\n unwritable: unwritableKeys,\n byKey\n };\n}\n\n/**\n * The type an *included* relation arrives as: the target's own row, inlined.\n *\n * This is what the read pipeline actually serves — the target's flat columns\n * where the relation was, through the SDK and the HTTP API alike. It is\n * deliberately *not* a `{ __type: \"relation\" }` envelope: that shape is the\n * panel's view-model and never reaches a developer's `find()`.\n *\n * Falls back to an open record when the target is not part of this generation\n * run, since there is no `Row` to point at.\n */\nfunction includedRelationType(relation: RelationDescriptor, run: Run): string {\n const accessor = run.accessors.get(relation.target);\n const rowType = accessor\n ? `Database[${emitString(accessor)}][\"Row\"]`\n : \"Record<string, unknown>\";\n // A read of a many-to-many whose junction carries columns serves them on\n // each target as `_pivot`.\n const pivot = relation.kind === \"manyToMany\" ? pivotType(relation.through.pivot, \"read\") : undefined;\n const elementType = pivot ? `${rowType} & { _pivot?: ${pivot} }` : rowType;\n return relation.cardinality === \"many\" ? `Array<${elementType}>` : elementType;\n}\n\n/**\n * Generate the typed SDK's `database.types.ts` from table descriptors — what\n * `compileTables` produces, `GET /api/schema/tables` serves and introspection\n * reports.\n *\n * Emits `Database` (per table: `Row`, `Insert`, `Update`, `Relations`, `Slug`),\n * `TableName`, `tablesDictionary`, `TablesDictionary` and the\n * `include` helpers `RelationsOf`, `RelationKeys`, `RelationTarget`,\n * `IncludeOptionsFor`, `IncludeFor` and `RowWith`.\n *\n * Deterministic: tables are emitted in slug order whatever order they arrive\n * in, so `rebase doctor` can regenerate in memory and diff against the file.\n *\n * @throws {CodegenError} when two slugs produce one accessor, or a slug has\n * nothing an accessor can be built from.\n *\n * @group SDK generation\n */\nexport function generateTypedefs(input: readonly TableDescriptor[]): string {\n // Sorted here rather than only in `generate-sdk`: the output is\n // order-dependent and `rebase doctor` regenerates it in memory to diff\n // against the file on disk. While only the writer sorted, a project whose\n // file order differed from its slug order was reported permanently stale.\n const tables = sortCollectionsBySlug(input);\n const run: Run = {\n accessors: buildAccessors(tables),\n bySlug: new Map(tables.map(table => [table.slug, table]))\n };\n const lines: string[] = [\n \"/**\",\n \" * This file was auto-generated by Rebase.\",\n \" * Do not make direct changes to the file.\",\n \" */\",\n \"\",\n \"export interface Database {\"\n ];\n\n for (const table of tables) {\n const plan = planTable(table, run);\n lines.push(` ${emitKey(run.accessors.get(table.slug)!)}: {`);\n emitRow(lines, plan, run);\n if (table.kind === \"view\") {\n // A view is never written: the server refuses a create, an update\n // and a delete on one, so no write is typed.\n lines.push(\" Insert: never;\");\n lines.push(\" Update: never;\");\n } else {\n emitInsert(lines, plan, run);\n emitUpdate(lines, plan, run);\n }\n emitRelations(lines, plan, run);\n\n // ── Slug ──\n //\n // The name the wire knows this table by. The entry is keyed by the\n // accessor (`orderItems`), and the client's typed `table(slug)`\n // has to get from one to the other. Written by the one function that\n // chose the accessor, so the two cannot disagree.\n lines.push(` Slug: ${emitString(table.slug)};`);\n lines.push(\" };\");\n }\n\n lines.push(\"}\");\n lines.push(\"\");\n lines.push(\"export type TableName = keyof Database;\");\n lines.push(\"\");\n lines.push(\"export const tablesDictionary = {\");\n for (const table of tables) {\n lines.push(` ${emitKey(run.accessors.get(table.slug)!)}: ${emitString(table.slug)},`);\n }\n lines.push(\"} as const;\");\n lines.push(\"\");\n // Describes the const above rather than restating its keys: `myNotes`\n // maps to `\"my-notes\"`, so a `{ [K in TableName]: K }` would be false\n // for every slug that is not already an identifier.\n lines.push(\"export type TablesDictionary = typeof tablesDictionary;\");\n lines.push(\"\");\n lines.push(...includeHelperLines());\n\n return lines.join(\"\\n\");\n}\n\n/**\n * `Row` — what a read serves.\n *\n * ## A `belongsTo` has three shapes, and all three are typed\n *\n * 1. **Write** — `Insert`/`Update` accept *either* the foreign key under its\n * own wire name (`{ authorId: 5 }`) or the relation's name\n * (`{ author: 5 }`). Emitted by `emitWritableRelations`.\n * 2. **Read** — a row carries `authorId`. Always: it is a column.\n * 3. **Read with `include`** — the target's own row arrives under `author`.\n * Optional, because it is absent from every read that did not name it; the\n * generated `RowWith` makes it required for a read that did.\n *\n * `fields` narrows which columns a read returns, but a column is optional here\n * only because the value may be null, never because the caller might not have\n * asked for it: a projection is a choice made at one call site.\n */\nfunction emitRow(lines: string[], plan: TablePlan, run: Run): void {\n lines.push(\" Row: {\");\n const emitted = new Set<string>(plan.excluded);\n // A primary key is on every row a read can return, and so is every\n // `NOT NULL` column; the rest may be null.\n for (const column of plan.columns) {\n if (emitted.has(column.key)) continue;\n const type = columnType(column);\n lines.push(line(column.key, column.nullable ? `${type} | null` : type, column.nullable));\n emitted.add(column.key);\n }\n // The foreign keys listed with their relations, under their wire names.\n for (const { relation, column } of plan.links) {\n if (!column || emitted.has(column.key)) continue;\n const type = targetKeyType(relation, run, plan);\n lines.push(line(column.key, column.nullable ? `${type} | null` : type, column.nullable));\n emitted.add(column.key);\n }\n // The relations — the target's own row, inlined. Optional throughout: a\n // relation is only loaded when the read names it in `include`.\n for (const relation of plan.table.relations) {\n if (emitted.has(relation.name)) continue;\n lines.push(line(relation.name, includedRelationType(relation, run), true));\n emitted.add(relation.name);\n }\n lines.push(\" };\");\n}\n\n/**\n * `Insert` — what `create()` accepts: no hidden column and nothing nobody may\n * write; a column the database or the server fills may be left out.\n */\nfunction emitInsert(lines: string[], plan: TablePlan, run: Run): void {\n lines.push(\" Insert: {\");\n const emitted = new Set<string>(plan.unwritable);\n for (const column of plan.columns) {\n if (emitted.has(column.key)) continue;\n lines.push(line(column.key, writableType(column, columnType(column)), insertOptional(column)));\n emitted.add(column.key);\n }\n const eitherSpelling = emitWritableRelations(lines, plan, run, emitted, false);\n // A required `belongsTo` written under either of its names: one\n // `& (A | B)` per such relation, so each is satisfied on its own.\n lines.push(eitherSpelling.length === 0 ? \" };\" : ` } & ${eitherSpelling.join(\" & \")};`);\n}\n\n/**\n * `Update` — everything optional, and the primary key left out: an update\n * addresses a row by its key, it does not reassign one.\n */\nfunction emitUpdate(lines: string[], plan: TablePlan, run: Run): void {\n lines.push(\" Update: {\");\n const emitted = new Set<string>(plan.unwritable);\n for (const column of plan.columns) {\n if (column.primaryKey || emitted.has(column.key)) continue;\n lines.push(line(column.key, writableType(column, columnType(column)), true));\n emitted.add(column.key);\n }\n emitWritableRelations(lines, plan, run, emitted, true);\n lines.push(\" };\");\n}\n\n/**\n * `Relations` — which relations the table has, and which table each one\n * reaches. Not a shape a read returns: it is the *graph*, and `include` is the\n * one parameter that needs it. `IncludeFor` walks it to constrain an include's\n * keys at every level, and `RowWith` reads it to make an included relation\n * non-optional on the row that comes back.\n *\n * Emitted as the accessor NAME rather than the target's `Row`, so a\n * self-referencing relation is a finite string instead of a type that expands\n * forever. A table with no relations gets `Record<never, never>`, not `{}`,\n * which typescript-eslint's `no-empty-object-type` refuses in every project\n * that lints its generated SDK. A hidden relation is left out: the server\n * answers an include naming one as it answers a typo.\n */\nfunction emitRelations(lines: string[], plan: TablePlan, run: Run): void {\n const includable = plan.table.relations.filter(relation => !plan.excluded.has(relation.name));\n if (includable.length === 0) {\n lines.push(\" Relations: Record<never, never>;\");\n return;\n }\n lines.push(\" Relations: {\");\n for (const relation of includable) {\n const accessor = run.accessors.get(relation.target);\n // A target outside this generation run has no accessor to name, so the\n // relation is typed as reaching nothing rather than as reaching\n // something that does not exist.\n lines.push(` ${emitKey(relation.name)}: ${accessor ? emitString(accessor) : \"never\"};`);\n }\n lines.push(\" };\");\n}\n\n/**\n * The `include` type machinery, emitted into the generated file.\n *\n * It lives here rather than in `@rebasepro/types` because it is the *graph*\n * that makes it work, and the graph only exists once a project's tables have\n * been generated. `IncludeSpec` in `@rebasepro/types` is deliberately\n * unconstrained; these narrow it for a project that has relations.\n *\n * - `IncludeFor<\"posts\">` — an include whose keys are relations that exist,\n * recursively, so a typo is a compile error rather than a 400 at runtime.\n * - `RowWith<\"posts\", I>` — the row a read with that include returns, where\n * every included relation is **present** rather than optional.\n *\n * The depth bound matches the server's (`MAX_INCLUDE_DEPTH`), and is spelled as\n * a decrementing tuple because TypeScript has no arithmetic — `Prev[3]` is `2`.\n */\nfunction includeHelperLines(): string[] {\n return [\n \"/** Which table each of `A`'s relations reaches. */\",\n \"export type RelationsOf<A extends TableName> =\",\n \" Database[A] extends { Relations: infer R } ? R : Record<string, never>;\",\n \"\",\n \"/** The names of `A`'s relations. */\",\n \"export type RelationKeys<A extends TableName> = keyof RelationsOf<A> & string;\",\n \"\",\n \"/** The table a relation reaches, or `never` when it left this project. */\",\n \"export type RelationTarget<A extends TableName, K extends RelationKeys<A>> =\",\n \" RelationsOf<A>[K] extends TableName ? RelationsOf<A>[K] : never;\",\n \"\",\n \"/** Counts `IncludeFor` down; TypeScript has no arithmetic. */\",\n \"type Prev = [never, 0, 1, 2, 3];\",\n \"\",\n \"/**\",\n \" * Per-relation options, minus `include` — which `IncludeFor` supplies at\",\n \" * the next depth so the nested keys are checked against the *target's*\",\n \" * relations rather than this table's.\",\n \" */\",\n \"export interface IncludeOptionsFor<A extends TableName, K extends RelationKeys<A>, D extends number> {\",\n \" limit?: number;\",\n \" where?: Record<string, unknown>;\",\n \" logical?: unknown;\",\n \" orderBy?: unknown;\",\n \" fields?: string[];\",\n \" include?: RelationTarget<A, K> extends TableName\",\n \" ? IncludeFor<RelationTarget<A, K>, Prev[D]>\",\n \" : never;\",\n \"}\",\n \"\",\n \"/**\",\n \" * An `include` for table `A`: its relation names, dotted paths, or the\",\n \" * parametrised tree — with every key checked against the relations that\",\n \" * actually exist, at every level.\",\n \" */\",\n \"export type IncludeFor<A extends TableName, D extends number = 3> =\",\n \" D extends 0\",\n \" ? never\",\n \" : | readonly (RelationKeys<A> | \\\"*\\\")[]\",\n \" | { [K in RelationKeys<A>]?: true | IncludeOptionsFor<A, K, D> };\",\n \"\",\n \"/** The relation names an include asks for at the top level. */\",\n \"type IncludedKeys<A extends TableName, I> =\",\n \" I extends readonly (infer K)[]\",\n \" ? Extract<K, RelationKeys<A>>\",\n \" : Extract<keyof I, RelationKeys<A>>;\",\n \"\",\n \"/**\",\n \" * The row a read with include `I` returns: `Row`, with every included\",\n \" * relation made **required**.\",\n \" *\",\n \" * `Row` types a relation as optional because it is absent from every read\",\n \" * that did not name it. Once a read has named it, it is there — and having\",\n \" * to write `row.author?.name` after asking for the author is the type\",\n \" * describing a possibility the query already ruled out.\",\n \" */\",\n \"export type RowWith<A extends TableName, I> =\",\n \" Database[A][\\\"Row\\\"] & Required<Pick<Database[A][\\\"Row\\\"], IncludedKeys<A, I> & keyof Database[A][\\\"Row\\\"]>>;\",\n \"\"\n ];\n}\n\n/**\n * Every relation write the server performs, typed.\n *\n * - A `belongsTo` is written under either of two names: its foreign key's wire\n * key (`{ authorId: 5 }`) and the relation's name (`{ author: 5 }`), which\n * the server maps onto the column — the second only over a constraint\n * (`rel.belongsTo(…, { constraint: false })` keeps a bare column, written by\n * its key alone). A **required** `belongsTo` is satisfied by either: on an\n * `Insert` both names go in optional, and the requirement comes back as one\n * returned `({ authorId: T } | { author: T })` for the caller to intersect\n * with the object. Both stay in the object so `keyof Insert` names them.\n * - A `hasOne`, and a single-hop to-one `via`, is written by naming the target\n * row; `null` unlinks it.\n * - A to-many membership (`hasMany`, `manyToMany`, a single-hop to-many `via`)\n * is written as the targets' keys, or `{ id }`, or `{ id, _pivot }` where the\n * junction declares payload columns. A multi-hop `via` is read-only.\n *\n * The target's key type is the one `Row` uses for the link.\n */\nfunction emitWritableRelations(\n lines: string[],\n plan: TablePlan,\n run: Run,\n emittedKeys: Set<string>,\n allOptional: boolean\n): string[] {\n // Every name each `belongsTo` can still be written under, so `emit` knows\n // whether a required one has a second spelling to fall back on.\n const spellings = new Map<BelongsTo, string[]>();\n const addSpelling = (relation: BelongsTo, key: string): void => {\n if (emittedKeys.has(key)) return;\n const keys = spellings.get(relation) ?? [];\n if (!keys.includes(key)) keys.push(key);\n spellings.set(relation, keys);\n };\n for (const { relation } of plan.links) addSpelling(relation, relation.localField);\n for (const { relation } of plan.links) if (relation.constraint) addSpelling(relation, relation.name);\n\n const eitherSpelling: string[] = [];\n const emit = (key: string, relation: BelongsTo): void => {\n if (emittedKeys.has(key)) return;\n const required = plan.byKey.get(relation.localField)?.nullable === false;\n // A foreign key that is not required can be unassigned, which is a\n // write of `null` — see `writableType`.\n const type = required ? targetKeyType(relation, run, plan) : `${targetKeyType(relation, run, plan)} | null`;\n const names = spellings.get(relation) ?? [key];\n const oneOfSeveral = required && !allOptional && names.length > 1;\n lines.push(line(key, type, allOptional || !required || oneOfSeveral));\n emittedKeys.add(key);\n if (oneOfSeveral && names[0] === key) {\n eitherSpelling.push(`(${names.map(name => `{ ${emitKey(name)}: ${type} }`).join(\" | \")})`);\n }\n };\n\n for (const { relation } of plan.links) emit(relation.localField, relation);\n for (const { relation } of plan.links) if (relation.constraint) emit(relation.name, relation);\n\n for (const relation of plan.table.relations) {\n if (emittedKeys.has(relation.name)) continue;\n const toOneWritable = relation.kind === \"hasOne\"\n || (relation.kind === \"via\" && relation.cardinality === \"one\" && relation.writable);\n if (!toOneWritable) continue;\n lines.push(line(relation.name, `${targetKeyType(relation, run, plan)} | null`, true));\n emittedKeys.add(relation.name);\n }\n\n for (const relation of plan.table.relations) {\n if (relation.cardinality !== \"many\" || emittedKeys.has(relation.name)) continue;\n if (relation.kind === \"via\" && !relation.writable) continue;\n const fk = targetKeyType(relation, run, plan);\n const pivot = relation.kind === \"manyToMany\" ? pivotType(relation.through.pivot, \"write\") : undefined;\n const element = `${fk} | { id: ${fk}${pivot ? `; _pivot?: ${pivot}` : \"\"} }`;\n lines.push(line(relation.name, `Array<${element}>`, true));\n emittedKeys.add(relation.name);\n }\n\n return eitherSpelling;\n}\n\n/**\n * The `_pivot` a many-to-many link carries: the junction's payload columns,\n * typed as a row's columns are on a read and as a write's on a write.\n * `undefined` when the junction declares none, so there is no `_pivot` to name.\n */\nfunction pivotType(pivot: readonly ColumnDescriptor[], direction: \"read\" | \"write\"): string | undefined {\n if (pivot.length === 0) return undefined;\n const fields = pivot.map(column => {\n const tsType = columnType(column);\n const required = !column.nullable;\n const type = direction === \"write\" ? writableType(column, tsType) : (required ? tsType : `${tsType} | null`);\n return `${emitKey(column.key)}${required && direction === \"read\" ? \"\" : \"?\"}: ${type};`;\n });\n return `{ ${fields.join(\" \")} }`;\n}\n","/**\n * @rebasepro/codegen\n *\n * Generates the typed SDK — a purely typed TypeScript database definition —\n * from table descriptors: what `compileTables` makes of `backend/schema`, what\n * `GET /api/schema/tables` serves, and what introspection reports.\n */\n\nimport type { TableDescriptor } from \"@rebasepro/types\";\nimport { generateTypedefs } from \"./generate-types\";\n\nexport { generateTypedefs, CodegenError } from \"./generate-types\";\nexport { toPascalCase, toCamelCase, toSafeIdentifier, toTableAccessor, indent } from \"./utils\";\n\n// ─── Public API ────────────────────────────────────────────────────\n\n/**\n * One file of a generated SDK.\n *\n * @group SDK generation\n */\nexport interface GeneratedFile {\n /** Relative file path within the output directory */\n path: string;\n /** File content */\n content: string;\n}\n\n/**\n * Options of {@link generateSDK}.\n *\n * @group SDK generation\n */\nexport interface GenerateSDKOptions {\n /** Whether to include a README file (default: true) */\n includeReadme?: boolean;\n /**\n * The address the README's example connects to. `rebase generate-sdk`\n * passes the one the project's backend last bound — `rebase dev` derives\n * its port from the project's path, so it is rarely 3001.\n * Default: `http://localhost:3001`.\n */\n baseUrl?: string;\n}\n\n/**\n * The typed SDK for a set of tables: `database.types.ts` (see\n * {@link generateTypedefs}) and, unless switched off, a README.\n *\n * @param tables The table descriptors, in any order.\n *\n * @group SDK generation\n */\nexport function generateSDK(\n tables: readonly TableDescriptor[],\n options: GenerateSDKOptions = {}\n): GeneratedFile[] {\n const files: GeneratedFile[] = [];\n\n files.push({\n path: \"database.types.ts\",\n content: generateTypedefs(tables)\n });\n\n if (options.includeReadme !== false) {\n files.push({\n path: \"README.md\",\n content: `# Rebase SDK\n\n> Auto-generated by \\`rebase generate-sdk\\`. Do not edit manually.\n\n## Usage\n\n1. Install the client package:\n \\`\\`\\`bash\n npm install @rebasepro/client\n \\`\\`\\`\n\n2. Initialize with your generated types:\n \\`\\`\\`typescript\n import { createRebaseClient } from '@rebasepro/client';\n import { tablesDictionary, type Database } from './database.types';\n\n const rebase = createRebaseClient<Database>({\n baseUrl: '${options.baseUrl ?? \"http://localhost:3001\"}',\n // Maps each accessor back to the slug the wire uses. Without it a\n // hyphenated slug is not resolvable from the property name alone.\n tables: tablesDictionary,\n });\n\n // Property access is the typed surface: rows, filters and sorts are all\n // checked against the generated Database.\n const { data: users } = await rebase.data.users.find();\n console.log(users[0].email); // flat access — no .values wrapper\n \\`\\`\\`\n\n## Field names are the ones the API serves\n\nThe generated \\`Row\\` uses each field's **wire** name — the key it arrives under in\nJSON — and nothing here renames anything.\n\n- **A column is its key in \\`columns\\`.** A column keyed \\`createdAt\\` is\n \\`row.createdAt\\`, whatever \\`.column()\\` says. A column name is the name of a\n different thing: where the value lives, not what the API calls it.\n- **A foreign key derived from a relation is camelCase**, because that is what\n the wire carries. A \\`belongsTo\\` named \\`author\\` gives you \\`row.authorId\\`, not\n the column spelling.\n- **A table accessor is camelCase too** (\\`my-notes\\` → \\`rebase.data.myNotes\\`),\n which is what \\`tablesDictionary\\` maps back to the slug.\n A slug whose accessor the client reserves (\\`table\\`, \\`then\\`, \\`toJSON\\`)\n is generated as \\`<name>Table\\`: \\`rebase.data.tableTable\\`.\n\n\\`where\\` and \\`orderBy\\` are keyed off the same type, so what compiles is what the\nbackend answers to.\n\n## \\`Row\\` vs \\`Insert\\` vs \\`Update\\`\n\n| Type | What it describes |\n|---|---|\n| \\`Row\\` | What a read serves. Nullable columns are \\`T \\\\| null\\`; relations appear only when \\`include\\` names them. |\n| \\`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\\`. |\n| \\`Update\\` | What \\`update()\\` accepts. Everything optional, and the primary key is not settable. |\n\nA column marked \\`.private()\\` is absent from all three: the API surface does\nnot mention it, in either direction. The server holds the same line — a\nread never serves the column and a write naming it is refused — so this is a\nguarantee rather than a description, and nothing generated names a password\nhash.\n\nIf you need an untyped escape hatch, \\`rebase.data.table(slug)\\` still works —\nbut it is generic over \\`Record<string, unknown>\\` and gives up everything above.\n`\n });\n }\n\n return files;\n}\n"],"mappings":";;;;;;AAaA,SAAgB,OAAO,MAAc,QAAwB;CACzD,MAAM,MAAM,IAAI,OAAO,MAAM;CA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;;AC9tBA,SAAgB,YACZ,QACA,UAA8B,CAAC,GAChB;CACf,MAAM,QAAyB,CAAC;CAEhC,MAAM,KAAK;EACP,MAAM;EACN,SAAS,iBAAiB,MAAM;CACpC,CAAC;CAED,IAAI,QAAQ,kBAAkB,OAC1B,MAAM,KAAK;EACP,MAAM;EACN,SAAS;;;;;;;;;;;;;;;;;oBAiBD,QAAQ,WAAW,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDvD,CAAC;CAGL,OAAO;AACX"}
package/dist/utils.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * The naming rules shared with the server's data proxies, which resolve a
6
6
  * generated accessor back to its slug: one home, so the two cannot drift.
7
7
  */
8
- export { toPascalCase, toCamelCase, toSafeIdentifier, toCollectionAccessor } from "@rebasepro/common";
8
+ export { toPascalCase, toCamelCase, toSafeIdentifier, toTableAccessor } from "@rebasepro/common";
9
9
  /**
10
10
  * Indent a block of text by a given number of spaces
11
11
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rebasepro/codegen",
3
- "version": "0.30.1",
4
- "description": "Generate a typed JS SDK from Rebase collection definitions",
3
+ "version": "0.31.0-canary.g59cd6fd",
4
+ "description": "Generate a typed JS SDK from Rebase table descriptors",
5
5
  "keywords": [
6
6
  "sdk",
7
7
  "codegen",
@@ -33,7 +33,7 @@
33
33
  "dist"
34
34
  ],
35
35
  "peerDependencies": {
36
- "@rebasepro/types": "0.30.1"
36
+ "@rebasepro/types": "0.31.0-canary.g59cd6fd"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@jest/globals": "^30.4.1",
@@ -43,7 +43,7 @@
43
43
  "ts-jest": "^29.4.12",
44
44
  "typescript": "^6.0.3",
45
45
  "vite": "^8.1.5",
46
- "@rebasepro/types": "0.30.1"
46
+ "@rebasepro/types": "0.31.0-canary.g59cd6fd"
47
47
  },
48
48
  "exports": {
49
49
  ".": {
@@ -54,7 +54,7 @@
54
54
  },
55
55
  "gitHead": "d935eefa5aa8d1009a2398cfac2c1e4ee9aeb6b6",
56
56
  "dependencies": {
57
- "@rebasepro/common": "0.30.1"
57
+ "@rebasepro/common": "0.31.0-canary.g59cd6fd"
58
58
  },
59
59
  "scripts": {
60
60
  "test": "jest --config jest.config.cjs",