@somewhere-cloud/cli 0.38.153 → 0.38.155

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.
Files changed (147) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/docs/adopt.md +39 -0
  3. package/dist/docs/analytics.md +161 -0
  4. package/dist/docs/api-reference.md +339 -0
  5. package/dist/docs/api-surface.md +2067 -0
  6. package/dist/docs/app-mcp.md +162 -0
  7. package/dist/docs/architecture-patterns.md +334 -0
  8. package/dist/docs/auth-client.md +531 -0
  9. package/dist/docs/billing.md +76 -0
  10. package/dist/docs/browser.md +639 -0
  11. package/dist/docs/calendar.md +298 -0
  12. package/dist/docs/changes.md +323 -0
  13. package/dist/docs/cli.md +407 -0
  14. package/dist/docs/common-mistakes.md +199 -0
  15. package/dist/docs/connect-agent.md +72 -0
  16. package/dist/docs/cors.md +114 -0
  17. package/dist/docs/cron.md +167 -0
  18. package/dist/docs/database-engine.md +167 -0
  19. package/dist/docs/declared-data.md +1656 -0
  20. package/dist/docs/declared-files.md +475 -0
  21. package/dist/docs/deploy-intelligence.md +188 -0
  22. package/dist/docs/deploy.md +733 -0
  23. package/dist/docs/design-system.md +273 -0
  24. package/dist/docs/dev-environments.md +496 -0
  25. package/dist/docs/domain-ownership.md +31 -0
  26. package/dist/docs/domains.md +370 -0
  27. package/dist/docs/feedback.md +88 -0
  28. package/dist/docs/file-tools.md +116 -0
  29. package/dist/docs/functions.md +489 -0
  30. package/dist/docs/getting-started.md +238 -0
  31. package/dist/docs/github.md +95 -0
  32. package/dist/docs/google-calendar.md +212 -0
  33. package/dist/docs/groups.md +836 -0
  34. package/dist/docs/guarantees.md +58 -0
  35. package/dist/docs/handled-for-you.md +224 -0
  36. package/dist/docs/inspect.md +171 -0
  37. package/dist/docs/limits.md +68 -0
  38. package/dist/docs/live-data.md +197 -0
  39. package/dist/docs/live.md +92 -0
  40. package/dist/docs/local-dev.md +30 -0
  41. package/dist/docs/migration-supabase.md +58 -0
  42. package/dist/docs/payments.md +1102 -0
  43. package/dist/docs/portability.md +194 -0
  44. package/dist/docs/postgres.md +301 -0
  45. package/dist/docs/pricing-comparison.md +42 -0
  46. package/dist/docs/pricing.md +39 -0
  47. package/dist/docs/project-groups.md +107 -0
  48. package/dist/docs/projects.md +380 -0
  49. package/dist/docs/recipe-ai-agent.md +112 -0
  50. package/dist/docs/recipe-ai-features.md +227 -0
  51. package/dist/docs/recipe-ai-receipts.md +783 -0
  52. package/dist/docs/recipe-background-jobs.md +369 -0
  53. package/dist/docs/recipe-booking.md +348 -0
  54. package/dist/docs/recipe-csv-import.md +390 -0
  55. package/dist/docs/recipe-ecommerce.md +127 -0
  56. package/dist/docs/recipe-email.md +282 -0
  57. package/dist/docs/recipe-escalation.md +133 -0
  58. package/dist/docs/recipe-file-uploads.md +159 -0
  59. package/dist/docs/recipe-import-app.md +110 -0
  60. package/dist/docs/recipe-login.md +457 -0
  61. package/dist/docs/recipe-multi-chat.md +198 -0
  62. package/dist/docs/recipe-paid-api.md +161 -0
  63. package/dist/docs/recipe-pdfs.md +205 -0
  64. package/dist/docs/recipe-push-notifications.md +107 -0
  65. package/dist/docs/recipe-seo.md +200 -0
  66. package/dist/docs/recipe-signed-in-app.md +330 -0
  67. package/dist/docs/render.md +99 -0
  68. package/dist/docs/rooms.md +554 -0
  69. package/dist/docs/sdk.md +287 -0
  70. package/dist/docs/sdks.md +24 -0
  71. package/dist/docs/search.md +199 -0
  72. package/dist/docs/security-model.md +168 -0
  73. package/dist/docs/setup.md +212 -0
  74. package/dist/docs/smoke.md +102 -0
  75. package/dist/docs/speed.md +298 -0
  76. package/dist/docs/sql-compatibility.md +96 -0
  77. package/dist/docs/sw.agent.md +248 -0
  78. package/dist/docs/sw.ai.md +1291 -0
  79. package/dist/docs/sw.auth.md +1811 -0
  80. package/dist/docs/sw.billing.md +171 -0
  81. package/dist/docs/sw.db.md +2128 -0
  82. package/dist/docs/sw.email.md +661 -0
  83. package/dist/docs/sw.endpoint.md +187 -0
  84. package/dist/docs/sw.env.md +303 -0
  85. package/dist/docs/sw.fetch.md +115 -0
  86. package/dist/docs/sw.fs.md +424 -0
  87. package/dist/docs/sw.groups.md +836 -0
  88. package/dist/docs/sw.image.md +69 -0
  89. package/dist/docs/sw.jobs.md +520 -0
  90. package/dist/docs/sw.logs.md +61 -0
  91. package/dist/docs/sw.mail.md +106 -0
  92. package/dist/docs/sw.notifications.md +78 -0
  93. package/dist/docs/sw.push.md +161 -0
  94. package/dist/docs/sw.rateLimit.md +67 -0
  95. package/dist/docs/sw.web.md +128 -0
  96. package/dist/docs/tasks.md +269 -0
  97. package/dist/docs/test.md +220 -0
  98. package/dist/docs/tool-reference-account.md +7 -0
  99. package/dist/docs/tool-reference-ai.md +121 -0
  100. package/dist/docs/tool-reference-analytics.md +37 -0
  101. package/dist/docs/tool-reference-api.md +19 -0
  102. package/dist/docs/tool-reference-artifacts.md +35 -0
  103. package/dist/docs/tool-reference-auth.md +163 -0
  104. package/dist/docs/tool-reference-browser.md +114 -0
  105. package/dist/docs/tool-reference-code.md +26 -0
  106. package/dist/docs/tool-reference-connect.md +21 -0
  107. package/dist/docs/tool-reference-cron.md +48 -0
  108. package/dist/docs/tool-reference-db.md +282 -0
  109. package/dist/docs/tool-reference-domains.md +107 -0
  110. package/dist/docs/tool-reference-email.md +55 -0
  111. package/dist/docs/tool-reference-env.md +19 -0
  112. package/dist/docs/tool-reference-feedback.md +56 -0
  113. package/dist/docs/tool-reference-fs.md +265 -0
  114. package/dist/docs/tool-reference-github.md +57 -0
  115. package/dist/docs/tool-reference-groups.md +85 -0
  116. package/dist/docs/tool-reference-help.md +29 -0
  117. package/dist/docs/tool-reference-jobs.md +39 -0
  118. package/dist/docs/tool-reference-live.md +48 -0
  119. package/dist/docs/tool-reference-logs.md +16 -0
  120. package/dist/docs/tool-reference-payments.md +44 -0
  121. package/dist/docs/tool-reference-project.md +706 -0
  122. package/dist/docs/tool-reference-push.md +78 -0
  123. package/dist/docs/tool-reference-rate-limit.md +18 -0
  124. package/dist/docs/tool-reference-search.md +68 -0
  125. package/dist/docs/tool-reference-security.md +42 -0
  126. package/dist/docs/tool-reference-smoke.md +17 -0
  127. package/dist/docs/tool-reference-stock-photos.md +20 -0
  128. package/dist/docs/tool-reference-tasks.md +73 -0
  129. package/dist/docs/tool-reference-telegram.md +32 -0
  130. package/dist/docs/tool-reference-usage.md +9 -0
  131. package/dist/docs/tool-reference-web.md +71 -0
  132. package/dist/docs/tool-reference-webhooks.md +9 -0
  133. package/dist/docs/troubleshooting.md +411 -0
  134. package/dist/docs/typed-functions.md +94 -0
  135. package/dist/docs/verify-before-deploy.md +67 -0
  136. package/dist/docs/vs-supabase.md +75 -0
  137. package/dist/docs/vs-vercel.md +103 -0
  138. package/dist/lib/bundle.js +303 -221
  139. package/dist/lib/bundle.js.map +3 -3
  140. package/dist/types/lib/test-session.d.ts +8 -0
  141. package/npm-shrinkwrap.json +2 -2
  142. package/package.json +3 -2
  143. package/runtime/DECLARED-DATA-VENDOR.json +5 -5
  144. package/runtime/PLATFORM-SOURCE.json +1 -1
  145. package/runtime/SOURCE-LINT-VENDOR.json +2 -2
  146. package/runtime/declared-data.cjs +37 -19
  147. package/runtime/source-lint.cjs +1 -1
@@ -0,0 +1,162 @@
1
+ # Use your app from Claude (app MCP tools)
2
+
3
+ **Preview feature.** It works end to end today and its shape may still change.
4
+
5
+ A signed-in Somewhere app can serve its own MCP tools at
6
+ `https://<your-app-address>/mcp`. Anyone who uses your app can then add that
7
+ address as a custom connector in Claude, or in another AI client that connects
8
+ to remote servers with OAuth sign-in. Claude then works with the app as that
9
+ person, using the app's own sign-in. The app's MCP sign-in uses standard OAuth
10
+ with PKCE and open client registration, so any OAuth client can use it.
11
+
12
+ ## Steps
13
+
14
+ Ask before destructive or paid actions unless the user already authorized them.
15
+
16
+ 1. Start from an app with sign-in. Run
17
+ `somewhere init --name my-app --features auth,private-data` to create one
18
+ with a `notes` table each user owns.
19
+ 2. Add one `api/*.ts` endpoint per tool, with an `mcp` declaration (below).
20
+ 3. Keep `somewhere.auth.json` at the project root. The `somewhere init` starter
21
+ ships it.
22
+ 4. `somewhere deploy`.
23
+ 5. In Claude: Customize, Connectors, Add custom connector. Paste
24
+ `https://<your-app-address>/mcp`, then Connect. Leave the OAuth client on
25
+ its default, or choose Register automatically. The project address works as
26
+ is; a custom domain serves the same `/mcp` path.
27
+ 6. Sign in with an account of the app, not your Somewhere login, and approve
28
+ the page that lists the tools.
29
+ 7. In a chat with the connector on, ask Claude to use a tool, for example "add
30
+ a note called Hello, then list my notes". Open the app as the same account to
31
+ see the result.
32
+
33
+ ## Test tools with a prepared app user
34
+
35
+ From the linked project folder, run `somewhere test-users prepare owner` and
36
+ grant the printed user ID any app role the tested data requires. For a
37
+ headless check, seed one browser context with
38
+ `.somewhere/test/owner.state.json` and open the authorization URL from an
39
+ OAuth-capable MCP test client. Use the same context for consent and approval
40
+ so the transaction cookie and same-origin request headers are retained.
41
+ After the client's PKCE exchange, use it to list and call tools at the app's
42
+ `/mcp` URL, then run `somewhere test-users cleanup`. Keep the session file and
43
+ OAuth tokens private. The CLI has no command that takes a prepared actor and
44
+ calls the app's MCP tools directly.
45
+
46
+ ## Declare tools
47
+
48
+ A signed-in app can be used from Claude, or any other MCP client, as the
49
+ person signed in to the app. Each tool is an ordinary endpoint with an `mcp`
50
+ declaration; its arguments arrive as the JSON body:
51
+
52
+ ```ts
53
+ // api/listNotes.ts — tool list_notes
54
+ export default sw.endpoint({
55
+ auth: 'required',
56
+ mcp: {
57
+ name: 'list_notes',
58
+ description: 'List the signed-in user\'s notes.',
59
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
60
+ annotations: { readOnlyHint: true },
61
+ },
62
+ handler: async (_input, sw) => ({ notes: (await sw.db.from('notes', { limit: 100 })).data }),
63
+ });
64
+ ```
65
+
66
+ ```ts
67
+ // api/addNote.ts — tool add_note
68
+ export default sw.endpoint({
69
+ auth: 'required',
70
+ body: { title: 'string' },
71
+ mcp: {
72
+ name: 'add_note',
73
+ description: 'Add a note for the signed-in user.',
74
+ inputSchema: { type: 'object', properties: { title: { type: 'string' } }, required: ['title'], additionalProperties: false },
75
+ },
76
+ handler: async ({ body }, sw) => ({ note: (await sw.db.insert('notes', { title: body.title })).data[0] }),
77
+ });
78
+ ```
79
+
80
+ A tool is the default export of a static `api/*.ts` route with
81
+ `auth: 'required'`: file and folder names are letters, digits and underscores
82
+ (`api/listNotes.ts`, not `api/list-notes.ts` or `api/[id].ts`). Everything in `mcp` is a plain literal:
83
+ a unique name (a letter, then up to 63 letters, digits or underscores), a
84
+ description, a draft-07 `type: 'object'` input schema, and optionally
85
+ `outputSchema` and the standard `annotations` hints. Return a JSON object.
86
+ At most 100 tools; arguments up to 64 KiB, results up to 1 MiB. A failed or
87
+ uncertain call is never retried. An invalid declaration fails the deploy.
88
+
89
+ **Sign-in.** `somewhere.auth.json` at the project root names the page where a
90
+ signed-out person signs in:
91
+
92
+ ```json
93
+ { "version": 1, "signInPath": "/" }
94
+ ```
95
+
96
+ The file is public configuration, served like any other app file: never
97
+ put secrets in it. The platform sends them there with `sw_auth_return` set to
98
+ `/mcp/consent?signin=<id>`; after signing in, the app loads exactly that
99
+ path. The `somewhere init` starter ships the file and that step
100
+ (`src/auth/connection-return.ts`). Without the file, a signed-out person
101
+ cannot connect (`409 app_auth_return_adapter_required`).
102
+
103
+ ## Who signs in and what a tool may do
104
+
105
+ **Who signs in.** The app's own user, with the account they use in the app,
106
+ never the developer's Somewhere login; the owner connects with an app account
107
+ too. They approve a page that lists the tools.
108
+
109
+ **What a tool may do.** A tool is your code, run as the signed-in user:
110
+ `user` is them, and `sw.db` reads and writes apply their declared access
111
+ (`owner()`, `member()`, roles); `sw.db.server` and server-only tables are
112
+ refused inside a tool call. Everything else the handler does is up to your
113
+ code, not that user's row access: explicit server files (`sw.fs.server`), raw
114
+ SQL, email and outbound requests can reach beyond what the user may see, so
115
+ check the user before using them. The consent page tells the person exactly
116
+ this.
117
+
118
+ **Re-consent.** Approval covers each tool's name, description, schemas and
119
+ route. Change any of them, or add a tool, and connected clients stop seeing
120
+ that tool until the person reconnects (in Claude: disconnect, connect again)
121
+ and approves. Changing only the handler's code keeps the approval. Access
122
+ lasts an hour and refreshes for up to 30 days, then the person reconnects.
123
+
124
+ **Revocation and deletion.** Each tool call is checked fresh when it starts:
125
+ the person's access, their account (signed out, banned), the app's MCP
126
+ setting and the live version. Revoking access, disabling MCP, banning or
127
+ signing the person out, or publishing a new version stops new calls at once;
128
+ a call already running can finish its work for at most 60 seconds after it
129
+ started. Deleting the person's account stops a running call at its next
130
+ platform call (`sw.db`, `sw.fs` and the other user-scoped calls).
131
+
132
+ **One call, 60 seconds.** A tool's user-scoped platform calls must happen
133
+ within 60 seconds of the call starting; after that they are refused with
134
+ `MCP_CALL_EXPIRED` and nothing changes. Within those 60 seconds a tool call's
135
+ platform authority is not single-use: if its delivery were captured and sent
136
+ again, the same tool would run again with the same arguments as the same
137
+ person, including after the original call completed. Make tools that change
138
+ data safe to repeat (an idempotency key from the arguments), as you already
139
+ do for client retries.
140
+
141
+ ## Current limits
142
+
143
+ - At most 100 tools per app. Arguments up to 64 KiB, results up to 1 MiB. A
144
+ failed or uncertain call is never retried.
145
+ - A tool's user-scoped platform calls must happen within 60 seconds of the
146
+ call starting (`MCP_CALL_EXPIRED` after that).
147
+ - Tool routes are static `api/*.ts` files with `auth: 'required'`. Names use
148
+ letters, digits and underscores only.
149
+ - Inside a tool, `sw.db.server` and server-only tables are refused.
150
+ - Changing a tool's name, description, schemas or route, or adding a tool,
151
+ hides it from connected clients until the person reconnects. The client is not
152
+ told.
153
+ - Access lasts an hour and refreshes for up to 30 days; then the person
154
+ connects again.
155
+ - The server speaks MCP revisions 2025-06-18, 2025-11-25 and 2026-07-28 over
156
+ Streamable HTTP at `/mcp`. The 2025 revisions use initialization; 2026-07-28
157
+ uses per-request metadata without an initialization handshake. Existing app
158
+ source does not need to change.
159
+ - Each caller address can register up to 30 clients and make up to 120 token
160
+ requests per minute per app.
161
+ - The consent page shows the name the connecting app gives itself. It is not
162
+ verified.
@@ -0,0 +1,334 @@
1
+ # Architecture Patterns — How to wire common app shapes
2
+
3
+ ## Start with managed access
4
+
5
+ A Somewhere app is one project: the React UI in `src/`, server functions in
6
+ `api/`, tables in `db/schema.ts`, and sign-in through the starter's auth
7
+ route. Pages read and write declared tables through the generated
8
+ `somewhere:data` client: the table's scope and `client` block decide whose rows
9
+ and which columns, so normal data needs no API file (`declared-data`). A
10
+ public enquiry to a published profile uses declared `client.intake`
11
+ (`declared-data` → `send-an-enquiry-to-a-public-profile`). A function
12
+ holds only what the declaration cannot express: an authorized exceptional
13
+ write, an external API call or a job. Mix the two: keep `owner()`/`member()`/`group()`
14
+ and the client for normal access; add a function only for that operation or
15
+ side effect (`recipe-signed-in-app`). One deploy publishes the UI, the
16
+ functions and the schema together.
17
+
18
+ ## Calling a function
19
+
20
+ When a page does call a function, the request flows like this: the page calls a same-origin
21
+ `/api/…` function with its session cookie, the function gets the verified
22
+ user from `sw.auth.fromRequest(req)`, and on an `owner()` table
23
+ `sw.db.from` and `sw.db.insert` read and write only that user's rows.
24
+
25
+ The REST pattern below is that path in full: an `owner()` posts table and one
26
+ function that lists and creates the caller's posts. Raw SQL through
27
+ `sw.db.server.*` runs as written, so authorize the caller and filter by user
28
+ yourself there. The other patterns are working sketches to lift and adapt:
29
+ chat with history, file upload, background work and an external API proxy.
30
+
31
+ ## Server-only fallback when a rule cannot be declared
32
+
33
+ Do not mark data people read or change through your app serverOnly() and
34
+ hand-write its access checks. Declare who may read and write it; the platform
35
+ enforces that for you.
36
+
37
+ Server-only is right for:
38
+ - Tables only server code touches: job state, import staging, audit records, counters.
39
+ - Membership/grant ledgers: never grant browser writes. grant() ledgers retain the
40
+ owner() scope required by that policy, with no client write grants.
41
+ - A rule the declarations cannot express; keep other operations declared:
42
+ - Arbitrary predicates (such as checking the current time): use a checked endpoint.
43
+ - Different writable fields by role on one table: split tables or check that write.
44
+ Server-assigned roles and role-filtered member() operations are declarable; they
45
+ are not reasons to make app data server-only.
46
+
47
+ For a typical app, declare owner() or group() scopes and use the generated
48
+ browser client. A team is a built-in group, not server-only team/task tables:
49
+ `somewhere docs sw.groups --section team-example`.
50
+ If just one operation needs an extra check, keep the table declared and use
51
+ sw.db.server only for that authorized operation.
52
+
53
+ Use this fallback only when every operation requires a rule the declarations
54
+ cannot express. This waitlist keeps email addresses private while public
55
+ functions accept signups and expose only a count. Declare it in db/schema.ts;
56
+ functions authorize their own access through sw.db.server. No separate migration
57
+ command is needed.
58
+
59
+ ```ts
60
+ // db/schema.ts
61
+ import { schema, table, id, text, timestamp, serverOnly } from 'somewhere/db';
62
+ export default schema({
63
+ waitlist_signups: table({
64
+ id: id(),
65
+ email: text({ unique: true }),
66
+ name: text({ nullable: true }),
67
+ created_at: timestamp({ default: 'now' }),
68
+ }, { scope: serverOnly() }),
69
+ });
70
+ ```
71
+
72
+ ```ts
73
+ // api/join.ts — intentionally public signup; validate before server writes
74
+ export default async function (req: Request, sw: SomewhereRuntimeContext) {
75
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 });
76
+ const input = await req.json().catch(() => null);
77
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {
78
+ return Response.json({ error: 'JSON object required' }, { status: 400 });
79
+ }
80
+ if (typeof input.email !== 'string' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.email.trim())) {
81
+ return Response.json({ error: 'Valid email required' }, { status: 400 });
82
+ }
83
+ if (input.name != null && typeof input.name !== 'string') {
84
+ return Response.json({ error: 'Name must be text' }, { status: 400 });
85
+ }
86
+ await sw.db.server.insert('waitlist_signups', {
87
+ email: input.email.trim().toLowerCase(), name: input.name ?? null,
88
+ }, { onConflict: 'ignore' });
89
+ return Response.json({ ok: true });
90
+ }
91
+ // api/count.ts — intentionally public aggregate; never returns signup rows
92
+ export default async function (req: Request, sw: SomewhereRuntimeContext) {
93
+ if (req.method !== 'GET') return new Response('Method not allowed', { status: 405 });
94
+ const { data: count } = await sw.db.server.count('waitlist_signups');
95
+ return Response.json({ count });
96
+ }
97
+ ```
98
+
99
+ Deploy these source files with your page. `unique: true` enforces email
100
+ uniqueness; `onConflict: 'ignore'` keeps a repeated signup unchanged.
101
+ Columns are required by default; `nullable: true` permits null. Column
102
+ helpers accept `nullable`, `default`, `unique`, `references`,
103
+ `onDelete`, and `renamedFrom`; `id()` instead accepts only `uuid`. On a new
104
+ table a bare `id()` is a random text key (128-bit hex, not a UUID); a table
105
+ that already has integer ids keeps them. `id({ uuid: false })` is an integer
106
+ key. An id never grants access: scope and grants decide.
107
+ Unknown options are rejected. `count` returns its number in `.data`,
108
+ while `from` returns rows in `.data`. Server authority bypasses declared
109
+ row permissions: authorize private/admin operations before using it. This
110
+ example intentionally allows public signup and a public total.
111
+
112
+ ## Two ways to use the platform
113
+
114
+ There are two distinct entry points. Pick based on where your code runs.
115
+
116
+ **Outside the platform** (your laptop, CI, a different host):
117
+ - Auth: `Authorization: Bearer smt_...` developer key (or app-user JWT for end-user calls)
118
+ - Surface: REST at `https://api.somewhere.cloud/v1/*` and MCP at `https://mcp.somewhere.cloud/mcp`
119
+ - Use case: deploy scripts, admin tooling, agent calls, webhooks from third parties
120
+
121
+ **Inside a deployed function** (code running on the platform):
122
+ - Auth: none — the binding is pre-scoped to your project
123
+ - Surface: `sw.db`, `sw.fs`, `sw.ai`, `sw.email`, `sw.auth`, `sw.env`, `sw.jobs`, `sw.logs`
124
+ - Use case: API endpoints, server-side logic, AI proxies, file uploads, scheduled work
125
+
126
+ When you write a function, default to `sw.*`. Only fall back to the
127
+ REST surface when you have a specific reason (calling another project,
128
+ calling from outside).
129
+
130
+ ## Pattern: Chat app with auth + history
131
+
132
+ Keep the starter's sign-in route (see `sw.auth`). This function uses the free default model
133
+ and saves each conversation under the verified user; no account or message
134
+ tables need to be declared by the app.
135
+
136
+ ```typescript
137
+ // api/chat.ts
138
+ export default async function (req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
139
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 });
140
+ const user = await sw.auth.fromRequest(req);
141
+ if (!user) return new Response('Unauthorized', { status: 401 });
142
+
143
+ const input: unknown = await req.json().catch(() => null);
144
+ if (!input || typeof input !== 'object' || Array.isArray(input)
145
+ || !('message' in input) || typeof input.message !== 'string'
146
+ || !input.message.trim() || input.message.length > 4000) {
147
+ return Response.json({ error: 'Send a message of 1 to 4000 characters.' }, { status: 400 });
148
+ }
149
+ const priorId = 'conversation_id' in input ? input.conversation_id : undefined;
150
+ if (priorId !== undefined && (typeof priorId !== 'string' || !priorId.trim() || priorId.length > 128)) {
151
+ return Response.json({ error: 'Invalid conversation ID.' }, { status: 400 });
152
+ }
153
+ // This app allows each user 20 messages per hour.
154
+ const allowance = await sw.rateLimit.check(`chat:${user.id}`, 20, 3600);
155
+ if (!allowance.allowed) return Response.json({ error: 'Try again later.' }, { status: 429 });
156
+
157
+ const conversationId = priorId ?? crypto.randomUUID();
158
+ try {
159
+ const result = await sw.ai.chat({
160
+ conversation_id: conversationId,
161
+ messages: [{ role: 'user', content: input.message }],
162
+ });
163
+ return Response.json({ conversation_id: conversationId, reply: result.text });
164
+ } catch (error) {
165
+ if (error && typeof error === 'object' && 'status' in error && error.status === 429) {
166
+ const code = 'code' in error && typeof error.code === 'string' ? error.code : 'RATE_LIMITED';
167
+ return Response.json({ error: code }, { status: 429 });
168
+ }
169
+ throw error;
170
+ }
171
+ }
172
+ ```
173
+
174
+ Sign in and POST `{ "message": "Hello" }` to `/api/chat`. Keep the returned
175
+ `conversation_id` and send it with the next message. The platform loads the
176
+ retained history for that user and conversation before calling the model.
177
+ The free default stops at its limits without charging. Its rate limit is shared
178
+ across your projects; see `sw.ai` for the allowance and limit responses.
179
+ For a model choice, use `ai_catalog`; for tools and multi-step work, see
180
+ `sw.agent`.
181
+
182
+ ## Pattern: REST API with end-user auth
183
+
184
+ Schema and function (`api/my-posts.ts`):
185
+ ```typescript
186
+ // db/schema.ts
187
+ import { id, owner, schema, table, text, timestamp } from 'somewhere/db';
188
+
189
+ export default schema({
190
+ posts: table(
191
+ { id: id(), title: text(), body: text(), created_at: timestamp({ default: 'now' }) },
192
+ { scope: owner() },
193
+ ),
194
+ });
195
+ ```
196
+
197
+ ```typescript
198
+ // api/my-posts.ts
199
+ export default async function (req: Request, sw: SomewhereRuntimeContext) {
200
+ const user = await sw.auth.fromRequest(req) // session cookie or Bearer token
201
+ if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 })
202
+
203
+ if (req.method === 'GET') {
204
+ const { data } = await sw.db.from('posts', { order: [['created_at', 'desc']] })
205
+ return Response.json(data)
206
+ }
207
+
208
+ if (req.method === 'POST') {
209
+ const input = await req.json().catch(() => null)
210
+ if (input === null || typeof input !== 'object' || typeof input.title !== 'string' || typeof input.body !== 'string') {
211
+ return Response.json({ error: 'title and body must be text' }, { status: 400 })
212
+ }
213
+ const { data } = await sw.db.insert('posts', { title: input.title, body: input.body })
214
+ return Response.json(data[0], { status: 201 })
215
+ }
216
+ return new Response('method not allowed', { status: 405 })
217
+ }
218
+ ```
219
+
220
+ With `posts` declared `scope: owner()` in `db/schema.ts`, the platform
221
+ scopes reads to the caller and sets the owner on insert; there is no `WHERE user_id` to write or forget. Raw SQL is
222
+ different: in a SQL-mode project, or through `sw.db.server.*` after your
223
+ own check, the query runs as written and you own the filter.
224
+
225
+ ## Pattern: Files owned by the signed-in user
226
+
227
+ Declare a collection and upload from the browser. The platform checks the
228
+ session and collection rules; file bytes go straight to storage.
229
+
230
+ ```typescript
231
+ // db/schema.ts
232
+ import { files, owner, schema } from 'somewhere/db';
233
+
234
+ export default schema({}, {
235
+ files: {
236
+ documents: files({
237
+ path: '/documents',
238
+ scope: owner(),
239
+ client: { read: true, upload: true },
240
+ limits: { maxSize: '10MB', types: ['application/pdf', 'image/*', 'text/*'] },
241
+ }),
242
+ },
243
+ });
244
+ ```
245
+
246
+ ```typescript
247
+ // src/services/documents.ts
248
+ import { files } from 'somewhere:files';
249
+
250
+ export async function uploadDocument(file: File): Promise<string> {
251
+ const { data, error } = await files.documents.upload(file);
252
+ if (error) throw new Error(error.message);
253
+ return files.documents.url(data.id);
254
+ }
255
+ ```
256
+
257
+ Call `uploadDocument(file)` after sign-in and use the returned URL in a link
258
+ or image. The URL checks the requesting session each time; another user
259
+ cannot open an owner-only document. Keep existing tables when adding this
260
+ collection to your schema. For progress, sharing and replacement, see
261
+ `recipe-file-uploads` and `declared-files`.
262
+
263
+ ## Pattern: Background work
264
+
265
+ Inline jobs (return immediately, work later):
266
+ ```typescript
267
+ // api/welcome.ts — the signed-in user queues their own welcome email
268
+ export default async function (req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
269
+ const user = await sw.auth.fromRequest(req)
270
+ if (!user) return new Response('Unauthorized', { status: 401 })
271
+ const job = await sw.jobs.create({
272
+ handler: '/api/jobs/send-welcome',
273
+ payload: { user_id: user.id, email: user.email },
274
+ })
275
+ return Response.json({ queued: true, job_id: job.job_id })
276
+ }
277
+ ```
278
+
279
+ Handler (`api/jobs/send-welcome.ts`) — a public URL, so it verifies the
280
+ platform's signature before it trusts the payload:
281
+ ```typescript
282
+ // api/jobs/send-welcome.ts
283
+ export default async function (req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
284
+ if (!(await sw.jobs.verifyInvocation(req))) return new Response('forbidden', { status: 403 })
285
+ const { user_id, email } = await req.json()
286
+ await sw.email.send({
287
+ to: email,
288
+ subject: 'Welcome',
289
+ html: '<h1>Hi!</h1>',
290
+ // Stored with the sent message, so a retried run — or a second job for the
291
+ // same user and address — returns that message instead of sending again.
292
+ idempotency_key: `welcome:${user_id}:${email}`,
293
+ })
294
+ return Response.json({ ok: true })
295
+ }
296
+ ```
297
+
298
+ The handler is a deployed function under `api/`, called with the payload as
299
+ its JSON body; a failed run is retried, so keep it idempotent
300
+ (`docs({ topic: 'sw.jobs' })`).
301
+
302
+ A fire-and-forget side effect is a job too: create it and never read its
303
+ status.
304
+
305
+ For scheduled work use `cron_create` to point a cron expression at
306
+ a function path.
307
+
308
+ ## Pattern: External API proxy (hide your key)
309
+
310
+ ```typescript
311
+ // api/openai-proxy.ts — keeps OPENAI_API_KEY off the client
312
+ export default async function (req: Request, sw: SomewhereRuntimeContext) {
313
+ const user = await sw.auth.fromRequest(req) // session cookie or Bearer token
314
+ if (!user) return new Response('Unauthorized', { status: 401 })
315
+
316
+ const body = await req.json()
317
+ const r = await fetch('https://api.openai.com/v1/chat/completions', {
318
+ method: 'POST',
319
+ headers: {
320
+ Authorization: `Bearer ${sw.env.OPENAI_API_KEY}`,
321
+ 'Content-Type': 'application/json'
322
+ },
323
+ body: JSON.stringify(body)
324
+ })
325
+ return new Response(r.body, { status: r.status, headers: { 'Content-Type': 'application/json' } })
326
+ }
327
+ ```
328
+
329
+ Set `OPENAI_API_KEY` as an env var on the project. The browser never
330
+ sees it. Same pattern for Stripe, Twilio, anything.
331
+
332
+ For built-in models (chat, image generation, TTS, embeddings, etc.)
333
+ prefer `sw.ai.*` — billing is metered through the platform and you
334
+ don't manage upstream keys at all.