@somewhere-cloud/cli 0.38.154 → 0.38.156

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.
@@ -44184,6 +44184,8 @@ Use \`somewhere docs <topic> --section <id>\` for one section or \`--full\` for
44184
44184
  INIT_AGENTS_MD = `# somewhere.cloud project contract
44185
44185
  ${AGENT_WORKFLOW}
44186
44186
  ${SKILLS_POINTER}
44187
+ Search the live docs with \`somewhere docs --search "<words>"\`.
44188
+ Download Markdown to \`.somewhere/docs/\` with \`somewhere docs pull\`.
44187
44189
  Without a global CLI, use \`npx @somewhere-cloud/cli deploy\` and \`npx @somewhere-cloud/cli test\`.
44188
44190
 
44189
44191
  For Node or Playwright tests, see [Testing your app](https://somewhere.cloud/docs/test).
@@ -44236,11 +44238,15 @@ try {
44236
44238
  });
44237
44239
 
44238
44240
  // dist/lib/typecheck-version.js
44239
- var TYPECHECK_TYPESCRIPT_VERSION;
44241
+ import { createRequire as createRequire2 } from "node:module";
44242
+ var require3, checkerContract, TYPECHECK_TYPESCRIPT_VERSION;
44240
44243
  var init_typecheck_version = __esm({
44241
44244
  "dist/lib/typecheck-version.js"() {
44242
44245
  "use strict";
44243
- TYPECHECK_TYPESCRIPT_VERSION = "5.9.3";
44246
+ init_package_root();
44247
+ require3 = createRequire2(CLI_PACKAGE_ROOT);
44248
+ ({ checkerContract } = require3("./runtime/declared-data.cjs"));
44249
+ TYPECHECK_TYPESCRIPT_VERSION = checkerContract.TYPESCRIPT_VERSION;
44244
44250
  }
44245
44251
  });
44246
44252
 
@@ -52595,7 +52601,16 @@ function registerProject(program2) {
52595
52601
  process.exit(1);
52596
52602
  }
52597
52603
  });
52598
- proj.command("delete <name-or-id>").description("Permanently delete a project and all its data").option("--confirm-code <code>", "Confirm deletion with the code returned by the first call").option("--json", "Print the raw delete response as JSON").action(async (nameOrId, opts) => {
52604
+ proj.command("delete <name-or-id>").description("Permanently delete a project and all its data").option("--confirm-code <code>", "Confirm deletion using the confirm_code returned by the first call").option("--json", "Print the deletion result as JSON").addOption(new Option("--yes").hideHelp()).addOption(new Option("--force").hideHelp()).action(async (nameOrId, opts) => {
52605
+ const unsupported = opts.yes ? "--yes" : opts.force ? "--force" : void 0;
52606
+ if (unsupported) {
52607
+ const message3 = `Unknown option '${unsupported}'. Run ${cliInvocation()} project delete <name-or-id> to get a code, then repeat with --confirm-code <code>.`;
52608
+ if (opts.json)
52609
+ printJsonError("UNKNOWN_OPTION", message3);
52610
+ else
52611
+ error(message3);
52612
+ process.exit(1);
52613
+ }
52599
52614
  const client = new ApiClient(getToken());
52600
52615
  const promptStdout = opts.json ? process.stderr : void 0;
52601
52616
  let project;
@@ -52626,7 +52641,7 @@ function registerProject(program2) {
52626
52641
  if (opts.json) {
52627
52642
  printJson({
52628
52643
  status: "needs_confirmation",
52629
- confirmation_code: code,
52644
+ confirm_code: code,
52630
52645
  confirm_command: confirmCommand
52631
52646
  });
52632
52647
  } else {
@@ -73980,7 +73995,7 @@ var init_privacy = __esm({
73980
73995
 
73981
73996
  // dist/lib/role-method-hints.js
73982
73997
  import { existsSync as existsSync9, readdirSync as readdirSync2, readFileSync as readFileSync10 } from "node:fs";
73983
- import { createRequire as createRequire2 } from "node:module";
73998
+ import { createRequire as createRequire3 } from "node:module";
73984
73999
  import { join as join9, relative as relative2, resolve as resolve4 } from "node:path";
73985
74000
  function roleMethodHints(projectDir, { removedOnly = false } = {}) {
73986
74001
  const api = join9(projectDir, "api");
@@ -73989,7 +74004,7 @@ function roleMethodHints(projectDir, { removedOnly = false } = {}) {
73989
74004
  const skipped = ["Role-method hints skipped: TypeScript is unavailable in this project."];
73990
74005
  let ts2;
73991
74006
  try {
73992
- const projectRequire = createRequire2(resolve4(projectDir, "package.json"));
74007
+ const projectRequire = createRequire3(resolve4(projectDir, "package.json"));
73993
74008
  ts2 = projectRequire("typescript");
73994
74009
  } catch {
73995
74010
  return skipped;
@@ -74305,7 +74320,7 @@ __export(declared_data_exports, {
74305
74320
  prepareDeclaredData: () => prepareDeclaredData
74306
74321
  });
74307
74322
  import { existsSync as existsSync11, readFileSync as readFileSync13, rmSync as rmSync2, writeFileSync as writeFileSync9 } from "node:fs";
74308
- import { createRequire as createRequire3 } from "node:module";
74323
+ import { createRequire as createRequire4 } from "node:module";
74309
74324
  import { join as join12, resolve as resolve5 } from "node:path";
74310
74325
  function generatedContents(path3) {
74311
74326
  const previous = existsSync11(path3) ? readFileSync13(path3, "utf8") : void 0;
@@ -74326,7 +74341,7 @@ function prepareDeclaredData(projectDir) {
74326
74341
  rmSync2(filesPath);
74327
74342
  if (previous !== void 0 && !previous.startsWith(GENERATED_DATA_HEADER))
74328
74343
  return void 0;
74329
- const generator2 = require3("./runtime/declared-data.cjs");
74344
+ const generator2 = require4("./runtime/declared-data.cjs");
74330
74345
  const declaration2 = GENERATED_DATA_HEADER + NO_SCHEMA_NOTE + generator2.RUNTIME_CONTEXT_DECLARATION + generator2.ENDPOINT_DECLARATION + SW_ENDPOINT_GLOBAL;
74331
74346
  if (declaration2 !== previous)
74332
74347
  writeFileSync9(declarationPath, declaration2);
@@ -74339,7 +74354,7 @@ function prepareDeclaredData(projectDir) {
74339
74354
  let tables;
74340
74355
  let runtimeDeclaration;
74341
74356
  let filesDeclaration;
74342
- const generator = require3("./runtime/declared-data.cjs");
74357
+ const generator = require4("./runtime/declared-data.cjs");
74343
74358
  try {
74344
74359
  const files = { "db/schema.ts": readFileSync13(schemaPath, "utf8") };
74345
74360
  client = generator.generateFromFiles(files);
@@ -74418,7 +74433,7 @@ function declaredDataPlugin(projectDir) {
74418
74433
  }
74419
74434
  };
74420
74435
  }
74421
- var DATA_MODULE, DATA_VIRTUAL_ID, DATA_DECLARATION_FILE, GENERATED_DATA_HEADER, NO_SCHEMA_NOTE, SW_ENDPOINT_GLOBAL, require3, FILES_DECLARATION_FILE;
74436
+ var DATA_MODULE, DATA_VIRTUAL_ID, DATA_DECLARATION_FILE, GENERATED_DATA_HEADER, NO_SCHEMA_NOTE, SW_ENDPOINT_GLOBAL, require4, FILES_DECLARATION_FILE;
74422
74437
  var init_declared_data = __esm({
74423
74438
  "dist/lib/declared-data.js"() {
74424
74439
  "use strict";
@@ -74439,8 +74454,8 @@ var init_declared_data = __esm({
74439
74454
  ): (req: Request, sw: SomewhereRuntimeContext) => Promise<Response>;
74440
74455
  };
74441
74456
  `;
74442
- require3 = createRequire3(CLI_PACKAGE_ROOT);
74443
- FILES_DECLARATION_FILE = require3("./runtime/declared-data.cjs").FILES_DECLARATION_FILE;
74457
+ require4 = createRequire4(CLI_PACKAGE_ROOT);
74458
+ FILES_DECLARATION_FILE = require4("./runtime/declared-data.cjs").FILES_DECLARATION_FILE;
74444
74459
  __name(generatedContents, "generatedContents");
74445
74460
  __name(prepareDeclaredData, "prepareDeclaredData");
74446
74461
  __name(declaredDataPlugin, "declaredDataPlugin");
@@ -77183,7 +77198,7 @@ var init_files = __esm({
77183
77198
  // dist/lib/deploy-check.js
77184
77199
  import { randomUUID as randomUUID5 } from "node:crypto";
77185
77200
  import { existsSync as existsSync14, mkdirSync as mkdirSync8, readFileSync as readFileSync16, realpathSync as realpathSync2, rmSync as rmSync4, writeFileSync as writeFileSync11 } from "node:fs";
77186
- import { createRequire as createRequire4 } from "node:module";
77201
+ import { createRequire as createRequire5 } from "node:module";
77187
77202
  import { isAbsolute as isAbsolute3, join as join17, relative as relative7, resolve as resolve8 } from "node:path";
77188
77203
  function projectTypeScriptVersion(projectDir) {
77189
77204
  try {
@@ -77349,17 +77364,18 @@ async function startDeployCheck(projectDir, onFetch) {
77349
77364
  }
77350
77365
  return { ok: findings.length === 0, findings, typescript, checkedFiles: checked.length };
77351
77366
  }
77352
- var require4, vendor2, contract, DEPLOY_CHECK_TYPESCRIPT_VERSION, DIAGNOSTIC, GLOBAL_ERROR, pendingCleanups;
77367
+ var require5, vendor2, contract, DEPLOY_CHECK_TYPESCRIPT_VERSION, DIAGNOSTIC, GLOBAL_ERROR, pendingCleanups;
77353
77368
  var init_deploy_check = __esm({
77354
77369
  "dist/lib/deploy-check.js"() {
77355
77370
  "use strict";
77356
77371
  init_package_root();
77372
+ init_typecheck_version();
77357
77373
  init_files();
77358
77374
  init_typecheck();
77359
- require4 = createRequire4(CLI_PACKAGE_ROOT);
77360
- vendor2 = require4("./runtime/declared-data.cjs");
77375
+ require5 = createRequire5(CLI_PACKAGE_ROOT);
77376
+ vendor2 = require5("./runtime/declared-data.cjs");
77361
77377
  contract = vendor2.checkerContract;
77362
- DEPLOY_CHECK_TYPESCRIPT_VERSION = contract.TYPESCRIPT_VERSION;
77378
+ DEPLOY_CHECK_TYPESCRIPT_VERSION = TYPECHECK_TYPESCRIPT_VERSION;
77363
77379
  __name(projectTypeScriptVersion, "projectTypeScriptVersion");
77364
77380
  __name(announceDeployCheckFetch, "announceDeployCheckFetch");
77365
77381
  __name(deployCheckTsc, "deployCheckTsc");
@@ -77754,14 +77770,14 @@ var source_lint_exports = {};
77754
77770
  __export(source_lint_exports, {
77755
77771
  lintProject: () => lintProject
77756
77772
  });
77757
- import { createRequire as createRequire5 } from "node:module";
77773
+ import { createRequire as createRequire6 } from "node:module";
77758
77774
  import { performance as performance2 } from "node:perf_hooks";
77759
77775
  async function lintProject(directory2, options2 = {}) {
77760
77776
  const started = performance2.now();
77761
77777
  const contract2 = platformContractVerdict(options2.apiBase ?? API_BASE_URL);
77762
77778
  const collected = collectFiles(directory2, { readBinary: false });
77763
- const require5 = createRequire5(CLI_PACKAGE_ROOT);
77764
- const vendor3 = require5("./runtime/source-lint.cjs");
77779
+ const require6 = createRequire6(CLI_PACKAGE_ROOT);
77780
+ const vendor3 = require6("./runtime/source-lint.cjs");
77765
77781
  const report2 = await vendor3.lintSourceSnapshot(collected.files, collected.functions);
77766
77782
  const generic = options2.generic ? genericLint(directory2) : { status: "not-requested", findings: [] };
77767
77783
  return {
@@ -79750,7 +79766,7 @@ var init_test_connectivity = __esm({
79750
79766
  });
79751
79767
 
79752
79768
  // dist/lib/test-run.js
79753
- import { createRequire as createRequire6 } from "node:module";
79769
+ import { createRequire as createRequire7 } from "node:module";
79754
79770
  import { pathToFileURL } from "node:url";
79755
79771
  import { join as join29, dirname as dirname9 } from "node:path";
79756
79772
  import { spawn as spawn4, spawnSync as spawnSync3 } from "node:child_process";
@@ -79769,12 +79785,12 @@ function testDependencyError(root) {
79769
79785
  return new Error(missingProjectDependencies(root).includes("@playwright/test") ? INSTALL_PROJECT_DEPENDENCIES : "Install project test dependencies: npm install -D @playwright/test @somewhere-cloud/cli");
79770
79786
  }
79771
79787
  async function prepareRunner(root) {
79772
- const require5 = createRequire6(join29(root, "package.json"));
79788
+ const require6 = createRequire7(join29(root, "package.json"));
79773
79789
  let cli;
79774
79790
  let pw;
79775
79791
  try {
79776
- cli = require5.resolve("@playwright/test/cli");
79777
- pw = require5("@playwright/test");
79792
+ cli = require6.resolve("@playwright/test/cli");
79793
+ pw = require6("@playwright/test");
79778
79794
  } catch {
79779
79795
  throw testDependencyError(root);
79780
79796
  }
@@ -87259,8 +87275,76 @@ var init_postgres = __esm({
87259
87275
  }
87260
87276
  });
87261
87277
 
87278
+ // dist/lib/local-docs.js
87279
+ import { appendFileSync as appendFileSync3, existsSync as existsSync31, lstatSync as lstatSync5, mkdirSync as mkdirSync16, mkdtempSync as mkdtempSync3, readFileSync as readFileSync32, renameSync as renameSync5, rmSync as rmSync13, writeFileSync as writeFileSync21 } from "node:fs";
87280
+ import { join as join36 } from "node:path";
87281
+ function localDocsVersion(root = process.cwd()) {
87282
+ const path3 = join36(root, FOLDER, DOCS, STAMP);
87283
+ if (!existsSync31(path3))
87284
+ return void 0;
87285
+ const stamp2 = JSON.parse(readFileSync32(path3, "utf8"));
87286
+ return typeof stamp2.version === "string" && /^[a-f0-9]{16}$/.test(stamp2.version) ? stamp2.version : void 0;
87287
+ }
87288
+ function ensureGitIgnore(root) {
87289
+ const path3 = join36(root, ".gitignore");
87290
+ const text = existsSync31(path3) ? readFileSync32(path3, "utf8") : "";
87291
+ if (text.split(/\r?\n/).some((line) => line === ".somewhere/" || line === "/.somewhere/"))
87292
+ return;
87293
+ appendFileSync3(path3, `${text && !text.endsWith("\n") ? "\n" : ""}/.somewhere/
87294
+ `);
87295
+ }
87296
+ function saveLocalDocs(version2, files, root = process.cwd()) {
87297
+ const state = join36(root, FOLDER);
87298
+ const target = join36(state, DOCS);
87299
+ if (existsSync31(state) && !lstatSync5(state).isDirectory())
87300
+ throw new Error(`${state} must be a directory.`);
87301
+ if (existsSync31(target) && (!lstatSync5(target).isDirectory() || !localDocsVersion(root))) {
87302
+ throw new Error(`Move the existing folder at ${target} before pulling docs.`);
87303
+ }
87304
+ ensureGitIgnore(root);
87305
+ mkdirSync16(state, { recursive: true });
87306
+ const staging = mkdtempSync3(join36(state, "docs-pull-"));
87307
+ const next = join36(staging, "next");
87308
+ const previous = join36(staging, "previous");
87309
+ let installed = false;
87310
+ try {
87311
+ mkdirSync16(next);
87312
+ for (const [name, content] of files)
87313
+ writeFileSync21(join36(next, name), content, { flag: "wx" });
87314
+ const pulledAt = (/* @__PURE__ */ new Date()).toISOString();
87315
+ writeFileSync21(join36(next, STAMP), JSON.stringify({ version: version2, pulledAt }) + "\n");
87316
+ writeFileSync21(join36(next, "README.md"), `# Somewhere docs
87317
+
87318
+ Pulled platform docs version ${version2} on ${pulledAt}. Run \`${cliInvocation()} docs\` to check whether this copy is older than the current docs and \`${cliInvocation()} docs pull\` to refresh it.
87319
+ `, { flag: "wx" });
87320
+ if (existsSync31(target))
87321
+ renameSync5(target, previous);
87322
+ renameSync5(next, target);
87323
+ installed = true;
87324
+ return target;
87325
+ } finally {
87326
+ if (!installed && existsSync31(previous) && !existsSync31(target))
87327
+ renameSync5(previous, target);
87328
+ if (installed || !existsSync31(previous))
87329
+ rmSync13(staging, { recursive: true, force: true });
87330
+ }
87331
+ }
87332
+ var FOLDER, DOCS, STAMP;
87333
+ var init_local_docs = __esm({
87334
+ "dist/lib/local-docs.js"() {
87335
+ "use strict";
87336
+ init_cli_invocation();
87337
+ FOLDER = ".somewhere";
87338
+ DOCS = "docs";
87339
+ STAMP = ".stamp.json";
87340
+ __name(localDocsVersion, "localDocsVersion");
87341
+ __name(ensureGitIgnore, "ensureGitIgnore");
87342
+ __name(saveLocalDocs, "saveLocalDocs");
87343
+ }
87344
+ });
87345
+
87262
87346
  // dist/lib/advisor-context.js
87263
- import { readFileSync as readFileSync32, statSync as statSync6 } from "node:fs";
87347
+ import { readFileSync as readFileSync33, statSync as statSync6 } from "node:fs";
87264
87348
  import { basename as basename7 } from "node:path";
87265
87349
  function tail(value, limit) {
87266
87350
  return value.length <= limit ? value : `\u2026${value.slice(-limit)}`;
@@ -87282,7 +87366,7 @@ function buildAdvisorContext(filePath) {
87282
87366
  const stat6 = statSync6(filePath);
87283
87367
  if (!stat6.isFile())
87284
87368
  throw new Error("--file must name a regular file.");
87285
- const content = readFileSync32(filePath, "utf8");
87369
+ const content = readFileSync33(filePath, "utf8");
87286
87370
  context.file = {
87287
87371
  path: filePath,
87288
87372
  content: tail(redactAdvisorText(content, isDotenvPath(filePath)), FILE_LIMIT)
@@ -87308,19 +87392,19 @@ var init_advisor_context = __esm({
87308
87392
 
87309
87393
  // dist/lib/advisor-runs.js
87310
87394
  import { randomBytes as randomBytes7, randomUUID as randomUUID7 } from "node:crypto";
87311
- import { chmodSync as chmodSync4, existsSync as existsSync31, mkdirSync as mkdirSync16, readFileSync as readFileSync33, renameSync as renameSync5, writeFileSync as writeFileSync21 } from "node:fs";
87312
- import { join as join36 } from "node:path";
87395
+ import { chmodSync as chmodSync4, existsSync as existsSync32, mkdirSync as mkdirSync17, readFileSync as readFileSync34, renameSync as renameSync6, writeFileSync as writeFileSync22 } from "node:fs";
87396
+ import { join as join37 } from "node:path";
87313
87397
  function path2(id) {
87314
87398
  if (!/^[a-f0-9-]{36}$/i.test(id))
87315
87399
  throw Error("Invalid Advisor request ID.");
87316
- return join36(directory(), id + ".json");
87400
+ return join37(directory(), id + ".json");
87317
87401
  }
87318
87402
  function save(record3) {
87319
- mkdirSync16(directory(), { recursive: true, mode: 448 });
87403
+ mkdirSync17(directory(), { recursive: true, mode: 448 });
87320
87404
  chmodSync4(directory(), 448);
87321
87405
  const target = path2(record3.request_id), temporary = target + "." + randomUUID7() + ".tmp";
87322
- writeFileSync21(temporary, JSON.stringify(record3), { mode: 384, flag: "wx" });
87323
- renameSync5(temporary, target);
87406
+ writeFileSync22(temporary, JSON.stringify(record3), { mode: 384, flag: "wx" });
87407
+ renameSync6(temporary, target);
87324
87408
  chmodSync4(target, 384);
87325
87409
  }
87326
87410
  function payloadDeadline(record3) {
@@ -87343,9 +87427,9 @@ function expiredResult(record3) {
87343
87427
  return { run_id: record3.run_id, request_id: record3.request_id, status: record3.provider_settled ? "settled" : "delivery_expired", payload_expired: true, payload_expires_at: payloadDeadline(record3), error: "ADVISOR_PAYLOAD_EXPIRED", incomplete: true, next_step: record3.provider_settled ? "none" : "status" };
87344
87428
  }
87345
87429
  function load(id) {
87346
- if (!existsSync31(path2(id)))
87430
+ if (!existsSync32(path2(id)))
87347
87431
  throw Error("Advisor request was not found in this CLI configuration.");
87348
- const record3 = JSON.parse(readFileSync33(path2(id), "utf8"));
87432
+ const record3 = JSON.parse(readFileSync34(path2(id), "utf8"));
87349
87433
  prune(record3);
87350
87434
  save(record3);
87351
87435
  return record3;
@@ -87451,7 +87535,7 @@ var init_advisor_runs = __esm({
87451
87535
  init_config();
87452
87536
  init_http();
87453
87537
  init_advisor_context();
87454
- directory = /* @__PURE__ */ __name(() => join36(cliConfigDir(), "advisor-runs"), "directory");
87538
+ directory = /* @__PURE__ */ __name(() => join37(cliConfigDir(), "advisor-runs"), "directory");
87455
87539
  __name(path2, "path");
87456
87540
  __name(save, "save");
87457
87541
  PAYLOAD_RETENTION_MS = 24 * 60 * 60 * 1e3;
@@ -87469,8 +87553,8 @@ var init_advisor_runs = __esm({
87469
87553
 
87470
87554
  // dist/lib/advisor-app.js
87471
87555
  import { createHash as createHash8 } from "node:crypto";
87472
- import { existsSync as existsSync32, mkdirSync as mkdirSync17, readFileSync as readFileSync34, rmSync as rmSync13, writeFileSync as writeFileSync22 } from "node:fs";
87473
- import { join as join37 } from "node:path";
87556
+ import { existsSync as existsSync33, mkdirSync as mkdirSync18, readFileSync as readFileSync35, rmSync as rmSync14, writeFileSync as writeFileSync23 } from "node:fs";
87557
+ import { join as join38 } from "node:path";
87474
87558
  async function gatherAdvisorApp(client, ref) {
87475
87559
  const project = await client.call("GET", `/projects/${encodeURIComponent(ref)}`);
87476
87560
  if (typeof project.id !== "string" || project.deleted === true)
@@ -87504,7 +87588,7 @@ async function gatherAdvisorApp(client, ref) {
87504
87588
  }
87505
87589
  function loadAdvisorTurns(dir, projectId, account, now2 = Date.now()) {
87506
87590
  try {
87507
- const saved = JSON.parse(readFileSync34(join37(dir, FILE), "utf8"));
87591
+ const saved = JSON.parse(readFileSync35(join38(dir, FILE), "utf8"));
87508
87592
  if (saved.project_id !== projectId || saved.owner !== ownerOf(account) || !Array.isArray(saved.turns))
87509
87593
  return [];
87510
87594
  const last = saved.turns.at(-1);
@@ -87514,25 +87598,25 @@ function loadAdvisorTurns(dir, projectId, account, now2 = Date.now()) {
87514
87598
  }
87515
87599
  }
87516
87600
  function saveAdvisorTurn(dir, projectId, account, earlier, turn) {
87517
- mkdirSync17(join37(dir, DIR), { recursive: true, mode: 448 });
87518
- writeFileSync22(join37(dir, FILE), JSON.stringify({ project_id: projectId, owner: ownerOf(account), turns: [...earlier, { question: turn.question.slice(0, 2e3), answer: turn.answer.slice(0, 3e3), at: turn.at }].slice(-3) }) + "\n", { mode: 384 });
87601
+ mkdirSync18(join38(dir, DIR), { recursive: true, mode: 448 });
87602
+ writeFileSync23(join38(dir, FILE), JSON.stringify({ project_id: projectId, owner: ownerOf(account), turns: [...earlier, { question: turn.question.slice(0, 2e3), answer: turn.answer.slice(0, 3e3), at: turn.at }].slice(-3) }) + "\n", { mode: 384 });
87519
87603
  ensureAdvisorStateIgnored(dir);
87520
87604
  }
87521
87605
  function clearAdvisorTurns(dir) {
87522
- if (existsSync32(join37(dir, FILE)))
87523
- rmSync13(join37(dir, FILE), { force: true });
87606
+ if (existsSync33(join38(dir, FILE)))
87607
+ rmSync14(join38(dir, FILE), { force: true });
87524
87608
  }
87525
87609
  function ensureAdvisorStateIgnored(dir) {
87526
- const path3 = join37(dir, ".gitignore");
87610
+ const path3 = join38(dir, ".gitignore");
87527
87611
  const covered = [".somewhere/", ".somewhere", "/.somewhere/", "/.somewhere", ".somewhere/advisor-conversation.json"];
87528
- if (!existsSync32(path3)) {
87529
- writeFileSync22(path3, "# somewhere: local CLI state (Advisor follow-ups, test users)\n.somewhere/\n");
87612
+ if (!existsSync33(path3)) {
87613
+ writeFileSync23(path3, "# somewhere: local CLI state (Advisor follow-ups, test users)\n.somewhere/\n");
87530
87614
  return;
87531
87615
  }
87532
- const text = readFileSync34(path3, "utf8");
87616
+ const text = readFileSync35(path3, "utf8");
87533
87617
  if (text.split(/\r?\n/).map((l) => l.trim()).some((l) => covered.includes(l)))
87534
87618
  return;
87535
- writeFileSync22(path3, `${text}${text.endsWith("\n") || !text ? "" : "\n"}
87619
+ writeFileSync23(path3, `${text}${text.endsWith("\n") || !text ? "" : "\n"}
87536
87620
  # somewhere: local CLI state (Advisor follow-ups, test users)
87537
87621
  .somewhere/
87538
87622
  `);
@@ -87543,7 +87627,7 @@ var init_advisor_app = __esm({
87543
87627
  "use strict";
87544
87628
  __name(gatherAdvisorApp, "gatherAdvisorApp");
87545
87629
  DIR = ".somewhere";
87546
- FILE = join37(DIR, "advisor-conversation.json");
87630
+ FILE = join38(DIR, "advisor-conversation.json");
87547
87631
  IDLE_MS = 30 * 6e4;
87548
87632
  ownerOf = /* @__PURE__ */ __name((account) => createHash8("sha256").update(`advisor:${account}`).digest("hex"), "ownerOf");
87549
87633
  __name(loadAdvisorTurns, "loadAdvisorTurns");
@@ -87702,10 +87786,32 @@ __export(docs_exports, {
87702
87786
  registerDocs: () => registerDocs,
87703
87787
  renderDocsIndex: () => renderDocsIndex,
87704
87788
  renderPublicDocsView: () => renderPublicDocsView,
87705
- searchPublicDocs: () => searchPublicDocs,
87706
87789
  writeResponseBodyToStdout: () => writeResponseBodyToStdout
87707
87790
  });
87708
87791
  import { once } from "node:events";
87792
+ function docsVersion(value) {
87793
+ return typeof value === "string" && /^[a-f0-9]{16}$/.test(value) ? value : void 0;
87794
+ }
87795
+ async function warnIfLocalDocsOlder(platformVersion) {
87796
+ try {
87797
+ const local = localDocsVersion();
87798
+ if (!local)
87799
+ return;
87800
+ if (!platformVersion) {
87801
+ const response = await fetchWithProxy(DOCS_BASE2 + PUBLIC_MANIFEST_PATH, { method: "HEAD" });
87802
+ if (!response.ok)
87803
+ throw new Error(`HTTP ${response.status}`);
87804
+ platformVersion = docsVersion(response.headers.get("etag")?.replace(/^(?:W\/)?"|"$/g, ""));
87805
+ }
87806
+ if (!platformVersion)
87807
+ throw new Error("the platform did not return a docs version");
87808
+ if (local !== platformVersion) {
87809
+ console.error(`The Markdown copy in .somewhere/docs/ is from an older version (${local}). Current platform docs: ${platformVersion}. Refresh with ${cliInvocation()} docs pull.`);
87810
+ }
87811
+ } catch (cause) {
87812
+ console.error(`Could not check the local Markdown version (${cause instanceof Error ? cause.message : String(cause)}). Refresh with ${cliInvocation()} docs pull.`);
87813
+ }
87814
+ }
87709
87815
  function closestMatches(wanted, candidates) {
87710
87816
  const query = wanted.trim().toLowerCase();
87711
87817
  const distance = /* @__PURE__ */ __name((candidate) => {
@@ -87752,7 +87858,7 @@ function renderPublicDocsView(page, view) {
87752
87858
  if (view.kind === "full")
87753
87859
  return { content: renderPublicPage(page), view: "full", complete: true };
87754
87860
  if (view.kind === "default") {
87755
- return page.summary ? { content: withNewline(page.summary), view: "summary", complete: page.summary_complete === true } : { content: renderPublicPage(page), view: "full", complete: true };
87861
+ return page.summary ? { content: page.summary_complete === true ? withNewline(page.summary) : topicSummary(page.summary, page.id, page.body.length), view: "summary", complete: page.summary_complete === true } : { content: renderPublicPage(page), view: "full", complete: true };
87756
87862
  }
87757
87863
  const sections = parseSections(page.sections, page.body.length);
87758
87864
  const fail5 = /* @__PURE__ */ __name((failure2) => ({
@@ -87817,9 +87923,6 @@ function parseDocsStatusLine(content) {
87817
87923
  function normalizeSectionHeading(value) {
87818
87924
  return value.trim().replace(/^#+\s*/, "").replace(/`([^`]*)`/g, "$1").replace(/\*\*([^*]+)\*\*/g, "$1").replace(/\*([^*]+)\*/g, "$1").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").toLowerCase().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").slice(0, 80);
87819
87925
  }
87820
- function headingText(section) {
87821
- return section.heading.replace(/^#+\s*/, "").trim();
87822
- }
87823
87926
  function withNewline(value) {
87824
87927
  return value.endsWith("\n") ? value : `${value}
87825
87928
  `;
@@ -87896,14 +87999,12 @@ async function fetchPublicManifestWithGroups() {
87896
87999
  }
87897
88000
  try {
87898
88001
  const body = await res.json();
87899
- return { pages: parsePublicDocsManifest(body), groups: parsePublicDocsGroups(body), aliases: parsePublicDocsAliases(body) };
88002
+ const version2 = body && typeof body === "object" && "sourceHash" in body ? docsVersion(body.sourceHash) : void 0;
88003
+ return { pages: parsePublicDocsManifest(body), groups: parsePublicDocsGroups(body), aliases: parsePublicDocsAliases(body), version: version2 };
87900
88004
  } catch (cause) {
87901
88005
  throw new Error(`Could not read ${DOCS_BASE2}${PUBLIC_MANIFEST_PATH}: ${cause instanceof Error ? cause.message : String(cause)}`);
87902
88006
  }
87903
88007
  }
87904
- async function fetchPublicManifest() {
87905
- return (await fetchPublicManifestWithGroups()).pages;
87906
- }
87907
88008
  function renderDocsIndex(pages, groups) {
87908
88009
  const byId = new Map(pages.map((page) => [page.id, page]));
87909
88010
  const listed = /* @__PURE__ */ new Set();
@@ -87940,49 +88041,31 @@ function renderDocsIndex(pages, groups) {
87940
88041
  lines.push("", "Quick links:");
87941
88042
  for (const [name, entry] of Object.entries(TOPICS))
87942
88043
  lines.push(` ${name.padEnd(10)} ${entry.blurb}`);
87943
- lines.push("", `Open a topic: ${cliInvocation()} docs <topic> (summary with its section ids)`, `Open a section: ${cliInvocation()} docs <topic> --section <id>`, `Whole topic: ${cliInvocation()} docs <topic> --full`, `Search all docs: ${cliInvocation()} docs search <term>`, `Full manual: ${cliInvocation()} docs --full (very large)`);
88044
+ lines.push("", `Open a topic: ${cliInvocation()} docs <topic> (full when piped or redirected)`, `Open a section: ${cliInvocation()} docs <topic> --section <id>`, `Whole topic: ${cliInvocation()} docs <topic> --full`, `Search all docs: ${cliInvocation()} docs --search "<words>"`, `Download Markdown: ${cliInvocation()} docs pull`, `Full manual: ${cliInvocation()} docs --full (very large)`);
87944
88045
  return lines.join("\n") + "\n";
87945
88046
  }
87946
- function searchPublicDocs(pages, query) {
87947
- const words = query.toLowerCase().split(/\s+/).filter(Boolean);
87948
- if (!words.length)
87949
- return [];
87950
- const scored = [];
87951
- for (const page of pages) {
87952
- const sections = parseSections(page.sections, page.body.length) ?? [];
87953
- const lower = page.body.toLowerCase();
87954
- const starts = [.../* @__PURE__ */ new Set([0, ...sections.map((section) => section.start)])].sort((a, b2) => a - b2);
87955
- const seen2 = /* @__PURE__ */ new Set();
87956
- for (let index = 0; index < starts.length; index++) {
87957
- const start = starts[index];
87958
- const end = starts[index + 1] ?? page.body.length;
87959
- const span2 = lower.slice(start, end);
87960
- if (!words.every((word) => span2.includes(word)))
87961
- continue;
87962
- const innermost = sections.filter((section) => section.start <= start && section.end >= end).sort((a, b2) => a.end - a.start - (b2.end - b2.start))[0];
87963
- const key = innermost?.id ?? "";
87964
- if (seen2.has(key))
87965
- continue;
87966
- seen2.add(key);
87967
- const at2 = start + span2.indexOf(words[0]);
87968
- const from = Math.max(0, at2 - SNIPPET_RADIUS);
87969
- const to2 = Math.min(page.body.length, at2 + words[0].length + SNIPPET_RADIUS);
87970
- const snippet = `${from > 0 ? "\u2026" : ""}${page.body.slice(from, to2).replace(/\s+/g, " ").trim()}${to2 < page.body.length ? "\u2026" : ""}`;
87971
- const heading = innermost ? headingText(innermost) : null;
87972
- const occurrences = words.reduce((count2, word) => count2 + span2.split(word).length - 1, 0);
87973
- const titleHit = words.every((word) => `${page.id} ${page.title} ${heading ?? ""}`.toLowerCase().includes(word));
87974
- scored.push({
87975
- topic: page.id,
87976
- title: page.title,
87977
- section: innermost?.id ?? null,
87978
- heading,
87979
- snippet,
87980
- open: innermost ? `${cliInvocation()} docs ${commandArg(page.id)} --section ${commandArg(innermost.id)}` : `${cliInvocation()} docs ${commandArg(page.id)} --full`,
87981
- score: (titleHit ? 1e3 : 0) + occurrences
87982
- });
87983
- }
88047
+ async function fetchDocsSearch(query, topic) {
88048
+ const params = new URLSearchParams({ q: query });
88049
+ if (topic)
88050
+ params.set("topic", topic);
88051
+ const res = await fetchWithProxy(`${DOCS_BASE2}${DOCS_SEARCH_PATH}?${params}`, {
88052
+ headers: { "User-Agent": "somewhere-cli" }
88053
+ });
88054
+ if (!res.ok) {
88055
+ if (topic && res.status === 404)
88056
+ throw new Error(`Unknown docs topic "${topic}". Run ${cliInvocation()} docs for the topic index.`);
88057
+ throw new Error(`Could not search docs at ${DOCS_BASE2} (HTTP ${res.status}).`);
87984
88058
  }
87985
- return scored.sort((a, b2) => b2.score - a.score || (a.topic < b2.topic ? -1 : a.topic > b2.topic ? 1 : 0)).slice(0, DOCS_SEARCH_LIMIT).map(({ score: _score, ...result }) => result);
88059
+ const { results, total, version: version2 } = await res.json();
88060
+ return {
88061
+ results: results.map(({ content, ...match }) => ({
88062
+ ...match,
88063
+ snippet: content,
88064
+ open: match.section ? `${cliInvocation()} docs ${commandArg(match.topic)} --section ${commandArg(match.section)}` : `${cliInvocation()} docs ${commandArg(match.topic)} --full`
88065
+ })),
88066
+ total,
88067
+ version: docsVersion(version2)
88068
+ };
87986
88069
  }
87987
88070
  function warnIfDocsNewerThanCli() {
87988
88071
  if (process.env.CI || process.env.SOMEWHERE_NO_NOTIFICATIONS)
@@ -88018,12 +88101,20 @@ async function writeResponseBodyToStdout(res) {
88018
88101
  reader.releaseLock();
88019
88102
  }
88020
88103
  }
88104
+ function topicSummary(content, topic, full) {
88105
+ const command = `${cliInvocation()} docs ${commandArg(topic)}`;
88106
+ return `${content.trimEnd()}
88107
+
88108
+ Full topic (${full} characters): ${command} --full
88109
+ `;
88110
+ }
88021
88111
  function registerDocs(program2) {
88022
- program2.command("docs [topic] [terms...]").description(`Read platform docs. No login needed \u2014 every topic is public. With no topic, prints the topic index. Search with \`${cliInvocation()} docs <topic> <term>\` or \`${cliInvocation()} docs search <term>\`. Quick topics: ` + Object.keys(TOPICS).join(", ") + `. Example manual topic: \`${cliInvocation()} docs sw.db\`.`).option("--list", `List available topics (the same index bare \`${cliInvocation()} docs\` prints)`).option("--full", "Print the complete topic instead of its summary; with no topic, the full manual").option("--section <id>", "Print one section of a topic (ids are listed in the summary)").option("--json", "Print the selected document in a JSON envelope").addHelpText("after", `
88112
+ program2.command("docs [topic] [terms...]").description(`Read platform docs. No login needed \u2014 every topic is public. With no topic, prints the topic index. Search with \`${cliInvocation()} docs --search "<words>"\`. Quick topics: ` + Object.keys(TOPICS).join(", ") + `. Example manual topic: \`${cliInvocation()} docs sw.db\`.`).option("--list", `List available topics (the same index bare \`${cliInvocation()} docs\` prints)`).option("--full", "Print the complete topic in a terminal; with no topic, the full manual").option("--search <words>", "Search matching sections across all live docs topics").option("--section <id>", "Print one section of a topic (ids are listed in the summary)").option("--json", "Print the selected document in a JSON envelope").addHelpText("after", `
88023
88113
  Examples:
88024
88114
  ${cliInvocation()} docs # topic index
88025
- ${cliInvocation()} docs search magic link # matching sections across every topic
88026
- ${cliInvocation()} docs sw.auth # topic summary with section ids
88115
+ ${cliInvocation()} docs --search "magic link" # matching sections across every topic
88116
+ ${cliInvocation()} docs pull # download Markdown into .somewhere/docs/
88117
+ ${cliInvocation()} docs sw.auth # full when piped or redirected
88027
88118
  ${cliInvocation()} docs sw.auth setRoles # search within this topic
88028
88119
  ${cliInvocation()} docs sw.auth --section <id> # one section
88029
88120
  ${cliInvocation()} docs --full # the whole manual (very large)
@@ -88035,39 +88126,73 @@ Examples:
88035
88126
  process.exitCode = 1;
88036
88127
  return;
88037
88128
  }
88038
- const searching = terms.length > 0;
88039
- const within = topic && topic !== "search" ? ALIASES[topic] ?? topic : void 0;
88040
88129
  warnIfDocsNewerThanCli();
88130
+ if (topic === "pull") {
88131
+ if (terms.length || opts.list || opts.full || opts.section !== void 0 || opts.search !== void 0) {
88132
+ error("docs pull accepts only --json.");
88133
+ process.exitCode = 1;
88134
+ return;
88135
+ }
88136
+ try {
88137
+ const { pages, version: version2 } = await fetchPublicManifestWithGroups();
88138
+ if (!version2 || !pages.length)
88139
+ throw new Error("The platform did not return a versioned docs collection.");
88140
+ const files = /* @__PURE__ */ new Map();
88141
+ const names = /* @__PURE__ */ new Set(["readme"]);
88142
+ for (const page of pages) {
88143
+ const name = page.id.toLowerCase();
88144
+ if (!/^[a-z0-9][a-z0-9.-]*$/.test(name) || names.has(name)) {
88145
+ throw new Error(`Invalid docs topic ID ${JSON.stringify(page.id)}.`);
88146
+ }
88147
+ names.add(name);
88148
+ files.set(page.id + ".md", renderPublicPage(page));
88149
+ }
88150
+ const path3 = saveLocalDocs(version2, files);
88151
+ if (opts.json)
88152
+ printJson({ path: path3, version: version2, count: files.size });
88153
+ else
88154
+ console.log(path3);
88155
+ } catch (e) {
88156
+ error(e instanceof Error ? e.message : String(e), e);
88157
+ process.exitCode = 1;
88158
+ }
88159
+ return;
88160
+ }
88161
+ const searching = opts.search !== void 0 || terms.length > 0;
88162
+ const within = topic && topic !== "search" ? ALIASES[topic] ?? topic : void 0;
88041
88163
  if (searching) {
88042
- if (opts.full || opts.section !== void 0 || opts.list) {
88043
- error("docs search takes only a term (and --json).");
88164
+ if (opts.full || opts.section !== void 0 || opts.list || opts.search !== void 0 && topic !== void 0) {
88165
+ error('Use docs --search "<words>" with optional --json.');
88166
+ process.exitCode = 1;
88167
+ return;
88168
+ }
88169
+ const query = (opts.search ?? terms.join(" ")).trim();
88170
+ if (!/[a-z0-9]/i.test(query) || query.length > 200) {
88171
+ error("Enter search words of up to 200 characters.");
88044
88172
  process.exitCode = 1;
88045
88173
  return;
88046
88174
  }
88047
- const query = terms.join(" ");
88048
88175
  try {
88049
- const pages = await fetchPublicManifest();
88050
- if (within && !pages.some((page) => page.id === within)) {
88051
- error(`Unknown docs topic "${within}". Run: ${cliInvocation()} docs`);
88052
- process.exitCode = 1;
88053
- return;
88054
- }
88055
- const results = searchPublicDocs(within ? pages.filter((page) => page.id === within) : pages, query);
88176
+ const { results, total, version: version2 } = await fetchDocsSearch(query, within);
88177
+ await warnIfLocalDocsOlder(version2);
88056
88178
  if (opts.json) {
88057
- printJson({ query, ...within ? { topic: within } : {}, count: results.length, results });
88179
+ printJson({ query, ...within ? { topic: within } : {}, count: results.length, total, results });
88058
88180
  return;
88059
88181
  }
88060
88182
  if (!results.length) {
88061
- console.log(`No docs sections${within ? ` in ${within}` : ""} mention "${query}". Search all topics: ${cliInvocation()} docs search ${query}`);
88183
+ console.log(`No docs sections${within ? ` in ${within}` : ""} match ${JSON.stringify(query)}.`);
88062
88184
  return;
88063
88185
  }
88064
88186
  for (const result of results) {
88065
88187
  console.log(`${result.topic}${result.section ? ` \u203A ${result.section}` : ""} ${dim(result.heading ?? result.title)}`);
88066
- console.log(` ${result.snippet}`);
88067
- console.log(` ${dim(result.open)}`);
88188
+ console.log(`
88189
+ ${result.snippet}
88190
+
88191
+ ${dim(result.open)}
88192
+ `);
88068
88193
  }
88069
- if (results.length === DOCS_SEARCH_LIMIT) {
88070
- console.log(dim(`Showing the first ${DOCS_SEARCH_LIMIT} matches; add a word to narrow the search.`));
88194
+ if (results.length < total) {
88195
+ console.log(dim(`Showing ${results.length} of ${total} matches. Add a word to narrow the search.`));
88071
88196
  }
88072
88197
  } catch (e) {
88073
88198
  error(e instanceof Error ? e.message : String(e), e);
@@ -88075,10 +88200,11 @@ Examples:
88075
88200
  }
88076
88201
  return;
88077
88202
  }
88078
- const view = opts.section !== void 0 ? { kind: "section", id: opts.section } : opts.full ? { kind: "full" } : { kind: "default" };
88203
+ const view = opts.section !== void 0 ? { kind: "section", id: opts.section } : opts.full || topic !== void 0 && !process.stdout.isTTY ? { kind: "full" } : { kind: "default" };
88079
88204
  if (opts.list || topic === void 0 && view.kind === "default") {
88080
88205
  try {
88081
- const { pages, groups } = await fetchPublicManifestWithGroups();
88206
+ const { pages, groups, version: version2 } = await fetchPublicManifestWithGroups();
88207
+ await warnIfLocalDocsOlder(version2);
88082
88208
  const quickLinks = Object.entries(TOPICS).map(([name, entry2]) => ({
88083
88209
  name,
88084
88210
  path: entry2.path,
@@ -88123,15 +88249,20 @@ ${dim(`No account yet? Start with: ${cliInvocation()} docs start`)}`);
88123
88249
  let authenticatedFailure = null;
88124
88250
  if (hasUsableCredential()) {
88125
88251
  try {
88126
- const content = await callPlatformHelpTool("docs", {
88252
+ let content = await callPlatformHelpTool("docs", {
88127
88253
  topic: resolvedTopic,
88128
88254
  ...view.kind === "full" ? { detail: "full" } : {},
88129
88255
  ...view.kind === "section" ? { section: view.id } : {}
88130
88256
  });
88131
88257
  const status = parseDocsStatusLine(content);
88132
- if (/^Topic "[^\n]*" not found\./.test(content) || view.kind === "section" && (status.view !== "section" || /(?:^|\n)No section "/.test(content))) {
88258
+ const first = content.split("\n", 1)[0];
88259
+ const full = /\bfull=(\d+)/.exec(first)?.[1];
88260
+ if (/^Topic "[^\n]*" not found\./.test(content) || view.kind === "full" && status.complete === false || status.view === "summary" && status.complete === false && !full || view.kind === "section" && (status.view !== "section" || /(?:^|\n)No section "/.test(content))) {
88133
88261
  throw new Error("Authenticated docs did not return the requested view; trying the public index.");
88134
88262
  }
88263
+ if (status.view === "summary" && status.complete === false)
88264
+ content = topicSummary(content, resolvedTopic, Number(full));
88265
+ await warnIfLocalDocsOlder();
88135
88266
  if (opts.json)
88136
88267
  printJson({ topic: requestedTopic, ...status, content });
88137
88268
  else
@@ -88142,7 +88273,8 @@ ${dim(`No account yet? Start with: ${cliInvocation()} docs start`)}`);
88142
88273
  }
88143
88274
  }
88144
88275
  try {
88145
- const { pages, aliases } = await fetchPublicManifestWithGroups();
88276
+ const { pages, aliases, version: version2 } = await fetchPublicManifestWithGroups();
88277
+ await warnIfLocalDocsOlder(version2);
88146
88278
  const page = findPublicDocsPage(pages, aliases, resolvedTopic);
88147
88279
  if (page) {
88148
88280
  const rendered = renderPublicDocsView(page, view);
@@ -88185,6 +88317,7 @@ ${dim(`No account yet? Start with: ${cliInvocation()} docs start`)}`);
88185
88317
  error(`Could not fetch ${DOCS_BASE2}${entry.path} (HTTP ${res.status}). Try again shortly, or open it in a browser.`);
88186
88318
  process.exit(1);
88187
88319
  }
88320
+ await warnIfLocalDocsOlder();
88188
88321
  if (opts.json) {
88189
88322
  printJson({
88190
88323
  topic: key,
@@ -88200,12 +88333,13 @@ ${dim(`No account yet? Start with: ${cliInvocation()} docs start`)}`);
88200
88333
  }
88201
88334
  });
88202
88335
  }
88203
- var DOCS_BASE2, TOPICS, ALIASES, PUBLIC_MANIFEST_PATH, DOCS_SECTION_MAX_CHARS, DOCS_SEARCH_LIMIT, SNIPPET_RADIUS;
88336
+ var DOCS_BASE2, TOPICS, ALIASES, PUBLIC_MANIFEST_PATH, DOCS_SEARCH_PATH, DOCS_SECTION_MAX_CHARS;
88204
88337
  var init_docs = __esm({
88205
88338
  "dist/commands/docs.js"() {
88206
88339
  "use strict";
88207
88340
  init_cli_invocation();
88208
88341
  init_http();
88342
+ init_local_docs();
88209
88343
  init_config();
88210
88344
  init_output();
88211
88345
  init_update();
@@ -88248,6 +88382,9 @@ var init_docs = __esm({
88248
88382
  schema: "declared-data"
88249
88383
  };
88250
88384
  PUBLIC_MANIFEST_PATH = "/docs-manifest.json";
88385
+ DOCS_SEARCH_PATH = "/docs-search.json";
88386
+ __name(docsVersion, "docsVersion");
88387
+ __name(warnIfLocalDocsOlder, "warnIfLocalDocsOlder");
88251
88388
  DOCS_SECTION_MAX_CHARS = 12e3;
88252
88389
  __name(closestMatches, "closestMatches");
88253
88390
  __name(commandArg, "commandArg");
@@ -88256,21 +88393,18 @@ var init_docs = __esm({
88256
88393
  __name(renderPublicDocsView, "renderPublicDocsView");
88257
88394
  __name(parseDocsStatusLine, "parseDocsStatusLine");
88258
88395
  __name(normalizeSectionHeading, "normalizeSectionHeading");
88259
- __name(headingText, "headingText");
88260
88396
  __name(withNewline, "withNewline");
88261
88397
  __name(parsePublicDocsManifest, "parsePublicDocsManifest");
88262
88398
  __name(parsePublicDocsGroups, "parsePublicDocsGroups");
88263
88399
  __name(parsePublicDocsAliases, "parsePublicDocsAliases");
88264
88400
  __name(findPublicDocsPage, "findPublicDocsPage");
88265
88401
  __name(fetchPublicManifestWithGroups, "fetchPublicManifestWithGroups");
88266
- __name(fetchPublicManifest, "fetchPublicManifest");
88267
88402
  __name(renderDocsIndex, "renderDocsIndex");
88268
- DOCS_SEARCH_LIMIT = 20;
88269
- SNIPPET_RADIUS = 90;
88270
- __name(searchPublicDocs, "searchPublicDocs");
88403
+ __name(fetchDocsSearch, "fetchDocsSearch");
88271
88404
  __name(warnIfDocsNewerThanCli, "warnIfDocsNewerThanCli");
88272
88405
  __name(renderPublicPage, "renderPublicPage");
88273
88406
  __name(writeResponseBodyToStdout, "writeResponseBodyToStdout");
88407
+ __name(topicSummary, "topicSummary");
88274
88408
  __name(registerDocs, "registerDocs");
88275
88409
  }
88276
88410
  });
@@ -88827,7 +88961,7 @@ var init_envfile_write = __esm({
88827
88961
  });
88828
88962
 
88829
88963
  // dist/commands/env.js
88830
- import { existsSync as existsSync33, readFileSync as readFileSync35, writeFileSync as writeFileSync23 } from "node:fs";
88964
+ import { existsSync as existsSync34, readFileSync as readFileSync36, writeFileSync as writeFileSync24 } from "node:fs";
88831
88965
  import { resolve as resolve19 } from "node:path";
88832
88966
  function resolveProjectId(explicit) {
88833
88967
  if (explicit)
@@ -88892,12 +89026,12 @@ function registerEnv(program2) {
88892
89026
  return;
88893
89027
  }
88894
89028
  const outPath = resolve19(process.cwd(), String(opts.out));
88895
- if (existsSync33(outPath) && !opts.force && opts.json) {
89029
+ if (existsSync34(outPath) && !opts.force && opts.json) {
88896
89030
  error(`${opts.out} exists. Pass --force to overwrite in --json mode.`);
88897
89031
  process.exit(1);
88898
89032
  }
88899
- if (existsSync33(outPath) && !opts.force) {
88900
- const existing = readFileSync35(outPath, "utf-8");
89033
+ if (existsSync34(outPath) && !opts.force) {
89034
+ const existing = readFileSync36(outPath, "utf-8");
88901
89035
  const hasValues = existing.split("\n").some((l) => /^[^#=]+=.+/.test(l.trim()));
88902
89036
  const { ok } = await (0, import_prompts9.default)({
88903
89037
  type: "confirm",
@@ -88910,7 +89044,7 @@ function registerEnv(program2) {
88910
89044
  return;
88911
89045
  }
88912
89046
  }
88913
- writeFileSync23(outPath, buildEnvTemplate(keys, { projectId: pid }));
89047
+ writeFileSync24(outPath, buildEnvTemplate(keys, { projectId: pid }));
88914
89048
  if (opts.json) {
88915
89049
  printJson(result);
88916
89050
  return;
@@ -88950,7 +89084,7 @@ function registerEnv(program2) {
88950
89084
  if (inputNote && !opts.json)
88951
89085
  process.stderr.write(`Note: ${inputNote}
88952
89086
  `);
88953
- const value = opts.stdin ? readFileSync35(0, "utf8").replace(/\r?\n$/, "") : positionalValue;
89087
+ const value = opts.stdin ? readFileSync36(0, "utf8").replace(/\r?\n$/, "") : positionalValue;
88954
89088
  const client = new ApiClient(getToken());
88955
89089
  const pid = resolveProjectId(opts.project);
88956
89090
  try {
@@ -89019,9 +89153,9 @@ var init_env = __esm({
89019
89153
  });
89020
89154
 
89021
89155
  // dist/commands/run.js
89022
- import { existsSync as existsSync34, readFileSync as readFileSync36 } from "node:fs";
89156
+ import { existsSync as existsSync35, readFileSync as readFileSync37 } from "node:fs";
89023
89157
  import { isAbsolute as isAbsolute6, resolve as resolve20 } from "node:path";
89024
- import { createRequire as createRequire7 } from "node:module";
89158
+ import { createRequire as createRequire8 } from "node:module";
89025
89159
  function parseArgs(values) {
89026
89160
  if (!values.length)
89027
89161
  return void 0;
@@ -89049,7 +89183,7 @@ function parseArgs(values) {
89049
89183
  function hasRelativeRuntimeImport(fileName2, code) {
89050
89184
  let ts2;
89051
89185
  try {
89052
- ts2 = createRequire7(resolve20(fileName2))("typescript");
89186
+ ts2 = createRequire8(resolve20(fileName2))("typescript");
89053
89187
  } catch {
89054
89188
  return false;
89055
89189
  }
@@ -89086,11 +89220,11 @@ function registerRun(program2) {
89086
89220
  projectId = config2.project_id;
89087
89221
  }
89088
89222
  const absPath = isAbsolute6(script) ? script : resolve20(process.cwd(), script);
89089
- if (!existsSync34(absPath)) {
89223
+ if (!existsSync35(absPath)) {
89090
89224
  error(`File not found: ${script}`);
89091
89225
  process.exit(1);
89092
89226
  }
89093
- const code = readFileSync36(absPath, "utf-8");
89227
+ const code = readFileSync37(absPath, "utf-8");
89094
89228
  if (!code.trim()) {
89095
89229
  error(`${script} is empty \u2014 nothing to run.`);
89096
89230
  process.exit(1);
@@ -89525,10 +89659,10 @@ var init_claim = __esm({
89525
89659
  });
89526
89660
 
89527
89661
  // dist/lib/frontend-dev.js
89528
- import { createRequire as createRequire8 } from "node:module";
89662
+ import { createRequire as createRequire9 } from "node:module";
89529
89663
  import { realpathSync as realpathSync4 } from "node:fs";
89530
89664
  import { createConnection, createServer as createNetServer } from "node:net";
89531
- import { join as join38 } from "node:path";
89665
+ import { join as join39 } from "node:path";
89532
89666
  import { pathToFileURL as pathToFileURL3 } from "node:url";
89533
89667
  function deployedOrigin(value) {
89534
89668
  const url3 = new URL(value);
@@ -89626,7 +89760,7 @@ async function startFrontendDev(cwd, target, port = 8787, open4 = false) {
89626
89760
  throw new Error(INSTALL_PROJECT_DEPENDENCIES);
89627
89761
  let vitePath;
89628
89762
  try {
89629
- vitePath = createRequire8(join38(cwd, "package.json")).resolve("vite");
89763
+ vitePath = createRequire9(join39(cwd, "package.json")).resolve("vite");
89630
89764
  } catch {
89631
89765
  if (readProjectPin(cwd)?.versionOnly) {
89632
89766
  throw new Error("Install the local frontend tools: npm install -D --save-exact vite@7.2.2");
@@ -89769,8 +89903,8 @@ var init_preview_jobs = __esm({
89769
89903
 
89770
89904
  // dist/commands/dev.js
89771
89905
  import { randomUUID as randomUUID8 } from "node:crypto";
89772
- import { existsSync as existsSync35, readFileSync as readFileSync37 } from "node:fs";
89773
- import { join as join39, relative as relative11 } from "node:path";
89906
+ import { existsSync as existsSync36, readFileSync as readFileSync38 } from "node:fs";
89907
+ import { join as join40, relative as relative11 } from "node:path";
89774
89908
  function previewFinishedReason(err) {
89775
89909
  if (!(err instanceof CliApiError) || err.code !== "DRAFT_SESSION_TERMINAL")
89776
89910
  return null;
@@ -90753,16 +90887,16 @@ async function deployBatch(client, projectId, cwd, changed, deleted, draftId, ex
90753
90887
  const updateBinary = {};
90754
90888
  const deleteKeys = [];
90755
90889
  for (const rel of changed) {
90756
- const abs = join39(cwd, rel);
90757
- if (!existsSync35(abs))
90890
+ const abs = join40(cwd, rel);
90891
+ if (!existsSync36(abs))
90758
90892
  continue;
90759
90893
  const { kind, key } = classifyKey(rel);
90760
90894
  if (kind === "function")
90761
- updateFunctions[key] = readFileSync37(abs, "utf-8");
90895
+ updateFunctions[key] = readFileSync38(abs, "utf-8");
90762
90896
  else if (kind === "binary")
90763
- updateBinary[key] = readFileSync37(abs).toString("base64");
90897
+ updateBinary[key] = readFileSync38(abs).toString("base64");
90764
90898
  else
90765
- updateFiles[key] = readFileSync37(abs, "utf-8");
90899
+ updateFiles[key] = readFileSync38(abs, "utf-8");
90766
90900
  }
90767
90901
  for (const rel of deleted)
90768
90902
  deleteKeys.push(classifyKey(rel).key);
@@ -90825,7 +90959,7 @@ async function deployBatch(client, projectId, cwd, changed, deleted, draftId, ex
90825
90959
  for (const rel of deleted)
90826
90960
  delete nextFiles[rel];
90827
90961
  for (const rel of changed)
90828
- if (existsSync35(join39(cwd, rel)))
90962
+ if (existsSync36(join40(cwd, rel)))
90829
90963
  Object.assign(nextFiles, hashFiles(cwd, [rel]));
90830
90964
  savePreviewRecord(cwd, { ...record3, preview_id: nextCandidate, files: nextFiles });
90831
90965
  }
@@ -91020,8 +91154,8 @@ var init_dev = __esm({
91020
91154
  });
91021
91155
 
91022
91156
  // dist/commands/check.js
91023
- import { existsSync as existsSync36 } from "node:fs";
91024
- import { join as join40, resolve as resolve21 } from "node:path";
91157
+ import { existsSync as existsSync37 } from "node:fs";
91158
+ import { join as join41, resolve as resolve21 } from "node:path";
91025
91159
  function buildCheckBody(collected, projectId) {
91026
91160
  const body = { project_id: projectId, files: collected.files };
91027
91161
  if (Object.keys(collected.functions).length > 0)
@@ -91126,7 +91260,7 @@ async function runLocalPreflight(targetDir, collected, typecheck = async (dir) =
91126
91260
  if (collected.excluded.length)
91127
91261
  source.not_published = collected.excluded;
91128
91262
  let typecheckStep;
91129
- if (!existsSync36(join40(targetDir, "tsconfig.json"))) {
91263
+ if (!existsSync37(join41(targetDir, "tsconfig.json"))) {
91130
91264
  typecheckStep = { name: "typecheck", status: "skipped", reason: MISSING_TSCONFIG_GUIDANCE };
91131
91265
  } else if (missingProjectDependencies(targetDir).length) {
91132
91266
  typecheckStep = { name: "typecheck", status: "skipped", reason: missingTypecheckDependenciesMessage() };
@@ -91543,7 +91677,7 @@ var init_api2 = __esm({
91543
91677
  import { createReadStream as createReadStream2, createWriteStream as createWriteStream2 } from "node:fs";
91544
91678
  import { stat as stat5, rename, unlink } from "node:fs/promises";
91545
91679
  import { randomUUID as randomUUID9 } from "node:crypto";
91546
- import { basename as basename8, dirname as dirname13, extname as extname6, join as join41, resolve as resolve23 } from "node:path";
91680
+ import { basename as basename8, dirname as dirname13, extname as extname6, join as join42, resolve as resolve23 } from "node:path";
91547
91681
  import { pipeline as pipeline2 } from "node:stream/promises";
91548
91682
  function registerFs(program2) {
91549
91683
  const fs2 = program2.command("fs").description("Manage project file storage");
@@ -91587,7 +91721,7 @@ function registerFs(program2) {
91587
91721
  if (!response.body)
91588
91722
  throw new Error("The server returned an empty file response.");
91589
91723
  const destination = resolve23(local);
91590
- tempPath = join41(dirname13(destination), `.${basename8(destination)}.${randomUUID9()}.tmp`);
91724
+ tempPath = join42(dirname13(destination), `.${basename8(destination)}.${randomUUID9()}.tmp`);
91591
91725
  await pipeline2(response.body, createWriteStream2(tempPath, { flags: "wx" }));
91592
91726
  await rename(tempPath, destination);
91593
91727
  tempPath = void 0;
@@ -109377,7 +109511,7 @@ var require_polyfill = __commonJS({
109377
109511
  var {
109378
109512
  dirname: dirname16,
109379
109513
  isAbsolute: isAbsolute7,
109380
- join: join51,
109514
+ join: join52,
109381
109515
  parse: parse3,
109382
109516
  resolve: resolve27,
109383
109517
  sep: sep2,
@@ -109658,8 +109792,8 @@ var require_polyfill = __commonJS({
109658
109792
  const dir = await readdir3(src);
109659
109793
  for (let i = 0; i < dir.length; i++) {
109660
109794
  const item = dir[i];
109661
- const srcItem = join51(src, item);
109662
- const destItem = join51(dest, item);
109795
+ const srcItem = join52(src, item);
109796
+ const destItem = join52(dest, item);
109663
109797
  const { destStat } = await checkPaths(srcItem, destItem, opts);
109664
109798
  await startCopy(destStat, srcItem, destItem, opts);
109665
109799
  }
@@ -109735,7 +109869,7 @@ var require_cp = __commonJS({
109735
109869
  // node_modules/@npmcli/fs/lib/with-temp-dir.js
109736
109870
  var require_with_temp_dir = __commonJS({
109737
109871
  "node_modules/@npmcli/fs/lib/with-temp-dir.js"(exports, module) {
109738
- var { join: join51, sep: sep2 } = __require("path");
109872
+ var { join: join52, sep: sep2 } = __require("path");
109739
109873
  var getOptions = require_get_options();
109740
109874
  var { mkdir, mkdtemp, rm } = __require("fs/promises");
109741
109875
  var withTempDir = /* @__PURE__ */ __name(async (root, fn, opts) => {
@@ -109743,7 +109877,7 @@ var require_with_temp_dir = __commonJS({
109743
109877
  copy: ["tmpPrefix"]
109744
109878
  });
109745
109879
  await mkdir(root, { recursive: true });
109746
- const target = await mkdtemp(join51(`${root}${sep2}`, options2.tmpPrefix || ""));
109880
+ const target = await mkdtemp(join52(`${root}${sep2}`, options2.tmpPrefix || ""));
109747
109881
  let err;
109748
109882
  let result;
109749
109883
  try {
@@ -109768,13 +109902,13 @@ var require_with_temp_dir = __commonJS({
109768
109902
  var require_readdir_scoped = __commonJS({
109769
109903
  "node_modules/@npmcli/fs/lib/readdir-scoped.js"(exports, module) {
109770
109904
  var { readdir: readdir3 } = __require("fs/promises");
109771
- var { join: join51 } = __require("path");
109905
+ var { join: join52 } = __require("path");
109772
109906
  var readdirScoped = /* @__PURE__ */ __name(async (dir) => {
109773
109907
  const results = [];
109774
109908
  for (const item of await readdir3(dir)) {
109775
109909
  if (item.startsWith("@")) {
109776
- for (const scopedItem of await readdir3(join51(dir, item))) {
109777
- results.push(join51(item, scopedItem));
109910
+ for (const scopedItem of await readdir3(join52(dir, item))) {
109911
+ results.push(join52(item, scopedItem));
109778
109912
  }
109779
109913
  } else {
109780
109914
  results.push(item);
@@ -109789,7 +109923,7 @@ var require_readdir_scoped = __commonJS({
109789
109923
  // node_modules/@npmcli/fs/lib/move-file.js
109790
109924
  var require_move_file = __commonJS({
109791
109925
  "node_modules/@npmcli/fs/lib/move-file.js"(exports, module) {
109792
- var { dirname: dirname16, join: join51, resolve: resolve27, relative: relative15, isAbsolute: isAbsolute7 } = __require("path");
109926
+ var { dirname: dirname16, join: join52, resolve: resolve27, relative: relative15, isAbsolute: isAbsolute7 } = __require("path");
109793
109927
  var fs2 = __require("fs/promises");
109794
109928
  var pathExists = /* @__PURE__ */ __name(async (path3) => {
109795
109929
  try {
@@ -109819,7 +109953,7 @@ var require_move_file = __commonJS({
109819
109953
  if (sourceStat.isDirectory()) {
109820
109954
  const files = await fs2.readdir(source);
109821
109955
  await Promise.all(files.map(
109822
- (file) => moveFile(join51(source, file), join51(destination, file), options2, false, symlinks)
109956
+ (file) => moveFile(join52(source, file), join52(destination, file), options2, false, symlinks)
109823
109957
  ));
109824
109958
  } else if (sourceStat.isSymbolicLink()) {
109825
109959
  symlinks.push({ source, destination });
@@ -129187,12 +129321,12 @@ var require_url = __commonJS({
129187
129321
  "node_modules/tuf-js/dist/utils/url.js"(exports) {
129188
129322
  "use strict";
129189
129323
  Object.defineProperty(exports, "__esModule", { value: true });
129190
- exports.join = join51;
129324
+ exports.join = join52;
129191
129325
  var url_1 = __require("url");
129192
- function join51(base, path3) {
129326
+ function join52(base, path3) {
129193
129327
  return new url_1.URL(ensureTrailingSlash(base) + removeLeadingSlash(path3)).toString();
129194
129328
  }
129195
- __name(join51, "join");
129329
+ __name(join52, "join");
129196
129330
  function ensureTrailingSlash(path3) {
129197
129331
  return path3.endsWith("/") ? path3 : path3 + "/";
129198
129332
  }
@@ -131528,8 +131662,8 @@ var require_dist15 = __commonJS({
131528
131662
 
131529
131663
  // dist/lib/update-security.js
131530
131664
  import { createHash as createHash9, timingSafeEqual } from "node:crypto";
131531
- import { mkdirSync as mkdirSync18, readFileSync as readFileSync38, statSync as statSync7 } from "node:fs";
131532
- import { join as join42 } from "node:path";
131665
+ import { mkdirSync as mkdirSync19, readFileSync as readFileSync39, statSync as statSync7 } from "node:fs";
131666
+ import { join as join43 } from "node:path";
131533
131667
  import { Readable as Readable2 } from "node:stream";
131534
131668
  import { pipeline as pipeline3 } from "node:stream/promises";
131535
131669
  function expectedTarballUrl(version2) {
@@ -131877,7 +132011,7 @@ async function extractArtifactSnapshot(artifact, extractionDir, filter) {
131877
132011
  await pipeline3(Readable2.from([artifact]), So({ cwd: extractionDir, strip: 1, strict: true, filter }));
131878
132012
  }
131879
132013
  async function verifyLockedArtifact(artifact, extractionDir, release2) {
131880
- mkdirSync18(extractionDir, { recursive: true, mode: 448 });
132014
+ mkdirSync19(extractionDir, { recursive: true, mode: 448 });
131881
132015
  const allowed = /* @__PURE__ */ new Map([
131882
132016
  ["package/package.json", MAX_MANIFEST_BYTES],
131883
132017
  ["package/npm-shrinkwrap.json", MAX_LOCKFILE_BYTES]
@@ -131894,15 +132028,15 @@ async function verifyLockedArtifact(artifact, extractionDir, release2) {
131894
132028
  seen2.add(path3);
131895
132029
  return true;
131896
132030
  });
131897
- const manifestPath = join42(extractionDir, "package.json");
131898
- const lockPath = join42(extractionDir, "npm-shrinkwrap.json");
132031
+ const manifestPath = join43(extractionDir, "package.json");
132032
+ const lockPath = join43(extractionDir, "npm-shrinkwrap.json");
131899
132033
  let manifest;
131900
132034
  let lock;
131901
132035
  try {
131902
132036
  if (statSync7(lockPath).size > MAX_LOCKFILE_BYTES)
131903
132037
  throw new Error("lockfile too large");
131904
- manifest = JSON.parse(readFileSync38(manifestPath, "utf8"));
131905
- lock = JSON.parse(readFileSync38(lockPath, "utf8"));
132038
+ manifest = JSON.parse(readFileSync39(manifestPath, "utf8"));
132039
+ lock = JSON.parse(readFileSync39(lockPath, "utf8"));
131906
132040
  } catch (cause) {
131907
132041
  throw new Error(`the verified artifact has no readable npm-shrinkwrap dependency lock: ${message(cause)}`);
131908
132042
  }
@@ -131939,8 +132073,8 @@ async function verifyLockedArtifact(artifact, extractionDir, release2) {
131939
132073
  }
131940
132074
  let bundledManifest;
131941
132075
  try {
131942
- const bundledPath = join42(extractionDir, ...lockPath2.split("/"), "package.json");
131943
- bundledManifest = JSON.parse(readFileSync38(bundledPath, "utf8"));
132076
+ const bundledPath = join43(extractionDir, ...lockPath2.split("/"), "package.json");
132077
+ bundledManifest = JSON.parse(readFileSync39(bundledPath, "utf8"));
131944
132078
  } catch (cause) {
131945
132079
  throw new Error(`the verified artifact has an unreadable bundled dependency ${lockPath2}: ${message(cause)}`);
131946
132080
  }
@@ -132010,10 +132144,10 @@ ${GITHUB_REPOSITORY_ID}`,
132010
132144
  // dist/commands/update.js
132011
132145
  import { spawn as spawn6 } from "node:child_process";
132012
132146
  import { randomBytes as randomBytes8 } from "node:crypto";
132013
- import { closeSync as closeSync5, constants as constants2, fstatSync, mkdtempSync as mkdtempSync3, openSync as openSync5, readFileSync as readFileSync39, readSync, rmSync as rmSync14, unlinkSync as unlinkSync5, writeFileSync as writeFileSync24 } from "node:fs";
132147
+ 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";
132014
132148
  import { createServer } from "node:http";
132015
132149
  import { tmpdir as tmpdir2 } from "node:os";
132016
- import { join as join43 } from "node:path";
132150
+ import { join as join44 } from "node:path";
132017
132151
  function refuse2(cause) {
132018
132152
  error(`Update refused: ${message2(cause)}.`);
132019
132153
  info(`To install the latest release with npm instead, run: ${teal(NPM_UPDATE_COMMAND)}`);
@@ -132021,7 +132155,7 @@ function refuse2(cause) {
132021
132155
  }
132022
132156
  function currentVersion2() {
132023
132157
  try {
132024
- const pkg = JSON.parse(readFileSync39(join43(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
132158
+ const pkg = JSON.parse(readFileSync40(join44(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
132025
132159
  return pkg.version;
132026
132160
  } catch {
132027
132161
  return "0.0.0";
@@ -132160,12 +132294,12 @@ async function serveArtifactSnapshot(artifact) {
132160
132294
  }
132161
132295
  async function installVerifiedTarball(tarballPath, tempDir, release2) {
132162
132296
  const ambientEnvironment = { ...process.env };
132163
- const packageDir = join43(tempDir, "authenticated-package");
132164
- const cacheDir = join43(tempDir, "empty-cache");
132165
- const userConfigPath = join43(tempDir, "user-npmrc");
132166
- const globalConfigPath = join43(tempDir, "global-npmrc");
132167
- writeFileSync24(userConfigPath, "", { mode: 384 });
132168
- writeFileSync24(globalConfigPath, "", { mode: 384 });
132297
+ const packageDir = join44(tempDir, "authenticated-package");
132298
+ const cacheDir = join44(tempDir, "empty-cache");
132299
+ const userConfigPath = join44(tempDir, "user-npmrc");
132300
+ const globalConfigPath = join44(tempDir, "global-npmrc");
132301
+ writeFileSync25(userConfigPath, "", { mode: 384 });
132302
+ writeFileSync25(globalConfigPath, "", { mode: 384 });
132169
132303
  const artifact = snapshotAuthenticatedArtifact(tarballPath);
132170
132304
  let artifactServer;
132171
132305
  try {
@@ -132235,9 +132369,9 @@ async function runUpdate(opts, dependencies = {}) {
132235
132369
  const provenance = await fetchJson(fetchImpl, release2.attestationUrl, "the official npm provenance endpoint");
132236
132370
  await (dependencies.verifyProvenance ?? verifyPublishedProvenance)(provenance, release2);
132237
132371
  const tarball = await downloadTarball(fetchImpl, release2);
132238
- tempDir = mkdtempSync3(join43(tmpdir2(), "somewhere-update-"));
132239
- const tarballPath = join43(tempDir, `cli-${release2.version}.tgz`);
132240
- writeFileSync24(tarballPath, tarball, { mode: 384 });
132372
+ tempDir = mkdtempSync4(join44(tmpdir2(), "somewhere-update-"));
132373
+ const tarballPath = join44(tempDir, `cli-${release2.version}.tgz`);
132374
+ writeFileSync25(tarballPath, tarball, { mode: 384 });
132241
132375
  info(`Cryptographically verified provenance and integrity for ${CLI_PACKAGE}@${release2.version}.`);
132242
132376
  info(`Updating ${CLI_PACKAGE} from its authenticated dependency lock \u2026`);
132243
132377
  await (dependencies.install ?? installVerifiedTarball)(tarballPath, tempDir, release2);
@@ -132245,7 +132379,7 @@ async function runUpdate(opts, dependencies = {}) {
132245
132379
  return refuse2(cause);
132246
132380
  } finally {
132247
132381
  if (tempDir)
132248
- rmSync14(tempDir, { recursive: true, force: true });
132382
+ rmSync15(tempDir, { recursive: true, force: true });
132249
132383
  }
132250
132384
  success(`Updated to ${release2.version}. Run ${teal(`${cliInvocation()} --version`)} to confirm.`);
132251
132385
  info(PROJECT_PIN_NOTE);
@@ -132368,7 +132502,7 @@ var init_upgrade = __esm({
132368
132502
  });
132369
132503
 
132370
132504
  // dist/commands/call.js
132371
- import { readFileSync as readFileSync40 } from "node:fs";
132505
+ import { readFileSync as readFileSync41 } from "node:fs";
132372
132506
  function parseArguments(value, file) {
132373
132507
  if (value === void 0)
132374
132508
  return {};
@@ -132392,7 +132526,7 @@ function readCallArguments(jsonArgs, file) {
132392
132526
  }
132393
132527
  let text;
132394
132528
  try {
132395
- text = readFileSync40(file, "utf8");
132529
+ text = readFileSync41(file, "utf8");
132396
132530
  } catch (err) {
132397
132531
  const code = err?.code;
132398
132532
  throw new Error(`Could not read --file ${file}${code ? ` (${code})` : ""}. The requested tool was not called.`);
@@ -134710,8 +134844,8 @@ var init_test_response_capture = __esm({
134710
134844
  import { randomUUID as randomUUID11 } from "node:crypto";
134711
134845
  import { setDefaultResultOrder } from "node:dns";
134712
134846
  import { lookup } from "node:dns/promises";
134713
- import { existsSync as existsSync37, mkdirSync as mkdirSync19, readFileSync as readFileSync41, writeFileSync as writeFileSync25 } from "node:fs";
134714
- import { basename as basename9, dirname as dirname14, join as join44, relative as relative12, resolve as resolve24 } from "node:path";
134847
+ import { existsSync as existsSync38, mkdirSync as mkdirSync20, readFileSync as readFileSync42, writeFileSync as writeFileSync26 } from "node:fs";
134848
+ import { basename as basename9, dirname as dirname14, join as join45, relative as relative12, resolve as resolve24 } from "node:path";
134715
134849
  function launchOptions(extra = {}) {
134716
134850
  return { ...extra, args: ["--disable-features=AsyncDns", ...extra.args ?? []] };
134717
134851
  }
@@ -134761,10 +134895,10 @@ function undeployedChanges(root, projectId, preview = false) {
134761
134895
  return null;
134762
134896
  base = { project_id: record3.project_id, release_id: record3.preview_id, files: record3.files };
134763
134897
  } else {
134764
- const path3 = join44(root, ".somewhere", "base-files.json");
134765
- if (!existsSync37(path3))
134898
+ const path3 = join45(root, ".somewhere", "base-files.json");
134899
+ if (!existsSync38(path3))
134766
134900
  return null;
134767
- base = JSON.parse(readFileSync41(path3, "utf8"));
134901
+ base = JSON.parse(readFileSync42(path3, "utf8"));
134768
134902
  }
134769
134903
  if (base.project_id !== projectId || !base.files)
134770
134904
  return null;
@@ -134934,7 +135068,7 @@ var init_app_test = __esm({
134934
135068
  for (const line of describeSweep(await sweepAccounts(control, root), "Before this script"))
134935
135069
  process.stderr.write(line + "\n");
134936
135070
  const scriptName = process.argv[1] ? basename9(process.argv[1]).replace(/\.[cm]?[jt]s$/, "") : "app-check";
134937
- const app = new _AppTest(root, control, resolve24(root, options2.results ?? join44(".somewhere", `${scriptName}${preview ? "-preview" : ""}.json`)));
135071
+ const app = new _AppTest(root, control, resolve24(root, options2.results ?? join45(".somewhere", `${scriptName}${preview ? "-preview" : ""}.json`)));
134938
135072
  return app;
134939
135073
  }
134940
135074
  /** What this run tests: the project, environment, preview, origin and script. */
@@ -135116,8 +135250,8 @@ page ${i + 1}: ${state}`).join("");
135116
135250
  }
135117
135251
  const passed = this.checks.filter((check) => check.ok).length;
135118
135252
  const failed = this.checks.filter((check) => !check.ok && !check.skipped).length;
135119
- mkdirSync19(dirname14(this.resultsPath), { recursive: true });
135120
- writeFileSync25(this.resultsPath, JSON.stringify({
135253
+ mkdirSync20(dirname14(this.resultsPath), { recursive: true });
135254
+ writeFileSync26(this.resultsPath, JSON.stringify({
135121
135255
  identity: this.identity(),
135122
135256
  origin: this.origin,
135123
135257
  environment: this.control.environment,
@@ -135136,7 +135270,7 @@ page ${i + 1}: ${state}`).join("");
135136
135270
  const resultFile = relative12(this.root, this.resultsPath);
135137
135271
  const handOver = process.env.SW_TEST_REPORT;
135138
135272
  if (handOver)
135139
- writeFileSync25(handOver, JSON.stringify({ checks: reported, resultFile }) + "\n");
135273
+ writeFileSync26(handOver, JSON.stringify({ checks: reported, resultFile }) + "\n");
135140
135274
  else {
135141
135275
  const verbose = process.argv.includes("--verbose") || process.env.SW_TEST_VERBOSE === "1";
135142
135276
  const script = process.argv[1] ? relative12(this.root, resolve24(process.argv[1])) : "this script";
@@ -135155,6 +135289,117 @@ page ${i + 1}: ${state}`).join("");
135155
135289
  }
135156
135290
  });
135157
135291
 
135292
+ // dist/lib/test-refusal.js
135293
+ async function bodyOf(response) {
135294
+ let json = null;
135295
+ try {
135296
+ json = await response.json();
135297
+ } catch {
135298
+ }
135299
+ const raw = typeof json?.error === "string" ? json.error : "";
135300
+ return { code: /^[A-Z_]+$/.test(raw) ? raw : "none", message: typeof json?.message === "string" ? scrub(json.message).slice(0, 300) : "", json };
135301
+ }
135302
+ function seen(status, code, message3) {
135303
+ const kind = status === 400 ? "a malformed request" : status === 409 ? "a stale data contract" : `HTTP ${status}`;
135304
+ return `${kind} (${status} ${code}${message3 ? `: ${message3}` : ""})`;
135305
+ }
135306
+ async function assertRefused(client, target, request2, allowed) {
135307
+ const endpoint = ENDPOINT.exec(target);
135308
+ if (endpoint) {
135309
+ const [, method, path3] = endpoint;
135310
+ const payload = method === "GET" ? void 0 : request2;
135311
+ const response2 = await client.endpoint(method, path3, payload);
135312
+ const status2 = response2.status;
135313
+ const { code: code2, message: message4 } = await bodyOf(response2);
135314
+ const said2 = `${target} answered ${seen(status2, code2, message4)}`;
135315
+ if (status2 < 400)
135316
+ throw new Error(`expectRefused: ${said2}: this person could call the endpoint.`);
135317
+ if (status2 === 400 || status2 === 422)
135318
+ throw new Error(`expectRefused: ${said2}: the endpoint rejected the input, which says nothing about who is asking. Send a body it accepts from someone who may.`);
135319
+ if (![401, 403, 404].includes(status2))
135320
+ throw new Error(`expectRefused: ${said2}: a refusal is 401, 403 or 404.`);
135321
+ if (status2 === 404 && !allowed)
135322
+ throw new Error(`expectRefused: ${said2}: a 404 ${INCONCLUSIVE}`);
135323
+ if (allowed) {
135324
+ const control = await allowed.endpoint(method, path3, payload);
135325
+ const c = await bodyOf(control);
135326
+ if (control.status >= 300)
135327
+ throw new Error(`expectRefused: ${said2}, but the allowed person got ${seen(control.status, c.code, c.message)} too, so the route or input is wrong and the refusal is not proven.`);
135328
+ }
135329
+ return;
135330
+ }
135331
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(target))
135332
+ throw new Error(`expectRefused: "${target}" is neither a table name nor 'METHOD /path'.`);
135333
+ if (!request2 || typeof request2 !== "object" || typeof request2.operation !== "string") {
135334
+ throw new Error(`expectRefused: pass a data request for table ${target}, for example { operation: 'get', id }.`);
135335
+ }
135336
+ const operation = request2.operation;
135337
+ const reading = operation === "get" || operation === "list" || operation === "relation_list";
135338
+ const writing = operation === "update" || operation === "delete";
135339
+ const id = request2.id;
135340
+ const rowOf = /* @__PURE__ */ __name(async (as2) => {
135341
+ const response2 = await as2.data(target, { operation: "get", id });
135342
+ const body = await bodyOf(response2);
135343
+ if (response2.status !== 200)
135344
+ throw new Error(`expectRefused: the allowed person could not read ${target} ${String(id)} (${seen(response2.status, body.code, body.message)}), so choose a control that can read this row.`);
135345
+ return body.json?.data ?? null;
135346
+ }, "rowOf");
135347
+ let before = "";
135348
+ if (writing && allowed) {
135349
+ const row = await rowOf(allowed);
135350
+ before = JSON.stringify(row);
135351
+ if (row === null)
135352
+ throw new Error(`expectRefused: ${target} ${String(id)} does not exist for the allowed person, so there is nothing to refuse. Create the row first.`);
135353
+ }
135354
+ const response = await client.data(target, request2);
135355
+ const status = response.status;
135356
+ const { code, message: message3, json } = await bodyOf(response);
135357
+ const said = `${operation} on ${target} answered ${seen(status, code, message3)}`;
135358
+ const { kind } = classifyData(status, json, operation);
135359
+ if (kind === "missing-contract" || kind === "stale-contract" || kind === "malformed") {
135360
+ throw new Error(`expectRefused: ${said}. Nothing ran, so this proves nothing about access.`);
135361
+ }
135362
+ const rows = json?.data;
135363
+ const empty = status === 200 && (operation === "get" && rows === null || (operation === "list" || operation === "relation_list") && Array.isArray(rows) && rows.length === 0);
135364
+ const missing = kind === "missing-or-refused";
135365
+ if (status === 200 && !empty) {
135366
+ if (reading)
135367
+ throw new Error(`expectRefused: ${said}: this person read ${Array.isArray(rows) ? `${rows.length} row(s)` : "the row"}.`);
135368
+ throw new Error(`expectRefused: ${said}: the ${operation} was allowed.`);
135369
+ }
135370
+ if (kind !== "refused" && !empty && !missing)
135371
+ throw new Error(`expectRefused: ${said}: expected an access refusal.`);
135372
+ if ((empty || missing) && !allowed)
135373
+ throw new Error(`expectRefused: ${said}: ${empty ? "an empty answer" : "a 404"} ${INCONCLUSIVE}`);
135374
+ if (!allowed)
135375
+ return;
135376
+ if (reading) {
135377
+ const control = await allowed.data(target, request2);
135378
+ const c = await bodyOf(control);
135379
+ const got = c.json?.data;
135380
+ const found = control.status === 200 && (operation === "get" ? got !== null && got !== void 0 : Array.isArray(got) && got.length > 0);
135381
+ if (!found)
135382
+ throw new Error(`expectRefused: ${said}, but the allowed person got ${control.status === 200 ? "nothing" : seen(control.status, c.code, c.message)} for the same request, so there was nothing to refuse.`);
135383
+ } else if (writing) {
135384
+ const after = await rowOf(allowed);
135385
+ if (JSON.stringify(after) !== before)
135386
+ throw new Error(`expectRefused: ${said}, but ${target} ${String(id)} ${after === null ? "is gone" : "changed"} for the allowed person afterwards.`);
135387
+ }
135388
+ }
135389
+ var ENDPOINT, INCONCLUSIVE;
135390
+ var init_test_refusal = __esm({
135391
+ "dist/lib/test-refusal.js"() {
135392
+ "use strict";
135393
+ init_app_test();
135394
+ init_test_diagnostics();
135395
+ ENDPOINT = /^(GET|POST|PUT|PATCH|DELETE) (\/\S*)$/;
135396
+ __name(bodyOf, "bodyOf");
135397
+ INCONCLUSIVE = "looks the same as an empty table, a missing row or a missing route, so it proves nothing on its own. Pass { allowed: <someone the same request succeeds for> } as the positive control.";
135398
+ __name(seen, "seen");
135399
+ __name(assertRefused, "assertRefused");
135400
+ }
135401
+ });
135402
+
135158
135403
  // dist/lib/test-session.js
135159
135404
  async function expectStatus(response, expected) {
135160
135405
  if (response.status !== expected)
@@ -135191,6 +135436,7 @@ var UserSession;
135191
135436
  var init_test_session = __esm({
135192
135437
  "dist/lib/test-session.js"() {
135193
135438
  "use strict";
135439
+ init_test_refusal();
135194
135440
  init_client();
135195
135441
  init_config();
135196
135442
  init_test_target();
@@ -135299,6 +135545,21 @@ var init_test_session = __esm({
135299
135545
  post(path3, body) {
135300
135546
  return this.request(path3, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
135301
135547
  }
135548
+ async expectRefused(target, request2, { allowed } = {}) {
135549
+ if (allowed && allowed.origin !== this.origin)
135550
+ throw new Error("Choose a control session from the same app.");
135551
+ const adapt = /* @__PURE__ */ __name((session) => ({
135552
+ endpoint(method, path3, body) {
135553
+ return session.request(path3, body === void 0 ? { method } : {
135554
+ method,
135555
+ headers: { "Content-Type": "application/json" },
135556
+ body: JSON.stringify(body)
135557
+ });
135558
+ },
135559
+ data: /* @__PURE__ */ __name((table2, request3) => session.data(table2, request3), "data")
135560
+ }), "adapt");
135561
+ await assertRefused(adapt(this), target, request2, allowed && adapt(allowed));
135562
+ }
135302
135563
  async data(table2, requestOrContract, request2) {
135303
135564
  if (typeof requestOrContract === "string") {
135304
135565
  return this.post("/__sw/data", { ...request2, table: table2, contract: requestOrContract });
@@ -135324,7 +135585,7 @@ var init_test_session = __esm({
135324
135585
 
135325
135586
  // dist/lib/prepared-actor-session.js
135326
135587
  import { createHash as createHash10 } from "node:crypto";
135327
- import { closeSync as closeSync6, openSync as openSync6, rmSync as rmSync15 } from "node:fs";
135588
+ import { closeSync as closeSync6, openSync as openSync6, rmSync as rmSync16 } from "node:fs";
135328
135589
  import { setTimeout as delay } from "node:timers/promises";
135329
135590
  async function preparedActorSession(root, target, name) {
135330
135591
  const read = /* @__PURE__ */ __name(() => preparedActorState(root, target, name), "read");
@@ -135360,7 +135621,7 @@ async function preparedActorSession(root, target, name) {
135360
135621
  return token;
135361
135622
  } finally {
135362
135623
  closeSync6(fd);
135363
- rmSync15(lock, { force: true });
135624
+ rmSync16(lock, { force: true });
135364
135625
  }
135365
135626
  }
135366
135627
  throw new Error(`Another command is refreshing test user ${name}. Wait for it to finish, or clean up and prepare the test users again.`);
@@ -135466,46 +135727,46 @@ var init_reference_check_note = __esm({
135466
135727
  });
135467
135728
 
135468
135729
  // dist/lib/test-scripts.js
135469
- import { createRequire as createRequire9 } from "node:module";
135470
- import { existsSync as existsSync38, mkdirSync as mkdirSync20, readFileSync as readFileSync42, readdirSync as readdirSync8, rmSync as rmSync16, statSync as statSync8, writeFileSync as writeFileSync26 } from "node:fs";
135471
- import { dirname as dirname15, join as join45, relative as relative13, resolve as resolve25 } from "node:path";
135730
+ import { createRequire as createRequire10 } from "node:module";
135731
+ 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";
135732
+ import { dirname as dirname15, join as join46, relative as relative13, resolve as resolve25 } from "node:path";
135472
135733
  import { spawn as spawn7, spawnSync as spawnSync5 } from "node:child_process";
135473
135734
  function hasSpecFiles(root) {
135474
135735
  const walk2 = /* @__PURE__ */ __name((dir) => {
135475
- if (!existsSync38(dir))
135736
+ if (!existsSync39(dir))
135476
135737
  return false;
135477
135738
  for (const entry of readdirSync8(dir, { withFileTypes: true })) {
135478
135739
  if (entry.name === "node_modules" || entry.name.startsWith("."))
135479
135740
  continue;
135480
- const path3 = join45(dir, entry.name);
135741
+ const path3 = join46(dir, entry.name);
135481
135742
  if (entry.isDirectory() ? walk2(path3) : /\.spec\.ts$/.test(entry.name))
135482
135743
  return true;
135483
135744
  }
135484
135745
  return false;
135485
135746
  }, "walk");
135486
- return walk2(join45(root, "tests"));
135747
+ return walk2(join46(root, "tests"));
135487
135748
  }
135488
135749
  function listScripts(root, files) {
135489
135750
  if (files.length)
135490
135751
  return files.map((file) => relative13(root, resolve25(root, file)));
135491
- const dir = join45(root, "tests");
135492
- if (!existsSync38(dir))
135752
+ const dir = join46(root, "tests");
135753
+ if (!existsSync39(dir))
135493
135754
  return [];
135494
- return readdirSync8(dir).filter((name) => isScript(name) && statSync8(join45(dir, name)).isFile()).sort().map((name) => join45("tests", name));
135755
+ return readdirSync8(dir).filter((name) => isScript(name) && statSync8(join46(dir, name)).isFile()).sort().map((name) => join46("tests", name));
135495
135756
  }
135496
135757
  function scriptBrowserEnv(root) {
135497
- const require5 = createRequire9(join45(root, "package.json"));
135758
+ const require6 = createRequire10(join46(root, "package.json"));
135498
135759
  let cli;
135499
135760
  try {
135500
- cli = require5.resolve("@playwright/test/cli");
135761
+ cli = require6.resolve("@playwright/test/cli");
135501
135762
  } catch {
135502
135763
  throw testDependencyError(root);
135503
135764
  }
135504
135765
  const env = { ...process.env, PLAYWRIGHT_NO_COPY_PROMPT: "1" };
135505
- const probe = spawnSync5(process.execPath, ["-e", "require(process.argv[1]).chromium.launch().then(b => b.close()).then(() => process.exit(0), () => process.exit(3))", require5.resolve("@playwright/test")], { env, stdio: "ignore" });
135766
+ const probe = spawnSync5(process.execPath, ["-e", "require(process.argv[1]).chromium.launch().then(b => b.close()).then(() => process.exit(0), () => process.exit(3))", require6.resolve("@playwright/test")], { env, stdio: "ignore" });
135506
135767
  if (probe.status === 0)
135507
135768
  return env;
135508
- env.PLAYWRIGHT_BROWSERS_PATH ??= join45(cliConfigDir(), "cache", "playwright");
135769
+ env.PLAYWRIGHT_BROWSERS_PATH ??= join46(cliConfigDir(), "cache", "playwright");
135509
135770
  process.stderr.write("Installing Playwright Chromium in the CLI cache (once).\n");
135510
135771
  const install = spawnSync5(process.execPath, [cli, "install", "chromium"], { stdio: "inherit", env });
135511
135772
  if (install.status !== 0)
@@ -135528,7 +135789,7 @@ async function runScripts(root, scripts, extraArgs, env = scriptBrowserEnv(root)
135528
135789
  env = testImportEnv(root, env);
135529
135790
  const results = [];
135530
135791
  for (const script of scripts) {
135531
- if (!existsSync38(join45(root, script))) {
135792
+ if (!existsSync39(join46(root, script))) {
135532
135793
  results.push({ script, ok: false, exitCode: 1, ms: 0, reason: "no such file" });
135533
135794
  continue;
135534
135795
  }
@@ -135537,9 +135798,9 @@ async function runScripts(root, scripts, extraArgs, env = scriptBrowserEnv(root)
135537
135798
  `);
135538
135799
  const started = performance.now();
135539
135800
  let output = "";
135540
- const handOver = join45(root, ".somewhere", "tests", `report-${results.length}.json`);
135541
- mkdirSync20(dirname15(handOver), { recursive: true });
135542
- rmSync16(handOver, { force: true });
135801
+ const handOver = join46(root, ".somewhere", "tests", `report-${results.length}.json`);
135802
+ mkdirSync21(dirname15(handOver), { recursive: true });
135803
+ rmSync17(handOver, { force: true });
135543
135804
  const askedForBrowserLog = /(^|,)\s*(pw:browser|pw:\*|\*)\s*(,|$)/.test(env.DEBUG ?? "");
135544
135805
  const childEnv = { ...env, SW_TEST_REPORT: handOver, DEBUG: askedForBrowserLog ? env.DEBUG : [env.DEBUG, "pw:browser"].filter(Boolean).join(",") };
135545
135806
  const child = spawn7(process.execPath, [script, ...extraArgs], { cwd: root, env: childEnv, stdio: ["inherit", "pipe", "pipe"] });
@@ -135567,11 +135828,11 @@ async function runScripts(root, scripts, extraArgs, env = scriptBrowserEnv(root)
135567
135828
  stderrLines("", true);
135568
135829
  let report2 = null;
135569
135830
  try {
135570
- report2 = existsSync38(handOver) ? JSON.parse(readFileSync42(handOver, "utf8")) : null;
135831
+ report2 = existsSync39(handOver) ? JSON.parse(readFileSync43(handOver, "utf8")) : null;
135571
135832
  } catch {
135572
135833
  report2 = null;
135573
135834
  }
135574
- rmSync16(handOver, { force: true });
135835
+ rmSync17(handOver, { force: true });
135575
135836
  results.push({
135576
135837
  script,
135577
135838
  ok: exitCode === 0,
@@ -135600,20 +135861,20 @@ function describeScriptResults(results, options2 = {}) {
135600
135861
  return results.some((result) => result.browserCrashed) ? lines.map((line) => line.startsWith("Next: ") ? `Next: give the browser access as the FAIL line says, then run ${TEST_COMMAND} again.` : line) : lines;
135601
135862
  }
135602
135863
  function lastFailedScripts(root) {
135603
- const path3 = join45(root, LAST);
135604
- if (!existsSync38(path3))
135864
+ const path3 = join46(root, LAST);
135865
+ if (!existsSync39(path3))
135605
135866
  return [];
135606
135867
  try {
135607
- return (JSON.parse(readFileSync42(path3, "utf8")).results ?? []).filter((r) => !r.ok).map((r) => r.script);
135868
+ return (JSON.parse(readFileSync43(path3, "utf8")).results ?? []).filter((r) => !r.ok).map((r) => r.script);
135608
135869
  } catch {
135609
135870
  return [];
135610
135871
  }
135611
135872
  }
135612
135873
  function recordScriptResults(root, results, rerunOnly) {
135613
- const previous = rerunOnly && existsSync38(join45(root, LAST)) ? JSON.parse(readFileSync42(join45(root, LAST), "utf8")).results ?? [] : [];
135874
+ const previous = rerunOnly && existsSync39(join46(root, LAST)) ? JSON.parse(readFileSync43(join46(root, LAST), "utf8")).results ?? [] : [];
135614
135875
  const merged = [...previous.filter((p2) => !results.some((r) => r.script === p2.script)), ...results];
135615
- mkdirSync20(join45(root, ".somewhere", "tests"), { recursive: true });
135616
- writeFileSync26(join45(root, LAST), JSON.stringify({ finished: (/* @__PURE__ */ new Date()).toISOString(), results: merged }, null, 2) + "\n");
135876
+ mkdirSync21(join46(root, ".somewhere", "tests"), { recursive: true });
135877
+ writeFileSync27(join46(root, LAST), JSON.stringify({ finished: (/* @__PURE__ */ new Date()).toISOString(), results: merged }, null, 2) + "\n");
135617
135878
  }
135618
135879
  var BROWSER_CRASH, BROWSER_CRASH_REASON, isScript, LAST;
135619
135880
  var init_test_scripts = __esm({
@@ -135631,7 +135892,7 @@ var init_test_scripts = __esm({
135631
135892
  __name(failureReason, "failureReason");
135632
135893
  __name(runScripts, "runScripts");
135633
135894
  __name(describeScriptResults, "describeScriptResults");
135634
- LAST = join45(".somewhere", "tests", "scripts-last.json");
135895
+ LAST = join46(".somewhere", "tests", "scripts-last.json");
135635
135896
  __name(lastFailedScripts, "lastFailedScripts");
135636
135897
  __name(recordScriptResults, "recordScriptResults");
135637
135898
  }
@@ -135726,8 +135987,8 @@ var init_test = __esm({
135726
135987
  });
135727
135988
 
135728
135989
  // dist/commands/test-users.js
135729
- import { existsSync as existsSync39, readFileSync as readFileSync43, rmSync as rmSync17 } from "node:fs";
135730
- import { basename as basename10, join as join46 } from "node:path";
135990
+ import { existsSync as existsSync40, readFileSync as readFileSync44, rmSync as rmSync18 } from "node:fs";
135991
+ import { basename as basename10, join as join47 } from "node:path";
135731
135992
  import { randomBytes as randomBytes9 } from "node:crypto";
135732
135993
  async function resolveTarget(projectOpt, originOpt) {
135733
135994
  const root = process.cwd();
@@ -135818,7 +136079,7 @@ function registerTestUsers(program2) {
135818
136079
  const record3 = /* @__PURE__ */ __name((spec, issued, receivedAt) => {
135819
136080
  const times = expiryOf(issued, receivedAt);
135820
136081
  const file = `${spec.name}.state.json`;
135821
- writePrivateFile(join46(dir, file), JSON.stringify(buildStorageState(target.origin, target.host, issued, times), null, 2) + "\n");
136082
+ writePrivateFile(join47(dir, file), JSON.stringify(buildStorageState(target.origin, target.host, issued, times), null, 2) + "\n");
135822
136083
  const actor = {
135823
136084
  name: spec.name,
135824
136085
  user_id: issued.user.id,
@@ -135919,7 +136180,7 @@ function registerTestUsers(program2) {
135919
136180
  if (name !== opts.linkOut || !/^[A-Za-z0-9._-]{1,64}$/.test(name))
135920
136181
  throw new Error(`--link-out takes a file name; it is written under ${TEST_STATE_DIR}/.`);
135921
136182
  ensurePrivateDir(stateDir(target.root));
135922
- writePrivateFile(join46(stateDir(target.root), name), newest.magic_link + "\n");
136183
+ writePrivateFile(join47(stateDir(target.root), name), newest.magic_link + "\n");
135923
136184
  linkFile = `${TEST_STATE_DIR}/${name}`;
135924
136185
  }
135925
136186
  const message3 = {
@@ -135990,12 +136251,12 @@ function registerTestUsers(program2) {
135990
136251
  local_state: { removed: localRemoved, kept: manifest.actors.map((actor) => actor.state_file).filter((file) => !localRemoved.includes(file)) },
135991
136252
  actors: manifest.actors.map(({ name, user_id, email: email2, role, created_at }) => ({ name, user_id, email: email2, role, created_at }))
135992
136253
  };
135993
- writePrivateFile(join46(stateDir(target.root), CLEANUP_RECEIPT_FILE), JSON.stringify(receipt, null, 2) + "\n");
136254
+ writePrivateFile(join47(stateDir(target.root), CLEANUP_RECEIPT_FILE), JSON.stringify(receipt, null, 2) + "\n");
135994
136255
  const left = manifest.actors.filter((actor) => !removed.includes(actor.user_id));
135995
136256
  if (left.length)
135996
136257
  writeManifest(target.root, { ...manifest, actors: left, status: "partial" });
135997
136258
  else
135998
- rmSync17(join46(stateDir(target.root), MANIFEST_FILE), { force: true });
136259
+ rmSync18(join47(stateDir(target.root), MANIFEST_FILE), { force: true });
135999
136260
  if (opts.json) {
136000
136261
  printJson(receipt);
136001
136262
  if (left.length)
@@ -136035,7 +136296,7 @@ var init_test_users = __esm({
136035
136296
  });
136036
136297
 
136037
136298
  // dist/commands/support.js
136038
- import { join as join47 } from "node:path";
136299
+ import { join as join48 } from "node:path";
136039
136300
  function commandPaths(program2) {
136040
136301
  const paths = /* @__PURE__ */ new Set();
136041
136302
  const walk2 = /* @__PURE__ */ __name((command, prefix) => {
@@ -136120,7 +136381,7 @@ function emitPacket(packet, opts) {
136120
136381
  if (opts.out) {
136121
136382
  if (!/^[A-Za-z0-9._-]{1,64}$/.test(opts.out))
136122
136383
  throw new Error("--out takes a plain file name in the current folder.");
136123
- writePrivateFile(join47(process.cwd(), opts.out), JSON.stringify(packet, null, 2) + "\n");
136384
+ writePrivateFile(join48(process.cwd(), opts.out), JSON.stringify(packet, null, 2) + "\n");
136124
136385
  }
136125
136386
  if (opts.json) {
136126
136387
  printJson(packet);
@@ -136242,7 +136503,7 @@ var init_skills = __esm({
136242
136503
  });
136243
136504
 
136244
136505
  // dist/commands/ai.js
136245
- import { readFileSync as readFileSync44 } from "node:fs";
136506
+ import { readFileSync as readFileSync45 } from "node:fs";
136246
136507
  function fail4(message3) {
136247
136508
  error(message3);
136248
136509
  process.exit(1);
@@ -136263,7 +136524,7 @@ async function readKey(stdin) {
136263
136524
  if (stdin) {
136264
136525
  if (process.stdin.isTTY)
136265
136526
  fail4("Pipe the key into --stdin, or leave out --stdin to type it into a hidden prompt.");
136266
- raw = readFileSync44(0, "utf8");
136527
+ raw = readFileSync45(0, "utf8");
136267
136528
  } else {
136268
136529
  if (!process.stdin.isTTY)
136269
136530
  fail4("Pass --stdin to read the key from a pipe. Nothing was sent.");
@@ -136410,13 +136671,13 @@ var init_startup_notice = __esm({
136410
136671
  });
136411
136672
 
136412
136673
  // dist/lib/last-run.js
136413
- import { lstatSync as lstatSync5, mkdirSync as mkdirSync21, renameSync as renameSync6, unlinkSync as unlinkSync6, writeFileSync as writeFileSync27 } from "node:fs";
136414
- import { join as join48 } from "node:path";
136674
+ import { lstatSync as lstatSync6, mkdirSync as mkdirSync22, renameSync as renameSync7, unlinkSync as unlinkSync6, writeFileSync as writeFileSync28 } from "node:fs";
136675
+ import { join as join49 } from "node:path";
136415
136676
  function removeStaleRunRecord(dir = cliConfigDir()) {
136416
136677
  for (const name of RUN_RECORD_FILES) {
136417
- const path3 = join48(dir, name);
136678
+ const path3 = join49(dir, name);
136418
136679
  try {
136419
- if (lstatSync5(path3).isDirectory()) {
136680
+ if (lstatSync6(path3).isDirectory()) {
136420
136681
  process.stderr.write(`Could not remove ${path3}: it is a directory, not this CLI's run record. Check it yourself.
136421
136682
  `);
136422
136683
  continue;
@@ -136445,7 +136706,7 @@ function recordLastRun(cliVersion) {
136445
136706
  process.once("exit", (exitCode) => {
136446
136707
  try {
136447
136708
  const dir = cliConfigDir();
136448
- mkdirSync21(dir, { recursive: true, mode: 448 });
136709
+ mkdirSync22(dir, { recursive: true, mode: 448 });
136449
136710
  const record3 = {
136450
136711
  // A usage error never reaches a command: no command and no options.
136451
136712
  command: invocation?.command ?? "",
@@ -136454,10 +136715,10 @@ function recordLastRun(cliVersion) {
136454
136715
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
136455
136716
  cli_version: cliVersion
136456
136717
  };
136457
- const path3 = join48(dir, "last-run.json");
136458
- const temporary = join48(dir, "last-run.json.tmp");
136459
- writeFileSync27(temporary, JSON.stringify(record3) + "\n", { mode: 384 });
136460
- renameSync6(temporary, path3);
136718
+ const path3 = join49(dir, "last-run.json");
136719
+ const temporary = join49(dir, "last-run.json.tmp");
136720
+ writeFileSync28(temporary, JSON.stringify(record3) + "\n", { mode: 384 });
136721
+ renameSync7(temporary, path3);
136461
136722
  } catch {
136462
136723
  }
136463
136724
  });
@@ -136493,8 +136754,8 @@ __export(dist_exports, {
136493
136754
  runCli: () => runCli
136494
136755
  });
136495
136756
  import { spawnSync as spawnSync6 } from "node:child_process";
136496
- import { readFileSync as readFileSync45 } from "node:fs";
136497
- import { join as join49 } from "node:path";
136757
+ import { readFileSync as readFileSync46 } from "node:fs";
136758
+ import { join as join50 } from "node:path";
136498
136759
  async function runCli() {
136499
136760
  const pinned = decidePin(process.cwd(), CLI_VERSION, process.argv, process.env);
136500
136761
  if (pinned.notice)
@@ -136522,7 +136783,7 @@ async function runCli() {
136522
136783
  process.exit(child.status ?? 1);
136523
136784
  }
136524
136785
  removeStaleRunRecord();
136525
- const pkg = JSON.parse(readFileSync45(join49(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
136786
+ const pkg = JSON.parse(readFileSync46(join50(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
136526
136787
  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);
136527
136788
  recordLastRun(pkg.version);
136528
136789
  const jsonOutputRequested = process.argv.includes("--json");
@@ -136935,8 +137196,8 @@ var init_screenshot_guard = __esm({
136935
137196
  });
136936
137197
 
136937
137198
  // dist/lib/playwright-fixtures.js
136938
- import { createRequire as createRequire10 } from "node:module";
136939
- import { join as join50 } from "node:path";
137199
+ import { createRequire as createRequire11 } from "node:module";
137200
+ import { join as join51 } from "node:path";
136940
137201
  function waitOnNavigation(page) {
136941
137202
  async function wait(options2) {
136942
137203
  if (options2?.waitUntil === "commit")
@@ -136988,10 +137249,10 @@ async function previewControlForWorker() {
136988
137249
  function runner() {
136989
137250
  if (loaded)
136990
137251
  return loaded;
136991
- const require5 = createRequire10(join50(process.cwd(), "package.json"));
137252
+ const require6 = createRequire11(join51(process.cwd(), "package.json"));
136992
137253
  let pw;
136993
137254
  try {
136994
- pw = require5("@playwright/test");
137255
+ pw = require6("@playwright/test");
136995
137256
  } catch {
136996
137257
  throw new Error("Install project test dependencies: npm install -D @playwright/test @somewhere-cloud/cli");
136997
137258
  }
@@ -137320,107 +137581,20 @@ function clientOf2(person) {
137320
137581
  return person.request;
137321
137582
  return person;
137322
137583
  }
137323
- async function bodyOf(response) {
137324
- let json = null;
137325
- try {
137326
- json = await response.json();
137327
- } catch {
137328
- }
137329
- const raw = typeof json?.error === "string" ? json.error : "";
137330
- return { code: /^[A-Z_]+$/.test(raw) ? raw : "none", message: typeof json?.message === "string" ? scrub(json.message).slice(0, 300) : "", json };
137331
- }
137332
- function seen(status, code, message3) {
137333
- const kind = status === 400 ? "a malformed request" : status === 409 ? "a stale data contract" : `HTTP ${status}`;
137334
- return `${kind} (${status} ${code}${message3 ? `: ${message3}` : ""})`;
137335
- }
137336
137584
  async function refusedAs(person, target, request2, options2) {
137337
- const client = clientOf2(person);
137338
- const allowed = options2.allowed === void 0 ? void 0 : clientOf2(options2.allowed);
137339
- const endpoint = ENDPOINT.exec(target);
137340
- if (endpoint) {
137341
- const [, method, path3] = endpoint;
137342
- const send = /* @__PURE__ */ __name((as2) => as2.fetch(path3, { method, ...method === "GET" || request2 === void 0 ? {} : { data: request2 } }), "send");
137343
- const response2 = await send(client);
137344
- const status2 = response2.status();
137345
- const { code: code2, message: message4 } = await bodyOf(response2);
137346
- const said2 = `${target} answered ${seen(status2, code2, message4)}`;
137347
- if (status2 < 400)
137348
- throw new Error(`expectRefused: ${said2}: it was allowed, not refused.`);
137349
- if (status2 === 400 || status2 === 422)
137350
- throw new Error(`expectRefused: ${said2}: the endpoint rejected the input, which says nothing about who is asking. Send a body it accepts from someone who may.`);
137351
- if (![401, 403, 404].includes(status2))
137352
- throw new Error(`expectRefused: ${said2}: a refusal is 401, 403 or 404.`);
137353
- if (status2 === 404 && !allowed)
137354
- throw new Error(`expectRefused: ${said2}: a 404 ${INCONCLUSIVE}`);
137355
- if (allowed) {
137356
- const control = await send(allowed);
137357
- const c = await bodyOf(control);
137358
- if (control.status() >= 300)
137359
- throw new Error(`expectRefused: ${said2}, but the allowed person got ${seen(control.status(), c.code, c.message)} too, so the route or input is wrong and the refusal is not proven.`);
137585
+ const adapt = /* @__PURE__ */ __name((client) => ({
137586
+ async endpoint(method, path3, body) {
137587
+ const response = await client.fetch(path3, { method, ...body === void 0 ? {} : { data: body } });
137588
+ return { status: response.status(), json: /* @__PURE__ */ __name(() => response.json(), "json") };
137589
+ },
137590
+ async data(table2, request3) {
137591
+ if (!digests.has(client))
137592
+ throw new Error("expectRefused: act as (and pass allowed as) a page that signed up or signed in (signUp/signIn), a newUser() user, or anonymous.");
137593
+ const response = await data(client, table2, request3);
137594
+ return { status: response.status(), json: /* @__PURE__ */ __name(() => response.json(), "json") };
137360
137595
  }
137361
- return;
137362
- }
137363
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(target))
137364
- throw new Error(`expectRefused: "${target}" is neither a table name nor 'METHOD /path'.`);
137365
- if (!request2 || typeof request2 !== "object" || typeof request2.operation !== "string") {
137366
- throw new Error(`expectRefused: pass a data request for table ${target}, for example { operation: 'get', id }.`);
137367
- }
137368
- for (const as2 of [client, ...allowed ? [allowed] : []]) {
137369
- if (!digests.has(as2))
137370
- throw new Error("expectRefused: act as (and pass allowed as) a page that signed up or signed in (signUp/signIn), a newUser() user, or anonymous.");
137371
- }
137372
- const operation = request2.operation;
137373
- const reading = operation === "get" || operation === "list" || operation === "relation_list";
137374
- const writing = operation === "update" || operation === "delete";
137375
- const id = request2.id;
137376
- const rowOf = /* @__PURE__ */ __name(async (as2) => {
137377
- const response2 = await data(as2, target, { operation: "get", id });
137378
- const body = await bodyOf(response2);
137379
- if (response2.status() !== 200)
137380
- throw new Error(`expectRefused: the allowed person could not read ${target} ${String(id)} (${seen(response2.status(), body.code, body.message)}), so it is not a control for this row.`);
137381
- return body.json?.data ?? null;
137382
- }, "rowOf");
137383
- let before = "";
137384
- if (writing && allowed) {
137385
- const row = await rowOf(allowed);
137386
- before = JSON.stringify(row);
137387
- if (row === null)
137388
- throw new Error(`expectRefused: ${target} ${String(id)} does not exist for the allowed person, so there is nothing to refuse. Create the row first.`);
137389
- }
137390
- const response = await data(client, target, request2);
137391
- const status = response.status();
137392
- const { code, message: message3, json } = await bodyOf(response);
137393
- const said = `${operation} on ${target} answered ${seen(status, code, message3)}`;
137394
- const { kind } = classifyData(status, json, operation);
137395
- if (kind === "missing-contract" || kind === "stale-contract" || kind === "malformed") {
137396
- throw new Error(`expectRefused: ${said}. Nothing ran, so this proves nothing about access.`);
137397
- }
137398
- const rows = json?.data;
137399
- const empty = status === 200 && (operation === "get" && rows === null || (operation === "list" || operation === "relation_list") && Array.isArray(rows) && rows.length === 0);
137400
- const missing = kind === "missing-or-refused";
137401
- if (status === 200 && !empty) {
137402
- if (reading)
137403
- throw new Error(`expectRefused: ${said}: this person read ${Array.isArray(rows) ? `${rows.length} row(s)` : "the row"}.`);
137404
- throw new Error(`expectRefused: ${said}: the ${operation} was allowed.`);
137405
- }
137406
- if (kind !== "refused" && !empty && !missing)
137407
- throw new Error(`expectRefused: ${said}: not a refusal.`);
137408
- if ((empty || missing) && !allowed)
137409
- throw new Error(`expectRefused: ${said}: ${empty ? "an empty answer" : "a 404"} ${INCONCLUSIVE}`);
137410
- if (!allowed)
137411
- return;
137412
- if (reading) {
137413
- const control = await data(allowed, target, request2);
137414
- const c = await bodyOf(control);
137415
- const got = c.json?.data;
137416
- const found = control.status() === 200 && (operation === "get" ? got !== null && got !== void 0 : Array.isArray(got) && got.length > 0);
137417
- if (!found)
137418
- throw new Error(`expectRefused: ${said}, but the allowed person got ${control.status() === 200 ? "nothing" : seen(control.status(), c.code, c.message)} for the same request, so there was nothing to refuse.`);
137419
- } else if (writing) {
137420
- const after = await rowOf(allowed);
137421
- if (JSON.stringify(after) !== before)
137422
- throw new Error(`expectRefused: ${said}, but ${target} ${String(id)} ${after === null ? "is gone" : "changed"} for the allowed person afterwards.`);
137423
- }
137596
+ }), "adapt");
137597
+ await assertRefused(adapt(clientOf2(person)), target, request2, options2.allowed === void 0 ? void 0 : adapt(clientOf2(options2.allowed)));
137424
137598
  }
137425
137599
  async function refreshTestContext(client, origin) {
137426
137600
  const ongoing = contextRefreshes.get(client);
@@ -137479,13 +137653,13 @@ async function data(client, table2, request2) {
137479
137653
  data: { ...request2, table: table2, contract: contractDigest ?? "" }
137480
137654
  });
137481
137655
  }
137482
- var loaded, digests, eager, test, expect, ENDPOINT, INCONCLUSIVE, contextRefreshes, contextTargets, constrained, FormRun;
137656
+ var loaded, digests, eager, test, expect, contextRefreshes, contextTargets, constrained, FormRun;
137483
137657
  var init_playwright_fixtures = __esm({
137484
137658
  "dist/lib/playwright-fixtures.js"() {
137485
137659
  "use strict";
137486
137660
  init_test_target();
137487
137661
  init_client();
137488
- init_app_test();
137662
+ init_test_refusal();
137489
137663
  init_config();
137490
137664
  init_test_identities();
137491
137665
  init_test_diagnostics();
@@ -137527,10 +137701,6 @@ var init_playwright_fixtures = __esm({
137527
137701
  });
137528
137702
  __name(expectRefused, "expectRefused");
137529
137703
  __name(clientOf2, "clientOf");
137530
- ENDPOINT = /^(GET|POST|PUT|PATCH|DELETE) (\/\S*)$/;
137531
- __name(bodyOf, "bodyOf");
137532
- INCONCLUSIVE = "looks the same as an empty table, a missing row or a missing route, so it proves nothing on its own. Pass { allowed: <someone the same request succeeds for> } as the positive control.";
137533
- __name(seen, "seen");
137534
137704
  __name(refusedAs, "refusedAs");
137535
137705
  contextRefreshes = /* @__PURE__ */ new WeakMap();
137536
137706
  __name(refreshTestContext, "refreshTestContext");