@somewhere-cloud/cli 0.38.91 → 0.38.93
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/commands/dev.js +160 -2
- package/dist/commands/dev.js.map +1 -1
- package/dist/commands/init.d.ts +15 -0
- package/dist/commands/init.js +231 -229
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/link.d.ts +2 -3
- package/dist/commands/link.js +6 -26
- package/dist/commands/link.js.map +1 -1
- package/dist/commands/test.js +4 -2
- package/dist/commands/test.js.map +1 -1
- package/dist/lib/app-test.d.ts +29 -7
- package/dist/lib/app-test.js +126 -41
- package/dist/lib/app-test.js.map +1 -1
- package/dist/lib/config.d.ts +6 -0
- package/dist/lib/config.js +15 -0
- package/dist/lib/config.js.map +1 -1
- package/dist/lib/form-accounts.d.ts +14 -2
- package/dist/lib/form-accounts.js +19 -6
- package/dist/lib/form-accounts.js.map +1 -1
- package/dist/lib/form-auth.d.ts +7 -5
- package/dist/lib/form-auth.js +70 -15
- package/dist/lib/form-auth.js.map +1 -1
- package/dist/lib/init-agent-guide.d.ts +3 -3
- package/dist/lib/init-agent-guide.js +15 -2
- package/dist/lib/init-agent-guide.js.map +1 -1
- package/dist/lib/init-feature-template.js +1 -1
- package/dist/lib/init-green-template.js +1 -1
- package/dist/lib/init-test-template.js +3 -0
- package/dist/lib/init-test-template.js.map +1 -1
- package/dist/lib/playwright-fixtures.d.ts +9 -2
- package/dist/lib/playwright-fixtures.js +150 -22
- package/dist/lib/playwright-fixtures.js.map +1 -1
- package/dist/lib/preview-credential.d.ts +11 -0
- package/dist/lib/preview-credential.js +56 -0
- package/dist/lib/preview-credential.js.map +1 -0
- package/dist/lib/screenshot-guard.d.ts +2 -0
- package/dist/lib/screenshot-guard.js +30 -0
- package/dist/lib/screenshot-guard.js.map +1 -0
- package/dist/lib/test-control.d.ts +65 -0
- package/dist/lib/test-control.js +202 -0
- package/dist/lib/test-control.js.map +1 -0
- package/dist/lib/test-diagnostics.d.ts +10 -0
- package/dist/lib/test-diagnostics.js +27 -0
- package/dist/lib/test-diagnostics.js.map +1 -1
- package/dist/lib/test-reporter.js +34 -9
- package/dist/lib/test-reporter.js.map +1 -1
- package/dist/lib/test-run.d.ts +6 -3
- package/dist/lib/test-run.js +28 -9
- package/dist/lib/test-run.js.map +1 -1
- package/dist/lib/test-target.d.ts +5 -0
- package/dist/lib/test-target.js.map +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/runtime/DECLARED-DATA-VENDOR.json +4 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const AGENT_WORKFLOW = "## Build, deploy, test\n\nEnough to start a typical app: declare access and use the browser client; docs are for exceptions.\n\n| Requirement | Declaration below |\n| --- | --- |\n| Each user sees only their own rows | notes: owner() |\n| Team: owner invites members; members read/write; creator or team owner deletes | tasks: anyOf(owner(), group()); sw.groups endpoints below |\n| Owner/staff record with staff-only child notes | tickets: owner() or appRole(); parent() thread; staff-only notes; staff by verified emailDomain (or grantableBy) |\n| Public pages from private drafts | pages: conditional publicRead |\n| Share one record read-only | shared_notes/note_shares: read-only grant() |\n\ndb/schema.ts is declaration only: imports, constants/spreads, default schema;\nno helpers/expressions. id() is random text; owner() stamps user_id. client.read\nincludes the key. Inside anyOf(), owner() takes only column/read: it stamps the\ncreator, not create/delete options; group() gates placement (non-member create is\nrefused); inside anyOf an operation missing from roles allows no group role. Other fields: timestamp({ default: 'now' }), text({ nullable: true });\nindexes: [['team_id']].\n\n```ts\nimport { schema, table, id, text, owner, group, anyOf, parent, appRole, boolean, grant } from 'somewhere/db';\nexport default schema({\n notes: table({ id: id(), title: text() }, { scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'], delete: true },\n }),\n tasks: table({ id: id(), team_id: text(), title: text() }, {\n scope: anyOf(owner(), group({ column: 'team_id', roles: { read: ['owner', 'admin', 'member'],\n create: ['owner', 'admin', 'member'], update: ['owner', 'admin', 'member'], delete: ['owner'] } })),\n client: { read: ['id', 'team_id', 'title'], create: ['team_id', 'title'], update: ['title'], delete: true },\n }),\n tickets: table({ id: id(), subject: text() }, {\n scope: anyOf(owner(), appRole({ roles: { read: ['staff'], create: ['staff'], update: ['staff'] } })),\n client: { read: true, create: ['subject'], update: ['subject'] },\n }),\n messages: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: parent({ via: 'ticket_id' }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n staff_notes: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: appRole({ roles: { read: ['staff'], create: ['staff'] } }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n pages: table({ id: id(), title: text(), published: boolean({ default: false }) }, {\n scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'],\n publicRead: { where: { published: true } } },\n }),\n note_shares: table({ id: id(), grantee_id: text(), note_id: text({ references: 'shared_notes', onDelete: 'cascade' }) }, {\n scope: owner(), unique: [['note_id', 'grantee_id']],\n }),\n shared_notes: table({ id: id(), title: text() }, {\n scope: anyOf(owner(), grant({ table: 'note_shares', grantee: 'grantee_id', row: 'note_id', operations: ['read'] })),\n client: { read: ['id', 'title'], create: ['title'], update: ['title'] },\n }),\n}, { appRoles: { staff: { emailDomain: 'staff.example' } } });\n```\n\nWho is staff is your app's decision; the platform enforces what the role may do.\nFirst choice, as above: emailDomain. The role holds once the person verifies an address\nat that domain; no grant code. An email ending alone proves nothing: anyone can sign up\nas anyone@your-domain without owning that mailbox. Without verification, grant only from\nsomething the visitor cannot choose, such as an invitation your app issued, checked inside\nthe sign-up route: single use, bound to one account, its link delivered only to that person:\nsomewhere docs sw.auth --section server-assigned-app-roles-setroles.\nmessages use parent(): owner() would hide staff replies from the customer.\nPublish pages in an owner-checked endpoint. Share with caller-scoped\nsw.db.insert('note_shares', { grantee_id, note_id }); it checks row ownership.\nBrowser calls THROW, not { error }; catch below.\nBrowser list: max 100, paginate after; no order (sort locally or in an endpoint).\n\n```ts\nimport { data } from 'somewhere:data';\nexport async function save(title: string) {\n try { await data.notes.create({ title }); return null; }\n catch (e) { return e instanceof Error ? e.message : 'Save failed'; }\n}\nexport const list = (after?: string) => data.notes.list({ limit: 100, after });\n```\n\nTeams are built-in groups: the platform keeps the team, invitations, roster, removal,\nleaving, last owner. Starting a team needs a signed-in user; joining needs a verified\nemail (a password sign-up joins once it enters its emailed code). The browser cannot call\nsw.groups: pass each call through an endpoint. A parent() child's delete follows the task\n(creator or team owner), so \"comment author or team owner deletes\" is an endpoint.\nStaff making others staff: appRoles { staff: { grantableBy: ['staff'] } } and\nsw.groups.appRoles.grant(request, userId, 'staff') in an endpoint (never to oneself).\nComplete apps and specs: somewhere docs sw.groups --section team-example or staff-example.\n\n```ts\n// api/teams.ts \u2014 GET my teams (completes invitations to me); POST starts one I own\nconst refusal = (e: { code: string; message: string; status: number }) =>\n Response.json({ error: e.code, message: e.message }, { status: e.status });\nexport const GET = sw.endpoint({ auth: 'required', handler: async ({ request }, sw) => {\n const page = await sw.groups.list(request, { limit: 100 });\n return page.error ? refusal(page.error) : { teams: page.data.items, next_cursor: page.data.next_cursor };\n} });\nexport default sw.endpoint({ auth: 'required', body: { name: 'string' }, handler: async ({ request, body }, sw) => {\n const made = await sw.groups.create(request, { name: body.name });\n return made.error ? refusal(made.error) : { id: made.data.id };\n} });\n```\n\n```ts\n// api/teams/[id]/invitations.ts \u2014 owners invite; others 403; a member's address 409 ALREADY_MEMBER\nexport default sw.endpoint({ auth: 'required', body: { email: 'string' }, handler: async ({ request, params, body }, sw) => {\n const sent = await sw.groups.invite(request, params.id, { email: body.email, role: 'member', redirect_uri: '/' });\n return sent.error ? Response.json({ error: sent.error.code }, { status: sent.error.status }) : { delivery: sent.data.delivery };\n} });\n```\n\nSame shape: sw.groups.get/members(request, id), remove(request, id, userId), leave(request, id)\n(last owner: 409 LAST_OWNER), delete(request, id) by owners.\n\nDo not hand-write access to app-read/write data: declare who may read/write it.\nserverOnly() fits job/import/audit/counter state.\nGrant ledgers use owner() without browser writes. Undeclarable: arbitrary predicates\n(e.g. expiry) or per-role writable fields (split tables or check that write).\n\nBuild src/pages/HomePage.tsx; routes src/App.tsx + src/routes.ts; auth src/auth/hooks.ts.\nAuth is wired: keep api/auth/[...path].ts; src/config.ts controls providers.\napi/notes/[id]/sub.ts \u2192 params.id; underscore files are helpers. POST: default export;\nGET/DELETE: named exports.\n\n```ts\nexport const GET = sw.endpoint({ auth: 'required', handler: async (_, sw) => sw.db.from('notes', { limit: 100 }) });\n```\n\nsw.db applies caller scopes; sw.db.server bypasses them: authorize first.\nCaller-scoped sw.db.insert needs no client.create grant: client limits only the browser.\nReads: from(table, { where, columns, order: [['id', 'asc']], limit, offset }).\nFilter: { id: { in: ids } }; unique: [['a', 'b']] in schema.\nWrites: insert(table, values), update(table, { where, set }), remove(table, { where }).\ntx takes an ARRAY of write intents, never a callback; pre-generate related IDs.\n\nBrowser: fetch(path, { method: 'POST', credentials: 'same-origin',\nheaders: { 'content-type': 'application/json' }, body: JSON.stringify(values) }).\nAccess cookies refresh automatically. Cookie-auth POST/PATCH/DELETE from scripts\nneed Origin equal to the app URL.\n\nTest with an ordinary Playwright script: the journeys you changed and your access boundaries.\nRun it only after a successful deploy: npx @somewhere-cloud/cli deploy && node tests/app-check.mjs\n(the starter's short example; one result file, and the exit code is the verdict). Rerun only to answer a question.\nHelpers from @somewhere-cloud/cli/script (import or require): openAppTest() then app.signUp/signIn/signOut(page)\nthrough your form, app.data(page, { table, operation, id, values, where }) as that person,\napp.expectRefused(page, request, { allowed: ownerPage }), captureResponses, dataReady, launchOptions.\nA rebuilt sign-in form keeps data-sw-auth=\"email\", \"password\", \"sign-up\", \"sign-in\" on its controls,\nor pass app.signUp(page, { form: { email, password, signUp, signIn } }) with your own selectors.\nDeploy raw source, no frontend build; type errors stop upload.\nEmail-domain role: app.signUp(page, { domain: 'staff.example' }), then app.verify(page, person).\nThe complete team spec, with removal and leaving: somewhere docs sw.groups --section team-example.\nDiagnose with somewhere errors and somewhere logs.\n\nOn demand:\n- Server paging: `somewhere docs sw.db --section server-read-paging`\n\n## Testing shared access\n\nWith the team endpoints above, the owner invites a fixture by email; test users are verified,\nso its next GET /api/teams shows the team. A test user who still owns a team is not deleted:\ndelete the team last (api/teams/[id].ts DELETE: sw.groups.delete). Group calls take\nabout a second, so raise the timeout:\n\n```ts\n// tests/team.spec.ts\nimport { test, expect } from '@somewhere-cloud/cli/testing';\ntest.describe.configure({ timeout: 90_000 });\ntest('owner invites a second user by email', async ({ newUser }) => {\n const [owner, bob] = await Promise.all([newUser(), newUser()]);\n const { id } = await (await owner.request.post('/api/teams', { data: { name: 'Shared team' } })).json();\n expect((await owner.request.post(`/api/teams/${id}/invitations`, { data: { email: bob.email } })).ok()).toBeTruthy();\n const { teams } = await (await bob.request.get('/api/teams')).json();\n expect(teams).toContainEqual(expect.objectContaining({ id, role: 'member' }));\n expect((await owner.request.delete(`/api/teams/${id}`)).status()).toBe(204);\n});\n```\n";
|
|
1
|
+
export declare const AGENT_WORKFLOW = "## Build, deploy, test\n\nEnough to start a typical app: declare access and use the browser client; docs are for exceptions.\n\n| Requirement | Declaration below |\n| --- | --- |\n| Each user sees only their own rows | notes: owner() |\n| Team: owner invites members; members read/write; creator or team owner deletes | tasks: anyOf(owner(), group()); sw.groups endpoints below |\n| Owner/staff record with staff-only child notes | tickets: owner() or appRole(); parent() thread; staff-only notes; staff by verified emailDomain (or grantableBy) |\n| Public pages from private drafts | pages: conditional publicRead |\n| Share one record read-only | shared_notes/note_shares: read-only grant() |\n\ndb/schema.ts is declaration only: imports, constants/spreads, default schema;\nno helpers/expressions. id() is random text; owner() stamps user_id. client.read\nincludes the key. Inside anyOf(), owner() takes only column/read: it stamps the\ncreator, not create/delete options; group() gates placement (non-member create is\nrefused); inside anyOf an operation missing from roles allows no group role. Other fields: timestamp({ default: 'now' }), text({ nullable: true });\nindexes: [['team_id']].\n\n```ts\nimport { schema, table, id, text, owner, group, anyOf, parent, appRole, boolean, grant } from 'somewhere/db';\nexport default schema({\n notes: table({ id: id(), title: text() }, { scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'], delete: true },\n }),\n tasks: table({ id: id(), team_id: text(), title: text() }, {\n scope: anyOf(owner(), group({ column: 'team_id', roles: { read: ['owner', 'admin', 'member'],\n create: ['owner', 'admin', 'member'], update: ['owner', 'admin', 'member'], delete: ['owner'] } })),\n client: { read: ['id', 'team_id', 'title'], create: ['team_id', 'title'], update: ['title'], delete: true },\n }),\n tickets: table({ id: id(), subject: text() }, {\n scope: anyOf(owner(), appRole({ roles: { read: ['staff'], create: ['staff'], update: ['staff'] } })),\n client: { read: true, create: ['subject'], update: ['subject'] },\n }),\n messages: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: parent({ via: 'ticket_id' }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n staff_notes: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: appRole({ roles: { read: ['staff'], create: ['staff'] } }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n pages: table({ id: id(), title: text(), published: boolean({ default: false }) }, {\n scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'],\n publicRead: { where: { published: true } } },\n }),\n note_shares: table({ id: id(), grantee_id: text(), note_id: text({ references: 'shared_notes', onDelete: 'cascade' }) }, {\n scope: owner(), unique: [['note_id', 'grantee_id']],\n }),\n shared_notes: table({ id: id(), title: text() }, {\n scope: anyOf(owner(), grant({ table: 'note_shares', grantee: 'grantee_id', row: 'note_id', operations: ['read'] })),\n client: { read: ['id', 'title'], create: ['title'], update: ['title'] },\n }),\n}, { appRoles: { staff: { emailDomain: 'staff.example' } } });\n```\n\nWho is staff is your app's decision; the platform enforces what the role may do.\nFirst choice, as above: emailDomain. The role holds once the person verifies an address\nat that domain; no grant code. An email ending alone proves nothing: anyone can sign up\nas anyone@your-domain without owning that mailbox. Without verification, grant only from\nsomething the visitor cannot choose, such as an invitation your app issued, checked inside\nthe sign-up route: single use, bound to one account, its link delivered only to that person:\nsomewhere docs sw.auth --section server-assigned-app-roles-setroles.\nmessages use parent(): owner() would hide staff replies from the customer.\nA staff reply is a messages row, and creating a parent() child needs create on the parent\nfor that person: its owner, or a role listed under the parent's create. Read or update is\nnot enough. So tickets lists create: ['staff']; without it every staff reply is refused\n(403 POLICY_AUTHORITY_REQUIRED).\nPublish pages in an owner-checked endpoint. Share with caller-scoped\nsw.db.insert('note_shares', { grantee_id, note_id }); it checks row ownership.\nBrowser calls THROW, not { error }; catch below.\nBrowser list: max 100, paginate after; no order (sort locally or in an endpoint).\n\n```ts\nimport { data } from 'somewhere:data';\nexport async function save(title: string) {\n try { await data.notes.create({ title }); return null; }\n catch (e) { return e instanceof Error ? e.message : 'Save failed'; }\n}\nexport const list = (after?: string) => data.notes.list({ limit: 100, after });\n```\n\nTeams are built-in groups: the platform keeps the team, invitations, roster, removal,\nleaving, last owner. Starting a team needs a signed-in user; joining needs a verified\nemail (a password sign-up joins once it enters its emailed code). The browser cannot call\nsw.groups: pass each call through an endpoint. A parent() child's delete follows the task\n(creator or team owner), so \"comment author or team owner deletes\" is an endpoint.\nStaff making others staff: appRoles { staff: { grantableBy: ['staff'] } } and\nsw.groups.appRoles.grant(request, userId, 'staff') in an endpoint (never to oneself).\nComplete apps and specs: somewhere docs sw.groups --section team-example or staff-example.\n\n```ts\n// api/teams.ts \u2014 GET my teams (completes invitations to me); POST starts one I own\nconst refusal = (e: { code: string; message: string; status: number }) =>\n Response.json({ error: e.code, message: e.message }, { status: e.status });\nexport const GET = sw.endpoint({ auth: 'required', handler: async ({ request }, sw) => {\n const page = await sw.groups.list(request, { limit: 100 });\n return page.error ? refusal(page.error) : { teams: page.data.items, next_cursor: page.data.next_cursor };\n} });\nexport default sw.endpoint({ auth: 'required', body: { name: 'string' }, handler: async ({ request, body }, sw) => {\n const made = await sw.groups.create(request, { name: body.name });\n return made.error ? refusal(made.error) : { id: made.data.id };\n} });\n```\n\n```ts\n// api/teams/[id]/invitations.ts \u2014 owners invite; others 403; a member's address 409 ALREADY_MEMBER\nexport default sw.endpoint({ auth: 'required', body: { email: 'string' }, handler: async ({ request, params, body }, sw) => {\n const sent = await sw.groups.invite(request, params.id, { email: body.email, role: 'member', redirect_uri: '/' });\n return sent.error ? Response.json({ error: sent.error.code }, { status: sent.error.status }) : { delivery: sent.data.delivery };\n} });\n```\n\nSame shape: sw.groups.get/members(request, id), remove(request, id, userId), leave(request, id)\n(last owner: 409 LAST_OWNER), delete(request, id) by owners.\n\nDo not hand-write access to app-read/write data: declare who may read/write it.\nserverOnly() fits job/import/audit/counter state.\nGrant ledgers use owner() without browser writes. Undeclarable: arbitrary predicates\n(e.g. expiry) or per-role writable fields (split tables or check that write).\n\nBuild src/pages/HomePage.tsx; routes src/App.tsx + src/routes.ts; auth src/auth/hooks.ts.\nAuth is wired: keep api/auth/[...path].ts; src/config.ts controls providers.\napi/notes/[id]/sub.ts \u2192 params.id; underscore files are helpers. POST: default export;\nGET/DELETE: named exports.\n\n```ts\nexport const GET = sw.endpoint({ auth: 'required', handler: async (_, sw) => sw.db.from('notes', { limit: 100 }) });\n```\n\nsw.db applies caller scopes; sw.db.server bypasses them: authorize first.\nCaller-scoped sw.db.insert needs no client.create grant: client limits only the browser.\nReads: from(table, { where, columns, order: [['id', 'asc']], limit, offset }).\nFilter: { id: { in: ids } }; unique: [['a', 'b']] in schema.\nWrites: insert(table, values), update(table, { where, set }), remove(table, { where }).\ntx takes an ARRAY of write intents, never a callback; pre-generate related IDs.\n\nBrowser: fetch(path, { method: 'POST', credentials: 'same-origin',\nheaders: { 'content-type': 'application/json' }, body: JSON.stringify(values) }).\nAccess cookies refresh automatically. Cookie-auth POST/PATCH/DELETE from scripts\nneed Origin equal to the app URL.\n\nTest with an ordinary Playwright script: the journeys you changed and your access boundaries.\nRun it only after a successful deploy: npx @somewhere-cloud/cli deploy && node tests/app-check.mjs\n(the starter's short example; one result file, and the exit code is the verdict).\nKeep each run short:\n- Short waits: page.setDefaultTimeout(5_000) on every page; a deployed app answers in under\n a second. Never sleep for a fixed time: wait for the thing itself (the text, the response).\n- Stop at the first failure and print what the page showed (page.url(), the visible error\n text). Checks after a failure only wait out their timeouts. app.check() does both.\n- After a fix, rerun only the checks that failed: node tests/app-check.mjs --failed.\n Keep setup (sign-ups, rows a check needs) outside app.check() so a rerun still has it.\nCall the data endpoint as a signed-in person: app.data(page, { table, operation, id, values })\n(the raw request: somewhere docs declared-data --section calling-the-data-endpoint-directly).\nHelpers from @somewhere-cloud/cli/script (import or require): openAppTest() then app.signUp/signIn/signOut(page)\nthrough your form, app.data(page, { table, operation, id, values, where }) as that person,\napp.expectRefused(page, request, { allowed: ownerPage }), captureResponses, dataReady, launchOptions.\nA rebuilt sign-in form keeps data-sw-auth=\"email\", \"password\", \"sign-up\", \"sign-in\" on its controls,\nor pass app.signUp(page, { form: { email, password, signUp, signIn } }) with your own selectors.\nDeploy raw source, no frontend build; type errors stop upload.\nEmail-domain role: app.signUp(page, { domain: 'staff.example' }), then app.verify(page, person).\nThe complete team spec, with removal and leaving: somewhere docs sw.groups --section team-example.\nDiagnose with somewhere errors and somewhere logs.\n\nOn demand:\n- Server paging: `somewhere docs sw.db --section server-read-paging`\n\n## Testing shared access\n\nWith the team endpoints above, the owner invites a fixture by email; test users are verified,\nso its next GET /api/teams shows the team. A test user who still owns a team is not deleted:\ndelete the team last (api/teams/[id].ts DELETE: sw.groups.delete). Group calls take\nabout a second, so raise the timeout:\n\n```ts\n// tests/team.spec.ts\nimport { test, expect } from '@somewhere-cloud/cli/testing';\ntest.describe.configure({ timeout: 90_000 });\ntest('owner invites a second user by email', async ({ newUser }) => {\n const [owner, bob] = await Promise.all([newUser(), newUser()]);\n const { id } = await (await owner.request.post('/api/teams', { data: { name: 'Shared team' } })).json();\n expect((await owner.request.post(`/api/teams/${id}/invitations`, { data: { email: bob.email } })).ok()).toBeTruthy();\n const { teams } = await (await bob.request.get('/api/teams')).json();\n expect(teams).toContainEqual(expect.objectContaining({ id, role: 'member' }));\n expect((await owner.request.delete(`/api/teams/${id}`)).status()).toBe(204);\n});\n```\n";
|
|
2
2
|
export declare const SKILLS_POINTER = "Task-specific skills: `.agents/skills/`. Inspect/update with somewhere skills status/update.";
|
|
3
3
|
export declare const DECLARED_ACCESS_POINTER = "";
|
|
4
4
|
/** One line telling agents the app's data and code can leave:
|
|
@@ -9,6 +9,6 @@ export declare const PORTABILITY_POINTER = "Data/code export limits: `somewhere
|
|
|
9
9
|
export declare const MCP_POINTER = "Use this app from Claude as its signed-in user (MCP tools): `somewhere docs sw.endpoint --section mcp-tools-for-claude`.";
|
|
10
10
|
/** One line on what a preview cannot do today, so no agent learns it by failing.
|
|
11
11
|
* Rewrite it when previews gain these (the full list: docs dev-environments). */
|
|
12
|
-
export declare const PREVIEW_POINTER = "somewhere preview runs your change on a copy of production data
|
|
13
|
-
export declare const INIT_AGENTS_MD = "# somewhere.cloud project contract\n## Build, deploy, test\n\nEnough to start a typical app: declare access and use the browser client; docs are for exceptions.\n\n| Requirement | Declaration below |\n| --- | --- |\n| Each user sees only their own rows | notes: owner() |\n| Team: owner invites members; members read/write; creator or team owner deletes | tasks: anyOf(owner(), group()); sw.groups endpoints below |\n| Owner/staff record with staff-only child notes | tickets: owner() or appRole(); parent() thread; staff-only notes; staff by verified emailDomain (or grantableBy) |\n| Public pages from private drafts | pages: conditional publicRead |\n| Share one record read-only | shared_notes/note_shares: read-only grant() |\n\ndb/schema.ts is declaration only: imports, constants/spreads, default schema;\nno helpers/expressions. id() is random text; owner() stamps user_id. client.read\nincludes the key. Inside anyOf(), owner() takes only column/read: it stamps the\ncreator, not create/delete options; group() gates placement (non-member create is\nrefused); inside anyOf an operation missing from roles allows no group role. Other fields: timestamp({ default: 'now' }), text({ nullable: true });\nindexes: [['team_id']].\n\n```ts\nimport { schema, table, id, text, owner, group, anyOf, parent, appRole, boolean, grant } from 'somewhere/db';\nexport default schema({\n notes: table({ id: id(), title: text() }, { scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'], delete: true },\n }),\n tasks: table({ id: id(), team_id: text(), title: text() }, {\n scope: anyOf(owner(), group({ column: 'team_id', roles: { read: ['owner', 'admin', 'member'],\n create: ['owner', 'admin', 'member'], update: ['owner', 'admin', 'member'], delete: ['owner'] } })),\n client: { read: ['id', 'team_id', 'title'], create: ['team_id', 'title'], update: ['title'], delete: true },\n }),\n tickets: table({ id: id(), subject: text() }, {\n scope: anyOf(owner(), appRole({ roles: { read: ['staff'], create: ['staff'], update: ['staff'] } })),\n client: { read: true, create: ['subject'], update: ['subject'] },\n }),\n messages: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: parent({ via: 'ticket_id' }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n staff_notes: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: appRole({ roles: { read: ['staff'], create: ['staff'] } }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n pages: table({ id: id(), title: text(), published: boolean({ default: false }) }, {\n scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'],\n publicRead: { where: { published: true } } },\n }),\n note_shares: table({ id: id(), grantee_id: text(), note_id: text({ references: 'shared_notes', onDelete: 'cascade' }) }, {\n scope: owner(), unique: [['note_id', 'grantee_id']],\n }),\n shared_notes: table({ id: id(), title: text() }, {\n scope: anyOf(owner(), grant({ table: 'note_shares', grantee: 'grantee_id', row: 'note_id', operations: ['read'] })),\n client: { read: ['id', 'title'], create: ['title'], update: ['title'] },\n }),\n}, { appRoles: { staff: { emailDomain: 'staff.example' } } });\n```\n\nWho is staff is your app's decision; the platform enforces what the role may do.\nFirst choice, as above: emailDomain. The role holds once the person verifies an address\nat that domain; no grant code. An email ending alone proves nothing: anyone can sign up\nas anyone@your-domain without owning that mailbox. Without verification, grant only from\nsomething the visitor cannot choose, such as an invitation your app issued, checked inside\nthe sign-up route: single use, bound to one account, its link delivered only to that person:\nsomewhere docs sw.auth --section server-assigned-app-roles-setroles.\nmessages use parent(): owner() would hide staff replies from the customer.\nPublish pages in an owner-checked endpoint. Share with caller-scoped\nsw.db.insert('note_shares', { grantee_id, note_id }); it checks row ownership.\nBrowser calls THROW, not { error }; catch below.\nBrowser list: max 100, paginate after; no order (sort locally or in an endpoint).\n\n```ts\nimport { data } from 'somewhere:data';\nexport async function save(title: string) {\n try { await data.notes.create({ title }); return null; }\n catch (e) { return e instanceof Error ? e.message : 'Save failed'; }\n}\nexport const list = (after?: string) => data.notes.list({ limit: 100, after });\n```\n\nTeams are built-in groups: the platform keeps the team, invitations, roster, removal,\nleaving, last owner. Starting a team needs a signed-in user; joining needs a verified\nemail (a password sign-up joins once it enters its emailed code). The browser cannot call\nsw.groups: pass each call through an endpoint. A parent() child's delete follows the task\n(creator or team owner), so \"comment author or team owner deletes\" is an endpoint.\nStaff making others staff: appRoles { staff: { grantableBy: ['staff'] } } and\nsw.groups.appRoles.grant(request, userId, 'staff') in an endpoint (never to oneself).\nComplete apps and specs: somewhere docs sw.groups --section team-example or staff-example.\n\n```ts\n// api/teams.ts \u2014 GET my teams (completes invitations to me); POST starts one I own\nconst refusal = (e: { code: string; message: string; status: number }) =>\n Response.json({ error: e.code, message: e.message }, { status: e.status });\nexport const GET = sw.endpoint({ auth: 'required', handler: async ({ request }, sw) => {\n const page = await sw.groups.list(request, { limit: 100 });\n return page.error ? refusal(page.error) : { teams: page.data.items, next_cursor: page.data.next_cursor };\n} });\nexport default sw.endpoint({ auth: 'required', body: { name: 'string' }, handler: async ({ request, body }, sw) => {\n const made = await sw.groups.create(request, { name: body.name });\n return made.error ? refusal(made.error) : { id: made.data.id };\n} });\n```\n\n```ts\n// api/teams/[id]/invitations.ts \u2014 owners invite; others 403; a member's address 409 ALREADY_MEMBER\nexport default sw.endpoint({ auth: 'required', body: { email: 'string' }, handler: async ({ request, params, body }, sw) => {\n const sent = await sw.groups.invite(request, params.id, { email: body.email, role: 'member', redirect_uri: '/' });\n return sent.error ? Response.json({ error: sent.error.code }, { status: sent.error.status }) : { delivery: sent.data.delivery };\n} });\n```\n\nSame shape: sw.groups.get/members(request, id), remove(request, id, userId), leave(request, id)\n(last owner: 409 LAST_OWNER), delete(request, id) by owners.\n\nDo not hand-write access to app-read/write data: declare who may read/write it.\nserverOnly() fits job/import/audit/counter state.\nGrant ledgers use owner() without browser writes. Undeclarable: arbitrary predicates\n(e.g. expiry) or per-role writable fields (split tables or check that write).\n\nBuild src/pages/HomePage.tsx; routes src/App.tsx + src/routes.ts; auth src/auth/hooks.ts.\nAuth is wired: keep api/auth/[...path].ts; src/config.ts controls providers.\napi/notes/[id]/sub.ts \u2192 params.id; underscore files are helpers. POST: default export;\nGET/DELETE: named exports.\n\n```ts\nexport const GET = sw.endpoint({ auth: 'required', handler: async (_, sw) => sw.db.from('notes', { limit: 100 }) });\n```\n\nsw.db applies caller scopes; sw.db.server bypasses them: authorize first.\nCaller-scoped sw.db.insert needs no client.create grant: client limits only the browser.\nReads: from(table, { where, columns, order: [['id', 'asc']], limit, offset }).\nFilter: { id: { in: ids } }; unique: [['a', 'b']] in schema.\nWrites: insert(table, values), update(table, { where, set }), remove(table, { where }).\ntx takes an ARRAY of write intents, never a callback; pre-generate related IDs.\n\nBrowser: fetch(path, { method: 'POST', credentials: 'same-origin',\nheaders: { 'content-type': 'application/json' }, body: JSON.stringify(values) }).\nAccess cookies refresh automatically. Cookie-auth POST/PATCH/DELETE from scripts\nneed Origin equal to the app URL.\n\nTest with an ordinary Playwright script: the journeys you changed and your access boundaries.\nRun it only after a successful deploy: npx @somewhere-cloud/cli deploy && node tests/app-check.mjs\n(the starter's short example; one result file, and the exit code is the verdict). Rerun only to answer a question.\nHelpers from @somewhere-cloud/cli/script (import or require): openAppTest() then app.signUp/signIn/signOut(page)\nthrough your form, app.data(page, { table, operation, id, values, where }) as that person,\napp.expectRefused(page, request, { allowed: ownerPage }), captureResponses, dataReady, launchOptions.\nA rebuilt sign-in form keeps data-sw-auth=\"email\", \"password\", \"sign-up\", \"sign-in\" on its controls,\nor pass app.signUp(page, { form: { email, password, signUp, signIn } }) with your own selectors.\nDeploy raw source, no frontend build; type errors stop upload.\nEmail-domain role: app.signUp(page, { domain: 'staff.example' }), then app.verify(page, person).\nThe complete team spec, with removal and leaving: somewhere docs sw.groups --section team-example.\nDiagnose with somewhere errors and somewhere logs.\n\nOn demand:\n- Server paging: `somewhere docs sw.db --section server-read-paging`\n\n## Testing shared access\n\nWith the team endpoints above, the owner invites a fixture by email; test users are verified,\nso its next GET /api/teams shows the team. A test user who still owns a team is not deleted:\ndelete the team last (api/teams/[id].ts DELETE: sw.groups.delete). Group calls take\nabout a second, so raise the timeout:\n\n```ts\n// tests/team.spec.ts\nimport { test, expect } from '@somewhere-cloud/cli/testing';\ntest.describe.configure({ timeout: 90_000 });\ntest('owner invites a second user by email', async ({ newUser }) => {\n const [owner, bob] = await Promise.all([newUser(), newUser()]);\n const { id } = await (await owner.request.post('/api/teams', { data: { name: 'Shared team' } })).json();\n expect((await owner.request.post(`/api/teams/${id}/invitations`, { data: { email: bob.email } })).ok()).toBeTruthy();\n const { teams } = await (await bob.request.get('/api/teams')).json();\n expect(teams).toContainEqual(expect.objectContaining({ id, role: 'member' }));\n expect((await owner.request.delete(`/api/teams/${id}`)).status()).toBe(204);\n});\n```\n\nTask-specific skills: `.agents/skills/`. Inspect/update with somewhere skills status/update.\nData/code export limits: `somewhere docs portability`.\nUse this app from Claude as its signed-in user (MCP tools): `somewhere docs sw.endpoint --section mcp-tools-for-claude`.\nsomewhere preview runs your change on a copy of production data, but sign-in, public reads for visitors, sw.groups, server user lookup, jobs/cron handlers and somewhere test do not work in a preview yet: check those in production after promoting (`somewhere docs dev-environments`).\n";
|
|
12
|
+
export declare const 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`.";
|
|
13
|
+
export declare const INIT_AGENTS_MD = "# somewhere.cloud project contract\n## Build, deploy, test\n\nEnough to start a typical app: declare access and use the browser client; docs are for exceptions.\n\n| Requirement | Declaration below |\n| --- | --- |\n| Each user sees only their own rows | notes: owner() |\n| Team: owner invites members; members read/write; creator or team owner deletes | tasks: anyOf(owner(), group()); sw.groups endpoints below |\n| Owner/staff record with staff-only child notes | tickets: owner() or appRole(); parent() thread; staff-only notes; staff by verified emailDomain (or grantableBy) |\n| Public pages from private drafts | pages: conditional publicRead |\n| Share one record read-only | shared_notes/note_shares: read-only grant() |\n\ndb/schema.ts is declaration only: imports, constants/spreads, default schema;\nno helpers/expressions. id() is random text; owner() stamps user_id. client.read\nincludes the key. Inside anyOf(), owner() takes only column/read: it stamps the\ncreator, not create/delete options; group() gates placement (non-member create is\nrefused); inside anyOf an operation missing from roles allows no group role. Other fields: timestamp({ default: 'now' }), text({ nullable: true });\nindexes: [['team_id']].\n\n```ts\nimport { schema, table, id, text, owner, group, anyOf, parent, appRole, boolean, grant } from 'somewhere/db';\nexport default schema({\n notes: table({ id: id(), title: text() }, { scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'], delete: true },\n }),\n tasks: table({ id: id(), team_id: text(), title: text() }, {\n scope: anyOf(owner(), group({ column: 'team_id', roles: { read: ['owner', 'admin', 'member'],\n create: ['owner', 'admin', 'member'], update: ['owner', 'admin', 'member'], delete: ['owner'] } })),\n client: { read: ['id', 'team_id', 'title'], create: ['team_id', 'title'], update: ['title'], delete: true },\n }),\n tickets: table({ id: id(), subject: text() }, {\n scope: anyOf(owner(), appRole({ roles: { read: ['staff'], create: ['staff'], update: ['staff'] } })),\n client: { read: true, create: ['subject'], update: ['subject'] },\n }),\n messages: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: parent({ via: 'ticket_id' }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n staff_notes: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {\n scope: appRole({ roles: { read: ['staff'], create: ['staff'] } }),\n client: { read: true, create: ['ticket_id', 'body'] },\n }),\n pages: table({ id: id(), title: text(), published: boolean({ default: false }) }, {\n scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'],\n publicRead: { where: { published: true } } },\n }),\n note_shares: table({ id: id(), grantee_id: text(), note_id: text({ references: 'shared_notes', onDelete: 'cascade' }) }, {\n scope: owner(), unique: [['note_id', 'grantee_id']],\n }),\n shared_notes: table({ id: id(), title: text() }, {\n scope: anyOf(owner(), grant({ table: 'note_shares', grantee: 'grantee_id', row: 'note_id', operations: ['read'] })),\n client: { read: ['id', 'title'], create: ['title'], update: ['title'] },\n }),\n}, { appRoles: { staff: { emailDomain: 'staff.example' } } });\n```\n\nWho is staff is your app's decision; the platform enforces what the role may do.\nFirst choice, as above: emailDomain. The role holds once the person verifies an address\nat that domain; no grant code. An email ending alone proves nothing: anyone can sign up\nas anyone@your-domain without owning that mailbox. Without verification, grant only from\nsomething the visitor cannot choose, such as an invitation your app issued, checked inside\nthe sign-up route: single use, bound to one account, its link delivered only to that person:\nsomewhere docs sw.auth --section server-assigned-app-roles-setroles.\nmessages use parent(): owner() would hide staff replies from the customer.\nA staff reply is a messages row, and creating a parent() child needs create on the parent\nfor that person: its owner, or a role listed under the parent's create. Read or update is\nnot enough. So tickets lists create: ['staff']; without it every staff reply is refused\n(403 POLICY_AUTHORITY_REQUIRED).\nPublish pages in an owner-checked endpoint. Share with caller-scoped\nsw.db.insert('note_shares', { grantee_id, note_id }); it checks row ownership.\nBrowser calls THROW, not { error }; catch below.\nBrowser list: max 100, paginate after; no order (sort locally or in an endpoint).\n\n```ts\nimport { data } from 'somewhere:data';\nexport async function save(title: string) {\n try { await data.notes.create({ title }); return null; }\n catch (e) { return e instanceof Error ? e.message : 'Save failed'; }\n}\nexport const list = (after?: string) => data.notes.list({ limit: 100, after });\n```\n\nTeams are built-in groups: the platform keeps the team, invitations, roster, removal,\nleaving, last owner. Starting a team needs a signed-in user; joining needs a verified\nemail (a password sign-up joins once it enters its emailed code). The browser cannot call\nsw.groups: pass each call through an endpoint. A parent() child's delete follows the task\n(creator or team owner), so \"comment author or team owner deletes\" is an endpoint.\nStaff making others staff: appRoles { staff: { grantableBy: ['staff'] } } and\nsw.groups.appRoles.grant(request, userId, 'staff') in an endpoint (never to oneself).\nComplete apps and specs: somewhere docs sw.groups --section team-example or staff-example.\n\n```ts\n// api/teams.ts \u2014 GET my teams (completes invitations to me); POST starts one I own\nconst refusal = (e: { code: string; message: string; status: number }) =>\n Response.json({ error: e.code, message: e.message }, { status: e.status });\nexport const GET = sw.endpoint({ auth: 'required', handler: async ({ request }, sw) => {\n const page = await sw.groups.list(request, { limit: 100 });\n return page.error ? refusal(page.error) : { teams: page.data.items, next_cursor: page.data.next_cursor };\n} });\nexport default sw.endpoint({ auth: 'required', body: { name: 'string' }, handler: async ({ request, body }, sw) => {\n const made = await sw.groups.create(request, { name: body.name });\n return made.error ? refusal(made.error) : { id: made.data.id };\n} });\n```\n\n```ts\n// api/teams/[id]/invitations.ts \u2014 owners invite; others 403; a member's address 409 ALREADY_MEMBER\nexport default sw.endpoint({ auth: 'required', body: { email: 'string' }, handler: async ({ request, params, body }, sw) => {\n const sent = await sw.groups.invite(request, params.id, { email: body.email, role: 'member', redirect_uri: '/' });\n return sent.error ? Response.json({ error: sent.error.code }, { status: sent.error.status }) : { delivery: sent.data.delivery };\n} });\n```\n\nSame shape: sw.groups.get/members(request, id), remove(request, id, userId), leave(request, id)\n(last owner: 409 LAST_OWNER), delete(request, id) by owners.\n\nDo not hand-write access to app-read/write data: declare who may read/write it.\nserverOnly() fits job/import/audit/counter state.\nGrant ledgers use owner() without browser writes. Undeclarable: arbitrary predicates\n(e.g. expiry) or per-role writable fields (split tables or check that write).\n\nBuild src/pages/HomePage.tsx; routes src/App.tsx + src/routes.ts; auth src/auth/hooks.ts.\nAuth is wired: keep api/auth/[...path].ts; src/config.ts controls providers.\napi/notes/[id]/sub.ts \u2192 params.id; underscore files are helpers. POST: default export;\nGET/DELETE: named exports.\n\n```ts\nexport const GET = sw.endpoint({ auth: 'required', handler: async (_, sw) => sw.db.from('notes', { limit: 100 }) });\n```\n\nsw.db applies caller scopes; sw.db.server bypasses them: authorize first.\nCaller-scoped sw.db.insert needs no client.create grant: client limits only the browser.\nReads: from(table, { where, columns, order: [['id', 'asc']], limit, offset }).\nFilter: { id: { in: ids } }; unique: [['a', 'b']] in schema.\nWrites: insert(table, values), update(table, { where, set }), remove(table, { where }).\ntx takes an ARRAY of write intents, never a callback; pre-generate related IDs.\n\nBrowser: fetch(path, { method: 'POST', credentials: 'same-origin',\nheaders: { 'content-type': 'application/json' }, body: JSON.stringify(values) }).\nAccess cookies refresh automatically. Cookie-auth POST/PATCH/DELETE from scripts\nneed Origin equal to the app URL.\n\nTest with an ordinary Playwright script: the journeys you changed and your access boundaries.\nRun it only after a successful deploy: npx @somewhere-cloud/cli deploy && node tests/app-check.mjs\n(the starter's short example; one result file, and the exit code is the verdict).\nKeep each run short:\n- Short waits: page.setDefaultTimeout(5_000) on every page; a deployed app answers in under\n a second. Never sleep for a fixed time: wait for the thing itself (the text, the response).\n- Stop at the first failure and print what the page showed (page.url(), the visible error\n text). Checks after a failure only wait out their timeouts. app.check() does both.\n- After a fix, rerun only the checks that failed: node tests/app-check.mjs --failed.\n Keep setup (sign-ups, rows a check needs) outside app.check() so a rerun still has it.\nCall the data endpoint as a signed-in person: app.data(page, { table, operation, id, values })\n(the raw request: somewhere docs declared-data --section calling-the-data-endpoint-directly).\nHelpers from @somewhere-cloud/cli/script (import or require): openAppTest() then app.signUp/signIn/signOut(page)\nthrough your form, app.data(page, { table, operation, id, values, where }) as that person,\napp.expectRefused(page, request, { allowed: ownerPage }), captureResponses, dataReady, launchOptions.\nA rebuilt sign-in form keeps data-sw-auth=\"email\", \"password\", \"sign-up\", \"sign-in\" on its controls,\nor pass app.signUp(page, { form: { email, password, signUp, signIn } }) with your own selectors.\nDeploy raw source, no frontend build; type errors stop upload.\nEmail-domain role: app.signUp(page, { domain: 'staff.example' }), then app.verify(page, person).\nThe complete team spec, with removal and leaving: somewhere docs sw.groups --section team-example.\nDiagnose with somewhere errors and somewhere logs.\n\nOn demand:\n- Server paging: `somewhere docs sw.db --section server-read-paging`\n\n## Testing shared access\n\nWith the team endpoints above, the owner invites a fixture by email; test users are verified,\nso its next GET /api/teams shows the team. A test user who still owns a team is not deleted:\ndelete the team last (api/teams/[id].ts DELETE: sw.groups.delete). Group calls take\nabout a second, so raise the timeout:\n\n```ts\n// tests/team.spec.ts\nimport { test, expect } from '@somewhere-cloud/cli/testing';\ntest.describe.configure({ timeout: 90_000 });\ntest('owner invites a second user by email', async ({ newUser }) => {\n const [owner, bob] = await Promise.all([newUser(), newUser()]);\n const { id } = await (await owner.request.post('/api/teams', { data: { name: 'Shared team' } })).json();\n expect((await owner.request.post(`/api/teams/${id}/invitations`, { data: { email: bob.email } })).ok()).toBeTruthy();\n const { teams } = await (await bob.request.get('/api/teams')).json();\n expect(teams).toContainEqual(expect.objectContaining({ id, role: 'member' }));\n expect((await owner.request.delete(`/api/teams/${id}`)).status()).toBe(204);\n});\n```\n\nTask-specific skills: `.agents/skills/`. Inspect/update with somewhere skills status/update.\nData/code export limits: `somewhere docs portability`.\nUse this app from Claude as its signed-in user (MCP tools): `somewhere docs sw.endpoint --section mcp-tools-for-claude`.\nsomewhere 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`.\n";
|
|
14
14
|
export declare const INIT_CLAUDE_MD = "Read AGENTS.md for project instructions.\n";
|
|
@@ -64,6 +64,10 @@ something the visitor cannot choose, such as an invitation your app issued, chec
|
|
|
64
64
|
the sign-up route: single use, bound to one account, its link delivered only to that person:
|
|
65
65
|
somewhere docs sw.auth --section server-assigned-app-roles-setroles.
|
|
66
66
|
messages use parent(): owner() would hide staff replies from the customer.
|
|
67
|
+
A staff reply is a messages row, and creating a parent() child needs create on the parent
|
|
68
|
+
for that person: its owner, or a role listed under the parent's create. Read or update is
|
|
69
|
+
not enough. So tickets lists create: ['staff']; without it every staff reply is refused
|
|
70
|
+
(403 POLICY_AUTHORITY_REQUIRED).
|
|
67
71
|
Publish pages in an owner-checked endpoint. Share with caller-scoped
|
|
68
72
|
sw.db.insert('note_shares', { grantee_id, note_id }); it checks row ownership.
|
|
69
73
|
Browser calls THROW, not { error }; catch below.
|
|
@@ -140,7 +144,16 @@ need Origin equal to the app URL.
|
|
|
140
144
|
|
|
141
145
|
Test with an ordinary Playwright script: the journeys you changed and your access boundaries.
|
|
142
146
|
Run it only after a successful deploy: npx @somewhere-cloud/cli deploy && node tests/app-check.mjs
|
|
143
|
-
(the starter's short example; one result file, and the exit code is the verdict).
|
|
147
|
+
(the starter's short example; one result file, and the exit code is the verdict).
|
|
148
|
+
Keep each run short:
|
|
149
|
+
- Short waits: page.setDefaultTimeout(5_000) on every page; a deployed app answers in under
|
|
150
|
+
a second. Never sleep for a fixed time: wait for the thing itself (the text, the response).
|
|
151
|
+
- Stop at the first failure and print what the page showed (page.url(), the visible error
|
|
152
|
+
text). Checks after a failure only wait out their timeouts. app.check() does both.
|
|
153
|
+
- After a fix, rerun only the checks that failed: node tests/app-check.mjs --failed.
|
|
154
|
+
Keep setup (sign-ups, rows a check needs) outside app.check() so a rerun still has it.
|
|
155
|
+
Call the data endpoint as a signed-in person: app.data(page, { table, operation, id, values })
|
|
156
|
+
(the raw request: somewhere docs declared-data --section calling-the-data-endpoint-directly).
|
|
144
157
|
Helpers from @somewhere-cloud/cli/script (import or require): openAppTest() then app.signUp/signIn/signOut(page)
|
|
145
158
|
through your form, app.data(page, { table, operation, id, values, where }) as that person,
|
|
146
159
|
app.expectRefused(page, request, { allowed: ownerPage }), captureResponses, dataReady, launchOptions.
|
|
@@ -185,7 +198,7 @@ export const PORTABILITY_POINTER = 'Data/code export limits: `somewhere docs por
|
|
|
185
198
|
export const MCP_POINTER = 'Use this app from Claude as its signed-in user (MCP tools): `somewhere docs sw.endpoint --section mcp-tools-for-claude`.';
|
|
186
199
|
/** One line on what a preview cannot do today, so no agent learns it by failing.
|
|
187
200
|
* Rewrite it when previews gain these (the full list: docs dev-environments). */
|
|
188
|
-
export const PREVIEW_POINTER = 'somewhere preview runs your change on a copy of production data
|
|
201
|
+
export const 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`.';
|
|
189
202
|
export const INIT_AGENTS_MD = `# somewhere.cloud project contract\n${AGENT_WORKFLOW}\n${SKILLS_POINTER}\n${PORTABILITY_POINTER}\n${MCP_POINTER}\n${PREVIEW_POINTER}\n`;
|
|
190
203
|
export const INIT_CLAUDE_MD = 'Read AGENTS.md for project instructions.\n';
|
|
191
204
|
//# sourceMappingURL=init-agent-guide.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init-agent-guide.js","sourceRoot":"","sources":["../../src/lib/init-agent-guide.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C,2EAA2E;AAC3E,0EAA0E;AAC1E,MAAM,CAAC,MAAM,cAAc,GAAG
|
|
1
|
+
{"version":3,"file":"init-agent-guide.js","sourceRoot":"","sources":["../../src/lib/init-agent-guide.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C,2EAA2E;AAC3E,0EAA0E;AAC1E,MAAM,CAAC,MAAM,cAAc,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0L7B,CAAC;AAEF,MAAM,CAAC,MAAM,cAAc,GAAG,2BAA2B,UAAU,0DAA0D,CAAC;AAE9H,MAAM,CAAC,MAAM,uBAAuB,GAAG,EAAE,CAAC;AAE1C;;+EAE+E;AAC/E,MAAM,CAAC,MAAM,mBAAmB,GAAG,wDAAwD,CAAC;AAE5F,6EAA6E;AAC7E,MAAM,CAAC,MAAM,WAAW,GAAG,0HAA0H,CAAC;AAEtJ;kFACkF;AAClF,MAAM,CAAC,MAAM,eAAe,GAAG,omBAAomB,CAAC;AAEpoB,MAAM,CAAC,MAAM,cAAc,GAAG,uCAAuC,cAAc,KAAK,cAAc,KAAK,mBAAmB,KAAK,WAAW,KAAK,eAAe,IAAI,CAAC;AACvK,MAAM,CAAC,MAAM,cAAc,GAAG,4CAA4C,CAAC"}
|
|
@@ -5,6 +5,8 @@ const SCRIPT = (privateData) => `// tests/app-check.mjs — an ordinary Playwrig
|
|
|
5
5
|
// what you built. Run it after a successful deploy, never after a refused one:
|
|
6
6
|
// npx somewhere deploy && node tests/app-check.mjs
|
|
7
7
|
// It writes its result once to .somewhere/app-check.json; the exit code is the verdict.
|
|
8
|
+
// It stops at the first failed check and prints the page's URL and visible error text.
|
|
9
|
+
// After a fix, rerun only what failed: node tests/app-check.mjs --failed (keep setup outside app.check).
|
|
8
10
|
// From a .cjs script: const { openAppTest } = require('@somewhere-cloud/cli/script');
|
|
9
11
|
import { chromium } from '@playwright/test';
|
|
10
12
|
import { openAppTest${privateData ? ', captureResponses, dataReady' : ''} } from '@somewhere-cloud/cli/script';
|
|
@@ -15,6 +17,7 @@ const browser = await chromium.launch(app.launchOptions());
|
|
|
15
17
|
// deleted by exact id in finish()).
|
|
16
18
|
const person = async () => {
|
|
17
19
|
const page = await browser.newPage({ baseURL: app.origin });
|
|
20
|
+
page.setDefaultTimeout(5_000); // a deployed app answers in well under a second; never sleep, wait for the thing itself
|
|
18
21
|
return { page, account: await app.signUp(page) };
|
|
19
22
|
};
|
|
20
23
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init-test-template.js","sourceRoot":"","sources":["../../src/lib/init-test-template.ts"],"names":[],"mappings":"AAEA,8FAA8F;AAC9F,qGAAqG;AACrG,wEAAwE;AAExE,MAAM,MAAM,GAAG,CAAC,WAAoB,EAAE,EAAE,CAAC
|
|
1
|
+
{"version":3,"file":"init-test-template.js","sourceRoot":"","sources":["../../src/lib/init-test-template.ts"],"names":[],"mappings":"AAEA,8FAA8F;AAC9F,qGAAqG;AACrG,wEAAwE;AAExE,MAAM,MAAM,GAAG,CAAC,WAAoB,EAAE,EAAE,CAAC;;;;;;;;sBAQnB,WAAW,CAAC,CAAC,CAAC,+BAA+B,CAAC,CAAC,CAAC,EAAE;;;;;;;;;;;;;;;;;;EAkBtE,WAAW,CAAC,CAAC,CAAC;;;;;;;;;;;;;;;CAef,CAAC,CAAC,CAAC,EAAE;;;;;;;;;;;;;;CAcL,CAAC;AAEF,kGAAkG;AAClG,MAAM,UAAU,YAAY,CAAC,UAAqC,EAAE;IAClE,OAAO,CAAC,EAAE,IAAI,EAAE,qBAAqB,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC,CAAC;AAC1F,CAAC"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { APIRequestContext, APIResponse, Page, TestType, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions } from '@playwright/test';
|
|
2
2
|
import { ready, type FormHost, type FormControl, type Attempt, type Person, type FormSteps, type CodeSteps, type SignUpOptions, type SignInOptions, type FormAdapter } from './form-auth.js';
|
|
3
|
+
import { type TestControl } from './test-control.js';
|
|
3
4
|
export type { Person, FormSteps, CodeSteps, SignUpOptions, SignInOptions, FormAdapter };
|
|
4
5
|
import type { TestInfo } from '@playwright/test';
|
|
5
6
|
import type { DataRequest } from '../testing.js';
|
|
@@ -14,6 +15,9 @@ export interface TestUser {
|
|
|
14
15
|
export interface NewUserOptions {
|
|
15
16
|
role?: string;
|
|
16
17
|
}
|
|
18
|
+
interface WorkerFixtures {
|
|
19
|
+
_preview: TestControl | null;
|
|
20
|
+
}
|
|
17
21
|
interface Fixtures {
|
|
18
22
|
_evidence: void;
|
|
19
23
|
anonymous: APIRequestContext;
|
|
@@ -31,7 +35,7 @@ interface Fixtures {
|
|
|
31
35
|
form?: FormAdapter;
|
|
32
36
|
}) => Promise<void>;
|
|
33
37
|
}
|
|
34
|
-
type RunnerTest = TestType<PlaywrightTestArgs & PlaywrightTestOptions & Fixtures, PlaywrightWorkerArgs & PlaywrightWorkerOptions>;
|
|
38
|
+
type RunnerTest = TestType<PlaywrightTestArgs & PlaywrightTestOptions & Fixtures, PlaywrightWorkerArgs & PlaywrightWorkerOptions & WorkerFixtures>;
|
|
35
39
|
export declare const test: RunnerTest;
|
|
36
40
|
export declare const expect: typeof import('@playwright/test').expect;
|
|
37
41
|
type Person_ = Page | {
|
|
@@ -62,13 +66,16 @@ export declare function data(client: APIRequestContext, table: string, request:
|
|
|
62
66
|
export { ready };
|
|
63
67
|
declare class FormRun implements FormHost {
|
|
64
68
|
readonly info: TestInfo;
|
|
69
|
+
private readonly preview;
|
|
65
70
|
readonly pages: Set<Page>;
|
|
66
71
|
readonly attempts: Attempt[];
|
|
67
72
|
private loading?;
|
|
73
|
+
private readonly prepared;
|
|
68
74
|
readonly root: string;
|
|
69
|
-
constructor(info: TestInfo);
|
|
75
|
+
constructor(info: TestInfo, preview: TestControl | null);
|
|
70
76
|
timed<T>(name: string, work: () => Promise<T>): Promise<T>;
|
|
71
77
|
control(): Promise<FormControl>;
|
|
78
|
+
prepare(page: Page): Promise<void>;
|
|
72
79
|
/** The page's own request client, with the app Origin and the data contract, for data()/expectRefused(). */
|
|
73
80
|
attach(page: Page): Promise<void>;
|
|
74
81
|
/** Email codes travel by real mail paths; give each auth step room inside the test's timeout. */
|
|
@@ -4,12 +4,42 @@ import { fixtureTestTarget } from './test-target.js';
|
|
|
4
4
|
import { ApiClient } from './client.js';
|
|
5
5
|
import { getToken, loadProjectConfig } from './config.js';
|
|
6
6
|
import { buildStorageState, createTestIdentities, expiryOf } from './test-identities.js';
|
|
7
|
-
import { diagnostics, rememberSecrets, scrub, describeError, timed, titled } from './test-diagnostics.js';
|
|
7
|
+
import { diagnostics, rememberSecrets, scrub, scrubTestErrors, describeError, timed, titled } from './test-diagnostics.js';
|
|
8
8
|
import { mark as timelineMark, markProcessStart, span, trackPage } from './test-timeline.js';
|
|
9
|
-
import {
|
|
9
|
+
import { forgetRecord } from './form-accounts.js';
|
|
10
10
|
import { ready, signUp, signIn, signOut, verify } from './form-auth.js';
|
|
11
|
+
import { openPreviewControl, openProductionControl } from './test-control.js';
|
|
12
|
+
import { safeToScreenshot } from './screenshot-guard.js';
|
|
13
|
+
// Playwright adds an accessibility snapshot of the failing page (its visible text, which can show a
|
|
14
|
+
// password, an emailed code or a reset link) to error-context.md. Off in every worker that loads these
|
|
15
|
+
// fixtures, whether or not `somewhere test` started it; the runner sets it too.
|
|
16
|
+
process.env.PLAYWRIGHT_NO_COPY_PROMPT = '1';
|
|
11
17
|
let loaded;
|
|
12
18
|
const digests = new WeakMap();
|
|
19
|
+
/** The run's target as the runner passed it (no credential is ever in it). */
|
|
20
|
+
function runTarget(projectId) {
|
|
21
|
+
if (!process.env.SW_TEST_TARGET)
|
|
22
|
+
return null;
|
|
23
|
+
const target = JSON.parse(process.env.SW_TEST_TARGET);
|
|
24
|
+
if (target.projectId !== projectId)
|
|
25
|
+
throw new Error('Test target belongs to a different project');
|
|
26
|
+
return target;
|
|
27
|
+
}
|
|
28
|
+
function linkedProject() {
|
|
29
|
+
const projectId = loadProjectConfig()?.project_id;
|
|
30
|
+
if (!projectId)
|
|
31
|
+
throw new Error('Run somewhere test from a linked project folder.');
|
|
32
|
+
return projectId;
|
|
33
|
+
}
|
|
34
|
+
/** A preview run's control for this worker, or null for a production run. A preview run never
|
|
35
|
+
* builds a production client: its control holds only the preview's tool credential. */
|
|
36
|
+
async function previewControlForWorker() {
|
|
37
|
+
const projectId = linkedProject();
|
|
38
|
+
const target = runTarget(projectId);
|
|
39
|
+
if (target?.environment !== 'preview')
|
|
40
|
+
return null;
|
|
41
|
+
return openPreviewControl({ root: process.cwd(), projectId, expect: target });
|
|
42
|
+
}
|
|
13
43
|
function runner() {
|
|
14
44
|
if (loaded)
|
|
15
45
|
return loaded;
|
|
@@ -22,16 +52,36 @@ function runner() {
|
|
|
22
52
|
throw new Error('Install project test dependencies: npm install -D @playwright/test @somewhere-cloud/cli');
|
|
23
53
|
}
|
|
24
54
|
const test = pw.test.extend({
|
|
55
|
+
_preview: [async ({}, use) => {
|
|
56
|
+
const control = await previewControlForWorker();
|
|
57
|
+
try {
|
|
58
|
+
await use(control);
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
await control?.close();
|
|
62
|
+
}
|
|
63
|
+
}, { scope: 'worker' }],
|
|
64
|
+
// A preview run: every browser context reaches the preview through the run's pinned session.
|
|
65
|
+
context: async ({ context, _preview }, use) => {
|
|
66
|
+
if (_preview)
|
|
67
|
+
await _preview.prepareContext(context);
|
|
68
|
+
await use(context);
|
|
69
|
+
},
|
|
25
70
|
_evidence: [async ({}, use, info) => {
|
|
26
71
|
try {
|
|
27
72
|
await use();
|
|
28
73
|
}
|
|
29
74
|
finally {
|
|
75
|
+
// Torn down after every other somewhere fixture and before Playwright writes error-context.md
|
|
76
|
+
// or reports the errors: scrub them in place first.
|
|
77
|
+
scrubTestErrors(info.errors);
|
|
30
78
|
const report = diagnostics(info);
|
|
31
79
|
await info.attach('somewhere-diagnostics', { body: Buffer.from(JSON.stringify({ ...report, title: titled(info.project.name, scrub(info.title)), errors: info.errors.map(error => describeError(error)), secretAudit: 'issued values scrubbed before reporting' })), contentType: 'application/json' });
|
|
32
80
|
}
|
|
33
81
|
}, { auto: true }],
|
|
34
|
-
newUser: async ({ browser, viewport, isMobile, hasTouch }, use, info) => {
|
|
82
|
+
newUser: async ({ browser, viewport, isMobile, hasTouch, _preview }, use, info) => {
|
|
83
|
+
if (_preview)
|
|
84
|
+
return previewNewUser(_preview, { browser, viewport, isMobile, hasTouch }, use, info);
|
|
35
85
|
const linked = loadProjectConfig()?.project_id;
|
|
36
86
|
if (!linked)
|
|
37
87
|
throw new Error('Run somewhere test from a linked project folder.');
|
|
@@ -99,7 +149,7 @@ function runner() {
|
|
|
99
149
|
rememberSecrets(...(await context.cookies()).map(cookie => cookie.value));
|
|
100
150
|
if (info.status !== info.expectedStatus && !diagnostics(info).screenshot) {
|
|
101
151
|
const page = context.pages()[0];
|
|
102
|
-
if (page &&
|
|
152
|
+
if (page && await safeToScreenshot(page)) {
|
|
103
153
|
const path = info.outputPath('failure.png');
|
|
104
154
|
await page.screenshot({ path, mask: [page.locator('input, textarea')] });
|
|
105
155
|
diagnostics(info).screenshot = path;
|
|
@@ -132,15 +182,16 @@ function runner() {
|
|
|
132
182
|
throw new Error(failures.join('; '));
|
|
133
183
|
}
|
|
134
184
|
},
|
|
135
|
-
anonymous: async ({ browser }, use, info) => {
|
|
185
|
+
anonymous: async ({ browser, _preview }, use, info) => {
|
|
136
186
|
const projectId = loadProjectConfig()?.project_id;
|
|
137
187
|
if (!projectId)
|
|
138
188
|
throw new Error('Run from a linked project folder.');
|
|
139
|
-
const
|
|
140
|
-
const target = await timed(info, 'target snapshot', () => fixtureTestTarget(client, projectId));
|
|
189
|
+
const target = _preview ? _preview.target : await timed(info, 'target snapshot', () => fixtureTestTarget(new ApiClient(getToken()), projectId));
|
|
141
190
|
const { origin } = target;
|
|
142
191
|
diagnostics(info).release = target.releaseId;
|
|
143
192
|
const context = await browser.newContext({ baseURL: origin, extraHTTPHeaders: { Origin: origin } });
|
|
193
|
+
if (_preview)
|
|
194
|
+
await _preview.prepareContext(context);
|
|
144
195
|
constrain(context.request, origin, info);
|
|
145
196
|
digests.set(context.request, target.contractDigest);
|
|
146
197
|
try {
|
|
@@ -151,12 +202,14 @@ function runner() {
|
|
|
151
202
|
await context.close();
|
|
152
203
|
}
|
|
153
204
|
},
|
|
154
|
-
newPage: async ({ browser, baseURL, viewport, isMobile, hasTouch, _forms }, use, info) => {
|
|
205
|
+
newPage: async ({ browser, baseURL, viewport, isMobile, hasTouch, _forms, _preview }, use, info) => {
|
|
155
206
|
const contexts = [];
|
|
156
207
|
try {
|
|
157
208
|
await use(async () => {
|
|
158
209
|
const context = await browser.newContext({ baseURL, viewport, isMobile, hasTouch });
|
|
159
210
|
contexts.push(context);
|
|
211
|
+
if (_preview)
|
|
212
|
+
await _preview.prepareContext(context);
|
|
160
213
|
const page = await context.newPage();
|
|
161
214
|
trackPage(page, titled(info.project.name, info.title));
|
|
162
215
|
_forms.pages.add(page);
|
|
@@ -169,8 +222,8 @@ function runner() {
|
|
|
169
222
|
}
|
|
170
223
|
},
|
|
171
224
|
// Depends on page so its teardown (screenshots, cookie scrubbing) runs while the page is open.
|
|
172
|
-
_forms: async ({ page }, use, info) => {
|
|
173
|
-
const run = new FormRun(info);
|
|
225
|
+
_forms: async ({ page, _preview }, use, info) => {
|
|
226
|
+
const run = new FormRun(info, _preview);
|
|
174
227
|
trackPage(page, titled(info.project.name, info.title));
|
|
175
228
|
run.pages.add(page);
|
|
176
229
|
try {
|
|
@@ -188,6 +241,72 @@ function runner() {
|
|
|
188
241
|
loaded = { test, expect: pw.expect };
|
|
189
242
|
return loaded;
|
|
190
243
|
}
|
|
244
|
+
/**
|
|
245
|
+
* newUser in a preview run: a managed test user made with the preview's developer tool (its
|
|
246
|
+
* password is returned once and never printed), signed in through the app's own auth route on the
|
|
247
|
+
* preview, and deleted by id at the end. App roles are assigned by the app's own server code in a
|
|
248
|
+
* preview (sw.auth.server.setRoles), so `{ role }` is refused rather than granted some other way.
|
|
249
|
+
*/
|
|
250
|
+
async function previewNewUser(control, args, use, info) {
|
|
251
|
+
const { origin } = control.target;
|
|
252
|
+
diagnostics(info).release = control.target.releaseId;
|
|
253
|
+
const ids = [];
|
|
254
|
+
const contexts = [];
|
|
255
|
+
const inflight = new Set();
|
|
256
|
+
const create = async (options = {}) => {
|
|
257
|
+
if (options.role !== undefined) {
|
|
258
|
+
throw new Error('newUser({ role }) is not available in a preview: a preview grants roles only through your app\'s own server code (sw.auth.server.setRoles). Sign the person up and let the app grant it, or test the role in production.');
|
|
259
|
+
}
|
|
260
|
+
const user = await timed(info, 'test-user creation', () => control.createManagedUser());
|
|
261
|
+
ids.push(user.id);
|
|
262
|
+
const context = await args.browser.newContext({ baseURL: origin, viewport: args.viewport, isMobile: args.isMobile, hasTouch: args.hasTouch, extraHTTPHeaders: { Origin: origin } });
|
|
263
|
+
contexts.push(context);
|
|
264
|
+
await control.prepareContext(context);
|
|
265
|
+
const signedIn = await timed(info, 'test-user sign-in', () => context.request.post(origin + '/api/auth/login', { data: { email: user.email, password: user.password }, headers: { Origin: origin }, maxRedirects: 0 }));
|
|
266
|
+
rememberSecrets(...(await context.cookies()).map((cookie) => cookie.value));
|
|
267
|
+
if (!signedIn.ok()) {
|
|
268
|
+
throw new Error(`newUser: the preview test user could not sign in through the app's /api/auth/login (HTTP ${signedIn.status()}). In a preview, newUser signs in through the app's own auth route; an app without one can use signUp(page) and signIn(page, person).`);
|
|
269
|
+
}
|
|
270
|
+
constrain(context.request, origin, info);
|
|
271
|
+
digests.set(context.request, control.target.contractDigest);
|
|
272
|
+
const page = await timed(info, 'page creation', () => context.newPage());
|
|
273
|
+
trackPage(page, titled(info.project.name, info.title));
|
|
274
|
+
return { id: user.id, email: user.email, page, request: context.request };
|
|
275
|
+
};
|
|
276
|
+
try {
|
|
277
|
+
await use((options) => { const creation = create(options); inflight.add(creation); void creation.finally(() => inflight.delete(creation)).catch(() => { }); return creation; });
|
|
278
|
+
}
|
|
279
|
+
finally {
|
|
280
|
+
while (inflight.size)
|
|
281
|
+
await Promise.allSettled([...inflight]);
|
|
282
|
+
const failures = [];
|
|
283
|
+
for (const context of contexts) {
|
|
284
|
+
try {
|
|
285
|
+
rememberSecrets(...(await context.cookies()).map((cookie) => cookie.value));
|
|
286
|
+
}
|
|
287
|
+
catch { /* closed */ }
|
|
288
|
+
const page = context.pages()[0];
|
|
289
|
+
if (info.status !== info.expectedStatus && !diagnostics(info).screenshot && page && await safeToScreenshot(page)) {
|
|
290
|
+
try {
|
|
291
|
+
const path = info.outputPath('failure.png');
|
|
292
|
+
await page.screenshot({ path, mask: [page.locator('input, textarea')] });
|
|
293
|
+
diagnostics(info).screenshot = path;
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
failures.push('Failure screenshot capture failed');
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
await Promise.all(contexts.map((context) => context.close().catch(() => { failures.push('Browser context cleanup failed'); })));
|
|
301
|
+
for (const id of ids) {
|
|
302
|
+
const refused = await timed(info, 'test-user deletion', () => control.deleteManagedUser(id));
|
|
303
|
+
if (refused !== null)
|
|
304
|
+
failures.push(`Preview test user cleanup unconfirmed (${refused})`);
|
|
305
|
+
}
|
|
306
|
+
if (failures.length)
|
|
307
|
+
throw new Error(failures.join('; '));
|
|
308
|
+
}
|
|
309
|
+
}
|
|
191
310
|
// Patch the shared-cookie client, preserving its identity and cookie rotation.
|
|
192
311
|
function constrain(client, origin, info) {
|
|
193
312
|
for (const method of ['fetch']) {
|
|
@@ -376,29 +495,38 @@ export { ready };
|
|
|
376
495
|
const constrained = new WeakSet();
|
|
377
496
|
class FormRun {
|
|
378
497
|
info;
|
|
498
|
+
preview;
|
|
379
499
|
pages = new Set();
|
|
380
500
|
attempts = [];
|
|
381
501
|
loading;
|
|
502
|
+
prepared = new WeakSet();
|
|
382
503
|
root = process.cwd();
|
|
383
|
-
constructor(info) {
|
|
504
|
+
constructor(info, preview) {
|
|
384
505
|
this.info = info;
|
|
506
|
+
this.preview = preview;
|
|
385
507
|
}
|
|
386
508
|
timed(name, work) { return timed(this.info, name, work); }
|
|
387
509
|
control() {
|
|
388
510
|
return this.loading ??= (async () => {
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
diagnostics(this.info).release = target.releaseId;
|
|
395
|
-
return {
|
|
511
|
+
// A preview run uses its worker's preview control; only a production run reads your sign-in.
|
|
512
|
+
const control = this.preview ?? await timed(this.info, 'target snapshot', async () => {
|
|
513
|
+
const projectId = linkedProject();
|
|
514
|
+
return openProductionControl(projectId, runTarget(projectId) ?? undefined);
|
|
515
|
+
});
|
|
516
|
+
diagnostics(this.info).release = control.target.releaseId;
|
|
517
|
+
return { control };
|
|
396
518
|
})();
|
|
397
519
|
}
|
|
520
|
+
async prepare(page) {
|
|
521
|
+
if (!this.preview || this.prepared.has(page.context()))
|
|
522
|
+
return;
|
|
523
|
+
this.prepared.add(page.context());
|
|
524
|
+
await this.preview.prepareContext(page.context());
|
|
525
|
+
}
|
|
398
526
|
/** The page's own request client, with the app Origin and the data contract, for data()/expectRefused(). */
|
|
399
527
|
async attach(page) {
|
|
400
528
|
this.pages.add(page);
|
|
401
|
-
const { target } = await this.control();
|
|
529
|
+
const { target } = (await this.control()).control;
|
|
402
530
|
const request = page.context().request;
|
|
403
531
|
if (constrained.has(request))
|
|
404
532
|
return;
|
|
@@ -419,7 +547,7 @@ class FormRun {
|
|
|
419
547
|
rememberSecrets(...(await page.context().cookies()).map(cookie => cookie.value));
|
|
420
548
|
}
|
|
421
549
|
catch { /* context already closed */ }
|
|
422
|
-
if (failed && !diagnostics(this.info).screenshot)
|
|
550
|
+
if (failed && !diagnostics(this.info).screenshot && await safeToScreenshot(page))
|
|
423
551
|
try {
|
|
424
552
|
const path = this.info.outputPath('failure.png');
|
|
425
553
|
await page.screenshot({ path, mask: [page.locator('input, textarea')] });
|
|
@@ -432,9 +560,9 @@ class FormRun {
|
|
|
432
560
|
// Each account is deleted by its exact id; the deletions run at the same time.
|
|
433
561
|
await Promise.all(this.attempts.map(async (attempt) => {
|
|
434
562
|
if (attempt.id) {
|
|
435
|
-
const {
|
|
563
|
+
const { control } = await this.control();
|
|
436
564
|
const id = attempt.id;
|
|
437
|
-
const refused = await timed(this.info, 'sign-up account deletion', () =>
|
|
565
|
+
const refused = await timed(this.info, 'sign-up account deletion', () => control.deleteSignup(id));
|
|
438
566
|
if (refused === null)
|
|
439
567
|
forgetRecord(attempt.record);
|
|
440
568
|
else
|