naro-cli 0.10.0 → 0.11.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/index.js CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  buildResetPlan,
11
11
  cellText,
12
12
  clearSession,
13
+ commentText,
13
14
  compareMigrations,
14
15
  controlPlaneUrl,
15
16
  countLintedTables,
@@ -34,11 +35,14 @@ import {
34
35
  openBrowser,
35
36
  parseGitHubRemote,
36
37
  parsePolicyNode,
38
+ parsePolicyStatement,
37
39
  parseRedirectEntry,
38
40
  pendingMigrationNames,
39
41
  policiesForTypes,
40
42
  projectPath,
41
43
  promptForMissingEnv,
44
+ quoteIdent,
45
+ quotePolicyName,
42
46
  readProjectLink,
43
47
  refreshStoredSession,
44
48
  removeProjectLink,
@@ -49,11 +53,12 @@ import {
49
53
  schemaMigrationTitle,
50
54
  serializeDotenv,
51
55
  slugify,
56
+ splitPolicyStatements,
52
57
  summarizeStatement,
53
58
  systemTablePredicate,
54
59
  toNaroError,
55
60
  writeProjectLink
56
- } from "./chunk-5U6YPVZS.js";
61
+ } from "./chunk-L7JOGWP3.js";
57
62
  import "./chunk-K3NQKI34.js";
58
63
 
59
64
  // src/args.ts
@@ -83,6 +88,7 @@ var BOOLEAN_FLAGS = {
83
88
  "--unique": "unique",
84
89
  "--no-write": "noWrite",
85
90
  "--signed-in": "signedIn",
91
+ "--allow-unindexed": "allowUnindexed",
86
92
  "--api-key-stdin": "apiKeyStdin",
87
93
  "--client-secret-stdin": "clientSecretStdin",
88
94
  "--password-stdin": "passwordStdin"
@@ -577,6 +583,9 @@ function printable(text) {
577
583
  }
578
584
  return out;
579
585
  }
586
+ function isPrintable(text) {
587
+ return printable(text) === text;
588
+ }
580
589
  function warningLine(warning) {
581
590
  if (warning === "out-of-order")
582
591
  return " \u26A0 older than an applied migration \u2014 db push will still apply it";
@@ -2218,1987 +2227,2207 @@ async function runDbReset(context) {
2218
2227
  // src/commands/db-schema.ts
2219
2228
  import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
2220
2229
  import { join as join3 } from "path";
2221
- var USAGE2 = {
2222
- table: "Usage: naro db table create|add-column|rename-column|rename|drop-column|drop \u2026 (see naro help)",
2223
- index: "Usage: naro db index create|drop \u2026 (see naro help)",
2224
- create: "Usage: naro db table create <name> --column <spec> [--column <spec>\u2026] [--owner <column>] [--if-not-exists]",
2225
- addColumn: "Usage: naro db table add-column <table> --column <spec>",
2226
- renameColumn: "Usage: naro db table rename-column <table> <column> <new-name>",
2227
- rename: "Usage: naro db table rename <table> <new-name>",
2228
- dropColumn: "Usage: naro db table drop-column <table> <column>",
2229
- drop: "Usage: naro db table drop <table>",
2230
- indexCreate: "Usage: naro db index create <table> <column[,column\u2026]> [--unique] [--name <name>]",
2231
- indexDrop: "Usage: naro db index drop <name>"
2230
+
2231
+ // src/commands/policy.ts
2232
+ import { readFileSync as readFileSync3 } from "fs";
2233
+ import { resolve as resolve3 } from "path";
2234
+
2235
+ // ../../packages/naro-sdk/src/query/filters.ts
2236
+ var MAX_FILTER_DEPTH = 4;
2237
+ var OPERATORS = {
2238
+ eq: "eq",
2239
+ neq: "neq",
2240
+ gt: "gt",
2241
+ gte: "gte",
2242
+ lt: "lt",
2243
+ lte: "lte",
2244
+ in: "in",
2245
+ is: "is",
2246
+ like: "like",
2247
+ ilike: "ilike",
2248
+ contains: "contains",
2249
+ containedBy: "containedBy",
2250
+ overlaps: "overlaps",
2251
+ cs: "contains",
2252
+ cd: "containedBy",
2253
+ ov: "overlaps"
2232
2254
  };
2233
- var SPEC_USAGE = '--column needs name:type, e.g. --column "title:text:notnull".';
2234
- var ON_DELETE = {
2235
- cascade: "CASCADE",
2236
- "set-null": "SET NULL",
2237
- "set-default": "SET DEFAULT",
2238
- restrict: "RESTRICT",
2239
- "no-action": "NO ACTION"
2255
+ function operatorOf(name) {
2256
+ return typeof name === "string" && Object.hasOwn(OPERATORS, name) ? OPERATORS[name] : void 0;
2257
+ }
2258
+ var Refusal = class extends Error {
2240
2259
  };
2241
- var KEYWORDS = /* @__PURE__ */ new Set(["CURRENT_TIMESTAMP", "CURRENT_DATE", "CURRENT_TIME"]);
2242
- var NUMBER = /^-?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
2243
- function segments(spec) {
2244
- const parts = [];
2245
- let current = "";
2246
- let quoted = false;
2247
- for (const char of spec) {
2248
- if (char === "'") quoted = !quoted;
2249
- if (char === ":" && !quoted) {
2250
- parts.push(current);
2251
- current = "";
2252
- continue;
2253
- }
2254
- current += char;
2255
- }
2256
- if (quoted) return null;
2257
- parts.push(current);
2258
- return parts;
2260
+ function refuse(reason) {
2261
+ throw new Refusal(reason);
2259
2262
  }
2260
- function defaultValue(text) {
2261
- if (text.length >= 2 && text.startsWith("'") && text.endsWith("'"))
2262
- return text.slice(1, -1).replace(/''/g, "'");
2263
- const lower = text.toLowerCase();
2264
- if (lower === "null") return null;
2265
- if (lower === "true") return true;
2266
- if (lower === "false") return false;
2267
- const upper = text.toUpperCase();
2268
- if (KEYWORDS.has(upper)) return { keyword: upper };
2269
- if (NUMBER.test(text)) return Number(text);
2270
- return text;
2263
+ var LIST_HINT = {
2264
+ in: ["(", ")", "needs a list in parentheses, like in.(a,b),"],
2265
+ array: ["{", "}", "needs a list in braces, like cs.{a,b},"]
2266
+ };
2267
+ function isSpace(char) {
2268
+ return char !== "" && char.trim() === "";
2271
2269
  }
2272
- function parseColumnSpec(spec) {
2273
- const shown = `--column "${printable(spec)}"`;
2274
- const parts = segments(spec);
2275
- if (parts === null)
2276
- throw new NaroError(
2277
- "VALIDATION_FAILED",
2278
- `${shown}: a quoted default is not closed.`
2279
- );
2280
- const [name, type, ...modifiers] = parts;
2281
- if (!name || !type) throw new NaroError("VALIDATION_FAILED", SPEC_USAGE);
2282
- const column = {
2283
- name,
2284
- type
2285
- };
2286
- let onDelete;
2287
- for (const modifier of modifiers) {
2288
- const eq = modifier.indexOf("=");
2289
- const key = (eq < 0 ? modifier : modifier.slice(0, eq)).toLowerCase();
2290
- const value = eq < 0 ? void 0 : modifier.slice(eq + 1);
2291
- if (value === void 0 && key === "pk") column.primaryKey = true;
2292
- else if (value === void 0 && key === "autoincrement")
2293
- column.autoIncrement = true;
2294
- else if (value === void 0 && key === "notnull") column.notNull = true;
2295
- else if (value === void 0 && key === "unique") column.unique = true;
2296
- else if (value !== void 0 && key === "default")
2297
- column.default = defaultValue(value);
2298
- else if (value !== void 0 && key === "references") {
2299
- const dot = value.lastIndexOf(".");
2300
- const table = dot < 0 ? "" : value.slice(0, dot);
2301
- const target = dot < 0 ? "" : value.slice(dot + 1);
2302
- if (!table || !target)
2303
- throw new NaroError(
2304
- "VALIDATION_FAILED",
2305
- `${shown}: references needs <table>.<column>.`
2306
- );
2307
- column.references = { table, column: target };
2308
- } else if (value !== void 0 && key === "ondelete") {
2309
- onDelete = ON_DELETE[value.toLowerCase()];
2310
- if (!onDelete)
2311
- throw new NaroError(
2312
- "VALIDATION_FAILED",
2313
- `${shown}: ondelete takes cascade, set-null, set-default, restrict or no-action.`
2270
+ function looseWord(text) {
2271
+ return text.replace(/\s+/g, "").toLowerCase().replace(/\(\)$/, "");
2272
+ }
2273
+ var Parser = class {
2274
+ constructor(text, tokens = {}) {
2275
+ this.text = text;
2276
+ this.tokens = tokens;
2277
+ }
2278
+ index = 0;
2279
+ /**
2280
+ * A token at the next value, followed only by spaces and then one of
2281
+ * `stops` or the end — `auth.uid()x` is text, not the token.
2282
+ */
2283
+ token(stops) {
2284
+ this.skipSpaces();
2285
+ const at = this.index;
2286
+ for (const [word, value] of Object.entries(this.tokens)) {
2287
+ if (!this.text.startsWith(word, at)) continue;
2288
+ let end = at + word.length;
2289
+ while (isSpace(this.text[end] ?? "")) end++;
2290
+ const next = this.text[end] ?? "";
2291
+ if (next !== "" && !stops.includes(next)) continue;
2292
+ this.index = end;
2293
+ return { value, word, at };
2294
+ }
2295
+ return void 0;
2296
+ }
2297
+ at() {
2298
+ return this.text[this.index] ?? "";
2299
+ }
2300
+ /**
2301
+ * An unquoted value that is one of the tokens misspelled — `auth.uid`,
2302
+ * `AUTH.UID` — is refused: read as text it would compare with the words
2303
+ * themselves (사용자 리뷰 반영). Quoted, it is the text.
2304
+ */
2305
+ notNearToken(value, at) {
2306
+ const loose = looseWord(value);
2307
+ for (const word of Object.keys(this.tokens))
2308
+ if (loose !== "" && loose === looseWord(word))
2309
+ refuse(
2310
+ `has ${JSON.stringify(value)} ${this.where(at)}: did you mean ${word}? Quote it to mean the text`
2314
2311
  );
2315
- } else
2316
- throw new NaroError(
2317
- "VALIDATION_FAILED",
2318
- `${shown}: unknown modifier ${printable(modifier)}. Use pk, autoincrement, notnull, unique, default=<value>, references=<table>.<column> or ondelete=<action>.`
2319
- );
2320
2312
  }
2321
- if (onDelete !== void 0) {
2322
- if (!column.references)
2323
- throw new NaroError(
2324
- "VALIDATION_FAILED",
2325
- `${shown}: ondelete needs references=<table>.<column>.`
2326
- );
2327
- column.references.onDelete = onDelete;
2313
+ /** `scalar`, with an unquoted value held to notNearToken. */
2314
+ bareOrQuoted(stops) {
2315
+ this.skipSpaces();
2316
+ const at = this.index;
2317
+ const quoted = this.at() === '"';
2318
+ const text = this.scalar(stops);
2319
+ if (!quoted) this.notNearToken(text, at);
2320
+ return { text, quoted };
2328
2321
  }
2329
- return column;
2330
- }
2331
- function policyLine(policy, dryRun = false) {
2332
- const rules = [policy.select, policy.insert, policy.update, policy.delete];
2333
- const owner = policy.ownerColumn === null ? "" : ` (owner column ${printable(policy.ownerColumn)})`;
2334
- const uniform = rules.every((rule) => rule === rules[0]);
2335
- const summary = uniform ? `${String(rules[0])} for select, insert, update and delete` : `select ${policy.select}, insert ${policy.insert}, update ${policy.update}, delete ${policy.delete}`;
2336
- const head = dryRun ? "Would set the Data API policy" : "\u2713 Data API policy";
2337
- return `${head} on ${printable(policy.table)}: ${summary}${owner}.`;
2338
- }
2339
- function removedLine(policy, dryRun) {
2340
- const owner = policy.ownerColumn === null ? "" : `, owner column ${printable(policy.ownerColumn)}`;
2341
- const rules = `select ${policy.select}, insert ${policy.insert}, update ${policy.update}, delete ${policy.delete}${owner}`;
2342
- return `${dryRun ? "Would remove" : "\u2713 Removed"} the Data API policy on ${printable(policy.table)} (${rules}).`;
2343
- }
2344
- async function runSchemaChange(context, operations, question) {
2345
- const dryRun = context.flags.dryRun === true;
2346
- if (question !== void 0 && !dryRun)
2347
- await confirmOrAbort(context, question);
2348
- const sent = dryRun ? operations.map((operation) => {
2349
- if (operation.op !== "dropTable" && operation.op !== "dropColumn")
2350
- return operation;
2351
- const { confirm: _confirm, ...rest } = operation;
2352
- return rest;
2353
- }) : operations;
2354
- const client = await context.client();
2355
- const projectId = await context.resolveProjectId();
2356
- const dir = migrationsDir(context);
2357
- const local = listMigrationFiles(dir);
2358
- const ledger = await appliedMigrations(client, projectId);
2359
- const pending = pendingMigrationNames(local, ledger);
2360
- if (pending.length > 0 && !dryRun)
2361
- throw migrationsPendingError(pending.map(printable));
2362
- const name = nextMigrationFileName(
2363
- [...local, ...ledger.map((row) => row.name)],
2364
- schemaMigrationTitle(operations[0] ?? {})
2365
- );
2366
- const result = await client.db.schema(projectId, sent, {
2367
- ...dryRun ? { dryRun: true } : {},
2368
- name
2369
- });
2370
- const sqlLines = result.sql.trimEnd().split("\n").map(printable);
2371
- const removed = result.removedPolicies ?? [];
2372
- if (result.dryRun) {
2373
- for (const warning of result.warnings)
2374
- context.output.warn(`\u26A0 ${printable(warning)}`);
2375
- context.output.result({ projectId, ...result, file: null }, [
2376
- ...sqlLines,
2377
- `Dry run \u2014 nothing was applied. It would be recorded as ${printable(result.name)}.`,
2378
- ...result.policies.map((policy) => policyLine(policy, true)),
2379
- ...removed.map((policy) => removedLine(policy, true))
2380
- ]);
2381
- return;
2322
+ where(index = this.index) {
2323
+ return `at character ${String(index + 1)}`;
2382
2324
  }
2383
- const allWarnings = result.name === name ? result.warnings : [...result.warnings, migrationNameMismatch(name, result.name)];
2384
- let file = null;
2385
- let fileWarning;
2386
- const relDir = relativeToCwd(context, dir);
2387
- const rel = join3(relDir === "." ? "" : relDir, name);
2388
- if (context.flags.noWrite) {
2389
- fileWarning = `Not written to ${relDir} (--no-write): naro db reset will not re-apply ${result.name}, and naro migration list shows it as remote-only.`;
2390
- } else {
2391
- try {
2392
- mkdirSync3(dir, { recursive: true });
2393
- writeFileSync3(join3(dir, name), result.sql, { flag: "wx" });
2394
- file = rel;
2395
- } catch (error) {
2396
- const reason = (error instanceof Error ? error.message : String(error)).replace(/[.\s]+$/, "");
2397
- fileWarning = `Applied, but ${rel} could not be written: ${reason}. Save the SQL above as ${rel} so naro db push and naro db reset see it.`;
2398
- }
2325
+ skipSpaces() {
2326
+ while (isSpace(this.at())) this.index++;
2399
2327
  }
2400
- for (const warning of allWarnings)
2401
- context.output.warn(`\u26A0 ${printable(warning)}`);
2402
- if (fileWarning) context.output.warn(`\u26A0 ${printable(fileWarning)}`);
2403
- context.output.result(
2404
- {
2405
- projectId,
2406
- ...result,
2407
- warnings: allWarnings,
2408
- file,
2409
- ...fileWarning ? { fileWarning } : {}
2410
- },
2411
- [
2412
- ...sqlLines,
2413
- file === null ? `\u2705 Applied ${printable(result.name)}.` : `\u2705 Applied ${printable(result.name)} and wrote ${printable(file)}.`,
2414
- ...result.policies.map((policy) => policyLine(policy)),
2415
- ...removed.map((policy) => removedLine(policy, false))
2416
- ]
2417
- );
2418
- }
2419
- function columnsFlag(context) {
2420
- return context.flags.columns ?? [];
2421
- }
2422
- async function runDbTableUsage() {
2423
- throw new NaroError("VALIDATION_FAILED", USAGE2.table);
2424
- }
2425
- async function runDbIndexUsage() {
2426
- throw new NaroError("VALIDATION_FAILED", USAGE2.index);
2427
- }
2428
- async function runDbTableCreate(context) {
2429
- const [table] = context.positionals;
2430
- const specs = columnsFlag(context);
2431
- if (!table || specs.length === 0)
2432
- throw new NaroError("VALIDATION_FAILED", USAGE2.create);
2433
- const columns = specs.map(parseColumnSpec);
2434
- const owner = context.flags.ownerColumn;
2435
- await runSchemaChange(context, [
2436
- {
2437
- op: "createTable",
2438
- table,
2439
- columns,
2440
- ...context.flags.ifNotExists ? { ifNotExists: true } : {},
2441
- ...owner === void 0 ? {} : { owner: { column: owner } }
2328
+ /** `item ("," item)*`, up to a `)` or the end, inside `level` groups. */
2329
+ list(level) {
2330
+ const nodes = [];
2331
+ for (; ; ) {
2332
+ nodes.push(this.item(level));
2333
+ this.skipSpaces();
2334
+ const char = this.at();
2335
+ if (char === ",") this.index++;
2336
+ else if (char === ")" || char === "") return nodes;
2337
+ else refuse(`has unexpected text ${this.where()}`);
2442
2338
  }
2443
- ]);
2444
- }
2445
- async function runDbTableAddColumn(context) {
2446
- const [table] = context.positionals;
2447
- const specs = columnsFlag(context);
2448
- const [spec] = specs;
2449
- if (!table || spec === void 0 || specs.length !== 1)
2450
- throw new NaroError("VALIDATION_FAILED", USAGE2.addColumn);
2451
- await runSchemaChange(context, [
2452
- { op: "addColumn", table, column: parseColumnSpec(spec) }
2453
- ]);
2454
- }
2455
- async function runDbTableRenameColumn(context) {
2456
- const [table, column, to] = context.positionals;
2457
- if (!table || !column || !to)
2458
- throw new NaroError("VALIDATION_FAILED", USAGE2.renameColumn);
2459
- await runSchemaChange(context, [{ op: "renameColumn", table, column, to }]);
2460
- }
2461
- async function runDbTableRename(context) {
2462
- const [table, to] = context.positionals;
2463
- if (!table || !to) throw new NaroError("VALIDATION_FAILED", USAGE2.rename);
2464
- await runSchemaChange(context, [{ op: "renameTable", table, to }]);
2465
- }
2466
- async function runDbTableDropColumn(context) {
2467
- const [table, column] = context.positionals;
2468
- if (!table || !column)
2469
- throw new NaroError("VALIDATION_FAILED", USAGE2.dropColumn);
2470
- const target = `${table}.${column}`;
2471
- await runSchemaChange(
2472
- context,
2473
- [{ op: "dropColumn", table, column, confirm: target }],
2474
- `Drop column ${printable(target)} and its value in every row? naro db restore can bring it back (Time Travel, 30 days).`
2475
- );
2476
- }
2477
- async function runDbTableDrop(context) {
2478
- const [table] = context.positionals;
2479
- if (!table) throw new NaroError("VALIDATION_FAILED", USAGE2.drop);
2480
- await runSchemaChange(
2481
- context,
2482
- [{ op: "dropTable", table, confirm: table }],
2483
- `Drop table ${printable(table)} and every row in it? naro db restore can bring it back (Time Travel, 30 days).`
2484
- );
2485
- }
2486
- async function runDbIndexCreate(context) {
2487
- const [table, list] = context.positionals;
2488
- const columns = listFlag(list);
2489
- if (!table || columns.length === 0)
2490
- throw new NaroError("VALIDATION_FAILED", USAGE2.indexCreate);
2491
- const name = context.flags.name;
2492
- await runSchemaChange(context, [
2493
- {
2494
- op: "createIndex",
2495
- table,
2496
- columns,
2497
- ...context.flags.unique ? { unique: true } : {},
2498
- ...name === void 0 ? {} : { name }
2339
+ }
2340
+ item(level) {
2341
+ this.skipSpaces();
2342
+ const start = this.index;
2343
+ const char = this.at();
2344
+ if (char === "" || char === "," || char === ")")
2345
+ refuse(`has an empty item ${this.where()}`);
2346
+ const group = /^(not\.)?(and|or)\(/.exec(this.text.slice(start));
2347
+ if (!group) return this.leaf(level);
2348
+ const negated = group[1] !== void 0;
2349
+ const inner = level + (negated ? 2 : 1);
2350
+ if (inner > MAX_FILTER_DEPTH)
2351
+ refuse(`nests deeper than ${String(MAX_FILTER_DEPTH)} groups`);
2352
+ const open = start + group[0].length - 1;
2353
+ this.index = open + 1;
2354
+ const children = this.list(inner);
2355
+ if (this.at() !== ")") refuse(`has an unclosed "(" ${this.where(open)}`);
2356
+ this.index++;
2357
+ const node = group[2] === "or" ? { or: children } : { and: children };
2358
+ return negated ? { not: node } : node;
2359
+ }
2360
+ /** `column.[not.]operator.value`. */
2361
+ leaf(level) {
2362
+ const start = this.index;
2363
+ const column = this.at() === '"' ? this.quoted() : this.word().trim();
2364
+ if (column === "" || this.at() !== ".")
2365
+ refuse(`needs column.operator.value ${this.where(start)}`);
2366
+ this.index++;
2367
+ let nameAt = this.index;
2368
+ let name = this.word();
2369
+ let negated = false;
2370
+ if (name === "not" && this.at() === ".") {
2371
+ if (level + 1 > MAX_FILTER_DEPTH)
2372
+ refuse(`nests deeper than ${String(MAX_FILTER_DEPTH)} groups`);
2373
+ negated = true;
2374
+ this.index++;
2375
+ nameAt = this.index;
2376
+ name = this.word();
2499
2377
  }
2500
- ]);
2501
- }
2502
- async function runDbIndexDrop(context) {
2503
- const [name] = context.positionals;
2504
- if (!name) throw new NaroError("VALIDATION_FAILED", USAGE2.indexDrop);
2505
- await runSchemaChange(context, [{ op: "dropIndex", name }]);
2506
- }
2507
-
2508
- // src/commands/git.ts
2509
- var defaults2 = {
2510
- detectRemote: async (dir) => (await detectGitInfo(dir)).repositoryUrl,
2511
- openBrowser,
2512
- sleep: (ms) => new Promise((resolve5) => setTimeout(resolve5, ms))
2513
- };
2514
- function connected(context, project) {
2515
- const branch = project.defaultBranch;
2516
- context.output.result(
2517
- {
2518
- projectId: project.id,
2519
- repositoryFullName: project.repositoryFullName,
2520
- autoDeploy: true
2521
- },
2522
- [
2523
- `\u2705 Connected to ${project.repositoryFullName ?? "the repository"}.`,
2524
- ` Pushes to ${branch} now deploy automatically.`,
2525
- "",
2526
- " To turn this off: naro git disconnect"
2527
- ]
2528
- );
2529
- }
2530
- async function runGitConnect(context, overrides = {}) {
2531
- const deps = { ...defaults2, ...overrides };
2532
- const { output } = context;
2533
- const explicit = context.positionals[0];
2534
- let fullName;
2535
- if (explicit) {
2536
- const parsed = parseGitHubRemote(explicit) ?? parseGitHubRemote(`https://github.com/${explicit}`);
2537
- if (!parsed)
2538
- throw new NaroError(
2539
- "VALIDATION_FAILED",
2540
- `"${explicit}" is not an owner/repo pair.`
2541
- );
2542
- fullName = parsed.fullName;
2543
- } else {
2544
- const remote = await deps.detectRemote(context.cwd);
2545
- const parsed = remote ? parseGitHubRemote(remote) : null;
2546
- if (!parsed) {
2547
- throw new NaroError(
2548
- "NO_GIT_REMOTE",
2549
- remote ? `Could not read a GitHub owner/repo from "${remote}". Pass it directly: naro git connect <owner/repo>` : "This directory has no GitHub origin remote. Pass one directly: naro git connect <owner/repo>"
2550
- );
2378
+ const operator = operatorOf(name);
2379
+ if (this.at() !== ".") {
2380
+ if (name !== "" && operator === void 0)
2381
+ refuse(`has an unknown operator "${name}" ${this.where(nameAt)}`);
2382
+ refuse(`needs column.operator.value ${this.where(start)}`);
2551
2383
  }
2552
- fullName = parsed.fullName;
2384
+ if (operator === void 0)
2385
+ refuse(`has an unknown operator "${name}" ${this.where(nameAt)}`);
2386
+ this.index++;
2387
+ const leaf = { operator, column, value: this.value(operator) };
2388
+ return negated ? { not: leaf } : leaf;
2553
2389
  }
2554
- const client = await context.client();
2555
- const projectId = await context.resolveProjectId();
2556
- const first = await client.projects.connectGit(projectId, fullName);
2557
- if (first.ok) {
2558
- connected(context, first.project);
2559
- return;
2390
+ /** Up to the next `.`, `,`, `(`, `)` or the end. */
2391
+ word() {
2392
+ const start = this.index;
2393
+ while (this.index < this.text.length && !".,()".includes(this.at()))
2394
+ this.index++;
2395
+ return this.text.slice(start, this.index);
2560
2396
  }
2561
- if (!first.installUrl) {
2562
- throw new NaroError(
2563
- "REPOSITORY_NOT_ACCESSIBLE",
2564
- `Naro cannot reach ${fullName}, and no install URL was offered. Connect it from the dashboard.`
2565
- );
2397
+ /** `"…"`, with `\` making the next character literal. */
2398
+ quoted() {
2399
+ const start = this.index;
2400
+ this.index++;
2401
+ let text = "";
2402
+ for (; ; ) {
2403
+ if (this.index >= this.text.length)
2404
+ refuse(`has an unclosed quote ${this.where(start)}`);
2405
+ const char = this.at();
2406
+ this.index++;
2407
+ if (char === '"') return text;
2408
+ if (char === "\\" && this.index < this.text.length) {
2409
+ text += this.at();
2410
+ this.index++;
2411
+ } else text += char;
2412
+ }
2566
2413
  }
2567
- output.log(`
2568
- \u25B8 Naro needs access to ${fullName}.`);
2569
- output.log(` Opening ${first.installUrl}`);
2570
- deps.openBrowser(first.installUrl);
2571
- output.log(" Waiting for the installation to finish...\n");
2572
- await waitForInstall(context, projectId, fullName, deps);
2573
- }
2574
- async function waitForInstall(context, projectId, fullName, deps) {
2575
- const client = await context.client();
2576
- const project = await client.projects.get(projectId);
2577
- const teams = await client.teams.list();
2578
- const teamSlug = teams.find((team) => team.id === project.teamId)?.slug;
2579
- if (teamSlug) {
2580
- const attempts = deps.pollAttempts ?? 60;
2581
- const interval = deps.pollIntervalMs ?? 3e3;
2582
- for (let attempt2 = 0; attempt2 < attempts; attempt2 += 1) {
2583
- await deps.sleep(interval);
2584
- let reachable = false;
2585
- try {
2586
- const repositories = await client.github.listRepositories(teamSlug);
2587
- reachable = repositories.some(
2588
- (repository) => repository.fullName.toLowerCase() === fullName.toLowerCase()
2589
- );
2590
- } catch {
2591
- }
2592
- if (!reachable) continue;
2593
- const retry = await client.projects.connectGit(projectId, fullName);
2594
- if (retry.ok) {
2595
- connected(context, retry.project);
2596
- return;
2597
- }
2598
- }
2599
- }
2600
- context.output.result(
2601
- { projectId, repositoryFullName: null, autoDeploy: false },
2602
- [
2603
- `\u25B8 Still waiting on access to ${fullName}.`,
2604
- " Finish the installation, then run: naro git connect"
2605
- ]
2606
- );
2607
- }
2608
- async function runGitDisconnect(context) {
2609
- const client = await context.client();
2610
- const projectId = await context.resolveProjectId();
2611
- const project = await client.projects.disconnectGit(projectId);
2612
- context.output.result({ projectId: project.id, autoDeploy: false }, [
2613
- `\u2705 ${project.name} no longer deploys on push.`,
2614
- " Deploy from here with: naro deploy"
2615
- ]);
2616
- }
2617
- async function offerAutoDeploy(context, projectId, overrides) {
2618
- const deps = { ...defaults2, ...overrides };
2619
- if (overrides.canPrompt === false) return;
2620
- try {
2621
- if (readProjectLink(context.cwd)?.autoDeployDeclined === true) return;
2622
- const connection = overrides.gitConnection;
2623
- if (connection.state === "connected" || connection.state === "none") return;
2624
- const fullName = connection.fullName;
2625
- if (!fullName) return;
2626
- let wanted;
2627
- if (connection.state === "unreachable") {
2628
- const installed = connection.installedAccounts ?? [];
2629
- context.output.log(
2630
- `
2631
- \u25B8 Automatic deploys need the Naro GitHub App on \`${connection.repoOwner ?? fullName}\`.`
2632
- );
2633
- if (overrides.teamSlug && installed.length > 0)
2634
- context.output.log(
2635
- ` Team ${overrides.teamSlug} has it on: ${installed.join(", ")}.`
2636
- );
2637
- wanted = await context.prompter.confirm(
2638
- "Install it for this team now? (opens your browser)"
2639
- );
2640
- } else {
2641
- wanted = await context.prompter.confirm(
2642
- "Should your changes deploy automatically from now on?"
2643
- );
2644
- }
2645
- if (!wanted) {
2646
- const link = readProjectLink(context.cwd);
2647
- writeProjectLink(context.cwd, {
2648
- ...link ?? { projectId },
2649
- autoDeployDeclined: true
2650
- });
2651
- context.output.log(
2652
- "\u25B8 Not now. Later, if you change your mind: naro git connect"
2653
- );
2654
- return;
2655
- }
2656
- const client = await context.client();
2657
- const result = await client.projects.connectGit(projectId, fullName);
2658
- if (result.ok) {
2659
- connected(context, result.project);
2660
- return;
2414
+ /** A quoted value, or everything up to `stops`, trimmed. */
2415
+ scalar(stops) {
2416
+ this.skipSpaces();
2417
+ if (this.at() === '"') {
2418
+ const text = this.quoted();
2419
+ this.skipSpaces();
2420
+ if (this.at() !== "" && !stops.includes(this.at()))
2421
+ refuse(`has text after a closing quote ${this.where()}`);
2422
+ return text;
2661
2423
  }
2662
- if (!result.installUrl) return;
2663
- context.output.log(`
2664
- \u25B8 Naro needs access to ${fullName}.`);
2665
- context.output.log(` Opening ${result.installUrl}`);
2666
- deps.openBrowser(result.installUrl);
2667
- context.output.log(" Waiting for the installation to finish...\n");
2668
- await waitForInstall(context, projectId, fullName, deps);
2669
- } catch (error) {
2670
- context.output.log(
2671
- `\u25B8 Could not set up automatic deploys (${error instanceof Error ? error.message : String(error)}).`
2672
- );
2673
- context.output.log(" Try later with: naro git connect");
2674
- }
2675
- }
2676
-
2677
- // src/commands/link.ts
2678
- var SWITCH_ACCOUNT = "Sign in as a different account\u2026";
2679
- async function resolveTeam(context, teams, deps = {}) {
2680
- const explicit = context.flags.team ?? process.env.NARO_TEAM;
2681
- if (explicit) {
2682
- const match = teams.find((team) => team.slug === explicit);
2683
- if (!match)
2684
- throw new NaroError(
2685
- "NOT_FOUND",
2686
- `You are not a member of team "${explicit}".`
2687
- );
2688
- return match;
2689
- }
2690
- const linked = context.projectLink();
2691
- if (linked?.teamSlug) {
2692
- const match = teams.find((team) => team.slug === linked.teamSlug);
2693
- if (match) return match;
2694
- }
2695
- if (teams.length === 0)
2696
- throw new NaroError("NOT_FOUND", "Your account has no teams yet.");
2697
- const only = teams.length === 1 ? teams[0] : null;
2698
- const deploying = (deps.intent ?? "deploy") === "deploy";
2699
- if (only && !deploying) return only;
2700
- const canPrompt = deps.canPrompt?.() ?? (!context.flags.json && !context.flags.yes && isInteractive());
2701
- if (!canPrompt)
2702
- throw new NaroError(
2703
- "TEAM_REQUIRED",
2704
- `Cannot pick a team without a prompt. Pass --team <slug>, set NARO_TEAM, or run \`naro link\` first.
2705
- Your teams: ${teams.map((team) => team.slug).join(", ")}`
2706
- );
2707
- const account = deps.accountLabel ? await deps.accountLabel() : "this account";
2708
- if (only) {
2709
- const label2 = only.isPersonal ? `${only.name} (personal)` : only.name;
2710
- context.output.log(`
2711
- ${account} \u2192 ${label2}`);
2712
- const ok = await context.prompter.confirm(
2713
- "Deploy to this account and team?"
2714
- );
2715
- if (ok) return only;
2716
- return switchAndRetry(context, deps);
2424
+ const start = this.index;
2425
+ while (this.index < this.text.length && !stops.includes(this.at()))
2426
+ this.index++;
2427
+ return this.text.slice(start, this.index).trim();
2717
2428
  }
2718
- const options = [
2719
- ...teams.map(
2720
- (team) => `${team.name}${team.isPersonal ? " (personal)" : ""}`
2721
- ),
2722
- SWITCH_ACCOUNT
2723
- ];
2724
- const index = await context.prompter.select(
2725
- deploying ? `Deploying as ${account} \u2014 which team owns this project?` : `Signed in as ${account}. Which team?`,
2726
- options
2727
- );
2728
- const picked = teams[index];
2729
- if (picked) return picked;
2730
- return switchAndRetry(context, deps);
2731
- }
2732
- async function switchAndRetry(context, deps) {
2733
- if (!deps.switchAccount || !deps.listTeams)
2734
- throw new NaroError(
2735
- "CANCELED",
2736
- "Canceled. Switch accounts with `naro logout && naro login`."
2737
- );
2738
- await deps.switchAccount();
2739
- const teams = await deps.listTeams();
2740
- return resolveTeam(context, teams, deps);
2741
- }
2742
- function saveLink(context, project, teamSlug) {
2743
- writeProjectLink(context.cwd, {
2744
- projectId: project.id,
2745
- teamSlug,
2746
- projectName: project.name
2747
- });
2748
- if (ensureGitignoreHasNaro(context.cwd))
2749
- context.output.log("\u25B8 added .naro to .gitignore");
2750
- }
2751
- async function runLink(context) {
2752
- const client = await context.client();
2753
- const teams = await client.teams.list();
2754
- const team = await resolveTeam(context, teams, { intent: "read" });
2755
- const projects = await client.projects.list(team.slug);
2756
- let project;
2757
- if (context.flags.project) {
2758
- project = projects.find(
2759
- (candidate) => candidate.id === context.flags.project
2760
- );
2761
- if (!project) {
2762
- project = await client.projects.get(context.flags.project);
2763
- }
2764
- } else if (context.flags.name) {
2765
- project = projects.find(
2766
- (candidate) => candidate.name === context.flags.name || candidate.slug === context.flags.name
2767
- );
2768
- if (!project)
2769
- throw new NaroError(
2770
- "PROJECT_NOT_FOUND",
2771
- `No project named "${context.flags.name}" in team ${team.slug}. Run \`naro deploy\` to create it.`
2772
- );
2773
- } else {
2774
- const guess = slugify(context.cwd.split("/").at(-1) ?? "app");
2775
- const exact = projects.find(
2776
- (candidate) => candidate.name === guess || candidate.slug === guess
2777
- );
2778
- if (exact && (context.flags.yes || context.flags.json)) {
2779
- project = exact;
2780
- } else if (projects.length === 0) {
2781
- throw new NaroError(
2782
- "PROJECT_NOT_FOUND",
2783
- `Team ${team.slug} has no projects yet. Run \`naro deploy\` to create one.`
2784
- );
2785
- } else {
2786
- const options = projects.map(
2787
- (candidate) => `${candidate.name} (${candidate.subdomain})`
2788
- );
2789
- const index = await context.prompter.select(
2790
- `Link ${context.cwd} to which project?`,
2791
- options
2792
- );
2793
- project = projects[index];
2429
+ /**
2430
+ * `(a,b)` for `in`: text values, except that an unquoted `true` or `false`
2431
+ * is a boolean (사용자 리뷰 반영, as in `eq`). `{a,b}` for the array
2432
+ * operators: text, except that an unquoted exact decimal is a number
2433
+ * (적대적 리뷰 반영, narrowed by 사용자 리뷰 반영) — json_each's values
2434
+ * have no type affinity to turn the text "1" into 1, so as text `cs.{1}`
2435
+ * matched no numeric array and `not.ov.{1}` matched every row. Quoted,
2436
+ * `"1"` and `"true"` stay text.
2437
+ */
2438
+ listValue(kind) {
2439
+ const [open, close, hint] = LIST_HINT[kind];
2440
+ this.skipSpaces();
2441
+ const openAt = this.index;
2442
+ if (this.at() !== open) refuse(`${hint} ${this.where()}`);
2443
+ this.index++;
2444
+ this.skipSpaces();
2445
+ const values = [];
2446
+ if (this.at() === close) {
2447
+ this.index++;
2448
+ return values;
2449
+ }
2450
+ for (; ; ) {
2451
+ this.skipSpaces();
2452
+ const itemAt = this.index;
2453
+ const token = this.token(`,${close}`);
2454
+ if (token) values.push(token.value);
2455
+ else {
2456
+ const { text: value, quoted } = this.bareOrQuoted(`,${close}`);
2457
+ if (!quoted && value === "") {
2458
+ if (this.index >= this.text.length)
2459
+ refuse(`has an unclosed "${open}" ${this.where(openAt)}`);
2460
+ refuse(`has an empty item ${this.where(itemAt)}`);
2461
+ }
2462
+ values.push(
2463
+ quoted ? value : kind === "array" ? exactNumber(value) : truth(value)
2464
+ );
2465
+ }
2466
+ if (this.index >= this.text.length)
2467
+ refuse(`has an unclosed "${open}" ${this.where(openAt)}`);
2468
+ const char = this.at();
2469
+ this.index++;
2470
+ if (char === close) return values;
2794
2471
  }
2795
2472
  }
2796
- if (!project)
2797
- throw new NaroError("PROJECT_NOT_FOUND", "No project selected.");
2798
- const owningTeam = teams.find((candidate) => candidate.id === project.teamId) ?? team;
2799
- saveLink(context, project, owningTeam.slug);
2800
- context.output.result(
2801
- {
2802
- projectId: project.id,
2803
- projectName: project.name,
2804
- teamSlug: owningTeam.slug,
2805
- subdomain: project.subdomain
2806
- },
2807
- [`\u2705 Linked to ${owningTeam.slug}/${project.name} (.naro/project.json)`]
2808
- );
2809
- }
2810
- async function runUnlink(context) {
2811
- const existing = readProjectLink(context.cwd);
2812
- const removed = removeProjectLink(context.cwd);
2813
- context.output.result(
2814
- { removed, ...existing ? { projectId: existing.projectId } : {} },
2815
- [removed ? "\u2705 Unlinked (.naro removed)" : "Nothing to unlink here."]
2816
- );
2817
- }
2818
-
2819
- // src/commands/deploy.ts
2820
- async function runDeploy(context, deps = { deploy: deployDirectory, offerAutoDeploy }) {
2821
- const { flags, output } = context;
2822
- const link = flags.project ? { projectId: flags.project, teamSlug: void 0 } : readProjectLink(context.cwd);
2823
- if (flags.prod && !flags.yes && !flags.json && isInteractive()) {
2824
- const confirmed = await context.prompter.confirm("Deploy to production?");
2825
- if (!confirmed) throw new NaroError("CANCELED", "Canceled.");
2826
- }
2827
- output.log(`
2828
- \u{1F680} Deploying ${context.cwd}
2829
- `);
2830
- const canPrompt = deps.canPrompt?.() ?? (!flags.json && !flags.yes && isInteractive());
2831
- const team = await resolveDestination(context, link, canPrompt);
2832
- const account = await accountLabel(context);
2833
- output.log(` ${account} \u2192 ${team.slug}
2834
- `);
2835
- const result = await deps.deploy(
2836
- context.cwd,
2837
- {
2838
- name: flags.name,
2839
- projectId: link?.projectId,
2840
- teamSlug: team.slug,
2841
- rootDirectory: flags.root ?? null,
2842
- branch: flags.branch,
2843
- production: flags.prod,
2844
- ...canPrompt && {
2845
- onMissingEnv: (keys) => promptForMissingEnv(
2846
- { cwd: context.cwd, prompter: context.prompter, output },
2847
- keys
2848
- )
2849
- },
2850
- token: flags.token,
2851
- allowLogin: !flags.json && !flags.yes
2852
- },
2853
- (message) => output.log(message)
2854
- );
2855
- const existing = readProjectLink(context.cwd);
2856
- writeProjectLink(context.cwd, {
2857
- projectId: result.projectId,
2858
- teamSlug: result.teamSlug,
2859
- projectName: result.projectSlug,
2860
- ...existing?.autoDeployDeclined === true ? { autoDeployDeclined: true } : {}
2861
- });
2862
- if (!link) {
2863
- if (ensureGitignoreHasNaro(context.cwd))
2864
- output.log("\u25B8 added .naro to .gitignore");
2865
- output.log("\u25B8 linked (.naro/project.json)");
2866
- }
2867
- await deps.offerAutoDeploy?.(context, result.projectId, {
2868
- canPrompt,
2869
- gitConnection: result.gitConnection,
2870
- teamSlug: result.teamSlug
2871
- });
2872
- const inspect = `${controlPlaneUrl()}${projectPath(result.teamSlug, result.projectSlug)}`;
2873
- context.output.result(
2874
- {
2875
- deploymentId: result.deploymentId,
2876
- projectId: result.projectId,
2877
- status: result.status,
2878
- url: result.url,
2879
- target: result.production ? "production" : "preview",
2880
- teamSlug: result.teamSlug,
2881
- inspectUrl: inspect,
2882
- missingEnvKeys: result.missingEnvKeys
2883
- },
2884
- [
2885
- "",
2886
- `\u2705 Deployment ready (${result.production ? "production" : "preview"})`,
2887
- "",
2888
- ` ${result.url}`,
2889
- ` Inspect ${inspect}`
2890
- ]
2891
- );
2892
- }
2893
- async function resolveDestination(context, link, canPrompt) {
2894
- const client = await context.client();
2895
- const teams = await client.teams.list();
2896
- const deps = scopeDeps(context, canPrompt);
2897
- if (link?.teamSlug) {
2898
- const match = teams.find((team) => team.slug === link.teamSlug);
2899
- if (match) return match;
2900
- } else if (link) {
2901
- let project;
2902
- try {
2903
- project = await client.projects.get(link.projectId);
2904
- } catch (error) {
2905
- if (isNaroError(error) && error.code !== "NOT_FOUND") throw error;
2906
- throw new NaroError(
2907
- "PROJECT_NOT_FOUND",
2908
- `This directory is linked to a project ${await accountLabel(context)} cannot see.
2909
- The CLI signs in separately from the dashboard \u2014 check with \`naro whoami\`.
2910
- Wrong account? naro logout && naro login
2911
- Project gone? remove .naro, then naro deploy`,
2912
- { cause: error }
2913
- );
2473
+ /** The value after `operator.`. */
2474
+ value(operator) {
2475
+ const start = this.index;
2476
+ switch (operator) {
2477
+ case "in":
2478
+ return this.listValue("in");
2479
+ case "contains":
2480
+ case "containedBy":
2481
+ case "overlaps":
2482
+ return this.listValue("array");
2483
+ case "is":
2484
+ return keyword(this.scalar(",)"), start);
2485
+ case "like":
2486
+ case "ilike": {
2487
+ const token = this.token(",)");
2488
+ if (token)
2489
+ refuse(
2490
+ `cannot use ${token.word} with ${operator} ${this.where(token.at)}`
2491
+ );
2492
+ return likePattern(this.bareOrQuoted(",)").text);
2493
+ }
2494
+ case "eq":
2495
+ case "neq": {
2496
+ const token = this.token(",)");
2497
+ if (token) return token.value;
2498
+ const { text, quoted } = this.bareOrQuoted(",)");
2499
+ return quoted ? text : truth(text);
2500
+ }
2501
+ default: {
2502
+ const token = this.token(",)");
2503
+ return token ? token.value : this.bareOrQuoted(",)").text;
2504
+ }
2914
2505
  }
2915
- const match = teams.find((team) => team.id === project.teamId);
2916
- if (match) return match;
2917
2506
  }
2918
- return resolveTeam(context, teams, deps);
2507
+ };
2508
+ function likePattern(pattern) {
2509
+ return pattern.replaceAll("*", "%");
2919
2510
  }
2920
- function scopeDeps(context, canPrompt) {
2921
- return {
2922
- canPrompt: () => canPrompt,
2923
- accountLabel: () => accountLabel(context),
2924
- switchAccount: async () => {
2925
- clearSession();
2926
- await runLogin(context);
2927
- },
2928
- listTeams: async () => (await context.client()).teams.list()
2929
- };
2511
+ function truth(text) {
2512
+ const word = text.toLowerCase();
2513
+ if (word === "true") return true;
2514
+ if (word === "false") return false;
2515
+ return text;
2930
2516
  }
2931
- async function accountLabel(context) {
2932
- try {
2933
- const { user } = await context.auth();
2934
- if (!user) return "this account";
2935
- const name = user.email ?? user.id;
2936
- return user.github ? `${name} (${user.github})` : name;
2937
- } catch {
2938
- return "this account";
2939
- }
2517
+ var DECIMAL = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/;
2518
+ function exactNumber(text) {
2519
+ if (!DECIMAL.test(text)) return text;
2520
+ const number = Number(text);
2521
+ if (!text.includes(".")) return Number.isSafeInteger(number) ? number : text;
2522
+ const trimmed = text.replace(/\.?0+$/, "");
2523
+ return String(number) === trimmed ? number : text;
2940
2524
  }
2941
-
2942
- // src/commands/deployments.ts
2943
- function shortSha(sha) {
2944
- return sha ? sha.slice(0, 7) : "-";
2525
+ function quoteFilterValue(value) {
2526
+ const text = String(value);
2527
+ return `"${text.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
2945
2528
  }
2946
- function formatDeploymentLine(deployment) {
2947
- return [
2948
- deployment.id.padEnd(38),
2949
- deployment.status.padEnd(10),
2950
- deployment.branch.padEnd(16),
2951
- shortSha(deployment.gitCommitSha).padEnd(9),
2952
- deployment.url ?? ""
2953
- ].join(" ");
2529
+ function keyword(text, at) {
2530
+ const word = text.toLowerCase();
2531
+ if (word === "null") return null;
2532
+ if (word === "true") return true;
2533
+ if (word === "false") return false;
2534
+ return refuse(
2535
+ `needs null, true or false after is at character ${String(at + 1)}`
2536
+ );
2954
2537
  }
2955
- async function runDeployments(context) {
2956
- const client = await context.client();
2957
- const projectId = await context.resolveProjectId();
2958
- const deployments = await client.deployments.list(projectId);
2959
- context.output.result({ projectId, deployments }, [
2960
- `Deployments for ${projectId}:`,
2961
- "",
2962
- [
2963
- "ID".padEnd(38),
2964
- "STATUS".padEnd(10),
2965
- "BRANCH".padEnd(16),
2966
- "COMMIT".padEnd(9),
2967
- "URL"
2968
- ].join(" "),
2969
- ...deployments.map(formatDeploymentLine)
2970
- ]);
2538
+ function attempt(parse) {
2539
+ try {
2540
+ return { ok: true, node: parse() };
2541
+ } catch (error) {
2542
+ if (error instanceof Refusal) return { ok: false, reason: error.message };
2543
+ throw error;
2544
+ }
2971
2545
  }
2972
- async function runInspect(context) {
2973
- const [deploymentId] = context.positionalOrThrow(
2974
- 1,
2975
- "Usage: naro inspect <deployment-id>"
2976
- );
2977
- const client = await context.client();
2978
- const detail = await client.deployments.get(deploymentId);
2979
- const { deployment } = detail;
2980
- const lastLogs = detail.logs.slice(-15);
2981
- context.output.result({ deployment, logs: detail.logs }, [
2982
- `Deployment ${deployment.id}`,
2983
- ` status: ${deployment.status}${deployment.errorCode ? ` (${deployment.errorCode})` : ""}`,
2984
- ` branch: ${deployment.branch}`,
2985
- ` commit: ${deployment.gitCommitSha ?? "-"}`,
2986
- ` url: ${deployment.url ?? "-"}`,
2987
- ` created: ${deployment.createdAt}`,
2988
- ` finished: ${deployment.finishedAt ?? "-"}`,
2989
- ...deployment.errorMessage ? [` error: ${deployment.errorMessage}`] : [],
2990
- ...lastLogs.length > 0 ? [
2991
- "",
2992
- "Recent build logs:",
2993
- ...lastLogs.map((log) => ` [${log.stage}] ${log.message}`)
2994
- ] : []
2995
- ]);
2546
+ function parseLogic(text, kind, options = {}) {
2547
+ if (typeof text !== "string")
2548
+ return { ok: false, reason: "must be a filter string or a function" };
2549
+ if (text.trim() === "") return { ok: false, reason: "must not be empty" };
2550
+ return attempt(() => {
2551
+ if (options.group === false) {
2552
+ const alone = items(text, options.tokens, 0);
2553
+ if (alone.length === 1 && alone[0]) return alone[0];
2554
+ }
2555
+ const nodes = items(text, options.tokens, 1);
2556
+ return kind === "or" ? { or: nodes } : { and: nodes };
2557
+ });
2558
+ }
2559
+ function items(text, tokens, level) {
2560
+ const parser = new Parser(text, tokens);
2561
+ const nodes = parser.list(level);
2562
+ if (parser.at() === ")") refuse(`has an unmatched ")" ${parser.where()}`);
2563
+ return nodes;
2996
2564
  }
2997
2565
 
2998
- // src/commands/domains.ts
2999
- var defaults3 = {
3000
- sleep: (ms) => new Promise((resolve5) => setTimeout(resolve5, ms)),
3001
- now: () => Date.now()
2566
+ // src/commands/policy.ts
2567
+ var SET_USAGE = "Usage: naro policy set <table> [--select <rule>] [--insert <rule>] [--update <rule>] [--delete <rule>] [--owner <column>] [--select-when <filter>] [--insert-when <filter>] [--update-when <filter>] [--update-check <filter>] [--delete-when <filter>] [--signed-in] | --from-file <policy.json>";
2568
+ var REMOVE_USAGE = "Usage: naro policy remove <table>";
2569
+ var CREATE_USAGE = 'Usage: naro policy create "CREATE POLICY <name> ON <table> \u2026" | --file <policies.sql>';
2570
+ var DROP_USAGE = "Usage: naro policy drop <name> --table <table>";
2571
+ var TAKES_EFFECT = "It takes effect within about 10 seconds.";
2572
+ var DEFAULT_DENY = "Tables without a policy deny anon and signed-in requests. The service key skips policies.";
2573
+ var RULE_FLAGS = {
2574
+ select: "selectRule",
2575
+ insert: "insertRule",
2576
+ update: "updateRule",
2577
+ delete: "deleteRule"
3002
2578
  };
3003
- var FIRST_DELAY_MS = 5e3;
3004
- var MAX_DELAY_MS = 3e4;
3005
- var WAIT_TIMEOUT_MS = 10 * 6e4;
3006
- function isReady(domain) {
3007
- return domain.ready ?? (domain.status === "active" && domain.sslStatus === "active");
2579
+ var WHEN_FLAGS = {
2580
+ select: { key: "selectWhen", tree: "using" },
2581
+ insert: { key: "insertWhen", tree: "check" },
2582
+ update: { key: "updateWhen", tree: "using" },
2583
+ delete: { key: "deleteWhen", tree: "using" }
2584
+ };
2585
+ var AUTH_UID = "auth.uid()";
2586
+ var OTHER_FLAGS = [
2587
+ "selectRule",
2588
+ "insertRule",
2589
+ "updateRule",
2590
+ "deleteRule",
2591
+ "ownerColumn",
2592
+ "selectWhen",
2593
+ "insertWhen",
2594
+ "updateWhen",
2595
+ "updateCheck",
2596
+ "deleteWhen",
2597
+ "signedIn"
2598
+ ];
2599
+ function isRule(value) {
2600
+ return POLICY_RULES.includes(value);
3008
2601
  }
3009
- function isTerminal(domain) {
3010
- return domain.ownership === "deleted" || domain.status === "blocked" || domain.status === "moved" || domain.status === "deleted";
2602
+ function refuse2(message) {
2603
+ throw new NaroError("VALIDATION_FAILED", message);
3011
2604
  }
3012
- var AXIS_DONE = /* @__PURE__ */ new Set(["verified", "active", "live"]);
3013
- var AXIS_FAILED = /* @__PURE__ */ new Set(["failed", "deleted"]);
3014
- function axisMark(value) {
3015
- if (AXIS_DONE.has(value)) return "\u2713";
3016
- if (AXIS_FAILED.has(value)) return "\u2717";
3017
- return "\xB7";
2605
+ function flagName(key) {
2606
+ return `--${key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`;
3018
2607
  }
3019
- function axisLines(domain) {
3020
- const axes = [
3021
- ["ownership", domain.ownership],
3022
- ["certificate", domain.certificate],
3023
- ["routing", domain.routing]
3024
- ];
3025
- return axes.filter((axis) => axis[1] !== void 0).map(
3026
- ([name, value]) => ` ${`${name}:`.padEnd(13)}${axisMark(value)} ${value}`
3027
- );
2608
+ function conditionTree(flag, text) {
2609
+ const parsed = parseLogic(text, "and", {
2610
+ tokens: { [AUTH_UID]: { auth: "uid" } },
2611
+ group: false
2612
+ });
2613
+ if (!parsed.ok) refuse2(`${flag} ${parsed.reason}.`);
2614
+ const tree = parsed.node;
2615
+ const checked = parsePolicyNode(tree, "");
2616
+ if (!checked.ok) {
2617
+ const path = checked.path.replace(/^\./, "");
2618
+ refuse2(
2619
+ path === "" ? `${flag} ${checked.reason}.` : `${flag}: ${path} ${checked.reason}.`
2620
+ );
2621
+ }
2622
+ return tree;
3028
2623
  }
3029
- function axisSummary(domain) {
3030
- const axes = [
3031
- domain.ownership,
3032
- domain.certificate,
3033
- domain.routing
3034
- ].filter((value) => value !== void 0);
3035
- return axes.length > 0 ? axes.join(" \xB7 ") : `${domain.status} \xB7 ssl ${domain.sslStatus}`;
2624
+ function conditionsFrom(flags) {
2625
+ const conditions = {};
2626
+ for (const action of POLICY_ACTIONS) {
2627
+ const { key, tree } = WHEN_FLAGS[action];
2628
+ const text = flags[key];
2629
+ if (text === void 0) continue;
2630
+ const flag = flagName(key);
2631
+ if (flags[RULE_FLAGS[action]] !== void 0)
2632
+ refuse2(`--${action} and ${flag} cannot be used together.`);
2633
+ const condition = { [tree]: conditionTree(flag, text) };
2634
+ if (action === "update" && flags.updateCheck !== void 0)
2635
+ condition.check = conditionTree("--update-check", flags.updateCheck);
2636
+ if (flags.signedIn) condition.role = "authenticated";
2637
+ conditions[action] = condition;
2638
+ }
2639
+ if (flags.updateCheck !== void 0 && flags.updateWhen === void 0)
2640
+ refuse2("--update-check needs --update-when.");
2641
+ if (flags.signedIn && Object.keys(conditions).length === 0)
2642
+ refuse2(
2643
+ "--signed-in needs --select-when, --insert-when, --update-when or --delete-when."
2644
+ );
2645
+ return conditions;
3036
2646
  }
3037
- function recordLines(domain) {
3038
- const instructions = domain.instructions ?? [];
3039
- if (instructions.length > 0) {
3040
- const lines2 = [" Required DNS records:"];
3041
- for (const instruction of instructions) {
3042
- lines2.push(
3043
- ` ${instruction.type.padEnd(5)} ${instruction.name}`,
3044
- ` host: ${instruction.host.padEnd(24)} value: ${instruction.value}`
2647
+ function patchFromFile(context, path, table) {
2648
+ let text;
2649
+ try {
2650
+ text = readFileSync3(resolve3(context.cwd, path), "utf8");
2651
+ } catch {
2652
+ refuse2(`Could not read ${path}.`);
2653
+ }
2654
+ let body;
2655
+ try {
2656
+ body = JSON.parse(text);
2657
+ } catch {
2658
+ refuse2(`${path} is not JSON.`);
2659
+ }
2660
+ if (typeof body !== "object" || body === null || Array.isArray(body))
2661
+ refuse2(`${path} must hold a JSON object.`);
2662
+ const { table: named, ...fields } = body;
2663
+ const patch = Object.fromEntries(
2664
+ Object.entries(fields).filter(([key]) => key !== "policies")
2665
+ );
2666
+ if (Object.hasOwn(body, "table")) {
2667
+ if (typeof named !== "string")
2668
+ refuse2(`${path}: table must be a string, the table's name.`);
2669
+ if (table !== void 0 && asciiLower(named) !== asciiLower(table))
2670
+ refuse2(
2671
+ `${path} is the policy of ${printable(named)}, not ${printable(table)}. Remove its "table" to set it on ${printable(table)}.`
3045
2672
  );
3046
- if (instruction.note) lines2.push(` note: ${instruction.note}`);
3047
- }
3048
- return lines2;
3049
2673
  }
3050
- if (domain.verification.length === 0) return [];
3051
- const lines = [" Required DNS records:"];
3052
- for (const record of domain.verification) {
3053
- lines.push(
3054
- ` Type: ${record.type.toUpperCase().padEnd(6)} Name: ${record.name}`,
3055
- ` Value: ${record.value}`
2674
+ const allowed = /* @__PURE__ */ new Set([...POLICY_ACTIONS, "ownerColumn"]);
2675
+ if (Object.keys(patch).some((key) => !allowed.has(key)))
2676
+ refuse2(
2677
+ `${path}: Only table, select, insert, update, delete and ownerColumn can be set.`
3056
2678
  );
3057
- }
3058
- return lines;
2679
+ return patch;
3059
2680
  }
3060
- function domainLines(domain) {
3061
- const lines = [
3062
- ` ${domain.hostname.padEnd(36)} ${domain.status.padEnd(12)} ssl: ${domain.sslStatus}`,
3063
- ...axisLines(domain)
3064
- ];
3065
- if (domain.redirectTo) {
3066
- const status = domain.redirectStatus ?? 308;
3067
- lines.push(` redirects to ${domain.redirectTo} (${String(status)})`);
2681
+ function asciiLower(text) {
2682
+ return text.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
2683
+ }
2684
+ function policyPatch(flags, context, table) {
2685
+ if (flags.fromFile !== void 0) {
2686
+ if (OTHER_FLAGS.some(
2687
+ (key) => flags[key] !== void 0 && flags[key] !== false
2688
+ ))
2689
+ refuse2(
2690
+ "--from-file takes the whole policy: leave out the other policy options."
2691
+ );
2692
+ if (!context) refuse2(SET_USAGE);
2693
+ return patchFromFile(context, flags.fromFile, table);
3068
2694
  }
3069
- if (domain.cause) {
3070
- lines.push(` \u2717 ${domain.cause.message}`);
3071
- if (domain.cause.fix) lines.push(` \u2192 ${domain.cause.fix}`);
2695
+ const patch = {};
2696
+ for (const action of POLICY_ACTIONS) {
2697
+ const value = flags[RULE_FLAGS[action]];
2698
+ if (value === void 0) continue;
2699
+ if (!isRule(value))
2700
+ refuse2(`--${action} must be one of ${POLICY_RULES.join(", ")}.`);
2701
+ patch[action] = value;
3072
2702
  }
3073
- if (isReady(domain)) return lines;
3074
- lines.push(...recordLines(domain));
3075
- const guidance = domain.guidance;
3076
- if (guidance && guidance.notes.length > 0) {
3077
- lines.push(
3078
- guidance.apex ? ` Apex domain (${domain.hostname}):` : " Note:"
3079
- );
3080
- for (const note of guidance.notes) lines.push(` ${note}`);
2703
+ Object.assign(patch, conditionsFrom(flags));
2704
+ if (flags.ownerColumn !== void 0) {
2705
+ if (flags.ownerColumn.trim() === "") refuse2("--owner must name a column.");
2706
+ patch.ownerColumn = flags.ownerColumn;
3081
2707
  }
3082
- return lines;
2708
+ if (Object.keys(patch).length === 0)
2709
+ refuse2(
2710
+ `Set at least one of --select, --insert, --update, --delete, --owner, --select-when, --insert-when, --update-when, --delete-when or --from-file. ${SET_USAGE}`
2711
+ );
2712
+ return patch;
3083
2713
  }
3084
- async function runDomainsList(context) {
3085
- const client = await context.client();
3086
- const projectId = await context.resolveProjectId();
3087
- const domains = await client.domains.list(projectId);
3088
- const pending = domains.filter((domain) => !isReady(domain));
3089
- context.output.result(
3090
- { projectId, domains },
3091
- domains.length === 0 ? ["No custom domains. Add one with `naro domains add example.com`."] : [
3092
- `Domains (${String(domains.length)}):`,
3093
- ...domains.flatMap(domainLines),
3094
- // list reads our stored copy; only verify goes and looks again.
3095
- ...pending.length > 0 ? ["", "Re-check DNS now: naro domains verify"] : []
3096
- ]
3097
- );
2714
+ var SHORT = {
2715
+ contains: "cs",
2716
+ containedBy: "cd",
2717
+ overlaps: "ov"
2718
+ };
2719
+ function isAuthUid(value) {
2720
+ return typeof value === "object" && value !== null && value.auth === "uid";
3098
2721
  }
3099
- async function runDomainsAdd(context) {
3100
- const [hostname] = context.positionalOrThrow(
3101
- 1,
3102
- "Usage: naro domains add <hostname> [--no-www]"
3103
- );
3104
- const client = await context.client();
3105
- const projectId = await context.resolveProjectId();
3106
- const withWww = context.flags.noWww !== true;
3107
- const domain = await client.domains.add(projectId, hostname, {
3108
- withWww
3109
- });
3110
- const companion = domain.companion;
3111
- const apex = domain.apex ?? domain.guidance?.apex ?? false;
3112
- const alternative = domain.guidance?.alternative ?? `www.${domain.hostname}`;
3113
- context.output.result(
3114
- { projectId, domain, withWww, ...companion ? { companion } : {} },
3115
- [
3116
- `\u2705 Domain added: ${domain.hostname}`,
3117
- "",
3118
- ...domainLines(domain),
3119
- ...companion ? [
3120
- "",
3121
- ` Also registered ${companion.hostname} \u2014 an apex domain often cannot hold`,
3122
- " the CNAME above, and this form always can.",
3123
- "",
3124
- ...domainLines(companion)
3125
- ] : [],
3126
- ...!companion && apex && !withWww ? [
3127
- "",
3128
- ` --no-www: ${domain.hostname} was registered on its own. If your registrar`,
3129
- ` refuses the record above, run \`naro domains add ${alternative}\`.`
3130
- ] : [],
3131
- "",
3132
- isReady(domain) ? "The domain is active." : "Status: Pending verification \u2014 add the DNS records above, then run `naro domains verify`."
3133
- ]
3134
- );
2722
+ function nearAuthUid(text) {
2723
+ return text.replace(/\s+/g, "").toLowerCase().replace(/\(\)$/, "") === "auth.uid";
3135
2724
  }
3136
- async function verifyAll(client, projectId, hostname, auto = false) {
3137
- if (hostname !== void 0)
3138
- return [
3139
- await client.domains.verifyByHostname(projectId, hostname, { auto })
3140
- ];
3141
- const listed = await client.domains.list(projectId);
3142
- const verified = [];
3143
- for (const domain of listed)
3144
- verified.push(await client.domains.verify(projectId, domain.id, { auto }));
3145
- return verified;
2725
+ var DECIMAL2 = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/;
2726
+ function readsAsNumber(value) {
2727
+ const text = String(value);
2728
+ if (!DECIMAL2.test(text) || !Object.is(Number(text), value)) return false;
2729
+ return text.includes(".") || Number.isSafeInteger(value);
2730
+ }
2731
+ function stringText(value, slot) {
2732
+ if (slot === "is") return void 0;
2733
+ if (slot === "like" && value.includes("*")) return void 0;
2734
+ const bare = value !== "" && value.trim() === value && !/[,()"{}\\]/.test(value) && !/^(?:true|false|null)$/i.test(value) && !nearAuthUid(value) && !(slot === "array" && DECIMAL2.test(value));
2735
+ return bare ? value : quoteFilterValue(value);
2736
+ }
2737
+ function valueText(value, slot) {
2738
+ if (isAuthUid(value))
2739
+ return slot === "like" || slot === "is" ? void 0 : AUTH_UID;
2740
+ if (value === null) return slot === "is" ? "null" : void 0;
2741
+ if (typeof value === "boolean")
2742
+ return slot === "is" || slot === "eq" || slot === "in" ? String(value) : void 0;
2743
+ if (typeof value === "number")
2744
+ return slot === "array" && readsAsNumber(value) ? String(value) : void 0;
2745
+ if (typeof value === "string") return stringText(value, slot);
2746
+ return void 0;
2747
+ }
2748
+ function columnText(name) {
2749
+ if (name === "") return void 0;
2750
+ return /[.,()"\s]/.test(name) ? quoteFilterValue(name) : name;
2751
+ }
2752
+ function slotOf(operator) {
2753
+ if (operator === "eq" || operator === "neq") return "eq";
2754
+ if (operator === "like" || operator === "ilike") return "like";
2755
+ if (operator === "is") return "is";
2756
+ return "ordered";
3146
2757
  }
3147
- async function runDomainsVerify(context, overrides = {}) {
3148
- const deps = { ...defaults3, ...overrides };
3149
- const client = await context.client();
3150
- const projectId = await context.resolveProjectId();
3151
- const hostname = context.positionals[0];
3152
- const wait = context.flags.wait === true;
3153
- const progress = (line) => {
3154
- if (!context.flags.json) context.output.log(line);
3155
- };
3156
- let domains = await verifyAll(client, projectId, hostname);
3157
- if (domains.length === 0) {
3158
- context.output.result({ projectId, domains, ready: false }, [
3159
- "No custom domains. Add one with `naro domains add example.com`."
3160
- ]);
3161
- return;
2758
+ function leafText(leaf, negated) {
2759
+ const column = columnText(leaf.column);
2760
+ if (column === void 0) return void 0;
2761
+ const prefix = `${column}.${negated ? "not." : ""}`;
2762
+ const short = SHORT[leaf.operator];
2763
+ if (leaf.operator === "in" || short !== void 0) {
2764
+ if (!Array.isArray(leaf.value)) return void 0;
2765
+ const slot = short === void 0 ? "in" : "array";
2766
+ const items2 = leaf.value.map((item) => valueText(item, slot));
2767
+ if (items2.some((item) => item === void 0)) return void 0;
2768
+ const list = items2.join(",");
2769
+ return slot === "in" ? `${prefix}in.(${list})` : `${prefix}${String(short)}.{${list}}`;
3162
2770
  }
3163
- let timedOut = false;
3164
- let abandoned = false;
3165
- if (wait && !domains.every(isReady)) {
3166
- const deadline = deps.now() + WAIT_TIMEOUT_MS;
3167
- let delay = FIRST_DELAY_MS;
3168
- for (; ; ) {
3169
- const pending = domains.filter((domain) => !isReady(domain));
3170
- if (pending.length > 0 && pending.every(isTerminal)) {
3171
- abandoned = true;
3172
- break;
3173
- }
3174
- const remaining = deadline - deps.now();
3175
- if (remaining <= 0) {
3176
- timedOut = true;
3177
- break;
3178
- }
3179
- for (const domain of pending)
3180
- progress(
3181
- isTerminal(domain) ? `\u26A0 ${domain.hostname}: ${axisSummary(domain)} \u2014 waiting cannot fix this one` : `\u25B8 ${domain.hostname}: ${axisSummary(domain)}`
3182
- );
3183
- await deps.sleep(Math.min(delay, remaining));
3184
- delay = Math.min(delay * 2, MAX_DELAY_MS);
3185
- domains = await verifyAll(client, projectId, hostname, true);
3186
- if (domains.every(isReady)) break;
3187
- }
2771
+ if (Array.isArray(leaf.value)) return void 0;
2772
+ const text = valueText(leaf.value, slotOf(leaf.operator));
2773
+ return text === void 0 ? void 0 : `${prefix}${leaf.operator}.${text}`;
2774
+ }
2775
+ function groupText(kind, children) {
2776
+ const texts = children.map((child) => filterText(child, false));
2777
+ if (texts.length === 0 || texts.some((text) => text === void 0))
2778
+ return void 0;
2779
+ return `${kind}(${texts.join(",")})`;
2780
+ }
2781
+ function filterText(node, top = true) {
2782
+ if ("operator" in node) return leafText(node, false);
2783
+ if ("not" in node) {
2784
+ const inner = node.not;
2785
+ if ("operator" in inner) return leafText(inner, true);
2786
+ if ("or" in inner) return negatedText(groupText("or", inner.or));
2787
+ if ("and" in inner) return negatedText(groupText("and", inner.and));
2788
+ return void 0;
3188
2789
  }
3189
- const ready = domains.every(isReady);
3190
- const body = domains.flatMap(domainLines);
3191
- if (!ready) {
3192
- for (const line of body) progress(line);
3193
- const notReady = domains.filter((domain) => !isReady(domain));
3194
- const names = notReady.map((domain) => domain.hostname).join(", ");
3195
- const details = { projectId, domains, ready: false };
3196
- if (timedOut) {
3197
- const cause2 = notReady[0]?.cause;
3198
- throw new NaroError(
3199
- "TIMEOUT",
3200
- `${names} did not go live within 10 minutes.${cause2 ? ` ${cause2.message}` : ""} DNS changes can take longer to propagate \u2014 re-run \`naro domains verify\` later.`,
3201
- { details }
3202
- );
3203
- }
3204
- if (abandoned) {
3205
- const blocked = domains.find(isTerminal);
3206
- throw new NaroError(
3207
- blocked?.cause?.code ?? "DOMAIN_VERIFICATION_FAILED",
3208
- blocked?.cause?.message ?? `${names} cannot be verified (status: ${blocked?.status ?? "unknown"}). Remove it and add it again.`,
3209
- { details }
3210
- );
3211
- }
3212
- const cause = notReady[0]?.cause;
3213
- throw new NaroError(
3214
- cause?.code ?? "DOMAIN_NOT_READY",
3215
- `${names} is not live yet.${cause ? ` ${cause.message}` : ""} Add the records above, then run \`naro domains verify --wait\`.`,
3216
- { details }
3217
- );
2790
+ if ("or" in node) return groupText("or", node.or);
2791
+ if (top && node.and.length > 1) {
2792
+ const texts = node.and.map((child) => filterText(child, false));
2793
+ return texts.some((text) => text === void 0) ? void 0 : texts.join(",");
3218
2794
  }
3219
- context.output.result({ projectId, domains, ready }, [
3220
- ...body,
3221
- "",
3222
- domains.length === 1 ? `\u2705 ${domains[0]?.hostname ?? ""} is live.` : "\u2705 Every domain is live."
3223
- ]);
2795
+ return groupText("and", node.and);
3224
2796
  }
3225
- async function runDomainsRemove(context) {
3226
- const [hostname] = context.positionalOrThrow(
3227
- 1,
3228
- "Usage: naro domains remove <hostname>"
2797
+ function negatedText(text) {
2798
+ return text === void 0 ? void 0 : `not.${text}`;
2799
+ }
2800
+ function isInvalid(value) {
2801
+ return typeof value === "object" && "invalid" in value;
2802
+ }
2803
+ function cellOf(value) {
2804
+ if (typeof value === "string") return value;
2805
+ return isInvalid(value) ? "invalid" : "condition";
2806
+ }
2807
+ function conditionText(action, value) {
2808
+ if (typeof value === "string") return value;
2809
+ if (isInvalid(value))
2810
+ return `cannot be read (${value.invalid}); it denies everyone but the service key`;
2811
+ const using = value.using ? filterText(value.using) : "";
2812
+ const check = value.check ? filterText(value.check) : "";
2813
+ if (using === void 0 || check === void 0)
2814
+ return `as JSON ${JSON.stringify(value)}`;
2815
+ const parts = [];
2816
+ if (using !== "") parts.push(`using ${using}`);
2817
+ if (check !== "") parts.push(`check ${check}`);
2818
+ else if (action === "update") parts.push("check = using");
2819
+ const text = parts.join("; ");
2820
+ return value.role === "authenticated" ? `${text} (signed-in users only)` : text;
2821
+ }
2822
+ function policyTable(policies) {
2823
+ const header = ["Table", ...POLICY_ACTIONS, "Owner column"];
2824
+ const rows = policies.map((policy) => [
2825
+ printable(policy.table),
2826
+ ...POLICY_ACTIONS.map((action) => cellOf(policy[action])),
2827
+ policy.ownerColumn === null ? "-" : printable(policy.ownerColumn)
2828
+ ]);
2829
+ const widths = header.map(
2830
+ (title, index) => Math.max(title.length, ...rows.map((row) => row[index]?.length ?? 0))
3229
2831
  );
3230
- await confirmOrAbort(
3231
- context,
3232
- `Remove ${String(hostname)}? Traffic to it will stop routing here.`
2832
+ const table = [header, ...rows].map(
2833
+ (cells) => cells.map(
2834
+ (cell, index) => index === cells.length - 1 ? cell : cell.padEnd(widths[index] ?? 0)
2835
+ ).join(" ").trimEnd()
3233
2836
  );
3234
- const client = await context.client();
3235
- const projectId = await context.resolveProjectId();
3236
- await client.domains.remove(projectId, hostname);
3237
- context.output.result({ projectId, hostname, removed: true }, [
3238
- `\u2705 Removed ${String(hostname)}`
3239
- ]);
2837
+ const lines = policies.flatMap(
2838
+ (policy) => POLICY_ACTIONS.filter((action) => typeof policy[action] !== "string").map(
2839
+ (action) => {
2840
+ const value = policy[action];
2841
+ const text = conditionText(action, value);
2842
+ return {
2843
+ label: `${printable(policy.table)}.${action}`,
2844
+ text: isInvalid(value) || isPrintable(text) ? printable(text) : `${UNSHOWN}: naro policy list --json has the exact text`
2845
+ };
2846
+ }
2847
+ )
2848
+ );
2849
+ if (lines.length === 0) return table;
2850
+ const width = Math.max(...lines.map((line) => line.label.length));
2851
+ return [
2852
+ ...table,
2853
+ "",
2854
+ ...lines.map((line) => `${line.label.padEnd(width)} ${line.text}`)
2855
+ ];
3240
2856
  }
3241
-
3242
- // src/commands/env.ts
3243
- import { existsSync, writeFileSync as writeFileSync4 } from "fs";
3244
- import { join as join4 } from "path";
3245
- var TARGETS = /* @__PURE__ */ new Set(["production", "preview", "all"]);
3246
- var KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
3247
- function parseTarget(value) {
3248
- if (value === void 0) return "all";
3249
- if (!TARGETS.has(value))
3250
- throw new NaroError(
3251
- "VALIDATION_FAILED",
3252
- "Environment must be production, preview or all."
2857
+ var UNSHOWN = "has characters that cannot be shown here";
2858
+ function statementLine(policy) {
2859
+ if (policy.invalid !== null)
2860
+ return printable(
2861
+ `-- ${policyNamed(policy.name, policy.table)} cannot be read (${commentText(policy.invalid)}); the requests it applies to are refused until it is dropped or created again.`
3253
2862
  );
3254
- return value;
2863
+ return shownStatement(policy, policy.table, "naro policy list --json");
3255
2864
  }
3256
- function maskedValue(row) {
3257
- if (!row.isSecret) return row.value ?? "";
3258
- return "\u2022\u2022\u2022\u2022\u2022\u2022 (secret)";
2865
+ function policyNamed(name, table) {
2866
+ return `Policy ${commentText(quotePolicyName(name))} on ${commentText(quoteIdent(table))}`;
3259
2867
  }
3260
- async function runEnvList(context) {
2868
+ function shownStatement(statement, table, exact) {
2869
+ if (isPrintable(statement.sql)) return statement.sql;
2870
+ return printable(
2871
+ `-- ${policyNamed(statement.name, table)} ${UNSHOWN}, so it is not printed as CREATE POLICY: ${exact} has its exact text.`
2872
+ );
2873
+ }
2874
+ function policyStatements(policies) {
2875
+ const lines = [];
2876
+ let table;
2877
+ for (const policy of policies) {
2878
+ if (table !== void 0 && policy.table !== table) lines.push("");
2879
+ table = policy.table;
2880
+ lines.push(statementLine(policy));
2881
+ }
2882
+ return lines;
2883
+ }
2884
+ async function runPolicyList(context) {
2885
+ const table = context.flags.table;
3261
2886
  const client = await context.client();
3262
2887
  const projectId = await context.resolveProjectId();
3263
- const reveal = context.flags.reveal;
3264
- const rows = await client.env.list(projectId, { reveal });
3265
- context.output.result(
3266
- {
3267
- projectId,
3268
- envVars: rows.map((row) => ({
3269
- id: row.id,
3270
- key: row.key,
3271
- target: row.target,
3272
- isSecret: row.isSecret,
3273
- value: row.isSecret && !reveal ? null : row.value
3274
- }))
3275
- },
3276
- [
3277
- `Environment variables (${String(rows.length)}):`,
3278
- ...rows.map(
3279
- (row) => ` ${row.key.padEnd(32)} ${row.target.padEnd(12)} ${reveal ? row.value ?? "" : maskedValue(row)}`
3280
- )
3281
- ]
2888
+ const policies = await client.backend.rlsPolicies(
2889
+ projectId,
2890
+ table === void 0 ? {} : { table }
3282
2891
  );
2892
+ let lines;
2893
+ if (policies.length > 0)
2894
+ lines = [...policyStatements(policies), "", DEFAULT_DENY];
2895
+ else if (table !== void 0)
2896
+ lines = [
2897
+ `No policies on ${printable(table)}: anon and signed-in requests to it are denied.`
2898
+ ];
2899
+ else
2900
+ lines = [
2901
+ "No policies yet: every table denies anon and signed-in requests.",
2902
+ 'Add one with `naro policy create "CREATE POLICY \u2026"` or `naro policy set <table> --select public`.'
2903
+ ];
2904
+ context.output.result({ projectId, policies }, lines);
2905
+ }
2906
+ function statementText(context) {
2907
+ const [positional] = context.positionals;
2908
+ const file = context.flags.file;
2909
+ if (positional !== void 0 && file !== void 0)
2910
+ refuse2(`Give the statement or --file, not both. ${CREATE_USAGE}`);
2911
+ let text = positional;
2912
+ if (file !== void 0) {
2913
+ try {
2914
+ text = readFileSync3(resolve3(context.cwd, file), "utf8");
2915
+ } catch {
2916
+ refuse2(`Could not read ${file}.`);
2917
+ }
2918
+ }
2919
+ if (text === void 0 || text.trim() === "") refuse2(CREATE_USAGE);
2920
+ return text;
3283
2921
  }
3284
- async function runEnvAdd(context) {
3285
- context.positionalOrThrow(
3286
- 1,
3287
- "Usage: naro env add KEY [production|preview|all]"
3288
- );
3289
- const [key, targetArg] = context.positionals;
3290
- if (!key || !KEY_RE.test(key) || key.length > 256)
3291
- throw new NaroError(
3292
- "VALIDATION_FAILED",
3293
- "Keys must look like MY_VARIABLE (letters, digits, underscore)."
2922
+ function policyStatementsOf(text) {
2923
+ const split = splitPolicyStatements(text);
2924
+ if (!split.ok)
2925
+ refuse2(`${split.reason} at character ${String(split.position)}.`);
2926
+ const { statements } = split;
2927
+ if (statements.length === 0) refuse2(CREATE_USAGE);
2928
+ statements.forEach((statement, index) => {
2929
+ const parsed = parsePolicyStatement(statement);
2930
+ if (parsed.ok) return;
2931
+ const where = `${parsed.reason} at character ${String(parsed.position)}.`;
2932
+ refuse2(
2933
+ statements.length === 1 ? where : `Statement ${String(index + 1)} of ${String(statements.length)}: ${where} Nothing was sent.`
3294
2934
  );
3295
- const target = parseTarget(targetArg);
3296
- let value;
3297
- if (!process.stdin.isTTY) {
3298
- value = await readStdin();
3299
- } else {
3300
- value = await context.prompter.askHidden(`? What's the value of ${key}? `);
2935
+ });
2936
+ return statements;
2937
+ }
2938
+ function resultLine(result) {
2939
+ if ("created" in result)
2940
+ return `\u2705 Created policy ${printable(result.created.name)} on ${printable(result.created.table)}.`;
2941
+ if (result.dropped === null)
2942
+ return "Nothing to drop: no such policy (IF EXISTS).";
2943
+ return `\u2705 Dropped policy ${printable(result.dropped.name)} on ${printable(result.dropped.table)}.`;
2944
+ }
2945
+ async function runStatements(client, projectId, statements, allowUnindexed) {
2946
+ const applied = [];
2947
+ for (const [index, statement] of statements.entries()) {
2948
+ try {
2949
+ applied.push(
2950
+ await client.backend.runPolicySql(
2951
+ projectId,
2952
+ statement,
2953
+ allowUnindexed ? { allowUnindexed } : {}
2954
+ )
2955
+ );
2956
+ } catch (error) {
2957
+ if (!isNaroError(error) || statements.length === 1) throw error;
2958
+ let before = "Nothing ran.";
2959
+ if (index === 1)
2960
+ before = "Statement 1 ran and stays; the rest were not sent.";
2961
+ else if (index > 1)
2962
+ before = `Statements 1\u2013${String(index)} ran and stay; the rest were not sent.`;
2963
+ throw new NaroError(
2964
+ error.code,
2965
+ `Statement ${String(index + 1)} of ${String(statements.length)}: ${error.message} ${before}`,
2966
+ {
2967
+ ...error.status === void 0 ? {} : { status: error.status },
2968
+ details: { ...error.details, applied },
2969
+ cause: error
2970
+ }
2971
+ );
2972
+ }
3301
2973
  }
3302
- if (value.length === 0)
3303
- throw new NaroError("VALIDATION_FAILED", `No value provided for ${key}.`);
3304
- const isSecret = !key.startsWith("NEXT_PUBLIC_");
2974
+ return applied;
2975
+ }
2976
+ async function runPolicyCreate(context) {
2977
+ const statements = policyStatementsOf(statementText(context));
3305
2978
  const client = await context.client();
3306
2979
  const projectId = await context.resolveProjectId();
3307
- await client.env.set(projectId, [{ key, value, target, isSecret }]);
3308
- context.output.result({ projectId, key, target, isSecret }, [
3309
- `\u2705 Added ${key} (${target}${isSecret ? ", secret" : ""})`
2980
+ const applied = await runStatements(
2981
+ client,
2982
+ projectId,
2983
+ statements,
2984
+ context.flags.allowUnindexed === true
2985
+ );
2986
+ context.output.result({ projectId, applied }, [
2987
+ ...applied.map(resultLine),
2988
+ applied.length === 1 ? TAKES_EFFECT : "They take effect within about 10 seconds."
3310
2989
  ]);
3311
2990
  }
3312
- async function runEnvRemove(context) {
3313
- context.positionalOrThrow(
3314
- 1,
3315
- "Usage: naro env remove KEY [production|preview|all]"
3316
- );
3317
- const [key, targetArg] = context.positionals;
3318
- const target = targetArg === void 0 ? void 0 : parseTarget(targetArg);
2991
+ async function runPolicyDrop(context) {
2992
+ const [name] = context.positionalOrThrow(1, DROP_USAGE);
2993
+ const table = context.flags.table;
2994
+ if (table === void 0 || table === "") refuse2(DROP_USAGE);
3319
2995
  await confirmOrAbort(
3320
2996
  context,
3321
- `Remove ${String(key)}${target ? ` (${target})` : ""} from this project?`
2997
+ `Drop policy ${printable(name)} on ${printable(table)}? It stops applying within about 10 seconds.`
3322
2998
  );
3323
2999
  const client = await context.client();
3324
3000
  const projectId = await context.resolveProjectId();
3325
- const removed = await client.env.remove(projectId, key, target);
3326
- context.output.result({ projectId, key, removed }, [
3327
- `\u2705 Removed ${String(key)} (${String(removed)} entr${removed === 1 ? "y" : "ies"})`
3001
+ const dropped = await client.backend.dropRlsPolicy(
3002
+ projectId,
3003
+ table,
3004
+ name
3005
+ );
3006
+ context.output.result({ projectId, dropped }, [
3007
+ `\u2705 Dropped policy ${printable(dropped.name)} on ${printable(dropped.table)}. It stops applying within about 10 seconds.`
3328
3008
  ]);
3329
3009
  }
3330
- async function runEnvPull(context) {
3331
- const file = context.positionals[0] ?? ".env.local";
3332
- const surface = context.flags.env === "production" ? "production" : "preview";
3333
- if (context.flags.env && !["production", "preview"].includes(context.flags.env))
3334
- throw new NaroError(
3335
- "VALIDATION_FAILED",
3336
- "--env must be production or preview."
3337
- );
3010
+ async function runPolicySet(context) {
3011
+ const [table] = context.positionalOrThrow(1, SET_USAGE);
3012
+ const patch = policyPatch(context.flags, context, table);
3338
3013
  const client = await context.client();
3339
3014
  const projectId = await context.resolveProjectId();
3340
- const rows = await client.env.list(projectId, { reveal: true });
3341
- const selected = rows.filter(
3342
- (row) => row.target === "all" || row.target === surface
3343
- );
3344
- const vars = Object.fromEntries(
3345
- selected.map((row) => [row.key, row.value ?? ""])
3015
+ const policy = await client.backend.setPolicy(
3016
+ projectId,
3017
+ table,
3018
+ patch
3346
3019
  );
3347
- const path = join4(context.cwd, file);
3348
- if (existsSync(path) && isInteractive() && !context.flags.yes && !context.flags.json) {
3349
- const confirmed = await context.prompter.confirm(`Overwrite ${file}?`);
3350
- if (!confirmed) throw new NaroError("CANCELED", "Canceled.");
3020
+ let named;
3021
+ try {
3022
+ named = await client.backend.rlsPolicies(projectId, {
3023
+ table: policy.table
3024
+ });
3025
+ } catch (error) {
3026
+ if (!isNaroError(error)) throw error;
3351
3027
  }
3352
- writeFileSync4(
3353
- path,
3354
- `# Pulled from Naro (${surface}) \u2014 do not commit secrets.
3355
- ${serializeDotenv(vars)}`,
3356
- { mode: 384 }
3357
- );
3358
3028
  context.output.result(
3359
- { projectId, file, environment: surface, count: selected.length },
3360
- [`\u2705 Pulled ${String(selected.length)} variable(s) into ${file}`]
3029
+ { projectId, policy, ...named === void 0 ? {} : { policies: named } },
3030
+ [
3031
+ `\u2705 Saved the policy for ${printable(policy.table)}. ${TAKES_EFFECT}`,
3032
+ ...policyTable([policy]),
3033
+ ...named === void 0 || named.length === 0 ? [] : ["", ...policyStatements(named)]
3034
+ ]
3361
3035
  );
3362
3036
  }
3363
-
3364
- // src/commands/gen.ts
3365
- import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync5 } from "fs";
3366
- import { dirname as dirname2, resolve as resolve3 } from "path";
3367
- var LANG_MESSAGE = "naro gen types writes TypeScript only. Pass --lang typescript, or leave --lang out.";
3368
- async function runGenTypes(context) {
3369
- const { lang } = context.flags;
3370
- if (lang !== void 0 && lang !== "typescript")
3371
- throw new NaroError("VALIDATION_FAILED", LANG_MESSAGE);
3037
+ async function runPolicyRemove(context) {
3038
+ const [table] = context.positionalOrThrow(1, REMOVE_USAGE);
3039
+ await confirmOrAbort(
3040
+ context,
3041
+ `Remove every policy on ${printable(table)}? Anon and signed-in requests to it are denied from then on.`
3042
+ );
3372
3043
  const client = await context.client();
3373
3044
  const projectId = await context.resolveProjectId();
3374
- const tables = await client.db.tables(projectId);
3375
- const read = await policiesForTypes(client, projectId);
3376
- const types = generateTypes(
3377
- tables,
3378
- read.policies === void 0 ? {} : { policies: read.policies }
3379
- );
3380
- const undescribed = tables.flatMap(
3381
- (table) => table.error === void 0 ? [] : [{ name: table.name, error: table.error }]
3382
- );
3383
- for (const { name, error } of undescribed)
3384
- context.output.warn(
3385
- `\u26A0 ${printable(name)} could not be described and was generated as an empty interface: ${printable(error)}`
3386
- );
3387
- if (read.policies === void 0)
3388
- context.output.warn(
3389
- `\u26A0 The backend's policies could not be read (${printable(read.reason)}), so owner columns stay required in Insert.`
3390
- );
3391
- const extra = {
3392
- ...undescribed.length > 0 ? { undescribed } : {},
3393
- ...read.policies === void 0 ? { policies: "unavailable", policiesReason: read.reason } : {}
3394
- };
3395
- if (context.flags.output) {
3396
- const path = resolve3(context.cwd, context.flags.output);
3397
- mkdirSync4(dirname2(path), { recursive: true });
3398
- writeFileSync5(path, types);
3399
- context.output.result(
3400
- {
3401
- projectId,
3402
- output: context.flags.output,
3403
- tables: tables.length,
3404
- ...extra
3405
- },
3406
- [
3407
- `\u2705 Wrote types for ${String(tables.length)} table(s) to ${context.flags.output}`
3408
- ]
3409
- );
3410
- return;
3411
- }
3412
- context.output.result({ projectId, types, ...extra }, [
3413
- types.replace(/\n$/, "")
3045
+ const policy = await client.backend.removePolicy(projectId, table);
3046
+ const names = policy.policies ?? [];
3047
+ context.output.result({ projectId, removed: true, policy }, [
3048
+ names.length === 0 ? `\u2705 Removed the policy for ${printable(policy.table)}. Anon and signed-in requests to it are denied within about 10 seconds.` : `\u2705 Removed ${names.length === 1 ? "policy" : "policies"} ${names.map(printable).join(", ")} on ${printable(policy.table)}. Anon and signed-in requests to it are denied within about 10 seconds.`
3414
3049
  ]);
3415
3050
  }
3416
3051
 
3417
- // src/commands/logs.ts
3418
- var FOLLOW_INTERVAL_MS = 3e3;
3419
- function sleep(ms) {
3420
- return new Promise((resolve5) => setTimeout(resolve5, ms));
3421
- }
3422
- function formatBuildLog(log) {
3423
- return `[${log.stage}] ${log.level === "ERROR" ? "\u2717 " : ""}${log.message}`;
3052
+ // src/commands/db-schema.ts
3053
+ var USAGE2 = {
3054
+ table: "Usage: naro db table create|add-column|rename-column|rename|drop-column|drop \u2026 (see naro help)",
3055
+ index: "Usage: naro db index create|drop \u2026 (see naro help)",
3056
+ create: "Usage: naro db table create <name> --column <spec> [--column <spec>\u2026] [--owner <column>] [--if-not-exists]",
3057
+ addColumn: "Usage: naro db table add-column <table> --column <spec>",
3058
+ renameColumn: "Usage: naro db table rename-column <table> <column> <new-name>",
3059
+ rename: "Usage: naro db table rename <table> <new-name>",
3060
+ dropColumn: "Usage: naro db table drop-column <table> <column>",
3061
+ drop: "Usage: naro db table drop <table>",
3062
+ indexCreate: "Usage: naro db index create <table> <column[,column\u2026]> [--unique] [--name <name>]",
3063
+ indexDrop: "Usage: naro db index drop <name>"
3064
+ };
3065
+ var SPEC_USAGE = '--column needs name:type, e.g. --column "title:text:notnull".';
3066
+ var ON_DELETE = {
3067
+ cascade: "CASCADE",
3068
+ "set-null": "SET NULL",
3069
+ "set-default": "SET DEFAULT",
3070
+ restrict: "RESTRICT",
3071
+ "no-action": "NO ACTION"
3072
+ };
3073
+ var KEYWORDS = /* @__PURE__ */ new Set(["CURRENT_TIMESTAMP", "CURRENT_DATE", "CURRENT_TIME"]);
3074
+ var NUMBER = /^-?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
3075
+ function segments(spec) {
3076
+ const parts = [];
3077
+ let current = "";
3078
+ let quoted = false;
3079
+ for (const char of spec) {
3080
+ if (char === "'") quoted = !quoted;
3081
+ if (char === ":" && !quoted) {
3082
+ parts.push(current);
3083
+ current = "";
3084
+ continue;
3085
+ }
3086
+ current += char;
3087
+ }
3088
+ if (quoted) return null;
3089
+ parts.push(current);
3090
+ return parts;
3424
3091
  }
3425
- function formatRuntimeLog(entry) {
3426
- const time = new Date(entry.ts).toISOString();
3427
- const request = entry.method && entry.path ? ` ${entry.method} ${entry.path}${entry.status ? ` ${String(entry.status)}` : ""}` : "";
3428
- return `${time} [${entry.level}]${request} ${entry.message}`.trimEnd();
3092
+ function defaultValue(text) {
3093
+ if (text.length >= 2 && text.startsWith("'") && text.endsWith("'"))
3094
+ return text.slice(1, -1).replace(/''/g, "'");
3095
+ const lower = text.toLowerCase();
3096
+ if (lower === "null") return null;
3097
+ if (lower === "true") return true;
3098
+ if (lower === "false") return false;
3099
+ const upper = text.toUpperCase();
3100
+ if (KEYWORDS.has(upper)) return { keyword: upper };
3101
+ if (NUMBER.test(text)) return Number(text);
3102
+ return text;
3429
3103
  }
3430
- async function latestProductionDeploymentId(client, projectId) {
3431
- const deployments = await client.deployments.list(projectId);
3432
- const latest = deployments.find(
3433
- (deployment) => deployment.status === "READY"
3434
- );
3435
- const fallback = deployments[0];
3436
- const chosen = latest ?? fallback;
3437
- if (!chosen)
3104
+ function parseColumnSpec(spec) {
3105
+ const shown = `--column "${printable(spec)}"`;
3106
+ const parts = segments(spec);
3107
+ if (parts === null)
3438
3108
  throw new NaroError(
3439
- "DEPLOYMENT_NOT_FOUND",
3440
- "This project has no deployments yet."
3441
- );
3442
- return chosen.id;
3443
- }
3444
- async function buildLogs(context, client, deploymentId) {
3445
- if (!context.flags.follow) {
3446
- const detail = await client.deployments.get(deploymentId);
3447
- context.output.result(
3448
- { deploymentId, type: "build", logs: detail.logs },
3449
- detail.logs.map(formatBuildLog)
3109
+ "VALIDATION_FAILED",
3110
+ `${shown}: a quoted default is not closed.`
3450
3111
  );
3451
- return;
3452
- }
3453
- let lastSequence = -1;
3454
- for (; ; ) {
3455
- const detail = await client.deployments.get(deploymentId);
3456
- for (const log of detail.logs) {
3457
- if (log.sequence > lastSequence) {
3458
- lastSequence = log.sequence;
3459
- context.output.log(formatBuildLog(log));
3460
- }
3461
- }
3462
- if (isTerminalStatus(detail.deployment.status)) {
3463
- context.output.result(
3464
- {
3465
- deploymentId,
3466
- type: "build",
3467
- status: detail.deployment.status,
3468
- logs: detail.logs
3469
- },
3470
- [`\u2014 deployment ${detail.deployment.status} \u2014`]
3112
+ const [name, type, ...modifiers] = parts;
3113
+ if (!name || !type) throw new NaroError("VALIDATION_FAILED", SPEC_USAGE);
3114
+ const column = {
3115
+ name,
3116
+ type
3117
+ };
3118
+ let onDelete;
3119
+ for (const modifier of modifiers) {
3120
+ const eq = modifier.indexOf("=");
3121
+ const key = (eq < 0 ? modifier : modifier.slice(0, eq)).toLowerCase();
3122
+ const value = eq < 0 ? void 0 : modifier.slice(eq + 1);
3123
+ if (value === void 0 && key === "pk") column.primaryKey = true;
3124
+ else if (value === void 0 && key === "autoincrement")
3125
+ column.autoIncrement = true;
3126
+ else if (value === void 0 && key === "notnull") column.notNull = true;
3127
+ else if (value === void 0 && key === "unique") column.unique = true;
3128
+ else if (value !== void 0 && key === "default")
3129
+ column.default = defaultValue(value);
3130
+ else if (value !== void 0 && key === "references") {
3131
+ const dot = value.lastIndexOf(".");
3132
+ const table = dot < 0 ? "" : value.slice(0, dot);
3133
+ const target = dot < 0 ? "" : value.slice(dot + 1);
3134
+ if (!table || !target)
3135
+ throw new NaroError(
3136
+ "VALIDATION_FAILED",
3137
+ `${shown}: references needs <table>.<column>.`
3138
+ );
3139
+ column.references = { table, column: target };
3140
+ } else if (value !== void 0 && key === "ondelete") {
3141
+ onDelete = ON_DELETE[value.toLowerCase()];
3142
+ if (!onDelete)
3143
+ throw new NaroError(
3144
+ "VALIDATION_FAILED",
3145
+ `${shown}: ondelete takes cascade, set-null, set-default, restrict or no-action.`
3146
+ );
3147
+ } else
3148
+ throw new NaroError(
3149
+ "VALIDATION_FAILED",
3150
+ `${shown}: unknown modifier ${printable(modifier)}. Use pk, autoincrement, notnull, unique, default=<value>, references=<table>.<column> or ondelete=<action>.`
3471
3151
  );
3472
- return;
3473
- }
3474
- await sleep(FOLLOW_INTERVAL_MS);
3475
3152
  }
3153
+ if (onDelete !== void 0) {
3154
+ if (!column.references)
3155
+ throw new NaroError(
3156
+ "VALIDATION_FAILED",
3157
+ `${shown}: ondelete needs references=<table>.<column>.`
3158
+ );
3159
+ column.references.onDelete = onDelete;
3160
+ }
3161
+ return column;
3476
3162
  }
3477
- async function runtimeLogs(context, client, projectId) {
3478
- const environment = context.flags.env === "preview" ? "preview" : "production";
3479
- if (context.flags.env && !["production", "preview"].includes(context.flags.env))
3480
- throw new NaroError(
3481
- "VALIDATION_FAILED",
3482
- "--env must be production or preview."
3163
+ function policyLine(policy, dryRun = false) {
3164
+ const rules = [policy.select, policy.insert, policy.update, policy.delete];
3165
+ const owner = policy.ownerColumn === null ? "" : ` (owner column ${printable(policy.ownerColumn)})`;
3166
+ const uniform = rules.every((rule) => rule === rules[0]);
3167
+ const summary = uniform ? `${String(rules[0])} for select, insert, update and delete` : `select ${policy.select}, insert ${policy.insert}, update ${policy.update}, delete ${policy.delete}`;
3168
+ const head = dryRun ? "Would set the Data API policy" : "\u2713 Data API policy";
3169
+ return `${head} on ${printable(policy.table)}: ${summary}${owner}.`;
3170
+ }
3171
+ function ruleText(value) {
3172
+ if (typeof value === "string") return value;
3173
+ return "invalid" in value ? "invalid" : "condition";
3174
+ }
3175
+ var SUGAR_NAME = /^naro_(?:select|insert|update|delete)$/;
3176
+ function removedLines(policy, dryRun) {
3177
+ const verb = dryRun ? "Would remove" : "\u2713 Removed";
3178
+ const names = policy.policies ?? [];
3179
+ let line;
3180
+ if (names.every((name) => SUGAR_NAME.test(name))) {
3181
+ const owner = policy.ownerColumn === null ? "" : `, owner column ${printable(policy.ownerColumn)}`;
3182
+ const rules = `select ${ruleText(policy.select)}, insert ${ruleText(policy.insert)}, update ${ruleText(policy.update)}, delete ${ruleText(policy.delete)}${owner}`;
3183
+ line = `${verb} the Data API policy on ${printable(policy.table)} (${rules}).`;
3184
+ } else
3185
+ line = `${verb} ${String(names.length)} Data API ${names.length === 1 ? "policy" : "policies"} on ${printable(policy.table)}: ${names.map(printable).join(", ")}.`;
3186
+ const heading = " As SQL, for naro policy create:";
3187
+ const statements = policy.statements;
3188
+ if (statements === void 0) {
3189
+ const sql = policy.sql ?? "";
3190
+ if (sql === "") return [line];
3191
+ return isPrintable(sql) ? [line, heading, sql] : [
3192
+ line,
3193
+ " The SQL has characters that cannot be shown here: --json has the exact text."
3194
+ ];
3195
+ }
3196
+ const owners = statements.filter(
3197
+ (statement) => typeof statement.ownerColumn === "string"
3198
+ );
3199
+ const created = statements.filter((statement) => !owners.includes(statement));
3200
+ const lines = [line];
3201
+ if (created.length > 0)
3202
+ lines.push(
3203
+ heading,
3204
+ ...created.map(
3205
+ (statement) => shownStatement(statement, policy.table, "--json")
3206
+ )
3483
3207
  );
3484
- const options = {
3485
- environment,
3486
- ...context.flags.level ? { level: context.flags.level } : {}
3487
- };
3488
- if (!context.flags.follow) {
3489
- const entries = await client.logs.runtime(projectId, options);
3490
- context.output.result(
3491
- { projectId, type: "runtime", environment, entries },
3492
- entries.length > 0 ? entries.map(formatRuntimeLog) : ["(no runtime logs yet \u2014 the worker logs on each request)"]
3208
+ if (owners.length > 0) {
3209
+ const one = owners.length === 1;
3210
+ const command = policy.setCommand;
3211
+ lines.push(
3212
+ ` As a command, for the owner ${one ? "rule" : "rules"} (${owners.map((owner) => printable(owner.name)).join(", ")}): CREATE POLICY has no owner column, so naro policy create cannot make ${one ? "it" : "them"} again.`,
3213
+ // The server's bytes, or not shown: a name may hold a line break.
3214
+ typeof command !== "string" ? " naro policy set <table> --<action> owner --owner <column> sets one." : isPrintable(command) ? command : " The command has characters that cannot be shown here: --json has the exact text."
3493
3215
  );
3494
- return;
3495
3216
  }
3496
- context.output.log(
3497
- `Following ${environment} runtime logs (Ctrl-C to stop)...`
3217
+ return lines;
3218
+ }
3219
+ function removedBeforeFailure(error) {
3220
+ if (!isNaroError(error)) return [];
3221
+ const removed = error.details?.removedPolicies;
3222
+ if (!Array.isArray(removed)) return [];
3223
+ return removed.filter(
3224
+ (entry) => typeof entry === "object" && entry !== null && typeof entry.table === "string" && entry.ownerColumn !== void 0
3498
3225
  );
3499
- let lastTs = -1;
3500
- let boundary = /* @__PURE__ */ new Set();
3501
- for (; ; ) {
3502
- const entries = await client.logs.runtime(projectId, options);
3503
- for (const entry of entries) {
3504
- if (entry.ts < lastTs) continue;
3505
- const key = JSON.stringify(entry);
3506
- if (entry.ts === lastTs) {
3507
- if (boundary.has(key)) continue;
3508
- } else {
3509
- lastTs = entry.ts;
3510
- boundary = /* @__PURE__ */ new Set();
3511
- }
3512
- boundary.add(key);
3513
- context.output.log(formatRuntimeLog(entry));
3514
- }
3515
- await sleep(FOLLOW_INTERVAL_MS);
3516
- }
3517
3226
  }
3518
- async function runLogs(context) {
3227
+ async function runSchemaChange(context, operations, question) {
3228
+ const dryRun = context.flags.dryRun === true;
3229
+ if (question !== void 0 && !dryRun)
3230
+ await confirmOrAbort(context, question);
3231
+ const sent = dryRun ? operations.map((operation) => {
3232
+ if (operation.op !== "dropTable" && operation.op !== "dropColumn")
3233
+ return operation;
3234
+ const { confirm: _confirm, ...rest } = operation;
3235
+ return rest;
3236
+ }) : operations;
3519
3237
  const client = await context.client();
3520
- const [deploymentId] = context.positionals;
3521
- const type = context.flags.type ?? (deploymentId !== void 0 ? "build" : "runtime");
3522
- if (type !== "build" && type !== "runtime")
3523
- throw new NaroError(
3524
- "VALIDATION_FAILED",
3525
- "--type must be build or runtime."
3526
- );
3527
- if (type === "runtime") {
3528
- if (deploymentId)
3529
- throw new NaroError(
3530
- "VALIDATION_FAILED",
3531
- "Runtime logs are per project, not per deployment. Drop the deployment id or use --type build."
3532
- );
3533
- const projectId = await context.resolveProjectId();
3534
- await runtimeLogs(context, client, projectId);
3238
+ const projectId = await context.resolveProjectId();
3239
+ const dir = migrationsDir(context);
3240
+ const local = listMigrationFiles(dir);
3241
+ const ledger = await appliedMigrations(client, projectId);
3242
+ const pending = pendingMigrationNames(local, ledger);
3243
+ if (pending.length > 0 && !dryRun)
3244
+ throw migrationsPendingError(pending.map(printable));
3245
+ const name = nextMigrationFileName(
3246
+ [...local, ...ledger.map((row) => row.name)],
3247
+ schemaMigrationTitle(operations[0] ?? {})
3248
+ );
3249
+ const result = await client.db.schema(projectId, sent, {
3250
+ ...dryRun ? { dryRun: true } : {},
3251
+ name
3252
+ }).catch((error) => {
3253
+ if (!context.flags.json)
3254
+ for (const policy of removedBeforeFailure(error))
3255
+ for (const line of removedLines(policy, false))
3256
+ context.output.warn(line);
3257
+ throw error;
3258
+ });
3259
+ const sqlLines = result.sql.trimEnd().split("\n").map(printable);
3260
+ const removed = result.removedPolicies ?? [];
3261
+ if (result.dryRun) {
3262
+ for (const warning of result.warnings)
3263
+ context.output.warn(`\u26A0 ${printable(warning)}`);
3264
+ context.output.result({ projectId, ...result, file: null }, [
3265
+ ...sqlLines,
3266
+ `Dry run \u2014 nothing was applied. It would be recorded as ${printable(result.name)}.`,
3267
+ ...result.policies.map((policy) => policyLine(policy, true)),
3268
+ ...removed.flatMap((policy) => removedLines(policy, true))
3269
+ ]);
3535
3270
  return;
3536
3271
  }
3537
- const target = deploymentId ?? await latestProductionDeploymentId(
3538
- client,
3539
- await context.resolveProjectId()
3272
+ const allWarnings = result.name === name ? result.warnings : [...result.warnings, migrationNameMismatch(name, result.name)];
3273
+ let file = null;
3274
+ let fileWarning;
3275
+ const relDir = relativeToCwd(context, dir);
3276
+ const rel = join3(relDir === "." ? "" : relDir, name);
3277
+ if (context.flags.noWrite) {
3278
+ fileWarning = `Not written to ${relDir} (--no-write): naro db reset will not re-apply ${result.name}, and naro migration list shows it as remote-only.`;
3279
+ } else {
3280
+ try {
3281
+ mkdirSync3(dir, { recursive: true });
3282
+ writeFileSync3(join3(dir, name), result.sql, { flag: "wx" });
3283
+ file = rel;
3284
+ } catch (error) {
3285
+ const reason = (error instanceof Error ? error.message : String(error)).replace(/[.\s]+$/, "");
3286
+ fileWarning = `Applied, but ${rel} could not be written: ${reason}. Save the SQL above as ${rel} so naro db push and naro db reset see it.`;
3287
+ }
3288
+ }
3289
+ for (const warning of allWarnings)
3290
+ context.output.warn(`\u26A0 ${printable(warning)}`);
3291
+ if (fileWarning) context.output.warn(`\u26A0 ${printable(fileWarning)}`);
3292
+ context.output.result(
3293
+ {
3294
+ projectId,
3295
+ ...result,
3296
+ warnings: allWarnings,
3297
+ file,
3298
+ ...fileWarning ? { fileWarning } : {}
3299
+ },
3300
+ [
3301
+ ...sqlLines,
3302
+ file === null ? `\u2705 Applied ${printable(result.name)}.` : `\u2705 Applied ${printable(result.name)} and wrote ${printable(file)}.`,
3303
+ ...result.policies.map((policy) => policyLine(policy)),
3304
+ ...removed.flatMap((policy) => removedLines(policy, false))
3305
+ ]
3540
3306
  );
3541
- await buildLogs(context, client, target);
3542
3307
  }
3543
-
3544
- // src/commands/policy.ts
3545
- import { readFileSync as readFileSync3 } from "fs";
3546
- import { resolve as resolve4 } from "path";
3547
-
3548
- // ../../packages/naro-sdk/src/query/filters.ts
3549
- var MAX_FILTER_DEPTH = 4;
3550
- var OPERATORS = {
3551
- eq: "eq",
3552
- neq: "neq",
3553
- gt: "gt",
3554
- gte: "gte",
3555
- lt: "lt",
3556
- lte: "lte",
3557
- in: "in",
3558
- is: "is",
3559
- like: "like",
3560
- ilike: "ilike",
3561
- contains: "contains",
3562
- containedBy: "containedBy",
3563
- overlaps: "overlaps",
3564
- cs: "contains",
3565
- cd: "containedBy",
3566
- ov: "overlaps"
3567
- };
3568
- function operatorOf(name) {
3569
- return typeof name === "string" && Object.hasOwn(OPERATORS, name) ? OPERATORS[name] : void 0;
3308
+ function columnsFlag(context) {
3309
+ return context.flags.columns ?? [];
3310
+ }
3311
+ async function runDbTableUsage() {
3312
+ throw new NaroError("VALIDATION_FAILED", USAGE2.table);
3313
+ }
3314
+ async function runDbIndexUsage() {
3315
+ throw new NaroError("VALIDATION_FAILED", USAGE2.index);
3316
+ }
3317
+ async function runDbTableCreate(context) {
3318
+ const [table] = context.positionals;
3319
+ const specs = columnsFlag(context);
3320
+ if (!table || specs.length === 0)
3321
+ throw new NaroError("VALIDATION_FAILED", USAGE2.create);
3322
+ const columns = specs.map(parseColumnSpec);
3323
+ const owner = context.flags.ownerColumn;
3324
+ await runSchemaChange(context, [
3325
+ {
3326
+ op: "createTable",
3327
+ table,
3328
+ columns,
3329
+ ...context.flags.ifNotExists ? { ifNotExists: true } : {},
3330
+ ...owner === void 0 ? {} : { owner: { column: owner } }
3331
+ }
3332
+ ]);
3333
+ }
3334
+ async function runDbTableAddColumn(context) {
3335
+ const [table] = context.positionals;
3336
+ const specs = columnsFlag(context);
3337
+ const [spec] = specs;
3338
+ if (!table || spec === void 0 || specs.length !== 1)
3339
+ throw new NaroError("VALIDATION_FAILED", USAGE2.addColumn);
3340
+ await runSchemaChange(context, [
3341
+ { op: "addColumn", table, column: parseColumnSpec(spec) }
3342
+ ]);
3343
+ }
3344
+ async function runDbTableRenameColumn(context) {
3345
+ const [table, column, to] = context.positionals;
3346
+ if (!table || !column || !to)
3347
+ throw new NaroError("VALIDATION_FAILED", USAGE2.renameColumn);
3348
+ await runSchemaChange(context, [{ op: "renameColumn", table, column, to }]);
3349
+ }
3350
+ async function runDbTableRename(context) {
3351
+ const [table, to] = context.positionals;
3352
+ if (!table || !to) throw new NaroError("VALIDATION_FAILED", USAGE2.rename);
3353
+ await runSchemaChange(context, [{ op: "renameTable", table, to }]);
3354
+ }
3355
+ async function runDbTableDropColumn(context) {
3356
+ const [table, column] = context.positionals;
3357
+ if (!table || !column)
3358
+ throw new NaroError("VALIDATION_FAILED", USAGE2.dropColumn);
3359
+ const target = `${table}.${column}`;
3360
+ await runSchemaChange(
3361
+ context,
3362
+ [{ op: "dropColumn", table, column, confirm: target }],
3363
+ `Drop column ${printable(target)} and its value in every row? naro db restore can bring it back (Time Travel, 30 days).`
3364
+ );
3365
+ }
3366
+ async function runDbTableDrop(context) {
3367
+ const [table] = context.positionals;
3368
+ if (!table) throw new NaroError("VALIDATION_FAILED", USAGE2.drop);
3369
+ await runSchemaChange(
3370
+ context,
3371
+ [{ op: "dropTable", table, confirm: table }],
3372
+ `Drop table ${printable(table)} and every row in it? naro db restore can bring it back (Time Travel, 30 days).`
3373
+ );
3570
3374
  }
3571
- var Refusal = class extends Error {
3572
- };
3573
- function refuse(reason) {
3574
- throw new Refusal(reason);
3375
+ async function runDbIndexCreate(context) {
3376
+ const [table, list] = context.positionals;
3377
+ const columns = listFlag(list);
3378
+ if (!table || columns.length === 0)
3379
+ throw new NaroError("VALIDATION_FAILED", USAGE2.indexCreate);
3380
+ const name = context.flags.name;
3381
+ await runSchemaChange(context, [
3382
+ {
3383
+ op: "createIndex",
3384
+ table,
3385
+ columns,
3386
+ ...context.flags.unique ? { unique: true } : {},
3387
+ ...name === void 0 ? {} : { name }
3388
+ }
3389
+ ]);
3575
3390
  }
3576
- var LIST_HINT = {
3577
- in: ["(", ")", "needs a list in parentheses, like in.(a,b),"],
3578
- array: ["{", "}", "needs a list in braces, like cs.{a,b},"]
3579
- };
3580
- function isSpace(char) {
3581
- return char !== "" && char.trim() === "";
3391
+ async function runDbIndexDrop(context) {
3392
+ const [name] = context.positionals;
3393
+ if (!name) throw new NaroError("VALIDATION_FAILED", USAGE2.indexDrop);
3394
+ await runSchemaChange(context, [{ op: "dropIndex", name }]);
3582
3395
  }
3583
- function looseWord(text) {
3584
- return text.replace(/\s+/g, "").toLowerCase().replace(/\(\)$/, "");
3396
+
3397
+ // src/commands/git.ts
3398
+ var defaults2 = {
3399
+ detectRemote: async (dir) => (await detectGitInfo(dir)).repositoryUrl,
3400
+ openBrowser,
3401
+ sleep: (ms) => new Promise((resolve5) => setTimeout(resolve5, ms))
3402
+ };
3403
+ function connected(context, project) {
3404
+ const branch = project.defaultBranch;
3405
+ context.output.result(
3406
+ {
3407
+ projectId: project.id,
3408
+ repositoryFullName: project.repositoryFullName,
3409
+ autoDeploy: true
3410
+ },
3411
+ [
3412
+ `\u2705 Connected to ${project.repositoryFullName ?? "the repository"}.`,
3413
+ ` Pushes to ${branch} now deploy automatically.`,
3414
+ "",
3415
+ " To turn this off: naro git disconnect"
3416
+ ]
3417
+ );
3585
3418
  }
3586
- var Parser = class {
3587
- constructor(text, tokens = {}) {
3588
- this.text = text;
3589
- this.tokens = tokens;
3590
- }
3591
- index = 0;
3592
- /**
3593
- * A token at the next value, followed only by spaces and then one of
3594
- * `stops` or the end — `auth.uid()x` is text, not the token.
3595
- */
3596
- token(stops) {
3597
- this.skipSpaces();
3598
- const at = this.index;
3599
- for (const [word, value] of Object.entries(this.tokens)) {
3600
- if (!this.text.startsWith(word, at)) continue;
3601
- let end = at + word.length;
3602
- while (isSpace(this.text[end] ?? "")) end++;
3603
- const next = this.text[end] ?? "";
3604
- if (next !== "" && !stops.includes(next)) continue;
3605
- this.index = end;
3606
- return { value, word, at };
3419
+ async function runGitConnect(context, overrides = {}) {
3420
+ const deps = { ...defaults2, ...overrides };
3421
+ const { output } = context;
3422
+ const explicit = context.positionals[0];
3423
+ let fullName;
3424
+ if (explicit) {
3425
+ const parsed = parseGitHubRemote(explicit) ?? parseGitHubRemote(`https://github.com/${explicit}`);
3426
+ if (!parsed)
3427
+ throw new NaroError(
3428
+ "VALIDATION_FAILED",
3429
+ `"${explicit}" is not an owner/repo pair.`
3430
+ );
3431
+ fullName = parsed.fullName;
3432
+ } else {
3433
+ const remote = await deps.detectRemote(context.cwd);
3434
+ const parsed = remote ? parseGitHubRemote(remote) : null;
3435
+ if (!parsed) {
3436
+ throw new NaroError(
3437
+ "NO_GIT_REMOTE",
3438
+ remote ? `Could not read a GitHub owner/repo from "${remote}". Pass it directly: naro git connect <owner/repo>` : "This directory has no GitHub origin remote. Pass one directly: naro git connect <owner/repo>"
3439
+ );
3607
3440
  }
3608
- return void 0;
3609
- }
3610
- at() {
3611
- return this.text[this.index] ?? "";
3612
- }
3613
- /**
3614
- * An unquoted value that is one of the tokens misspelled — `auth.uid`,
3615
- * `AUTH.UID` — is refused: read as text it would compare with the words
3616
- * themselves (사용자 리뷰 반영). Quoted, it is the text.
3617
- */
3618
- notNearToken(value, at) {
3619
- const loose = looseWord(value);
3620
- for (const word of Object.keys(this.tokens))
3621
- if (loose !== "" && loose === looseWord(word))
3622
- refuse(
3623
- `has ${JSON.stringify(value)} ${this.where(at)}: did you mean ${word}? Quote it to mean the text`
3624
- );
3625
- }
3626
- /** `scalar`, with an unquoted value held to notNearToken. */
3627
- bareOrQuoted(stops) {
3628
- this.skipSpaces();
3629
- const at = this.index;
3630
- const quoted = this.at() === '"';
3631
- const text = this.scalar(stops);
3632
- if (!quoted) this.notNearToken(text, at);
3633
- return { text, quoted };
3441
+ fullName = parsed.fullName;
3634
3442
  }
3635
- where(index = this.index) {
3636
- return `at character ${String(index + 1)}`;
3443
+ const client = await context.client();
3444
+ const projectId = await context.resolveProjectId();
3445
+ const first = await client.projects.connectGit(projectId, fullName);
3446
+ if (first.ok) {
3447
+ connected(context, first.project);
3448
+ return;
3637
3449
  }
3638
- skipSpaces() {
3639
- while (isSpace(this.at())) this.index++;
3450
+ if (!first.installUrl) {
3451
+ throw new NaroError(
3452
+ "REPOSITORY_NOT_ACCESSIBLE",
3453
+ `Naro cannot reach ${fullName}, and no install URL was offered. Connect it from the dashboard.`
3454
+ );
3640
3455
  }
3641
- /** `item ("," item)*`, up to a `)` or the end, inside `level` groups. */
3642
- list(level) {
3643
- const nodes = [];
3644
- for (; ; ) {
3645
- nodes.push(this.item(level));
3646
- this.skipSpaces();
3647
- const char = this.at();
3648
- if (char === ",") this.index++;
3649
- else if (char === ")" || char === "") return nodes;
3650
- else refuse(`has unexpected text ${this.where()}`);
3456
+ output.log(`
3457
+ \u25B8 Naro needs access to ${fullName}.`);
3458
+ output.log(` Opening ${first.installUrl}`);
3459
+ deps.openBrowser(first.installUrl);
3460
+ output.log(" Waiting for the installation to finish...\n");
3461
+ await waitForInstall(context, projectId, fullName, deps);
3462
+ }
3463
+ async function waitForInstall(context, projectId, fullName, deps) {
3464
+ const client = await context.client();
3465
+ const project = await client.projects.get(projectId);
3466
+ const teams = await client.teams.list();
3467
+ const teamSlug = teams.find((team) => team.id === project.teamId)?.slug;
3468
+ if (teamSlug) {
3469
+ const attempts = deps.pollAttempts ?? 60;
3470
+ const interval = deps.pollIntervalMs ?? 3e3;
3471
+ for (let attempt2 = 0; attempt2 < attempts; attempt2 += 1) {
3472
+ await deps.sleep(interval);
3473
+ let reachable = false;
3474
+ try {
3475
+ const repositories = await client.github.listRepositories(teamSlug);
3476
+ reachable = repositories.some(
3477
+ (repository) => repository.fullName.toLowerCase() === fullName.toLowerCase()
3478
+ );
3479
+ } catch {
3480
+ }
3481
+ if (!reachable) continue;
3482
+ const retry = await client.projects.connectGit(projectId, fullName);
3483
+ if (retry.ok) {
3484
+ connected(context, retry.project);
3485
+ return;
3486
+ }
3651
3487
  }
3652
3488
  }
3653
- item(level) {
3654
- this.skipSpaces();
3655
- const start = this.index;
3656
- const char = this.at();
3657
- if (char === "" || char === "," || char === ")")
3658
- refuse(`has an empty item ${this.where()}`);
3659
- const group = /^(not\.)?(and|or)\(/.exec(this.text.slice(start));
3660
- if (!group) return this.leaf(level);
3661
- const negated = group[1] !== void 0;
3662
- const inner = level + (negated ? 2 : 1);
3663
- if (inner > MAX_FILTER_DEPTH)
3664
- refuse(`nests deeper than ${String(MAX_FILTER_DEPTH)} groups`);
3665
- const open = start + group[0].length - 1;
3666
- this.index = open + 1;
3667
- const children = this.list(inner);
3668
- if (this.at() !== ")") refuse(`has an unclosed "(" ${this.where(open)}`);
3669
- this.index++;
3670
- const node = group[2] === "or" ? { or: children } : { and: children };
3671
- return negated ? { not: node } : node;
3672
- }
3673
- /** `column.[not.]operator.value`. */
3674
- leaf(level) {
3675
- const start = this.index;
3676
- const column = this.at() === '"' ? this.quoted() : this.word().trim();
3677
- if (column === "" || this.at() !== ".")
3678
- refuse(`needs column.operator.value ${this.where(start)}`);
3679
- this.index++;
3680
- let nameAt = this.index;
3681
- let name = this.word();
3682
- let negated = false;
3683
- if (name === "not" && this.at() === ".") {
3684
- if (level + 1 > MAX_FILTER_DEPTH)
3685
- refuse(`nests deeper than ${String(MAX_FILTER_DEPTH)} groups`);
3686
- negated = true;
3687
- this.index++;
3688
- nameAt = this.index;
3689
- name = this.word();
3489
+ context.output.result(
3490
+ { projectId, repositoryFullName: null, autoDeploy: false },
3491
+ [
3492
+ `\u25B8 Still waiting on access to ${fullName}.`,
3493
+ " Finish the installation, then run: naro git connect"
3494
+ ]
3495
+ );
3496
+ }
3497
+ async function runGitDisconnect(context) {
3498
+ const client = await context.client();
3499
+ const projectId = await context.resolveProjectId();
3500
+ const project = await client.projects.disconnectGit(projectId);
3501
+ context.output.result({ projectId: project.id, autoDeploy: false }, [
3502
+ `\u2705 ${project.name} no longer deploys on push.`,
3503
+ " Deploy from here with: naro deploy"
3504
+ ]);
3505
+ }
3506
+ async function offerAutoDeploy(context, projectId, overrides) {
3507
+ const deps = { ...defaults2, ...overrides };
3508
+ if (overrides.canPrompt === false) return;
3509
+ try {
3510
+ if (readProjectLink(context.cwd)?.autoDeployDeclined === true) return;
3511
+ const connection = overrides.gitConnection;
3512
+ if (connection.state === "connected" || connection.state === "none") return;
3513
+ const fullName = connection.fullName;
3514
+ if (!fullName) return;
3515
+ let wanted;
3516
+ if (connection.state === "unreachable") {
3517
+ const installed = connection.installedAccounts ?? [];
3518
+ context.output.log(
3519
+ `
3520
+ \u25B8 Automatic deploys need the Naro GitHub App on \`${connection.repoOwner ?? fullName}\`.`
3521
+ );
3522
+ if (overrides.teamSlug && installed.length > 0)
3523
+ context.output.log(
3524
+ ` Team ${overrides.teamSlug} has it on: ${installed.join(", ")}.`
3525
+ );
3526
+ wanted = await context.prompter.confirm(
3527
+ "Install it for this team now? (opens your browser)"
3528
+ );
3529
+ } else {
3530
+ wanted = await context.prompter.confirm(
3531
+ "Should your changes deploy automatically from now on?"
3532
+ );
3690
3533
  }
3691
- const operator = operatorOf(name);
3692
- if (this.at() !== ".") {
3693
- if (name !== "" && operator === void 0)
3694
- refuse(`has an unknown operator "${name}" ${this.where(nameAt)}`);
3695
- refuse(`needs column.operator.value ${this.where(start)}`);
3534
+ if (!wanted) {
3535
+ const link = readProjectLink(context.cwd);
3536
+ writeProjectLink(context.cwd, {
3537
+ ...link ?? { projectId },
3538
+ autoDeployDeclined: true
3539
+ });
3540
+ context.output.log(
3541
+ "\u25B8 Not now. Later, if you change your mind: naro git connect"
3542
+ );
3543
+ return;
3696
3544
  }
3697
- if (operator === void 0)
3698
- refuse(`has an unknown operator "${name}" ${this.where(nameAt)}`);
3699
- this.index++;
3700
- const leaf = { operator, column, value: this.value(operator) };
3701
- return negated ? { not: leaf } : leaf;
3545
+ const client = await context.client();
3546
+ const result = await client.projects.connectGit(projectId, fullName);
3547
+ if (result.ok) {
3548
+ connected(context, result.project);
3549
+ return;
3550
+ }
3551
+ if (!result.installUrl) return;
3552
+ context.output.log(`
3553
+ \u25B8 Naro needs access to ${fullName}.`);
3554
+ context.output.log(` Opening ${result.installUrl}`);
3555
+ deps.openBrowser(result.installUrl);
3556
+ context.output.log(" Waiting for the installation to finish...\n");
3557
+ await waitForInstall(context, projectId, fullName, deps);
3558
+ } catch (error) {
3559
+ context.output.log(
3560
+ `\u25B8 Could not set up automatic deploys (${error instanceof Error ? error.message : String(error)}).`
3561
+ );
3562
+ context.output.log(" Try later with: naro git connect");
3702
3563
  }
3703
- /** Up to the next `.`, `,`, `(`, `)` or the end. */
3704
- word() {
3705
- const start = this.index;
3706
- while (this.index < this.text.length && !".,()".includes(this.at()))
3707
- this.index++;
3708
- return this.text.slice(start, this.index);
3564
+ }
3565
+
3566
+ // src/commands/link.ts
3567
+ var SWITCH_ACCOUNT = "Sign in as a different account\u2026";
3568
+ async function resolveTeam(context, teams, deps = {}) {
3569
+ const explicit = context.flags.team ?? process.env.NARO_TEAM;
3570
+ if (explicit) {
3571
+ const match = teams.find((team) => team.slug === explicit);
3572
+ if (!match)
3573
+ throw new NaroError(
3574
+ "NOT_FOUND",
3575
+ `You are not a member of team "${explicit}".`
3576
+ );
3577
+ return match;
3709
3578
  }
3710
- /** `"…"`, with `\` making the next character literal. */
3711
- quoted() {
3712
- const start = this.index;
3713
- this.index++;
3714
- let text = "";
3715
- for (; ; ) {
3716
- if (this.index >= this.text.length)
3717
- refuse(`has an unclosed quote ${this.where(start)}`);
3718
- const char = this.at();
3719
- this.index++;
3720
- if (char === '"') return text;
3721
- if (char === "\\" && this.index < this.text.length) {
3722
- text += this.at();
3723
- this.index++;
3724
- } else text += char;
3725
- }
3579
+ const linked = context.projectLink();
3580
+ if (linked?.teamSlug) {
3581
+ const match = teams.find((team) => team.slug === linked.teamSlug);
3582
+ if (match) return match;
3726
3583
  }
3727
- /** A quoted value, or everything up to `stops`, trimmed. */
3728
- scalar(stops) {
3729
- this.skipSpaces();
3730
- if (this.at() === '"') {
3731
- const text = this.quoted();
3732
- this.skipSpaces();
3733
- if (this.at() !== "" && !stops.includes(this.at()))
3734
- refuse(`has text after a closing quote ${this.where()}`);
3735
- return text;
3736
- }
3737
- const start = this.index;
3738
- while (this.index < this.text.length && !stops.includes(this.at()))
3739
- this.index++;
3740
- return this.text.slice(start, this.index).trim();
3584
+ if (teams.length === 0)
3585
+ throw new NaroError("NOT_FOUND", "Your account has no teams yet.");
3586
+ const only = teams.length === 1 ? teams[0] : null;
3587
+ const deploying = (deps.intent ?? "deploy") === "deploy";
3588
+ if (only && !deploying) return only;
3589
+ const canPrompt = deps.canPrompt?.() ?? (!context.flags.json && !context.flags.yes && isInteractive());
3590
+ if (!canPrompt)
3591
+ throw new NaroError(
3592
+ "TEAM_REQUIRED",
3593
+ `Cannot pick a team without a prompt. Pass --team <slug>, set NARO_TEAM, or run \`naro link\` first.
3594
+ Your teams: ${teams.map((team) => team.slug).join(", ")}`
3595
+ );
3596
+ const account = deps.accountLabel ? await deps.accountLabel() : "this account";
3597
+ if (only) {
3598
+ const label2 = only.isPersonal ? `${only.name} (personal)` : only.name;
3599
+ context.output.log(`
3600
+ ${account} \u2192 ${label2}`);
3601
+ const ok = await context.prompter.confirm(
3602
+ "Deploy to this account and team?"
3603
+ );
3604
+ if (ok) return only;
3605
+ return switchAndRetry(context, deps);
3741
3606
  }
3742
- /**
3743
- * `(a,b)` for `in`: text values, except that an unquoted `true` or `false`
3744
- * is a boolean (사용자 리뷰 반영, as in `eq`). `{a,b}` for the array
3745
- * operators: text, except that an unquoted exact decimal is a number
3746
- * (적대적 리뷰 반영, narrowed by 사용자 리뷰 반영) — json_each's values
3747
- * have no type affinity to turn the text "1" into 1, so as text `cs.{1}`
3748
- * matched no numeric array and `not.ov.{1}` matched every row. Quoted,
3749
- * `"1"` and `"true"` stay text.
3750
- */
3751
- listValue(kind) {
3752
- const [open, close, hint] = LIST_HINT[kind];
3753
- this.skipSpaces();
3754
- const openAt = this.index;
3755
- if (this.at() !== open) refuse(`${hint} ${this.where()}`);
3756
- this.index++;
3757
- this.skipSpaces();
3758
- const values = [];
3759
- if (this.at() === close) {
3760
- this.index++;
3761
- return values;
3762
- }
3763
- for (; ; ) {
3764
- this.skipSpaces();
3765
- const itemAt = this.index;
3766
- const token = this.token(`,${close}`);
3767
- if (token) values.push(token.value);
3768
- else {
3769
- const { text: value, quoted } = this.bareOrQuoted(`,${close}`);
3770
- if (!quoted && value === "") {
3771
- if (this.index >= this.text.length)
3772
- refuse(`has an unclosed "${open}" ${this.where(openAt)}`);
3773
- refuse(`has an empty item ${this.where(itemAt)}`);
3774
- }
3775
- values.push(
3776
- quoted ? value : kind === "array" ? exactNumber(value) : truth(value)
3777
- );
3778
- }
3779
- if (this.index >= this.text.length)
3780
- refuse(`has an unclosed "${open}" ${this.where(openAt)}`);
3781
- const char = this.at();
3782
- this.index++;
3783
- if (char === close) return values;
3607
+ const options = [
3608
+ ...teams.map(
3609
+ (team) => `${team.name}${team.isPersonal ? " (personal)" : ""}`
3610
+ ),
3611
+ SWITCH_ACCOUNT
3612
+ ];
3613
+ const index = await context.prompter.select(
3614
+ deploying ? `Deploying as ${account} \u2014 which team owns this project?` : `Signed in as ${account}. Which team?`,
3615
+ options
3616
+ );
3617
+ const picked = teams[index];
3618
+ if (picked) return picked;
3619
+ return switchAndRetry(context, deps);
3620
+ }
3621
+ async function switchAndRetry(context, deps) {
3622
+ if (!deps.switchAccount || !deps.listTeams)
3623
+ throw new NaroError(
3624
+ "CANCELED",
3625
+ "Canceled. Switch accounts with `naro logout && naro login`."
3626
+ );
3627
+ await deps.switchAccount();
3628
+ const teams = await deps.listTeams();
3629
+ return resolveTeam(context, teams, deps);
3630
+ }
3631
+ function saveLink(context, project, teamSlug) {
3632
+ writeProjectLink(context.cwd, {
3633
+ projectId: project.id,
3634
+ teamSlug,
3635
+ projectName: project.name
3636
+ });
3637
+ if (ensureGitignoreHasNaro(context.cwd))
3638
+ context.output.log("\u25B8 added .naro to .gitignore");
3639
+ }
3640
+ async function runLink(context) {
3641
+ const client = await context.client();
3642
+ const teams = await client.teams.list();
3643
+ const team = await resolveTeam(context, teams, { intent: "read" });
3644
+ const projects = await client.projects.list(team.slug);
3645
+ let project;
3646
+ if (context.flags.project) {
3647
+ project = projects.find(
3648
+ (candidate) => candidate.id === context.flags.project
3649
+ );
3650
+ if (!project) {
3651
+ project = await client.projects.get(context.flags.project);
3784
3652
  }
3785
- }
3786
- /** The value after `operator.`. */
3787
- value(operator) {
3788
- const start = this.index;
3789
- switch (operator) {
3790
- case "in":
3791
- return this.listValue("in");
3792
- case "contains":
3793
- case "containedBy":
3794
- case "overlaps":
3795
- return this.listValue("array");
3796
- case "is":
3797
- return keyword(this.scalar(",)"), start);
3798
- case "like":
3799
- case "ilike": {
3800
- const token = this.token(",)");
3801
- if (token)
3802
- refuse(
3803
- `cannot use ${token.word} with ${operator} ${this.where(token.at)}`
3804
- );
3805
- return likePattern(this.bareOrQuoted(",)").text);
3806
- }
3807
- case "eq":
3808
- case "neq": {
3809
- const token = this.token(",)");
3810
- if (token) return token.value;
3811
- const { text, quoted } = this.bareOrQuoted(",)");
3812
- return quoted ? text : truth(text);
3813
- }
3814
- default: {
3815
- const token = this.token(",)");
3816
- return token ? token.value : this.bareOrQuoted(",)").text;
3817
- }
3653
+ } else if (context.flags.name) {
3654
+ project = projects.find(
3655
+ (candidate) => candidate.name === context.flags.name || candidate.slug === context.flags.name
3656
+ );
3657
+ if (!project)
3658
+ throw new NaroError(
3659
+ "PROJECT_NOT_FOUND",
3660
+ `No project named "${context.flags.name}" in team ${team.slug}. Run \`naro deploy\` to create it.`
3661
+ );
3662
+ } else {
3663
+ const guess = slugify(context.cwd.split("/").at(-1) ?? "app");
3664
+ const exact = projects.find(
3665
+ (candidate) => candidate.name === guess || candidate.slug === guess
3666
+ );
3667
+ if (exact && (context.flags.yes || context.flags.json)) {
3668
+ project = exact;
3669
+ } else if (projects.length === 0) {
3670
+ throw new NaroError(
3671
+ "PROJECT_NOT_FOUND",
3672
+ `Team ${team.slug} has no projects yet. Run \`naro deploy\` to create one.`
3673
+ );
3674
+ } else {
3675
+ const options = projects.map(
3676
+ (candidate) => `${candidate.name} (${candidate.subdomain})`
3677
+ );
3678
+ const index = await context.prompter.select(
3679
+ `Link ${context.cwd} to which project?`,
3680
+ options
3681
+ );
3682
+ project = projects[index];
3818
3683
  }
3819
3684
  }
3820
- };
3821
- function likePattern(pattern) {
3822
- return pattern.replaceAll("*", "%");
3685
+ if (!project)
3686
+ throw new NaroError("PROJECT_NOT_FOUND", "No project selected.");
3687
+ const owningTeam = teams.find((candidate) => candidate.id === project.teamId) ?? team;
3688
+ saveLink(context, project, owningTeam.slug);
3689
+ context.output.result(
3690
+ {
3691
+ projectId: project.id,
3692
+ projectName: project.name,
3693
+ teamSlug: owningTeam.slug,
3694
+ subdomain: project.subdomain
3695
+ },
3696
+ [`\u2705 Linked to ${owningTeam.slug}/${project.name} (.naro/project.json)`]
3697
+ );
3823
3698
  }
3824
- function truth(text) {
3825
- const word = text.toLowerCase();
3826
- if (word === "true") return true;
3827
- if (word === "false") return false;
3828
- return text;
3699
+ async function runUnlink(context) {
3700
+ const existing = readProjectLink(context.cwd);
3701
+ const removed = removeProjectLink(context.cwd);
3702
+ context.output.result(
3703
+ { removed, ...existing ? { projectId: existing.projectId } : {} },
3704
+ [removed ? "\u2705 Unlinked (.naro removed)" : "Nothing to unlink here."]
3705
+ );
3829
3706
  }
3830
- var DECIMAL = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/;
3831
- function exactNumber(text) {
3832
- if (!DECIMAL.test(text)) return text;
3833
- const number = Number(text);
3834
- if (!text.includes(".")) return Number.isSafeInteger(number) ? number : text;
3835
- const trimmed = text.replace(/\.?0+$/, "");
3836
- return String(number) === trimmed ? number : text;
3707
+
3708
+ // src/commands/deploy.ts
3709
+ async function runDeploy(context, deps = { deploy: deployDirectory, offerAutoDeploy }) {
3710
+ const { flags, output } = context;
3711
+ const link = flags.project ? { projectId: flags.project, teamSlug: void 0 } : readProjectLink(context.cwd);
3712
+ if (flags.prod && !flags.yes && !flags.json && isInteractive()) {
3713
+ const confirmed = await context.prompter.confirm("Deploy to production?");
3714
+ if (!confirmed) throw new NaroError("CANCELED", "Canceled.");
3715
+ }
3716
+ output.log(`
3717
+ \u{1F680} Deploying ${context.cwd}
3718
+ `);
3719
+ const canPrompt = deps.canPrompt?.() ?? (!flags.json && !flags.yes && isInteractive());
3720
+ const team = await resolveDestination(context, link, canPrompt);
3721
+ const account = await accountLabel(context);
3722
+ output.log(` ${account} \u2192 ${team.slug}
3723
+ `);
3724
+ const result = await deps.deploy(
3725
+ context.cwd,
3726
+ {
3727
+ name: flags.name,
3728
+ projectId: link?.projectId,
3729
+ teamSlug: team.slug,
3730
+ rootDirectory: flags.root ?? null,
3731
+ branch: flags.branch,
3732
+ production: flags.prod,
3733
+ ...canPrompt && {
3734
+ onMissingEnv: (keys) => promptForMissingEnv(
3735
+ { cwd: context.cwd, prompter: context.prompter, output },
3736
+ keys
3737
+ )
3738
+ },
3739
+ token: flags.token,
3740
+ allowLogin: !flags.json && !flags.yes
3741
+ },
3742
+ (message) => output.log(message)
3743
+ );
3744
+ const existing = readProjectLink(context.cwd);
3745
+ writeProjectLink(context.cwd, {
3746
+ projectId: result.projectId,
3747
+ teamSlug: result.teamSlug,
3748
+ projectName: result.projectSlug,
3749
+ ...existing?.autoDeployDeclined === true ? { autoDeployDeclined: true } : {}
3750
+ });
3751
+ if (!link) {
3752
+ if (ensureGitignoreHasNaro(context.cwd))
3753
+ output.log("\u25B8 added .naro to .gitignore");
3754
+ output.log("\u25B8 linked (.naro/project.json)");
3755
+ }
3756
+ await deps.offerAutoDeploy?.(context, result.projectId, {
3757
+ canPrompt,
3758
+ gitConnection: result.gitConnection,
3759
+ teamSlug: result.teamSlug
3760
+ });
3761
+ const inspect = `${controlPlaneUrl()}${projectPath(result.teamSlug, result.projectSlug)}`;
3762
+ context.output.result(
3763
+ {
3764
+ deploymentId: result.deploymentId,
3765
+ projectId: result.projectId,
3766
+ status: result.status,
3767
+ url: result.url,
3768
+ target: result.production ? "production" : "preview",
3769
+ teamSlug: result.teamSlug,
3770
+ inspectUrl: inspect,
3771
+ missingEnvKeys: result.missingEnvKeys
3772
+ },
3773
+ [
3774
+ "",
3775
+ `\u2705 Deployment ready (${result.production ? "production" : "preview"})`,
3776
+ "",
3777
+ ` ${result.url}`,
3778
+ ` Inspect ${inspect}`
3779
+ ]
3780
+ );
3837
3781
  }
3838
- function quoteFilterValue(value) {
3839
- const text = String(value);
3840
- return `"${text.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
3782
+ async function resolveDestination(context, link, canPrompt) {
3783
+ const client = await context.client();
3784
+ const teams = await client.teams.list();
3785
+ const deps = scopeDeps(context, canPrompt);
3786
+ if (link?.teamSlug) {
3787
+ const match = teams.find((team) => team.slug === link.teamSlug);
3788
+ if (match) return match;
3789
+ } else if (link) {
3790
+ let project;
3791
+ try {
3792
+ project = await client.projects.get(link.projectId);
3793
+ } catch (error) {
3794
+ if (isNaroError(error) && error.code !== "NOT_FOUND") throw error;
3795
+ throw new NaroError(
3796
+ "PROJECT_NOT_FOUND",
3797
+ `This directory is linked to a project ${await accountLabel(context)} cannot see.
3798
+ The CLI signs in separately from the dashboard \u2014 check with \`naro whoami\`.
3799
+ Wrong account? naro logout && naro login
3800
+ Project gone? remove .naro, then naro deploy`,
3801
+ { cause: error }
3802
+ );
3803
+ }
3804
+ const match = teams.find((team) => team.id === project.teamId);
3805
+ if (match) return match;
3806
+ }
3807
+ return resolveTeam(context, teams, deps);
3841
3808
  }
3842
- function keyword(text, at) {
3843
- const word = text.toLowerCase();
3844
- if (word === "null") return null;
3845
- if (word === "true") return true;
3846
- if (word === "false") return false;
3847
- return refuse(
3848
- `needs null, true or false after is at character ${String(at + 1)}`
3849
- );
3809
+ function scopeDeps(context, canPrompt) {
3810
+ return {
3811
+ canPrompt: () => canPrompt,
3812
+ accountLabel: () => accountLabel(context),
3813
+ switchAccount: async () => {
3814
+ clearSession();
3815
+ await runLogin(context);
3816
+ },
3817
+ listTeams: async () => (await context.client()).teams.list()
3818
+ };
3850
3819
  }
3851
- function attempt(parse) {
3820
+ async function accountLabel(context) {
3852
3821
  try {
3853
- return { ok: true, node: parse() };
3854
- } catch (error) {
3855
- if (error instanceof Refusal) return { ok: false, reason: error.message };
3856
- throw error;
3822
+ const { user } = await context.auth();
3823
+ if (!user) return "this account";
3824
+ const name = user.email ?? user.id;
3825
+ return user.github ? `${name} (${user.github})` : name;
3826
+ } catch {
3827
+ return "this account";
3857
3828
  }
3858
3829
  }
3859
- function parseLogic(text, kind, options = {}) {
3860
- if (typeof text !== "string")
3861
- return { ok: false, reason: "must be a filter string or a function" };
3862
- if (text.trim() === "") return { ok: false, reason: "must not be empty" };
3863
- return attempt(() => {
3864
- if (options.group === false) {
3865
- const alone = items(text, options.tokens, 0);
3866
- if (alone.length === 1 && alone[0]) return alone[0];
3867
- }
3868
- const nodes = items(text, options.tokens, 1);
3869
- return kind === "or" ? { or: nodes } : { and: nodes };
3870
- });
3830
+
3831
+ // src/commands/deployments.ts
3832
+ function shortSha(sha) {
3833
+ return sha ? sha.slice(0, 7) : "-";
3871
3834
  }
3872
- function items(text, tokens, level) {
3873
- const parser = new Parser(text, tokens);
3874
- const nodes = parser.list(level);
3875
- if (parser.at() === ")") refuse(`has an unmatched ")" ${parser.where()}`);
3876
- return nodes;
3835
+ function formatDeploymentLine(deployment) {
3836
+ return [
3837
+ deployment.id.padEnd(38),
3838
+ deployment.status.padEnd(10),
3839
+ deployment.branch.padEnd(16),
3840
+ shortSha(deployment.gitCommitSha).padEnd(9),
3841
+ deployment.url ?? ""
3842
+ ].join(" ");
3877
3843
  }
3878
-
3879
- // src/commands/policy.ts
3880
- var SET_USAGE = "Usage: naro policy set <table> [--select <rule>] [--insert <rule>] [--update <rule>] [--delete <rule>] [--owner <column>] [--select-when <filter>] [--insert-when <filter>] [--update-when <filter>] [--update-check <filter>] [--delete-when <filter>] [--signed-in] | --from-file <policy.json>";
3881
- var REMOVE_USAGE = "Usage: naro policy remove <table>";
3882
- var RULE_FLAGS = {
3883
- select: "selectRule",
3884
- insert: "insertRule",
3885
- update: "updateRule",
3886
- delete: "deleteRule"
3887
- };
3888
- var WHEN_FLAGS = {
3889
- select: { key: "selectWhen", tree: "using" },
3890
- insert: { key: "insertWhen", tree: "check" },
3891
- update: { key: "updateWhen", tree: "using" },
3892
- delete: { key: "deleteWhen", tree: "using" }
3844
+ async function runDeployments(context) {
3845
+ const client = await context.client();
3846
+ const projectId = await context.resolveProjectId();
3847
+ const deployments = await client.deployments.list(projectId);
3848
+ context.output.result({ projectId, deployments }, [
3849
+ `Deployments for ${projectId}:`,
3850
+ "",
3851
+ [
3852
+ "ID".padEnd(38),
3853
+ "STATUS".padEnd(10),
3854
+ "BRANCH".padEnd(16),
3855
+ "COMMIT".padEnd(9),
3856
+ "URL"
3857
+ ].join(" "),
3858
+ ...deployments.map(formatDeploymentLine)
3859
+ ]);
3860
+ }
3861
+ async function runInspect(context) {
3862
+ const [deploymentId] = context.positionalOrThrow(
3863
+ 1,
3864
+ "Usage: naro inspect <deployment-id>"
3865
+ );
3866
+ const client = await context.client();
3867
+ const detail = await client.deployments.get(deploymentId);
3868
+ const { deployment } = detail;
3869
+ const lastLogs = detail.logs.slice(-15);
3870
+ context.output.result({ deployment, logs: detail.logs }, [
3871
+ `Deployment ${deployment.id}`,
3872
+ ` status: ${deployment.status}${deployment.errorCode ? ` (${deployment.errorCode})` : ""}`,
3873
+ ` branch: ${deployment.branch}`,
3874
+ ` commit: ${deployment.gitCommitSha ?? "-"}`,
3875
+ ` url: ${deployment.url ?? "-"}`,
3876
+ ` created: ${deployment.createdAt}`,
3877
+ ` finished: ${deployment.finishedAt ?? "-"}`,
3878
+ ...deployment.errorMessage ? [` error: ${deployment.errorMessage}`] : [],
3879
+ ...lastLogs.length > 0 ? [
3880
+ "",
3881
+ "Recent build logs:",
3882
+ ...lastLogs.map((log) => ` [${log.stage}] ${log.message}`)
3883
+ ] : []
3884
+ ]);
3885
+ }
3886
+
3887
+ // src/commands/domains.ts
3888
+ var defaults3 = {
3889
+ sleep: (ms) => new Promise((resolve5) => setTimeout(resolve5, ms)),
3890
+ now: () => Date.now()
3893
3891
  };
3894
- var AUTH_UID = "auth.uid()";
3895
- var OTHER_FLAGS = [
3896
- "selectRule",
3897
- "insertRule",
3898
- "updateRule",
3899
- "deleteRule",
3900
- "ownerColumn",
3901
- "selectWhen",
3902
- "insertWhen",
3903
- "updateWhen",
3904
- "updateCheck",
3905
- "deleteWhen",
3906
- "signedIn"
3907
- ];
3908
- function isRule(value) {
3909
- return POLICY_RULES.includes(value);
3892
+ var FIRST_DELAY_MS = 5e3;
3893
+ var MAX_DELAY_MS = 3e4;
3894
+ var WAIT_TIMEOUT_MS = 10 * 6e4;
3895
+ function isReady(domain) {
3896
+ return domain.ready ?? (domain.status === "active" && domain.sslStatus === "active");
3910
3897
  }
3911
- function refuse2(message) {
3912
- throw new NaroError("VALIDATION_FAILED", message);
3898
+ function isTerminal(domain) {
3899
+ return domain.ownership === "deleted" || domain.status === "blocked" || domain.status === "moved" || domain.status === "deleted";
3913
3900
  }
3914
- function flagName(key) {
3915
- return `--${key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`;
3901
+ var AXIS_DONE = /* @__PURE__ */ new Set(["verified", "active", "live"]);
3902
+ var AXIS_FAILED = /* @__PURE__ */ new Set(["failed", "deleted"]);
3903
+ function axisMark(value) {
3904
+ if (AXIS_DONE.has(value)) return "\u2713";
3905
+ if (AXIS_FAILED.has(value)) return "\u2717";
3906
+ return "\xB7";
3916
3907
  }
3917
- function conditionTree(flag, text) {
3918
- const parsed = parseLogic(text, "and", {
3919
- tokens: { [AUTH_UID]: { auth: "uid" } },
3920
- group: false
3921
- });
3922
- if (!parsed.ok) refuse2(`${flag} ${parsed.reason}.`);
3923
- const tree = parsed.node;
3924
- const checked = parsePolicyNode(tree, "");
3925
- if (!checked.ok) {
3926
- const path = checked.path.replace(/^\./, "");
3927
- refuse2(
3928
- path === "" ? `${flag} ${checked.reason}.` : `${flag}: ${path} ${checked.reason}.`
3929
- );
3930
- }
3931
- return tree;
3908
+ function axisLines(domain) {
3909
+ const axes = [
3910
+ ["ownership", domain.ownership],
3911
+ ["certificate", domain.certificate],
3912
+ ["routing", domain.routing]
3913
+ ];
3914
+ return axes.filter((axis) => axis[1] !== void 0).map(
3915
+ ([name, value]) => ` ${`${name}:`.padEnd(13)}${axisMark(value)} ${value}`
3916
+ );
3932
3917
  }
3933
- function conditionsFrom(flags) {
3934
- const conditions = {};
3935
- for (const action of POLICY_ACTIONS) {
3936
- const { key, tree } = WHEN_FLAGS[action];
3937
- const text = flags[key];
3938
- if (text === void 0) continue;
3939
- const flag = flagName(key);
3940
- if (flags[RULE_FLAGS[action]] !== void 0)
3941
- refuse2(`--${action} and ${flag} cannot be used together.`);
3942
- const condition = { [tree]: conditionTree(flag, text) };
3943
- if (action === "update" && flags.updateCheck !== void 0)
3944
- condition.check = conditionTree("--update-check", flags.updateCheck);
3945
- if (flags.signedIn) condition.role = "authenticated";
3946
- conditions[action] = condition;
3947
- }
3948
- if (flags.updateCheck !== void 0 && flags.updateWhen === void 0)
3949
- refuse2("--update-check needs --update-when.");
3950
- if (flags.signedIn && Object.keys(conditions).length === 0)
3951
- refuse2(
3952
- "--signed-in needs --select-when, --insert-when, --update-when or --delete-when."
3953
- );
3954
- return conditions;
3918
+ function axisSummary(domain) {
3919
+ const axes = [
3920
+ domain.ownership,
3921
+ domain.certificate,
3922
+ domain.routing
3923
+ ].filter((value) => value !== void 0);
3924
+ return axes.length > 0 ? axes.join(" \xB7 ") : `${domain.status} \xB7 ssl ${domain.sslStatus}`;
3955
3925
  }
3956
- function patchFromFile(context, path, table) {
3957
- let text;
3958
- try {
3959
- text = readFileSync3(resolve4(context.cwd, path), "utf8");
3960
- } catch {
3961
- refuse2(`Could not read ${path}.`);
3962
- }
3963
- let body;
3964
- try {
3965
- body = JSON.parse(text);
3966
- } catch {
3967
- refuse2(`${path} is not JSON.`);
3968
- }
3969
- if (typeof body !== "object" || body === null || Array.isArray(body))
3970
- refuse2(`${path} must hold a JSON object.`);
3971
- const { table: named, ...patch } = body;
3972
- if (Object.hasOwn(body, "table")) {
3973
- if (typeof named !== "string")
3974
- refuse2(`${path}: table must be a string, the table's name.`);
3975
- if (table !== void 0 && asciiLower(named) !== asciiLower(table))
3976
- refuse2(
3977
- `${path} is the policy of ${printable(named)}, not ${printable(table)}. Remove its "table" to set it on ${printable(table)}.`
3926
+ function recordLines(domain) {
3927
+ const instructions = domain.instructions ?? [];
3928
+ if (instructions.length > 0) {
3929
+ const lines2 = [" Required DNS records:"];
3930
+ for (const instruction of instructions) {
3931
+ lines2.push(
3932
+ ` ${instruction.type.padEnd(5)} ${instruction.name}`,
3933
+ ` host: ${instruction.host.padEnd(24)} value: ${instruction.value}`
3978
3934
  );
3935
+ if (instruction.note) lines2.push(` note: ${instruction.note}`);
3936
+ }
3937
+ return lines2;
3979
3938
  }
3980
- const allowed = /* @__PURE__ */ new Set([...POLICY_ACTIONS, "ownerColumn"]);
3981
- if (Object.keys(patch).some((key) => !allowed.has(key)))
3982
- refuse2(
3983
- `${path}: Only table, select, insert, update, delete and ownerColumn can be set.`
3939
+ if (domain.verification.length === 0) return [];
3940
+ const lines = [" Required DNS records:"];
3941
+ for (const record of domain.verification) {
3942
+ lines.push(
3943
+ ` Type: ${record.type.toUpperCase().padEnd(6)} Name: ${record.name}`,
3944
+ ` Value: ${record.value}`
3984
3945
  );
3985
- return patch;
3986
- }
3987
- function asciiLower(text) {
3988
- return text.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
3989
- }
3990
- function policyPatch(flags, context, table) {
3991
- if (flags.fromFile !== void 0) {
3992
- if (OTHER_FLAGS.some(
3993
- (key) => flags[key] !== void 0 && flags[key] !== false
3994
- ))
3995
- refuse2(
3996
- "--from-file takes the whole policy: leave out the other policy options."
3997
- );
3998
- if (!context) refuse2(SET_USAGE);
3999
- return patchFromFile(context, flags.fromFile, table);
4000
3946
  }
4001
- const patch = {};
4002
- for (const action of POLICY_ACTIONS) {
4003
- const value = flags[RULE_FLAGS[action]];
4004
- if (value === void 0) continue;
4005
- if (!isRule(value))
4006
- refuse2(`--${action} must be one of ${POLICY_RULES.join(", ")}.`);
4007
- patch[action] = value;
3947
+ return lines;
3948
+ }
3949
+ function domainLines(domain) {
3950
+ const lines = [
3951
+ ` ${domain.hostname.padEnd(36)} ${domain.status.padEnd(12)} ssl: ${domain.sslStatus}`,
3952
+ ...axisLines(domain)
3953
+ ];
3954
+ if (domain.redirectTo) {
3955
+ const status = domain.redirectStatus ?? 308;
3956
+ lines.push(` redirects to ${domain.redirectTo} (${String(status)})`);
4008
3957
  }
4009
- Object.assign(patch, conditionsFrom(flags));
4010
- if (flags.ownerColumn !== void 0) {
4011
- if (flags.ownerColumn.trim() === "") refuse2("--owner must name a column.");
4012
- patch.ownerColumn = flags.ownerColumn;
3958
+ if (domain.cause) {
3959
+ lines.push(` \u2717 ${domain.cause.message}`);
3960
+ if (domain.cause.fix) lines.push(` \u2192 ${domain.cause.fix}`);
4013
3961
  }
4014
- if (Object.keys(patch).length === 0)
4015
- refuse2(
4016
- `Set at least one of --select, --insert, --update, --delete, --owner, --select-when, --insert-when, --update-when, --delete-when or --from-file. ${SET_USAGE}`
3962
+ if (isReady(domain)) return lines;
3963
+ lines.push(...recordLines(domain));
3964
+ const guidance = domain.guidance;
3965
+ if (guidance && guidance.notes.length > 0) {
3966
+ lines.push(
3967
+ guidance.apex ? ` Apex domain (${domain.hostname}):` : " Note:"
4017
3968
  );
4018
- return patch;
4019
- }
4020
- var SHORT = {
4021
- contains: "cs",
4022
- containedBy: "cd",
4023
- overlaps: "ov"
4024
- };
4025
- function isAuthUid(value) {
4026
- return typeof value === "object" && value !== null && value.auth === "uid";
4027
- }
4028
- function nearAuthUid(text) {
4029
- return text.replace(/\s+/g, "").toLowerCase().replace(/\(\)$/, "") === "auth.uid";
4030
- }
4031
- var DECIMAL2 = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/;
4032
- function readsAsNumber(value) {
4033
- const text = String(value);
4034
- if (!DECIMAL2.test(text) || !Object.is(Number(text), value)) return false;
4035
- return text.includes(".") || Number.isSafeInteger(value);
4036
- }
4037
- function stringText(value, slot) {
4038
- if (slot === "is") return void 0;
4039
- if (slot === "like" && value.includes("*")) return void 0;
4040
- const bare = value !== "" && value.trim() === value && !/[,()"{}\\]/.test(value) && !/^(?:true|false|null)$/i.test(value) && !nearAuthUid(value) && !(slot === "array" && DECIMAL2.test(value));
4041
- return bare ? value : quoteFilterValue(value);
3969
+ for (const note of guidance.notes) lines.push(` ${note}`);
3970
+ }
3971
+ return lines;
4042
3972
  }
4043
- function valueText(value, slot) {
4044
- if (isAuthUid(value))
4045
- return slot === "like" || slot === "is" ? void 0 : AUTH_UID;
4046
- if (value === null) return slot === "is" ? "null" : void 0;
4047
- if (typeof value === "boolean")
4048
- return slot === "is" || slot === "eq" || slot === "in" ? String(value) : void 0;
4049
- if (typeof value === "number")
4050
- return slot === "array" && readsAsNumber(value) ? String(value) : void 0;
4051
- if (typeof value === "string") return stringText(value, slot);
4052
- return void 0;
3973
+ async function runDomainsList(context) {
3974
+ const client = await context.client();
3975
+ const projectId = await context.resolveProjectId();
3976
+ const domains = await client.domains.list(projectId);
3977
+ const pending = domains.filter((domain) => !isReady(domain));
3978
+ context.output.result(
3979
+ { projectId, domains },
3980
+ domains.length === 0 ? ["No custom domains. Add one with `naro domains add example.com`."] : [
3981
+ `Domains (${String(domains.length)}):`,
3982
+ ...domains.flatMap(domainLines),
3983
+ // list reads our stored copy; only verify goes and looks again.
3984
+ ...pending.length > 0 ? ["", "Re-check DNS now: naro domains verify"] : []
3985
+ ]
3986
+ );
4053
3987
  }
4054
- function columnText(name) {
4055
- if (name === "") return void 0;
4056
- return /[.,()"\s]/.test(name) ? quoteFilterValue(name) : name;
3988
+ async function runDomainsAdd(context) {
3989
+ const [hostname] = context.positionalOrThrow(
3990
+ 1,
3991
+ "Usage: naro domains add <hostname> [--no-www]"
3992
+ );
3993
+ const client = await context.client();
3994
+ const projectId = await context.resolveProjectId();
3995
+ const withWww = context.flags.noWww !== true;
3996
+ const domain = await client.domains.add(projectId, hostname, {
3997
+ withWww
3998
+ });
3999
+ const companion = domain.companion;
4000
+ const apex = domain.apex ?? domain.guidance?.apex ?? false;
4001
+ const alternative = domain.guidance?.alternative ?? `www.${domain.hostname}`;
4002
+ context.output.result(
4003
+ { projectId, domain, withWww, ...companion ? { companion } : {} },
4004
+ [
4005
+ `\u2705 Domain added: ${domain.hostname}`,
4006
+ "",
4007
+ ...domainLines(domain),
4008
+ ...companion ? [
4009
+ "",
4010
+ ` Also registered ${companion.hostname} \u2014 an apex domain often cannot hold`,
4011
+ " the CNAME above, and this form always can.",
4012
+ "",
4013
+ ...domainLines(companion)
4014
+ ] : [],
4015
+ ...!companion && apex && !withWww ? [
4016
+ "",
4017
+ ` --no-www: ${domain.hostname} was registered on its own. If your registrar`,
4018
+ ` refuses the record above, run \`naro domains add ${alternative}\`.`
4019
+ ] : [],
4020
+ "",
4021
+ isReady(domain) ? "The domain is active." : "Status: Pending verification \u2014 add the DNS records above, then run `naro domains verify`."
4022
+ ]
4023
+ );
4057
4024
  }
4058
- function slotOf(operator) {
4059
- if (operator === "eq" || operator === "neq") return "eq";
4060
- if (operator === "like" || operator === "ilike") return "like";
4061
- if (operator === "is") return "is";
4062
- return "ordered";
4025
+ async function verifyAll(client, projectId, hostname, auto = false) {
4026
+ if (hostname !== void 0)
4027
+ return [
4028
+ await client.domains.verifyByHostname(projectId, hostname, { auto })
4029
+ ];
4030
+ const listed = await client.domains.list(projectId);
4031
+ const verified = [];
4032
+ for (const domain of listed)
4033
+ verified.push(await client.domains.verify(projectId, domain.id, { auto }));
4034
+ return verified;
4063
4035
  }
4064
- function leafText(leaf, negated) {
4065
- const column = columnText(leaf.column);
4066
- if (column === void 0) return void 0;
4067
- const prefix = `${column}.${negated ? "not." : ""}`;
4068
- const short = SHORT[leaf.operator];
4069
- if (leaf.operator === "in" || short !== void 0) {
4070
- if (!Array.isArray(leaf.value)) return void 0;
4071
- const slot = short === void 0 ? "in" : "array";
4072
- const items2 = leaf.value.map((item) => valueText(item, slot));
4073
- if (items2.some((item) => item === void 0)) return void 0;
4074
- const list = items2.join(",");
4075
- return slot === "in" ? `${prefix}in.(${list})` : `${prefix}${String(short)}.{${list}}`;
4036
+ async function runDomainsVerify(context, overrides = {}) {
4037
+ const deps = { ...defaults3, ...overrides };
4038
+ const client = await context.client();
4039
+ const projectId = await context.resolveProjectId();
4040
+ const hostname = context.positionals[0];
4041
+ const wait = context.flags.wait === true;
4042
+ const progress = (line) => {
4043
+ if (!context.flags.json) context.output.log(line);
4044
+ };
4045
+ let domains = await verifyAll(client, projectId, hostname);
4046
+ if (domains.length === 0) {
4047
+ context.output.result({ projectId, domains, ready: false }, [
4048
+ "No custom domains. Add one with `naro domains add example.com`."
4049
+ ]);
4050
+ return;
4076
4051
  }
4077
- if (Array.isArray(leaf.value)) return void 0;
4078
- const text = valueText(leaf.value, slotOf(leaf.operator));
4079
- return text === void 0 ? void 0 : `${prefix}${leaf.operator}.${text}`;
4080
- }
4081
- function groupText(kind, children) {
4082
- const texts = children.map((child) => filterText(child, false));
4083
- if (texts.length === 0 || texts.some((text) => text === void 0))
4084
- return void 0;
4085
- return `${kind}(${texts.join(",")})`;
4086
- }
4087
- function filterText(node, top = true) {
4088
- if ("operator" in node) return leafText(node, false);
4089
- if ("not" in node) {
4090
- const inner = node.not;
4091
- if ("operator" in inner) return leafText(inner, true);
4092
- if ("or" in inner) return negatedText(groupText("or", inner.or));
4093
- if ("and" in inner) return negatedText(groupText("and", inner.and));
4094
- return void 0;
4052
+ let timedOut = false;
4053
+ let abandoned = false;
4054
+ if (wait && !domains.every(isReady)) {
4055
+ const deadline = deps.now() + WAIT_TIMEOUT_MS;
4056
+ let delay = FIRST_DELAY_MS;
4057
+ for (; ; ) {
4058
+ const pending = domains.filter((domain) => !isReady(domain));
4059
+ if (pending.length > 0 && pending.every(isTerminal)) {
4060
+ abandoned = true;
4061
+ break;
4062
+ }
4063
+ const remaining = deadline - deps.now();
4064
+ if (remaining <= 0) {
4065
+ timedOut = true;
4066
+ break;
4067
+ }
4068
+ for (const domain of pending)
4069
+ progress(
4070
+ isTerminal(domain) ? `\u26A0 ${domain.hostname}: ${axisSummary(domain)} \u2014 waiting cannot fix this one` : `\u25B8 ${domain.hostname}: ${axisSummary(domain)}`
4071
+ );
4072
+ await deps.sleep(Math.min(delay, remaining));
4073
+ delay = Math.min(delay * 2, MAX_DELAY_MS);
4074
+ domains = await verifyAll(client, projectId, hostname, true);
4075
+ if (domains.every(isReady)) break;
4076
+ }
4095
4077
  }
4096
- if ("or" in node) return groupText("or", node.or);
4097
- if (top && node.and.length > 1) {
4098
- const texts = node.and.map((child) => filterText(child, false));
4099
- return texts.some((text) => text === void 0) ? void 0 : texts.join(",");
4078
+ const ready = domains.every(isReady);
4079
+ const body = domains.flatMap(domainLines);
4080
+ if (!ready) {
4081
+ for (const line of body) progress(line);
4082
+ const notReady = domains.filter((domain) => !isReady(domain));
4083
+ const names = notReady.map((domain) => domain.hostname).join(", ");
4084
+ const details = { projectId, domains, ready: false };
4085
+ if (timedOut) {
4086
+ const cause2 = notReady[0]?.cause;
4087
+ throw new NaroError(
4088
+ "TIMEOUT",
4089
+ `${names} did not go live within 10 minutes.${cause2 ? ` ${cause2.message}` : ""} DNS changes can take longer to propagate \u2014 re-run \`naro domains verify\` later.`,
4090
+ { details }
4091
+ );
4092
+ }
4093
+ if (abandoned) {
4094
+ const blocked = domains.find(isTerminal);
4095
+ throw new NaroError(
4096
+ blocked?.cause?.code ?? "DOMAIN_VERIFICATION_FAILED",
4097
+ blocked?.cause?.message ?? `${names} cannot be verified (status: ${blocked?.status ?? "unknown"}). Remove it and add it again.`,
4098
+ { details }
4099
+ );
4100
+ }
4101
+ const cause = notReady[0]?.cause;
4102
+ throw new NaroError(
4103
+ cause?.code ?? "DOMAIN_NOT_READY",
4104
+ `${names} is not live yet.${cause ? ` ${cause.message}` : ""} Add the records above, then run \`naro domains verify --wait\`.`,
4105
+ { details }
4106
+ );
4100
4107
  }
4101
- return groupText("and", node.and);
4108
+ context.output.result({ projectId, domains, ready }, [
4109
+ ...body,
4110
+ "",
4111
+ domains.length === 1 ? `\u2705 ${domains[0]?.hostname ?? ""} is live.` : "\u2705 Every domain is live."
4112
+ ]);
4102
4113
  }
4103
- function negatedText(text) {
4104
- return text === void 0 ? void 0 : `not.${text}`;
4114
+ async function runDomainsRemove(context) {
4115
+ const [hostname] = context.positionalOrThrow(
4116
+ 1,
4117
+ "Usage: naro domains remove <hostname>"
4118
+ );
4119
+ await confirmOrAbort(
4120
+ context,
4121
+ `Remove ${String(hostname)}? Traffic to it will stop routing here.`
4122
+ );
4123
+ const client = await context.client();
4124
+ const projectId = await context.resolveProjectId();
4125
+ await client.domains.remove(projectId, hostname);
4126
+ context.output.result({ projectId, hostname, removed: true }, [
4127
+ `\u2705 Removed ${String(hostname)}`
4128
+ ]);
4105
4129
  }
4106
- function isInvalid(value) {
4107
- return typeof value === "object" && "invalid" in value;
4130
+
4131
+ // src/commands/env.ts
4132
+ import { existsSync, writeFileSync as writeFileSync4 } from "fs";
4133
+ import { join as join4 } from "path";
4134
+ var TARGETS = /* @__PURE__ */ new Set(["production", "preview", "all"]);
4135
+ var KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
4136
+ function parseTarget(value) {
4137
+ if (value === void 0) return "all";
4138
+ if (!TARGETS.has(value))
4139
+ throw new NaroError(
4140
+ "VALIDATION_FAILED",
4141
+ "Environment must be production, preview or all."
4142
+ );
4143
+ return value;
4108
4144
  }
4109
- function cellOf(value) {
4110
- if (typeof value === "string") return value;
4111
- return isInvalid(value) ? "invalid" : "condition";
4145
+ function maskedValue(row) {
4146
+ if (!row.isSecret) return row.value ?? "";
4147
+ return "\u2022\u2022\u2022\u2022\u2022\u2022 (secret)";
4112
4148
  }
4113
- function conditionText(action, value) {
4114
- if (typeof value === "string") return value;
4115
- if (isInvalid(value))
4116
- return `cannot be read (${value.invalid}); it denies everyone but the service key`;
4117
- const using = value.using ? filterText(value.using) : "";
4118
- const check = value.check ? filterText(value.check) : "";
4119
- if (using === void 0 || check === void 0)
4120
- return `as JSON ${JSON.stringify(value)}`;
4121
- const parts = [];
4122
- if (using !== "") parts.push(`using ${using}`);
4123
- if (check !== "") parts.push(`check ${check}`);
4124
- else if (action === "update") parts.push("check = using");
4125
- const text = parts.join("; ");
4126
- return value.role === "authenticated" ? `${text} (signed-in users only)` : text;
4149
+ async function runEnvList(context) {
4150
+ const client = await context.client();
4151
+ const projectId = await context.resolveProjectId();
4152
+ const reveal = context.flags.reveal;
4153
+ const rows = await client.env.list(projectId, { reveal });
4154
+ context.output.result(
4155
+ {
4156
+ projectId,
4157
+ envVars: rows.map((row) => ({
4158
+ id: row.id,
4159
+ key: row.key,
4160
+ target: row.target,
4161
+ isSecret: row.isSecret,
4162
+ value: row.isSecret && !reveal ? null : row.value
4163
+ }))
4164
+ },
4165
+ [
4166
+ `Environment variables (${String(rows.length)}):`,
4167
+ ...rows.map(
4168
+ (row) => ` ${row.key.padEnd(32)} ${row.target.padEnd(12)} ${reveal ? row.value ?? "" : maskedValue(row)}`
4169
+ )
4170
+ ]
4171
+ );
4127
4172
  }
4128
- function policyTable(policies) {
4129
- const header = ["Table", ...POLICY_ACTIONS, "Owner column"];
4130
- const rows = policies.map((policy) => [
4131
- printable(policy.table),
4132
- ...POLICY_ACTIONS.map((action) => cellOf(policy[action])),
4133
- policy.ownerColumn === null ? "-" : printable(policy.ownerColumn)
4173
+ async function runEnvAdd(context) {
4174
+ context.positionalOrThrow(
4175
+ 1,
4176
+ "Usage: naro env add KEY [production|preview|all]"
4177
+ );
4178
+ const [key, targetArg] = context.positionals;
4179
+ if (!key || !KEY_RE.test(key) || key.length > 256)
4180
+ throw new NaroError(
4181
+ "VALIDATION_FAILED",
4182
+ "Keys must look like MY_VARIABLE (letters, digits, underscore)."
4183
+ );
4184
+ const target = parseTarget(targetArg);
4185
+ let value;
4186
+ if (!process.stdin.isTTY) {
4187
+ value = await readStdin();
4188
+ } else {
4189
+ value = await context.prompter.askHidden(`? What's the value of ${key}? `);
4190
+ }
4191
+ if (value.length === 0)
4192
+ throw new NaroError("VALIDATION_FAILED", `No value provided for ${key}.`);
4193
+ const isSecret = !key.startsWith("NEXT_PUBLIC_");
4194
+ const client = await context.client();
4195
+ const projectId = await context.resolveProjectId();
4196
+ await client.env.set(projectId, [{ key, value, target, isSecret }]);
4197
+ context.output.result({ projectId, key, target, isSecret }, [
4198
+ `\u2705 Added ${key} (${target}${isSecret ? ", secret" : ""})`
4134
4199
  ]);
4135
- const widths = header.map(
4136
- (title, index) => Math.max(title.length, ...rows.map((row) => row[index]?.length ?? 0))
4137
- );
4138
- const table = [header, ...rows].map(
4139
- (cells) => cells.map(
4140
- (cell, index) => index === cells.length - 1 ? cell : cell.padEnd(widths[index] ?? 0)
4141
- ).join(" ").trimEnd()
4200
+ }
4201
+ async function runEnvRemove(context) {
4202
+ context.positionalOrThrow(
4203
+ 1,
4204
+ "Usage: naro env remove KEY [production|preview|all]"
4142
4205
  );
4143
- const lines = policies.flatMap(
4144
- (policy) => POLICY_ACTIONS.filter((action) => typeof policy[action] !== "string").map(
4145
- (action) => ({
4146
- label: `${printable(policy.table)}.${action}`,
4147
- text: printable(conditionText(action, policy[action]))
4148
- })
4149
- )
4206
+ const [key, targetArg] = context.positionals;
4207
+ const target = targetArg === void 0 ? void 0 : parseTarget(targetArg);
4208
+ await confirmOrAbort(
4209
+ context,
4210
+ `Remove ${String(key)}${target ? ` (${target})` : ""} from this project?`
4150
4211
  );
4151
- if (lines.length === 0) return table;
4152
- const width = Math.max(...lines.map((line) => line.label.length));
4153
- return [
4154
- ...table,
4155
- "",
4156
- ...lines.map((line) => `${line.label.padEnd(width)} ${line.text}`)
4157
- ];
4212
+ const client = await context.client();
4213
+ const projectId = await context.resolveProjectId();
4214
+ const removed = await client.env.remove(projectId, key, target);
4215
+ context.output.result({ projectId, key, removed }, [
4216
+ `\u2705 Removed ${String(key)} (${String(removed)} entr${removed === 1 ? "y" : "ies"})`
4217
+ ]);
4158
4218
  }
4159
- async function runPolicyList(context) {
4219
+ async function runEnvPull(context) {
4220
+ const file = context.positionals[0] ?? ".env.local";
4221
+ const surface = context.flags.env === "production" ? "production" : "preview";
4222
+ if (context.flags.env && !["production", "preview"].includes(context.flags.env))
4223
+ throw new NaroError(
4224
+ "VALIDATION_FAILED",
4225
+ "--env must be production or preview."
4226
+ );
4160
4227
  const client = await context.client();
4161
4228
  const projectId = await context.resolveProjectId();
4162
- const policies = await client.backend.policies(projectId);
4229
+ const rows = await client.env.list(projectId, { reveal: true });
4230
+ const selected = rows.filter(
4231
+ (row) => row.target === "all" || row.target === surface
4232
+ );
4233
+ const vars = Object.fromEntries(
4234
+ selected.map((row) => [row.key, row.value ?? ""])
4235
+ );
4236
+ const path = join4(context.cwd, file);
4237
+ if (existsSync(path) && isInteractive() && !context.flags.yes && !context.flags.json) {
4238
+ const confirmed = await context.prompter.confirm(`Overwrite ${file}?`);
4239
+ if (!confirmed) throw new NaroError("CANCELED", "Canceled.");
4240
+ }
4241
+ writeFileSync4(
4242
+ path,
4243
+ `# Pulled from Naro (${surface}) \u2014 do not commit secrets.
4244
+ ${serializeDotenv(vars)}`,
4245
+ { mode: 384 }
4246
+ );
4163
4247
  context.output.result(
4164
- { projectId, policies },
4165
- policies.length === 0 ? [
4166
- "No policies yet: every table denies anon and signed-in requests.",
4167
- "Open one with `naro policy set <table> --select public`."
4168
- ] : [
4169
- ...policyTable(policies),
4170
- "",
4171
- "Tables not listed deny anon and signed-in requests. The service key skips policies."
4172
- ]
4248
+ { projectId, file, environment: surface, count: selected.length },
4249
+ [`\u2705 Pulled ${String(selected.length)} variable(s) into ${file}`]
4173
4250
  );
4174
4251
  }
4175
- async function runPolicySet(context) {
4176
- const [table] = context.positionalOrThrow(1, SET_USAGE);
4177
- const patch = policyPatch(context.flags, context, table);
4252
+
4253
+ // src/commands/gen.ts
4254
+ import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync5 } from "fs";
4255
+ import { dirname as dirname2, resolve as resolve4 } from "path";
4256
+ var LANG_MESSAGE = "naro gen types writes TypeScript only. Pass --lang typescript, or leave --lang out.";
4257
+ async function runGenTypes(context) {
4258
+ const { lang } = context.flags;
4259
+ if (lang !== void 0 && lang !== "typescript")
4260
+ throw new NaroError("VALIDATION_FAILED", LANG_MESSAGE);
4178
4261
  const client = await context.client();
4179
4262
  const projectId = await context.resolveProjectId();
4180
- const policy = await client.backend.setPolicy(
4181
- projectId,
4182
- table,
4183
- patch
4263
+ const tables = await client.db.tables(projectId);
4264
+ const read = await policiesForTypes(client, projectId);
4265
+ const types = generateTypes(
4266
+ tables,
4267
+ read.policies === void 0 ? {} : { policies: read.policies }
4184
4268
  );
4185
- context.output.result({ projectId, policy }, [
4186
- `\u2705 Saved the policy for ${printable(policy.table)}. It takes effect within about 10 seconds.`,
4187
- ...policyTable([policy])
4269
+ const undescribed = tables.flatMap(
4270
+ (table) => table.error === void 0 ? [] : [{ name: table.name, error: table.error }]
4271
+ );
4272
+ for (const { name, error } of undescribed)
4273
+ context.output.warn(
4274
+ `\u26A0 ${printable(name)} could not be described and was generated as an empty interface: ${printable(error)}`
4275
+ );
4276
+ if (read.policies === void 0)
4277
+ context.output.warn(
4278
+ `\u26A0 The backend's policies could not be read (${printable(read.reason)}), so owner columns stay required in Insert.`
4279
+ );
4280
+ const extra = {
4281
+ ...undescribed.length > 0 ? { undescribed } : {},
4282
+ ...read.policies === void 0 ? { policies: "unavailable", policiesReason: read.reason } : {}
4283
+ };
4284
+ if (context.flags.output) {
4285
+ const path = resolve4(context.cwd, context.flags.output);
4286
+ mkdirSync4(dirname2(path), { recursive: true });
4287
+ writeFileSync5(path, types);
4288
+ context.output.result(
4289
+ {
4290
+ projectId,
4291
+ output: context.flags.output,
4292
+ tables: tables.length,
4293
+ ...extra
4294
+ },
4295
+ [
4296
+ `\u2705 Wrote types for ${String(tables.length)} table(s) to ${context.flags.output}`
4297
+ ]
4298
+ );
4299
+ return;
4300
+ }
4301
+ context.output.result({ projectId, types, ...extra }, [
4302
+ types.replace(/\n$/, "")
4188
4303
  ]);
4189
4304
  }
4190
- async function runPolicyRemove(context) {
4191
- const [table] = context.positionalOrThrow(1, REMOVE_USAGE);
4192
- await confirmOrAbort(
4193
- context,
4194
- `Remove the policy for ${printable(table)}? Anon and signed-in requests to it are denied from then on.`
4305
+
4306
+ // src/commands/logs.ts
4307
+ var FOLLOW_INTERVAL_MS = 3e3;
4308
+ function sleep(ms) {
4309
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
4310
+ }
4311
+ function formatBuildLog(log) {
4312
+ return `[${log.stage}] ${log.level === "ERROR" ? "\u2717 " : ""}${log.message}`;
4313
+ }
4314
+ function formatRuntimeLog(entry) {
4315
+ const time = new Date(entry.ts).toISOString();
4316
+ const request = entry.method && entry.path ? ` ${entry.method} ${entry.path}${entry.status ? ` ${String(entry.status)}` : ""}` : "";
4317
+ return `${time} [${entry.level}]${request} ${entry.message}`.trimEnd();
4318
+ }
4319
+ async function latestProductionDeploymentId(client, projectId) {
4320
+ const deployments = await client.deployments.list(projectId);
4321
+ const latest = deployments.find(
4322
+ (deployment) => deployment.status === "READY"
4323
+ );
4324
+ const fallback = deployments[0];
4325
+ const chosen = latest ?? fallback;
4326
+ if (!chosen)
4327
+ throw new NaroError(
4328
+ "DEPLOYMENT_NOT_FOUND",
4329
+ "This project has no deployments yet."
4330
+ );
4331
+ return chosen.id;
4332
+ }
4333
+ async function buildLogs(context, client, deploymentId) {
4334
+ if (!context.flags.follow) {
4335
+ const detail = await client.deployments.get(deploymentId);
4336
+ context.output.result(
4337
+ { deploymentId, type: "build", logs: detail.logs },
4338
+ detail.logs.map(formatBuildLog)
4339
+ );
4340
+ return;
4341
+ }
4342
+ let lastSequence = -1;
4343
+ for (; ; ) {
4344
+ const detail = await client.deployments.get(deploymentId);
4345
+ for (const log of detail.logs) {
4346
+ if (log.sequence > lastSequence) {
4347
+ lastSequence = log.sequence;
4348
+ context.output.log(formatBuildLog(log));
4349
+ }
4350
+ }
4351
+ if (isTerminalStatus(detail.deployment.status)) {
4352
+ context.output.result(
4353
+ {
4354
+ deploymentId,
4355
+ type: "build",
4356
+ status: detail.deployment.status,
4357
+ logs: detail.logs
4358
+ },
4359
+ [`\u2014 deployment ${detail.deployment.status} \u2014`]
4360
+ );
4361
+ return;
4362
+ }
4363
+ await sleep(FOLLOW_INTERVAL_MS);
4364
+ }
4365
+ }
4366
+ async function runtimeLogs(context, client, projectId) {
4367
+ const environment = context.flags.env === "preview" ? "preview" : "production";
4368
+ if (context.flags.env && !["production", "preview"].includes(context.flags.env))
4369
+ throw new NaroError(
4370
+ "VALIDATION_FAILED",
4371
+ "--env must be production or preview."
4372
+ );
4373
+ const options = {
4374
+ environment,
4375
+ ...context.flags.level ? { level: context.flags.level } : {}
4376
+ };
4377
+ if (!context.flags.follow) {
4378
+ const entries = await client.logs.runtime(projectId, options);
4379
+ context.output.result(
4380
+ { projectId, type: "runtime", environment, entries },
4381
+ entries.length > 0 ? entries.map(formatRuntimeLog) : ["(no runtime logs yet \u2014 the worker logs on each request)"]
4382
+ );
4383
+ return;
4384
+ }
4385
+ context.output.log(
4386
+ `Following ${environment} runtime logs (Ctrl-C to stop)...`
4195
4387
  );
4388
+ let lastTs = -1;
4389
+ let boundary = /* @__PURE__ */ new Set();
4390
+ for (; ; ) {
4391
+ const entries = await client.logs.runtime(projectId, options);
4392
+ for (const entry of entries) {
4393
+ if (entry.ts < lastTs) continue;
4394
+ const key = JSON.stringify(entry);
4395
+ if (entry.ts === lastTs) {
4396
+ if (boundary.has(key)) continue;
4397
+ } else {
4398
+ lastTs = entry.ts;
4399
+ boundary = /* @__PURE__ */ new Set();
4400
+ }
4401
+ boundary.add(key);
4402
+ context.output.log(formatRuntimeLog(entry));
4403
+ }
4404
+ await sleep(FOLLOW_INTERVAL_MS);
4405
+ }
4406
+ }
4407
+ async function runLogs(context) {
4196
4408
  const client = await context.client();
4197
- const projectId = await context.resolveProjectId();
4198
- const policy = await client.backend.removePolicy(projectId, table);
4199
- context.output.result({ projectId, removed: true, policy }, [
4200
- `\u2705 Removed the policy for ${printable(policy.table)}. Anon and signed-in requests to it are denied within about 10 seconds.`
4201
- ]);
4409
+ const [deploymentId] = context.positionals;
4410
+ const type = context.flags.type ?? (deploymentId !== void 0 ? "build" : "runtime");
4411
+ if (type !== "build" && type !== "runtime")
4412
+ throw new NaroError(
4413
+ "VALIDATION_FAILED",
4414
+ "--type must be build or runtime."
4415
+ );
4416
+ if (type === "runtime") {
4417
+ if (deploymentId)
4418
+ throw new NaroError(
4419
+ "VALIDATION_FAILED",
4420
+ "Runtime logs are per project, not per deployment. Drop the deployment id or use --type build."
4421
+ );
4422
+ const projectId = await context.resolveProjectId();
4423
+ await runtimeLogs(context, client, projectId);
4424
+ return;
4425
+ }
4426
+ const target = deploymentId ?? await latestProductionDeploymentId(
4427
+ client,
4428
+ await context.resolveProjectId()
4429
+ );
4430
+ await buildLogs(context, client, target);
4202
4431
  }
4203
4432
 
4204
4433
  // src/commands/projects.ts
@@ -4438,15 +4667,24 @@ Usage:
4438
4667
  works too, but lands in shell history
4439
4668
  naro backend users delete <id|username|email>
4440
4669
  Delete a user and end its sessions (asks first; --yes to skip)
4441
- naro policy list Who the Data API lets through, per table (no policy = deny)
4670
+ naro policy list [--table <t>] Row-level security policies as CREATE POLICY (no policy = deny)
4671
+ naro policy create "CREATE POLICY <name> ON <table> \u2026" | --file <policies.sql>
4672
+ Postgres's CREATE POLICY: AS PERMISSIVE|RESTRICTIVE,
4673
+ FOR ALL|SELECT|INSERT|UPDATE|DELETE, TO anon|authenticated|public,
4674
+ USING (\u2026), WITH CHECK (\u2026); a file may hold DROP POLICY too
4675
+ (run in order, stops at the first refusal)
4676
+ [--allow-unindexed] Accept a subquery on the outer row that no index serves
4677
+ (refused otherwise, naming the index to create)
4678
+ naro policy drop <name> --table <t> DROP POLICY (asks first)
4442
4679
  naro policy set <table> [--select <rule>] [--insert <rule>] [--update <rule>] [--delete <rule>]
4443
4680
  [--owner <column>] Rules: none | public | authenticated | owner (owner needs --owner)
4444
4681
  [--select-when <filter>] [--insert-when <filter>] [--update-when <filter>]
4445
4682
  [--update-check <filter>] [--delete-when <filter>] [--signed-in]
4446
4683
  Or a condition per action, in Supabase filter syntax;
4447
4684
  auth.uid() is the signed-in user's id
4448
- [--from-file <policy.json>] Or the whole policy as JSON
4449
- naro policy remove <table> Back to deny for anon and signed-in requests (asks first)
4685
+ [--from-file <policy.json>] Or the whole policy as JSON. Writes the policies naro_select,
4686
+ naro_insert, naro_update, naro_delete (shorthand for CREATE POLICY)
4687
+ naro policy remove <table> Drop every policy on it: back to deny (asks first)
4450
4688
 
4451
4689
  naro promote <deployment-id> Publish a build to production
4452
4690
  naro rollback [deployment-id] Roll production back to the previous build
@@ -4463,7 +4701,7 @@ Global options:
4463
4701
  --prod Deploy/target production
4464
4702
  --wait Poll until the domain goes live (naro domains verify)
4465
4703
  --no-www Register the apex alone (naro domains add)
4466
- --file <path> SQL file to run (naro db query)
4704
+ --file <path> SQL file to run (naro db query, naro policy create)
4467
4705
  --dry-run Show what would change without changing it (naro db push, db restore, db reset, db table, db index)
4468
4706
  --output <file> Write to a file instead of stdout (naro gen types, db dump)
4469
4707
  --lang <lang> Language of the types; typescript, the default, is the only one (naro gen types)
@@ -4471,7 +4709,8 @@ Global options:
4471
4709
  --strict Fail on warnings too, not only errors (naro db lint)
4472
4710
  --schema-only Dump the schema without rows (naro db dump)
4473
4711
  --data-only Dump rows without the schema (naro db dump)
4474
- --table <a,b> Dump only these tables, comma-separated (naro db dump)
4712
+ --table <a,b> Dump only these tables, comma-separated (naro db dump); the policy's table
4713
+ (naro policy list, naro policy drop)
4475
4714
  --bookmark <id> Restore point: a bookmark from db dump or db restore (naro db restore)
4476
4715
  --timestamp <time> Restore point: RFC 3339 with a timezone, or Unix seconds (naro db restore)
4477
4716
  --status <s> applied or reverted (naro migration repair)
@@ -4758,6 +4997,13 @@ function route(parsed) {
4758
4997
  return { handler: runPolicyList, positionals: positionals.slice(1) };
4759
4998
  case "set":
4760
4999
  return { handler: runPolicySet, positionals: positionals.slice(1) };
5000
+ case "create":
5001
+ return {
5002
+ handler: runPolicyCreate,
5003
+ positionals: positionals.slice(1)
5004
+ };
5005
+ case "drop":
5006
+ return { handler: runPolicyDrop, positionals: positionals.slice(1) };
4761
5007
  case "remove":
4762
5008
  case "rm":
4763
5009
  return {