@somewhere-cloud/cli 0.38.172 → 0.38.174

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.
@@ -30833,7 +30833,7 @@ var require_util5 = __commonJS({
30833
30833
  "node_modules/undici/lib/web/websocket/util.js"(exports, module) {
30834
30834
  "use strict";
30835
30835
  var { states, opcodes } = require_constants5();
30836
- var { isUtf8 } = __require("node:buffer");
30836
+ var { isUtf8: isUtf82 } = __require("node:buffer");
30837
30837
  var { removeHTTPWhitespace } = require_data_url();
30838
30838
  var { collectASequenceOfCodePointsFast } = require_infra();
30839
30839
  function isConnecting(readyState) {
@@ -30993,7 +30993,7 @@ var require_util5 = __commonJS({
30993
30993
  return fatalDecoder.decode.bind(fatalDecoder);
30994
30994
  }
30995
30995
  return function(buffer) {
30996
- if (isUtf8(buffer)) {
30996
+ if (isUtf82(buffer)) {
30997
30997
  return buffer.toString("utf-8");
30998
30998
  }
30999
30999
  throw new TypeError("Invalid utf-8 received.");
@@ -67717,8 +67717,8 @@ var require_resolve = __commonJS({
67717
67717
  return count2;
67718
67718
  }
67719
67719
  __name(countKeys, "countKeys");
67720
- function getFullPath(resolver, id = "", normalize3) {
67721
- if (normalize3 !== false)
67720
+ function getFullPath(resolver, id = "", normalize4) {
67721
+ if (normalize4 !== false)
67722
67722
  id = normalizeId(id);
67723
67723
  const p2 = resolver.parse(id);
67724
67724
  return _getFullPath(resolver, p2);
@@ -69445,7 +69445,7 @@ var require_fast_uri = __commonJS({
69445
69445
  return stringScheme;
69446
69446
  }
69447
69447
  __name(validateScheme, "validateScheme");
69448
- function normalize3(uri, options2) {
69448
+ function normalize4(uri, options2) {
69449
69449
  if (typeof uri === "string") {
69450
69450
  uri = /** @type {T} */
69451
69451
  normalizeString(uri, options2);
@@ -69455,7 +69455,7 @@ var require_fast_uri = __commonJS({
69455
69455
  }
69456
69456
  return uri;
69457
69457
  }
69458
- __name(normalize3, "normalize");
69458
+ __name(normalize4, "normalize");
69459
69459
  function resolve27(baseURI, relativeURI, options2) {
69460
69460
  const schemelessOptions = options2 ? Object.assign({ scheme: "null" }, options2) : { scheme: "null" };
69461
69461
  const {
@@ -69862,7 +69862,7 @@ var require_fast_uri = __commonJS({
69862
69862
  __name(normalizeComparableURI, "normalizeComparableURI");
69863
69863
  var fastUri = {
69864
69864
  SCHEMES,
69865
- normalize: normalize3,
69865
+ normalize: normalize4,
69866
69866
  resolve: resolve27,
69867
69867
  resolveComponent,
69868
69868
  equal,
@@ -74136,6 +74136,110 @@ var init_privacy = __esm({
74136
74136
  }
74137
74137
  });
74138
74138
 
74139
+ // dist/lib/vendor/deploy-protected-files.js
74140
+ function normalize2(path3) {
74141
+ return path3.replace(/^\/+/, "");
74142
+ }
74143
+ function isProtectedDeployPath(path3) {
74144
+ const p2 = normalize2(path3);
74145
+ if (PROTECTED_NAMES.has(p2))
74146
+ return true;
74147
+ if (p2.startsWith(".env."))
74148
+ return true;
74149
+ if (PROTECTED_DIR_PREFIXES.some((prefix) => p2.startsWith(prefix) || p2.includes(`/${prefix}`)))
74150
+ return true;
74151
+ const base = p2.slice(p2.lastIndexOf("/") + 1);
74152
+ if (PROTECTED_BASENAMES.has(base))
74153
+ return true;
74154
+ if (base.startsWith(".env."))
74155
+ return true;
74156
+ return false;
74157
+ }
74158
+ function reincludePatterns(files) {
74159
+ const out = /* @__PURE__ */ new Set();
74160
+ {
74161
+ const content = files[IGNORE_FILE_NAME];
74162
+ if (typeof content !== "string")
74163
+ return out;
74164
+ for (const raw of content.split(/\r?\n/)) {
74165
+ const line = raw.trim();
74166
+ if (line.startsWith("!") && line.length > 1)
74167
+ out.add(normalize2(line.slice(1).trim()));
74168
+ }
74169
+ }
74170
+ return out;
74171
+ }
74172
+ function protectDeployFiles(files, binaryFiles) {
74173
+ const reinclude = reincludePatterns(files);
74174
+ const excluded = [];
74175
+ const reincluded = [];
74176
+ const keep = /* @__PURE__ */ __name((path3) => {
74177
+ const p2 = normalize2(path3);
74178
+ if (!isProtectedDeployPath(p2))
74179
+ return true;
74180
+ if (reinclude.has(p2)) {
74181
+ reincluded.push(p2);
74182
+ return true;
74183
+ }
74184
+ excluded.push(p2);
74185
+ return false;
74186
+ }, "keep");
74187
+ const outFiles = {};
74188
+ for (const [path3, content] of Object.entries(files)) {
74189
+ if (keep(path3))
74190
+ outFiles[path3] = content;
74191
+ }
74192
+ let outBinary = binaryFiles;
74193
+ if (binaryFiles) {
74194
+ outBinary = {};
74195
+ for (const [path3, content] of Object.entries(binaryFiles)) {
74196
+ if (keep(path3))
74197
+ outBinary[path3] = content;
74198
+ }
74199
+ }
74200
+ excluded.sort();
74201
+ reincluded.sort();
74202
+ return { files: outFiles, binaryFiles: outBinary, excluded, reincluded };
74203
+ }
74204
+ var IGNORE_FILE_NAME, PROTECTED_NAMES, PROTECTED_DIR_PREFIXES, PROTECTED_BASENAMES;
74205
+ var init_deploy_protected_files = __esm({
74206
+ "dist/lib/vendor/deploy-protected-files.js"() {
74207
+ "use strict";
74208
+ IGNORE_FILE_NAME = ".somewhereignore";
74209
+ PROTECTED_NAMES = /* @__PURE__ */ new Set([
74210
+ "CLAUDE.md",
74211
+ "AGENTS.md",
74212
+ "AGENT.md",
74213
+ "README.md",
74214
+ ".env",
74215
+ ".envrc",
74216
+ ".npmrc",
74217
+ ".somewhere.json",
74218
+ ".mcp.json",
74219
+ ".somewhereignore",
74220
+ ".gitignore",
74221
+ ".gitattributes",
74222
+ ".gitmodules",
74223
+ ".DS_Store",
74224
+ "Thumbs.db"
74225
+ ]);
74226
+ PROTECTED_DIR_PREFIXES = [
74227
+ ".git/",
74228
+ ".claude/",
74229
+ ".cursor/",
74230
+ ".vscode/",
74231
+ ".idea/",
74232
+ ".wrangler/",
74233
+ "node_modules/"
74234
+ ];
74235
+ PROTECTED_BASENAMES = /* @__PURE__ */ new Set([".DS_Store", ".env", "CLAUDE.md", "AGENTS.md"]);
74236
+ __name(normalize2, "normalize");
74237
+ __name(isProtectedDeployPath, "isProtectedDeployPath");
74238
+ __name(reincludePatterns, "reincludePatterns");
74239
+ __name(protectDeployFiles, "protectDeployFiles");
74240
+ }
74241
+ });
74242
+
74139
74243
  // dist/lib/role-method-hints.js
74140
74244
  import { existsSync as existsSync9, readdirSync as readdirSync2, readFileSync as readFileSync10 } from "node:fs";
74141
74245
  import { createRequire as createRequire3 } from "node:module";
@@ -76890,6 +76994,7 @@ __export(files_exports, {
76890
76994
  testExclusionReason: () => testExclusionReason,
76891
76995
  testFolderOf: () => testFolderOf
76892
76996
  });
76997
+ import { isUtf8 } from "node:buffer";
76893
76998
  import { existsSync as existsSync13, readdirSync as readdirSync3, readFileSync as readFileSync15, statSync as statSync2 } from "node:fs";
76894
76999
  import { extname as extname3, isAbsolute as isAbsolute2, join as join16, relative as relative6 } from "node:path";
76895
77000
  function isTestSourcePath(relPath) {
@@ -77062,14 +77167,17 @@ function classifyKey(relPath) {
77062
77167
  return { kind: "static", key: staticPath };
77063
77168
  }
77064
77169
  function classifyInto(out, baseDir, relPath, readBinary = true) {
77065
- const fullPath = join16(baseDir, relPath);
77066
77170
  const { kind, key } = classifyKey(relPath);
77067
- if (kind === "function") {
77068
- out.functions[key] = readFileSync15(fullPath, "utf-8");
77069
- } else if (kind === "binary") {
77070
- out.binaryFiles[key] = readBinary ? readFileSync15(fullPath).toString("base64") : "";
77171
+ const bytes = kind === "binary" && !readBinary ? Buffer.alloc(0) : readFileSync15(join16(baseDir, relPath));
77172
+ const binary = kind === "binary" || !isUtf8(bytes);
77173
+ if (binary) {
77174
+ if (kind === "function")
77175
+ throw new Error(`Function ${relPath} must contain UTF-8 source text.`);
77176
+ out.binaryFiles[key] = readBinary ? bytes.toString("base64") : "";
77177
+ } else if (kind === "function") {
77178
+ out.functions[key] = bytes.toString("utf8");
77071
77179
  } else {
77072
- out.files[key] = readFileSync15(fullPath, "utf-8");
77180
+ out.files[key] = bytes.toString("utf8");
77073
77181
  }
77074
77182
  }
77075
77183
  function formatBytes(bytes) {
@@ -77179,9 +77287,18 @@ function oversizeRefusal(collected) {
77179
77287
  return [
77180
77288
  `Nothing was sent. ${collected.oversize.length === 1 ? "This file is" : "These files are"} over the ${formatBytes(MAX_FILE_SIZE)} per-file limit and would be left out, which removes any copy already live:`,
77181
77289
  ...collected.oversize.map((entry) => ` ${entry.path} (${formatBytes(entry.bytes)})`),
77182
- "Make the file smaller, or keep it out of the deploy on purpose: add it to .somewhereignore (or .gitignore) or move it out of this folder, then run the command again."
77290
+ ...fileStorageRecovery(collected.oversize)
77183
77291
  ].join("\n");
77184
77292
  }
77293
+ function fileStorageRecovery(entries) {
77294
+ return [
77295
+ "Make the file smaller, or upload it to file storage and add its local path to .somewhereignore before retrying.",
77296
+ ...entries.map(({ path: path3 }) => {
77297
+ const remote = path3.replace(/^public\//, "");
77298
+ return ` ${cliInvocation()} fs put ${shellQuote(path3)} ${shellQuote(remote)}`;
77299
+ })
77300
+ ];
77301
+ }
77185
77302
  function includeHadNoEffect(baseDir, raw, published) {
77186
77303
  const path3 = toDeployPath(raw).replace(/^\.\//, "").replace(/\/+$/, "");
77187
77304
  if (!path3 || isAbsolute2(raw) || path3 === ".." || path3.startsWith("../"))
@@ -77222,7 +77339,8 @@ function previewOversizeRefusal(oversize) {
77222
77339
  return [
77223
77340
  `Nothing in this save was sent: ${oversize.length === 1 ? "this file is" : "these files are"} over the ${formatBytes(MAX_FILE_SIZE)} per-file limit:`,
77224
77341
  ...oversize.map((entry) => ` ${entry.path} (${formatBytes(entry.bytes)})`),
77225
- "Your last preview is unchanged. Make the file smaller (or add it to .somewhereignore), then save an app file again: the held changes are sent with the next save the watcher sees. Editing .somewhereignore alone is not a save it sees."
77342
+ ...fileStorageRecovery(oversize),
77343
+ "The last successful preview is still served. Save an app file again to send the held changes."
77226
77344
  ].join("\n");
77227
77345
  }
77228
77346
  function sensitiveReferenceRefusal(collected) {
@@ -77276,6 +77394,7 @@ var init_files = __esm({
77276
77394
  ".otf",
77277
77395
  ".eot",
77278
77396
  ".pdf",
77397
+ ".docx",
77279
77398
  ".zip",
77280
77399
  ".gz",
77281
77400
  ".tar",
@@ -77336,6 +77455,7 @@ var init_files = __esm({
77336
77455
  __name(globToRegExp, "globToRegExp");
77337
77456
  __name(escapeRegExp, "escapeRegExp");
77338
77457
  __name(oversizeRefusal, "oversizeRefusal");
77458
+ __name(fileStorageRecovery, "fileStorageRecovery");
77339
77459
  __name(includeHadNoEffect, "includeHadNoEffect");
77340
77460
  __name(previewBatchCheck, "previewBatchCheck");
77341
77461
  __name(previewOversizeRefusal, "previewOversizeRefusal");
@@ -84531,6 +84651,27 @@ Existing app: \`${cliInvocation()} pull <app>\` downloads the live source and li
84531
84651
  error(sizeRefusal);
84532
84652
  process.exit(1);
84533
84653
  }
84654
+ const submittedFiles = opts.scope === "functions" ? functionDependencyManifest(files) : files;
84655
+ const submittedBinaries = opts.scope === "functions" ? {} : binaryFiles;
84656
+ const submittedFunctions = opts.scope === "static" ? {} : functions;
84657
+ const measured = protectDeployFiles(submittedFiles, submittedBinaries);
84658
+ const sizes = /* @__PURE__ */ new Map();
84659
+ for (const [path3, content] of Object.entries(measured.files))
84660
+ sizes.set(path3, Buffer.byteLength(content));
84661
+ for (const [path3, content] of Object.entries(measured.binaryFiles ?? {}))
84662
+ sizes.set(path3, Buffer.byteLength(content, "base64"));
84663
+ for (const [path3, content] of Object.entries(submittedFunctions))
84664
+ sizes.set(path3, Buffer.byteLength(content));
84665
+ const payloadBytes = [...sizes.values()].reduce((total, bytes) => total + bytes, 0);
84666
+ const limitBytes = 20 * 1024 * 1024;
84667
+ if (payloadBytes > limitBytes) {
84668
+ const message3 = `This deploy contains ${(payloadBytes / 1024 ** 2).toFixed(1)} MiB of files. The limit is 20 MiB per deploy. Move large assets to file storage before deploying.`;
84669
+ if (opts.json)
84670
+ printJsonError("DEPLOY_TOO_LARGE", message3, { payload_bytes: payloadBytes, limit_bytes: limitBytes });
84671
+ else
84672
+ error(message3);
84673
+ process.exit(1);
84674
+ }
84534
84675
  if (Object.keys(files).length === 0 && Object.keys(binaryFiles).length === 0 && Object.keys(functions).length === 0) {
84535
84676
  const message3 = `No deployable source found. Create an index.html or add raw app source files, or add API handlers under api/, then run \`${cliInvocation()} deploy\` again.`;
84536
84677
  if (opts.json)
@@ -84898,14 +85039,14 @@ Existing app: \`${cliInvocation()} pull <app>\` downloads the live source and li
84898
85039
  // inverse: no functions. The dependency manifest is the functions'
84899
85040
  // too: a backend change that adds a package sends package.json (and
84900
85041
  // its lockfile), so the platform builds against the new dependencies.
84901
- files: scope === "functions" ? functionDependencyManifest(files) : files
85042
+ files: submittedFiles
84902
85043
  };
84903
- if (scope !== "functions" && Object.keys(binaryFiles).length > 0) {
84904
- body.binary_files = binaryFiles;
85044
+ if (Object.keys(submittedBinaries).length > 0) {
85045
+ body.binary_files = submittedBinaries;
84905
85046
  }
84906
85047
  const replaceFunctions = Boolean(opts.replaceFunctions) || !scope;
84907
85048
  if (scope !== "static" && (replaceFunctions || Object.keys(functions).length > 0)) {
84908
- body.functions = functions;
85049
+ body.functions = submittedFunctions;
84909
85050
  }
84910
85051
  if (scope)
84911
85052
  body.scope = scope;
@@ -84971,11 +85112,19 @@ Existing app: \`${cliInvocation()} pull <app>\` downloads the live source and li
84971
85112
  const requestStartedAt = performance.now();
84972
85113
  deployRequestStartedAt = (/* @__PURE__ */ new Date()).toISOString();
84973
85114
  const preparationMs = requestStartedAt - collectionEndedAt;
85115
+ body.deploy_attempt_id = crypto.randomUUID();
84974
85116
  const result = await callDeployWithRetry(client, body, {
84975
85117
  spinner,
84976
85118
  json: Boolean(opts.json),
84977
85119
  dryRun: false,
84978
85120
  baseText: spinner?.text ?? "Deploying..."
85121
+ }).catch(async (err) => {
85122
+ const attemptId = body.deploy_attempt_id;
85123
+ if (!projectId || typeof attemptId !== "string" || !outcomeUnknown(err))
85124
+ throw err;
85125
+ if (spinner)
85126
+ spinner.text = "Checking whether the deploy went live...";
85127
+ return await recoverDeployOutcome(client, projectId, attemptId) ?? Promise.reject(err);
84979
85128
  }).finally(stopPrestart);
84980
85129
  deployAnswered = true;
84981
85130
  answered = result;
@@ -85252,6 +85401,13 @@ ${dim("Build")}`);
85252
85401
  }
85253
85402
  process.exit(1);
85254
85403
  }
85404
+ if (err instanceof CliApiError && err.code === "DEPLOY_UNVERIFIED") {
85405
+ if (opts.json)
85406
+ printJsonError(err.code, err.message, err.data);
85407
+ else
85408
+ error(err.message);
85409
+ process.exit(1);
85410
+ }
85255
85411
  const live = opts.dryRun ? null : liveRefusal(err);
85256
85412
  if (live && err instanceof CliApiError) {
85257
85413
  const version2 = live.version ?? (answered && (answered.active_release_id ?? answered.release_id) === live.releaseId && typeof answered.version === "number" ? answered.version : null);
@@ -85501,6 +85657,8 @@ async function callDeployWithRetry(client, body, opts) {
85501
85657
  }
85502
85658
  if (waitMs)
85503
85659
  await new Promise((r) => setTimeout(r, waitMs));
85660
+ if (!opts.dryRun)
85661
+ body.deploy_attempt_id = crypto.randomUUID();
85504
85662
  attempt++;
85505
85663
  }
85506
85664
  }
@@ -85510,10 +85668,40 @@ function outcomeUnknown(err) {
85510
85668
  return false;
85511
85669
  if (err.meta.responseBodyIncomplete === true)
85512
85670
  return true;
85671
+ if (err.code === "CONTROL_UNAVAILABLE" || err.code === "DEPLOY_OUTCOME_UNKNOWN")
85672
+ return true;
85513
85673
  return RETRYABLE_DEPLOY_CODES.has(err.code) && err.meta.notSent !== true;
85514
85674
  }
85675
+ async function recoverDeployOutcome(client, projectId, attemptId) {
85676
+ const query = { project_id: projectId, deploy_attempt_id: attemptId };
85677
+ for (const delay2 of [0, 1e3, 2e3, 4e3, 8e3]) {
85678
+ if (delay2)
85679
+ await new Promise((resolve27) => setTimeout(resolve27, delay2));
85680
+ const status = await client.call("GET", "/deploy/status", void 0, query, { timeoutMs: 2e3, refresh: false }).catch(() => null);
85681
+ if (status?.deployment_outcome === "live" && status.verified === true && typeof status.release_id === "string" && status.release_id === status.active_release_id && status.project_id === projectId && typeof status.version === "number") {
85682
+ return { ...status, has_functions: status.has_functions === true };
85683
+ }
85684
+ if (status?.deployment_outcome === "unverified" && status.project_id === projectId && typeof status.release_id === "string" && status.release_id === status.active_release_id) {
85685
+ const next = `${cliInvocation()} status --project ${shellQuote(projectId)}`;
85686
+ throw new CliApiError("DEPLOY_UNVERIFIED", `The deploy failed verification. The release is still selected for production. Run \`${next}\` to inspect the current release.`, 409, {
85687
+ deployment_outcome: "unverified",
85688
+ base_recorded: false,
85689
+ release_id: status.release_id,
85690
+ active_release_id: status.active_release_id,
85691
+ ...typeof status.version === "number" ? { version: status.version } : {},
85692
+ next_steps: [next]
85693
+ });
85694
+ }
85695
+ if (status?.deployment_outcome === "not_live") {
85696
+ throw new CliApiError("DEPLOY_NOT_LIVE", "This deploy is not live. Check the deploy log for details.", 409);
85697
+ }
85698
+ if (status && status.deployment_outcome !== "pending")
85699
+ break;
85700
+ }
85701
+ return null;
85702
+ }
85515
85703
  function formatUnknownDeployOutcomeExplanation(err, projectId, startedAt) {
85516
- const what = err.meta.responseBodyIncomplete ? "got a response that was cut off before its result could be read" : err.code === "TIMEOUT" ? "timed out" : err.code === "SERVER_SLOW" ? "stalled waiting for the server" : "lost its connection";
85704
+ const what = err.meta.responseBodyIncomplete ? "got a response that was cut off before its result could be read" : err.code === "CONTROL_UNAVAILABLE" || err.code === "DEPLOY_OUTCOME_UNKNOWN" ? "did not get a confirmed result" : err.code === "TIMEOUT" ? "timed out" : err.code === "SERVER_SLOW" ? "stalled waiting for the server" : "lost its connection";
85517
85705
  const ids = [err.meta.requestId ? `request ${err.meta.requestId}` : "", err.meta.traceId ? `trace ${err.meta.traceId}` : ""].filter(Boolean);
85518
85706
  return [
85519
85707
  `The deploy request ${what} after it may have reached the platform. Its outcome is unknown: it may have gone live, may have been refused, or may still be running. It was not sent again, and this CLI cannot confirm what happened to it.`,
@@ -85680,6 +85868,7 @@ var import_prompts4, DOTFILE_NOTICE, SERVER_FRAMEWORK_DEPS, SERVER_CODE_PATTERN,
85680
85868
  var init_deploy = __esm({
85681
85869
  "dist/commands/deploy.js"() {
85682
85870
  "use strict";
85871
+ init_deploy_protected_files();
85683
85872
  init_first_cli_permission();
85684
85873
  init_init_scaffold();
85685
85874
  init_link_hint();
@@ -85793,6 +85982,7 @@ var init_deploy = __esm({
85793
85982
  __name(deployRetriedAfterTransportFailure, "deployRetriedAfterTransportFailure");
85794
85983
  __name(callDeployWithRetry, "callDeployWithRetry");
85795
85984
  __name(outcomeUnknown, "outcomeUnknown");
85985
+ __name(recoverDeployOutcome, "recoverDeployOutcome");
85796
85986
  __name(formatUnknownDeployOutcomeExplanation, "formatUnknownDeployOutcomeExplanation");
85797
85987
  __name(deployTimeoutMs, "deployTimeoutMs");
85798
85988
  __name(isRetryableDeployError, "isRetryableDeployError");
@@ -87206,9 +87396,9 @@ function registerDb(program2) {
87206
87396
  process.exit(1);
87207
87397
  }
87208
87398
  });
87209
- db.command("restore-points").description("List the restore points the platform keeps: full copies of the database taken before each deploy that changes its shape, daily when the data changed, and by hand (project owner only)").option("--project <id>", "Project ID (defaults to .somewhere.json)").option("--take", "Take a restore point now").option("--delete <id>", "Delete one restore point now").option("--json", "Print the API response as JSON").action(async (opts) => {
87210
- if (opts.take && opts.delete) {
87211
- error("Use --take or --delete, not both.");
87399
+ db.command("restore-points").description("List database restore points (project owner only)").option("--project <id>", "Project ID (defaults to .somewhere.json)").option("--take", "Take a restore point now").option("--delete <id>", "Delete one restore point now").option("--restore <id>", "Inspect or restore a database history point").option("--confirm-app <name>", "Confirm the exact app name. Members, groups and roles return to the saved moment.").option("--json", "Print the API response as JSON").action(async (opts) => {
87400
+ if ([opts.take, opts.delete, opts.restore].filter(Boolean).length > 1 || opts.confirmApp && !opts.restore) {
87401
+ error("Choose one action. --confirm-app requires --restore.");
87212
87402
  process.exit(1);
87213
87403
  }
87214
87404
  let projectId = opts.project;
@@ -87223,6 +87413,28 @@ function registerDb(program2) {
87223
87413
  const size = /* @__PURE__ */ __name((n) => n >= 1e6 ? `${(n / 1e6).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1e3))} KB`, "size");
87224
87414
  const client = new ApiClient(getToken());
87225
87415
  try {
87416
+ if (opts.restore) {
87417
+ if (opts.confirmApp && !opts.json) {
87418
+ info("Restoring returns the app\u2019s members, groups and roles to the recorded moment. People removed since then will have access again; remove them again after the restore. Completion can take a minute while cached sign-ins expire.");
87419
+ }
87420
+ const result = await client.call("POST", `/db/restore-points/${encodeURIComponent(opts.restore)}/restore`, {
87421
+ project_id: projectId,
87422
+ ...opts.confirmApp ? { confirm: { app: opts.confirmApp, point: opts.restore } } : {}
87423
+ }, void 0, opts.confirmApp ? { timeoutMs: 24e4 } : void 0);
87424
+ if (opts.json) {
87425
+ printJson(result);
87426
+ return;
87427
+ }
87428
+ if (result.confirmed) {
87429
+ success(`Database restored. Undo point: ${result.undo_point_id}.`);
87430
+ return;
87431
+ }
87432
+ info(result.warning);
87433
+ for (const moment of result.moments)
87434
+ info(`${moment.plane}: ${moment.at}`);
87435
+ info(`Confirm app "${result.app}" and point ${result.point_id} before ${result.expires_at}. Repeat with --confirm-app and the exact app name to restore.`);
87436
+ return;
87437
+ }
87226
87438
  if (opts.take) {
87227
87439
  const spinner = opts.json ? null : ora("Taking a restore point\u2026").start();
87228
87440
  let point = (await client.call("POST", "/db/restore-points", { project_id: projectId })).restore_point;
@@ -87230,7 +87442,7 @@ function registerDb(program2) {
87230
87442
  await new Promise((resolve27) => setTimeout(resolve27, 3e3));
87231
87443
  const listed = await client.call("GET", "/db/restore-points", void 0, { project_id: projectId });
87232
87444
  point = listed.restore_points.find((p2) => p2.id === point.id) ?? { ...point, state: "failed", detail: "It is no longer listed." };
87233
- if (spinner)
87445
+ if (spinner && point.rows)
87234
87446
  spinner.text = `Taking a restore point\u2026 ${point.rows.toLocaleString()} rows so far`;
87235
87447
  }
87236
87448
  if (opts.json) {
@@ -87248,7 +87460,10 @@ function registerDb(program2) {
87248
87460
  process.exitCode = 1;
87249
87461
  return;
87250
87462
  }
87251
- spinner?.succeed(`Restore point ${point.id} taken (${size(point.size_bytes)}, ${point.tables} tables, ${point.rows} rows); kept until ${point.expires_at}.`);
87463
+ if (point.kind === "history")
87464
+ spinner?.succeed(`Database history point ${point.id} recorded. It expires at ${point.expires_at}.`);
87465
+ else
87466
+ spinner?.succeed(`Restore point ${point.id} taken (${size(point.size_bytes)}, ${point.tables} tables, ${point.rows} rows); kept until ${point.expires_at}.`);
87252
87467
  for (const line of [point.consistency, point.validation])
87253
87468
  if (line)
87254
87469
  info(dim(line));
@@ -87268,13 +87483,15 @@ function registerDb(program2) {
87268
87483
  printJson(r);
87269
87484
  return;
87270
87485
  }
87486
+ if (r.restore)
87487
+ info(`${r.restore.point_id}: ${r.restore.message}`);
87271
87488
  if (!r.restore_points.length) {
87272
87489
  info(dim(`No restore points yet. Take one now with \`${cliInvocation()} db restore-points --take\`; the platform also takes them before deploys that change the database (when it can finish within the deploy's wait) and daily when the data changed.`));
87273
87490
  return;
87274
87491
  }
87275
- table(["Restore point", "Taken", "Why", "State", "Size", "Expires"], r.restore_points.map((p2) => [teal(p2.id), p2.taken_at, p2.reason, p2.state === "ready" ? p2.exact === false ? "ready (read while running)" : "ready" : `${p2.state}${p2.detail ? `: ${p2.detail}` : ""}`, p2.state === "ready" ? size(p2.size_bytes) : dim("\u2014"), p2.expires_at]));
87492
+ table(["Restore point", "Taken", "Why", "State", "Size", "Expires"], r.restore_points.map((p2) => [teal(p2.id), p2.taken_at, p2.reason, p2.state === "ready" ? p2.exact === false ? "ready (read while running)" : "ready" : `${p2.state}${p2.detail ? `: ${p2.detail}` : ""}`, p2.state === "ready" && p2.kind !== "history" ? size(p2.size_bytes) : dim("\u2014"), p2.expires_at]));
87276
87493
  for (const p2 of r.restore_points)
87277
- if (p2.state === "ready" && p2.consistency && p2.consistency !== "Read in one moment: an exact copy.")
87494
+ if ((p2.state === "ready" || p2.kind === "history") && p2.consistency && p2.consistency !== "Read in one moment: an exact copy.")
87278
87495
  info(dim(`${p2.id}: ${p2.consistency}`));
87279
87496
  } catch (err) {
87280
87497
  error(err instanceof Error ? err.message : String(err), err);
@@ -90390,7 +90607,7 @@ var init_preview_jobs = __esm({
90390
90607
 
90391
90608
  // dist/commands/dev.js
90392
90609
  import { randomUUID as randomUUID9 } from "node:crypto";
90393
- import { existsSync as existsSync36, readFileSync as readFileSync39 } from "node:fs";
90610
+ import { existsSync as existsSync36 } from "node:fs";
90394
90611
  import { join as join41, relative as relative11 } from "node:path";
90395
90612
  function previewFinishedReason(err) {
90396
90613
  if (!(err instanceof CliApiError) || err.code !== "DRAFT_SESSION_TERMINAL")
@@ -91382,13 +91599,7 @@ async function deployBatch(client, projectId, cwd, changed, deleted, draftId, ex
91382
91599
  const abs = join41(cwd, rel);
91383
91600
  if (!existsSync36(abs))
91384
91601
  continue;
91385
- const { kind, key } = classifyKey(rel);
91386
- if (kind === "function")
91387
- updateFunctions[key] = readFileSync39(abs, "utf-8");
91388
- else if (kind === "binary")
91389
- updateBinary[key] = readFileSync39(abs).toString("base64");
91390
- else
91391
- updateFiles[key] = readFileSync39(abs, "utf-8");
91602
+ classifyInto({ files: updateFiles, functions: updateFunctions, binaryFiles: updateBinary }, cwd, rel);
91392
91603
  }
91393
91604
  for (const rel of deleted)
91394
91605
  deleteKeys.push(classifyKey(rel).key);
@@ -132174,7 +132385,7 @@ var require_dist15 = __commonJS({
132174
132385
 
132175
132386
  // dist/lib/update-security.js
132176
132387
  import { createHash as createHash9, timingSafeEqual } from "node:crypto";
132177
- import { mkdirSync as mkdirSync19, readFileSync as readFileSync40, statSync as statSync7 } from "node:fs";
132388
+ import { mkdirSync as mkdirSync19, readFileSync as readFileSync39, statSync as statSync7 } from "node:fs";
132178
132389
  import { join as join44 } from "node:path";
132179
132390
  import { Readable as Readable3 } from "node:stream";
132180
132391
  import { pipeline as pipeline4 } from "node:stream/promises";
@@ -132342,8 +132553,8 @@ function stringMap(value, label) {
132342
132553
  return value;
132343
132554
  }
132344
132555
  function sameStringMap(left, right) {
132345
- const normalize3 = /* @__PURE__ */ __name((value) => Object.entries(value).sort(([a], [b2]) => a.localeCompare(b2)), "normalize");
132346
- return JSON.stringify(normalize3(left)) === JSON.stringify(normalize3(right));
132556
+ const normalize4 = /* @__PURE__ */ __name((value) => Object.entries(value).sort(([a], [b2]) => a.localeCompare(b2)), "normalize");
132557
+ return JSON.stringify(normalize4(left)) === JSON.stringify(normalize4(right));
132347
132558
  }
132348
132559
  function stringArray(value, label) {
132349
132560
  if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
@@ -132547,8 +132758,8 @@ async function verifyLockedArtifact(artifact, extractionDir, release2) {
132547
132758
  try {
132548
132759
  if (statSync7(lockPath).size > MAX_LOCKFILE_BYTES)
132549
132760
  throw new Error("lockfile too large");
132550
- manifest = JSON.parse(readFileSync40(manifestPath, "utf8"));
132551
- lock = JSON.parse(readFileSync40(lockPath, "utf8"));
132761
+ manifest = JSON.parse(readFileSync39(manifestPath, "utf8"));
132762
+ lock = JSON.parse(readFileSync39(lockPath, "utf8"));
132552
132763
  } catch (cause) {
132553
132764
  throw new Error(`the verified artifact has no readable npm-shrinkwrap dependency lock: ${message(cause)}`);
132554
132765
  }
@@ -132586,7 +132797,7 @@ async function verifyLockedArtifact(artifact, extractionDir, release2) {
132586
132797
  let bundledManifest;
132587
132798
  try {
132588
132799
  const bundledPath = join44(extractionDir, ...lockPath2.split("/"), "package.json");
132589
- bundledManifest = JSON.parse(readFileSync40(bundledPath, "utf8"));
132800
+ bundledManifest = JSON.parse(readFileSync39(bundledPath, "utf8"));
132590
132801
  } catch (cause) {
132591
132802
  throw new Error(`the verified artifact has an unreadable bundled dependency ${lockPath2}: ${message(cause)}`);
132592
132803
  }
@@ -132656,7 +132867,7 @@ ${GITHUB_REPOSITORY_ID}`,
132656
132867
  // dist/commands/update.js
132657
132868
  import { spawn as spawn6 } from "node:child_process";
132658
132869
  import { randomBytes as randomBytes8 } from "node:crypto";
132659
- import { closeSync as closeSync5, constants as constants2, fstatSync, mkdtempSync as mkdtempSync4, openSync as openSync5, readFileSync as readFileSync41, readSync, rmSync as rmSync15, unlinkSync as unlinkSync5, writeFileSync as writeFileSync25 } from "node:fs";
132870
+ import { closeSync as closeSync5, constants as constants2, fstatSync, mkdtempSync as mkdtempSync4, openSync as openSync5, readFileSync as readFileSync40, readSync, rmSync as rmSync15, unlinkSync as unlinkSync5, writeFileSync as writeFileSync25 } from "node:fs";
132660
132871
  import { createServer } from "node:http";
132661
132872
  import { tmpdir as tmpdir2 } from "node:os";
132662
132873
  import { join as join45 } from "node:path";
@@ -132667,7 +132878,7 @@ function refuse2(cause) {
132667
132878
  }
132668
132879
  function currentVersion2() {
132669
132880
  try {
132670
- const pkg = JSON.parse(readFileSync41(join45(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
132881
+ const pkg = JSON.parse(readFileSync40(join45(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
132671
132882
  return pkg.version;
132672
132883
  } catch {
132673
132884
  return "0.0.0";
@@ -133014,7 +133225,7 @@ var init_upgrade = __esm({
133014
133225
  });
133015
133226
 
133016
133227
  // dist/commands/call.js
133017
- import { readFileSync as readFileSync42 } from "node:fs";
133228
+ import { readFileSync as readFileSync41 } from "node:fs";
133018
133229
  function parseArguments(value, file) {
133019
133230
  if (value === void 0)
133020
133231
  return {};
@@ -133038,7 +133249,7 @@ function readCallArguments(jsonArgs, file) {
133038
133249
  }
133039
133250
  let text;
133040
133251
  try {
133041
- text = readFileSync42(file, "utf8");
133252
+ text = readFileSync41(file, "utf8");
133042
133253
  } catch (err) {
133043
133254
  const code = err?.code;
133044
133255
  throw new Error(`Could not read --file ${file}${code ? ` (${code})` : ""}. The requested tool was not called.`);
@@ -135366,7 +135577,7 @@ var init_test_response_capture = __esm({
135366
135577
  import { randomUUID as randomUUID12 } from "node:crypto";
135367
135578
  import { setDefaultResultOrder } from "node:dns";
135368
135579
  import { lookup } from "node:dns/promises";
135369
- import { existsSync as existsSync38, mkdirSync as mkdirSync20, readFileSync as readFileSync43, writeFileSync as writeFileSync26 } from "node:fs";
135580
+ import { existsSync as existsSync38, mkdirSync as mkdirSync20, readFileSync as readFileSync42, writeFileSync as writeFileSync26 } from "node:fs";
135370
135581
  import { basename as basename10, dirname as dirname15, join as join46, relative as relative12, resolve as resolve24 } from "node:path";
135371
135582
  function launchOptions(extra = {}) {
135372
135583
  return { ...extra, args: ["--disable-features=AsyncDns", ...extra.args ?? []] };
@@ -135420,7 +135631,7 @@ function undeployedChanges(root, projectId, preview = false) {
135420
135631
  const path3 = join46(root, ".somewhere", "base-files.json");
135421
135632
  if (!existsSync38(path3))
135422
135633
  return null;
135423
- base = JSON.parse(readFileSync43(path3, "utf8"));
135634
+ base = JSON.parse(readFileSync42(path3, "utf8"));
135424
135635
  }
135425
135636
  if (base.project_id !== projectId || !base.files)
135426
135637
  return null;
@@ -136363,7 +136574,7 @@ var init_reference_check_note = __esm({
136363
136574
 
136364
136575
  // dist/lib/test-scripts.js
136365
136576
  import { createRequire as createRequire10 } from "node:module";
136366
- import { existsSync as existsSync39, mkdirSync as mkdirSync21, readFileSync as readFileSync44, readdirSync as readdirSync8, rmSync as rmSync17, statSync as statSync8, writeFileSync as writeFileSync27 } from "node:fs";
136577
+ import { existsSync as existsSync39, mkdirSync as mkdirSync21, readFileSync as readFileSync43, readdirSync as readdirSync8, rmSync as rmSync17, statSync as statSync8, writeFileSync as writeFileSync27 } from "node:fs";
136367
136578
  import { dirname as dirname16, join as join47, relative as relative13, resolve as resolve25 } from "node:path";
136368
136579
  import { spawn as spawn7, spawnSync as spawnSync5 } from "node:child_process";
136369
136580
  function hasSpecFiles(root) {
@@ -136463,7 +136674,7 @@ async function runScripts(root, scripts, extraArgs, env = scriptBrowserEnv(root)
136463
136674
  stderrLines("", true);
136464
136675
  let report2 = null;
136465
136676
  try {
136466
- report2 = existsSync39(handOver) ? JSON.parse(readFileSync44(handOver, "utf8")) : null;
136677
+ report2 = existsSync39(handOver) ? JSON.parse(readFileSync43(handOver, "utf8")) : null;
136467
136678
  } catch {
136468
136679
  report2 = null;
136469
136680
  }
@@ -136500,13 +136711,13 @@ function lastFailedScripts(root) {
136500
136711
  if (!existsSync39(path3))
136501
136712
  return [];
136502
136713
  try {
136503
- return (JSON.parse(readFileSync44(path3, "utf8")).results ?? []).filter((r) => !r.ok).map((r) => r.script);
136714
+ return (JSON.parse(readFileSync43(path3, "utf8")).results ?? []).filter((r) => !r.ok).map((r) => r.script);
136504
136715
  } catch {
136505
136716
  return [];
136506
136717
  }
136507
136718
  }
136508
136719
  function recordScriptResults(root, results, rerunOnly) {
136509
- const previous = rerunOnly && existsSync39(join47(root, LAST)) ? JSON.parse(readFileSync44(join47(root, LAST), "utf8")).results ?? [] : [];
136720
+ const previous = rerunOnly && existsSync39(join47(root, LAST)) ? JSON.parse(readFileSync43(join47(root, LAST), "utf8")).results ?? [] : [];
136510
136721
  const merged = [...previous.filter((p2) => !results.some((r) => r.script === p2.script)), ...results];
136511
136722
  mkdirSync21(join47(root, ".somewhere", "tests"), { recursive: true });
136512
136723
  writeFileSync27(join47(root, LAST), JSON.stringify({ finished: (/* @__PURE__ */ new Date()).toISOString(), results: merged }, null, 2) + "\n");
@@ -136622,7 +136833,7 @@ var init_test = __esm({
136622
136833
  });
136623
136834
 
136624
136835
  // dist/commands/test-users.js
136625
- import { existsSync as existsSync40, readFileSync as readFileSync45, rmSync as rmSync18 } from "node:fs";
136836
+ import { existsSync as existsSync40, readFileSync as readFileSync44, rmSync as rmSync18 } from "node:fs";
136626
136837
  import { basename as basename11, join as join48 } from "node:path";
136627
136838
  import { randomBytes as randomBytes9 } from "node:crypto";
136628
136839
  async function resolveTarget(projectOpt, originOpt) {
@@ -137149,7 +137360,7 @@ var init_skills = __esm({
137149
137360
  });
137150
137361
 
137151
137362
  // dist/commands/ai.js
137152
- import { readFileSync as readFileSync46 } from "node:fs";
137363
+ import { readFileSync as readFileSync45 } from "node:fs";
137153
137364
  function fail4(message3) {
137154
137365
  error(message3);
137155
137366
  process.exit(1);
@@ -137170,7 +137381,7 @@ async function readKey(stdin) {
137170
137381
  if (stdin) {
137171
137382
  if (process.stdin.isTTY)
137172
137383
  fail4("Pipe the key into --stdin, or leave out --stdin to type it into a hidden prompt.");
137173
- raw = readFileSync46(0, "utf8");
137384
+ raw = readFileSync45(0, "utf8");
137174
137385
  } else {
137175
137386
  if (!process.stdin.isTTY)
137176
137387
  fail4("Pass --stdin to read the key from a pipe. Nothing was sent.");
@@ -137400,7 +137611,7 @@ __export(dist_exports, {
137400
137611
  runCli: () => runCli
137401
137612
  });
137402
137613
  import { spawnSync as spawnSync6 } from "node:child_process";
137403
- import { readFileSync as readFileSync47 } from "node:fs";
137614
+ import { readFileSync as readFileSync46 } from "node:fs";
137404
137615
  import { join as join51 } from "node:path";
137405
137616
  async function runCli() {
137406
137617
  const pinned = decidePin(process.cwd(), CLI_VERSION2, process.argv, process.env);
@@ -137429,7 +137640,7 @@ async function runCli() {
137429
137640
  process.exit(child.status ?? 1);
137430
137641
  }
137431
137642
  removeStaleRunRecord();
137432
- const pkg = JSON.parse(readFileSync47(join51(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
137643
+ const pkg = JSON.parse(readFileSync46(join51(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
137433
137644
  const program2 = new Command().name(cliInvocation()).description(`CLI for somewhere.cloud. Run ${cliInvocation()} init first, then read generated AGENTS.md: call shapes and access patterns for a typical app; docs are for exceptions.`).version(pkg.version);
137434
137645
  recordLastRun(pkg.version);
137435
137646
  const jsonOutputRequested = process.argv.includes("--json");