@rebasepro/cli 0.24.0 → 0.24.1-canary.g56af4a4
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/bin/rebase.js +3 -0
- package/dist/agent-setup-B31F00DC.js +324 -0
- package/dist/agent-setup-B31F00DC.js.map +1 -0
- package/dist/api-keys-BPBi5nOF.js +524 -0
- package/dist/api-keys-BPBi5nOF.js.map +1 -0
- package/dist/apps-CPXNElX4.js +256 -0
- package/dist/apps-CPXNElX4.js.map +1 -0
- package/dist/args-BnmsEXvu.js +109 -0
- package/dist/args-BnmsEXvu.js.map +1 -0
- package/dist/atlas-dev-database-DTMuEScS.js +62 -0
- package/dist/atlas-dev-database-DTMuEScS.js.map +1 -0
- package/dist/auth-DvY94ZuL.js +395 -0
- package/dist/auth-DvY94ZuL.js.map +1 -0
- package/dist/branch-pointer-DIhKbQLp.js +2 -0
- package/dist/build-CFwUx-Ff.js +336 -0
- package/dist/build-CFwUx-Ff.js.map +1 -0
- package/dist/bundle-BQhP_xiA.js +1617 -0
- package/dist/bundle-BQhP_xiA.js.map +1 -0
- package/dist/cli.d.ts +2 -2
- package/dist/cloud-CkTr-yt0.js +9640 -0
- package/dist/cloud-CkTr-yt0.js.map +1 -0
- package/dist/collection-drift-BKj_BoMq.js +106 -0
- package/dist/collection-drift-BKj_BoMq.js.map +1 -0
- package/dist/commands/api-keys.d.ts +2 -0
- package/dist/commands/db.d.ts +37 -24
- package/dist/commands/dev.d.ts +103 -0
- package/dist/commands/generate_sdk.d.ts +26 -0
- package/dist/commands/skills.d.ts +22 -7
- package/dist/commands/storage.d.ts +46 -0
- package/dist/consent-BWHaYx5p.js +76 -0
- package/dist/consent-BWHaYx5p.js.map +1 -0
- package/dist/context-BqhRydBg.js +1234 -0
- package/dist/context-BqhRydBg.js.map +1 -0
- package/dist/daemon-DBn-shxX.js +2 -0
- package/dist/{daemon-entry-LTFKtpHy.js → daemon-entry-Da-D3rmH.js} +3 -4
- package/dist/daemon-entry-Da-D3rmH.js.map +1 -0
- package/dist/db-CMpBK3sv.js +1252 -0
- package/dist/db-CMpBK3sv.js.map +1 -0
- package/dist/derive-RPIsAVO4.js +474 -0
- package/dist/derive-RPIsAVO4.js.map +1 -0
- package/dist/dev-C9P5Yp9k.js +1593 -0
- package/dist/dev-C9P5Yp9k.js.map +1 -0
- package/dist/dev-db/atlas-dev-database.d.ts +32 -0
- package/dist/dev-db/daemon-entry.d.ts +13 -0
- package/dist/dev-preflight-N1evJL3S.js +2 -0
- package/dist/doctor-DYs-NqFI.js +771 -0
- package/dist/doctor-DYs-NqFI.js.map +1 -0
- package/dist/eject-BT6t37D0.js +335 -0
- package/dist/eject-BT6t37D0.js.map +1 -0
- package/dist/fold-static-C1EtHlfV.js +201 -0
- package/dist/fold-static-C1EtHlfV.js.map +1 -0
- package/dist/function-portability-BIvlvR9q.js +265 -0
- package/dist/function-portability-BIvlvR9q.js.map +1 -0
- package/dist/generate_sdk-UV635zSe.js +477 -0
- package/dist/generate_sdk-UV635zSe.js.map +1 -0
- package/dist/index.es.js +141 -24674
- package/dist/index.es.js.map +1 -1
- package/dist/init-fXeBcxuN.js +1042 -0
- package/dist/init-fXeBcxuN.js.map +1 -0
- package/dist/manifest-DzlC60WX.js +871 -0
- package/dist/manifest-DzlC60WX.js.map +1 -0
- package/dist/normalize-imports-CmVdE9iZ.js +100 -0
- package/dist/normalize-imports-CmVdE9iZ.js.map +1 -0
- package/dist/{package-manager-CXQevsE1.js → package-manager-DSEOwTqM.js} +2 -2
- package/dist/{package-manager-CXQevsE1.js.map → package-manager-DSEOwTqM.js.map} +1 -1
- package/dist/path-flags-DUBuI2i1.js +77 -0
- package/dist/path-flags-DUBuI2i1.js.map +1 -0
- package/dist/precompress.d.ts +17 -0
- package/dist/prepare-Btn9Ewbn.js +1052 -0
- package/dist/prepare-Btn9Ewbn.js.map +1 -0
- package/dist/{project-DmaGLmH2.js → project-Wp2zoyeN.js} +33 -4
- package/dist/project-Wp2zoyeN.js.map +1 -0
- package/dist/resolve-CJLkfFV0.js +2 -0
- package/dist/resources-DT1COn_6.js +161 -0
- package/dist/resources-DT1COn_6.js.map +1 -0
- package/dist/schema-BDBWvCHu.js +125 -0
- package/dist/schema-BDBWvCHu.js.map +1 -0
- package/dist/skills-DTFibT1m.js +642 -0
- package/dist/skills-DTFibT1m.js.map +1 -0
- package/dist/start-rU2e3Kp5.js +228 -0
- package/dist/start-rU2e3Kp5.js.map +1 -0
- package/dist/{state-C59Elrnt.js → state-Do7ZJYkF.js} +49 -4
- package/dist/state-Do7ZJYkF.js.map +1 -0
- package/dist/status-BR9oyi-y.js +351 -0
- package/dist/status-BR9oyi-y.js.map +1 -0
- package/dist/storage-DyvrSTH3.js +303 -0
- package/dist/storage-DyvrSTH3.js.map +1 -0
- package/dist/telemetry-CAWNCugs.js +338 -0
- package/dist/telemetry-CAWNCugs.js.map +1 -0
- package/dist/telemetry-DbLqGIBW.js +129 -0
- package/dist/telemetry-DbLqGIBW.js.map +1 -0
- package/dist/unknown-command-DNwDcX3w.js +98 -0
- package/dist/unknown-command-DNwDcX3w.js.map +1 -0
- package/dist/upgrade-D-5-Od96.js +1265 -0
- package/dist/upgrade-D-5-Od96.js.map +1 -0
- package/dist/utils/project.d.ts +16 -0
- package/dist/{version-DsgBmP22.js → version-Buyyo1ut.js} +2 -2
- package/dist/{version-DsgBmP22.js.map → version-Buyyo1ut.js.map} +1 -1
- package/package.json +7 -7
- package/templates/eject/backend/src/env.ts +1 -1
- package/templates/eject/backend/src/index.ts +10 -2
- package/templates/template/README.md +1 -1
- package/templates/template/ai-instructions.md +2 -1
- package/templates/template/frontend/vite.config.ts +11 -3
- package/templates/template/scripts/example.ts +2 -1
- package/dist/branch-pointer-kk9F5FBO.js +0 -111
- package/dist/branch-pointer-kk9F5FBO.js.map +0 -1
- package/dist/constraints-DKGbNfUW.js +0 -48
- package/dist/constraints-DKGbNfUW.js.map +0 -1
- package/dist/daemon-C8p32i-n.js +0 -357
- package/dist/daemon-C8p32i-n.js.map +0 -1
- package/dist/daemon-entry-LTFKtpHy.js.map +0 -1
- package/dist/dev-preflight-CNLl4rdo.js +0 -367
- package/dist/dev-preflight-CNLl4rdo.js.map +0 -1
- package/dist/project-DmaGLmH2.js.map +0 -1
- package/dist/resolve-BAeRUBhg.js +0 -74
- package/dist/resolve-BAeRUBhg.js.map +0 -1
- package/dist/state-C59Elrnt.js.map +0 -1
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
import { n as getPMCommands, t as detectPackageManager } from "./package-manager-DSEOwTqM.js";
|
|
2
|
+
import { c as findProjectRoot } from "./project-Wp2zoyeN.js";
|
|
3
|
+
import { d as findBackendApp, m as manifestExists, p as loadManifest, x as writeManifest } from "./manifest-DzlC60WX.js";
|
|
4
|
+
import { M as readLink } from "./context-BqhRydBg.js";
|
|
5
|
+
import { n as COLLECTIONS_PATH_RULE, t as COLLECTIONS_FLAG_HELP } from "./path-flags-DUBuI2i1.js";
|
|
6
|
+
import { n as isLoadedCollectionFile } from "./collection-drift-BKj_BoMq.js";
|
|
7
|
+
import chalk from "chalk";
|
|
8
|
+
import fs from "fs";
|
|
9
|
+
import path from "path";
|
|
10
|
+
import { computeSchemaVersion, deserializeCollections } from "@rebasepro/types";
|
|
11
|
+
import { CodegenError, generateSDK, toCollectionAccessor } from "@rebasepro/codegen";
|
|
12
|
+
//#region src/commands/generate_sdk.ts
|
|
13
|
+
/**
|
|
14
|
+
* CLI command: generate-sdk
|
|
15
|
+
*
|
|
16
|
+
* Reads every collection file in a directory (default: ./config/collections) —
|
|
17
|
+
* the files the backend serves, not the barrel's list — generates a typed
|
|
18
|
+
* TypeScript SDK, and writes it to the output directory (default: ./generated/sdk).
|
|
19
|
+
*
|
|
20
|
+
* Uses jiti for dynamic TypeScript import of collection files.
|
|
21
|
+
*/
|
|
22
|
+
/** What `--register` writes, and what marks a project as having opted in. */
|
|
23
|
+
var REGISTER_FILE = "register.ts";
|
|
24
|
+
/** The first line of {@link REGISTER_FILE}: a file without it is the developer's own. */
|
|
25
|
+
var REGISTER_MARKER = "// Auto-generated by `rebase generate-sdk --register`. Do not edit.";
|
|
26
|
+
var REGISTER_SOURCE = `${REGISTER_MARKER}
|
|
27
|
+
//
|
|
28
|
+
// Registers this project's generated \`Database\` on \`@rebasepro/types\`, so
|
|
29
|
+
// \`context.data\` in collection callbacks, \`rebase.dataAsAdmin\`, and the
|
|
30
|
+
// \`rebase\` a function or a cron receives are typed from it. Every later
|
|
31
|
+
// \`rebase generate-sdk\` (and \`rebase dev\`) refreshes this directory; delete
|
|
32
|
+
// it to go back to untyped server-side data.
|
|
33
|
+
import type { Database } from "./database.types";
|
|
34
|
+
|
|
35
|
+
declare module "@rebasepro/types" {
|
|
36
|
+
interface Register {
|
|
37
|
+
database: Database;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
`;
|
|
41
|
+
/**
|
|
42
|
+
* Where `--register` writes: `generated/` beside the collections directory,
|
|
43
|
+
* which is `config/generated/` in a scaffolded project.
|
|
44
|
+
*
|
|
45
|
+
* Inside `config/` because that is the one directory both compiles of a
|
|
46
|
+
* collection file include: the backend's program (it includes
|
|
47
|
+
* `../config/**`) and the `config` package's own `tsc`. A registration
|
|
48
|
+
* there that imported `../generated/sdk/database.types` pulled a file from
|
|
49
|
+
* outside `config/` into that package's program, which TypeScript refuses
|
|
50
|
+
* (the file is not under its `rootDir`) — so the types are copied in beside
|
|
51
|
+
* the registration rather than imported from the SDK.
|
|
52
|
+
*/
|
|
53
|
+
function registrationDir(collectionsDir) {
|
|
54
|
+
return path.join(path.dirname(path.resolve(collectionsDir)), "generated");
|
|
55
|
+
}
|
|
56
|
+
/** Whether this project opted in: the registration is there, and it is ours. */
|
|
57
|
+
function hasRegistration(dir) {
|
|
58
|
+
try {
|
|
59
|
+
return fs.readFileSync(path.join(dir, REGISTER_FILE), "utf-8").startsWith(REGISTER_MARKER);
|
|
60
|
+
} catch {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** Write a file only when its content changed, so a watcher on the directory does not restart for nothing. */
|
|
65
|
+
function writeIfChanged(filePath, content) {
|
|
66
|
+
try {
|
|
67
|
+
if (fs.readFileSync(filePath, "utf-8") === content) return;
|
|
68
|
+
} catch {}
|
|
69
|
+
fs.writeFileSync(filePath, content, "utf-8");
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Write the generated `Database` and its `Register` augmentation into
|
|
73
|
+
* {@link registrationDir}. Refuses to overwrite a `register.ts` it did not
|
|
74
|
+
* write.
|
|
75
|
+
*/
|
|
76
|
+
function writeRegistration(dir, databaseTypes) {
|
|
77
|
+
const registerPath = path.join(dir, REGISTER_FILE);
|
|
78
|
+
if (fs.existsSync(registerPath) && !hasRegistration(dir)) throw new Error(`${registerPath} exists and was not written by "rebase generate-sdk --register". Move it, or register the Database there yourself.`);
|
|
79
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
80
|
+
writeIfChanged(path.join(dir, "database.types.ts"), databaseTypes);
|
|
81
|
+
writeIfChanged(registerPath, REGISTER_SOURCE);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Whether `rebase.json` asks for the registration (`registerDatabase: true` on
|
|
85
|
+
* the backend app). That is what survives a clone: `generated/` is gitignored,
|
|
86
|
+
* so a `register.ts` from an earlier run is not there to say it.
|
|
87
|
+
*
|
|
88
|
+
* An unreadable manifest answers no; `rebase build` is where it is reported.
|
|
89
|
+
*/
|
|
90
|
+
function manifestRegisters(projectRoot) {
|
|
91
|
+
if (!projectRoot || !manifestExists(projectRoot)) return false;
|
|
92
|
+
try {
|
|
93
|
+
return findBackendApp(loadManifest(projectRoot).manifest)?.app.registerDatabase === true;
|
|
94
|
+
} catch {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Remember `--register` in `rebase.json`, so later runs, `rebase dev` and a
|
|
100
|
+
* fresh clone keep registering. Returns where it was written, or why not.
|
|
101
|
+
*
|
|
102
|
+
* Never creates the file: a project without one is synthesized from its
|
|
103
|
+
* layout, and writing one is `rebase apps init`'s decision, not this flag's.
|
|
104
|
+
*/
|
|
105
|
+
function rememberRegistration(projectRoot) {
|
|
106
|
+
if (!projectRoot || !manifestExists(projectRoot)) return { skipped: "No rebase.json here, so the choice lasts as long as the generated files." };
|
|
107
|
+
let loaded;
|
|
108
|
+
try {
|
|
109
|
+
loaded = loadManifest(projectRoot);
|
|
110
|
+
} catch (error) {
|
|
111
|
+
return { skipped: `rebase.json could not be read (${error instanceof Error ? error.message : String(error)}).` };
|
|
112
|
+
}
|
|
113
|
+
const backend = findBackendApp(loaded.manifest);
|
|
114
|
+
if (!backend) return { skipped: "rebase.json declares no backend app to remember it on." };
|
|
115
|
+
if (backend.app.registerDatabase === true) return { written: loaded.filePath ?? projectRoot };
|
|
116
|
+
return { written: writeManifest(projectRoot, {
|
|
117
|
+
...loaded.manifest,
|
|
118
|
+
apps: {
|
|
119
|
+
...loaded.manifest.apps,
|
|
120
|
+
[backend.name]: {
|
|
121
|
+
...backend.app,
|
|
122
|
+
registerDatabase: true
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}) };
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Load the collections the backend serves, the way it finds them.
|
|
129
|
+
*
|
|
130
|
+
* A directory is read as `loadCollectionsFromDirectory` in @rebasepro/server
|
|
131
|
+
* reads it: every top-level collection file, each default-exporting one
|
|
132
|
+
* collection. The barrel (`index.ts`) is not a registry. The runtime, the admin
|
|
133
|
+
* panel, `rebase build` and `rebase schema generate` all scan the directory, and
|
|
134
|
+
* the barrel only orders the panel's navigation and declares
|
|
135
|
+
* `defaultSecurityRules`. This command used to read the barrel instead, so a
|
|
136
|
+
* collection file left out of it was created, served at `/api/data/<slug>` and
|
|
137
|
+
* listed in the panel, and missing from the typed SDK alone.
|
|
138
|
+
*
|
|
139
|
+
* A file that does not load is fatal, as it is at boot: `rebase dev` runs this
|
|
140
|
+
* on every save, and skipping the file would overwrite good types with a
|
|
141
|
+
* `Database` that is silently short a collection.
|
|
142
|
+
*
|
|
143
|
+
* A path to a single module is read as the runtime reads one: its
|
|
144
|
+
* `backendCollections`, or its `collections`.
|
|
145
|
+
*/
|
|
146
|
+
async function loadCollections(collectionsDir) {
|
|
147
|
+
const absDir = path.resolve(collectionsDir);
|
|
148
|
+
if (!fs.existsSync(absDir)) throw new Error(`Collections directory not found: ${absDir} (${COLLECTIONS_PATH_RULE})`);
|
|
149
|
+
let jiti;
|
|
150
|
+
try {
|
|
151
|
+
const jitiModule = await import("jiti");
|
|
152
|
+
jiti = jitiModule.default || jitiModule;
|
|
153
|
+
} catch {
|
|
154
|
+
const installCmd = [
|
|
155
|
+
...getPMCommands(detectPackageManager()).install,
|
|
156
|
+
"-D",
|
|
157
|
+
"jiti"
|
|
158
|
+
].join(" ");
|
|
159
|
+
throw new Error(`Could not load 'jiti'. Install it with: ${installCmd}\njiti is required to dynamically import TypeScript collection definitions.`);
|
|
160
|
+
}
|
|
161
|
+
if (!fs.statSync(absDir).isDirectory()) {
|
|
162
|
+
const mod = jiti(path.dirname(absDir), {
|
|
163
|
+
interopDefault: true,
|
|
164
|
+
esmResolve: true
|
|
165
|
+
})(absDir);
|
|
166
|
+
const listed = mod.backendCollections ?? mod.collections ?? mod.default;
|
|
167
|
+
if (Array.isArray(listed)) return listed;
|
|
168
|
+
throw new Error(`Could not extract collections from ${absDir}.\nA single collections module exports \`backendCollections\` or \`collections\`: an array of collections.`);
|
|
169
|
+
}
|
|
170
|
+
const jitiInstance = jiti(absDir, {
|
|
171
|
+
interopDefault: true,
|
|
172
|
+
esmResolve: true
|
|
173
|
+
});
|
|
174
|
+
const collections = [];
|
|
175
|
+
const failures = [];
|
|
176
|
+
const files = fs.readdirSync(absDir).filter(isLoadedCollectionFile).sort();
|
|
177
|
+
for (const file of files) try {
|
|
178
|
+
const mod = jitiInstance(path.join(absDir, file));
|
|
179
|
+
const exported = mod.default ?? mod;
|
|
180
|
+
if (exported && typeof exported === "object" && "slug" in exported) collections.push(exported);
|
|
181
|
+
else failures.push(`${file}: no default export of a collection`);
|
|
182
|
+
} catch (err) {
|
|
183
|
+
failures.push(`${file}: ${err.message}`);
|
|
184
|
+
}
|
|
185
|
+
if (failures.length > 0) throw new Error(`Could not load ${failures.length} collection file(s) from ${absDir}:\n` + failures.map((failure) => ` • ${failure}`).join("\n") + "\n\nEvery collection file must import cleanly and default-export a collection — the backend refuses to boot on the same file.");
|
|
186
|
+
return collections;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Write generated files to the output directory.
|
|
190
|
+
*/
|
|
191
|
+
function writeFiles(outputDir, files) {
|
|
192
|
+
const absOutput = path.resolve(outputDir);
|
|
193
|
+
fs.mkdirSync(absOutput, { recursive: true });
|
|
194
|
+
for (const file of files) {
|
|
195
|
+
const filePath = path.join(absOutput, file.path);
|
|
196
|
+
const dir = path.dirname(filePath);
|
|
197
|
+
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
|
198
|
+
fs.writeFileSync(filePath, file.content, "utf-8");
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
function printSdkHelp() {
|
|
202
|
+
console.log(`
|
|
203
|
+
${chalk.bold("rebase generate-sdk")} — generate a typed client from a project's schema
|
|
204
|
+
|
|
205
|
+
${chalk.bold("Usage")}
|
|
206
|
+
rebase generate-sdk [options]
|
|
207
|
+
|
|
208
|
+
${chalk.bold("Options")}
|
|
209
|
+
-c, --collections <dir> ${COLLECTIONS_FLAG_HELP}
|
|
210
|
+
(--collections-dir is accepted too)
|
|
211
|
+
-o, --output <dir> Where to write the SDK (default: ./generated/sdk)
|
|
212
|
+
(--out is accepted too, as on 'rebase build')
|
|
213
|
+
--from <link|url> Fetch the schema from a running project instead of
|
|
214
|
+
local source. "link" uses this checkout's linked project.
|
|
215
|
+
--token <token> Bearer token for the contract endpoint
|
|
216
|
+
(default: $REBASE_SERVICE_KEY)
|
|
217
|
+
--register Also type server-side data: write the types and the
|
|
218
|
+
Register declaration to config/generated/, and
|
|
219
|
+
remember it in rebase.json so later runs keep it.
|
|
220
|
+
-h, --help Show this help
|
|
221
|
+
|
|
222
|
+
${chalk.bold("Examples")}
|
|
223
|
+
rebase generate-sdk From local collections
|
|
224
|
+
rebase generate-sdk --from link From the linked project
|
|
225
|
+
rebase generate-sdk --from https://api.acme.com From any Rebase backend
|
|
226
|
+
rebase generate-sdk --register Type context.data and rebase.dataAsAdmin too
|
|
227
|
+
`.trim());
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Fetch collections from a running project's contract endpoint.
|
|
231
|
+
*
|
|
232
|
+
* The payload replaces relation `target` functions with slug references, so it
|
|
233
|
+
* has to be rehydrated before the generator sees it — the generator *calls*
|
|
234
|
+
* `target()` to decide whether a foreign key is a string or a number, and a
|
|
235
|
+
* missing target silently degrades that to a union rather than failing.
|
|
236
|
+
*/
|
|
237
|
+
async function fetchRemoteCollections(baseUrl, token) {
|
|
238
|
+
const url = `${baseUrl.replace(/\/+$/, "")}/api/meta/contract`;
|
|
239
|
+
const headers = { accept: "application/json" };
|
|
240
|
+
if (token) headers.authorization = `Bearer ${token}`;
|
|
241
|
+
let response;
|
|
242
|
+
try {
|
|
243
|
+
response = await fetch(url, { headers });
|
|
244
|
+
} catch (err) {
|
|
245
|
+
console.log(chalk.red(` ✗ Could not reach ${url}`));
|
|
246
|
+
console.log(chalk.gray(` ${err instanceof Error ? err.message : String(err)}`));
|
|
247
|
+
process.exit(1);
|
|
248
|
+
}
|
|
249
|
+
if (response.status === 401 || response.status === 403) {
|
|
250
|
+
console.log(chalk.red(` ✗ Not authorized to read the project contract (${response.status}).`));
|
|
251
|
+
console.log(chalk.gray(" The contract describes every table and relation, so it is admin-only."));
|
|
252
|
+
console.log(chalk.gray(" Pass --token, or set REBASE_SERVICE_KEY."));
|
|
253
|
+
process.exit(1);
|
|
254
|
+
}
|
|
255
|
+
if (response.status === 404) {
|
|
256
|
+
console.log(chalk.red(" ✗ This server has no contract endpoint."));
|
|
257
|
+
console.log(chalk.gray(" It needs to be running Rebase 0.11 or newer."));
|
|
258
|
+
process.exit(1);
|
|
259
|
+
}
|
|
260
|
+
if (!response.ok) {
|
|
261
|
+
console.log(chalk.red(` ✗ Contract request failed with ${response.status}.`));
|
|
262
|
+
process.exit(1);
|
|
263
|
+
}
|
|
264
|
+
const contract = await response.json();
|
|
265
|
+
if (!Array.isArray(contract.collections)) {
|
|
266
|
+
console.log(chalk.red(" ✗ The contract response did not contain collections."));
|
|
267
|
+
process.exit(1);
|
|
268
|
+
}
|
|
269
|
+
return {
|
|
270
|
+
collections: deserializeCollections(contract.collections),
|
|
271
|
+
schemaVersion: contract.schemaVersion ?? "unknown"
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Decide whether the ambient service key may be sent to this host.
|
|
276
|
+
*
|
|
277
|
+
* `REBASE_SERVICE_KEY` grants full admin bypass. Attaching it to whatever URL
|
|
278
|
+
* happened to be passed — or, worse, to whatever a committed `.rebase/cloud.json`
|
|
279
|
+
* points at — would hand the project's most powerful credential to a host nobody
|
|
280
|
+
* vetted. An explicit `--token` is a decision the caller made; the ambient
|
|
281
|
+
* variable is not, so it only travels to the project this checkout is linked to.
|
|
282
|
+
*/
|
|
283
|
+
function mayUseAmbientKey(target, cwd) {
|
|
284
|
+
const link = readLink(findProjectRoot(cwd) ?? cwd);
|
|
285
|
+
if (!link?.apiUrl) return false;
|
|
286
|
+
try {
|
|
287
|
+
return new URL(link.apiUrl).origin === new URL(target).origin;
|
|
288
|
+
} catch {
|
|
289
|
+
return false;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* The base URL to show in the printed usage example.
|
|
294
|
+
*
|
|
295
|
+
* `rebase dev` binds a port derived from the project path, not 3001, and writes
|
|
296
|
+
* the one it actually got to `.rebase/state.json`. Printing a hardcoded
|
|
297
|
+
* `localhost:3001` sent people to a port nothing was listening on — or, with
|
|
298
|
+
* several projects on one machine, to a different project's backend. Prefer the
|
|
299
|
+
* port this project last ran on; fall back to the literal only when the project
|
|
300
|
+
* has never been started.
|
|
301
|
+
*/
|
|
302
|
+
function resolveExampleBaseUrl(cwd) {
|
|
303
|
+
const projectRoot = findProjectRoot(cwd) ?? cwd;
|
|
304
|
+
try {
|
|
305
|
+
const state = JSON.parse(fs.readFileSync(path.join(projectRoot, ".rebase", "state.json"), "utf-8"));
|
|
306
|
+
if (typeof state.baseUrl === "string" && state.baseUrl) return state.baseUrl;
|
|
307
|
+
if (typeof state.port === "number") return `http://localhost:${state.port}`;
|
|
308
|
+
} catch {}
|
|
309
|
+
return "http://localhost:3001";
|
|
310
|
+
}
|
|
311
|
+
/** Whether a slug can be written as `rebase.data.<slug>` rather than a lookup. */
|
|
312
|
+
function isIdentifierLike(slug) {
|
|
313
|
+
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(slug);
|
|
314
|
+
}
|
|
315
|
+
/** Resolve `--from` into a base URL, following the link file when asked. */
|
|
316
|
+
function resolveSchemaSource(from, cwd) {
|
|
317
|
+
if (from !== "link") {
|
|
318
|
+
let parsed;
|
|
319
|
+
try {
|
|
320
|
+
parsed = new URL(from);
|
|
321
|
+
} catch {
|
|
322
|
+
console.log(chalk.red(` ✗ "${from}" is not a valid URL.`));
|
|
323
|
+
console.log(chalk.gray(" Pass a full URL, e.g. https://api.example.com, or \"link\"."));
|
|
324
|
+
process.exit(1);
|
|
325
|
+
}
|
|
326
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
327
|
+
console.log(chalk.red(" ✗ The project URL must be http or https."));
|
|
328
|
+
process.exit(1);
|
|
329
|
+
}
|
|
330
|
+
return from;
|
|
331
|
+
}
|
|
332
|
+
const link = readLink(findProjectRoot(cwd) ?? cwd);
|
|
333
|
+
if (!link) {
|
|
334
|
+
console.log(chalk.red(" ✗ This checkout is not linked to a project."));
|
|
335
|
+
console.log(chalk.gray(" Run `rebase cloud link <url>`, or pass --from <url>."));
|
|
336
|
+
process.exit(1);
|
|
337
|
+
}
|
|
338
|
+
const apiUrl = link.apiUrl;
|
|
339
|
+
if (!apiUrl) {
|
|
340
|
+
console.log(chalk.red(" ✗ The project link has no API URL."));
|
|
341
|
+
console.log(chalk.gray(" Re-link with `rebase cloud link <url>` to record one."));
|
|
342
|
+
process.exit(1);
|
|
343
|
+
}
|
|
344
|
+
return apiUrl;
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Main entry point for the generate-sdk command.
|
|
348
|
+
*/
|
|
349
|
+
async function generateSdkCommand(args) {
|
|
350
|
+
const { collectionsDir, output, cwd } = args;
|
|
351
|
+
if (args.help) {
|
|
352
|
+
printSdkHelp();
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
const resolvedCollectionsDir = path.isAbsolute(collectionsDir) ? collectionsDir : path.join(cwd, collectionsDir);
|
|
356
|
+
const resolvedOutput = path.isAbsolute(output) ? output : path.join(cwd, output);
|
|
357
|
+
console.log("");
|
|
358
|
+
console.log(chalk.bold(" 🔧 Rebase SDK Generator"));
|
|
359
|
+
console.log("");
|
|
360
|
+
let collections;
|
|
361
|
+
let remoteSchemaVersion;
|
|
362
|
+
if (args.from) {
|
|
363
|
+
const baseUrl = resolveSchemaSource(args.from, cwd);
|
|
364
|
+
console.log(` ${chalk.gray("Project:")} ${baseUrl}`);
|
|
365
|
+
console.log(` ${chalk.gray("Output:")} ${resolvedOutput}`);
|
|
366
|
+
console.log("");
|
|
367
|
+
console.log(chalk.cyan(" → Fetching the project contract..."));
|
|
368
|
+
const ambient = mayUseAmbientKey(baseUrl, cwd) ? process.env.REBASE_SERVICE_KEY : void 0;
|
|
369
|
+
if (!args.token && !ambient && process.env.REBASE_SERVICE_KEY) console.log(chalk.dim(" (not sending REBASE_SERVICE_KEY — this host is not the linked project; pass --token to override)"));
|
|
370
|
+
const remote = await fetchRemoteCollections(baseUrl, args.token || ambient);
|
|
371
|
+
collections = remote.collections;
|
|
372
|
+
remoteSchemaVersion = remote.schemaVersion;
|
|
373
|
+
} else {
|
|
374
|
+
if (!fs.existsSync(resolvedCollectionsDir)) {
|
|
375
|
+
console.log(chalk.gray(" ○ This project derives its API from the database — run `rebase schema introspect` first."));
|
|
376
|
+
console.log(chalk.gray(` Nothing to generate from: ${resolvedCollectionsDir} does not exist.`));
|
|
377
|
+
console.log("");
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
console.log(` ${chalk.gray("Collections:")} ${resolvedCollectionsDir}`);
|
|
381
|
+
console.log(` ${chalk.gray("Output:")} ${resolvedOutput}`);
|
|
382
|
+
console.log("");
|
|
383
|
+
console.log(chalk.cyan(" → Loading collection definitions..."));
|
|
384
|
+
collections = await loadCollections(resolvedCollectionsDir);
|
|
385
|
+
}
|
|
386
|
+
collections.sort((a, b) => a.slug.localeCompare(b.slug));
|
|
387
|
+
if (collections.length === 0) {
|
|
388
|
+
console.log(chalk.red(" ✗ No collections found. Nothing to generate."));
|
|
389
|
+
process.exit(1);
|
|
390
|
+
}
|
|
391
|
+
console.log(chalk.green(` ✓ Found ${collections.length} collection(s): ${collections.map((c) => c.slug).join(", ")}`));
|
|
392
|
+
console.log("");
|
|
393
|
+
console.log(chalk.cyan(" → Generating SDK files..."));
|
|
394
|
+
let files;
|
|
395
|
+
try {
|
|
396
|
+
files = generateSDK(collections);
|
|
397
|
+
} catch (err) {
|
|
398
|
+
if (err instanceof CodegenError) {
|
|
399
|
+
console.log("");
|
|
400
|
+
console.log(chalk.red(` ✗ ${err.message}`));
|
|
401
|
+
process.exit(1);
|
|
402
|
+
}
|
|
403
|
+
throw err;
|
|
404
|
+
}
|
|
405
|
+
const schemaVersion = remoteSchemaVersion ?? computeSchemaVersion(collections);
|
|
406
|
+
files.push({
|
|
407
|
+
path: "schema.meta.ts",
|
|
408
|
+
content: `// Auto-generated by \`rebase generate-sdk\`. Do not edit.
|
|
409
|
+
//
|
|
410
|
+
// The schema version this SDK was generated from. Compare it against the
|
|
411
|
+
// project's current version to detect drift:
|
|
412
|
+
//
|
|
413
|
+
// curl -s <api-url>/api/meta/schema-version
|
|
414
|
+
//
|
|
415
|
+
// Pass it to the client as \`schemaVersion\` and every request carries it in
|
|
416
|
+
// the \`x-rebase-schema\` header, so the server can name the drift instead of
|
|
417
|
+
// answering a renamed field with a bare 400.
|
|
418
|
+
export const SCHEMA_VERSION = ${JSON.stringify(schemaVersion)};
|
|
419
|
+
`
|
|
420
|
+
});
|
|
421
|
+
console.log(chalk.green(` ✓ Generated ${files.length} file(s)`));
|
|
422
|
+
console.log(chalk.gray(` schema ${schemaVersion}`));
|
|
423
|
+
console.log(chalk.cyan(` → Writing to ${resolvedOutput}...`));
|
|
424
|
+
writeFiles(resolvedOutput, files);
|
|
425
|
+
const registerDir = registrationDir(resolvedCollectionsDir);
|
|
426
|
+
const projectRoot = args.projectRoot ?? findProjectRoot(cwd) ?? void 0;
|
|
427
|
+
if (args.register || hasRegistration(registerDir) || manifestRegisters(projectRoot)) {
|
|
428
|
+
if (!fs.existsSync(path.dirname(registerDir))) {
|
|
429
|
+
console.log(chalk.red(` ✗ No ${path.dirname(registerDir)} to register the Database in.`));
|
|
430
|
+
console.log(chalk.gray(" --register writes beside the collections directory; pass --collections."));
|
|
431
|
+
process.exit(1);
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
const databaseTypes = files.find((file) => file.path === "database.types.ts")?.content;
|
|
435
|
+
if (databaseTypes !== void 0) {
|
|
436
|
+
try {
|
|
437
|
+
writeRegistration(registerDir, databaseTypes);
|
|
438
|
+
} catch (error) {
|
|
439
|
+
console.log(chalk.red(` ✗ ${error instanceof Error ? error.message : String(error)}`));
|
|
440
|
+
process.exit(1);
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
console.log(chalk.green(` ✓ Registered the Database for server-side code in ${registerDir}`));
|
|
444
|
+
if (args.register) {
|
|
445
|
+
const remembered = rememberRegistration(projectRoot);
|
|
446
|
+
if ("written" in remembered) console.log(chalk.gray(` Remembered in ${path.relative(cwd, remembered.written) || "rebase.json"} (registerDatabase).`));
|
|
447
|
+
else console.log(chalk.yellow(` ${remembered.skipped}`));
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
console.log("");
|
|
452
|
+
console.log(chalk.green.bold(" ✓ SDK generated successfully!"));
|
|
453
|
+
console.log("");
|
|
454
|
+
const typesImport = `./${path.relative(cwd, path.join(resolvedOutput, "database.types"))}`;
|
|
455
|
+
const metaImport = `./${path.relative(cwd, path.join(resolvedOutput, "schema.meta"))}`;
|
|
456
|
+
const exampleSlug = collections[0]?.slug || "my_collection";
|
|
457
|
+
console.log(chalk.gray(" Usage:"));
|
|
458
|
+
console.log(chalk.gray(" import { createRebaseClient } from '@rebasepro/client';"));
|
|
459
|
+
console.log(chalk.gray(` import { collectionsDictionary, type Database } from '${typesImport}';`));
|
|
460
|
+
console.log(chalk.gray(` import { SCHEMA_VERSION } from '${metaImport}';`));
|
|
461
|
+
console.log("");
|
|
462
|
+
console.log(chalk.gray(" const rebase = createRebaseClient<Database>({"));
|
|
463
|
+
console.log(chalk.gray(` baseUrl: '${resolveExampleBaseUrl(cwd)}',`));
|
|
464
|
+
console.log(chalk.gray(" schemaVersion: SCHEMA_VERSION,"));
|
|
465
|
+
console.log(chalk.gray(" collections: collectionsDictionary,"));
|
|
466
|
+
console.log(chalk.gray(" // token: 'your-jwt-token',"));
|
|
467
|
+
console.log(chalk.gray(" });"));
|
|
468
|
+
console.log("");
|
|
469
|
+
const exampleAccessor = toCollectionAccessor(exampleSlug);
|
|
470
|
+
const exampleAccess = isIdentifierLike(exampleAccessor) ? `rebase.data.${exampleAccessor}` : `rebase.data[${JSON.stringify(exampleAccessor)}]`;
|
|
471
|
+
console.log(chalk.gray(` const { data } = await ${exampleAccess}.find();`));
|
|
472
|
+
console.log("");
|
|
473
|
+
}
|
|
474
|
+
//#endregion
|
|
475
|
+
export { generateSdkCommand };
|
|
476
|
+
|
|
477
|
+
//# sourceMappingURL=generate_sdk-UV635zSe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate_sdk-UV635zSe.js","names":[],"sources":["../src/commands/generate_sdk.ts"],"sourcesContent":["/**\n * CLI command: generate-sdk\n *\n * Reads every collection file in a directory (default: ./config/collections) —\n * the files the backend serves, not the barrel's list — generates a typed\n * TypeScript SDK, and writes it to the output directory (default: ./generated/sdk).\n *\n * Uses jiti for dynamic TypeScript import of collection files.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { CollectionConfig, computeSchemaVersion, deserializeCollections } from \"@rebasepro/types\";\nimport { CodegenError, generateSDK, GeneratedFile, toCollectionAccessor } from \"@rebasepro/codegen\";\nimport { detectPackageManager, getPMCommands } from \"../utils/package-manager\";\nimport { findProjectRoot } from \"../utils/project\";\nimport { findBackendApp, loadManifest, manifestExists, writeManifest } from \"../manifest\";\nimport { readLink } from \"./cloud/context\";\nimport { COLLECTIONS_FLAG_HELP, COLLECTIONS_PATH_RULE } from \"../utils/path-flags\";\nimport { isLoadedCollectionFile } from \"../utils/collection-drift\";\n\ninterface GenerateSDKArgs {\n collectionsDir: string;\n output: string;\n cwd: string;\n /**\n * Where to read the schema from instead of local source.\n *\n * `link` uses this checkout's linked project; anything else is treated as\n * the base URL of a Rebase backend. This is what lets a repository that\n * contains no collections — a separate frontend, a second web app — generate\n * a typed client from the project it talks to.\n */\n from?: string;\n /** Bearer token for the contract endpoint. Falls back to REBASE_SERVICE_KEY. */\n token?: string;\n /**\n * Also register the generated `Database` for server-side code: write the\n * types and the `Register` augmentation into `config/generated/`. See\n * {@link writeRegistration}.\n */\n register?: boolean;\n /**\n * The directory holding `rebase.json`, where `--register` is remembered.\n * Found from `cwd` when not given.\n */\n projectRoot?: string;\n help?: boolean;\n}\n\n/** What `--register` writes, and what marks a project as having opted in. */\nexport const REGISTER_FILE = \"register.ts\";\n\n/** The first line of {@link REGISTER_FILE}: a file without it is the developer's own. */\nconst REGISTER_MARKER = \"// Auto-generated by `rebase generate-sdk --register`. Do not edit.\";\n\nconst REGISTER_SOURCE = `${REGISTER_MARKER}\n//\n// Registers this project's generated \\`Database\\` on \\`@rebasepro/types\\`, so\n// \\`context.data\\` in collection callbacks, \\`rebase.dataAsAdmin\\`, and the\n// \\`rebase\\` a function or a cron receives are typed from it. Every later\n// \\`rebase generate-sdk\\` (and \\`rebase dev\\`) refreshes this directory; delete\n// it to go back to untyped server-side data.\nimport type { Database } from \"./database.types\";\n\ndeclare module \"@rebasepro/types\" {\n interface Register {\n database: Database;\n }\n}\n`;\n\n/**\n * Where `--register` writes: `generated/` beside the collections directory,\n * which is `config/generated/` in a scaffolded project.\n *\n * Inside `config/` because that is the one directory both compiles of a\n * collection file include: the backend's program (it includes\n * `../config/**`) and the `config` package's own `tsc`. A registration\n * there that imported `../generated/sdk/database.types` pulled a file from\n * outside `config/` into that package's program, which TypeScript refuses\n * (the file is not under its `rootDir`) — so the types are copied in beside\n * the registration rather than imported from the SDK.\n */\nexport function registrationDir(collectionsDir: string): string {\n return path.join(path.dirname(path.resolve(collectionsDir)), \"generated\");\n}\n\n/** Whether this project opted in: the registration is there, and it is ours. */\nfunction hasRegistration(dir: string): boolean {\n try {\n return fs.readFileSync(path.join(dir, REGISTER_FILE), \"utf-8\").startsWith(REGISTER_MARKER);\n } catch {\n return false;\n }\n}\n\n/** Write a file only when its content changed, so a watcher on the directory does not restart for nothing. */\nfunction writeIfChanged(filePath: string, content: string): void {\n try {\n if (fs.readFileSync(filePath, \"utf-8\") === content) return;\n } catch {\n // Not there yet.\n }\n fs.writeFileSync(filePath, content, \"utf-8\");\n}\n\n/**\n * Write the generated `Database` and its `Register` augmentation into\n * {@link registrationDir}. Refuses to overwrite a `register.ts` it did not\n * write.\n */\nfunction writeRegistration(dir: string, databaseTypes: string): void {\n const registerPath = path.join(dir, REGISTER_FILE);\n if (fs.existsSync(registerPath) && !hasRegistration(dir)) {\n throw new Error(\n `${registerPath} exists and was not written by \"rebase generate-sdk --register\". ` +\n \"Move it, or register the Database there yourself.\"\n );\n }\n fs.mkdirSync(dir, { recursive: true });\n writeIfChanged(path.join(dir, \"database.types.ts\"), databaseTypes);\n writeIfChanged(registerPath, REGISTER_SOURCE);\n}\n\n/**\n * Whether `rebase.json` asks for the registration (`registerDatabase: true` on\n * the backend app). That is what survives a clone: `generated/` is gitignored,\n * so a `register.ts` from an earlier run is not there to say it.\n *\n * An unreadable manifest answers no; `rebase build` is where it is reported.\n */\nfunction manifestRegisters(projectRoot: string | undefined): boolean {\n if (!projectRoot || !manifestExists(projectRoot)) return false;\n try {\n return findBackendApp(loadManifest(projectRoot).manifest)?.app.registerDatabase === true;\n } catch {\n return false;\n }\n}\n\n/**\n * Remember `--register` in `rebase.json`, so later runs, `rebase dev` and a\n * fresh clone keep registering. Returns where it was written, or why not.\n *\n * Never creates the file: a project without one is synthesized from its\n * layout, and writing one is `rebase apps init`'s decision, not this flag's.\n */\nfunction rememberRegistration(projectRoot: string | undefined): { written: string } | { skipped: string } {\n if (!projectRoot || !manifestExists(projectRoot)) {\n return { skipped: \"No rebase.json here, so the choice lasts as long as the generated files.\" };\n }\n let loaded: ReturnType<typeof loadManifest>;\n try {\n loaded = loadManifest(projectRoot);\n } catch (error) {\n return { skipped: `rebase.json could not be read (${error instanceof Error ? error.message : String(error)}).` };\n }\n const backend = findBackendApp(loaded.manifest);\n if (!backend) return { skipped: \"rebase.json declares no backend app to remember it on.\" };\n if (backend.app.registerDatabase === true) return { written: loaded.filePath ?? projectRoot };\n const manifest = {\n ...loaded.manifest,\n apps: { ...loaded.manifest.apps, [backend.name]: { ...backend.app, registerDatabase: true } }\n };\n return { written: writeManifest(projectRoot, manifest) };\n}\n\n/**\n * Load the collections the backend serves, the way it finds them.\n *\n * A directory is read as `loadCollectionsFromDirectory` in @rebasepro/server\n * reads it: every top-level collection file, each default-exporting one\n * collection. The barrel (`index.ts`) is not a registry. The runtime, the admin\n * panel, `rebase build` and `rebase schema generate` all scan the directory, and\n * the barrel only orders the panel's navigation and declares\n * `defaultSecurityRules`. This command used to read the barrel instead, so a\n * collection file left out of it was created, served at `/api/data/<slug>` and\n * listed in the panel, and missing from the typed SDK alone.\n *\n * A file that does not load is fatal, as it is at boot: `rebase dev` runs this\n * on every save, and skipping the file would overwrite good types with a\n * `Database` that is silently short a collection.\n *\n * A path to a single module is read as the runtime reads one: its\n * `backendCollections`, or its `collections`.\n */\nasync function loadCollections(collectionsDir: string): Promise<CollectionConfig[]> {\n const absDir = path.resolve(collectionsDir);\n\n if (!fs.existsSync(absDir)) {\n throw new Error(`Collections directory not found: ${absDir} (${COLLECTIONS_PATH_RULE})`);\n }\n\n let jiti: (id: string, userOptions?: Record<string, unknown>) => (modulePath: string) => Record<string, unknown>;\n try {\n const jitiModule = await import(\"jiti\");\n jiti = (jitiModule.default || jitiModule) as typeof jiti;\n } catch {\n const installCmd = [...getPMCommands(detectPackageManager()).install, \"-D\", \"jiti\"].join(\" \");\n throw new Error(\n `Could not load 'jiti'. Install it with: ${installCmd}\\n` +\n \"jiti is required to dynamically import TypeScript collection definitions.\"\n );\n }\n\n if (!fs.statSync(absDir).isDirectory()) {\n const mod = jiti(path.dirname(absDir), { interopDefault: true, esmResolve: true })(absDir);\n const listed = mod.backendCollections ?? mod.collections ?? mod.default;\n if (Array.isArray(listed)) return listed as CollectionConfig[];\n throw new Error(\n `Could not extract collections from ${absDir}.\\n` +\n \"A single collections module exports `backendCollections` or `collections`: an array of collections.\"\n );\n }\n\n const jitiInstance = jiti(absDir, {\n interopDefault: true,\n esmResolve: true\n });\n\n const collections: CollectionConfig[] = [];\n const failures: string[] = [];\n const files = fs.readdirSync(absDir).filter(isLoadedCollectionFile).sort();\n\n for (const file of files) {\n try {\n const mod = jitiInstance(path.join(absDir, file));\n const exported = mod.default ?? mod;\n if (exported && typeof exported === \"object\" && \"slug\" in exported) {\n collections.push(exported as CollectionConfig);\n } else {\n failures.push(`${file}: no default export of a collection`);\n }\n } catch (err) {\n failures.push(`${file}: ${(err as Error).message}`);\n }\n }\n\n if (failures.length > 0) {\n throw new Error(\n `Could not load ${failures.length} collection file(s) from ${absDir}:\\n` +\n failures.map(failure => ` • ${failure}`).join(\"\\n\") +\n \"\\n\\nEvery collection file must import cleanly and default-export a collection — \" +\n \"the backend refuses to boot on the same file.\"\n );\n }\n\n return collections;\n}\n\n/**\n * Write generated files to the output directory.\n */\nfunction writeFiles(outputDir: string, files: GeneratedFile[]): void {\n const absOutput = path.resolve(outputDir);\n\n // Create output directory\n fs.mkdirSync(absOutput, { recursive: true });\n\n for (const file of files) {\n const filePath = path.join(absOutput, file.path);\n const dir = path.dirname(filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n fs.writeFileSync(filePath, file.content, \"utf-8\");\n }\n}\n\nfunction printSdkHelp(): void {\n console.log(`\n${chalk.bold(\"rebase generate-sdk\")} — generate a typed client from a project's schema\n\n${chalk.bold(\"Usage\")}\n rebase generate-sdk [options]\n\n${chalk.bold(\"Options\")}\n -c, --collections <dir> ${COLLECTIONS_FLAG_HELP}\n (--collections-dir is accepted too)\n -o, --output <dir> Where to write the SDK (default: ./generated/sdk)\n (--out is accepted too, as on 'rebase build')\n --from <link|url> Fetch the schema from a running project instead of\n local source. \"link\" uses this checkout's linked project.\n --token <token> Bearer token for the contract endpoint\n (default: $REBASE_SERVICE_KEY)\n --register Also type server-side data: write the types and the\n Register declaration to config/generated/, and\n remember it in rebase.json so later runs keep it.\n -h, --help Show this help\n\n${chalk.bold(\"Examples\")}\n rebase generate-sdk From local collections\n rebase generate-sdk --from link From the linked project\n rebase generate-sdk --from https://api.acme.com From any Rebase backend\n rebase generate-sdk --register Type context.data and rebase.dataAsAdmin too\n`.trim());\n}\n\n/**\n * Fetch collections from a running project's contract endpoint.\n *\n * The payload replaces relation `target` functions with slug references, so it\n * has to be rehydrated before the generator sees it — the generator *calls*\n * `target()` to decide whether a foreign key is a string or a number, and a\n * missing target silently degrades that to a union rather than failing.\n */\nasync function fetchRemoteCollections(\n baseUrl: string,\n token: string | undefined\n): Promise<{ collections: CollectionConfig[]; schemaVersion: string }> {\n const url = `${baseUrl.replace(/\\/+$/, \"\")}/api/meta/contract`;\n\n const headers: Record<string, string> = { accept: \"application/json\" };\n if (token) headers.authorization = `Bearer ${token}`;\n\n let response: Response;\n try {\n response = await fetch(url, { headers });\n } catch (err) {\n console.log(chalk.red(` ✗ Could not reach ${url}`));\n console.log(chalk.gray(` ${err instanceof Error ? err.message : String(err)}`));\n process.exit(1);\n }\n\n if (response.status === 401 || response.status === 403) {\n console.log(chalk.red(` ✗ Not authorized to read the project contract (${response.status}).`));\n console.log(chalk.gray(\" The contract describes every table and relation, so it is admin-only.\"));\n console.log(chalk.gray(\" Pass --token, or set REBASE_SERVICE_KEY.\"));\n process.exit(1);\n }\n\n if (response.status === 404) {\n console.log(chalk.red(\" ✗ This server has no contract endpoint.\"));\n console.log(chalk.gray(\" It needs to be running Rebase 0.11 or newer.\"));\n process.exit(1);\n }\n\n if (!response.ok) {\n console.log(chalk.red(` ✗ Contract request failed with ${response.status}.`));\n process.exit(1);\n }\n\n const contract = await response.json() as {\n collections?: unknown[];\n schemaVersion?: string;\n };\n\n if (!Array.isArray(contract.collections)) {\n console.log(chalk.red(\" ✗ The contract response did not contain collections.\"));\n process.exit(1);\n }\n\n return {\n collections: deserializeCollections(contract.collections),\n schemaVersion: contract.schemaVersion ?? \"unknown\"\n };\n}\n\n/**\n * Decide whether the ambient service key may be sent to this host.\n *\n * `REBASE_SERVICE_KEY` grants full admin bypass. Attaching it to whatever URL\n * happened to be passed — or, worse, to whatever a committed `.rebase/cloud.json`\n * points at — would hand the project's most powerful credential to a host nobody\n * vetted. An explicit `--token` is a decision the caller made; the ambient\n * variable is not, so it only travels to the project this checkout is linked to.\n */\nfunction mayUseAmbientKey(target: string, cwd: string): boolean {\n const link = readLink(findProjectRoot(cwd) ?? cwd);\n if (!link?.apiUrl) return false;\n try {\n // Origin, not host: with a link recorded as https, an `http://` target\n // for the same host would otherwise pass and send the key in cleartext.\n return new URL(link.apiUrl).origin === new URL(target).origin;\n } catch {\n return false;\n }\n}\n\n/**\n * The base URL to show in the printed usage example.\n *\n * `rebase dev` binds a port derived from the project path, not 3001, and writes\n * the one it actually got to `.rebase/state.json`. Printing a hardcoded\n * `localhost:3001` sent people to a port nothing was listening on — or, with\n * several projects on one machine, to a different project's backend. Prefer the\n * port this project last ran on; fall back to the literal only when the project\n * has never been started.\n */\nexport function resolveExampleBaseUrl(cwd: string): string {\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n try {\n const state = JSON.parse(fs.readFileSync(path.join(projectRoot, \".rebase\", \"state.json\"), \"utf-8\"));\n if (typeof state.baseUrl === \"string\" && state.baseUrl) return state.baseUrl;\n if (typeof state.port === \"number\") return `http://localhost:${state.port}`;\n } catch {\n // Never started, or the file is unreadable — fall through.\n }\n return \"http://localhost:3001\";\n}\n\n/** Whether a slug can be written as `rebase.data.<slug>` rather than a lookup. */\nexport function isIdentifierLike(slug: string): boolean {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(slug);\n}\n\n/** Resolve `--from` into a base URL, following the link file when asked. */\nfunction resolveSchemaSource(from: string, cwd: string): string {\n if (from !== \"link\") {\n // A bare hostname or a typo would otherwise be handed to `fetch` and fail\n // with something unhelpful; a non-http scheme has no business here at all.\n let parsed: URL;\n try {\n parsed = new URL(from);\n } catch {\n console.log(chalk.red(` ✗ \"${from}\" is not a valid URL.`));\n console.log(chalk.gray(\" Pass a full URL, e.g. https://api.example.com, or \\\"link\\\".\"));\n process.exit(1);\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n console.log(chalk.red(\" ✗ The project URL must be http or https.\"));\n process.exit(1);\n }\n return from;\n }\n\n const projectRoot = findProjectRoot(cwd) ?? cwd;\n const link = readLink(projectRoot);\n\n if (!link) {\n console.log(chalk.red(\" ✗ This checkout is not linked to a project.\"));\n console.log(chalk.gray(\" Run `rebase cloud link <url>`, or pass --from <url>.\"));\n process.exit(1);\n }\n\n const apiUrl = link.apiUrl;\n if (!apiUrl) {\n console.log(chalk.red(\" ✗ The project link has no API URL.\"));\n console.log(chalk.gray(\" Re-link with `rebase cloud link <url>` to record one.\"));\n process.exit(1);\n }\n\n return apiUrl;\n}\n\n/**\n * Main entry point for the generate-sdk command.\n */\nexport async function generateSdkCommand(args: GenerateSDKArgs): Promise<void> {\n const { collectionsDir, output, cwd } = args;\n\n if (args.help) {\n printSdkHelp();\n return;\n }\n\n const resolvedCollectionsDir = path.isAbsolute(collectionsDir)\n ? collectionsDir\n : path.join(cwd, collectionsDir);\n\n const resolvedOutput = path.isAbsolute(output)\n ? output\n : path.join(cwd, output);\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔧 Rebase SDK Generator\"));\n console.log(\"\");\n\n let collections: CollectionConfig[];\n let remoteSchemaVersion: string | undefined;\n\n if (args.from) {\n const baseUrl = resolveSchemaSource(args.from, cwd);\n console.log(` ${chalk.gray(\"Project:\")} ${baseUrl}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Fetching the project contract...\"));\n\n const ambient = mayUseAmbientKey(baseUrl, cwd)\n ? process.env.REBASE_SERVICE_KEY\n : undefined;\n\n if (!args.token && !ambient && process.env.REBASE_SERVICE_KEY) {\n console.log(chalk.dim(\n \" (not sending REBASE_SERVICE_KEY — this host is not the linked project; pass --token to override)\"\n ));\n }\n\n const remote = await fetchRemoteCollections(baseUrl, args.token || ambient);\n collections = remote.collections;\n remoteSchemaVersion = remote.schemaVersion;\n } else {\n // A headless project has no collections directory by design: its API is\n // introspected from the live database at boot, and there is nothing here\n // to generate a client from. The scaffold ships `pnpm generate:sdk`\n // anyway, so the documented headless path had a script that could only\n // ever fail — and it failed with a path, which reads as a broken install\n // rather than a question with an answer.\n if (!fs.existsSync(resolvedCollectionsDir)) {\n console.log(chalk.gray(\n \" ○ This project derives its API from the database — \"\n + \"run `rebase schema introspect` first.\"\n ));\n console.log(chalk.gray(\n ` Nothing to generate from: ${resolvedCollectionsDir} does not exist.`\n ));\n console.log(\"\");\n return;\n }\n console.log(` ${chalk.gray(\"Collections:\")} ${resolvedCollectionsDir}`);\n console.log(` ${chalk.gray(\"Output:\")} ${resolvedOutput}`);\n console.log(\"\");\n console.log(chalk.cyan(\" → Loading collection definitions...\"));\n collections = await loadCollections(resolvedCollectionsDir);\n }\n\n // Sort collections alphabetically by slug to ensure deterministic SDK generation\n collections.sort((a, b) => a.slug.localeCompare(b.slug));\n\n if (collections.length === 0) {\n console.log(chalk.red(\" ✗ No collections found. Nothing to generate.\"));\n process.exit(1);\n }\n\n console.log(chalk.green(` ✓ Found ${collections.length} collection(s): ${collections.map(c => c.slug).join(\", \")}`));\n console.log(\"\");\n\n // 2. Generate SDK files\n console.log(chalk.cyan(\" → Generating SDK files...\"));\n let files: GeneratedFile[];\n try {\n files = generateSDK(collections);\n } catch (err) {\n // A schema that cannot be expressed as valid TypeScript — two slugs\n // that collide on one accessor, a slug with no usable name. The\n // generator refuses rather than emitting a file that does not compile,\n // or one that silently routes a collection's reads to another's table.\n if (err instanceof CodegenError) {\n console.log(\"\");\n console.log(chalk.red(` ✗ ${err.message}`));\n process.exit(1);\n }\n throw err;\n }\n\n // Stamp the schema this SDK was built from.\n //\n // Without it, an app in a separate repository has no way to know its client\n // is stale: the backend moves on, the frontend keeps compiling against types\n // captured weeks ago, and the mismatch only surfaces as a runtime error. With\n // it, CI can compare against `/api/meta/schema-version` and say so.\n //\n // No generation timestamp. Collections are sorted above precisely so that\n // the same schema produces the same bytes; a timestamp put that back,\n // turning every regeneration into a diff and making the obvious staleness\n // gate — `rebase generate-sdk && git diff --exit-code` — impossible to pass.\n // `SCHEMA_VERSION` already identifies what this was built from, and does it\n // in a way that can be compared against a running project.\n const schemaVersion = remoteSchemaVersion ?? computeSchemaVersion(collections);\n files.push({\n path: \"schema.meta.ts\",\n content: `// Auto-generated by \\`rebase generate-sdk\\`. Do not edit.\n//\n// The schema version this SDK was generated from. Compare it against the\n// project's current version to detect drift:\n//\n// curl -s <api-url>/api/meta/schema-version\n//\n// Pass it to the client as \\`schemaVersion\\` and every request carries it in\n// the \\`x-rebase-schema\\` header, so the server can name the drift instead of\n// answering a renamed field with a bare 400.\nexport const SCHEMA_VERSION = ${JSON.stringify(schemaVersion)};\n`\n });\n\n console.log(chalk.green(` ✓ Generated ${files.length} file(s)`));\n console.log(chalk.gray(` schema ${schemaVersion}`));\n\n // 3. Write to disk\n console.log(chalk.cyan(` → Writing to ${resolvedOutput}...`));\n writeFiles(resolvedOutput, files);\n\n // 4. The server-side registration: on request, and kept current once a\n // project has it, so `rebase dev` regenerating the SDK never leaves the\n // server typed against an older schema than the client.\n const registerDir = registrationDir(resolvedCollectionsDir);\n const projectRoot = args.projectRoot ?? findProjectRoot(cwd) ?? undefined;\n if (args.register || hasRegistration(registerDir) || manifestRegisters(projectRoot)) {\n if (!fs.existsSync(path.dirname(registerDir))) {\n console.log(chalk.red(` ✗ No ${path.dirname(registerDir)} to register the Database in.`));\n console.log(chalk.gray(\" --register writes beside the collections directory; pass --collections.\"));\n process.exit(1);\n return;\n }\n const databaseTypes = files.find((file) => file.path === \"database.types.ts\")?.content;\n if (databaseTypes !== undefined) {\n try {\n writeRegistration(registerDir, databaseTypes);\n } catch (error) {\n console.log(chalk.red(` ✗ ${error instanceof Error ? error.message : String(error)}`));\n process.exit(1);\n return;\n }\n console.log(chalk.green(` ✓ Registered the Database for server-side code in ${registerDir}`));\n if (args.register) {\n const remembered = rememberRegistration(projectRoot);\n if (\"written\" in remembered) {\n console.log(chalk.gray(` Remembered in ${path.relative(cwd, remembered.written) || \"rebase.json\"} (registerDatabase).`));\n } else {\n console.log(chalk.yellow(` ${remembered.skipped}`));\n }\n }\n }\n }\n\n console.log(\"\");\n console.log(chalk.green.bold(\" ✓ SDK generated successfully!\"));\n console.log(\"\");\n const typesImport = `./${path.relative(cwd, path.join(resolvedOutput, \"database.types\"))}`;\n const metaImport = `./${path.relative(cwd, path.join(resolvedOutput, \"schema.meta\"))}`;\n const exampleSlug = collections[0]?.slug || \"my_collection\";\n\n console.log(chalk.gray(\" Usage:\"));\n console.log(chalk.gray(\" import { createRebaseClient } from '@rebasepro/client';\"));\n console.log(chalk.gray(` import { collectionsDictionary, type Database } from '${typesImport}';`));\n console.log(chalk.gray(` import { SCHEMA_VERSION } from '${metaImport}';`));\n console.log(\"\");\n console.log(chalk.gray(\" const rebase = createRebaseClient<Database>({\"));\n console.log(chalk.gray(` baseUrl: '${resolveExampleBaseUrl(cwd)}',`));\n // Sent as `x-rebase-schema` on every request. Costs one line here and is\n // the difference between a server that can say \"this client is three\n // deploys behind\" and one that can only reject a field it does not know.\n console.log(chalk.gray(\" schemaVersion: SCHEMA_VERSION,\"));\n // Without the dictionary a hyphenated slug is not resolvable from the\n // property name alone, and the request 404s at runtime.\n console.log(chalk.gray(\" collections: collectionsDictionary,\"));\n console.log(chalk.gray(\" // token: 'your-jwt-token',\"));\n console.log(chalk.gray(\" });\"));\n console.log(\"\");\n // `rebase.data.<accessor>` is the typed surface, so it is what gets printed.\n // `rebase.data.collection(slug)` exists too, but it is generic over\n // `Record<string, unknown>` and has no link to `Database` — it was the\n // headline example here for a while, which advertised the one call shape\n // that throws away the types this command just generated.\n const exampleAccessor = toCollectionAccessor(exampleSlug);\n const exampleAccess = isIdentifierLike(exampleAccessor)\n ? `rebase.data.${exampleAccessor}`\n : `rebase.data[${JSON.stringify(exampleAccessor)}]`;\n console.log(chalk.gray(` const { data } = await ${exampleAccess}.find();`));\n console.log(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoDA,IAAa,gBAAgB;;AAG7B,IAAM,kBAAkB;AAExB,IAAM,kBAAkB,GAAG,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4B3C,SAAgB,gBAAgB,gBAAgC;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