@teable/next-cli 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,1246 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { readFileSync as readFileSync4 } from "node:fs";
5
+ import { parseArgs } from "node:util";
6
+
7
+ // src/checkout.ts
8
+ import { existsSync as existsSync2, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
9
+ import { dirname as dirname2, join, resolve } from "node:path";
10
+
11
+ // src/errors.ts
12
+ var CommandError = class extends Error {
13
+ details;
14
+ constructor(message, details = {}) {
15
+ super(message);
16
+ this.name = "CommandError";
17
+ this.details = details;
18
+ }
19
+ };
20
+ function messageOf(error) {
21
+ if (!(error instanceof Error)) return String(error);
22
+ return error.cause instanceof Error ? `${error.message} (${error.cause.message})` : error.message;
23
+ }
24
+
25
+ // src/git.ts
26
+ import { execFile } from "node:child_process";
27
+
28
+ // src/programs.ts
29
+ import { spawn } from "node:child_process";
30
+ import { existsSync, mkdirSync } from "node:fs";
31
+ import { dirname, posix, win32 } from "node:path";
32
+ var TAIL_CHARS = 4e3;
33
+ function childEnv() {
34
+ const { TEABLE_TOKEN: _withheld, ...env } = process.env;
35
+ return env;
36
+ }
37
+ function currentHost() {
38
+ return {
39
+ platform: process.platform,
40
+ execPath: process.execPath,
41
+ env: process.env,
42
+ exists: existsSync
43
+ };
44
+ }
45
+ function runProgram(program, options) {
46
+ return new Promise((resolve3) => {
47
+ let tail = "";
48
+ let timedOut = false;
49
+ const keep = (chunk) => {
50
+ process.stderr.write(chunk);
51
+ tail = (tail + chunk.toString()).slice(-TAIL_CHARS);
52
+ };
53
+ const child = spawn(program.command, program.args, {
54
+ cwd: options.cwd,
55
+ env: childEnv(),
56
+ stdio: ["ignore", "pipe", "pipe"]
57
+ });
58
+ const timer = setTimeout(() => {
59
+ timedOut = true;
60
+ child.kill("SIGTERM");
61
+ }, options.timeoutMs);
62
+ child.stdout.on("data", keep);
63
+ child.stderr.on("data", keep);
64
+ child.on("error", (error) => {
65
+ clearTimeout(timer);
66
+ resolve3({ exitCode: null, missing: error.code === "ENOENT", tail: tail || error.message });
67
+ });
68
+ child.on("close", (code) => {
69
+ clearTimeout(timer);
70
+ resolve3({ exitCode: timedOut ? null : code, timedOut, tail });
71
+ });
72
+ });
73
+ }
74
+ function npxScript(host) {
75
+ const path = host.platform === "win32" ? win32 : posix;
76
+ const npxCli = ["node_modules", "npm", "bin", "npx-cli.js"];
77
+ const candidates = [path.join(path.dirname(host.execPath), ...npxCli)];
78
+ if (host.env.APPDATA) candidates.push(path.join(host.env.APPDATA, "npm", ...npxCli));
79
+ return candidates.find((candidate) => host.exists(candidate));
80
+ }
81
+ function packageRunners(host, packageArgs) {
82
+ if (host.platform !== "win32") {
83
+ return [
84
+ { command: "bunx", args: packageArgs },
85
+ { command: "npx", args: ["--yes", ...packageArgs] }
86
+ ];
87
+ }
88
+ const npx = npxScript(host);
89
+ return [
90
+ { command: "bun.exe", args: ["x", ...packageArgs] },
91
+ ...npx ? [{ command: host.execPath, args: [npx, "--yes", ...packageArgs] }] : []
92
+ ];
93
+ }
94
+ function bunScript(host, script) {
95
+ return { command: host.platform === "win32" ? "bun.exe" : "bun", args: ["run", script] };
96
+ }
97
+ var SCAFFOLD_TIMEOUT_MS = 5 * 6e4;
98
+ async function runCreateApp(input) {
99
+ const cwd = dirname(input.root);
100
+ mkdirSync(cwd, { recursive: true });
101
+ const packageArgs = [`@teable/create-app@${input.version}`, input.root, "--app-id", input.appId];
102
+ let tried;
103
+ for (const program of packageRunners(currentHost(), packageArgs)) {
104
+ const command = [program.command, ...program.args].join(" ");
105
+ tried = { command, run: await runProgram(program, { cwd, timeoutMs: SCAFFOLD_TIMEOUT_MS }) };
106
+ if (!tried.run.missing) return tried;
107
+ }
108
+ return tried ?? { command: "npx", run: { exitCode: null, missing: true, tail: "" } };
109
+ }
110
+ var SCRIPT_TIMEOUT_MS = 15 * 6e4;
111
+ function runBunScript(root, script) {
112
+ return runProgram(bunScript(currentHost(), script), { cwd: root, timeoutMs: SCRIPT_TIMEOUT_MS });
113
+ }
114
+
115
+ // src/git.ts
116
+ var REMOTE = "teable";
117
+ var BRANCH = "main";
118
+ var SECRET_PATHSPECS = [".env*", "*/.env*", ".dev.vars*", "*/.dev.vars*"];
119
+ var EXCLUDE_SECRETS = SECRET_PATHSPECS.map((spec) => `:!${spec}`);
120
+ var GIT_TIMEOUT_MS = 5 * 6e4;
121
+ function gitEnv(auth) {
122
+ const { GIT_ASKPASS: _askpass, SSH_ASKPASS: _sshAskpass, ...env } = childEnv();
123
+ const config = [
124
+ ["credential.helper", ""],
125
+ ["core.askPass", ""]
126
+ ];
127
+ if (auth !== void 0) {
128
+ const header = `http.${new URL(auth.gitUrl).origin}/.extraHeader`;
129
+ config.push([header, `Authorization: Bearer ${auth.token}`]);
130
+ }
131
+ const count2 = Number.parseInt(env.GIT_CONFIG_COUNT ?? "", 10) || 0;
132
+ const added = config.flatMap(([key, value], i) => [
133
+ [`GIT_CONFIG_KEY_${count2 + i}`, key],
134
+ [`GIT_CONFIG_VALUE_${count2 + i}`, value]
135
+ ]);
136
+ return {
137
+ ...env,
138
+ ...Object.fromEntries(added),
139
+ GIT_CONFIG_COUNT: String(count2 + config.length),
140
+ GIT_TERMINAL_PROMPT: "0",
141
+ LC_ALL: "C"
142
+ };
143
+ }
144
+ function git(args, options) {
145
+ const env = gitEnv(options.auth);
146
+ return new Promise((resolve3, reject) => {
147
+ execFile(
148
+ "git",
149
+ args,
150
+ { cwd: options.cwd, env, timeout: GIT_TIMEOUT_MS, maxBuffer: 64 << 20 },
151
+ (error, stdout, stderr) => {
152
+ if (error === null) return resolve3({ stdout, stderr, code: 0 });
153
+ const { code } = error;
154
+ if (code === "ENOENT") {
155
+ return reject(
156
+ new CommandError("git is not installed, or not on PATH: install it first.")
157
+ );
158
+ }
159
+ if (options.allowFailure && typeof code === "number")
160
+ return resolve3({ stdout, stderr, code });
161
+ const said = `${stderr}`.trim() || error.message;
162
+ const shown = options.auth ? said.split(options.auth.token).join("<token>") : said;
163
+ reject(new CommandError(`git ${args[0]} failed: ${shown.slice(-800)}`));
164
+ }
165
+ );
166
+ });
167
+ }
168
+ async function head(root) {
169
+ const run = await git(["rev-parse", "--verify", "-q", "HEAD"], { cwd: root, allowFailure: true });
170
+ return run.code === 0 ? run.stdout.trim() : null;
171
+ }
172
+ async function remoteMain(auth, cwd) {
173
+ const { stdout } = await git(["ls-remote", "--heads", auth.gitUrl, `refs/heads/${BRANCH}`], {
174
+ cwd,
175
+ auth
176
+ });
177
+ return stdout.trim().split(/\s+/)[0] || null;
178
+ }
179
+ async function setRemote(root, gitUrl) {
180
+ const current = await git(["remote", "get-url", REMOTE], { cwd: root, allowFailure: true });
181
+ if (current.code !== 0) await git(["remote", "add", REMOTE, gitUrl], { cwd: root });
182
+ else if (current.stdout.trim() !== gitUrl) {
183
+ await git(["remote", "set-url", REMOTE, gitUrl], { cwd: root });
184
+ }
185
+ }
186
+ async function cloneRepository(root, auth, cwd) {
187
+ await git(["clone", "--origin", REMOTE, "--branch", BRANCH, auth.gitUrl, root], { cwd, auth });
188
+ return (await git(["rev-parse", "HEAD"], { cwd: root })).stdout.trim();
189
+ }
190
+ async function fetchMain(root, auth) {
191
+ const run = await git(["fetch", "-q", REMOTE, BRANCH], { cwd: root, auth, allowFailure: true });
192
+ if (run.code !== 0) {
193
+ if (/couldn't find remote ref/i.test(run.stderr)) return null;
194
+ throw new CommandError(`git fetch failed: ${run.stderr.trim().slice(-800)}`);
195
+ }
196
+ return (await git(["rev-parse", "FETCH_HEAD"], { cwd: root })).stdout.trim();
197
+ }
198
+ async function isAncestor(root, ancestor, of) {
199
+ const run = await git(["merge-base", "--is-ancestor", ancestor, of], {
200
+ cwd: root,
201
+ allowFailure: true
202
+ });
203
+ return run.code === 0;
204
+ }
205
+ async function fastForward(root, remoteHead) {
206
+ const local = await head(root);
207
+ if (local === remoteHead) return "up-to-date";
208
+ if (local !== null && await isAncestor(root, remoteHead, local)) return "ahead";
209
+ const merge = await git(["merge", "--ff-only", "-q", "FETCH_HEAD"], {
210
+ cwd: root,
211
+ allowFailure: true
212
+ });
213
+ if (merge.code === 0) return "fast-forward";
214
+ const dirty = await git(["status", "--porcelain", "--untracked-files=no"], { cwd: root });
215
+ if (dirty.stdout.trim()) {
216
+ throw new CommandError(
217
+ `The app repository moved to ${remoteHead.slice(0, 8)}, but this checkout has uncommitted changes the update would overwrite. Commit them (\`teable-next push -m "<what changed>"\`) or stash them, then \`teable-next pull\` again.`,
218
+ { git: "dirty" }
219
+ );
220
+ }
221
+ throw new CommandError(
222
+ `Local commits diverged from ${REMOTE}/${BRANCH} (${remoteHead.slice(0, 8)}). Run \`git rebase ${REMOTE}/${BRANCH}\`, resolve conflicts, then \`teable-next push\`. Commit or stash working tree changes first.`,
223
+ { git: "diverged" }
224
+ );
225
+ }
226
+ async function stageAllExcept(root, excluded) {
227
+ await git(["add", "-A", "--", "."], { cwd: root });
228
+ if (excluded.length > 0) await git(["reset", "-q", "--", ...excluded], { cwd: root });
229
+ }
230
+ async function hasChanges(root) {
231
+ const status = await git(["status", "--porcelain", "--", ".", ...EXCLUDE_SECRETS], { cwd: root });
232
+ return status.stdout.trim() !== "";
233
+ }
234
+ async function commitChanges(root, message) {
235
+ if (!await hasChanges(root)) return false;
236
+ if (message === void 0) {
237
+ throw new CommandError(
238
+ 'The working tree has uncommitted changes. Pass -m "<what changed>" to commit them, or commit them yourself first.'
239
+ );
240
+ }
241
+ await stageAllExcept(root, SECRET_PATHSPECS);
242
+ const staged = await git(["diff", "--cached", "--quiet"], { cwd: root, allowFailure: true });
243
+ if (staged.code === 0) return false;
244
+ await git(["commit", "-q", "-m", message], { cwd: root });
245
+ return true;
246
+ }
247
+ async function assertNoSecrets(root, base) {
248
+ const lines = (out) => out.split("\n").filter((line) => line.trim() !== "");
249
+ const tracked = lines((await git(["ls-files", "--", ...SECRET_PATHSPECS], { cwd: root })).stdout);
250
+ let range = "HEAD";
251
+ if (base !== null) {
252
+ const known = await git(["cat-file", "-e", `${base}^{commit}`], {
253
+ cwd: root,
254
+ allowFailure: true
255
+ });
256
+ if (known.code === 0) range = `${base}..HEAD`;
257
+ }
258
+ const touched = await git(["log", "--format=%H", range, "--", ...SECRET_PATHSPECS], {
259
+ cwd: root,
260
+ allowFailure: true
261
+ });
262
+ const commits = touched.code === 0 ? lines(touched.stdout) : [];
263
+ const files = SECRET_PATHSPECS.map((spec) => `'${spec}'`).join(" ");
264
+ const rewrite = `\`git reset --soft ${base ?? "<the commit before them>"}\`, then \`git rm -r --cached -- ${files}\`, and commit again`;
265
+ if (tracked.length > 0) {
266
+ throw new CommandError(
267
+ `Files that hold secrets are tracked by git: ${tracked.join(", ")}. Their values must stay out of the repository: remove them from the commits about to be pushed, not only from the index: ${rewrite}.`
268
+ );
269
+ }
270
+ const [first] = commits;
271
+ if (first !== void 0) {
272
+ throw new CommandError(
273
+ `${commits.length} commit(s) about to be pushed touch env files (for example ${first.slice(0, 8)}). Untracking is not enough: a push uploads every commit with its content. Rewrite them without those files: ${rewrite}.`
274
+ );
275
+ }
276
+ }
277
+ async function subjectOf(root, commit) {
278
+ return (await git(["log", "-1", "--format=%s", commit], { cwd: root })).stdout.trim();
279
+ }
280
+
281
+ // src/platform.ts
282
+ var TIMEOUT_MS = 6e4;
283
+ function parseJson(text2) {
284
+ try {
285
+ return text2 === "" ? void 0 : JSON.parse(text2);
286
+ } catch {
287
+ return void 0;
288
+ }
289
+ }
290
+ async function request(teable, method, path, body) {
291
+ const url = `${teable.endpoint}/api${path}`;
292
+ let response;
293
+ try {
294
+ response = await fetch(url, {
295
+ method,
296
+ headers: {
297
+ Authorization: `Bearer ${teable.token}`,
298
+ ...body !== void 0 && { "Content-Type": "application/json" }
299
+ },
300
+ ...body !== void 0 && { body: JSON.stringify(body) },
301
+ signal: AbortSignal.timeout(TIMEOUT_MS)
302
+ });
303
+ } catch (error) {
304
+ throw new CommandError(`Teable did not answer ${method} ${url}: ${messageOf(error)}`);
305
+ }
306
+ const text2 = await response.text();
307
+ const json = parseJson(text2);
308
+ if (!response.ok) {
309
+ const said = typeof json?.message === "string" && json.message ? json.message : text2.trim();
310
+ const why = said.slice(0, 500) || response.statusText;
311
+ if (response.status === 401) {
312
+ throw new CommandError(
313
+ `Teable at ${teable.endpoint} refused the token from ${teable.tokenFrom} (401: ${why}). Use a token of your own that is still valid: --token, TEABLE_TOKEN, or \`teable-next login --token <token>\`.`
314
+ );
315
+ }
316
+ throw new CommandError(`${method} ${url} answered ${response.status}: ${why}`);
317
+ }
318
+ if (typeof json !== "object" || json === null) {
319
+ throw new CommandError(`${method} ${url} answered what is not JSON: ${text2.slice(0, 300)}`);
320
+ }
321
+ return json;
322
+ }
323
+ function field(answer, name, what) {
324
+ const value = answer[name];
325
+ if (typeof value !== "string" || value === "") {
326
+ const has = Object.keys(answer).join(", ") || "nothing";
327
+ throw new CommandError(`Teable's answer for ${what} has no ${name} (it has ${has}).`);
328
+ }
329
+ return value;
330
+ }
331
+ var projectPath = (projectId) => `/base/${encodeURIComponent(projectId)}`;
332
+ async function currentUser(teable) {
333
+ const user = await request(teable, "GET", "/auth/user");
334
+ return {
335
+ id: field(user, "id", "the user"),
336
+ name: typeof user.name === "string" ? user.name : null,
337
+ ...typeof user.email === "string" && { email: user.email }
338
+ };
339
+ }
340
+ async function teableNextProject(teable, projectId) {
341
+ const project = await request(teable, "GET", projectPath(projectId));
342
+ const name = typeof project.name === "string" ? project.name : "";
343
+ if (project.runtime !== "next") {
344
+ throw new CommandError(
345
+ `Project ${projectId}${name ? ` ("${name}")` : ""} does not run in teable-next, so it has no app of its own: it is a classic Teable project, and its apps are App Builder apps, which the \`teable\` CLI works on (\`teable app --help\`).`
346
+ );
347
+ }
348
+ return { id: projectId, name };
349
+ }
350
+ async function identityToken(teable, projectId) {
351
+ const answer = await request(teable, "POST", `${projectPath(projectId)}/teable-next/identity`, {
352
+ delivery: "token"
353
+ });
354
+ return field(answer, "token", "an identity");
355
+ }
356
+ async function gitCredentials(teable, projectId, ops) {
357
+ const path = `${projectPath(projectId)}/teable-next/git/credentials`;
358
+ const answer = await request(teable, "POST", path, { ops });
359
+ return {
360
+ gitUrl: field(answer, "gitUrl", "repository credentials"),
361
+ token: field(answer, "token", "repository credentials")
362
+ };
363
+ }
364
+
365
+ // src/checkout.ts
366
+ var APP_FILE = "teable.json";
367
+ function appIdIn(dir) {
368
+ let text2;
369
+ try {
370
+ text2 = readFileSync(join(dir, APP_FILE), "utf8");
371
+ } catch {
372
+ return void 0;
373
+ }
374
+ let config;
375
+ try {
376
+ config = JSON.parse(text2);
377
+ } catch {
378
+ throw new CommandError(`${join(dir, APP_FILE)} is not JSON: restore it from git.`);
379
+ }
380
+ return typeof config?.appId === "string" && config.appId.trim() !== "" ? config.appId.trim() : void 0;
381
+ }
382
+ function isEmptyOrMissing(dir) {
383
+ if (!existsSync2(dir)) return true;
384
+ return statSync(dir).isDirectory() && readdirSync(dir).length === 0;
385
+ }
386
+ function findApp(cwd) {
387
+ let dir = resolve(cwd);
388
+ while (!existsSync2(join(dir, APP_FILE))) {
389
+ const parent = dirname2(dir);
390
+ if (parent === dir) {
391
+ throw new CommandError(
392
+ `No ${APP_FILE} in ${resolve(cwd)} or above: run this in an app's checkout (\`teable-next clone <projectId>\` makes one).`
393
+ );
394
+ }
395
+ dir = parent;
396
+ }
397
+ const appId = appIdIn(dir);
398
+ if (appId === void 0) {
399
+ throw new CommandError(
400
+ `${join(dir, APP_FILE)} names no app: give it the project's id, as {"appId": "bse\u2026"}.`
401
+ );
402
+ }
403
+ return { root: dir, appId };
404
+ }
405
+ async function openCheckout(cwd) {
406
+ const { root: dir, appId } = findApp(cwd);
407
+ const top = await git(["rev-parse", "--show-toplevel"], { cwd: dir, allowFailure: true });
408
+ if (top.code !== 0 || realpathSync(top.stdout.trim()) !== realpathSync(dir)) {
409
+ throw new CommandError(
410
+ top.code !== 0 ? `${dir} is not a git repository: clone the app with \`teable-next clone ${appId}\`.` : `${dir} is inside the git repository at ${top.stdout.trim()}: an app is a repository of its own (\`teable-next clone ${appId}\`).`,
411
+ { appId, dir }
412
+ );
413
+ }
414
+ return { root: dir, appId };
415
+ }
416
+ async function checkoutCredentials(root, appId, teable, ops) {
417
+ const credentials = await gitCredentials(teable, appId, ops);
418
+ await setRemote(root, credentials.gitUrl);
419
+ return credentials;
420
+ }
421
+
422
+ // src/config.ts
423
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "node:fs";
424
+ import { homedir } from "node:os";
425
+ import { dirname as dirname3, join as join2 } from "node:path";
426
+ var DEFAULT_ENDPOINT = "https://app.teable.ai";
427
+ function loginPath() {
428
+ const { XDG_CONFIG_HOME, APPDATA } = process.env;
429
+ let base = XDG_CONFIG_HOME || process.platform === "win32" && APPDATA || void 0;
430
+ if (base === void 0) {
431
+ try {
432
+ base = join2(homedir(), ".config");
433
+ } catch {
434
+ throw new CommandError("No home directory to keep a login in: set HOME or XDG_CONFIG_HOME.");
435
+ }
436
+ }
437
+ return join2(base, "teable-next", "config.json");
438
+ }
439
+ function fromEnv(name) {
440
+ return process.env[name]?.trim() || void 0;
441
+ }
442
+ function endpointOf(value, source) {
443
+ let url;
444
+ try {
445
+ url = new URL(value.trim());
446
+ } catch {
447
+ url = void 0;
448
+ }
449
+ if (url === void 0 || url.protocol !== "https:" && url.protocol !== "http:") {
450
+ throw new CommandError(`${source} is not an http(s) URL: ${value}`);
451
+ }
452
+ return `${url.origin}${url.pathname}`.replace(/\/+$/, "");
453
+ }
454
+ function readLogin() {
455
+ let path;
456
+ try {
457
+ path = loginPath();
458
+ } catch {
459
+ return void 0;
460
+ }
461
+ let text2;
462
+ try {
463
+ text2 = readFileSync2(path, "utf8");
464
+ } catch (error) {
465
+ if (error.code === "ENOENT") return void 0;
466
+ throw new CommandError(`Cannot read the saved login at ${path}: ${messageOf(error)}`);
467
+ }
468
+ let saved;
469
+ try {
470
+ saved = JSON.parse(text2);
471
+ } catch {
472
+ saved = void 0;
473
+ }
474
+ if (typeof saved?.endpoint !== "string" || typeof saved.token !== "string") {
475
+ throw new CommandError(
476
+ `${path} is not a login teable-next saved: run \`teable-next login --token <token>\` again, or delete it.`
477
+ );
478
+ }
479
+ return { endpoint: endpointOf(saved.endpoint, `The login saved in ${path}`), token: saved.token };
480
+ }
481
+ function namedEndpoint(flags) {
482
+ if (flags.endpoint !== void 0) return endpointOf(flags.endpoint, "--endpoint");
483
+ const env = fromEnv("TEABLE_ENDPOINT");
484
+ return env === void 0 ? void 0 : endpointOf(env, "TEABLE_ENDPOINT");
485
+ }
486
+ function nextEndpointOf(endpoint) {
487
+ const env = fromEnv("TEABLE_NEXT_ENDPOINT");
488
+ return env === void 0 ? endpoint : endpointOf(env, "TEABLE_NEXT_ENDPOINT");
489
+ }
490
+ function resolveTeable(flags) {
491
+ const named = namedEndpoint(flags);
492
+ const given = flags.token ?? fromEnv("TEABLE_TOKEN");
493
+ const login = named === void 0 || given === void 0 ? readLogin() : void 0;
494
+ const endpoint = named ?? login?.endpoint ?? DEFAULT_ENDPOINT;
495
+ const nextEndpoint = nextEndpointOf(endpoint);
496
+ if (flags.token !== void 0) {
497
+ return { endpoint, nextEndpoint, token: flags.token, tokenFrom: "--token" };
498
+ }
499
+ if (given !== void 0)
500
+ return { endpoint, nextEndpoint, token: given, tokenFrom: "TEABLE_TOKEN" };
501
+ if (login !== void 0 && login.endpoint === endpoint) {
502
+ return { endpoint, nextEndpoint, token: login.token, tokenFrom: "teable-next login" };
503
+ }
504
+ throw new CommandError(
505
+ login === void 0 ? "No token: pass --token <token>, set TEABLE_TOKEN, or save one with `teable-next login --token <token>`. Use a personal access token (Teable: Settings, Personal access tokens) that can read and update the project." : `The saved login is for ${login.endpoint}, not ${endpoint}: pass --token <token>, set TEABLE_TOKEN, or \`teable-next login --endpoint ${endpoint} --token <token>\`.`
506
+ );
507
+ }
508
+ function loginTeable(flags) {
509
+ const endpoint = namedEndpoint(flags) ?? DEFAULT_ENDPOINT;
510
+ return {
511
+ endpoint,
512
+ nextEndpoint: nextEndpointOf(endpoint),
513
+ token: flags.token,
514
+ tokenFrom: "--token"
515
+ };
516
+ }
517
+ function saveLogin(login) {
518
+ const path = loginPath();
519
+ mkdirSync2(dirname3(path), { recursive: true, mode: 448 });
520
+ const fresh = `${path}.${process.pid}.tmp`;
521
+ rmSync(fresh, { force: true });
522
+ writeFileSync(fresh, `${JSON.stringify(login, null, 2)}
523
+ `, { mode: 384, flag: "wx" });
524
+ renameSync(fresh, path);
525
+ return path;
526
+ }
527
+
528
+ // src/publish.ts
529
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
530
+ import { join as join3 } from "node:path";
531
+
532
+ // ../app/src/protocol.ts
533
+ var EVERY_CAPABILITY = { files: true, http: true };
534
+ var CAPABILITIES = Object.keys(EVERY_CAPABILITY);
535
+ var APPS_PATH = "/api/v4/apps";
536
+ var DEPLOY_HEADERS = { commit: "X-Teable-Commit", message: "X-Teable-Message" };
537
+
538
+ // src/runtime.ts
539
+ var DEPLOY_TIMEOUT_MS = 10 * 6e4;
540
+ var TIMEOUT_MS2 = 6e4;
541
+ var BUILDER_PATH = "/apps";
542
+ function appUrls(teable, appId) {
543
+ const id = encodeURIComponent(appId);
544
+ const api = `${teable.nextEndpoint}${APPS_PATH}/${id}`;
545
+ return {
546
+ builder: `${teable.nextEndpoint}${BUILDER_PATH}/${id}`,
547
+ api,
548
+ openapi: `${api}/openapi.json`,
549
+ mcp: `${api}/mcp`
550
+ };
551
+ }
552
+ async function callRuntime(teable, appId, path, init2) {
553
+ const identity = await identityToken(teable, appId);
554
+ const url = `${appUrls(teable, appId).api}${path}`;
555
+ let response;
556
+ try {
557
+ response = await fetch(url, {
558
+ method: init2.method,
559
+ headers: { Authorization: `Bearer ${identity}`, ...init2.headers },
560
+ ...init2.body !== void 0 && { body: init2.body },
561
+ signal: AbortSignal.timeout(init2.timeoutMs ?? TIMEOUT_MS2)
562
+ });
563
+ } catch (error) {
564
+ throw new CommandError(`The runtime did not answer ${init2.method} ${url}: ${messageOf(error)}`);
565
+ }
566
+ const text2 = await response.text();
567
+ let body;
568
+ try {
569
+ body = text2 === "" ? void 0 : JSON.parse(text2);
570
+ } catch {
571
+ body = void 0;
572
+ }
573
+ if (!response.ok) {
574
+ const error = body?.error;
575
+ const code = typeof error?.code === "string" ? error.code : `HTTP ${response.status}`;
576
+ const message = typeof error?.message === "string" ? error.message : text2.trim().slice(0, 300);
577
+ throw new CommandError(`${code}: ${message || "the runtime refused the request"}`, {
578
+ status: response.status
579
+ });
580
+ }
581
+ if (body === void 0) {
582
+ throw new CommandError(
583
+ `${init2.method} ${url} answered what is not JSON: ${text2.slice(0, 300)}`
584
+ );
585
+ }
586
+ return body;
587
+ }
588
+ function versionIn(answer, field2) {
589
+ const value = answer?.[field2];
590
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
591
+ throw new CommandError(
592
+ `The runtime's answer has no ${field2}: ${JSON.stringify(answer).slice(0, 300)}`
593
+ );
594
+ }
595
+ return value;
596
+ }
597
+ function summary(manifest) {
598
+ if (manifest === void 0 || !Array.isArray(manifest.methods)) return void 0;
599
+ return {
600
+ protocol: manifest.protocol,
601
+ methods: manifest.methods.map(({ name, kind, access }) => ({ name, kind, access })),
602
+ tables: (manifest.tables ?? []).map((table) => table.name),
603
+ ...manifest.capabilities?.length ? { capabilities: manifest.capabilities } : {}
604
+ };
605
+ }
606
+ async function deploy(teable, appId, bundle, built) {
607
+ const answer = await callRuntime(teable, appId, "/versions", {
608
+ method: "POST",
609
+ headers: {
610
+ "Content-Type": "application/javascript",
611
+ [DEPLOY_HEADERS.commit]: built.commit,
612
+ [DEPLOY_HEADERS.message]: encodeURIComponent(built.message)
613
+ },
614
+ body: bundle,
615
+ timeoutMs: DEPLOY_TIMEOUT_MS
616
+ });
617
+ return { version: versionIn(answer, "version"), manifest: summary(answer.manifest) };
618
+ }
619
+ async function listVersions(teable, appId) {
620
+ const answer = await callRuntime(teable, appId, "/versions", { method: "GET" });
621
+ if (!Array.isArray(answer)) {
622
+ throw new CommandError(
623
+ `The runtime listed no versions: ${JSON.stringify(answer).slice(0, 300)}`
624
+ );
625
+ }
626
+ return answer.sort((a, b) => b.version - a.version);
627
+ }
628
+ async function rollback(teable, appId, to) {
629
+ const answer = await callRuntime(teable, appId, "/rollback", {
630
+ method: "POST",
631
+ headers: { "Content-Type": "application/json" },
632
+ body: JSON.stringify({ to }),
633
+ timeoutMs: DEPLOY_TIMEOUT_MS
634
+ });
635
+ return {
636
+ version: versionIn(answer, "version"),
637
+ from: versionIn(answer, "from"),
638
+ manifest: summary(answer.manifest)
639
+ };
640
+ }
641
+
642
+ // src/publish.ts
643
+ var SERVER_BUNDLE = "dist/server.js";
644
+ var MESSAGE_MAX_CHARS = 500;
645
+ async function unpushedReason(root, local, remote) {
646
+ if (remote === null) return "Nothing is pushed yet: run `teable-next push`, then publish.";
647
+ if (await isAncestor(root, remote, local)) {
648
+ return `Commit ${local.slice(0, 8)} is not pushed yet: run \`teable-next push\`, then publish.`;
649
+ }
650
+ if (await isAncestor(root, local, remote)) {
651
+ return `The app repository moved ahead to ${remote.slice(0, 8)}: run \`teable-next pull\`, then publish.`;
652
+ }
653
+ return `This checkout diverged from the app repository (${remote.slice(0, 8)}): run \`teable-next pull\`, rebase, push, then publish.`;
654
+ }
655
+ async function checkAndBuild(root, stop) {
656
+ if (!existsSync3(join3(root, "node_modules"))) {
657
+ throw new CommandError(
658
+ `No node_modules in ${root}: run \`bun install\`, then publish.`,
659
+ stop({ step: "check" })
660
+ );
661
+ }
662
+ for (const script of ["check", "build"]) {
663
+ const run = await runBunScript(root, script);
664
+ if (run.missing) {
665
+ throw new CommandError(
666
+ "Bun is not installed: install it (https://bun.sh), then publish.",
667
+ stop({ step: script })
668
+ );
669
+ }
670
+ if (run.exitCode !== 0) {
671
+ const why = run.timedOut ? "timed out" : `exited with ${run.exitCode}`;
672
+ throw new CommandError(
673
+ `\`bun run ${script}\` ${why}; nothing was deployed. Fix it, commit and push, then publish again.`,
674
+ stop({ step: script, output: run.tail.trim().slice(-2e3) })
675
+ );
676
+ }
677
+ }
678
+ const bundle = existsSync3(join3(root, SERVER_BUNDLE)) ? readFileSync3(join3(root, SERVER_BUNDLE), "utf8") : "";
679
+ if (bundle.trim() === "") {
680
+ throw new CommandError(`\`bun run build\` wrote no ${SERVER_BUNDLE}.`, stop({ step: "build" }));
681
+ }
682
+ return bundle;
683
+ }
684
+ async function publish(teable, cwd) {
685
+ const { root, appId } = await openCheckout(cwd);
686
+ const stop = (details) => ({ appId, dir: root, ...details });
687
+ if (await hasChanges(root)) {
688
+ throw new CommandError(
689
+ 'This checkout has uncommitted changes, and publish deploys only what is pushed. Commit and push them first: `teable-next push -m "<what changed>"`.',
690
+ stop({ step: "git" })
691
+ );
692
+ }
693
+ const commit = await head(root);
694
+ if (commit === null) {
695
+ throw new CommandError(
696
+ "Nothing is committed yet: commit and push your work, then publish.",
697
+ stop({ step: "git" })
698
+ );
699
+ }
700
+ const remote = await fetchMain(root, await checkoutCredentials(root, appId, teable, "fetch"));
701
+ if (remote !== commit) {
702
+ throw new CommandError(await unpushedReason(root, commit, remote), stop({ step: "git" }));
703
+ }
704
+ const bundle = await checkAndBuild(root, stop);
705
+ const subject = (await subjectOf(root, commit)).slice(0, MESSAGE_MAX_CHARS);
706
+ let deployed;
707
+ try {
708
+ deployed = await deploy(teable, appId, bundle, { commit, message: subject });
709
+ } catch (error) {
710
+ if (error instanceof CommandError) {
711
+ throw new CommandError(
712
+ `Nothing was deployed: ${error.message}`,
713
+ stop({ step: "deploy", ...error.details })
714
+ );
715
+ }
716
+ throw error;
717
+ }
718
+ return {
719
+ success: true,
720
+ appId,
721
+ dir: root,
722
+ version: deployed.version,
723
+ commitSha: commit,
724
+ commitMessage: subject,
725
+ urls: appUrls(teable, appId),
726
+ ...deployed.manifest && { deployed: deployed.manifest },
727
+ message: `Version ${deployed.version} of ${appId} is live, built from ${commit.slice(0, 8)} ("${subject}").`
728
+ };
729
+ }
730
+ async function versions(teable, appId, limit) {
731
+ const all = await listVersions(teable, appId);
732
+ return {
733
+ success: true,
734
+ appId,
735
+ total: all.length,
736
+ live: all.find((version2) => version2.live)?.version ?? null,
737
+ versions: all.slice(0, limit).map((version2) => ({
738
+ ...version2,
739
+ createdAt: typeof version2.createdAt === "number" ? new Date(version2.createdAt).toISOString() : version2.createdAt
740
+ }))
741
+ };
742
+ }
743
+ async function rollBack(teable, appId, to) {
744
+ const rolledBack = await rollback(teable, appId, to);
745
+ return {
746
+ success: true,
747
+ appId,
748
+ version: rolledBack.version,
749
+ rolledBackFrom: rolledBack.from,
750
+ urls: appUrls(teable, appId),
751
+ message: `Version ${to}'s code is live again, as version ${rolledBack.version} (version ${rolledBack.from} was live). The app repository is unchanged: its main branch still holds what was pushed last, which the next \`teable-next publish\` deploys, so fix or revert it there first.`
752
+ };
753
+ }
754
+
755
+ // src/repository.ts
756
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, statSync as statSync2 } from "node:fs";
757
+ import { dirname as dirname4, join as join4, relative, resolve as resolve2 } from "node:path";
758
+ var DEFAULT_CREATE_APP_VERSION = "latest";
759
+ function shellPath(path) {
760
+ const where = relative(process.cwd(), path) || ".";
761
+ return /^[\w@%+=:,./-]+$/.test(where) ? where : `'${where.replaceAll("'", "'\\''")}'`;
762
+ }
763
+ function workflow(root, pull2) {
764
+ return [
765
+ `cd ${shellPath(root)}`,
766
+ "Read AGENTS.md (CLAUDE.md points to it): how this app is built, checked and tested.",
767
+ "bun install",
768
+ ...pull2 ? ["teable-next pull # before each session, in case someone else pushed"] : [],
769
+ "bun run check # before every push",
770
+ 'teable-next push -m "<what changed>" # commit, and save it to the app repository',
771
+ "teable-next publish # check, build and deploy what you pushed: publish each change once it is ready"
772
+ ];
773
+ }
774
+ function directoryFor(name, projectId) {
775
+ const slug = name.trim().replace(/[\\/:*?"<>|\s]+/g, "-").replace(/^[-.]+|-+$/g, "").toLowerCase();
776
+ return slug || projectId;
777
+ }
778
+ var NO_GIT_IDENTITY = /Please tell me who you are|empty ident|unable to auto-detect email|no email was given/i;
779
+ async function commitScaffold(root, version2) {
780
+ if (!existsSync4(join4(root, ".git"))) await git(["init", "-q"], { cwd: root });
781
+ const existing = await head(root);
782
+ if (existing !== null) {
783
+ await git(["branch", "-M", BRANCH], { cwd: root });
784
+ return existing;
785
+ }
786
+ await git(["symbolic-ref", "HEAD", `refs/heads/${BRANCH}`], { cwd: root });
787
+ await stageAllExcept(root, SECRET_PATHSPECS);
788
+ const message = `Create the app with @teable/create-app@${version2}`;
789
+ const commit = await git(["commit", "-q", "-m", message], { cwd: root, allowFailure: true });
790
+ if (commit.code !== 0) {
791
+ const said = `${commit.stderr}${commit.stdout}`.trim();
792
+ throw new CommandError(
793
+ NO_GIT_IDENTITY.test(said) ? `git has no identity to commit with here. Set one (\`git config --global user.name "<name>"\` and \`git config --global user.email "<email>"\`, or GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, GIT_COMMITTER_NAME and GIT_COMMITTER_EMAIL), then run the same \`teable-next init\` again: it goes on with the app already in ${root}.` : `git commit failed: ${said.slice(-800)}`,
794
+ { dir: root }
795
+ );
796
+ }
797
+ const made = await head(root);
798
+ if (made === null)
799
+ throw new CommandError(`@teable/create-app wrote nothing to commit in ${root}.`);
800
+ return made;
801
+ }
802
+ async function scaffold(root, appId, version2) {
803
+ const { command, run } = await runCreateApp({ root, appId, version: version2 });
804
+ if (run.missing) {
805
+ throw new CommandError(
806
+ "Neither bunx (Bun) nor npx (npm) is on PATH: install Bun (https://bun.sh), or Node.js with npm, then run `teable-next init` again."
807
+ );
808
+ }
809
+ if (run.exitCode !== 0) {
810
+ const why = run.timedOut ? "timed out" : `exited with ${run.exitCode}`;
811
+ throw new CommandError(`\`${command}\` ${why}: ${run.tail.trim().slice(-1500)}`, { dir: root });
812
+ }
813
+ if (appIdIn(root) !== appId) {
814
+ throw new CommandError(
815
+ `@teable/create-app@${version2} wrote no ${APP_FILE} naming ${appId} in ${root}.`,
816
+ { dir: root }
817
+ );
818
+ }
819
+ }
820
+ async function init(teable, input) {
821
+ const project = await teableNextProject(teable, input.projectId);
822
+ const appId = project.id;
823
+ const root = resolve2(input.dir);
824
+ const version2 = input.createAppVersion;
825
+ if (existsSync4(root) && !statSync2(root).isDirectory()) {
826
+ throw new CommandError(`${root} is a file: name an empty or new directory.`);
827
+ }
828
+ const earlier = appIdIn(root);
829
+ if (earlier !== void 0 && earlier !== appId) {
830
+ throw new CommandError(
831
+ `${root} holds another app (${earlier}): name an empty or new directory.`
832
+ );
833
+ }
834
+ if (earlier === void 0 && !isEmptyOrMissing(root)) {
835
+ throw new CommandError(`${root} is not empty: name an empty or new directory.`);
836
+ }
837
+ const credentials = await gitCredentials(teable, appId, "push");
838
+ mkdirSync3(dirname4(root), { recursive: true });
839
+ const remoteHead = await remoteMain(credentials, dirname4(root));
840
+ const resuming = earlier !== void 0 && existsSync4(join4(root, ".git"));
841
+ const localHead = resuming ? await head(root) : null;
842
+ if (remoteHead !== null && remoteHead !== localHead) {
843
+ throw new CommandError(
844
+ `The project already has code in its repository (${remoteHead.slice(0, 8)}). Clone it instead: \`teable-next clone ${appId}\`.`
845
+ );
846
+ }
847
+ if (earlier === void 0) await scaffold(root, appId, version2);
848
+ const commitSha = await commitScaffold(root, version2);
849
+ await setRemote(root, credentials.gitUrl);
850
+ if (remoteHead !== commitSha) {
851
+ await git(["push", "-q", "-u", REMOTE, `HEAD:refs/heads/${BRANCH}`], {
852
+ cwd: root,
853
+ auth: credentials
854
+ });
855
+ }
856
+ return {
857
+ success: true,
858
+ appId,
859
+ appName: project.name,
860
+ dir: root,
861
+ commitSha,
862
+ createApp: `@teable/create-app@${version2}`,
863
+ nextSteps: workflow(root, false),
864
+ message: `Created app ${appId} with @teable/create-app@${version2}, pushed it to the project's repository and checked it out at ${root}. Nothing is deployed yet: \`teable-next publish\` deploys it.`
865
+ };
866
+ }
867
+ async function clone(teable, input) {
868
+ const project = await teableNextProject(teable, input.projectId);
869
+ const appId = project.id;
870
+ const root = resolve2(input.dir ?? directoryFor(project.name, appId));
871
+ if (!isEmptyOrMissing(root)) {
872
+ throw new CommandError(
873
+ `${root} is not empty: name an empty or new directory (\`teable-next clone ${appId} <dir>\`).`
874
+ );
875
+ }
876
+ const credentials = await gitCredentials(teable, appId, "fetch");
877
+ mkdirSync3(dirname4(root), { recursive: true });
878
+ let commitSha;
879
+ try {
880
+ commitSha = await cloneRepository(root, credentials, dirname4(root));
881
+ } catch (error) {
882
+ if (/Remote branch \S+ not found|empty repository/i.test(messageOf(error))) {
883
+ throw new CommandError(
884
+ `The project has no code yet. Start it with \`teable-next init <dir> --project ${appId}\`.`
885
+ );
886
+ }
887
+ throw error;
888
+ }
889
+ const named = appIdIn(root);
890
+ if (named !== appId) {
891
+ throw new CommandError(
892
+ `The repository cloned into ${root} is not this project's app: its ${APP_FILE} ${named === void 0 ? "names no app" : `names ${named}`}.`,
893
+ { dir: root }
894
+ );
895
+ }
896
+ return {
897
+ success: true,
898
+ appId,
899
+ appName: project.name,
900
+ dir: root,
901
+ commitSha,
902
+ nextSteps: workflow(root, true),
903
+ message: `Cloned app ${appId} into ${root} (${commitSha.slice(0, 8)}).`
904
+ };
905
+ }
906
+ async function pull(teable, cwd) {
907
+ const { root, appId } = await openCheckout(cwd);
908
+ const credentials = await checkoutCredentials(root, appId, teable, "fetch");
909
+ const remoteHead = await fetchMain(root, credentials);
910
+ if (remoteHead === null) {
911
+ return {
912
+ success: true,
913
+ appId,
914
+ dir: root,
915
+ commitSha: await head(root),
916
+ git: "empty-remote",
917
+ message: "The app repository is empty: `teable-next push` saves your commits there."
918
+ };
919
+ }
920
+ let state;
921
+ try {
922
+ state = await fastForward(root, remoteHead);
923
+ } catch (error) {
924
+ if (error instanceof CommandError) Object.assign(error.details, { appId, dir: root });
925
+ throw error;
926
+ }
927
+ const messages = {
928
+ "fast-forward": `Fast-forwarded to the app repository's ${remoteHead.slice(0, 8)}.`,
929
+ "up-to-date": `Already up to date with the app repository (${remoteHead.slice(0, 8)}).`,
930
+ ahead: `This checkout has commits the app repository (${remoteHead.slice(0, 8)}) lacks: \`teable-next push\` saves them.`
931
+ };
932
+ return {
933
+ success: true,
934
+ appId,
935
+ dir: root,
936
+ commitSha: await head(root),
937
+ git: state,
938
+ message: messages[state]
939
+ };
940
+ }
941
+ async function push(teable, cwd, message) {
942
+ const { root, appId } = await openCheckout(cwd);
943
+ await commitChanges(root, message);
944
+ const commitSha = await head(root);
945
+ if (commitSha === null) {
946
+ throw new CommandError(
947
+ 'Nothing is committed yet: pass -m "<what changed>" to commit, then push.'
948
+ );
949
+ }
950
+ const credentials = await checkoutCredentials(root, appId, teable, "push");
951
+ const remoteHead = await fetchMain(root, credentials);
952
+ await assertNoSecrets(root, remoteHead);
953
+ if (remoteHead !== null && remoteHead !== commitSha && !await isAncestor(root, remoteHead, commitSha)) {
954
+ throw new CommandError(
955
+ `The app repository moved to ${remoteHead.slice(0, 8)} since your last pull. Run \`teable-next pull\` (or \`git rebase ${REMOTE}/${BRANCH}\` if your commits diverged), then push again.`,
956
+ { appId, dir: root }
957
+ );
958
+ }
959
+ let pushedCommits = 0;
960
+ if (remoteHead !== commitSha) {
961
+ await git(["push", "-q", REMOTE, `HEAD:refs/heads/${BRANCH}`], {
962
+ cwd: root,
963
+ auth: credentials
964
+ });
965
+ const range = remoteHead === null ? commitSha : `${remoteHead}..${commitSha}`;
966
+ pushedCommits = Number(
967
+ (await git(["rev-list", "--count", range], { cwd: root })).stdout.trim()
968
+ );
969
+ }
970
+ return {
971
+ success: true,
972
+ appId,
973
+ dir: root,
974
+ commitSha,
975
+ pushedCommits,
976
+ message: pushedCommits > 0 ? `Pushed ${pushedCommits} commit(s); the app repository is at ${commitSha.slice(0, 8)}. Deploy it with \`teable-next publish\`.` : `Nothing new to push: the app repository already holds ${commitSha.slice(0, 8)}. Deploy it with \`teable-next publish\`.`
977
+ };
978
+ }
979
+
980
+ // src/cli.ts
981
+ var COMMON = {
982
+ token: { type: "string" },
983
+ endpoint: { type: "string" },
984
+ help: { type: "boolean", short: "h" }
985
+ };
986
+ var COMMON_HELP = [
987
+ " --token <token> Your Teable token: default TEABLE_TOKEN, then the saved login",
988
+ " --endpoint <url> Teable: default TEABLE_ENDPOINT, then the saved login's, then https://app.teable.ai",
989
+ " -h, --help Help: for a command too, teable-next <command> --help"
990
+ ];
991
+ var PROJECT_OPTION = " --project <projectId> The project (bseXXX) outside a checkout";
992
+ var text = (value) => typeof value === "string" ? value : void 0;
993
+ var teableOf = (values) => resolveTeable({ token: text(values.token), endpoint: text(values.endpoint) });
994
+ function count(value, name) {
995
+ if (value === void 0) return void 0;
996
+ const n = typeof value === "string" && /^\d+$/.test(value) ? Number(value) : 0;
997
+ if (!Number.isSafeInteger(n) || n < 1) {
998
+ throw new CommandError(`--${name} takes a whole number from 1 up, not "${value}".`);
999
+ }
1000
+ return n;
1001
+ }
1002
+ async function appOf(teable, values) {
1003
+ const project = text(values.project);
1004
+ if (project !== void 0) return (await teableNextProject(teable, project)).id;
1005
+ return findApp(process.cwd()).appId;
1006
+ }
1007
+ var COMMANDS = {
1008
+ init: {
1009
+ usage: "init <dir> --project <projectId> [--create-app-version <version>]",
1010
+ summary: "Write a new app into <dir> and push it to the project's repository",
1011
+ details: `The project is the app: its id is the project's, and its code a repository in Teable's git
1012
+ registry, empty until this pushes to it.
1013
+ 1. Writes a blank app into <dir> with @teable/create-app (bunx, or npx without Bun).
1014
+ 2. Commits it on main and pushes it to the project's repository (git remote \`teable\`).
1015
+ The app brings its own AGENTS.md (CLAUDE.md points to it). Then: cd <dir>, read it, \`bun install\`,
1016
+ work, \`teable-next push -m "<what changed>"\`, \`teable-next publish\`.
1017
+ <dir> must be absent or empty. After a failure (git has no identity, say), run the same command again:
1018
+ it goes on from the scaffold. A project whose repository has code is cloned instead.`,
1019
+ options: { project: { type: "string" }, "create-app-version": { type: "string" } },
1020
+ optionHelp: [
1021
+ " --project <projectId> The project the app is (bseXXX); it must run in teable-next",
1022
+ ` --create-app-version <version> The @teable/create-app to start from: default TEABLE_CREATE_APP_VERSION, then ${DEFAULT_CREATE_APP_VERSION}`
1023
+ ],
1024
+ takes: [1, 1],
1025
+ run: (values, [dir = ""]) => {
1026
+ const projectId = text(values.project);
1027
+ if (projectId === void 0) {
1028
+ throw new CommandError("init needs --project <projectId>: the project the app is.");
1029
+ }
1030
+ const createAppVersion = text(values["create-app-version"]) ?? (process.env.TEABLE_CREATE_APP_VERSION?.trim() || DEFAULT_CREATE_APP_VERSION);
1031
+ return init(teableOf(values), { dir, projectId, createAppVersion });
1032
+ }
1033
+ },
1034
+ clone: {
1035
+ usage: "clone <projectId> [dir]",
1036
+ summary: "Check out the project's app",
1037
+ details: `Clones the project's repository into [dir] (default: a new directory named after the project),
1038
+ its remote named \`teable\`. The repository is the whole app.`,
1039
+ options: {},
1040
+ optionHelp: [],
1041
+ takes: [1, 2],
1042
+ run: (values, [projectId = "", dir]) => clone(teableOf(values), { projectId, dir })
1043
+ },
1044
+ pull: {
1045
+ usage: "pull",
1046
+ summary: "Fast-forward the checkout to the app repository",
1047
+ details: `In a checkout: fetches the app repository's main and fast-forwards to it. Commit or stash first
1048
+ when the update would overwrite your changes, and rebase when your commits diverged.`,
1049
+ options: {},
1050
+ optionHelp: [],
1051
+ takes: [0, 0],
1052
+ run: (values) => pull(teableOf(values), process.cwd())
1053
+ },
1054
+ push: {
1055
+ usage: 'push [-m "<what changed>"]',
1056
+ summary: "Commit (with -m) and push to the app repository; deploys nothing",
1057
+ details: `In a checkout: commits the working tree with the message (needed when it has changes), then
1058
+ pushes to the app repository's main. Refuses env files (.env*, .dev.vars) in what goes out, and work
1059
+ pushed since your last pull. Nothing is deployed: \`teable-next publish\` deploys what you pushed.`,
1060
+ options: { message: { type: "string", short: "m" } },
1061
+ optionHelp: [" -m, --message <message> The commit's subject: what changed"],
1062
+ takes: [0, 0],
1063
+ run: (values) => push(teableOf(values), process.cwd(), text(values.message))
1064
+ },
1065
+ publish: {
1066
+ usage: "publish",
1067
+ summary: "Check, build and deploy what you pushed, as the app's next version",
1068
+ details: `In a checkout: deploys the pushed commit as the app's next version, as you.
1069
+ 1. The checkout must be clean, its HEAD pushed to the app repository's main (\`teable-next push\`).
1070
+ 2. Runs \`bun run check\`, then \`bun run build\`; their output goes to stderr.
1071
+ 3. Uploads dist/server.js to the runtime with the commit's id and subject. The runtime runs the
1072
+ version's migrations on a copy of the live data, then on the live data, and makes it live only
1073
+ if both work.
1074
+ Prints the version and the app's URLs (builder, API, OpenAPI, MCP). Publish each change once it is
1075
+ checked: no approval is needed. Publishing takes the creator or owner role in the project's space.
1076
+ TEABLE_NEXT_ENDPOINT points it at another runtime (a local one); by default the runtime is under
1077
+ Teable's own address.`,
1078
+ options: {},
1079
+ optionHelp: [],
1080
+ takes: [0, 0],
1081
+ run: (values) => publish(teableOf(values), process.cwd())
1082
+ },
1083
+ versions: {
1084
+ usage: "versions [--project <projectId>] [--limit <n>]",
1085
+ summary: "The app's published versions, newest first",
1086
+ details: "The versions the runtime deployed, newest first: when, by whom, from which commit, and which is live.",
1087
+ options: { project: { type: "string" }, limit: { type: "string" } },
1088
+ optionHelp: [PROJECT_OPTION, " --limit <n> How many of the newest (default 20)"],
1089
+ takes: [0, 0],
1090
+ run: async (values) => {
1091
+ const limit = count(values.limit, "limit") ?? 20;
1092
+ const teable = teableOf(values);
1093
+ return versions(teable, await appOf(teable, values), limit);
1094
+ }
1095
+ },
1096
+ rollback: {
1097
+ usage: "rollback --version <n> [--project <projectId>]",
1098
+ summary: "Deploy version n's code again, as the next version",
1099
+ details: `Deploys version <n>'s code again, as the next version. The runtime refuses (CONFLICT) when the
1100
+ live database has run a migration that version lacks: roll forward with a new version instead. The
1101
+ app repository is unchanged: fix or revert the code there before the next publish.`,
1102
+ options: { version: { type: "string" }, project: { type: "string" } },
1103
+ optionHelp: [
1104
+ " --version <n> The version whose code to deploy again",
1105
+ PROJECT_OPTION
1106
+ ],
1107
+ takes: [0, 0],
1108
+ run: async (values) => {
1109
+ const to = count(values.version, "version");
1110
+ if (to === void 0) throw new CommandError("rollback needs --version <n>.");
1111
+ const teable = teableOf(values);
1112
+ return rollBack(teable, await appOf(teable, values), to);
1113
+ }
1114
+ },
1115
+ whoami: {
1116
+ usage: "whoami",
1117
+ summary: "Who your token belongs to",
1118
+ details: "Who the token belongs to, at which Teable, and where the token came from.",
1119
+ options: {},
1120
+ optionHelp: [],
1121
+ takes: [0, 0],
1122
+ run: async (values) => {
1123
+ const teable = teableOf(values);
1124
+ const user = await currentUser(teable);
1125
+ return { success: true, user, endpoint: teable.endpoint, token: teable.tokenFrom };
1126
+ }
1127
+ },
1128
+ login: {
1129
+ usage: "login --token <token> [--endpoint <url>]",
1130
+ summary: "Save your token for later commands",
1131
+ details: `Checks the token with Teable, then saves it for that Teable (--endpoint, else TEABLE_ENDPOINT,
1132
+ else https://app.teable.ai) in teable-next/config.json of your config directory (XDG_CONFIG_HOME, else
1133
+ ~/.config; APPDATA on Windows), which only you can read. Later commands use it when neither --token
1134
+ nor TEABLE_TOKEN gives one, and only with that Teable. A login replaces the saved one. A personal
1135
+ access token (Teable: Settings, Personal access tokens) works; give it access to your projects with
1136
+ base read and update.`,
1137
+ options: {},
1138
+ optionHelp: [],
1139
+ takes: [0, 0],
1140
+ run: async (values) => {
1141
+ const token = text(values.token);
1142
+ if (token === void 0) throw new CommandError("login needs --token <token>.");
1143
+ const teable = loginTeable({ token, endpoint: text(values.endpoint) });
1144
+ const user = await currentUser(teable);
1145
+ const saved = saveLogin({ endpoint: teable.endpoint, token });
1146
+ return { success: true, user, endpoint: teable.endpoint, saved };
1147
+ }
1148
+ }
1149
+ };
1150
+ function version() {
1151
+ const pkg = JSON.parse(readFileSync4(new URL("../package.json", import.meta.url), "utf8"));
1152
+ return String(pkg.version);
1153
+ }
1154
+ function help() {
1155
+ const width = Math.max(...Object.values(COMMANDS).map((command) => command.usage.length));
1156
+ const shortUsage = (command) => command.usage.replace(/ \[--.*$/, "");
1157
+ const list = Object.values(COMMANDS).map(
1158
+ (command) => ` ${shortUsage(command).padEnd(Math.min(width, 34))} ${command.summary}`
1159
+ );
1160
+ return `teable-next ${version()}: start, check out, push and publish Teable apps (teable-next)
1161
+
1162
+ Usage: teable-next <command> [options]
1163
+
1164
+ Commands:
1165
+ ${list.join("\n")}
1166
+
1167
+ Options of every command:
1168
+ ${COMMON_HELP.join("\n")}
1169
+
1170
+ A teable-next project is its own app: the app's id is the project's (bseXXX). Inside a checkout (a
1171
+ directory with teable.json, or below one) commands take it from teable.json. Results are JSON on
1172
+ stdout; programs a command runs (the scaffolder, bun run check and build) print to stderr.
1173
+ `;
1174
+ }
1175
+ function commandHelp(command) {
1176
+ const options = [...command.optionHelp, ...COMMON_HELP];
1177
+ return `Usage: teable-next ${command.usage}
1178
+
1179
+ ${command.details}
1180
+
1181
+ Options:
1182
+ ${options.join("\n")}
1183
+ `;
1184
+ }
1185
+ function failed(error, details = {}) {
1186
+ process.stdout.write(`${JSON.stringify({ success: false, error, ...details }, null, 2)}
1187
+ `);
1188
+ return 1;
1189
+ }
1190
+ async function main(argv) {
1191
+ const [name, ...args] = argv;
1192
+ if (name === void 0 || name === "--help" || name === "-h") {
1193
+ process.stdout.write(help());
1194
+ return 0;
1195
+ }
1196
+ if (name === "--version" || name === "-V") {
1197
+ process.stdout.write(`${version()}
1198
+ `);
1199
+ return 0;
1200
+ }
1201
+ const topic = name === "help" ? args[0] : name;
1202
+ const command = topic !== void 0 && Object.hasOwn(COMMANDS, topic) ? COMMANDS[topic] : void 0;
1203
+ if (name === "help") {
1204
+ process.stdout.write(command === void 0 ? help() : commandHelp(command));
1205
+ return 0;
1206
+ }
1207
+ if (command === void 0) {
1208
+ return failed(`Unknown command "${name}". teable-next --help lists them.`);
1209
+ }
1210
+ const usage = `teable-next ${command.usage}`;
1211
+ let values;
1212
+ let positionals;
1213
+ try {
1214
+ ({ values, positionals } = parseArgs({
1215
+ args,
1216
+ options: { ...COMMON, ...command.options },
1217
+ allowPositionals: true,
1218
+ strict: true
1219
+ }));
1220
+ } catch (error) {
1221
+ return failed(messageOf(error), { usage });
1222
+ }
1223
+ if (values.help) {
1224
+ process.stdout.write(commandHelp(command));
1225
+ return 0;
1226
+ }
1227
+ const [min, max] = command.takes;
1228
+ if (positionals.length < min || positionals.length > max) {
1229
+ const given = positionals.length === 0 ? "none" : positionals.join(" ");
1230
+ return failed(`Wrong arguments for ${name} (given: ${given}).`, { usage });
1231
+ }
1232
+ const blank = Object.entries(values).find(([, value]) => value === "");
1233
+ if (blank !== void 0) return failed(`--${blank[0]} needs a value.`, { usage });
1234
+ try {
1235
+ const result = await command.run(values, positionals);
1236
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
1237
+ `);
1238
+ return 0;
1239
+ } catch (error) {
1240
+ if (error instanceof CommandError) return failed(error.message, error.details);
1241
+ process.stderr.write(`${error instanceof Error ? error.stack : String(error)}
1242
+ `);
1243
+ return failed(messageOf(error));
1244
+ }
1245
+ }
1246
+ process.exitCode = await main(process.argv.slice(2));