@somewhere-cloud/cli 0.38.160 → 0.38.162

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.38.162
4
+
5
+ - `somewhere typecheck` runs the same project TypeScript check as deploy, then checks deployable files and service calls in `sw.endpoint` handlers.
6
+ - New projects use SDK 0.14.5 or later within the same minor version, depending on the template.
7
+
8
+ ## 0.38.161
9
+
10
+ - Syncs local runtime declarations with platform consumer contract 43. The declarations document the stop reasons for model refusals in `sw.ai.chat` and `sw.agent.run`.
11
+
3
12
  ## 0.38.160
4
13
 
5
14
  - Find complete examples with `somewhere docs example`. Search returns an outline and the best matching section in full. Add `--include-api` to include API reference topics.
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+
3
+ const { existsSync } = require('node:fs');
4
+ const { delimiter, join, resolve } = require('node:path');
5
+ const { checkerContract } = require('../runtime/declared-data.cjs');
6
+
7
+ const configPath = process.argv[2];
8
+ const projectRoot = process.cwd();
9
+ const own = join(projectRoot, 'node_modules', 'typescript');
10
+ const compiler = [own, ...(process.env.PATH ?? '').split(delimiter).map(bin => resolve(bin, '..', 'typescript'))]
11
+ .find(dir => existsSync(join(dir, 'package.json')) && require(join(dir, 'package.json')).version === checkerContract.TYPESCRIPT_VERSION);
12
+ if (!compiler) throw new Error(`TypeScript ${checkerContract.TYPESCRIPT_VERSION} was not found.`);
13
+ const ts = require(compiler);
14
+ const config = ts.readConfigFile(configPath, ts.sys.readFile);
15
+ const parsed = config.error ? null : ts.parseJsonConfigFileContent(config.config, ts.sys, projectRoot);
16
+ const errors = config.error ? [config.error] : parsed.errors;
17
+ if (parsed && !errors.length) {
18
+ const { options, fileNames } = parsed;
19
+ const functionFiles = new Set(config.config.somewhereFunctionFiles.map(file => resolve(projectRoot, file)));
20
+ const host = ts.createCompilerHost(options);
21
+ const read = host.getSourceFile.bind(host);
22
+ host.getSourceFile = (file, ...args) => {
23
+ const source = read(file, ...args);
24
+ return functionFiles.has(resolve(file)) ? checkerContract.withEndpointBinding(ts, source, options) : source;
25
+ };
26
+ errors.push(...ts.getPreEmitDiagnostics(ts.createProgram(fileNames, options, host)));
27
+ }
28
+ if (errors.length) {
29
+ process.stdout.write(ts.formatDiagnostics(errors, {
30
+ getCanonicalFileName: (file) => file,
31
+ getCurrentDirectory: () => projectRoot,
32
+ getNewLine: () => '\n',
33
+ }));
34
+ process.exitCode = 1;
35
+ }
@@ -44427,7 +44427,7 @@ var init_init_green_template = __esm({
44427
44427
  "typecheck": "npx -y @somewhere-cloud/cli typecheck"
44428
44428
  },
44429
44429
  "dependencies": {
44430
- "@somewhere-cloud/sdk": "0.14.2",
44430
+ "@somewhere-cloud/sdk": "0.14.5",
44431
44431
  "react": "19.2.7",
44432
44432
  "react-dom": "19.2.7"
44433
44433
  },
@@ -48711,7 +48711,7 @@ var init_init_feature_template = __esm({
48711
48711
  "typecheck": "npx -y @somewhere-cloud/cli typecheck"
48712
48712
  },
48713
48713
  "dependencies": {
48714
- "@somewhere-cloud/sdk": "0.14.2",
48714
+ "@somewhere-cloud/sdk": "0.14.5",
48715
48715
  "react": "19.2.7",
48716
48716
  "react-dom": "19.2.7"
48717
48717
  },
@@ -52507,7 +52507,7 @@ var init_allowed_origins = __esm({
52507
52507
  // dist/commands/project.js
52508
52508
  function registerProject(program2) {
52509
52509
  const proj = program2.command("project").description("Manage projects");
52510
- proj.command("create <name>").description("Create a new project").option("--subdomain <subdomain>", "Custom subdomain").addOption(new Option("--preview").hideHelp()).option("--json", "Print the raw project response as JSON").action(async (name, opts) => {
52510
+ proj.command("create <name>").description("Create a new project").option("--subdomain <subdomain>", "Custom subdomain").option("--json", "Print the raw project response as JSON").action(async (name, opts) => {
52511
52511
  const client = new ApiClient(getToken());
52512
52512
  const spinner = opts.json ? null : ora("Creating project...").start();
52513
52513
  try {
@@ -74331,11 +74331,20 @@ __export(declared_data_exports, {
74331
74331
  FILES_DECLARATION_FILE: () => FILES_DECLARATION_FILE,
74332
74332
  GENERATED_DATA_HEADER: () => GENERATED_DATA_HEADER,
74333
74333
  declaredDataPlugin: () => declaredDataPlugin,
74334
+ localFilesContract: () => localFilesContract,
74334
74335
  prepareDeclaredData: () => prepareDeclaredData
74335
74336
  });
74336
74337
  import { existsSync as existsSync11, readFileSync as readFileSync13, rmSync as rmSync2, writeFileSync as writeFileSync9 } from "node:fs";
74337
74338
  import { createRequire as createRequire4 } from "node:module";
74338
74339
  import { join as join12, resolve as resolve5 } from "node:path";
74340
+ function localFilesContract(projectDir) {
74341
+ const path3 = join12(projectDir, "db", "schema.ts");
74342
+ const generator = require4("./runtime/declared-data.cjs");
74343
+ const digest = existsSync11(path3) && generator.filesContractFromFiles({ "db/schema.ts": readFileSync13(path3, "utf8") });
74344
+ if (!digest)
74345
+ throw new Error("Declare file collections in db/schema.ts and deploy the app before testing files.");
74346
+ return { digest, singleRequestMaxBytes: generator.SINGLE_REQUEST_MAX_BYTES };
74347
+ }
74339
74348
  function generatedContents(path3) {
74340
74349
  const previous = existsSync11(path3) ? readFileSync13(path3, "utf8") : void 0;
74341
74350
  if (previous !== void 0 && !previous.startsWith(GENERATED_DATA_HEADER)) {
@@ -74457,19 +74466,11 @@ var init_declared_data = __esm({
74457
74466
  DATA_DECLARATION_FILE = "__somewhere_data.d.ts";
74458
74467
  GENERATED_DATA_HEADER = "// Generated by Somewhere from db/schema.ts. Do not edit.\n";
74459
74468
  NO_SCHEMA_NOTE = "// No db/schema.ts yet: runtime types only (no tables, somewhere:data or somewhere:files).\n";
74460
- SW_ENDPOINT_GLOBAL = `declare const sw: {
74461
- // docs({ topic: 'sw.endpoint' }). Throw an Error with .status and .code
74462
- // for a typed error response; anything else is 500 HANDLER_ERROR.
74463
- // Roles imply a signed-in caller: with roles and auth left out, the user is typed as signed in.
74464
- endpoint<const Schema extends SomewhereEndpointBodySchema | undefined = undefined, Auth extends SomewhereEndpointAuth = 'none',
74465
- const Roles extends readonly string[] | undefined = undefined>(
74466
- config: SomewhereEndpointConfig<[Roles] extends [readonly string[]] ? ([Auth] extends ['none'] ? 'required' : Auth) : Auth, Schema>
74467
- & { auth?: Auth; roles?: Roles },
74468
- ): (req: Request, sw: SomewhereRuntimeContext) => Promise<Response>;
74469
- };
74469
+ SW_ENDPOINT_GLOBAL = `declare const sw: SomewhereEndpointGlobal;
74470
74470
  `;
74471
74471
  require4 = createRequire4(CLI_PACKAGE_ROOT);
74472
74472
  FILES_DECLARATION_FILE = require4("./runtime/declared-data.cjs").FILES_DECLARATION_FILE;
74473
+ __name(localFilesContract, "localFilesContract");
74473
74474
  __name(generatedContents, "generatedContents");
74474
74475
  __name(prepareDeclaredData, "prepareDeclaredData");
74475
74476
  __name(declaredDataPlugin, "declaredDataPlugin");
@@ -77228,16 +77229,13 @@ function announceDeployCheckFetch(projectDir) {
77228
77229
  `);
77229
77230
  }
77230
77231
  function deployCheckTsc(projectDir, platform2 = process.platform) {
77231
- try {
77232
- const manifest = join17(projectDir, "node_modules", "typescript", "package.json");
77233
- if (JSON.parse(readFileSync16(manifest, "utf8")).version === DEPLOY_CHECK_TYPESCRIPT_VERSION) {
77234
- return { command: process.execPath, args: [join17(projectDir, "node_modules", "typescript", "bin", "tsc")] };
77235
- }
77236
- } catch {
77232
+ const runner2 = join17(CLI_PACKAGE_ROOT, "bin", "deploy-check.cjs");
77233
+ if (projectTypeScriptVersion(projectDir) === DEPLOY_CHECK_TYPESCRIPT_VERSION) {
77234
+ return { command: process.execPath, args: [runner2] };
77237
77235
  }
77238
77236
  return {
77239
77237
  command: platform2 === "win32" ? "npx.cmd" : "npx",
77240
- args: ["-y", "-p", `typescript@${DEPLOY_CHECK_TYPESCRIPT_VERSION}`, "tsc"]
77238
+ args: ["-y", "-p", `typescript@${DEPLOY_CHECK_TYPESCRIPT_VERSION}`, "--", "node", runner2]
77241
77239
  };
77242
77240
  }
77243
77241
  function projectCompilerOptions(tsconfigText) {
@@ -77354,7 +77352,8 @@ async function startDeployCheck(projectDir, onFetch) {
77354
77352
  });
77355
77353
  writeFileSync11(config2, JSON.stringify({
77356
77354
  compilerOptions: contract.localCheckCompilerOptions(own2),
77357
- files: [...checked, ...declarations]
77355
+ files: [...checked, ...declarations],
77356
+ somewhereFunctionFiles: Object.keys(collected.functions)
77358
77357
  }));
77359
77358
  if (command !== process.execPath)
77360
77359
  onFetch?.();
@@ -77362,7 +77361,7 @@ async function startDeployCheck(projectDir, onFetch) {
77362
77361
  cleanup();
77363
77362
  throw error3;
77364
77363
  }
77365
- const run = await runBounded(command, [...args, "--project", config2, "--pretty", "false"], projectDir, { onAbort: cleanup });
77364
+ const run = await runBounded(command, [...args, config2], projectDir, { onAbort: cleanup });
77366
77365
  cleanup();
77367
77366
  const out = run.out;
77368
77367
  if (run.timedOut)
@@ -77856,7 +77855,7 @@ var init_lint = __esm({
77856
77855
  import { existsSync as existsSync17 } from "node:fs";
77857
77856
  import { join as join20, relative as relative9, resolve as resolve11 } from "node:path";
77858
77857
  function registerTypecheck(program2) {
77859
- program2.command("typecheck [dir]").description(`Check the deployable source with the platform's TypeScript ${DEPLOY_CHECK_TYPESCRIPT_VERSION}, generated types and checker settings. Reports file and line for deploy-check type findings and exits 1 when there are findings. Install the project dependencies first. The CLI fetches the pinned TypeScript with npx if needed. Use --project to check the full project with its own tsconfig.json and compiler.`).option("--json", "Print typecheck and platform source findings as JSON").option("--deploy", "Run the deploy reference check and return its findings").addOption(new Option("--project", "Run the full project TypeScript check using tsconfig.json").conflicts("deploy")).option("--hook <host>", `With --deploy: run as an agent after-edit hook (${AGENT_HOSTS.join(", ")}), reading the host's event on stdin. Installed by \`${cliInvocation()} hooks install\``).option("--watch", "Keep running and re-check after each save while this command is open. It is not installed into your editor or agent; start it yourself. Never deploys or touches live data").action(async (dirArg, opts) => {
77858
+ program2.command("typecheck [dir]").description("Run the same project TypeScript check as deploy, then check the files that will be uploaded. Install the project dependencies first. Use --project or --deploy to run just one check.").option("--json", "Print typecheck and platform source findings as JSON").option("--deploy", "Only run the platform reference check on deployable files").addOption(new Option("--project", "Only check the project using its tsconfig.json and compiler").conflicts("deploy")).option("--hook <host>", `With --deploy: run as an agent after-edit hook (${AGENT_HOSTS.join(", ")}), reading the host's event on stdin. Installed by \`${cliInvocation()} hooks install\``).option("--watch", "Keep running and re-check after each save while this command is open. It is not installed into your editor or agent; start it yourself. Never deploys or touches live data").action(async (dirArg, opts) => {
77860
77859
  const dir = resolve11(process.cwd(), dirArg ?? ".");
77861
77860
  for (const hint of roleMethodHints(dir))
77862
77861
  console.error(hint);
@@ -77915,32 +77914,30 @@ function registerTypecheck(program2) {
77915
77914
  process.exit(1);
77916
77915
  }
77917
77916
  const deployVia = deployCheckTsc(dir).command === process.execPath ? "project" : "npx";
77918
- const via = opts.project ? typecheckCompilerSource(dir) : deployVia;
77919
- const notInstalled = /* @__PURE__ */ __name(() => {
77917
+ const notInstalled = /* @__PURE__ */ __name((via) => {
77920
77918
  const missing = missingProjectDependencies(dir);
77921
77919
  return missing.length ? { ok: false, errors: [], via, raw: "", spawnError: missingTypecheckDependenciesMessage() } : null;
77922
77920
  }, "notInstalled");
77923
77921
  let announced = false;
77924
- const announceFetch = /* @__PURE__ */ __name(() => {
77925
- if (announced || via !== "npx")
77926
- return;
77927
- announced = true;
77928
- announceNpxTypeScriptFetch(TYPECHECK_TYPESCRIPT_VERSION);
77929
- }, "announceFetch");
77930
77922
  const check = /* @__PURE__ */ __name(async () => {
77931
- const refused = notInstalled();
77932
- if (!refused && opts.project)
77933
- announceFetch();
77934
- const spinner = opts.json || refused || opts.watch ? null : ora("Typechecking (tsc --noEmit)...").start();
77935
- const deployResult = refused || opts.project ? void 0 : await runDeployCheck(dir, announceDeployFetch);
77923
+ const checkProject = opts.project || existsSync17(join20(dir, "tsconfig.json"));
77924
+ const projectVia = checkProject ? typecheckCompilerSource(dir) : void 0;
77925
+ const refused = notInstalled(projectVia ?? deployVia);
77926
+ if (!refused && !announced && projectVia === "npx") {
77927
+ announced = true;
77928
+ announceNpxTypeScriptFetch(TYPECHECK_TYPESCRIPT_VERSION);
77929
+ }
77930
+ const spinner = opts.json || refused || opts.watch ? null : ora(checkProject ? "Checking project types..." : "Checking deployable files...").start();
77931
+ const projectResult = !refused && checkProject ? await runTypecheck(dir) : void 0;
77932
+ const deployResult = !refused && !opts.project && (projectResult?.ok ?? true) ? await runDeployCheck(dir, announceDeployFetch) : void 0;
77936
77933
  const result2 = deployResult ? {
77937
77934
  ok: deployResult.ok,
77938
77935
  errors: deployResult.findings,
77939
- via,
77936
+ via: deployVia,
77940
77937
  raw: deployResult.error ?? "",
77941
77938
  spawnError: deployResult.error,
77942
77939
  typescript: deployResult.typescript
77943
- } : refused ?? await runTypecheck(dir);
77940
+ } : refused ?? projectResult;
77944
77941
  spinner?.stop();
77945
77942
  const sourceLint = await lintProject(dir).catch((failure2) => ({
77946
77943
  ok: false,
@@ -78942,7 +78939,9 @@ function messagesAfter(messages, address, since) {
78942
78939
  subject: String(m2.subject ?? ""),
78943
78940
  verification_code: typeof m2.verification_code === "string" && m2.verification_code ? m2.verification_code : null,
78944
78941
  magic_link: typeof m2.magic_link === "string" && m2.magic_link ? m2.magic_link : null,
78945
- created_at: String(m2.created_at ?? "")
78942
+ created_at: String(m2.created_at ?? ""),
78943
+ text: typeof m2.text === "string" ? m2.text : null,
78944
+ html: typeof m2.html === "string" ? m2.html : null
78946
78945
  })).filter((m2) => m2.to.toLowerCase() === want && Date.parse(m2.created_at) > since).sort((a, b2) => Date.parse(b2.created_at) - Date.parse(a.created_at));
78947
78946
  }
78948
78947
  function parseSince(value) {
@@ -79562,14 +79561,14 @@ var init_test_diagnostics = __esm({
79562
79561
 
79563
79562
  // dist/lib/test-control.js
79564
79563
  import { join as join28 } from "node:path";
79565
- function productionControl(client, target) {
79564
+ function productionControl(client, target, options2 = {}) {
79566
79565
  const projectId = target.projectId;
79567
79566
  return {
79568
79567
  environment: "production",
79569
79568
  projectId,
79570
79569
  target,
79571
79570
  async inbox(address, wait) {
79572
- const body = await client.call("GET", "/email/test-inbox", void 0, { project_id: projectId, address, limit: 20, ...wait ? { wait_ms: wait.ms ?? 1e4, since: wait.since } : {} });
79571
+ const body = await client.call("GET", "/email/test-inbox", void 0, { project_id: projectId, address, limit: 20, ...options2.liveInboxOnly ? { environment: "production" } : {}, ...wait ? { wait_ms: wait.ms ?? 1e4, since: wait.since } : {} });
79573
79572
  return messagesAfter(body.messages, address, 0);
79574
79573
  },
79575
79574
  deleteSignups: /* @__PURE__ */ __name((ids) => deleteAccounts(client, projectId, ids), "deleteSignups"),
@@ -84807,7 +84806,7 @@ Existing app: \`${cliInvocation()} pull <app>\` downloads the live source and li
84807
84806
  if (!opts.allowTypeErrors) {
84808
84807
  stopPrestart();
84809
84808
  spinner?.stop();
84810
- error(`Deploy stopped before upload. To proceed anyway: ${cliInvocation()} deploy --allow-type-errors`);
84809
+ error(`Deploy stopped before upload. Calls to missing platform methods or with invalid options will fail at runtime. To upload anyway, run ${cliInvocation()} deploy --allow-type-errors.`);
84811
84810
  process.exitCode = 1;
84812
84811
  return;
84813
84812
  }
@@ -88077,7 +88076,7 @@ async function fetchDocsSearch(query, topic, includeApi) {
88077
88076
  results: results.map(({ content, ...match }) => ({
88078
88077
  ...match,
88079
88078
  snippet: content,
88080
- open: match.section ? `${cliInvocation()} docs ${commandArg(match.topic)} --section ${commandArg(match.section)}` : `${cliInvocation()} docs ${commandArg(match.topic)} --full`
88079
+ open: match.example ? `${cliInvocation()} docs example ${commandArg(match.example)}` : match.section ? `${cliInvocation()} docs ${commandArg(match.topic)} --section ${commandArg(match.section)}` : `${cliInvocation()} docs ${commandArg(match.topic)} --full`
88081
88080
  })),
88082
88081
  total,
88083
88082
  version: docsVersion(version2)
@@ -88261,7 +88260,7 @@ Examples:
88261
88260
  }
88262
88261
  for (const result of results) {
88263
88262
  console.log(`${result.topic}${result.section ? ` \u203A ${result.section}` : ""} ${dim(result.heading ?? result.title)}`);
88264
- console.log(dim(result.open));
88263
+ console.log(dim(result.example ? `Full example: ${result.open}` : result.open));
88265
88264
  }
88266
88265
  if (results[0].snippet)
88267
88266
  console.log(`
@@ -135498,13 +135497,75 @@ var init_test_refusal = __esm({
135498
135497
  init_test_diagnostics();
135499
135498
  ENDPOINT = /^(GET|POST|PUT|PATCH|DELETE) (\/\S*)$/;
135500
135499
  __name(bodyOf, "bodyOf");
135501
- 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.";
135500
+ INCONCLUSIVE = "looks the same as an empty table, a missing row or a missing route, so it proves nothing on its own. Pass { allowed: owner } with a test user that can make the same request.";
135502
135501
  __name(seen, "seen");
135503
135502
  __name(assertRefused, "assertRefused");
135504
135503
  }
135505
135504
  });
135506
135505
 
135506
+ // dist/lib/test-files.js
135507
+ function transfer(url3, init) {
135508
+ if (new URL(url3).protocol !== "https:")
135509
+ throw new Error("Expected an HTTPS file transfer URL.");
135510
+ return fetch(url3, { ...init, credentials: "omit", redirect: "error" });
135511
+ }
135512
+ async function transferTestFile(link, file, type, singleRequestMaxBytes) {
135513
+ if (file.size <= singleRequestMaxBytes) {
135514
+ return transfer(link.url, { method: "PUT", headers: { "Content-Type": type }, body: file });
135515
+ }
135516
+ const start = await transfer(link.multipart_url, {
135517
+ method: "POST",
135518
+ headers: { "Content-Type": "application/json" },
135519
+ body: JSON.stringify({ size_bytes: file.size, content_type: type })
135520
+ });
135521
+ if (!start.ok)
135522
+ return start;
135523
+ const { data: data2 } = await start.json();
135524
+ const abort = /* @__PURE__ */ __name(async () => {
135525
+ await transfer(data2.abort_url, { method: "DELETE" }).catch(() => {
135526
+ });
135527
+ }, "abort");
135528
+ try {
135529
+ for (let n = 1; n <= data2.part_count; n++) {
135530
+ const from = (n - 1) * data2.part_size;
135531
+ const part = await transfer(data2.parts_url + "/" + n, {
135532
+ method: "PUT",
135533
+ body: file.slice(from, from + data2.part_size)
135534
+ });
135535
+ if (!part.ok) {
135536
+ await abort();
135537
+ return part;
135538
+ }
135539
+ await part.body?.cancel();
135540
+ }
135541
+ return await transfer(data2.complete_url, { method: "POST" });
135542
+ } catch (error3) {
135543
+ await abort();
135544
+ throw error3;
135545
+ }
135546
+ }
135547
+ var init_test_files = __esm({
135548
+ "dist/lib/test-files.js"() {
135549
+ "use strict";
135550
+ __name(transfer, "transfer");
135551
+ __name(transferTestFile, "transferTestFile");
135552
+ }
135553
+ });
135554
+
135507
135555
  // dist/lib/test-session.js
135556
+ function managedFileSession(session, root, userId) {
135557
+ managedFiles.set(session, { root, userId });
135558
+ }
135559
+ function sessionSubject(token) {
135560
+ const payload = token?.split(".")[1];
135561
+ if (!payload)
135562
+ return void 0;
135563
+ try {
135564
+ return JSON.parse(Buffer.from(payload, "base64url").toString()).sub;
135565
+ } catch {
135566
+ return void 0;
135567
+ }
135568
+ }
135508
135569
  async function expectStatus(response, expected) {
135509
135570
  if (response.status !== expected)
135510
135571
  throw new Error("Expected HTTP " + expected + ", received " + response.status);
@@ -135536,16 +135597,21 @@ async function createUser(baseUrl) {
135536
135597
  throw new Error("Signup did not establish a cookie session");
135537
135598
  return session;
135538
135599
  }
135539
- var UserSession;
135600
+ var managedFiles, UserSession;
135540
135601
  var init_test_session = __esm({
135541
135602
  "dist/lib/test-session.js"() {
135542
135603
  "use strict";
135543
135604
  init_test_refusal();
135605
+ init_declared_data();
135606
+ init_test_files();
135544
135607
  init_client();
135545
135608
  init_config();
135546
135609
  init_test_target();
135547
135610
  init_test_identities();
135548
- UserSession = class {
135611
+ managedFiles = /* @__PURE__ */ new WeakMap();
135612
+ __name(managedFileSession, "managedFileSession");
135613
+ __name(sessionSubject, "sessionSubject");
135614
+ UserSession = class _UserSession {
135549
135615
  static {
135550
135616
  __name(this, "UserSession");
135551
135617
  }
@@ -135650,8 +135716,10 @@ var init_test_session = __esm({
135650
135716
  return this.request(path3, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
135651
135717
  }
135652
135718
  async expectRefused(target, request2, { allowed } = {}) {
135653
- if (allowed && allowed.origin !== this.origin)
135654
- throw new Error("Choose a control session from the same app.");
135719
+ const control = allowed instanceof _UserSession ? allowed : allowed?.session;
135720
+ if (allowed !== void 0 && (!(control instanceof _UserSession) || control.origin !== this.origin)) {
135721
+ throw new Error("Pass { allowed: owner } or { allowed: owner.session } from the same app.");
135722
+ }
135655
135723
  const adapt = /* @__PURE__ */ __name((session) => ({
135656
135724
  endpoint(method, path3, body) {
135657
135725
  return session.request(path3, body === void 0 ? { method } : {
@@ -135662,7 +135730,51 @@ var init_test_session = __esm({
135662
135730
  },
135663
135731
  data: /* @__PURE__ */ __name((table2, request3) => session.data(table2, request3), "data")
135664
135732
  }), "adapt");
135665
- await assertRefused(adapt(this), target, request2, allowed && adapt(allowed));
135733
+ await assertRefused(adapt(this), target, request2, control && adapt(control));
135734
+ }
135735
+ /** Exercise the declared file door as a managed test user. */
135736
+ async files(collection, request2) {
135737
+ const fixture = managedFiles.get(this);
135738
+ if (!fixture)
135739
+ throw new Error("Choose a session created by openTestApp().users() or signInWithLink().");
135740
+ await this.ensureFresh();
135741
+ if (sessionSubject(this.cookies.get(ACCESS_COOKIE)) !== fixture.userId) {
135742
+ throw new Error("This session no longer belongs to its managed test user.");
135743
+ }
135744
+ const url3 = /* @__PURE__ */ __name((id) => "/__sw/files/" + encodeURIComponent(collection) + "/" + encodeURIComponent(id), "url");
135745
+ if (request2.operation === "url")
135746
+ return this.request(url3(request2.id));
135747
+ const { digest: contract2, singleRequestMaxBytes } = fixture.contract ??= localFilesContract(fixture.root);
135748
+ const post2 = /* @__PURE__ */ __name((operation, fields) => this.post("/__sw/files", { ...fields, contract: contract2, collection, operation }), "post");
135749
+ switch (request2.operation) {
135750
+ case "list":
135751
+ return post2("list", { ...request2.scope, limit: request2.limit, cursor: request2.cursor });
135752
+ case "shareLink":
135753
+ return post2("link", { id: request2.id, expires_in: request2.expiresIn });
135754
+ case "delete":
135755
+ return post2("delete", { id: request2.id });
135756
+ case "upload": {
135757
+ const { file } = request2;
135758
+ const name = request2.name || (file instanceof File ? file.name : "file");
135759
+ const type = (request2.contentType || file.type || "application/octet-stream").split(";")[0].trim().toLowerCase();
135760
+ const minted = await post2("upload", { ...request2.scope, name, size: file.size, content_type: type });
135761
+ if (!minted.ok)
135762
+ return minted;
135763
+ const { data: link } = await minted.json();
135764
+ const uploaded = await transferTestFile(link, file, type, singleRequestMaxBytes);
135765
+ if (!uploaded.ok)
135766
+ return uploaded;
135767
+ const { data: data2 } = await uploaded.json();
135768
+ return Response.json({ ok: true, data: {
135769
+ id: link.id,
135770
+ name: link.name ?? name,
135771
+ size: data2.size_bytes,
135772
+ content_type: data2.content_type,
135773
+ version: data2.version,
135774
+ url: url3(link.id)
135775
+ } }, { status: uploaded.status });
135776
+ }
135777
+ }
135666
135778
  }
135667
135779
  async data(table2, requestOrContract, request2) {
135668
135780
  if (typeof requestOrContract === "string") {
@@ -138032,7 +138144,11 @@ async function openTestApp(options2 = {}) {
138032
138144
  const client = tool ? void 0 : new ApiClient(testingDeveloperToken());
138033
138145
  const target = tool && setup ? await readPreviewTarget(tool, projectId, setup.previewSessionId) : await loadTestTarget(client, projectId);
138034
138146
  const control = tool ? previewControl(tool, target) : void 0;
138147
+ const inbox2 = control ?? productionControl(client, target, { liveInboxOnly: true });
138035
138148
  const origin = target.origin;
138149
+ const hostLabel = new URL(origin).hostname.split(".")[0];
138150
+ const subdomain = control ? hostLabel.replace(/-dev$/, "") : hostLabel;
138151
+ const inboxDomain = `${subdomain}.test.somewhere.site`;
138036
138152
  const emptyState = { cookies: [], origins: [] };
138037
138153
  const cookie = await control?.previewCookie?.();
138038
138154
  if (cookie) {
@@ -138049,6 +138165,10 @@ async function openTestApp(options2 = {}) {
138049
138165
  }
138050
138166
  const ids = /* @__PURE__ */ new Set();
138051
138167
  const actors = /* @__PURE__ */ new Set();
138168
+ const managedRecipients = /* @__PURE__ */ new Map();
138169
+ const freshRecipients = /* @__PURE__ */ new Map();
138170
+ const invitees = /* @__PURE__ */ new Set();
138171
+ const signInLinks = /* @__PURE__ */ new Map();
138052
138172
  const cleanupSteps = [];
138053
138173
  let closed = false;
138054
138174
  const open4 = /* @__PURE__ */ __name(() => {
@@ -138058,6 +138178,7 @@ async function openTestApp(options2 = {}) {
138058
138178
  const add = /* @__PURE__ */ __name((id, email2, session) => {
138059
138179
  const actor = { id, email: email2, session };
138060
138180
  actors.add(actor);
138181
+ managedFileSession(session, root, id);
138061
138182
  return actor;
138062
138183
  }, "add");
138063
138184
  const onCleanup = /* @__PURE__ */ __name((label, action) => {
@@ -138110,6 +138231,7 @@ async function openTestApp(options2 = {}) {
138110
138231
  open4();
138111
138232
  if (!Number.isInteger(count2) || count2 < 1 || count2 > 25)
138112
138233
  throw new Error("Choose 1 to 25 test users.");
138234
+ const since = Date.now();
138113
138235
  if (control) {
138114
138236
  const out2 = [];
138115
138237
  for (let i = 0; i < count2; i++) {
@@ -138119,6 +138241,7 @@ async function openTestApp(options2 = {}) {
138119
138241
  const login = await session.post("/api/auth/login", { email: user.email, password: user.password });
138120
138242
  if (!login.ok)
138121
138243
  throw new Error(`Could not sign in preview test user ${user.id} (HTTP ${login.status}).`);
138244
+ managedRecipients.set(user.email.toLowerCase(), { id: user.id, since });
138122
138245
  out2.push(add(user.id, user.email, session));
138123
138246
  }
138124
138247
  return out2;
@@ -138131,6 +138254,7 @@ async function openTestApp(options2 = {}) {
138131
138254
  ids.add(identity.user.id);
138132
138255
  for (const identity of issued) {
138133
138256
  const state = buildStorageState(origin, new URL(origin).hostname, identity, expiryOf(identity, receivedAt));
138257
+ managedRecipients.set(identity.user.email.toLowerCase(), { id: identity.user.id, since });
138134
138258
  out.push(add(identity.user.id, identity.user.email, new UserSession(origin, { target, storageState: state })));
138135
138259
  }
138136
138260
  }
@@ -138144,6 +138268,59 @@ async function openTestApp(options2 = {}) {
138144
138268
  throw error3;
138145
138269
  }
138146
138270
  },
138271
+ inboxAddress(name = "invite") {
138272
+ open4();
138273
+ const email2 = freshTestAddress(subdomain, name);
138274
+ freshRecipients.set(email2, Date.now());
138275
+ return email2;
138276
+ },
138277
+ async testInbox(email2) {
138278
+ open4();
138279
+ const address = email2.trim().toLowerCase();
138280
+ const [local, domain, extra] = address.split("@");
138281
+ if (!local || /\s/.test(local) || domain !== inboxDomain || extra !== void 0) {
138282
+ throw new Error(`Use an address at ${inboxDomain} for this app\u2019s test inbox.`);
138283
+ }
138284
+ const since = managedRecipients.get(address)?.since ?? freshRecipients.get(address) ?? 0;
138285
+ const messages = await inbox2.inbox(address, { since, ms: 3e3 });
138286
+ open4();
138287
+ return messages.filter((message3) => Date.parse(message3.created_at) > since).map((message3) => {
138288
+ const links = /* @__PURE__ */ new Set();
138289
+ if (message3.magic_link) {
138290
+ links.add(message3.magic_link);
138291
+ const url3 = URL.parse(message3.magic_link);
138292
+ if (url3?.origin === origin && url3.pathname === "/auth/magic" && url3.searchParams.get("token")) {
138293
+ signInLinks.set(message3.magic_link, address);
138294
+ }
138295
+ }
138296
+ for (const match of [message3.text, message3.html].join(" ").matchAll(/https?:\/\/[^\s<>"']+/gi)) {
138297
+ links.add(match[0].replaceAll("&amp;", "&").replace(/[.,]+$/, ""));
138298
+ }
138299
+ return { ...message3, links: [...links] };
138300
+ });
138301
+ },
138302
+ async signInWithLink(url3) {
138303
+ open4();
138304
+ const address = signInLinks.get(url3);
138305
+ if (!address)
138306
+ throw new Error("Use a sign-in link from this test app\u2019s inbox.");
138307
+ signInLinks.delete(url3);
138308
+ const token = new URL(url3).searchParams.get("token");
138309
+ const session = new UserSession(origin, { target, storageState: emptyState });
138310
+ const response = await session.post("/api/auth/magic-link/verify", { token });
138311
+ open4();
138312
+ if (!response.ok)
138313
+ throw new Error(`Could not sign in with the link (HTTP ${response.status}).`);
138314
+ const body = await response.json();
138315
+ const id = body.user?.id;
138316
+ const managed = managedRecipients.get(address);
138317
+ if (!body.cookie_session || typeof id !== "string" || !id || body.user?.email?.toLowerCase() !== address || managed && managed.id !== id) {
138318
+ throw new Error("The link did not sign in the expected test user.");
138319
+ }
138320
+ if (freshRecipients.has(address))
138321
+ invitees.add(id);
138322
+ return add(id, address, session);
138323
+ },
138147
138324
  create,
138148
138325
  async plantMarker(user, table2, field2, values = {}) {
138149
138326
  const marker = privateMarker();
@@ -138159,6 +138336,7 @@ async function openTestApp(options2 = {}) {
138159
138336
  if (closed)
138160
138337
  return;
138161
138338
  closed = true;
138339
+ signInLinks.clear();
138162
138340
  const remains = [];
138163
138341
  for (const { label, action } of cleanupSteps.reverse()) {
138164
138342
  try {
@@ -138167,10 +138345,17 @@ async function openTestApp(options2 = {}) {
138167
138345
  remains.push(label);
138168
138346
  }
138169
138347
  }
138348
+ if (invitees.size) {
138349
+ const result = await inbox2.deleteSignups([...invitees]);
138350
+ for (const [id, why] of result.kept)
138351
+ remains.push(`invited test user ${id} (${why})`);
138352
+ }
138170
138353
  if (control) {
138171
- for (const id of ids)
138172
- if (await control.deleteManagedUser(id))
138173
- remains.push(`test user ${id}`);
138354
+ for (const id of ids) {
138355
+ const reason = await control.deleteManagedUser(id);
138356
+ if (reason)
138357
+ remains.push(`test user ${id} (${reason})`);
138358
+ }
138174
138359
  await control.close();
138175
138360
  } else if (ids.size) {
138176
138361
  try {
@@ -138179,8 +138364,8 @@ async function openTestApp(options2 = {}) {
138179
138364
  for (const user of identities)
138180
138365
  if (ids.has(user.id))
138181
138366
  remains.push(`test user ${user.id}`);
138182
- } catch {
138183
- remains.push(...[...ids].map((id) => `test user ${id}`));
138367
+ } catch (error3) {
138368
+ remains.push(`test users ${[...ids].join(", ")} (${describeCallError(error3)})`);
138184
138369
  }
138185
138370
  }
138186
138371
  if (remains.length)
@@ -138192,6 +138377,7 @@ var init_testing_app = __esm({
138192
138377
  "dist/lib/testing-app.js"() {
138193
138378
  "use strict";
138194
138379
  init_client();
138380
+ init_form_accounts();
138195
138381
  init_config();
138196
138382
  init_preview_credential();
138197
138383
  init_test_control();