@somewhere-cloud/cli 0.38.126 → 0.38.128

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.
@@ -36599,6 +36599,9 @@ var init_client = __esm({
36599
36599
  * API_KEY_EXPIRED. */
36600
36600
  async refreshAccessKey(timeoutMs) {
36601
36601
  const config2 = loadConfig();
36602
+ if (config2?.claim_access && config2.token === this.token) {
36603
+ throw new CliApiError("SESSION_EXPIRED", `This app connection expired. Run \`${cliInvocation()} login\` and ask the account owner to approve it.`, 401);
36604
+ }
36602
36605
  const refreshToken = config2?.refresh_token;
36603
36606
  if (!refreshToken) {
36604
36607
  throw new CliApiError("SESSION_EXPIRED", `Your somewhere session expired and there is no refresh token saved (old login format). Run \`${cliInvocation()} login\` to sign in again \u2014 that upgrades your config so sessions refresh automatically from now on.`, 401);
@@ -36692,7 +36695,9 @@ var init_client = __esm({
36692
36695
  if (typeof retry_after_ms === "number" && Number.isFinite(retry_after_ms)) {
36693
36696
  meta3.retryAfterMs = retry_after_ms;
36694
36697
  }
36695
- throw new CliApiError(error3 ?? "UNKNOWN", error3 === void 0 && message3 === void 0 ? unclassifiedResponseMessage(res.status, text) : message3 ?? "Unknown error", res.status, data2 ?? extraData, hint, meta3);
36698
+ const agentSignIn = `Run \`${cliInvocation()} login\` and ask the account owner to approve it.`;
36699
+ const agentMessage = error3 === "PROJECT_AGENT_OPERATION_FORBIDDEN" ? `This app connection cannot use that feature. ${agentSignIn}` : error3 === "PROJECT_AGENT_PROJECT_FORBIDDEN" ? `This app is outside this connection or no longer available. ${agentSignIn}` : void 0;
36700
+ throw new CliApiError(error3 ?? "UNKNOWN", agentMessage ?? (error3 === void 0 && message3 === void 0 ? unclassifiedResponseMessage(res.status, text) : message3 ?? "Unknown error"), res.status, data2 ?? extraData, hint, meta3);
36696
36701
  }
36697
36702
  /** Like call(), but returns the raw response TEXT instead of JSON-parsing it
36698
36703
  * — for endpoints that legitimately return non-JSON (e.g. a SQL db dump). A
@@ -38368,8 +38373,8 @@ tests/app-check.mjs: change its checks to the journeys you changed and your acce
38368
38373
  Keep each run short:
38369
38374
  - Short waits: page.setDefaultTimeout(5_000) on every page; a deployed app answers in under
38370
38375
  a second. Never sleep for a fixed time: wait for the thing itself (the text, the response).
38371
- - Stop at the first failure and print what the page showed (page.url(), the visible error
38372
- text). Checks after a failure only wait out their timeouts. app.check() does both.
38376
+ - Keep independent checks running. For a dependent check, pass { requires: { name, passed } }
38377
+ to app.check() using the earlier check's boolean result, so a skip explains what it needed.
38373
38378
  - After a fix, rerun the scripts that failed, each one whole: npx @somewhere-cloud/cli test --failed.
38374
38379
  The CLI supplies its test helpers when it runs your tests. For the first browser test, install Playwright with npm install -D --save-exact @playwright/test@1.65.0.
38375
38380
  For a local Vite server, install the frontend tools with npm install -D --save-exact vite@7.2.2.
@@ -41047,84 +41052,84 @@ var init_init_test_template = __esm({
41047
41052
  "dist/lib/init-test-template.js"() {
41048
41053
  "use strict";
41049
41054
  init_first_cli_permission();
41050
- SCRIPT = /* @__PURE__ */ __name((privateData) => `// tests/app-check.mjs \u2014 an ordinary Playwright script for this app: change the checks to match
41051
- // what you built. Run it after a successful deploy, never after a refused one:
41055
+ SCRIPT = /* @__PURE__ */ __name((privateData) => `// Change these Playwright checks to match your app. Run after a successful deploy.
41052
41056
  // ${FIRST_CLI_PERMISSION}
41053
41057
  // npx @somewhere-cloud/cli deploy && npx @somewhere-cloud/cli test
41054
- // Tests that need the email inbox work after you claim the app.
41055
- // It writes its result once to .somewhere/app-check.json; the exit code is the verdict.
41056
- // It stops at the first failed check and prints the page's URL and visible error text.
41057
- // After a fix, rerun the scripts that failed, each one whole: npx @somewhere-cloud/cli test --failed.
41058
- // From a .cjs script: const { openAppTest } = require('@somewhere-cloud/cli/script');
41058
+ // Results: .somewhere/app-check.json. Rerun failed scripts with npx @somewhere-cloud/cli test --failed.
41059
41059
  import { chromium } from '@playwright/test';
41060
41060
  import { openAppTest${privateData ? ", captureResponses, dataReady" : ""} } from '@somewhere-cloud/cli/script';
41061
-
41062
41061
  const app = await openAppTest(); // stops if this folder has changes the live release lacks
41063
41062
  const browser = await chromium.launch(app.launchOptions());
41064
- // One person = one browser context, signed up through the app's own form (accounts are
41065
- // deleted by exact id in finish()).
41066
41063
  const person = async () => {
41067
41064
  const page = await browser.newPage({ baseURL: app.origin });
41068
41065
  page.setDefaultTimeout(5_000); // a deployed app answers in well under a second; never sleep, wait for the thing itself
41069
41066
  return { page, account: await app.signUp(page) };
41070
41067
  };
41071
41068
  try {
41072
- await app.check('the sign-in page loads', async () => {
41069
+ await app.check('the sign-in page loads', async (at) => {
41073
41070
  const page = await browser.newPage({ baseURL: app.origin });
41074
41071
  try {
41075
41072
  await page.goto('/');
41073
+ at('Wait for the signed-out page', '[data-app-state="signed-out"]');
41076
41074
  await page.locator('[data-app-state="signed-out"]').waitFor({ timeout: 5_000 });
41077
- } finally {
41078
- await page.close();
41079
- }
41075
+ } finally { await page.close(); }
41080
41076
  });
41081
41077
  let ana, ben;
41082
- const signedUp = await app.check('sign up through the app', async () => {
41078
+ const needsSignup = { name: 'sign up through the app', passed: false };
41079
+ needsSignup.passed = await app.check(needsSignup.name, async () => {
41083
41080
  // Finish both attempts before cleanup, even if one fails.
41084
41081
  const people = await Promise.allSettled([person(), person()]);
41085
41082
  for (const result of people) if (result.status === 'rejected') throw result.reason;
41086
41083
  [ana, ben] = people.map(result => result.value);
41087
41084
  });
41088
- if (signedUp) {
41089
- await app.check('the signed-in page shows the account', () => ana.page.getByText(ana.account.email).waitFor());
41090
- await app.check('sign out, then sign back in', async () => {
41091
- await app.signOut(ana.page);
41092
- await app.signIn(ana.page, ana.account);
41093
- });
41094
- ${privateData ? ` await app.check('a note stays private to its owner', async () => {
41095
- const secret = 'private ' + crypto.randomUUID(); // a unique value: search for it, not a common word
41096
- await ana.page.getByLabel('Title').fill(secret);
41097
- await ana.page.getByRole('button', { name: 'Add note' }).click();
41098
- await ana.page.getByRole('heading', { name: secret }).waitFor();
41099
- const seen = captureResponses(ben.page);
41085
+ await app.check('the signed-in page shows the account', () => ana.page.getByText(ana.account.email).waitFor(), { requires: needsSignup });
41086
+ const roundTrip = 'sign out, then sign back in';
41087
+ const signedBackIn = await app.check(roundTrip, async (at) => {
41088
+ await app.signOut(ana.page);
41089
+ at('Sign back in');
41090
+ await app.signIn(ana.page, ana.account);
41091
+ }, { requires: needsSignup });
41092
+ ${privateData ? ` await app.check('a note stays private to its owner', async (at) => {
41093
+ const secret = 'private ' + crypto.randomUUID();
41094
+ at('Create the first person\u2019s note');
41095
+ await ana.page.getByLabel('Title').fill(secret);
41096
+ await ana.page.getByRole('button', { name: 'Add note' }).click();
41097
+ await ana.page.getByRole('heading', { name: secret }).waitFor();
41098
+ const seen = captureResponses(ben.page);
41099
+ try {
41100
41100
  await ben.page.reload();
41101
- await dataReady(ben.page); // the list has loaded, not merely "signed in"
41102
- const leaks = await seen.find(secret);
41103
- if (leaks.length) throw new Error('the other person received the note: ' + JSON.stringify(leaks));
41104
- const { data: [note] } = await app.data(ana.page, { table: 'notes', operation: 'list', where: { title: secret } });
41105
- await app.expectRefused(ben.page, { table: 'notes', operation: 'get', id: note.id }, { allowed: ana.page });
41106
- await app.expectRefused(ben.page, { table: 'notes', operation: 'update', id: note.id, values: { title: 'changed' } }, { allowed: ana.page });
41107
- await app.expectRefused(ben.page, { table: 'notes', operation: 'delete', id: note.id }, { allowed: ana.page });
41108
- });
41109
- ` : ` // Your own tables (db/schema.ts), called as a signed-in person: app.data adds the release's
41110
- // data contract and the Origin, and says ok, empty or refused. No need to read either from the page.
41111
- // const { data: [task] } = await app.data(ana.page, { table: 'tasks', operation: 'list' });
41112
- // await app.expectRefused(ben.page, { table: 'tasks', operation: 'get', id: task.id }, { allowed: ana.page });
41113
- `} // A list item opens its page when a person clicks the item itself. Click the item element, not a link
41114
- // inside it: a test that clicks the inner link passes even when clicking the item does nothing.
41115
- // await ana.page.getByTestId('team-item').first().click();
41116
- // await ana.page.getByTestId('team-name').waitFor(); // the item's own page, reached in the app
41117
- await app.check('at phone width nothing scrolls sideways', async () => {
41118
- await ana.page.setViewportSize({ width: 390, height: 844 });
41119
- await ana.page.reload();
41120
- await ana.page.getByText(ana.account.email).waitFor();
41121
- const wide = await ana.page.evaluate(() => [document.documentElement, ...document.querySelectorAll('body *')]
41122
- .filter((el) => el.scrollWidth > el.clientWidth + 1
41123
- && (el === document.documentElement || ['auto', 'scroll'].includes(getComputedStyle(el).overflowX)))
41124
- .map((el) => el.tagName.toLowerCase() + (typeof el.className === 'string' && el.className ? '.' + el.className.split(' ')[0] : '')));
41125
- if (wide.length) throw new Error('scrolls sideways at 390 px: ' + wide.join(', '));
41126
- });
41127
- }
41101
+ // On the data view, set data-sw-data="loading" while fetching, "ready" once loaded, or "error" if fetching fails.
41102
+ at('Wait for the second person\u2019s notes to load', '[data-sw-data]');
41103
+ if (await dataReady(ben.page) === 'error') throw new Error('The second person\u2019s notes view reported a loading error.');
41104
+ const [leak] = await seen.find(secret);
41105
+ if (leak) {
41106
+ at('Check the second person\u2019s responses for the note', leak.url);
41107
+ throw new Error('The second person received the first person\u2019s note.');
41108
+ }
41109
+ } finally { seen.stop(); }
41110
+ at('Read the note as its owner');
41111
+ const owned = await app.data(ana.page, { table: 'notes', operation: 'list', where: { title: secret } });
41112
+ const note = owned.data?.[0];
41113
+ if (!note) throw new Error('The owner\u2019s request did not return the new note (HTTP ' + owned.status + ').');
41114
+ at('Check that the second person cannot read, edit, or delete the note');
41115
+ await app.expectRefused(ben.page, { table: 'notes', operation: 'get', id: note.id }, { allowed: ana.page });
41116
+ await app.expectRefused(ben.page, { table: 'notes', operation: 'update', id: note.id, values: { title: 'changed' } }, { allowed: ana.page });
41117
+ await app.expectRefused(ben.page, { table: 'notes', operation: 'delete', id: note.id }, { allowed: ana.page });
41118
+ }, { requires: needsSignup.passed ? { name: roundTrip, passed: signedBackIn } : needsSignup });
41119
+ ` : ` // After adding tables in db/schema.ts, test access with these helpers:
41120
+ // const { data: [task] } = await app.data(ana.page, { table: 'tasks', operation: 'list' });
41121
+ // await app.expectRefused(ben.page, { table: 'tasks', operation: 'get', id: task.id }, { allowed: ana.page });
41122
+ `} await app.check('at phone width nothing scrolls sideways', async (at) => {
41123
+ await ben.page.setViewportSize({ width: 390, height: 844 });
41124
+ await ben.page.reload();
41125
+ await ben.page.getByText(ben.account.email).waitFor();
41126
+ at('Measure horizontal overflow', app.origin);
41127
+ const wide = await ben.page.evaluate(() => [document.documentElement, ...document.querySelectorAll('body *')]
41128
+ .filter((el) => el.scrollWidth > el.clientWidth + 1
41129
+ && (el === document.documentElement || ['auto', 'scroll'].includes(getComputedStyle(el).overflowX)))
41130
+ .map((el) => el.tagName.toLowerCase() + (typeof el.className === 'string' && el.className ? '.' + el.className.split(' ')[0] : '')));
41131
+ if (wide.length) throw new Error('scrolls sideways at 390 px: ' + wide.join(', '));
41132
+ }, { requires: needsSignup });
41128
41133
  } finally {
41129
41134
  await app.finish(); // confirms the release, deletes the accounts, writes the result once
41130
41135
  await browser.close();
@@ -46551,6 +46556,200 @@ var init_link = __esm({
46551
46556
  }
46552
46557
  });
46553
46558
 
46559
+ // dist/lib/claim-handoff.js
46560
+ import { createDecipheriv, createHash as createHash3, randomBytes as randomBytes2 } from "node:crypto";
46561
+ function readClaimConnection(client) {
46562
+ return client.call("GET", "/auth/temp-claim/status", void 0, void 0, { refresh: false });
46563
+ }
46564
+ function verifierHash(verifier) {
46565
+ return createHash3("sha256").update(verifier, "utf8").digest("hex");
46566
+ }
46567
+ function newVerifier() {
46568
+ return randomBytes2(32).toString("base64url");
46569
+ }
46570
+ function decodeCredentials(state, response) {
46571
+ if (!state.handoff_id || response.project_id !== state.project_id) {
46572
+ throw new Error("Claim continuation returned a different project. No credential was installed.");
46573
+ }
46574
+ const key = createHash3("sha256").update(`claim-cli-handoff:v1:${state.verifier}`, "utf8").digest();
46575
+ const combined = Buffer.from(response.ciphertext, "base64");
46576
+ if (combined.length <= 16)
46577
+ throw new Error("Claim continuation returned an invalid credential payload.");
46578
+ const encrypted = combined.subarray(0, -16);
46579
+ const tag = combined.subarray(-16);
46580
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(response.iv, "base64"));
46581
+ decipher.setAAD(Buffer.from(`${state.handoff_id}:${state.project_id}`, "utf8"));
46582
+ decipher.setAuthTag(tag);
46583
+ const plaintext = Buffer.concat([decipher.update(encrypted), decipher.final()]).toString("utf8");
46584
+ const parsed = JSON.parse(plaintext);
46585
+ const projects = parsed.scope?.projects;
46586
+ const agent = parsed.credential_kind === "project_agent";
46587
+ if (typeof parsed.token !== "string" || !parsed.token || typeof parsed.expires_at !== "string" || typeof parsed.email !== "string" || parsed.project_id !== state.project_id || parsed.approved_scope !== void 0 && parsed.approved_scope !== "project" || !Array.isArray(projects) || !projects.includes(state.project_id) || projects.some((project) => typeof project !== "string" || !project) || (agent ? parsed.refresh_token !== null || parsed.claim_access !== "new_projects" && parsed.claim_access !== "all_projects" : parsed.credential_kind !== void 0 || parsed.claim_access !== void 0 || typeof parsed.refresh_token !== "string" || projects.length !== 1)) {
46588
+ throw new Error("Claim continuation credential did not match the approved project. Nothing was installed.");
46589
+ }
46590
+ return parsed;
46591
+ }
46592
+ async function post(path3, body, token) {
46593
+ const response = await fetchWithProxy(`${API_BASE_URL}${path3}`, {
46594
+ method: "POST",
46595
+ headers: {
46596
+ "Content-Type": "application/json",
46597
+ ...token ? { Authorization: `Bearer ${token}` } : {}
46598
+ },
46599
+ body: JSON.stringify(body),
46600
+ signal: AbortSignal.timeout(15e3)
46601
+ }, 15e3);
46602
+ const envelope = await response.json();
46603
+ return { response, envelope };
46604
+ }
46605
+ async function ensureClaimHandoff(projectId) {
46606
+ const config2 = loadConfig();
46607
+ if (!config2?.temporary || !config2.token)
46608
+ return null;
46609
+ let state = config2.claim_handoff;
46610
+ if (!state || state.project_id !== projectId) {
46611
+ state = { project_id: projectId, verifier: newVerifier() };
46612
+ saveConfig({ ...config2, claim_handoff: state });
46613
+ }
46614
+ if (state.handoff_id)
46615
+ return state;
46616
+ const { response, envelope } = await post("/auth/temp-handoff/register", {
46617
+ project_id: projectId,
46618
+ verifier_hash: verifierHash(state.verifier),
46619
+ device_name: getDeviceKeyName(),
46620
+ client: { hostname: describeThisDevice().hostname },
46621
+ capabilities: ["claim_project_agent_v1"]
46622
+ }, config2.token);
46623
+ if (!response.ok || !envelope.ok || !envelope.data) {
46624
+ throw new Error(envelope.message || envelope.error || `CLI continuation registration failed (HTTP ${response.status}).`);
46625
+ }
46626
+ const registered = { ...state, handoff_id: envelope.data.handoff_id, expires_at: envelope.data.expires_at };
46627
+ const current = loadConfig();
46628
+ if (!current?.temporary || current.claim_handoff?.verifier !== state.verifier)
46629
+ return null;
46630
+ saveConfig({ ...current, claim_handoff: registered });
46631
+ return registered;
46632
+ }
46633
+ async function acknowledge(handoffId, verifier) {
46634
+ try {
46635
+ const { response, envelope } = await post("/auth/temp-handoff/ack", {
46636
+ handoff_id: handoffId,
46637
+ verifier
46638
+ });
46639
+ return response.ok && envelope.ok && envelope.data?.acknowledged === true;
46640
+ } catch {
46641
+ return false;
46642
+ }
46643
+ }
46644
+ function clearCurrentAcknowledgement(expected) {
46645
+ const current = loadConfig();
46646
+ if (!current)
46647
+ return null;
46648
+ if (current.claim_handoff_ack?.handoff_id !== expected.handoff_id || current.claim_handoff_ack.verifier !== expected.verifier)
46649
+ return current;
46650
+ const { claim_handoff_ack: _removed, ...clean } = current;
46651
+ saveConfig(clean);
46652
+ return clean;
46653
+ }
46654
+ function dropExpiredHandoff(token, state) {
46655
+ const current = loadConfig();
46656
+ if (!current?.temporary || current.token !== token || current.claim_handoff?.handoff_id !== state.handoff_id || current.claim_handoff?.verifier !== state.verifier)
46657
+ return;
46658
+ const { claim_handoff: _expired, ...rest } = current;
46659
+ saveConfig(rest);
46660
+ }
46661
+ async function recoverClaimHandoff() {
46662
+ let config2 = loadConfig();
46663
+ if (!config2)
46664
+ return { kind: "none" };
46665
+ if (config2.claim_handoff_ack) {
46666
+ const ack = config2.claim_handoff_ack;
46667
+ if (await acknowledge(ack.handoff_id, ack.verifier)) {
46668
+ config2 = clearCurrentAcknowledgement(ack);
46669
+ if (!config2)
46670
+ return { kind: "none" };
46671
+ }
46672
+ }
46673
+ const state = config2.temporary ? config2.claim_handoff : void 0;
46674
+ if (!state?.handoff_id)
46675
+ return { kind: "none" };
46676
+ let response;
46677
+ let envelope;
46678
+ try {
46679
+ ({ response, envelope } = await post("/auth/temp-handoff/exchange", {
46680
+ handoff_id: state.handoff_id,
46681
+ verifier: state.verifier
46682
+ }));
46683
+ } catch {
46684
+ return { kind: "none" };
46685
+ }
46686
+ if (envelope.error === "CLAIM_CLI_ACCOUNT_SCOPE_FORBIDDEN" || envelope.data?.approved_scope !== void 0 && envelope.data.approved_scope !== "project") {
46687
+ return {
46688
+ kind: "manual",
46689
+ message: `This claim approval cannot be used to sign in. Run \`${cliInvocation()} login\` and ask the account owner to approve it.`
46690
+ };
46691
+ }
46692
+ if (!response.ok || !envelope.ok || !envelope.data) {
46693
+ if (["CLAIM_CLI_HANDOFF_PENDING", "CLAIM_CLI_HANDOFF_IN_PROGRESS"].includes(envelope.error || "")) {
46694
+ return { kind: "none" };
46695
+ }
46696
+ if (envelope.error === "CLAIM_CLI_HANDOFF_EXPIRED" && temporaryConfigExpired(config2)) {
46697
+ dropExpiredHandoff(config2.token, state);
46698
+ return {
46699
+ kind: "stale",
46700
+ message: `The temporary workspace on this machine expired at ${config2.temp_expires_at}. If you claimed it in the browser, \`${cliInvocation()} login\` signs in to it.`
46701
+ };
46702
+ }
46703
+ if (["CLAIM_CLI_HANDOFF_DENIED", "CLAIM_CLI_HANDOFF_EXPIRED", "CLAIM_CLI_HANDOFF_CONSUMED", "CLAIM_CLI_HANDOFF_OWNERSHIP_MISMATCH"].includes(envelope.error || "")) {
46704
+ return {
46705
+ kind: "manual",
46706
+ message: envelope.message || `Run \`${cliInvocation()} login\` in this directory. Keep the existing project link; do not unlink or redeploy.`
46707
+ };
46708
+ }
46709
+ return { kind: "none" };
46710
+ }
46711
+ const delivered = decodeCredentials(state, envelope.data);
46712
+ const current = loadConfig();
46713
+ if (!current?.temporary || current.token !== config2.token || current.claim_handoff?.project_id !== state.project_id || current.claim_handoff.verifier !== state.verifier || current.claim_handoff.handoff_id !== state.handoff_id) {
46714
+ return { kind: "none" };
46715
+ }
46716
+ const next = {
46717
+ token: delivered.token,
46718
+ ...delivered.credential_kind === "project_agent" ? { claim_access: delivered.claim_access } : { refresh_token: delivered.refresh_token, access_expires_at: delivered.expires_at },
46719
+ user: { email: delivered.email, username: "" },
46720
+ claim_handoff_ack: { handoff_id: state.handoff_id, verifier: state.verifier }
46721
+ };
46722
+ saveConfig(next);
46723
+ if (await acknowledge(state.handoff_id, state.verifier)) {
46724
+ clearCurrentAcknowledgement(next.claim_handoff_ack);
46725
+ }
46726
+ return {
46727
+ kind: "recovered",
46728
+ message: delivered.claim_access === "new_projects" ? "Connected. You can work on the saved apps and create new apps in this account." : delivered.claim_access === "all_projects" ? "Connected. You can work on the apps already in this account and create new ones." : `Connected. You can work on the saved app. Run \`${cliInvocation()} login\` for account access.`
46729
+ };
46730
+ }
46731
+ var init_claim_handoff = __esm({
46732
+ "dist/lib/claim-handoff.js"() {
46733
+ "use strict";
46734
+ init_cli_invocation();
46735
+ init_config();
46736
+ init_device();
46737
+ init_device_login();
46738
+ init_client();
46739
+ init_http();
46740
+ __name(readClaimConnection, "readClaimConnection");
46741
+ __name(verifierHash, "verifierHash");
46742
+ __name(newVerifier, "newVerifier");
46743
+ __name(decodeCredentials, "decodeCredentials");
46744
+ __name(post, "post");
46745
+ __name(ensureClaimHandoff, "ensureClaimHandoff");
46746
+ __name(acknowledge, "acknowledge");
46747
+ __name(clearCurrentAcknowledgement, "clearCurrentAcknowledgement");
46748
+ __name(dropExpiredHandoff, "dropExpiredHandoff");
46749
+ __name(recoverClaimHandoff, "recoverClaimHandoff");
46750
+ }
46751
+ });
46752
+
46554
46753
  // dist/lib/allowed-origins.js
46555
46754
  function isExactOrigin(value) {
46556
46755
  const trimmed = value.trim();
@@ -46825,6 +47024,30 @@ async function listProjects(opts = {}) {
46825
47024
  const client = new ApiClient(getToken());
46826
47025
  const spinner = opts.json ? null : ora("Fetching projects...").start();
46827
47026
  try {
47027
+ if (loadConfig()?.claim_access) {
47028
+ const connection = await readClaimConnection(client);
47029
+ spinner?.stop();
47030
+ if (connection.state !== "claimed_connected") {
47031
+ throw new Error(`This app connection is closed. Run \`${cliInvocation()} login\` and ask the account owner to approve it.`);
47032
+ }
47033
+ if (opts.json)
47034
+ printJson(connection);
47035
+ else {
47036
+ const apps = connection.projects ?? [];
47037
+ if (apps.length)
47038
+ table(["App", "ID", "URL", "Deploy"], apps.map((app) => [
47039
+ app.name,
47040
+ app.project_id,
47041
+ app.url,
47042
+ app.can_deploy ? "Available" : app.reason === "private_configuration" ? "Paused for private configuration" : "Unavailable"
47043
+ ]));
47044
+ else
47045
+ info("This connection has no apps yet.");
47046
+ if (connection.can_create_projects)
47047
+ info(`Create an app with \`${cliInvocation()} init --name <name>\`.`);
47048
+ }
47049
+ return;
47050
+ }
46828
47051
  const result = await client.call("GET", "/projects");
46829
47052
  spinner?.stop();
46830
47053
  if (opts.json) {
@@ -46873,6 +47096,7 @@ var init_project = __esm({
46873
47096
  init_spinner();
46874
47097
  init_client();
46875
47098
  init_config();
47099
+ init_claim_handoff();
46876
47100
  init_output();
46877
47101
  init_project_urls();
46878
47102
  init_platform_command();
@@ -76028,11 +76252,11 @@ var init_typecheck2 = __esm({
76028
76252
  });
76029
76253
 
76030
76254
  // dist/lib/base-files.js
76031
- import { createHash as createHash3 } from "node:crypto";
76255
+ import { createHash as createHash4 } from "node:crypto";
76032
76256
  import { existsSync as existsSync17, mkdirSync as mkdirSync10, readFileSync as readFileSync18, rmSync as rmSync5, writeFileSync as writeFileSync13 } from "node:fs";
76033
76257
  import { join as join20 } from "node:path";
76034
76258
  function sha2562(content) {
76035
- return createHash3("sha256").update(content).digest("hex");
76259
+ return createHash4("sha256").update(content).digest("hex");
76036
76260
  }
76037
76261
  function hashFiles(dir, paths) {
76038
76262
  const out = {};
@@ -76308,7 +76532,7 @@ var init_build_errors = __esm({
76308
76532
  });
76309
76533
 
76310
76534
  // dist/lib/temp-auth.js
76311
- import { createHash as createHash4 } from "node:crypto";
76535
+ import { createHash as createHash5 } from "node:crypto";
76312
76536
  function leadingZeroBits(buf) {
76313
76537
  let bits = 0;
76314
76538
  for (const byte of buf) {
@@ -76329,7 +76553,7 @@ function solvePow(nonce, difficulty) {
76329
76553
  let i = 0;
76330
76554
  for (; ; ) {
76331
76555
  const suffix = (i++).toString(36);
76332
- const hash2 = createHash4("sha256").update(`${nonce}:${suffix}`, "utf8").digest();
76556
+ const hash2 = createHash5("sha256").update(`${nonce}:${suffix}`, "utf8").digest();
76333
76557
  if (leadingZeroBits(hash2) >= difficulty) {
76334
76558
  return { suffix, hash: hash2.toString("hex") };
76335
76559
  }
@@ -76374,194 +76598,6 @@ var init_temp_auth = __esm({
76374
76598
  }
76375
76599
  });
76376
76600
 
76377
- // dist/lib/claim-handoff.js
76378
- import { createDecipheriv, createHash as createHash5, randomBytes as randomBytes2 } from "node:crypto";
76379
- function verifierHash(verifier) {
76380
- return createHash5("sha256").update(verifier, "utf8").digest("hex");
76381
- }
76382
- function newVerifier() {
76383
- return randomBytes2(32).toString("base64url");
76384
- }
76385
- function decodeCredentials(state, response) {
76386
- if (!state.handoff_id || response.project_id !== state.project_id) {
76387
- throw new Error("Claim continuation returned a different project. No credential was installed.");
76388
- }
76389
- const key = createHash5("sha256").update(`claim-cli-handoff:v1:${state.verifier}`, "utf8").digest();
76390
- const combined = Buffer.from(response.ciphertext, "base64");
76391
- if (combined.length <= 16)
76392
- throw new Error("Claim continuation returned an invalid credential payload.");
76393
- const encrypted = combined.subarray(0, -16);
76394
- const tag = combined.subarray(-16);
76395
- const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(response.iv, "base64"));
76396
- decipher.setAAD(Buffer.from(`${state.handoff_id}:${state.project_id}`, "utf8"));
76397
- decipher.setAuthTag(tag);
76398
- const plaintext = Buffer.concat([decipher.update(encrypted), decipher.final()]).toString("utf8");
76399
- const parsed = JSON.parse(plaintext);
76400
- if (typeof parsed.token !== "string" || typeof parsed.refresh_token !== "string" || typeof parsed.expires_at !== "string" || typeof parsed.email !== "string" || parsed.project_id !== state.project_id || parsed.approved_scope !== void 0 && parsed.approved_scope !== "project" || parsed.scope?.projects?.length !== 1 || parsed.scope.projects[0] !== state.project_id) {
76401
- throw new Error("Claim continuation credential did not match the approved project. Nothing was installed.");
76402
- }
76403
- return parsed;
76404
- }
76405
- async function post(path3, body, token) {
76406
- const response = await fetchWithProxy(`${API_BASE_URL}${path3}`, {
76407
- method: "POST",
76408
- headers: {
76409
- "Content-Type": "application/json",
76410
- ...token ? { Authorization: `Bearer ${token}` } : {}
76411
- },
76412
- body: JSON.stringify(body),
76413
- signal: AbortSignal.timeout(15e3)
76414
- }, 15e3);
76415
- const envelope = await response.json();
76416
- return { response, envelope };
76417
- }
76418
- async function ensureClaimHandoff(projectId) {
76419
- const config2 = loadConfig();
76420
- if (!config2?.temporary || !config2.token)
76421
- return null;
76422
- let state = config2.claim_handoff;
76423
- if (!state || state.project_id !== projectId) {
76424
- state = { project_id: projectId, verifier: newVerifier() };
76425
- saveConfig({ ...config2, claim_handoff: state });
76426
- }
76427
- if (state.handoff_id)
76428
- return state;
76429
- const { response, envelope } = await post("/auth/temp-handoff/register", {
76430
- project_id: projectId,
76431
- verifier_hash: verifierHash(state.verifier),
76432
- device_name: getDeviceKeyName(),
76433
- client: describeThisDevice()
76434
- }, config2.token);
76435
- if (!response.ok || !envelope.ok || !envelope.data) {
76436
- throw new Error(envelope.message || envelope.error || `CLI continuation registration failed (HTTP ${response.status}).`);
76437
- }
76438
- const registered = { ...state, handoff_id: envelope.data.handoff_id, expires_at: envelope.data.expires_at };
76439
- const current = loadConfig();
76440
- if (!current?.temporary || current.claim_handoff?.verifier !== state.verifier)
76441
- return null;
76442
- saveConfig({ ...current, claim_handoff: registered });
76443
- return registered;
76444
- }
76445
- async function acknowledge(handoffId, verifier) {
76446
- try {
76447
- const { response, envelope } = await post("/auth/temp-handoff/ack", {
76448
- handoff_id: handoffId,
76449
- verifier
76450
- });
76451
- return response.ok && envelope.ok && envelope.data?.acknowledged === true;
76452
- } catch {
76453
- return false;
76454
- }
76455
- }
76456
- function clearCurrentAcknowledgement(expected) {
76457
- const current = loadConfig();
76458
- if (!current)
76459
- return null;
76460
- if (current.claim_handoff_ack?.handoff_id !== expected.handoff_id || current.claim_handoff_ack.verifier !== expected.verifier)
76461
- return current;
76462
- const { claim_handoff_ack: _removed, ...clean } = current;
76463
- saveConfig(clean);
76464
- return clean;
76465
- }
76466
- function dropExpiredHandoff(token, state) {
76467
- const current = loadConfig();
76468
- if (!current?.temporary || current.token !== token || current.claim_handoff?.handoff_id !== state.handoff_id || current.claim_handoff?.verifier !== state.verifier)
76469
- return;
76470
- const { claim_handoff: _expired, ...rest } = current;
76471
- saveConfig(rest);
76472
- }
76473
- async function recoverClaimHandoff() {
76474
- let config2 = loadConfig();
76475
- if (!config2)
76476
- return { kind: "none" };
76477
- if (config2.claim_handoff_ack) {
76478
- const ack = config2.claim_handoff_ack;
76479
- if (await acknowledge(ack.handoff_id, ack.verifier)) {
76480
- config2 = clearCurrentAcknowledgement(ack);
76481
- if (!config2)
76482
- return { kind: "none" };
76483
- }
76484
- }
76485
- const state = config2.temporary ? config2.claim_handoff : void 0;
76486
- if (!state?.handoff_id)
76487
- return { kind: "none" };
76488
- let response;
76489
- let envelope;
76490
- try {
76491
- ({ response, envelope } = await post("/auth/temp-handoff/exchange", {
76492
- handoff_id: state.handoff_id,
76493
- verifier: state.verifier
76494
- }));
76495
- } catch {
76496
- return { kind: "none" };
76497
- }
76498
- if (envelope.error === "CLAIM_CLI_ACCOUNT_SCOPE_FORBIDDEN" || envelope.data?.approved_scope !== void 0 && envelope.data.approved_scope !== "project") {
76499
- return {
76500
- kind: "manual",
76501
- message: `A claim link connects this CLI only to the claimed project. Run \`${cliInvocation()} login\` for account access.`
76502
- };
76503
- }
76504
- if (!response.ok || !envelope.ok || !envelope.data) {
76505
- if (["CLAIM_CLI_HANDOFF_PENDING", "CLAIM_CLI_HANDOFF_IN_PROGRESS"].includes(envelope.error || "")) {
76506
- return { kind: "none" };
76507
- }
76508
- if (envelope.error === "CLAIM_CLI_HANDOFF_EXPIRED" && temporaryConfigExpired(config2)) {
76509
- dropExpiredHandoff(config2.token, state);
76510
- return {
76511
- kind: "stale",
76512
- message: `The temporary workspace on this machine expired at ${config2.temp_expires_at}. If you claimed it in the browser, \`${cliInvocation()} login\` signs in to it.`
76513
- };
76514
- }
76515
- if (["CLAIM_CLI_HANDOFF_DENIED", "CLAIM_CLI_HANDOFF_EXPIRED", "CLAIM_CLI_HANDOFF_CONSUMED", "CLAIM_CLI_HANDOFF_OWNERSHIP_MISMATCH"].includes(envelope.error || "")) {
76516
- return {
76517
- kind: "manual",
76518
- message: envelope.message || `Run \`${cliInvocation()} login\` in this directory. Keep the existing project link; do not unlink or redeploy.`
76519
- };
76520
- }
76521
- return { kind: "none" };
76522
- }
76523
- const delivered = decodeCredentials(state, envelope.data);
76524
- const current = loadConfig();
76525
- if (!current?.temporary || current.token !== config2.token || current.claim_handoff?.project_id !== state.project_id || current.claim_handoff.verifier !== state.verifier || current.claim_handoff.handoff_id !== state.handoff_id) {
76526
- return { kind: "none" };
76527
- }
76528
- const next = {
76529
- token: delivered.token,
76530
- refresh_token: delivered.refresh_token,
76531
- access_expires_at: delivered.expires_at,
76532
- user: { email: delivered.email, username: "" },
76533
- claim_handoff_ack: { handoff_id: state.handoff_id, verifier: state.verifier }
76534
- };
76535
- saveConfig(next);
76536
- if (await acknowledge(state.handoff_id, state.verifier)) {
76537
- clearCurrentAcknowledgement(next.claim_handoff_ack);
76538
- }
76539
- return {
76540
- kind: "recovered",
76541
- message: `Connected to ${delivered.email} for this project only. The existing project link was kept. Run \`${cliInvocation()} login\` for account access.`
76542
- };
76543
- }
76544
- var init_claim_handoff = __esm({
76545
- "dist/lib/claim-handoff.js"() {
76546
- "use strict";
76547
- init_cli_invocation();
76548
- init_config();
76549
- init_device();
76550
- init_device_login();
76551
- init_client();
76552
- init_http();
76553
- __name(verifierHash, "verifierHash");
76554
- __name(newVerifier, "newVerifier");
76555
- __name(decodeCredentials, "decodeCredentials");
76556
- __name(post, "post");
76557
- __name(ensureClaimHandoff, "ensureClaimHandoff");
76558
- __name(acknowledge, "acknowledge");
76559
- __name(clearCurrentAcknowledgement, "clearCurrentAcknowledgement");
76560
- __name(dropExpiredHandoff, "dropExpiredHandoff");
76561
- __name(recoverClaimHandoff, "recoverClaimHandoff");
76562
- }
76563
- });
76564
-
76565
76601
  // dist/lib/project-notices.js
76566
76602
  import { existsSync as existsSync19, mkdirSync as mkdirSync11, readFileSync as readFileSync20, writeFileSync as writeFileSync14 } from "node:fs";
76567
76603
  import { dirname as dirname8, join as join22 } from "node:path";
@@ -77335,9 +77371,21 @@ function describeReport(groups, options2 = {}) {
77335
77371
  }, "note");
77336
77372
  const failed = checks.filter((check2) => !check2.ok && !check2.skipped);
77337
77373
  const notRun = checks.filter((check2) => check2.skipped === "after-failure");
77338
- const skipped = checks.filter((check2) => check2.skipped === "needs-claim");
77374
+ const skipped = checks.filter((check2) => check2.skipped && check2.skipped !== "after-failure");
77339
77375
  const lines = [
77340
- ...failed.map((check2) => `FAIL ${check2.name}${note(check2.script)}: ${firstLine(check2.error) || "failed"}`),
77376
+ ...failed.flatMap((check2) => {
77377
+ const name = `FAIL ${check2.name}${note(check2.script)}`;
77378
+ const failure = check2.failure;
77379
+ if (!failure)
77380
+ return [`${name}: ${firstLine(check2.error) || "failed"}`];
77381
+ return [
77382
+ name,
77383
+ ` Expected: ${failure.expected}`,
77384
+ ` Happened: ${failure.happened}`,
77385
+ ` Step: ${failure.step}`,
77386
+ ...failure.evidence ? [` Evidence: ${failure.evidence}`] : []
77387
+ ];
77388
+ }),
77341
77389
  ...checks.filter((check2) => check2.ok).map((check2) => `PASS ${check2.name}${note(check2.script)}`),
77342
77390
  ...skipped.map((check2) => `SKIPPED ${check2.name}${note(check2.script)}: ${firstLine(check2.error)}`),
77343
77391
  ...notRun.map((check2) => `NOT RUN ${check2.name}${note(check2.script, "after the first failure")}`)
@@ -77345,9 +77393,10 @@ function describeReport(groups, options2 = {}) {
77345
77393
  const scripts = plural(groups.length, "script");
77346
77394
  if (!checks.length)
77347
77395
  lines.push(`FAILED: no check ran in ${scripts}: it stopped before its first check (its error is in the script's output).`);
77348
- else if (failed.length)
77349
- lines.push(`FAILED: ${failed.length} of ${plural(checks.length, "check")} in ${scripts}${notRun.length ? ` (${notRun.length} not run)` : ""}`);
77350
- else if (skipped.length)
77396
+ else if (failed.length) {
77397
+ const omitted = [skipped.length && `${skipped.length} skipped`, notRun.length && `${notRun.length} not run`].filter(Boolean);
77398
+ lines.push(`FAILED: ${failed.length} of ${plural(checks.length, "check")} in ${scripts}${omitted.length ? ` (${omitted.join(", ")})` : ""}`);
77399
+ } else if (skipped.length)
77351
77400
  lines.push(`${checks.length - skipped.length} passed, ${skipped.length} skipped in ${scripts}`);
77352
77401
  else
77353
77402
  lines.push(`PASSED: ${plural(checks.length, "check")} in ${scripts}`);
@@ -77355,7 +77404,7 @@ function describeReport(groups, options2 = {}) {
77355
77404
  lines.push(`Next: fix the error in the script's output, then run ${TEST_COMMAND} again.`);
77356
77405
  else if (failed.length)
77357
77406
  lines.push(`Next: fix what each FAIL line names, run ${DEPLOY_COMMAND}, then ${TEST_COMMAND} --failed to rerun each script that failed.`);
77358
- if (skipped.length)
77407
+ if (skipped.some((check2) => check2.skipped === "needs-claim"))
77359
77408
  lines.push(TEST_INBOX_CLAIM_NEXT);
77360
77409
  const files = [...new Set(groups.map((group) => group.resultFile).filter((file2) => Boolean(file2)))];
77361
77410
  if (files.length && (failed.length || !checks.length || options2.verbose))
@@ -82465,7 +82514,7 @@ Existing project: \`${cliInvocation()} init --link --project <ref>\` (see \`${cl
82465
82514
  } else if (linkedProjectEntry && projectConfigMatchesRef(linkedProjectEntry.config, projectId)) {
82466
82515
  deployStateEntry = linkedProjectEntry;
82467
82516
  }
82468
- const stopPrestart = projectId && !tempSession && !opts.dryRun ? startDeployPrestart(client, projectId) : () => void 0;
82517
+ const stopPrestart = projectId && !tempSession && !opts.dryRun && !storedConfig?.claim_access ? startDeployPrestart(client, projectId) : () => void 0;
82469
82518
  let explicitProjectId = null;
82470
82519
  const earlyLiveBase = opts.project && projectId && !tempSession && !opts.force && CANONICAL_PROJECT_ID.test(projectId) && !readSourceBase(targetProjectConfig, projectId) ? { projectId, read: readExplicitProjectLiveBase(client, projectId) } : null;
82471
82520
  if (opts.project && projectId && !tempSession) {
@@ -82924,11 +82973,11 @@ ${dim("Build")}`);
82924
82973
  info(formatTempExpiry(tempSession.expiresAt, tempSession.ttlSeconds));
82925
82974
  const link = teal(tempSession.claimUrl);
82926
82975
  if (tempSession.handoffReady) {
82927
- info(`Open ${link} and select "Save and connect agent" to save the project and connect this terminal to it only. Run \`${cliInvocation()} login\` for account access.`);
82976
+ info(`Open ${link} and select "Save and connect agent" to work on the saved apps and create new ones. You can choose to include your other apps.`);
82928
82977
  } else if (besideRealLogin) {
82929
- info(`Open ${link} to save the project to your account, then run \`${cliInvocation()} init --link --project ${projectId}\` in an unlinked folder to work on it.`);
82978
+ info(`Open ${link} to save the app to your account, then run \`${cliInvocation()} init --link --project ${projectId}\` in an unlinked folder to work on it.`);
82930
82979
  } else {
82931
- info(`Open ${link} to save the project to your account, then run \`${cliInvocation()} login\` to connect this terminal.`);
82980
+ info(`Open ${link} to save the app to your account, then run \`${cliInvocation()} login\` to connect this terminal.`);
82932
82981
  }
82933
82982
  }
82934
82983
  if (hasFunctionErrors) {
@@ -87131,6 +87180,7 @@ function registerStatus(program2) {
87131
87180
  program2.command("status [project]").description("Show project and workspace status").option("--project <ref>", "Project ID, name, slug, or subdomain \u2014 the same flag every other command takes. The positional form still works.").option("--json", "Print the raw status responses as JSON").action(async (projectArg, opts) => {
87132
87181
  const token = getToken();
87133
87182
  const client = new ApiClient(token);
87183
+ const claimConnection = Boolean(loadConfig()?.claim_access);
87134
87184
  const chosen = chooseProjectRef(projectArg, opts.project);
87135
87185
  if (chosen.kind === "conflict") {
87136
87186
  error(projectRefConflictMessage(chosen));
@@ -87154,7 +87204,7 @@ function registerStatus(program2) {
87154
87204
  try {
87155
87205
  const p2 = await client.call("GET", `/projects/${encodeURIComponent(projectId)}`);
87156
87206
  projectStatus = p2;
87157
- const servingUrl = await getProjectServingUrl(client, projectId).catch(() => fallbackProjectServingUrl(p2));
87207
+ const servingUrl = claimConnection ? fallbackProjectServingUrl(p2) : await getProjectServingUrl(client, projectId).catch(() => fallbackProjectServingUrl(p2));
87158
87208
  if (!opts.json) {
87159
87209
  console.log(`
87160
87210
  Project: ${teal(p2.name)} (${statusDot(p2.status)})`);
@@ -87171,7 +87221,7 @@ function registerStatus(program2) {
87171
87221
  process.exitCode = 1;
87172
87222
  }
87173
87223
  try {
87174
- const deployment = unwrapPlatformData(await callPlatformTool("deploy_status", { project_id: projectId }, { allTools: true }));
87224
+ const deployment = claimConnection ? await client.call("GET", "/deploy/status", void 0, { project_id: projectId }) : unwrapPlatformData(await callPlatformTool("deploy_status", { project_id: projectId }, { allTools: true }));
87175
87225
  if (!isRecord(deployment))
87176
87226
  throw new Error("deploy_status returned an unexpected response.");
87177
87227
  deploymentStatus = deployment;
@@ -87221,24 +87271,25 @@ function registerStatus(program2) {
87221
87271
  process.exitCode = 1;
87222
87272
  }
87223
87273
  }
87224
- try {
87225
- const ws2 = await client.call("GET", "/hosted/status");
87226
- workspaceStatus = ws2;
87227
- if (!opts.json) {
87228
- console.log("");
87229
- const wsStatus = ws2.status === "ready" ? "running" : `${ws2.status} (starting)`;
87230
- info(`Dev workspace: ${wsStatus} ${dim("\u2014 optional code workspace; your deployed app serves regardless")}`);
87231
- if (ws2.terminal_url) {
87232
- info(`Terminal: ${dim(ws2.terminal_url)}`);
87274
+ if (!claimConnection)
87275
+ try {
87276
+ const ws2 = await client.call("GET", "/hosted/status");
87277
+ workspaceStatus = ws2;
87278
+ if (!opts.json) {
87279
+ console.log("");
87280
+ const wsStatus = ws2.status === "ready" ? "running" : `${ws2.status} (starting)`;
87281
+ info(`Dev workspace: ${wsStatus} ${dim("\u2014 optional code workspace; your deployed app serves regardless")}`);
87282
+ if (ws2.terminal_url) {
87283
+ info(`Terminal: ${dim(ws2.terminal_url)}`);
87284
+ }
87233
87285
  }
87286
+ } catch {
87234
87287
  }
87235
- } catch {
87236
- }
87237
87288
  if (opts.json) {
87238
87289
  let appUrl = null;
87239
87290
  let appUrlError = null;
87240
87291
  try {
87241
- appUrl = await getAuthoritativeAppUrl(client, projectId);
87292
+ appUrl = claimConnection ? projectStatus && fallbackProjectServingUrl(projectStatus) : await getAuthoritativeAppUrl(client, projectId);
87242
87293
  if (!appUrl)
87243
87294
  appUrlError = { code: "APP_URL_NOT_REPORTED", message: "The platform reported no https app URL for this project. Deploy it, then run this again." };
87244
87295
  } catch (err) {
@@ -87345,10 +87396,10 @@ var init_open2 = __esm({
87345
87396
 
87346
87397
  // dist/commands/claim.js
87347
87398
  function registerClaim(program2) {
87348
- program2.command("claim").description("Print the claim URL that keeps this computer's temporary (signed-out) projects").option("--json", "Print { claim_url, expires_at } as JSON").action((opts) => {
87399
+ program2.command("claim").description("Print the claim URL for this computer's temporary apps").option("--json", "Print { claim_url, expires_at } as JSON").action((opts) => {
87349
87400
  const config2 = loadConfig();
87350
87401
  if (!config2?.temporary || !config2.claim_url) {
87351
- const message3 = config2?.token ? `This terminal has no temporary workspace to claim. Run \`${cliInvocation()} projects\` to see the projects it can access.` : `This terminal has no temporary workspace. If you deployed signed out from another terminal, run \`${cliInvocation()} claim\` there. Run \`${cliInvocation()} deploy\` here to start one.`;
87402
+ const message3 = config2?.token ? `This terminal has no temporary workspace to claim. Run \`${cliInvocation()} projects\` to see the apps it can access.` : `This terminal has no temporary workspace. If you deployed signed out from another terminal, run \`${cliInvocation()} claim\` there. Run \`${cliInvocation()} deploy\` here to start one.`;
87352
87403
  if (opts.json)
87353
87404
  printJson({ ok: false, error: config2?.token ? "NOT_TEMPORARY" : "NO_TEMPORARY_WORKSPACE", message: message3 });
87354
87405
  else
@@ -87363,17 +87414,18 @@ function registerClaim(program2) {
87363
87414
  return;
87364
87415
  }
87365
87416
  if (expired) {
87366
- error(`This computer's temporary workspace expired at ${config2.temp_expires_at}; unclaimed projects are gone. Run \`${cliInvocation()} deploy\` to start a new one.`);
87417
+ error(`This computer's temporary workspace expired at ${config2.temp_expires_at}. Unclaimed apps are gone. Run \`${cliInvocation()} deploy\` to start a new one.`);
87367
87418
  process.exit(1);
87368
87419
  }
87369
87420
  info(`Claim URL: ${teal(config2.claim_url)}`);
87370
87421
  if (config2.temp_expires_at)
87371
87422
  info(`Expires at: ${config2.temp_expires_at} (UTC)`);
87372
- info("Open it in a browser and sign in or create an account to keep these projects.");
87423
+ info("Open it in a browser and sign in or create an account to keep these apps.");
87373
87424
  if (config2.claim_handoff?.handoff_id) {
87374
- info('Choose "Save and connect agent" to connect this terminal to the claimed project only.');
87425
+ info('Choose "Save and connect agent" to work on the saved apps and create new ones. You can choose to include your other apps.');
87426
+ } else {
87427
+ info(`Run \`${cliInvocation()} login\` to connect this terminal after saving.`);
87375
87428
  }
87376
- info(`Run \`${cliInvocation()} login\` for account access.`);
87377
87429
  });
87378
87430
  }
87379
87431
  var init_claim = __esm({
@@ -131349,7 +131401,7 @@ var init_test_scripts = __esm({
131349
131401
 
131350
131402
  // dist/commands/test.js
131351
131403
  function registerTest(program2) {
131352
- program2.command("test [files...]").description("Run this project's tests: every tests/*.mjs and tests/*.cjs script (such as tests/app-check.mjs), or, when the project has tests/**/*.spec.ts, its Playwright specs against the live release (--preview: this folder's open preview)").option("--preview", "Test this folder's open preview (its own users, data copy and captured mail), pinned to the version saved when the run starts. Production is never touched.").option("--workers <count>", "Parallel workers", "5").option("--failed", "Rerun what failed last time: each failed tests/*.mjs or *.cjs script, all its checks (specs: only the failed tests)").option("--grep <name>", "Filter test names (subset)").option("--url <url>", "Unsupported in phase 1").option("--phone", "Run every test again in a 390x844 phone viewport ([phone] in results)").option("--json", "Print structured results").option("--verbose", "Also print where the full result file is when everything passed").action(async (files, opts) => {
131404
+ program2.command("test [files...]").description("Run this project's tests: every tests/*.mjs and tests/*.cjs script (such as tests/app-check.mjs), or, when the project has tests/**/*.spec.ts, its Playwright specs against the live release (--preview: this folder's open preview)").option("--preview", "Test this folder's open preview (its own users, data copy and captured mail), pinned to the version saved when the run starts. Production is never touched.").option("--workers <count>", "Parallel workers", "5").option("--failed", "Rerun what failed last time: each failed tests/*.mjs or *.cjs script, all its checks (specs: only the failed tests)").option("--fail-fast", "Stop app-check scripts at their first failed check").option("--grep <name>", "Filter test names (subset)").option("--url <url>", "Unsupported in phase 1").option("--phone", "Run every test again in a 390x844 phone viewport ([phone] in results)").option("--json", "Print structured results").option("--verbose", "Also print where the full result file is when everything passed").addHelpText("after", '\nFor the starter privacy check, mark the data view with data-sw-data="loading" while fetching, "ready" once data loads, or "error" if fetching fails.\n').action(async (files, opts) => {
131353
131405
  markProcessStart("cli");
131354
131406
  mark("cli:action");
131355
131407
  if (opts.url)
@@ -131371,6 +131423,8 @@ function registerTest(program2) {
131371
131423
  const scripts = opts.failed ? lastFailedScripts(root) : listScripts(root, files);
131372
131424
  if (opts.failed && !scripts.length)
131373
131425
  throw new Error("No failed scripts are recorded from the last run here; run somewhere test.");
131426
+ if (opts.failFast)
131427
+ process.env.SW_TEST_FAIL_FAST = "1";
131374
131428
  const results = await runScripts(root, scripts, []);
131375
131429
  await note;
131376
131430
  if (results.length)
@@ -131384,6 +131438,8 @@ function registerTest(program2) {
131384
131438
  process.exitCode = failed || !results.length ? 1 : 0;
131385
131439
  return;
131386
131440
  }
131441
+ if (opts.failFast)
131442
+ throw new Error("--fail-fast applies to app-check scripts (tests/*.mjs or *.cjs).");
131387
131443
  const outcome2 = await runTests({ root, ...opts.preview ? {} : { client: new ApiClient(getToken()) }, projectId, prepared: prepareRunner(root), options: { ...opts, files } });
131388
131444
  await note;
131389
131445
  mark("cli:exit");
@@ -132301,8 +132357,12 @@ Run ${cliInvocation()} <command> --help for full command details.`);
132301
132357
  program2.enablePositionalOptions();
132302
132358
  const skipRecovery = ["lint", "upgrade", "update", "login", "signup", "logout", "docs", "help", "--help", "-h", "--version", "-V"].includes(command);
132303
132359
  const recovery = skipRecovery ? { kind: "none" } : await recoverClaimHandoff();
132304
- if (recovery.kind === "recovered" && recovery.message && !jsonOutputRequested && command !== "file")
132305
- info(recovery.message);
132360
+ if (recovery.kind === "recovered" && recovery.message) {
132361
+ if (jsonOutputRequested || command === "file")
132362
+ console.error(recovery.message);
132363
+ else
132364
+ info(recovery.message);
132365
+ }
132306
132366
  if (recovery.kind === "stale" && recovery.message) {
132307
132367
  if (jsonOutputRequested || command === "file")
132308
132368
  console.error(recovery.message);
@@ -132993,6 +133053,19 @@ import { basename as basename10, dirname as dirname15, join as join48, relative
132993
133053
  function launchOptions(extra = {}) {
132994
133054
  return { ...extra, args: ["--disable-features=AsyncDns", ...extra.args ?? []] };
132995
133055
  }
133056
+ function describeCheckFailure(message3, expected, step2, evidence, pageUrl) {
133057
+ const detail = /* @__PURE__ */ __name((pattern) => message3.match(pattern)?.[1]?.trim(), "detail");
133058
+ const observed = detail(/^Received(?: \w+)?: *(.*)$/m);
133059
+ const header = message3.split("\n").find((line) => line.trim())?.trim() || "The check did not finish.";
133060
+ const artifact = detail(/\b(HTTP [1-5][0-9]{2}(?: [A-Z][A-Z_0-9]+)?)/) ?? detail(/^(?:Locator|Selector): *(.*)$/mi) ?? evidence ?? pageUrl;
133061
+ const singleLine = /* @__PURE__ */ __name((value) => scrub(value).replace(/\s+/g, " ").trim().slice(0, 500), "singleLine");
133062
+ return {
133063
+ expected: singleLine(detail(/^Expected(?: \w+)?: *(.*)$/m) ?? expected),
133064
+ happened: singleLine(observed ? `Received ${observed}.` : header),
133065
+ step: singleLine(step2),
133066
+ ...artifact ? { evidence: singleLine(artifact) } : {}
133067
+ };
133068
+ }
132996
133069
  async function pageState(page) {
132997
133070
  if (page.isClosed())
132998
133071
  return "closed";
@@ -133072,7 +133145,15 @@ function captureResponses(page) {
133072
133145
  async function dataReady(scope, timeout = 5e3) {
133073
133146
  const root = typeof scope.goto === "function" ? scope.locator(":root") : scope;
133074
133147
  const views = root.locator("[data-sw-data]");
133075
- await views.first().waitFor({ state: "attached", timeout });
133148
+ try {
133149
+ await views.first().waitFor({ state: "attached", timeout });
133150
+ } catch (error3) {
133151
+ const page = root.page();
133152
+ if (error3 instanceof Error && error3.name === "TimeoutError" && page.url() !== "about:blank" && await page.evaluate('document.readyState !== "loading" && !!document.body').catch(() => false)) {
133153
+ throw new Error('The page loaded without the expected [data-sw-data] marker, which your app sets on the data view to "loading", "ready", or "error" as shown in `somewhere test --help`.');
133154
+ }
133155
+ throw error3;
133156
+ }
133076
133157
  await root.locator('[data-sw-data="loading"]').first().waitFor({ state: "detached", timeout }).catch(async () => {
133077
133158
  if (await root.locator('[data-sw-data="loading"]').count())
133078
133159
  throw new Error(`dataReady: a data view was still loading after ${timeout / 1e3} s`);
@@ -133095,6 +133176,7 @@ var init_app_test = __esm({
133095
133176
  init_test_diagnostics();
133096
133177
  init_test_timeline();
133097
133178
  __name(launchOptions, "launchOptions");
133179
+ __name(describeCheckFailure, "describeCheckFailure");
133098
133180
  __name(pageState, "pageState");
133099
133181
  __name(clientOf, "clientOf");
133100
133182
  __name(undeployedChanges, "undeployedChanges");
@@ -133268,19 +133350,26 @@ var init_app_test = __esm({
133268
133350
  }
133269
133351
  return result;
133270
133352
  }
133271
- /** Run one named check. The first failure stops the run: it prints the check, the error and
133272
- * what each signed-in page shows (URL, visible error text), and every later check is skipped
133273
- * instead of waiting out its own timeout. `somewhere test --failed` reruns a failed script whole,
133274
- * so setup done inside earlier checks runs again. */
133275
- async check(label, work) {
133353
+ /** Run one named check unless its prerequisite did not pass. Use at() inside a
133354
+ * check that has several steps. `somewhere test --failed` reruns the whole script. */
133355
+ async check(label, work, options2 = {}) {
133276
133356
  const name = scrub(label);
133277
133357
  if (this.stopped) {
133278
133358
  this.checks.push({ name, ok: false, ms: 0, skipped: "after-failure" });
133279
133359
  return false;
133280
133360
  }
133361
+ if (options2.requires && !options2.requires.passed) {
133362
+ this.checks.push({ name, ok: false, ms: 0, skipped: "prerequisite", error: `Requires \u201C${scrub(options2.requires.name)}\u201D, which did not pass.` });
133363
+ return false;
133364
+ }
133281
133365
  const start = performance.now();
133366
+ let step2 = label;
133367
+ let evidence;
133282
133368
  try {
133283
- await work();
133369
+ await work((current, artifact) => {
133370
+ step2 = current;
133371
+ evidence = artifact;
133372
+ });
133284
133373
  this.checks.push({ name, ok: true, ms: Math.round(performance.now() - start) });
133285
133374
  return true;
133286
133375
  } catch (error3) {
@@ -133291,14 +133380,12 @@ var init_app_test = __esm({
133291
133380
  await this.rememberPageSecrets();
133292
133381
  const pages = await Promise.all([...this.host.pages].map(pageState));
133293
133382
  const stopped = [...this.host.pages].map((page) => browserStoppedMessage(page, error3)).find(Boolean);
133294
- const message3 = stopped ?? scrub((error3 instanceof Error ? error3.message.split("\n").slice(0, 6).join("\n") : String(error3)) + pages.map((state, i) => `
133295
- page ${i + 1}: ${state}`).join(""));
133296
- this.checks.push({ name, ok: false, ms: Math.round(performance.now() - start), error: message3 });
133297
- this.stopped = true;
133298
- process.stdout.write(`FAIL ${name}
133299
- ${message3.replaceAll("\n", "\n ")}
133300
- Stopping here: later checks are skipped. After a fix, rerun the scripts that failed: ${TEST_COMMAND} --failed
133301
- `);
133383
+ const message3 = stopped ?? scrub(error3 instanceof Error ? error3.message : String(error3));
133384
+ const failure = describeCheckFailure(message3, options2.expected ?? name, step2, evidence, [...this.host.pages].find((page) => !page.isClosed())?.url() ?? this.origin);
133385
+ const detail = message3.split("\n").slice(0, 12).join("\n") + pages.map((state, i) => `
133386
+ page ${i + 1}: ${state}`).join("");
133387
+ this.checks.push({ name, ok: false, ms: Math.round(performance.now() - start), error: detail, failure });
133388
+ this.stopped = process.env.SW_TEST_FAIL_FAST === "1";
133302
133389
  return false;
133303
133390
  }
133304
133391
  }
@@ -133350,6 +133437,11 @@ Stopping here: later checks are skipped. After a fix, rerun the scripts that fai
133350
133437
  await this.control.close();
133351
133438
  if (cleanup.length)
133352
133439
  this.checks.push({ name: "cleanup of sign-up accounts", ok: false, ms: 0, error: cleanup.join("; ") });
133440
+ for (const check2 of this.checks) {
133441
+ if (!check2.ok && !check2.skipped && !check2.failure) {
133442
+ check2.failure = describeCheckFailure(check2.error ?? "", check2.name, check2.name, this.origin);
133443
+ }
133444
+ }
133353
133445
  const passed = this.checks.filter((check2) => check2.ok).length;
133354
133446
  const failed = this.checks.filter((check2) => !check2.ok && !check2.skipped).length;
133355
133447
  mkdirSync20(dirname15(this.resultsPath), { recursive: true });
@@ -133365,7 +133457,10 @@ Stopping here: later checks are skipped. After a fix, rerun the scripts that fai
133365
133457
  failed,
133366
133458
  checks: this.checks.map((check2) => ({ ...check2, ...check2.error ? { error: scrub(check2.error) } : {} }))
133367
133459
  }, null, 2) + "\n");
133368
- const reported = this.checks.map((check2) => ({ name: scrub(check2.name), ok: check2.ok, ...check2.skipped ? { skipped: check2.skipped } : {}, ...check2.error ? { error: scrub(check2.error) } : {} }));
133460
+ const reported = this.checks.map(({ ms: ms2, ...check2 }) => ({
133461
+ ...check2,
133462
+ ...check2.error ? { error: scrub(check2.error) } : {}
133463
+ }));
133369
133464
  const resultFile = relative14(this.root, this.resultsPath);
133370
133465
  const handOver = process.env.SW_TEST_REPORT;
133371
133466
  if (handOver)