@somewhere-cloud/cli 0.38.150 → 0.38.152

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.
@@ -42604,7 +42604,8 @@ var init_client = __esm({
42604
42604
  method,
42605
42605
  headers,
42606
42606
  body: reqBody,
42607
- signal: AbortSignal.timeout(timeoutMs)
42607
+ signal: AbortSignal.timeout(timeoutMs),
42608
+ ...opts?.redirect ? { redirect: opts.redirect } : {}
42608
42609
  }, timeoutMs);
42609
42610
  } catch (err) {
42610
42611
  const cause = err.cause;
@@ -43507,7 +43508,7 @@ var FIRST_CLI_PERMISSION;
43507
43508
  var init_first_cli_permission = __esm({
43508
43509
  "dist/lib/first-cli-permission.js"() {
43509
43510
  "use strict";
43510
- FIRST_CLI_PERMISSION = "Before your first Somewhere command for a user, ask their permission and say where it will run, either as an npm package in your own cloud workspace (nothing installs on their computer) or as an npm package on their machine. Approval in their first message covers this.";
43511
+ FIRST_CLI_PERMISSION = "Ask before destructive or paid actions unless the user already authorized them.";
43511
43512
  }
43512
43513
  });
43513
43514
 
@@ -44092,236 +44093,65 @@ var init_skills_pack = __esm({
44092
44093
  });
44093
44094
 
44094
44095
  // dist/lib/init-agent-guide.js
44095
- var AGENT_WORKFLOW, SKILLS_POINTER, PORTABILITY_POINTER, MCP_POINTER, PREVIEW_POINTER, TEST_ACCESS_RULES, INIT_AGENTS_MD, INIT_CLAUDE_MD;
44096
+ var AGENT_WORKFLOW, SKILLS_POINTER, PORTABILITY_POINTER, MCP_POINTER, PREVIEW_POINTER, INIT_AGENTS_MD, INIT_CLAUDE_MD;
44096
44097
  var init_init_agent_guide = __esm({
44097
44098
  "dist/lib/init-agent-guide.js"() {
44098
44099
  "use strict";
44099
- init_first_cli_permission();
44100
44100
  init_skills_pack();
44101
44101
  AGENT_WORKFLOW = `## Build, deploy, test
44102
44102
 
44103
- Enough to start a typical app: declare access and use the browser client; docs are for exceptions.
44104
-
44105
- | Requirement | Declaration below |
44103
+ | Does your app verify emails? | Choose the declared access rule |
44106
44104
  | --- | --- |
44107
- | Each user sees only their own rows | notes: owner() |
44108
- | Team: owner invites members; members read/write; creator or team owner deletes | tasks: anyOf(owner(), group()); sw.groups endpoints below |
44109
- | Owner/staff record with staff-only child notes | tickets: owner() or appRole(); parent() thread; staff-only notes; staff by verified emailDomain (or grantableBy) |
44110
- | Public pages from private drafts | pages: conditional publicRead |
44111
- | Share one record read-only | shared_notes/note_shares: read-only grant() |
44112
-
44113
- db/schema.ts is declaration only: imports, constants/spreads, default schema;
44114
- no helpers/expressions. id() is random text; owner() stamps user_id. client.read
44115
- includes the key. Inside anyOf(), owner() takes only column/read: it stamps the
44116
- creator, not create/delete options; group() gates placement (non-member create is
44117
- refused); inside anyOf an operation missing from roles allows no group role. Other fields: timestamp({ default: 'now' }), text({ nullable: true });
44118
- indexes: [['team_id']].
44119
-
44120
- \`\`\`ts
44121
- import { schema, table, id, text, owner, group, anyOf, parent, appRole, boolean, grant } from 'somewhere/db';
44122
- export default schema({
44123
- notes: table({ id: id(), title: text() }, { scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'], delete: true },
44124
- }),
44125
- tasks: table({ id: id(), team_id: text(), title: text() }, {
44126
- scope: anyOf(owner(), group({ column: 'team_id', roles: { read: ['owner', 'admin', 'member'],
44127
- create: ['owner', 'admin', 'member'], update: ['owner', 'admin', 'member'], delete: ['owner'] } })),
44128
- client: { read: ['id', 'team_id', 'title'], create: ['team_id', 'title'], update: ['title'], delete: true },
44129
- }),
44130
- tickets: table({ id: id(), subject: text() }, {
44131
- scope: anyOf(owner(), appRole({ roles: { read: ['staff'], create: ['staff'], update: ['staff'] } })),
44132
- client: { read: true, create: ['subject'], update: ['subject'] },
44133
- }),
44134
- messages: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {
44135
- scope: parent({ via: 'ticket_id' }),
44136
- client: { read: true, create: ['ticket_id', 'body'] },
44137
- }),
44138
- staff_notes: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {
44139
- scope: appRole({ roles: { read: ['staff'], create: ['staff'] } }),
44140
- client: { read: true, create: ['ticket_id', 'body'] },
44141
- }),
44142
- pages: table({ id: id(), title: text(), published: boolean({ default: false }) }, {
44143
- scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'],
44144
- publicRead: { where: { published: true } } },
44145
- }),
44146
- note_shares: table({ id: id(), grantee_id: text(), note_id: text({ references: 'shared_notes', onDelete: 'cascade' }) }, {
44147
- scope: owner(), unique: [['note_id', 'grantee_id']],
44148
- }),
44149
- shared_notes: table({ id: id(), title: text() }, {
44150
- scope: anyOf(owner(), grant({ table: 'note_shares', grantee: 'grantee_id', row: 'note_id', operations: ['read'] })),
44151
- client: { read: ['id', 'title'], create: ['title'], update: ['title'] },
44152
- }),
44153
- }, { appRoles: { staff: { emailDomain: 'staff.example' } } });
44154
- \`\`\`
44155
-
44156
- Who is staff is your app's decision; the platform enforces what the role may do.
44157
- First choice, as above: emailDomain. The role holds once the person verifies an address
44158
- at that domain; no grant code. An email ending alone proves nothing: anyone can sign up
44159
- as anyone@your-domain without owning that mailbox. Without verification, grant only from
44160
- something the visitor cannot choose, such as an invitation your app issued, checked inside
44161
- the sign-up route: single use, bound to one account, its link delivered only to that person:
44162
- somewhere docs sw.auth --section server-assigned-app-roles-setroles.
44163
- messages use parent(): owner() would hide staff replies from the customer.
44164
- A staff reply is a messages row, and creating a parent() child needs create on the parent
44165
- for that person: its owner, or a role listed under the parent's create. Read or update is
44166
- not enough. So tickets lists create: ['staff']; without it every staff reply is refused
44167
- (403 POLICY_AUTHORITY_REQUIRED).
44168
- Publish pages in an owner-checked endpoint. Share with caller-scoped
44169
- sw.db.insert('note_shares', { grantee_id, note_id }); it checks row ownership.
44170
- Browser calls THROW, not { error }; catch below.
44171
- Browser list: paginate with after. Sort locally or in an endpoint.
44172
-
44173
- \`\`\`ts
44174
- import { data } from 'somewhere:data';
44175
- export async function save(title: string) {
44176
- try { await data.notes.create({ title }); return null; }
44177
- catch (e) { return e instanceof Error ? e.message : 'Save failed'; }
44178
- }
44179
- export const list = (after?: string) => data.notes.list({ limit: 100, after });
44180
- \`\`\`
44105
+ | Yes, invited teams | Use \`group()\` and \`sw.groups\` for invitations, membership and owner/admin permissions. See \`somewhere docs sw.groups --section team-example\`. |
44106
+ | No, app-managed teams | Use \`member()\` over a server-only roster. Declare author-or-team-owner delete with \`anyOf()\` and a role-filtered branch. See \`somewhere docs declared-data --section teams-without-email-verification\`. |
44107
+ | Yes, staff by domain | Use \`appRole()\` and \`appRoles: { staff: { emailDomain: 'staff.example' } }\`. The address must be verified. |
44108
+ | No, staff by invitation | Use \`appRole()\` and \`assignedBy: 'server'\`. Redeem an app-issued invitation and call \`sw.auth.server.setRoles\` inside the sign-up route. See \`somewhere docs sw.auth --section server-assigned-app-roles-setroles\`. |
44109
+ | Either, personal rows | Use \`owner()\`. The platform stamps the owner from the signed-in user. |
44110
+ | Either, shared private row | Use a read-only \`grant()\` for a known app-user ID. Share by address only after verification. Adding the grant widens existing caller-scoped reads. See \`somewhere docs declared-data --section read-only-sharing-without-email-verification\`. |
44111
+ | Either, public pages from private drafts | Use conditional \`client.publicRead\`. Anonymous results can be cached for up to 120 seconds. For fresh pages, read with \`sw.db.server.from\` in a page handler, filter for published rows, select public fields, and set \`Cache-Control: no-store\`. |
44181
44112
 
44182
- A page that needs several reads: start them together and show it once every read it depends on has answered.
44183
- Keep an input disabled until the data it depends on has loaded, including who the user is.
44184
- Never let a late answer overwrite what the user typed: fill an input from loaded data only before it is enabled.
44185
-
44186
- Teams are built-in groups: the platform keeps the team, invitations, roster, removal,
44187
- leaving, last owner. Starting a team needs a signed-in user; joining needs a verified
44188
- email (a password sign-up joins once it enters its emailed code).
44189
- No email verification in your app: keep membership in your own table with member() (somewhere docs sw.groups --section relationships-that-are-not-teams) and assign staff with setRoles in the sign-up route (above).
44190
- The browser cannot call
44191
- sw.groups: pass each call through an endpoint. A parent() child's delete follows the task
44192
- (creator or team owner), so "comment author or team owner deletes" is an endpoint.
44193
- Staff making others staff: appRoles { staff: { grantableBy: ['staff'] } } and
44194
- sw.groups.appRoles.grant(request, userId, 'staff') in an endpoint (never to oneself).
44195
- Complete apps and specs: somewhere docs sw.groups --section team-example or staff-example.
44196
-
44197
- \`\`\`ts
44198
- // api/teams.ts \u2014 GET my teams (completes invitations to me); POST starts one I own
44199
- const refusal = (e: { code: string; message: string; status: number }) =>
44200
- Response.json({ error: e.code, message: e.message }, { status: e.status });
44201
- export const GET = sw.endpoint({ auth: 'required', handler: async ({ request }, sw) => {
44202
- const page = await sw.groups.list(request, { limit: 100 });
44203
- return page.error ? refusal(page.error) : { teams: page.data.items, next_cursor: page.data.next_cursor };
44204
- } });
44205
- export default sw.endpoint({ auth: 'required', body: { name: 'string' }, handler: async ({ request, body }, sw) => {
44206
- const made = await sw.groups.create(request, { name: body.name });
44207
- return made.error ? refusal(made.error) : { id: made.data.id };
44208
- } });
44209
- \`\`\`
44113
+ ### Schema and data
44210
44114
 
44211
- \`\`\`ts
44212
- // api/teams/[id]/invitations.ts \u2014 owners invite; others 403; a member's address 409 ALREADY_MEMBER
44213
- export default sw.endpoint({ auth: 'required', body: { email: 'string' }, handler: async ({ request, params, body }, sw) => {
44214
- const sent = await sw.groups.invite(request, params.id, { email: body.email, role: 'member', redirect_uri: '/' });
44215
- return sent.error ? Response.json({ error: sent.error.code }, { status: sent.error.status }) : { delivery: sent.data.delivery };
44216
- } });
44217
- \`\`\`
44115
+ Declare tables in \`db/schema.ts\` with imports, literal values, constants and spreads.
44116
+ New \`id()\` keys are text. Reference them with \`text({ references: 'table_name' })\`.
44117
+ Existing integer IDs stay integers. Declare composite uniqueness with \`unique: [['a', 'b']]\`.
44218
44118
 
44219
- Same shape: sw.groups.get/members(request, id), remove(request, id, userId), leave(request, id)
44220
- (last owner: 409 LAST_OWNER), delete(request, id) by owners.
44119
+ - Browser reads and writes use generated \`somewhere:data\`. \`client\` sets allowed operations and fields. Include the key in explicit read lists. Browser calls throw errors, and list pages use the returned \`next\` as \`after\` (at most 100 rows per page).
44120
+ - \`anyOf()\` grants access through either branch. \`allOf()\` requires both the membership gate and the action rule. \`parent()\` inherits the parent row's access. To let a child author update or delete, declare \`parent({ author, update, delete })\`. It evaluates the child author and the parent operation separately. For staff replies through \`parent()\`, grant staff create permission on the ticket's rule. See \`somewhere docs declared-data --section comments-that-their-author-may-edit\`.
44121
+ - \`sw.db.from/insert/update/remove\` apply the caller's scope and return \`{ data, count, changes }\`. Use \`where\`, \`columns\`, \`order\`, \`limit\` and \`offset\` for server reads. \`sw.db.tx\` takes an array of write intents. Supply related IDs up front.
44122
+ - Authorize before \`sw.db.server\` calls, which bypass the caller's scope. Keep declared scopes on records users work with, even when an exceptional write needs server authority. Use \`serverOnly()\` for protected ledgers and job state. Raw SQL uses a separate raw database.
44123
+ - For booking and help desk schemas, see \`somewhere docs sw.db --section provider-or-booker-and-owner-or-staff-recipes\`. For browser paging, server paging and transactions, see \`somewhere docs sw.db\`.
44221
44124
 
44222
- Do not hand-write access to app-read/write data: declare who may read/write it.
44223
- serverOnly() fits job/import/audit/counter state.
44224
- Grant ledgers use owner() without browser writes. Undeclarable: arbitrary predicates
44225
- (e.g. expiry) or per-role writable fields (split tables or check that write).
44125
+ Use \`client.intake\` for public submissions to a private parent row. See
44126
+ \`somewhere docs declared-data\` for intake, scoped writes and related rows.
44226
44127
 
44227
- Build src/pages/HomePage.tsx; routes src/App.tsx + src/routes.ts; auth src/auth/hooks.ts.
44228
- Auth is wired: keep api/auth/[...path].ts; src/config.ts controls providers.
44229
- api/notes/[id]/sub.ts \u2192 params.id; underscore files are helpers. POST: default export;
44230
- GET/DELETE: named exports.
44128
+ ### Routes and auth
44231
44129
 
44232
- \`\`\`ts
44233
- export const GET = sw.endpoint({ auth: 'required', handler: async (_, sw) => sw.db.from('notes', { limit: 100 }) });
44234
- \`\`\`
44130
+ - \`src/App.tsx\` and \`src/routes.ts\` route React pages. \`api/notes/[id].ts\` serves \`/api/notes/:id\`. A root \`[...path].ts\` handles document routes, including \`/\`. Underscore-prefixed files are import-only helpers.
44131
+ - JSON routes use \`sw.endpoint({ auth, body, rateLimit, handler })\`. Set \`auth\` to \`'required'\`, \`'optional'\` or \`'none'\`. Use a limit like \`'30/minute'\`. Read route parameters from the handler's \`params\`. Use a default handler or named HTTP method exports. For streaming, webhooks or custom responses, use a bare \`(req, sw)\` handler and \`sw.params\`. See \`somewhere docs functions\`.
44132
+ - Keep \`api/auth/[...path].ts\` and extend the starter's \`src/auth/hooks.ts\`. Configure providers in \`src/config.ts\`. Gate private UI on auth state. Password sign-up starts unverified, and signed-in unverified users pass \`auth: 'required'\`. See \`somewhere docs auth-client\`.
44133
+ - Render a view when the reads it depends on finish. Keep inputs disabled until their initial data and identity are ready, and preserve edits when a late response arrives.
44134
+ - Browser requests use same-origin cookies. For scripted writes with a cookie session, send the app's origin in the \`Origin\` header. Use the CLI test helper to send data endpoint calls with the deployed contract digest.
44235
44135
 
44236
- sw.db applies caller scopes; sw.db.server bypasses them: authorize first.
44237
- Caller-scoped sw.db.insert needs no client.create grant: client limits only the browser.
44238
- Reads: from(table, { where, columns, order: [['id', 'asc']], limit, offset }).
44239
- Filter: { id: { in: ids } }; unique: [['a', 'b']] in schema.
44240
- Writes: insert(table, values), update(table, { where, set }), remove(table, { where }).
44241
- tx takes an ARRAY of write intents, never a callback; pre-generate related IDs.
44242
-
44243
- Browser: fetch(path, { method: 'POST', credentials: 'same-origin',
44244
- headers: { 'content-type': 'application/json' }, body: JSON.stringify(values) }).
44245
- Access cookies refresh automatically. Cookie-auth POST/PATCH/DELETE from scripts
44246
- need Origin equal to the app URL.
44247
-
44248
- After every deploy the platform checks the live app in its own browser: pages load signed out and as a
44249
- test user, a stranger and a signed-out visitor cannot read a person's data, and your saved checks pass.
44250
- Save each journey you want re-checked after every deploy as checks/<plain-name>.json; the platform runs them
44251
- in its browser after each deploy and \`somewhere test\` runs them now.
44252
- ${FIRST_CLI_PERMISSION}
44253
- Run them now: npx @somewhere-cloud/cli test (one PASS or FAIL line per check, failures first; exit 1 when one fails).
44254
- A saved check is the somewhere verify --flow actions list; "signed_in": true runs it as a test user the platform
44255
- creates and removes, and "viewports": ["desktop", "mobile"] runs it at both sizes:
44256
- { "actions": [ { "fill": "[data-testid=note-title]", "value": "Lunch with Ana 42" },
44257
- { "click": "[data-testid=note-save]" },
44258
- { "expect": { "selector": "[data-testid=note-item]", "text": "Lunch with Ana 42" } } ],
44259
- "signed_in": true, "viewports": ["desktop", "mobile"] }
44260
- Find controls by data-testid so renaming a button does not break a check; keep the ids when you restyle.
44261
- The notes starter ships this one as checks/add-a-note.json (note-title, note-save, note-item): start from it.
44262
- Open a list item by clicking the item element itself (what a person clicks), not a link inside it.
44263
- Deploy raw source, no frontend build; type errors stop upload.
44264
- The complete team spec, with removal and leaving: somewhere docs sw.groups --section team-example.
44265
- Diagnose with somewhere errors and somewhere logs.
44266
-
44267
- On demand:
44268
- - Server paging: \`somewhere docs sw.db --section server-read-paging\`
44269
-
44270
- ## Testing shared access
44271
-
44272
- With the team endpoints above, the owner invites a fixture by email; test users are verified,
44273
- so its next GET /api/teams shows the team. A test user who still owns a team is not deleted:
44274
- delete the team last (api/teams/[id].ts DELETE: sw.groups.delete). Group calls take
44275
- about a second, so raise the timeout:
44276
-
44277
- \`\`\`ts
44278
- // tests/team.spec.ts
44279
- import { test, expect } from '@somewhere-cloud/cli/testing';
44280
- test.describe.configure({ timeout: 90_000 });
44281
- test('owner invites a second user by email', async ({ newUser }) => {
44282
- const [owner, bob] = await Promise.all([newUser(), newUser()]);
44283
- const { id } = await (await owner.request.post('/api/teams', { data: { name: 'Shared team' } })).json();
44284
- expect((await owner.request.post(\`/api/teams/\${id}/invitations\`, { data: { email: bob.email } })).ok()).toBeTruthy();
44285
- const { teams } = await (await bob.request.get('/api/teams')).json();
44286
- expect(teams).toContainEqual(expect.objectContaining({ id, role: 'member' }));
44287
- expect((await owner.request.delete(\`/api/teams/\${id}\`)).status()).toBe(204);
44288
- });
44289
- \`\`\`
44290
- `;
44291
- SKILLS_POINTER = `Task-specific skills: \`${SKILLS_DIR}/\`. Inspect/update with somewhere skills status/update.`;
44292
- PORTABILITY_POINTER = "Data/code export limits: `somewhere docs portability`.";
44293
- MCP_POINTER = "Use this app from Claude as its signed-in user (MCP tools): `somewhere docs sw.endpoint --section mcp-tools-for-claude`.";
44294
- PREVIEW_POINTER = "somewhere preview runs your change on a copy of production data with its own sign-in: a preview starts with no users (sign up in it or `somewhere preview user-add`), its sign-in mail is captured (`somewhere preview mail`), and rows private to a production user stay hidden from preview users. Server user lookup, roles and built-in teams work in a preview (its own users, its own copy; team invitations are captured); jobs/cron handlers do not yet: check those in production after promoting (`somewhere docs dev-environments`). Test your change in the preview before you promote it: `somewhere test --preview`.";
44295
- TEST_ACCESS_RULES = `## Testing access rules
44136
+ ### Run and verify
44296
44137
 
44297
- In a linked test app, run \`somewhere test-users prepare alice bob\`. For an
44298
- owner() table with client create and read, create a fixture as Alice and read it
44299
- as both users:
44138
+ Run \`somewhere typecheck\` and focused tests. \`somewhere deploy-check\` checks compilation and schema without publishing. \`somewhere deploy\` uploads raw source directly to production. When testing changes with real users or data, use \`somewhere preview\`, test with \`somewhere test --preview\`, then promote. See \`somewhere docs dev-environments\`.
44300
44139
 
44301
- \`\`\`sh
44302
- ID=$(somewhere data create notes --as alice --values '{"title":"Access test"}' | jq -er 'select(.status == 200 and .kind == "ok") | .data.id') &&
44303
- somewhere data get notes --as alice --id "$ID" | jq -e '.status == 200 and .kind == "ok"' &&
44304
- somewhere data get notes --as bob --id "$ID" | jq -e '.status == 200 and .kind == "empty" and .data == null and .access == {"filtered":true}'
44305
- \`\`\`
44140
+ Save journeys in \`checks/<name>.json\`, using \`checks/add-a-note.json\` from the notes starter as a model. Keep test IDs when restyling and click the item a person would use. Set \`"signed_in": true\` for a test user and \`"viewports": ["desktop", "mobile"]\` to check both sizes. Saved checks run after deploy. Use \`somewhere test\` to rerun them and \`somewhere verify --flow flow.json\` for a focused journey. For shared access, test the owner, a recipient and an unrelated user separately. The team fixture is in \`somewhere docs sw.groups --section team-example\`. For schedules, trigger \`somewhere cron run <id> --wait\` before asserting its effects. Inspect failures with \`somewhere errors\` and \`somewhere logs\`.
44306
44141
 
44307
- 200 with access.filtered means the rule constrained the read, even when rows
44308
- are returned. 404 DATA_NOT_FOUND on update or delete hides whether the row
44309
- exists. 401 AUTH_REQUIRED needs a signed-in session. 403 names the access rule
44310
- or operation that refused the call. DATA_CONTRACT_* means the operation never
44311
- ran. Assert the exact outcome in handed-over tests and confirm a refused write
44312
- left the owner's fixture unchanged.
44142
+ Use \`somewhere docs <topic> --section <id>\` for one section or \`--full\` for all examples. Ask before destructive or paid actions unless the user already authorized them.
44313
44143
  `;
44144
+ SKILLS_POINTER = `Task-specific skills: \`${SKILLS_DIR}/\`. Inspect/update with somewhere skills status/update.`;
44145
+ PORTABILITY_POINTER = "Data/code export limits: `somewhere docs portability`.";
44146
+ MCP_POINTER = "App MCP tools: `somewhere docs app-mcp`.";
44147
+ PREVIEW_POINTER = "Preview users are separate from live users. Sign up in the preview or use `somewhere preview user-add`. Check captured mail with `somewhere preview mail`.";
44314
44148
  INIT_AGENTS_MD = `# somewhere.cloud project contract
44315
- ${FIRST_CLI_PERMISSION}
44316
-
44149
+ ${AGENT_WORKFLOW}
44317
44150
  ${SKILLS_POINTER}
44151
+ Without a global CLI, use \`npx @somewhere-cloud/cli deploy\` and \`npx @somewhere-cloud/cli test\`.
44318
44152
 
44319
- Build your app. Deploy the raw source and run its tests: \`npx @somewhere-cloud/cli deploy && npx @somewhere-cloud/cli test\`.
44153
+ For a signed-in browser test, wait for the SDK's expected \`data-sw-auth\` state when available. See \`somewhere docs auth-client --section wait-for-auth-in-a-browser-test\`. For direct data checks, prepare fixture users with \`somewhere test-users prepare alice bob\`, then call \`somewhere data get notes --as alice --id <id>\` as each user. Assert the exact outcome. See \`somewhere docs test --section testing-access-rules\`.
44320
44154
 
44321
- For an app with sign-in, keep the starter's auth gate. Render private UI only after the session is confirmed. Keep the pending and retry views. In a browser test wait for the expected screen; if the SDK publishes \`data-sw-auth\` on \`<html>\`, first wait for the expected sign-in state there.
44322
-
44323
- ${AGENT_WORKFLOW}
44324
- ${TEST_ACCESS_RULES}
44325
44155
  ${PORTABILITY_POINTER}
44326
44156
  ${MCP_POINTER}
44327
44157
  ${PREVIEW_POINTER}
@@ -44669,8 +44499,8 @@ var init_skills_pack_generated = __esm({
44669
44499
  BUNDLED_SKILLS_PACK = {
44670
44500
  "schema": 1,
44671
44501
  "name": "somewhere-skills",
44672
- "version": "1+c727c92e8193",
44673
- "sha256": "c727c92e81938d2e7cbf125de17c4d8a6feef4cf5bc4530f173f6dc04fe0da3e",
44502
+ "version": "1+30e51d444ef2",
44503
+ "sha256": "30e51d444ef28d9ad6eda0999739679f9fe13e9a102b8d908044694378bbfc96",
44674
44504
  "files": [
44675
44505
  {
44676
44506
  "path": "adopt/SKILL.md",
@@ -44679,18 +44509,18 @@ var init_skills_pack_generated = __esm({
44679
44509
  },
44680
44510
  {
44681
44511
  "path": "deploy-verify-loop/SKILL.md",
44682
- "sha256": "b394c2944cd64a48517dff6c80917b0e9332758f429e96600587ca91e4e951f8",
44683
- "content": '---\nname: deploy-verify-loop\ndescription: After edits, typecheck and run focused tests; verify the final deployed journey and rerun after relevant fixes.\n---\n\n# Deploy, verify, read the failure\n\n## The loop\n\nBefore your first Somewhere command for a user, ask their permission and say where it will run, either as an npm package in your own cloud workspace (nothing installs on their computer) or as an npm package on their machine. Approval in their first message covers this.\n\n```bash\nsomewhere typecheck\nsomewhere deploy\n```\n\nDon\'t bundle the source yourself; the platform runs the frontend build.\n\nRun `somewhere claim` and open its link to keep a temporary app.\n\n```bash\nsomewhere deploy-check --run /api/hello -X POST -d \'{"name":"Ada"}\'\n```\n\n| Step | Command | What it tells you |\n|---|---|---|\n| Verify | `somewhere verify [--flow flow.json]` | Runs the live app at desktop and phone sizes: named steps, console/network health, both screenshots. |\n| Inspect | `somewhere browser [target]` | One page: screenshot, snapshot, DOM, network, or an evaluated expression. |\n| Diagnose | `somewhere logs --tail 10`, `somewhere errors` | Recent function output, then failures split into refused and exception. `errors` also works on a temporary project. |\n\n## A flow for verify --flow\n\n```json\n{ "actions": [{ "fill": "#title", "value": "Verify entry" }, { "fill": "#from_email", "value": "v@example.com" },\n { "click": "#send" }, { "expect": { "selector": "#status", "text": "Received" } }], "viewports": ["desktop"] }\n```\n\n`passed` requires successful steps and request expectations, no page errors, and no unexpected failed requests. It can be false even when every step succeeded.\n\n## Failure 1: the live site still shows the old version\n\nBrowser or CDN cache. Hard-reload (Cmd-Shift-R), or check with `curl -sI https://{subdomain}.somewhere.site`.\n\n## Failure 2: a route fails\n\nShow recent failures with a `kind` column: **refused** for a 4xx your own handler returned on purpose, **exception** for an uncaught throw or a 5xx.\n\nThe `stack` field is the single most useful field for debugging \u2014 it tells you the exact file + line in your code where the throw originated.\n\n| `somewhere rollback [project]` | `-y, --yes`, `--json` | Select the previous retained production release. By default this changes code without restoring data. |\n\nSources (`somewhere docs <topic>`): browser, cli, common-mistakes, deploy, getting-started, recipe-signed-in-app, troubleshooting.\n'
44512
+ "sha256": "a8d6850065722efe3098ed54008d22066d8274338b037758d0d8490df7e68986",
44513
+ "content": '---\nname: deploy-verify-loop\ndescription: After edits, typecheck and run focused tests; verify the final deployed journey and rerun after relevant fixes.\n---\n\n# Deploy, verify, read the failure\n\n## The loop\n\nAsk before destructive or paid actions unless the user already authorized them.\n\n```bash\nnpx somewhere typecheck\nnpx somewhere deploy\n```\n\nDon\'t bundle the source yourself; the platform runs the frontend build.\n\nRun `somewhere claim` and open its link to keep a temporary app.\n\n```bash\nsomewhere deploy-check --run /api/hello -X POST -d \'{"name":"Ada"}\'\n```\n\n| Step | Command | What it tells you |\n|---|---|---|\n| Verify | `somewhere verify [--flow flow.json]` | Runs the live app at desktop and phone sizes: named steps, console/network health, both screenshots. |\n| Inspect | `somewhere browser [target]` | One page: screenshot, snapshot, DOM, network, or an evaluated expression. |\n| Diagnose | `somewhere logs --tail 10`, `somewhere errors` | Recent function output, then failures split into refused and exception. `errors` also works on a temporary project. |\n\n## A flow for verify --flow\n\n```json\n{ "actions": [{ "fill": "#title", "value": "Verify entry" }, { "fill": "#from_email", "value": "v@example.com" },\n { "click": "#send" }, { "expect": { "selector": "#status", "text": "Received" } }], "viewports": ["desktop"] }\n```\n\n`passed` requires successful steps and request expectations, no page errors, and no unexpected failed requests. It can be false even when every step succeeded.\n\n## Failure 1: the live site still shows the old version\n\nBrowser or CDN cache. Hard-reload (Cmd-Shift-R), or check with `curl -sI https://{subdomain}.somewhere.site`.\n\n## Failure 2: a route fails\n\nShow recent failures with a `kind` column: **refused** for a 4xx your own handler returned on purpose, **exception** for an uncaught throw or a 5xx.\n\nThe `stack` field is the single most useful field for debugging \u2014 it tells you the exact file + line in your code where the throw originated.\n\n| `somewhere rollback [project]` | `-y, --yes`, `--json` | Select the previous retained production release. By default this changes code without restoring data. |\n\nSources (`somewhere docs <topic>`): browser, cli, common-mistakes, deploy, getting-started, recipe-signed-in-app, troubleshooting.\n'
44684
44514
  },
44685
44515
  {
44686
44516
  "path": "schema-changes/SKILL.md",
44687
- "sha256": "ab5a21715672de983d2bb1ed19822563a8d94fad936b2424f3653c0c087642b2",
44688
- "content": "---\nname: schema-changes\ndescription: Before adding, changing, or removing a table or column in db/schema.ts.\n---\n\n# Change the database schema safely\n\n## The file is the contract\n\nThe default `somewhere init` starter has no `db/schema.ts`: create it at the project root, or run `somewhere init --name my-app --features private-data` to start with a schema.\n\n```ts\n// db/schema.ts\nimport { id, owner, schema, table, text, timestamp } from 'somewhere/db';\n\nexport default schema({\n notes: table(\n {\n id: id(),\n title: text(),\n body: text({ default: '' }),\n created_at: timestamp({ default: 'now' }),\n },\n {\n scope: owner(),\n client: {\n read: ['id', 'title', 'body', 'created_at'],\n create: ['title', 'body'],\n update: ['title', 'body'],\n delete: true,\n },\n },\n ),\n});\n```\n\nA table without a `client` block can't be reached from the browser at all.\n\nBefore the first deploy, delete an unused starter table declaration outright: there is no deployed table to retire. After a table has been deployed, mark it `removedTable()` to retire it with 30-day data retention, including when the table is empty.\n\nRun `somewhere typecheck` before deploying schema changes.\n\n## What a deploy does with it\n\n- **Additive changes apply**: a new table, a new nullable-or-defaulted column, a new index, a new unique group. Unchanged schema is a no-op.\n- **Unmarked removals and shape changes refuse** with `409 SCHEMA_DEPLOY_REFUSED` and a message naming the change.\n- **Access-rule changes apply in place**: a later deploy can change an existing table's scope, and its rows stay.\n- a production deploy or a promotion that would remove or rename a column is refused before anything changes, so a running release never loses a column it uses. Keep the column declared and leave its data in place.\n\n## Failure: raw SQL refused after the schema file deploys\n\nOn an older shared database, ordinary `sw.db.query` / `sw.db.batch` fail before transport with `MANAGED_RAW_SQL_REQUIRES_SERVER_AUTHORITY`, including in job, queue, and cron handlers; with a separate SQL database they run there and never see declared tables. Fix: write with `sw.db.insert` / `sw.db.update` / `sw.db.remove` (the table needs a declared intent)\n\nSources (`somewhere docs <topic>`): declared-data, getting-started, sw.db, troubleshooting.\n"
44517
+ "sha256": "3b74e0482260cc6673f12a2d5105950357dab8d0d9960fd5de8a3f54a153faef",
44518
+ "content": "---\nname: schema-changes\ndescription: Before adding, changing, or removing a table or column in db/schema.ts.\n---\n\n# Change the database schema safely\n\n## The file is the contract\n\nThe default `somewhere init` starter has no `db/schema.ts`: create it at the project root, or run `somewhere init --name my-app --features private-data` to start with a schema.\n\n```ts\n// db/schema.ts\nimport { id, owner, schema, table, text, timestamp } from 'somewhere/db';\n\nexport default schema({\n notes: table(\n {\n id: id(),\n title: text(),\n body: text({ default: '' }),\n created_at: timestamp({ default: 'now' }),\n },\n {\n scope: owner(),\n client: {\n read: ['id', 'title', 'body', 'created_at'],\n create: ['title', 'body'],\n update: ['title', 'body'],\n delete: true,\n },\n },\n ),\n});\n```\n\nA table without a `client` block can't be reached from the browser at all.\n\nDelete a never-deployed starter table's declaration and references. A `removedTable()` marker for it is a no-op. **Removing a table** is `old_table: removedTable()`. The deploy keeps the table while your previous version is still serving; once the new version is live it retires the table and keeps its data for 30 days.\n\nRun `somewhere typecheck` before deploying schema changes.\n\n## What a deploy does with it\n\n- **Additive changes apply**: a new table, a new nullable-or-defaulted column, a new index, a new unique group. Unchanged schema is a no-op.\n- **Unmarked removals and shape changes refuse** with `409 SCHEMA_DEPLOY_REFUSED` and a message naming the change.\n- **Access-rule changes apply in place**: a later deploy can change an existing table's scope, and its rows stay.\n- a production deploy or a promotion that would remove or rename a column is refused before anything changes, so a running release never loses a column it uses. Keep the column declared and leave its data in place.\n\n## Failure: raw SQL refused after the schema file deploys\n\nOn an older shared database, ordinary `sw.db.query` / `sw.db.batch` fail before transport with `MANAGED_RAW_SQL_REQUIRES_SERVER_AUTHORITY`, including in job, queue, and cron handlers; with a separate SQL database they run there and never see declared tables. Fix: write with `sw.db.insert` / `sw.db.update` / `sw.db.remove` (the table needs a declared intent)\n\nSources (`somewhere docs <topic>`): declared-data, getting-started, sw.db, troubleshooting.\n"
44689
44519
  },
44690
44520
  {
44691
44521
  "path": "sign-in-setup/SKILL.md",
44692
- "sha256": "ffc4f29eb96c0a18c5ea0ce10308f696f227ec842c37e0bd70951b2284d885ba",
44693
- "content": "---\nname: sign-in-setup\ndescription: When the app needs users to sign up, sign in, or sign out.\n---\n\n# Set up sign-in\n\n## Server: one route file\n\n`login` / `signup` are developer-key-gated (the browser can't call them), so one server route mediates them and sets the session cookies.\n\n```ts\n// api/auth/[...path].ts\nexport { somewhereAuth as default } from '@somewhere-cloud/sdk/server';\n```\n\nIt serves `POST /signup`, `/login`, `/logout`, `/magic-link`, `/magic-link/verify`, `GET /me`, and the Google/GitHub/Discord `GET /<provider>-url` + `POST /<provider>` code exchange, and `POST /mfa/challenge`, the email sign-in code step: in the page, `auth.completeMfa({ code })` finishes a sign-in that rejected with code `MFA_REQUIRED` (`sw.auth` \u2192 `email-sign-in-codes`).\n\n## Client and React state reference\n\nRead `docs({ topic: 'auth-client', section: 'react-auth-state' })` for the SDK's React state contract. Extend the starter's existing provider and auth client.\n\n## Page: the SDK client\n\n```bash\nnpm i @somewhere-cloud/sdk\n```\n\n```ts\n// src/auth.ts \u2014 page code\nimport { createSomewhereAuth } from '@somewhere-cloud/sdk/auth'\n\nexport const auth = createSomewhereAuth()\n\n// Call from your sign-up form; throws AuthError with the message on failure.\nexport async function signUp(email: string, password: string) {\n await auth.signUp({ email, password }) // or auth.signIn({ email, password })\n return auth.getUser() // the signed-in user, or null\n}\nexport async function signOut() {\n await auth.signOut();\n if (auth.getState().signOutUnconfirmed) {\n throw new Error('Sign-out could not be confirmed. Please try again.');\n }\n // Only navigate or reload after confirmed logout.\n}\n```\n\nAwait `signOut()` in the click handler before navigating or reloading. While it is pending, keep the current screen or show a disabled signing-out state. Do not use the appearance of a signed-out form as proof that the server session has ended. After awaiting, check `auth.getState().signOutUnconfirmed`; show a retry message when true. `signOut()` can settle without confirming server logout.\n\nCalls to your own `api/*` functions just send `credentials: 'include'`.\n\nDon't write `getCookie()` / token-parsing helpers \u2192 `sw.auth.fromRequest(req)` reads cookie + Bearer header and returns the validated user (or null) in one call.\n\nMail to `<name>@<project>.test.somewhere.site` is read with `somewhere email test-inbox <address>`.\n\n## Failure 1: sign-in errors\n\nexpected failures (wrong password, duplicate email, weak password) come back as structured 4xx with the real message, never an opaque 500.\n\n## Failure 2: AUTH_REQUIRED from an owner() table\n\nThe table is user-owned, so the platform scopes it to a principal, and this request had none: there is no signed-in user, and this table does not declare `owner({ visitors: true })`, which is the declaration that accepts a stable anonymous visitor identity.\n\nSources (`somewhere docs <topic>`): auth-client, common-mistakes, recipe-signed-in-app, sdk, troubleshooting.\n"
44522
+ "sha256": "c0c2095f24ced94d6457389d4943b79cc101cc66adc60b23114944e3a64a0d71",
44523
+ "content": "---\nname: sign-in-setup\ndescription: When the app needs users to sign up, sign in, or sign out.\n---\n\n# Set up sign-in\n\n## Server: one route file\n\n`login` / `signup` are developer-key-gated (the browser can't call them), so one server route mediates them and sets the session cookies.\n\n```ts\n// api/auth/[...path].ts\nexport { somewhereAuth as default } from '@somewhere-cloud/sdk/server';\n```\n\nIt serves `POST /signup`, `/login`, `/logout`, `/magic-link`, `/magic-link/verify`, `GET /me`, and the Google/GitHub/Discord `GET /<provider>-url` + `POST /<provider>` code exchange, and `POST /mfa/challenge`, the email sign-in code step: in the page, `auth.completeMfa({ code })` finishes a sign-in that rejected with code `MFA_REQUIRED` (`sw.auth` \u2192 `email-sign-in-codes`).\n\n## Client and React state reference\n\nRead `docs({ topic: 'auth-client', section: 'react-auth-state' })` for the SDK's React state contract. Extend the starter's existing provider and auth client.\n\n## Page: the SDK client\n\n```bash\nnpm i @somewhere-cloud/sdk\n```\n\n```ts\n// src/auth.ts \u2014 page code\nimport { createSomewhereAuth } from '@somewhere-cloud/sdk/auth'\n\nexport const auth = createSomewhereAuth()\n\n// Call from your sign-up form; throws AuthError with the message on failure.\nexport async function signUp(email: string, password: string) {\n return auth.signUp({ email, password }) // or auth.signIn({ email, password })\n}\nexport async function signOut() {\n await auth.signOut();\n if (auth.getState().signOutUnconfirmed) {\n throw new Error('Sign-out could not be confirmed. Please try again.');\n }\n // Only navigate or reload after confirmed logout.\n}\n```\n\nAwait `signOut()` in the click handler before navigating or reloading. While it is pending, keep the current screen or show a disabled signing-out state. Do not use the appearance of a signed-out form as proof that the server session has ended. After awaiting, check `auth.getState().signOutUnconfirmed`; show a retry message when true. `signOut()` can settle without confirming server logout.\n\nCalls to your own `api/*` functions just send `credentials: 'include'`.\n\nDon't write `getCookie()` / token-parsing helpers \u2192 `sw.auth.fromRequest(req)` reads cookie + Bearer header and returns the validated user (or null) in one call.\n\nMail to `<name>@<project>.test.somewhere.site` is read with `somewhere email test-inbox <address>`.\n\n## Failure 1: sign-in errors\n\nexpected failures (wrong password, duplicate email, weak password) come back as structured 4xx with the real message, never an opaque 500.\n\n## Failure 2: AUTH_REQUIRED from an owner() table\n\nThe table is user-owned, so the platform scopes it to a principal, and this request had none: there is no signed-in user, and this table does not declare `owner({ visitors: true })`, which is the declaration that accepts a stable anonymous visitor identity.\n\nSources (`somewhere docs <topic>`): auth-client, common-mistakes, recipe-signed-in-app, sdk, troubleshooting.\n"
44694
44524
  },
44695
44525
  {
44696
44526
  "path": "troubleshooting/SKILL.md",
@@ -78246,7 +78076,8 @@ function checksJsonReport(check) {
78246
78076
  findings,
78247
78077
  sentence: findings.length !== (check?.findings?.length ?? 0) ? null : check?.sentence ?? null,
78248
78078
  passed: summary.outcome === "passed",
78249
- ...summary
78079
+ ...summary,
78080
+ not_checked: check?.not_checked ?? null
78250
78081
  };
78251
78082
  }
78252
78083
  function resultEvidence(line) {
@@ -78277,8 +78108,12 @@ function formatChecksReport(check) {
78277
78108
  if (!line.outcome && label === "Could not check")
78278
78109
  lines.push(` Run ${cliInvocation()} test --again to confirm this access check.`);
78279
78110
  }
78280
- for (const line of checks.filter((item) => lineOutcome(item) === "passed"))
78281
- lines.push(`PASS ${line.name}`);
78111
+ for (const line of checks.filter((item) => lineOutcome(item) === "passed")) {
78112
+ const observation = line.responses?.[0]?.observed || line.detail || "The stored result has no observation.";
78113
+ const label = check.not_checked ? line.name : `${line.method === "flow" ? "Browser flow" : line.method ?? "Check"} ${line.path ?? "(surface unavailable)"}`;
78114
+ const status = line.status ? ` (HTTP ${line.status})` : "";
78115
+ lines.push(`PASS ${label}${status} \u2014 ${observation}`);
78116
+ }
78282
78117
  for (const finding of functionWarnings(check)) {
78283
78118
  if (finding.kind === "crash") {
78284
78119
  lines.push(`Warning: A server function crashed: ${finding.via} (request ID ${finding.request_id}).`);
@@ -78296,7 +78131,31 @@ function formatChecksReport(check) {
78296
78131
  if (summary.counts.could_not_check && !lines.some((line) => line.startsWith("Could not check")))
78297
78132
  lines.push(`Could not check: run ${cliInvocation()} test --again to get named results.`);
78298
78133
  }
78299
- return [...lines, JSON.stringify(summary)];
78134
+ const coverage = check?.not_checked ?? null;
78135
+ if (coverage) {
78136
+ if (typeof check?.routes_discovered === "number")
78137
+ lines.push(`${check.routes_checked ?? 0} of ${check.routes_discovered} app routes had a completed read check.`);
78138
+ const { routes_without_read_check: reads, routes_without_write_check: writes, schedules_not_run: schedules, other } = coverage;
78139
+ if (reads === null || writes === null)
78140
+ lines.push("App route coverage could not be listed.");
78141
+ if (reads?.length)
78142
+ lines.push(`${reads.length} ${reads.length === 1 ? "route" : "routes"} without a read check (${reads.join(", ")}).`);
78143
+ if (writes?.length)
78144
+ lines.push(`${writes.length} ${writes.length === 1 ? "route" : "routes"} without a write check (${writes.join(", ")}).`);
78145
+ if (schedules === null)
78146
+ lines.push("Registered schedules could not be listed.");
78147
+ if (schedules?.length)
78148
+ lines.push(`${schedules.length} registered ${schedules.length === 1 ? "schedule" : "schedules"} did not run (${schedules.join(", ")}). Run one on your preview with ${cliInvocation()} cron run <name> --preview --wait.`);
78149
+ if (other.length)
78150
+ lines.push(`Other checks skipped or out of scope: ${other.join(", ")}.`);
78151
+ } else {
78152
+ lines.push("Coverage details are unavailable for this run.");
78153
+ }
78154
+ return [...lines, JSON.stringify({
78155
+ ...summary,
78156
+ not_checked: coverage,
78157
+ ...coverage ? { routes_checked: check?.routes_checked, routes_discovered: check?.routes_discovered } : {}
78158
+ })];
78300
78159
  }
78301
78160
  var DEPLOY_CHECKS_POLL_MS, DEPLOY_CHECKS_RUNNING, TEST_CHECKS_WAIT_MS, cleanupFindings, functionWarnings;
78302
78161
  var init_deploy_checks = __esm({
@@ -133179,6 +133038,123 @@ var init_git = __esm({
133179
133038
  }
133180
133039
  });
133181
133040
 
133041
+ // dist/lib/test-preview-job.js
133042
+ function rowCountChanges(before, after) {
133043
+ if (!before || !after || Object.keys(before).length !== Object.keys(after).length)
133044
+ return void 0;
133045
+ if (Object.keys(before).some((table2) => !Object.hasOwn(after, table2)))
133046
+ return void 0;
133047
+ return Object.keys(after).sort().filter((table2) => before[table2] !== after[table2]).map((table2) => ({ table: table2, before: before[table2], after: after[table2] }));
133048
+ }
133049
+ async function runPreviewScheduleTest(client, cronId, target, twice, report2, sleep3 = (ms2) => new Promise((resolve26) => setTimeout(resolve26, ms2))) {
133050
+ const path3 = `/cron/${encodeURIComponent(cronId)}/run-preview`;
133051
+ const validTarget = /* @__PURE__ */ __name((value) => value.preview_session_id === target.preview_session_id && value.preview_id === target.preview_id, "validTarget");
133052
+ const first = await client.call("GET", path3, void 0, { ...target, counts: twice ? 1 : void 0 });
133053
+ if (!validTarget(first) || !first.notice)
133054
+ throw new Error("The platform did not confirm the preview job test target.");
133055
+ report2(first.notice);
133056
+ let before = first.row_counts;
133057
+ let countsReason = first.row_counts_reason;
133058
+ const runs = [];
133059
+ for (let index = 0; index < (twice ? 2 : 1); index++) {
133060
+ let requestId;
133061
+ let jobId;
133062
+ let timeoutSeconds = 270;
133063
+ try {
133064
+ const response = await client.callRaw("POST", path3, target, { captureIncompleteBody: true, redirect: "error" });
133065
+ requestId = response.headers["x-request-id"] ?? response.headers["cf-ray"];
133066
+ const envelope = JSON.parse(response.body);
133067
+ if (response.status >= 400 && response.status < 500 && typeof envelope.error === "string") {
133068
+ runs.push({ status: "refused", duration_ms: null, request_id: requestId, detail: envelope.message ?? envelope.error });
133069
+ break;
133070
+ }
133071
+ const data2 = envelope.data;
133072
+ if (response.status === 202 && data2 && data2.preview_session_id === target.preview_session_id && data2.preview_id === target.preview_id && typeof data2.job_id === "string" && data2.job_id.startsWith("job_")) {
133073
+ jobId = data2.job_id;
133074
+ if (typeof data2.timeout_seconds === "number" && data2.timeout_seconds > 0)
133075
+ timeoutSeconds = Math.min(data2.timeout_seconds, timeoutSeconds);
133076
+ }
133077
+ } catch (error3) {
133078
+ if (error3 instanceof CliApiError)
133079
+ requestId = error3.meta.requestId ?? requestId;
133080
+ }
133081
+ if (!jobId) {
133082
+ runs.push({ status: "unknown", duration_ms: null, request_id: requestId, detail: "Job admission is unknown. The request was not resubmitted." });
133083
+ break;
133084
+ }
133085
+ report2(`Queued job ${jobId}${requestId ? ` (request ${requestId})` : ""}.`);
133086
+ const deadline = Date.now() + timeoutSeconds * 1e3;
133087
+ let last;
133088
+ let readFailed = false;
133089
+ while (Date.now() < deadline) {
133090
+ try {
133091
+ const result = await client.call("GET", path3, void 0, { ...target, job_id: jobId, counts: twice ? 1 : void 0 }, { timeoutMs: Math.max(1, deadline - Date.now()), refresh: false });
133092
+ if (!validTarget(result) || result.job?.job_id !== jobId)
133093
+ throw new Error("Unexpected job status receipt");
133094
+ last = result;
133095
+ if (result.job.terminal)
133096
+ break;
133097
+ } catch {
133098
+ readFailed = true;
133099
+ break;
133100
+ }
133101
+ if (Date.now() < deadline)
133102
+ await sleep3(Math.min(1e3, deadline - Date.now()));
133103
+ }
133104
+ const job = last?.job;
133105
+ if (!job?.terminal || job.status === "indeterminate") {
133106
+ const detail = readFailed ? "The job status could not be read." : job?.terminal ? "The job\u2019s execution outcome is indeterminate." : "The job did not reach a terminal status before the wait expired.";
133107
+ runs.push({ status: "unknown", duration_ms: job?.duration_ms ?? null, job_id: jobId, request_id: requestId, detail });
133108
+ break;
133109
+ }
133110
+ const changes = twice ? rowCountChanges(before, last?.row_counts) : void 0;
133111
+ runs.push({
133112
+ status: job.status,
133113
+ duration_ms: job.duration_ms,
133114
+ job_id: jobId,
133115
+ request_id: requestId,
133116
+ ...job.error_code ? { detail: job.error_code } : {},
133117
+ ...twice ? changes ? { row_count_changes: changes } : { row_counts_reason: last?.row_counts_reason ?? countsReason ?? "Two comparable row count snapshots were unavailable." } : {}
133118
+ });
133119
+ before = last?.row_counts;
133120
+ countsReason = last?.row_counts_reason;
133121
+ }
133122
+ return runs;
133123
+ }
133124
+ async function printPreviewScheduleTest(cronId, preview, twice, json) {
133125
+ const { preview_session_id, preview_id } = await previewCurrentVersion(preview.credential);
133126
+ const version2 = { preview_session_id, preview_id };
133127
+ if (preview.previewSessionId !== version2.preview_session_id)
133128
+ throw new Error("The preview credential did not resolve to this folder\u2019s preview.");
133129
+ const runs = await runPreviewScheduleTest(new ApiClient(getToken()), cronId, version2, twice, (message3) => process.stderr.write(message3 + "\n"));
133130
+ if (json)
133131
+ process.stdout.write(JSON.stringify({ cron_id: cronId, ...version2, runs }) + "\n");
133132
+ else
133133
+ runs.forEach((run, i) => {
133134
+ const receipt = [run.job_id && `job ${run.job_id}`, run.request_id && `request ${run.request_id}`].filter(Boolean).join(", ");
133135
+ const duration3 = run.duration_ms !== null ? ` in ${(run.duration_ms / 1e3).toFixed(2)} s` : "";
133136
+ console.log(`Run ${i + 1} ${run.status}${duration3}${receipt ? ` (${receipt})` : ""}.${run.detail ? ` ${run.detail}` : ""}`);
133137
+ if (run.row_count_changes) {
133138
+ const changes = run.row_count_changes.map(({ table: table2, before, after }) => `${table2} ${before} \u2192 ${after}`);
133139
+ console.log(changes.length ? `Observed row counts changed in ${changes.join(", ")}.` : "No declared table row count changed between reads.");
133140
+ }
133141
+ if (run.row_counts_reason)
133142
+ console.log(`Row count observation unavailable. ${run.row_counts_reason}`);
133143
+ });
133144
+ process.exitCode = runs.some((run) => ["failed", "cancelled"].includes(run.status)) ? 1 : runs.every((run) => run.status === "complete") ? 0 : 2;
133145
+ }
133146
+ var init_test_preview_job = __esm({
133147
+ "dist/lib/test-preview-job.js"() {
133148
+ "use strict";
133149
+ init_client();
133150
+ init_config();
133151
+ init_preview_jobs();
133152
+ __name(rowCountChanges, "rowCountChanges");
133153
+ __name(runPreviewScheduleTest, "runPreviewScheduleTest");
133154
+ __name(printPreviewScheduleTest, "printPreviewScheduleTest");
133155
+ }
133156
+ });
133157
+
133182
133158
  // dist/commands/cron.js
133183
133159
  function parsePayload(value) {
133184
133160
  if (value === void 0)
@@ -133600,15 +133576,22 @@ zone each trigger is stored in, and \`cron update --schedule\` keeps that zone u
133600
133576
  console.log(dim(policy));
133601
133577
  });
133602
133578
  });
133603
- cron.command("run <cron-id-or-name>").description("Queue one run of a scheduled task now without changing its schedule; --wait waits for it to finish").option("-p, --project <project>", "Project slug or ID used to resolve a task name; defaults to the linked project").option("--wait", "Wait for the queued job to finish and print its result; exits non-zero on failure or timeout").option("--preview", "Run the task's handler and payload once in this folder's open preview instead (its code, data, files and mail); the production schedule never changes").option("--timeout <seconds>", `With --wait, how long to wait before giving up (default ${DEFAULT_WAIT_TIMEOUT_SECONDS})`).option("--json", "Print the complete response as JSON").addHelpText("after", "\nWithout --wait the command returns as soon as the job is queued; the task has not run yet,\nso anything it writes may not be visible for a few seconds. Pass --wait before reading its effects.\n").action(async (target, opts) => {
133579
+ cron.command("run <cron-id-or-name>").description("Queue one run of a scheduled task now without changing its schedule; --wait waits for it to finish").option("-p, --project <project>", "Project slug or ID used to resolve a task name; defaults to the linked project").option("--wait", "Wait for the queued job to finish and print its result; exits non-zero on failure or timeout").option("--preview", "Run the task's handler and payload once in this folder's open preview instead (its code, data, files and mail); the production schedule never changes").option("--twice", "With --preview, wait for each of two runs and report declared table row count changes").option("--timeout <seconds>", `With --wait, how long to wait before giving up (default ${DEFAULT_WAIT_TIMEOUT_SECONDS})`).option("--json", "Print the complete response as JSON").addHelpText("after", "\nWithout --wait the command returns as soon as the job is queued; the task has not run yet,\nso anything it writes may not be visible for a few seconds. Pass --wait before reading its effects.\n").action(async (target, opts) => {
133604
133580
  let queued = false;
133605
133581
  try {
133582
+ if (opts.twice && (!opts.preview || opts.timeout !== void 0)) {
133583
+ throw new Error("USAGE_ERROR: --twice requires --preview and uses the platform job timeout.");
133584
+ }
133606
133585
  const timeoutSeconds = parseWaitTimeout(opts.timeout);
133607
133586
  if (opts.timeout !== void 0 && !opts.wait) {
133608
133587
  throw new Error("USAGE_ERROR: --timeout only applies with --wait.");
133609
133588
  }
133610
133589
  const cronId = await resolveCronId(target, opts.project);
133611
133590
  if (opts.preview) {
133591
+ if (opts.twice) {
133592
+ await printPreviewScheduleTest(cronId, await folderPreviewTool({}), true, Boolean(opts.json));
133593
+ return;
133594
+ }
133612
133595
  await runCronInPreview(cronId, opts, timeoutSeconds);
133613
133596
  return;
133614
133597
  }
@@ -133764,6 +133747,7 @@ var DEFAULT_WAIT_TIMEOUT_SECONDS, WAIT_POLL_INTERVAL_MS, JOB_SUCCESS_STATUS, JOB
133764
133747
  var init_cron = __esm({
133765
133748
  "dist/commands/cron.js"() {
133766
133749
  "use strict";
133750
+ init_test_preview_job();
133767
133751
  init_cli_invocation();
133768
133752
  init_config();
133769
133753
  init_next_actions();
@@ -135313,7 +135297,8 @@ function registerTestUsers(program2) {
135313
135297
  group.command("prepare <actors...>").description("Create preverified test users and write one Playwright storageState file per actor (e.g. alice bob:admin)").option("-p, --project <project>", "Project slug or ID; defaults to the linked project").option("--origin <url>", "Only the project's production origin is supported; anything else is refused").option("--json", "Print the manifest (no tokens) as JSON").addHelpText("after", [
135314
135298
  "",
135315
135299
  "From the linked project folder, run somewhere test-users prepare alice. It writes .somewhere/test/<actor>.state.json (a standard Playwright storageState) and manifest.json.",
135316
- 'Playwright: browser.newContext({ storageState: ".somewhere/test/alice.state.json" })',
135300
+ 'Playwright: const alice = await browser.newContext({ storageState: ".somewhere/test/alice.state.json" })',
135301
+ 'With data imported from @somewhere-cloud/cli/testing: await data(alice.request, "notes", { operation: "list" })',
135317
135302
  'Save the context back after each run: await context.storageState({ path: ".somewhere/test/alice.state.json" })',
135318
135303
  "The app refreshes the short-lived access token and rotates the session on its first refresh, so an unsaved",
135319
135304
  "file stops working after a run that refreshed it. The prepared session starts with the expiry prepare",
@@ -136967,12 +136952,31 @@ async function refusedAs(person, target, request2, options2) {
136967
136952
  throw new Error(`expectRefused: ${said}, but ${target} ${String(id)} ${after === null ? "is gone" : "changed"} for the allowed person afterwards.`);
136968
136953
  }
136969
136954
  }
136970
- function data(client, table2, request2) {
136971
- if (!digests.has(client))
136972
- throw new Error("Use a newUser or anonymous fixture client");
136973
- return client.post("/__sw/data", { data: { ...request2, table: table2, contract: digests.get(client) ?? "" } });
136955
+ async function data(client, table2, request2) {
136956
+ if (digests.has(client)) {
136957
+ return client.post("/__sw/data", { data: { ...request2, table: table2, contract: digests.get(client) ?? "" } });
136958
+ }
136959
+ const projectId = loadProjectConfig()?.project_id;
136960
+ if (!projectId)
136961
+ throw new Error("Use the data helper from a linked project folder.");
136962
+ let target = contextTargets.get(client);
136963
+ if (!target || target.projectId !== projectId) {
136964
+ const load2 = fixtureTestTarget(new ApiClient(process.env.SW_TEST_TARGET ? null : getToken()), projectId).catch((error3) => {
136965
+ if (contextTargets.get(client)?.load === load2)
136966
+ contextTargets.delete(client);
136967
+ throw error3;
136968
+ });
136969
+ target = { projectId, load: load2 };
136970
+ contextTargets.set(client, target);
136971
+ }
136972
+ const { origin, contractDigest } = await target.load;
136973
+ return client.post(new URL("/__sw/data", origin).href, {
136974
+ headers: { Origin: origin },
136975
+ maxRedirects: 0,
136976
+ data: { ...request2, table: table2, contract: contractDigest ?? "" }
136977
+ });
136974
136978
  }
136975
- var loaded, digests, eager, test, expect, ENDPOINT, INCONCLUSIVE, constrained, FormRun;
136979
+ var loaded, digests, eager, test, expect, ENDPOINT, INCONCLUSIVE, contextTargets, constrained, FormRun;
136976
136980
  var init_playwright_fixtures = __esm({
136977
136981
  "dist/lib/playwright-fixtures.js"() {
136978
136982
  "use strict";
@@ -137025,6 +137029,7 @@ var init_playwright_fixtures = __esm({
137025
137029
  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.";
137026
137030
  __name(seen, "seen");
137027
137031
  __name(refusedAs, "refusedAs");
137032
+ contextTargets = /* @__PURE__ */ new WeakMap();
137028
137033
  __name(data, "data");
137029
137034
  constrained = /* @__PURE__ */ new WeakSet();
137030
137035
  FormRun = class {