@somewhere-cloud/cli 0.38.161 → 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,10 @@
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
+
3
8
  ## 0.38.161
4
9
 
5
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`.
@@ -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
  },
@@ -74466,16 +74466,7 @@ var init_declared_data = __esm({
74466
74466
  DATA_DECLARATION_FILE = "__somewhere_data.d.ts";
74467
74467
  GENERATED_DATA_HEADER = "// Generated by Somewhere from db/schema.ts. Do not edit.\n";
74468
74468
  NO_SCHEMA_NOTE = "// No db/schema.ts yet: runtime types only (no tables, somewhere:data or somewhere:files).\n";
74469
- SW_ENDPOINT_GLOBAL = `declare const sw: {
74470
- // docs({ topic: 'sw.endpoint' }). Throw an Error with .status and .code
74471
- // for a typed error response; anything else is 500 HANDLER_ERROR.
74472
- // Roles imply a signed-in caller: with roles and auth left out, the user is typed as signed in.
74473
- endpoint<const Schema extends SomewhereEndpointBodySchema | undefined = undefined, Auth extends SomewhereEndpointAuth = 'none',
74474
- const Roles extends readonly string[] | undefined = undefined>(
74475
- config: SomewhereEndpointConfig<[Roles] extends [readonly string[]] ? ([Auth] extends ['none'] ? 'required' : Auth) : Auth, Schema>
74476
- & { auth?: Auth; roles?: Roles },
74477
- ): (req: Request, sw: SomewhereRuntimeContext) => Promise<Response>;
74478
- };
74469
+ SW_ENDPOINT_GLOBAL = `declare const sw: SomewhereEndpointGlobal;
74479
74470
  `;
74480
74471
  require4 = createRequire4(CLI_PACKAGE_ROOT);
74481
74472
  FILES_DECLARATION_FILE = require4("./runtime/declared-data.cjs").FILES_DECLARATION_FILE;
@@ -77238,16 +77229,13 @@ function announceDeployCheckFetch(projectDir) {
77238
77229
  `);
77239
77230
  }
77240
77231
  function deployCheckTsc(projectDir, platform2 = process.platform) {
77241
- try {
77242
- const manifest = join17(projectDir, "node_modules", "typescript", "package.json");
77243
- if (JSON.parse(readFileSync16(manifest, "utf8")).version === DEPLOY_CHECK_TYPESCRIPT_VERSION) {
77244
- return { command: process.execPath, args: [join17(projectDir, "node_modules", "typescript", "bin", "tsc")] };
77245
- }
77246
- } 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] };
77247
77235
  }
77248
77236
  return {
77249
77237
  command: platform2 === "win32" ? "npx.cmd" : "npx",
77250
- args: ["-y", "-p", `typescript@${DEPLOY_CHECK_TYPESCRIPT_VERSION}`, "tsc"]
77238
+ args: ["-y", "-p", `typescript@${DEPLOY_CHECK_TYPESCRIPT_VERSION}`, "--", "node", runner2]
77251
77239
  };
77252
77240
  }
77253
77241
  function projectCompilerOptions(tsconfigText) {
@@ -77364,7 +77352,8 @@ async function startDeployCheck(projectDir, onFetch) {
77364
77352
  });
77365
77353
  writeFileSync11(config2, JSON.stringify({
77366
77354
  compilerOptions: contract.localCheckCompilerOptions(own2),
77367
- files: [...checked, ...declarations]
77355
+ files: [...checked, ...declarations],
77356
+ somewhereFunctionFiles: Object.keys(collected.functions)
77368
77357
  }));
77369
77358
  if (command !== process.execPath)
77370
77359
  onFetch?.();
@@ -77372,7 +77361,7 @@ async function startDeployCheck(projectDir, onFetch) {
77372
77361
  cleanup();
77373
77362
  throw error3;
77374
77363
  }
77375
- const run = await runBounded(command, [...args, "--project", config2, "--pretty", "false"], projectDir, { onAbort: cleanup });
77364
+ const run = await runBounded(command, [...args, config2], projectDir, { onAbort: cleanup });
77376
77365
  cleanup();
77377
77366
  const out = run.out;
77378
77367
  if (run.timedOut)
@@ -77866,7 +77855,7 @@ var init_lint = __esm({
77866
77855
  import { existsSync as existsSync17 } from "node:fs";
77867
77856
  import { join as join20, relative as relative9, resolve as resolve11 } from "node:path";
77868
77857
  function registerTypecheck(program2) {
77869
- 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) => {
77870
77859
  const dir = resolve11(process.cwd(), dirArg ?? ".");
77871
77860
  for (const hint of roleMethodHints(dir))
77872
77861
  console.error(hint);
@@ -77925,32 +77914,30 @@ function registerTypecheck(program2) {
77925
77914
  process.exit(1);
77926
77915
  }
77927
77916
  const deployVia = deployCheckTsc(dir).command === process.execPath ? "project" : "npx";
77928
- const via = opts.project ? typecheckCompilerSource(dir) : deployVia;
77929
- const notInstalled = /* @__PURE__ */ __name(() => {
77917
+ const notInstalled = /* @__PURE__ */ __name((via) => {
77930
77918
  const missing = missingProjectDependencies(dir);
77931
77919
  return missing.length ? { ok: false, errors: [], via, raw: "", spawnError: missingTypecheckDependenciesMessage() } : null;
77932
77920
  }, "notInstalled");
77933
77921
  let announced = false;
77934
- const announceFetch = /* @__PURE__ */ __name(() => {
77935
- if (announced || via !== "npx")
77936
- return;
77937
- announced = true;
77938
- announceNpxTypeScriptFetch(TYPECHECK_TYPESCRIPT_VERSION);
77939
- }, "announceFetch");
77940
77922
  const check = /* @__PURE__ */ __name(async () => {
77941
- const refused = notInstalled();
77942
- if (!refused && opts.project)
77943
- announceFetch();
77944
- const spinner = opts.json || refused || opts.watch ? null : ora("Typechecking (tsc --noEmit)...").start();
77945
- 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;
77946
77933
  const result2 = deployResult ? {
77947
77934
  ok: deployResult.ok,
77948
77935
  errors: deployResult.findings,
77949
- via,
77936
+ via: deployVia,
77950
77937
  raw: deployResult.error ?? "",
77951
77938
  spawnError: deployResult.error,
77952
77939
  typescript: deployResult.typescript
77953
- } : refused ?? await runTypecheck(dir);
77940
+ } : refused ?? projectResult;
77954
77941
  spinner?.stop();
77955
77942
  const sourceLint = await lintProject(dir).catch((failure2) => ({
77956
77943
  ok: false,
@@ -84819,7 +84806,7 @@ Existing app: \`${cliInvocation()} pull <app>\` downloads the live source and li
84819
84806
  if (!opts.allowTypeErrors) {
84820
84807
  stopPrestart();
84821
84808
  spinner?.stop();
84822
- 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.`);
84823
84810
  process.exitCode = 1;
84824
84811
  return;
84825
84812
  }
@@ -135510,7 +135497,7 @@ var init_test_refusal = __esm({
135510
135497
  init_test_diagnostics();
135511
135498
  ENDPOINT = /^(GET|POST|PUT|PATCH|DELETE) (\/\S*)$/;
135512
135499
  __name(bodyOf, "bodyOf");
135513
- 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.";
135514
135501
  __name(seen, "seen");
135515
135502
  __name(assertRefused, "assertRefused");
135516
135503
  }
@@ -135624,7 +135611,7 @@ var init_test_session = __esm({
135624
135611
  managedFiles = /* @__PURE__ */ new WeakMap();
135625
135612
  __name(managedFileSession, "managedFileSession");
135626
135613
  __name(sessionSubject, "sessionSubject");
135627
- UserSession = class {
135614
+ UserSession = class _UserSession {
135628
135615
  static {
135629
135616
  __name(this, "UserSession");
135630
135617
  }
@@ -135729,8 +135716,10 @@ var init_test_session = __esm({
135729
135716
  return this.request(path3, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
135730
135717
  }
135731
135718
  async expectRefused(target, request2, { allowed } = {}) {
135732
- if (allowed && allowed.origin !== this.origin)
135733
- 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
+ }
135734
135723
  const adapt = /* @__PURE__ */ __name((session) => ({
135735
135724
  endpoint(method, path3, body) {
135736
135725
  return session.request(path3, body === void 0 ? { method } : {
@@ -135741,7 +135730,7 @@ var init_test_session = __esm({
135741
135730
  },
135742
135731
  data: /* @__PURE__ */ __name((table2, request3) => session.data(table2, request3), "data")
135743
135732
  }), "adapt");
135744
- await assertRefused(adapt(this), target, request2, allowed && adapt(allowed));
135733
+ await assertRefused(adapt(this), target, request2, control && adapt(control));
135745
135734
  }
135746
135735
  /** Exercise the declared file door as a managed test user. */
135747
135736
  async files(collection, request2) {
@@ -138157,6 +138146,9 @@ async function openTestApp(options2 = {}) {
138157
138146
  const control = tool ? previewControl(tool, target) : void 0;
138158
138147
  const inbox2 = control ?? productionControl(client, target, { liveInboxOnly: true });
138159
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`;
138160
138152
  const emptyState = { cookies: [], origins: [] };
138161
138153
  const cookie = await control?.previewCookie?.();
138162
138154
  if (cookie) {
@@ -138173,7 +138165,9 @@ async function openTestApp(options2 = {}) {
138173
138165
  }
138174
138166
  const ids = /* @__PURE__ */ new Set();
138175
138167
  const actors = /* @__PURE__ */ new Set();
138176
- const recipients = /* @__PURE__ */ new Map();
138168
+ const managedRecipients = /* @__PURE__ */ new Map();
138169
+ const freshRecipients = /* @__PURE__ */ new Map();
138170
+ const invitees = /* @__PURE__ */ new Set();
138177
138171
  const signInLinks = /* @__PURE__ */ new Map();
138178
138172
  const cleanupSteps = [];
138179
138173
  let closed = false;
@@ -138247,7 +138241,7 @@ async function openTestApp(options2 = {}) {
138247
138241
  const login = await session.post("/api/auth/login", { email: user.email, password: user.password });
138248
138242
  if (!login.ok)
138249
138243
  throw new Error(`Could not sign in preview test user ${user.id} (HTTP ${login.status}).`);
138250
- recipients.set(user.email.toLowerCase(), { id: user.id, email: user.email, since });
138244
+ managedRecipients.set(user.email.toLowerCase(), { id: user.id, since });
138251
138245
  out2.push(add(user.id, user.email, session));
138252
138246
  }
138253
138247
  return out2;
@@ -138260,7 +138254,7 @@ async function openTestApp(options2 = {}) {
138260
138254
  ids.add(identity.user.id);
138261
138255
  for (const identity of issued) {
138262
138256
  const state = buildStorageState(origin, new URL(origin).hostname, identity, expiryOf(identity, receivedAt));
138263
- recipients.set(identity.user.email.toLowerCase(), { ...identity.user, since });
138257
+ managedRecipients.set(identity.user.email.toLowerCase(), { id: identity.user.id, since });
138264
138258
  out.push(add(identity.user.id, identity.user.email, new UserSession(origin, { target, storageState: state })));
138265
138259
  }
138266
138260
  }
@@ -138274,20 +138268,29 @@ async function openTestApp(options2 = {}) {
138274
138268
  throw error3;
138275
138269
  }
138276
138270
  },
138271
+ inboxAddress(name = "invite") {
138272
+ open4();
138273
+ const email2 = freshTestAddress(subdomain, name);
138274
+ freshRecipients.set(email2, Date.now());
138275
+ return email2;
138276
+ },
138277
138277
  async testInbox(email2) {
138278
138278
  open4();
138279
- const recipient = recipients.get(email2.toLowerCase());
138280
- if (!recipient)
138281
- throw new Error("Choose a test email created by this test app.");
138282
- const messages = await inbox2.inbox(recipient.email, { since: recipient.since, ms: 3e3 });
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 });
138283
138286
  open4();
138284
- return messages.filter((message3) => Date.parse(message3.created_at) > recipient.since).map((message3) => {
138287
+ return messages.filter((message3) => Date.parse(message3.created_at) > since).map((message3) => {
138285
138288
  const links = /* @__PURE__ */ new Set();
138286
138289
  if (message3.magic_link) {
138287
138290
  links.add(message3.magic_link);
138288
138291
  const url3 = URL.parse(message3.magic_link);
138289
138292
  if (url3?.origin === origin && url3.pathname === "/auth/magic" && url3.searchParams.get("token")) {
138290
- signInLinks.set(message3.magic_link, recipient);
138293
+ signInLinks.set(message3.magic_link, address);
138291
138294
  }
138292
138295
  }
138293
138296
  for (const match of [message3.text, message3.html].join(" ").matchAll(/https?:\/\/[^\s<>"']+/gi)) {
@@ -138298,8 +138301,8 @@ async function openTestApp(options2 = {}) {
138298
138301
  },
138299
138302
  async signInWithLink(url3) {
138300
138303
  open4();
138301
- const recipient = signInLinks.get(url3);
138302
- if (!recipient)
138304
+ const address = signInLinks.get(url3);
138305
+ if (!address)
138303
138306
  throw new Error("Use a sign-in link from this test app\u2019s inbox.");
138304
138307
  signInLinks.delete(url3);
138305
138308
  const token = new URL(url3).searchParams.get("token");
@@ -138309,10 +138312,14 @@ async function openTestApp(options2 = {}) {
138309
138312
  if (!response.ok)
138310
138313
  throw new Error(`Could not sign in with the link (HTTP ${response.status}).`);
138311
138314
  const body = await response.json();
138312
- if (!body.cookie_session || body.user?.id !== recipient.id || body.user.email?.toLowerCase() !== recipient.email.toLowerCase()) {
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) {
138313
138318
  throw new Error("The link did not sign in the expected test user.");
138314
138319
  }
138315
- return add(recipient.id, recipient.email, session);
138320
+ if (freshRecipients.has(address))
138321
+ invitees.add(id);
138322
+ return add(id, address, session);
138316
138323
  },
138317
138324
  create,
138318
138325
  async plantMarker(user, table2, field2, values = {}) {
@@ -138338,10 +138345,17 @@ async function openTestApp(options2 = {}) {
138338
138345
  remains.push(label);
138339
138346
  }
138340
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
+ }
138341
138353
  if (control) {
138342
- for (const id of ids)
138343
- if (await control.deleteManagedUser(id))
138344
- 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
+ }
138345
138359
  await control.close();
138346
138360
  } else if (ids.size) {
138347
138361
  try {
@@ -138350,8 +138364,8 @@ async function openTestApp(options2 = {}) {
138350
138364
  for (const user of identities)
138351
138365
  if (ids.has(user.id))
138352
138366
  remains.push(`test user ${user.id}`);
138353
- } catch {
138354
- remains.push(...[...ids].map((id) => `test user ${id}`));
138367
+ } catch (error3) {
138368
+ remains.push(`test users ${[...ids].join(", ")} (${describeCallError(error3)})`);
138355
138369
  }
138356
138370
  }
138357
138371
  if (remains.length)
@@ -138363,6 +138377,7 @@ var init_testing_app = __esm({
138363
138377
  "dist/lib/testing-app.js"() {
138364
138378
  "use strict";
138365
138379
  init_client();
138380
+ init_form_accounts();
138366
138381
  init_config();
138367
138382
  init_preview_credential();
138368
138383
  init_test_control();