@somewhere-cloud/cli 0.38.155 → 0.38.156

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 (142) hide show
  1. package/CHANGELOG.md +4 -1
  2. package/dist/commands/docs.js +1 -1
  3. package/dist/lib/bundle.js +276 -188
  4. package/dist/lib/bundle.js.map +3 -3
  5. package/npm-shrinkwrap.json +2 -2
  6. package/package.json +2 -3
  7. package/dist/docs/adopt.md +0 -39
  8. package/dist/docs/analytics.md +0 -161
  9. package/dist/docs/api-reference.md +0 -339
  10. package/dist/docs/api-surface.md +0 -2067
  11. package/dist/docs/app-mcp.md +0 -162
  12. package/dist/docs/architecture-patterns.md +0 -334
  13. package/dist/docs/auth-client.md +0 -531
  14. package/dist/docs/billing.md +0 -76
  15. package/dist/docs/browser.md +0 -639
  16. package/dist/docs/calendar.md +0 -298
  17. package/dist/docs/changes.md +0 -323
  18. package/dist/docs/cli.md +0 -407
  19. package/dist/docs/common-mistakes.md +0 -199
  20. package/dist/docs/connect-agent.md +0 -72
  21. package/dist/docs/cors.md +0 -114
  22. package/dist/docs/cron.md +0 -167
  23. package/dist/docs/database-engine.md +0 -167
  24. package/dist/docs/declared-data.md +0 -1656
  25. package/dist/docs/declared-files.md +0 -475
  26. package/dist/docs/deploy-intelligence.md +0 -188
  27. package/dist/docs/deploy.md +0 -733
  28. package/dist/docs/design-system.md +0 -273
  29. package/dist/docs/dev-environments.md +0 -496
  30. package/dist/docs/domain-ownership.md +0 -31
  31. package/dist/docs/domains.md +0 -370
  32. package/dist/docs/feedback.md +0 -88
  33. package/dist/docs/file-tools.md +0 -116
  34. package/dist/docs/functions.md +0 -489
  35. package/dist/docs/getting-started.md +0 -238
  36. package/dist/docs/github.md +0 -95
  37. package/dist/docs/google-calendar.md +0 -212
  38. package/dist/docs/groups.md +0 -836
  39. package/dist/docs/guarantees.md +0 -58
  40. package/dist/docs/handled-for-you.md +0 -224
  41. package/dist/docs/inspect.md +0 -171
  42. package/dist/docs/limits.md +0 -68
  43. package/dist/docs/live-data.md +0 -197
  44. package/dist/docs/live.md +0 -92
  45. package/dist/docs/local-dev.md +0 -30
  46. package/dist/docs/migration-supabase.md +0 -58
  47. package/dist/docs/payments.md +0 -1102
  48. package/dist/docs/portability.md +0 -194
  49. package/dist/docs/postgres.md +0 -301
  50. package/dist/docs/pricing-comparison.md +0 -42
  51. package/dist/docs/pricing.md +0 -39
  52. package/dist/docs/project-groups.md +0 -107
  53. package/dist/docs/projects.md +0 -380
  54. package/dist/docs/recipe-ai-agent.md +0 -112
  55. package/dist/docs/recipe-ai-features.md +0 -227
  56. package/dist/docs/recipe-ai-receipts.md +0 -783
  57. package/dist/docs/recipe-background-jobs.md +0 -369
  58. package/dist/docs/recipe-booking.md +0 -348
  59. package/dist/docs/recipe-csv-import.md +0 -390
  60. package/dist/docs/recipe-ecommerce.md +0 -127
  61. package/dist/docs/recipe-email.md +0 -282
  62. package/dist/docs/recipe-escalation.md +0 -133
  63. package/dist/docs/recipe-file-uploads.md +0 -159
  64. package/dist/docs/recipe-import-app.md +0 -110
  65. package/dist/docs/recipe-login.md +0 -457
  66. package/dist/docs/recipe-multi-chat.md +0 -198
  67. package/dist/docs/recipe-paid-api.md +0 -161
  68. package/dist/docs/recipe-pdfs.md +0 -205
  69. package/dist/docs/recipe-push-notifications.md +0 -107
  70. package/dist/docs/recipe-seo.md +0 -200
  71. package/dist/docs/recipe-signed-in-app.md +0 -330
  72. package/dist/docs/render.md +0 -99
  73. package/dist/docs/rooms.md +0 -554
  74. package/dist/docs/sdk.md +0 -287
  75. package/dist/docs/sdks.md +0 -24
  76. package/dist/docs/search.md +0 -199
  77. package/dist/docs/security-model.md +0 -168
  78. package/dist/docs/setup.md +0 -212
  79. package/dist/docs/smoke.md +0 -102
  80. package/dist/docs/speed.md +0 -298
  81. package/dist/docs/sql-compatibility.md +0 -96
  82. package/dist/docs/sw.agent.md +0 -248
  83. package/dist/docs/sw.ai.md +0 -1291
  84. package/dist/docs/sw.auth.md +0 -1811
  85. package/dist/docs/sw.billing.md +0 -171
  86. package/dist/docs/sw.db.md +0 -2128
  87. package/dist/docs/sw.email.md +0 -661
  88. package/dist/docs/sw.endpoint.md +0 -187
  89. package/dist/docs/sw.env.md +0 -303
  90. package/dist/docs/sw.fetch.md +0 -115
  91. package/dist/docs/sw.fs.md +0 -424
  92. package/dist/docs/sw.groups.md +0 -836
  93. package/dist/docs/sw.image.md +0 -69
  94. package/dist/docs/sw.jobs.md +0 -520
  95. package/dist/docs/sw.logs.md +0 -61
  96. package/dist/docs/sw.mail.md +0 -106
  97. package/dist/docs/sw.notifications.md +0 -78
  98. package/dist/docs/sw.push.md +0 -161
  99. package/dist/docs/sw.rateLimit.md +0 -67
  100. package/dist/docs/sw.web.md +0 -128
  101. package/dist/docs/tasks.md +0 -269
  102. package/dist/docs/test.md +0 -220
  103. package/dist/docs/tool-reference-account.md +0 -7
  104. package/dist/docs/tool-reference-ai.md +0 -121
  105. package/dist/docs/tool-reference-analytics.md +0 -37
  106. package/dist/docs/tool-reference-api.md +0 -19
  107. package/dist/docs/tool-reference-artifacts.md +0 -35
  108. package/dist/docs/tool-reference-auth.md +0 -163
  109. package/dist/docs/tool-reference-browser.md +0 -114
  110. package/dist/docs/tool-reference-code.md +0 -26
  111. package/dist/docs/tool-reference-connect.md +0 -21
  112. package/dist/docs/tool-reference-cron.md +0 -48
  113. package/dist/docs/tool-reference-db.md +0 -282
  114. package/dist/docs/tool-reference-domains.md +0 -107
  115. package/dist/docs/tool-reference-email.md +0 -55
  116. package/dist/docs/tool-reference-env.md +0 -19
  117. package/dist/docs/tool-reference-feedback.md +0 -56
  118. package/dist/docs/tool-reference-fs.md +0 -265
  119. package/dist/docs/tool-reference-github.md +0 -57
  120. package/dist/docs/tool-reference-groups.md +0 -85
  121. package/dist/docs/tool-reference-help.md +0 -29
  122. package/dist/docs/tool-reference-jobs.md +0 -39
  123. package/dist/docs/tool-reference-live.md +0 -48
  124. package/dist/docs/tool-reference-logs.md +0 -16
  125. package/dist/docs/tool-reference-payments.md +0 -44
  126. package/dist/docs/tool-reference-project.md +0 -706
  127. package/dist/docs/tool-reference-push.md +0 -78
  128. package/dist/docs/tool-reference-rate-limit.md +0 -18
  129. package/dist/docs/tool-reference-search.md +0 -68
  130. package/dist/docs/tool-reference-security.md +0 -42
  131. package/dist/docs/tool-reference-smoke.md +0 -17
  132. package/dist/docs/tool-reference-stock-photos.md +0 -20
  133. package/dist/docs/tool-reference-tasks.md +0 -73
  134. package/dist/docs/tool-reference-telegram.md +0 -32
  135. package/dist/docs/tool-reference-usage.md +0 -9
  136. package/dist/docs/tool-reference-web.md +0 -71
  137. package/dist/docs/tool-reference-webhooks.md +0 -9
  138. package/dist/docs/troubleshooting.md +0 -411
  139. package/dist/docs/typed-functions.md +0 -94
  140. package/dist/docs/verify-before-deploy.md +0 -67
  141. package/dist/docs/vs-supabase.md +0 -75
  142. package/dist/docs/vs-vercel.md +0 -103
@@ -1,489 +0,0 @@
1
- # Deployed Functions
2
-
3
- ## Functions
4
-
5
- A function is a TypeScript file in `api/`. Its path is its route:
6
- `api/hello.ts` answers `/api/hello`. Deploy the source and Somewhere compiles it.
7
-
8
- A JSON route in api/ is export default sw.endpoint({ auth, handler }) with auth set explicitly. TypeScript infers the handler inputs and sw context. auth: 'none' marks a deliberately public route.
9
-
10
- ```ts
11
- // api/hello.ts
12
- export default sw.endpoint({ auth: 'none', handler: async () => ({ ok: true }) });
13
- ```
14
-
15
- ### Validate input and sign-in
16
-
17
- This function takes feedback from a signed-in user and writes it to your
18
- project logs:
19
-
20
- ```ts
21
- // api/feedback.ts
22
- export default sw.endpoint({
23
- auth: 'required',
24
- body: { message: 'string' },
25
- rateLimit: '5/hour',
26
- handler: async ({ body, user }, sw) => {
27
- const message = body.message.trim();
28
- if (!message || message.length > 2000) {
29
- return Response.json({ error: 'Feedback must be 1–2,000 characters.' }, { status: 400 });
30
- }
31
- await sw.logs.info('feedback', { user_id: user.id, message });
32
- return Response.json({ received: true }, { status: 202 });
33
- },
34
- });
35
- ```
36
-
37
- Call it from your page with an ordinary same-origin request. The browser sends
38
- the session cookie and its origin, so there's no token or CORS setup:
39
-
40
- ```ts
41
- // src/services/feedback.ts
42
- export async function sendFeedback(message: string): Promise<void> {
43
- const response = await fetch('/api/feedback', {
44
- method: 'POST',
45
- headers: { 'Content-Type': 'application/json' },
46
- body: JSON.stringify({ message }),
47
- });
48
- if (!response.ok) {
49
- const payload: unknown = await response.json().catch(() => null);
50
- const error =
51
- typeof payload === 'object' && payload !== null && 'error' in payload ? payload.error : null;
52
- throw new Error(typeof error === 'string' ? error : `Request failed (${response.status}).`);
53
- }
54
- }
55
- ```
56
-
57
- Run `somewhere typecheck`, then `somewhere deploy`. Send feedback from the
58
- signed-in app, then run `somewhere logs --tail 5` to see the entry. A
59
- signed-out request gets 401, an empty message gets 400, and a sixth message
60
- within an hour gets 429.
61
-
62
- The generated TypeScript declarations infer `body.message`, `user` and `sw`
63
- from the endpoint settings. Both typecheck and deploy use those declarations.
64
-
65
- ### The rules that keep it correct
66
-
67
- - **Check the caller, then the input, then act.** In the example, the log
68
- write comes after the user, body and allowance checks. Do the same before any
69
- write, email, payment or call to another service.
70
- - **Use `sw` for built-in platform operations.** `sw.db`, `sw.auth`, `sw.fs`,
71
- `sw.email`, `sw.ai`, `sw.jobs` and the rest are already scoped to your
72
- project, with no keys or URLs. Don't use the SDK's HTTP clients
73
- (`createClient`, `createSomewhereAuth`) inside a function. They reach the
74
- platform API or your own origin over HTTP. The supported server-side SDK use
75
- is the packaged sign-in route that the starter's `api/auth/[...path].ts`
76
- re-exports, `export { somewhereAuth as default } from '@somewhere-cloud/sdk/server'`,
77
- with `@somewhere-cloud/sdk` pinned in `package.json`.
78
- - **Long work goes to a job.** Keep a handler to the work its response needs.
79
- Work that must outlive the request belongs in `sw.jobs`. For
80
- what happens when a caller disconnects mid-request, see
81
- `functions` → `when-the-caller-disconnects-mid-request`.
82
- - **A caller may retry.** Someone who never saw your response can send the
83
- request again. For effects that must not repeat, such as an email or a
84
- charge, pass the service's idempotency key or check before acting.
85
-
86
- ### Routes and files
87
-
88
- - `api/notes/[id].ts` answers `/api/notes/42`, with `sw.params.id === '42'`.
89
- `api/files/[...path].ts` matches the rest of the path.
90
- - Use named methods such as `GET` and `DELETE` when behavior depends on the
91
- method. See `sw.endpoint` for the export shapes.
92
- - A file or folder whose name starts with `_` (such as `api/_lib/format.ts`) is
93
- an import-only helper, not a route.
94
- - npm packages listed in `package.json` are bundled at deploy. Pure-JavaScript
95
- packages built on web-standard APIs work. Native modules such as `sharp` don't.
96
- - Functions can `fetch` public HTTPS endpoints. For URLs that users can
97
- influence, use `sw.fetch`. It blocks private addresses, checks redirects and
98
- applies a timeout.
99
-
100
- ### Endpoint options
101
-
102
- For an ordinary JSON endpoint, use `sw.endpoint` and set its options
103
- explicitly: `auth: 'required'` (or `'optional'` / `'none'` only when the
104
- endpoint is public on purpose), a `body` schema and a `rateLimit`. A deploy
105
- refuses an endpoint written without `auth`; `body` and `rateLimit` apply
106
- only when declared. The direct HTTP handler under **Format** also supports webhooks and streaming. Typed
107
- functions generate a typed browser client from a contract you declare next to
108
- either form.
109
-
110
- ### More on functions
111
-
112
- | Need | Where |
113
- |---|---|
114
- | Wrapper with auth, body schema, rate limit, CORS | `sw.endpoint` |
115
- | Typed browser client for a function | `typed-functions` |
116
- | Compiling, imports, npm packages, lockfiles | `functions` → `compilation-ship-ts-not-pre-built-mjs` |
117
- | Runtime APIs and outbound requests | `functions` → `runtime-and-outbound-networking`, `sw.fetch` |
118
- | Caller disconnects mid-request | `functions` → `when-the-caller-disconnects-mid-request` |
119
- | Dynamic routes and params | `functions` → `routing`, `reading-route-params` |
120
- | Redirects, binary files, outbound WebSockets | `functions` → `redirects`, `binary-files-in-deploy`, `outbound-websocket-client` |
121
- | Rate-limit counters | `sw.rateLimit` |
122
- | Calling from another origin | `cors` |
123
-
124
- ## Compilation: ship .ts, not pre-built .mjs
125
-
126
- You write `api/chat.ts` (with whatever imports it needs); the platform
127
- compiles it to a self-contained function the runtime executes. You ship
128
- the same files you write. **Do not pre-bundle.** No `esbuild api/chat.ts
129
- -o api/chat.mjs`, no `tsc`, no `vite build`. Pre-built output still deploys,
130
- but with a warning, and bundled functions lose cross-function imports and source
131
- round-trips; pass `--prebuilt`, enable the project setting, or send
132
- `allow_bundled: true` only if you accept that.
133
-
134
- What works inside a function source file — **all natively, no
135
- restructuring**:
136
- - TypeScript syntax (type annotations, interfaces) — stripped.
137
- - Type-only imports (`import { type X } from './types'`) — stripped.
138
- - Imports from ANY folder —
139
- `import { foo } from '../utils/helpers'`,
140
- `import { z } from './schemas'`, etc.
141
- - **No extension required** — `'./helper'` resolves to
142
- `./helper.ts`/`.tsx`/`.js`/`.mjs`/`.json` automatically.
143
- - **JSON imports** — `import data from './seed.json'` works ONLY when the
144
- `.json` is part of your function source set (uploaded alongside your
145
- handlers, not as a separate static asset). A `.json` that lives in your
146
- static `files` — or a blob in a parent folder — is NOT a bundler module
147
- and fails to compile with `No such module`. For data you deploy as a
148
- static file, read it at runtime with `sw.fs.server.read()`; inline small
149
- constants directly in code.
150
- - The documented runtime compatibility subset includes `node:crypto`,
151
- `node:buffer`, `node:events`, `node:path`, `node:stream`,
152
- `node:string_decoder`, `node:util`, and `node:url`;
153
- `cloudflare:workers` also passes through. Do not assume another Node
154
- built-in is supported unless it is documented.
155
- `node:fs` also loads, but it is temporary scratch space, not storage:
156
- only `/tmp` is writable, and everything written there is gone after the
157
- response. Use `sw.fs` for any file that must persist.
158
-
159
- **npm packages resolve at deploy, with compatibility boundaries** — declare
160
- them in `package.json` and the platform bundles them (no npm install).
161
- Pure-JS packages that use web-standard APIs or the documented compatibility
162
- subset work, including `zod`, `lodash`, `nanoid`, and `date-fns`. Native
163
- modules such as `sharp` are unsupported, and a package that requires another
164
- Node built-in may be refused with `FUNCTION_BUILD_ERROR`. Package compatibility
165
- is not universal; prefer web-standard APIs where they suffice. Declare versions in `package.json`;
166
- `zod@^3.22` is a range, and a range resolves at deploy time. To pin
167
- exactly, ship a `package-lock.json` (version 2 or 3) — see docs({ topic:
168
- 'deploy' }) → "Dependencies and lockfiles". A compiled release records the
169
- package versions and relationships it selected or bundled and never
170
- re-resolves. No build step on your side — you deploy raw source and the
171
- platform handles it.
172
-
173
- ## Format
174
- For a webhook, streaming, or custom HTTP response, a function file can export a plain request handler:
175
-
176
- ```ts
177
- // api/raw-hello.ts
178
- export default async function(req: Request, sw: SomewhereRuntimeContext) {
179
- return Response.json({ hello: 'world' })
180
- }
181
- ```
182
-
183
- req = standard Request object (method, headers, json(), text(), etc.)
184
- sw = project-scoped platform context with all services
185
-
186
- ## Runtime and outbound networking
187
-
188
- Functions run in a Workers-compatible Web runtime, not a Node server process.
189
- Available Web APIs include `Request`, `Response`, `Headers`, `URL`,
190
- `URLSearchParams`, `fetch`, `WebSocket`, `crypto`, `TextEncoder`,
191
- `TextDecoder`, `ReadableStream`, `WritableStream`, `TransformStream`,
192
- `Blob`, `FormData`, timers, and `AbortController`.
193
-
194
- Use standard `fetch()` for public HTTP and HTTPS requests. The platform checks
195
- destinations and redirects; calls return a standard `Response`. Check
196
- `response.ok` before reading the body. `sw.fetch` is the same function.
197
- Timeouts, cancellation and destination rules: `docs({ topic: 'sw.fetch' })`.
198
- Raw TCP sockets and listening ports are not part of the customer runtime
199
- contract; use HTTPS or an outbound WebSocket.
200
-
201
- ## When the caller disconnects mid-request
202
-
203
- A visitor who closes the tab, or a client that times out, does not cut your
204
- handler off half-way:
205
- - A handler that has started runs to its own end: until it returns or throws.
206
- It is not retried and gets no extra time beyond that.
207
- - The budget is the one every request has: the CPU limit, and about 30 s after
208
- the disconnect. A handler still running at that point is stopped.
209
- - The response is discarded. A streamed body is not kept going once your
210
- handler has returned.
211
- - Your logs show it. A `CLIENT_DISCONNECTED` warning is written when the
212
- caller leaves, and a second one when the handler finishes, with its status.
213
- If only the first one is there, the handler was stopped before it finished.
214
-
215
- This protects work that belongs to the request, like writing a row and then
216
- emailing the members. Work that must happen whatever the caller does, or that
217
- takes longer than that, belongs in `sw.jobs`. Keep handlers
218
- safe to repeat anyway (`idempotency_key` on email sends): a caller who never
219
- saw the answer may retry.
220
-
221
- ## sw.endpoint — the ordinary JSON endpoint
222
-
223
- Most endpoints need sign-in, body validation and a rate limit. `sw.endpoint`
224
- declares them so you only write business logic; set each one explicitly: a
225
- deploy refuses an endpoint written without `auth`, and `body` / `rateLimit`
226
- are off unless declared. See **Format** for the bare `export default async function(req, sw)` for
227
- webhooks, streaming and custom responses. This is the contact insert from
228
- "Routing" below, on the same `contacts` table:
229
-
230
- ```ts
231
- // api/contacts/add.ts — a signed-in user adds a contact
232
- export default sw.endpoint({
233
- auth: 'required', // signed out → 401 AUTH_REQUIRED
234
- body: { email: 'string' }, // mismatch → 400 VALIDATION_ERROR
235
- rateLimit: '10/minute', // over → 429 RATE_LIMITED + Retry-After
236
- handler: async ({ body, user }, sw) => {
237
- const email = body.email.trim();
238
- if (email.length > 254 || !/^[^\s@]+@[^\s@]+$/.test(email)) {
239
- return Response.json({ error: 'BAD_EMAIL', message: 'Enter a valid email address.' }, { status: 400 });
240
- }
241
- // contacts is an owner() table: the row is stamped with this user.
242
- const { data: [contact] } = await sw.db.insert('contacts', { email });
243
- return { id: contact.id, owner: user.id };
244
- },
245
- });
246
- ```
247
-
248
- Full reference (schema types, handler args { body, user, headers, params,
249
- request }, error formatting, CORS): `docs({ topic: 'sw.endpoint' })`.
250
-
251
- ## sw services available
252
- sw.db — database (query, batch, from/insert/update/remove, live, tables)
253
- sw.auth — signed-in user (requireUser, fromRequest)
254
- sw.fs — file storage (read, write, delete, move, stat, list, glob, diff, search, replace)
255
- sw.email — send email (send)
256
- sw.ai — AI models (chat, complete, embeddings, transcribe, tts, generateImage, evaluate, catalog)
257
- sw.agent — inline/durable model-tool loops (run, start, status, cancel)
258
- sw.env — environment variables (sw.env.STRIPE_KEY etc.)
259
- sw.fetch — outbound HTTP requests
260
- sw.search — search indexes (upsert, query, remove)
261
- sw.payments — checkout (checkout, checkoutForUser)
262
- sw.jobs — background jobs (create, status, cancel, verifyInvocation)
263
- sw.logs — application logging (info, warn, error, debug)
264
-
265
- Each has its own topic with the full surface.
266
-
267
- ## Routing
268
- File path becomes the URL path:
269
- api/hello.ts → /api/hello
270
- api/users/list.ts → /api/users/list
271
- api/auth/login.ts → /api/auth/login
272
-
273
- Parametric segments use square brackets and become req.params:
274
- api/sites/[id].ts → /api/sites/123 → req.params.id === '123'
275
- api/users/[userId]/posts.ts → /api/users/42/posts → req.params.userId === '42'
276
- api/files/[...path].ts → /api/files/a/b/c → req.params.path === 'a/b/c'
277
-
278
- [name] — single-segment placeholder
279
- [...name] — catch-all, must be the last segment, matches one or more segments
280
-
281
- Specific routes beat dynamic ones. api/sites/new.ts wins over api/sites/[id].ts
282
- for /api/sites/new. [...rest] only matches when nothing more specific does.
283
-
284
- In a shell, quote bracket paths — `mkdir -p api/auth && cat > 'api/auth/[...path].ts'`.
285
- Unquoted, zsh reads the brackets as a pattern and stops with "no matches found".
286
-
287
- A function fetching its OWN origin (https://<project>.somewhere.site/...) hits
288
- the function router, NOT your static files — an unmatched path returns
289
- FUNCTION_NOT_FOUND (404), even for a path that serves fine to an external
290
- browser. Don't self-fetch your own static URLs: read static assets with
291
- sw.fs.server.read() or inline them. (External clients still get the static file — only
292
- the function's own same-origin subrequest skips the static fallback.)
293
-
294
- All HTTP methods hit the same function. Check req.method inside:
295
-
296
- ```ts
297
- // db/schema.ts — owner() scopes every contacts call to the signed-in user
298
- import { schema, table, id, text, owner } from 'somewhere/db'
299
- export default schema({
300
- contacts: table({ id: id(), email: text() }, { scope: owner() }),
301
- })
302
- ```
303
-
304
- ```ts
305
- // api/contacts.ts
306
- export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
307
- const user = await sw.auth.fromRequest(req)
308
- if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
309
- if (req.method === 'GET') {
310
- const contacts = await sw.db.from('contacts', { limit: 50 })
311
- return Response.json(contacts.data)
312
- }
313
- if (req.method === 'POST') {
314
- const body = await req.json().catch(() => null)
315
- const email = body && body.email
316
- if (typeof email !== 'string' || email.length > 254 || !/^[^\s@]+@[^\s@]+$/.test(email)) {
317
- return Response.json({ error: 'invalid email' }, { status: 400 })
318
- }
319
- await sw.db.insert('contacts', { email })
320
- return Response.json({ ok: true })
321
- }
322
- return new Response('Method not allowed', { status: 405 })
323
- }
324
- ```
325
-
326
- ## Server-rendered pages alongside the SPA
327
-
328
- Create `[...path].ts` at the project root, then deploy raw source normally.
329
- The root catch-all handles document paths, including `/`, and the special
330
- `/sitemap.xml` and `/robots.txt` paths. A root `[page].ts` matches one
331
- segment. Static files explicitly deployed at a non-root path take precedence;
332
- reserved paths and script, stylesheet and image requests keep their normal
333
- handlers. The SPA's implicit `index.html` fallback does not override a
334
- root catch-all.
335
-
336
- This route serves an HTML document without JavaScript and keeps the SPA at
337
- `/`. Replace the article constant with an authorized data read when needed.
338
-
339
- ```ts
340
- // [...path].ts
341
- const article = { title: 'Getting started', body: 'Your first article.' };
342
- const escapeHtml = (value: string): string => value.replace(/&/g, '&amp;')
343
- .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
344
-
345
- export default async function(request: Request): Promise<Response> {
346
- const path = new URL(request.url).pathname;
347
- if (path === '/') {
348
- return Response.json({ error: 'FUNCTION_NOT_FOUND' }, { status: 404 });
349
- }
350
- if (request.method !== 'GET' && request.method !== 'HEAD') {
351
- return new Response('Method not allowed', { status: 405, headers: { Allow: 'GET, HEAD' } });
352
- }
353
- if (path === '/articles/getting-started') {
354
- const html = '<!doctype html><html><head><title>' + escapeHtml(article.title)
355
- + '</title></head><body><h1>' + escapeHtml(article.title)
356
- + '</h1><p>' + escapeHtml(article.body) + '</p></body></html>';
357
- return new Response(request.method === 'HEAD' ? null : html, {
358
- headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'private, no-store' },
359
- });
360
- }
361
- return new Response(request.method === 'HEAD' ? null : '<h1>Article not found</h1>', {
362
- status: 404, headers: { 'Content-Type': 'text/html; charset=utf-8' },
363
- });
364
- }
365
- ```
366
-
367
- Return the JSON `FUNCTION_NOT_FOUND` marker only for paths you want the
368
- SPA/static chain to own. Return an ordinary HTML 404 for a missing article;
369
- adding `404.html` alone does not disable the SPA fallback. Do not fetch your
370
- own origin to get `index.html`: same-origin function subrequests use the
371
- function router. The explicit decline above uses the platform's static chain.
372
- Include `*.ts` in your TypeScript configuration when adding root route files.
373
- Verify `/`, a known article and a missing article with JavaScript disabled.
374
-
375
- ## Reading route params
376
-
377
- For parametric routes, req.params holds the decoded segment values;
378
- `sw.params` is its typed twin. Reading one contact from the `contacts` table
379
- above:
380
-
381
- ```ts
382
- // api/contacts/[id].ts
383
- export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
384
- const user = await sw.auth.fromRequest(req)
385
- if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
386
- const contact = await sw.db.from('contacts', { where: { id: sw.params.id }, limit: 1 })
387
- if (!contact.data.length) return new Response('Not found', { status: 404 })
388
- return Response.json(contact.data[0])
389
- }
390
- ```
391
-
392
- ```ts
393
- // api/files/[...path].ts — a signed-in user reads files under their own folder
394
- export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
395
- const user = await sw.auth.fromRequest(req)
396
- if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
397
- const parts = sw.params.path.split('/') // sw.params is the typed twin of req.params
398
- if (parts.some((p) => p === '' || p === '.' || p === '..')) return new Response('Bad path', { status: 400 })
399
- try {
400
- // sw.fs.read checks the caller only against files an app user owns; a private
401
- // file your server wrote is project-owned and would be returned to any caller
402
- // of this route. Reading only under /uploads/<user.id>/ keeps each user to
403
- // their own folder.
404
- const file = await sw.fs.server.read(`/uploads/${user.id}/${parts.join('/')}`)
405
- return new Response(file.body, { headers: { 'Content-Type': file.headers.get('Content-Type') || 'application/octet-stream' } })
406
- } catch (err) {
407
- if ((err as { status?: number }).status === 404) return new Response('Not found', { status: 404 })
408
- throw err
409
- }
410
- }
411
- ```
412
-
413
- For downloads, a short-lived link from `sw.fs.server.signedUrl(path)` keeps file
414
- bytes out of your function; per-user upload and download rules with no
415
- function at all are declared files (`docs({ topic: 'declared-files' })`).
416
-
417
- ## Outbound WebSocket client
418
- A function can open an OUTBOUND WebSocket to another server — a
419
- server-to-server bridge — with a fetch upgrade. Set `WEBSOCKET_UPSTREAM_URL`
420
- to your upstream server's HTTPS endpoint that accepts a WebSocket upgrade.
421
-
422
- ```ts
423
- // api/socket-bridge.ts
424
- export default async function(req: Request, sw: SomewhereRuntimeContext) {
425
- const upstream = sw.env.WEBSOCKET_UPSTREAM_URL
426
- if (!upstream) {
427
- return Response.json({
428
- error: 'UPSTREAM_WEBSOCKET_NOT_CONFIGURED',
429
- message: 'Set WEBSOCKET_UPSTREAM_URL to your server’s WebSocket upgrade endpoint.'
430
- }, { status: 503 })
431
- }
432
- const resp = await fetch(upstream, { headers: { Upgrade: 'websocket' } })
433
- const ws = resp.webSocket
434
- if (!ws) {
435
- return Response.json({
436
- error: 'UPSTREAM_WEBSOCKET_REFUSED',
437
- message: 'The server did not upgrade the connection. Check that WEBSOCKET_UPSTREAM_URL points to an endpoint that accepts WebSocket upgrades.',
438
- upstream_status: resp.status
439
- }, { status: 502 })
440
- }
441
- ws.accept()
442
- ws.send('hello')
443
- ws.addEventListener('message', (e) => { /* handle e.data */ })
444
- return new Response('bridged')
445
- }
446
- ```
447
-
448
- This is for connecting OUT to someone else's socket. To push updates to your
449
- OWN app's browser clients, declare a live view over the data they are
450
- watching — the channel transport does not accept app-user sessions. See
451
- docs({ topic: 'live' }).
452
-
453
- ## Secrets / env vars
454
- Set them with the CLI or MCP as shown in [Environment variables and secrets](https://somewhere.cloud/docs/sw.env.txt).
455
- Access inside functions as sw.env.KEY_NAME, read inside the handler. The
456
- checked example is `sw.env` → `timing` (`api/admin/stripe-balance.ts`): it
457
- lets only admins call the integration and returns only the field the page
458
- needs, so the key and the provider's full response stay on the server.
459
-
460
- ## Binary files in deploy
461
- Static files go in the files parameter.
462
- Binary files (images, fonts) go in binary_files as base64:
463
-
464
- project_deploy({
465
- project_id: "my-app",
466
- files: {
467
- "index.html": "<html>...</html>",
468
- "api/hello.ts": "export default sw.endpoint({ auth: 'none', handler: async () => ({ ok: true }) });"
469
- },
470
- binary_files: {
471
- "images/logo.png": "iVBORw0KGgo..."
472
- }
473
- })
474
-
475
- ## Redirects
476
-
477
- There is no `sw.redirect`. Return a standard redirect response with an
478
- ABSOLUTE URL: `return Response.redirect(new URL('/billing', req.url).toString(), 302)`.
479
- A relative location is not a valid redirect target inside a deployed function.
480
-
481
- ## What NOT to do
482
- - NEVER deploy a separate backend, Express server, or external BFF — the platform IS your backend
483
- - NEVER put secrets in the files parameter (use env vars)
484
- - NEVER call api.somewhere.cloud from inside a function (use sw directly)
485
- - NEVER use the SDK's HTTP clients (`createClient`, `createSomewhereAuth`) inside functions — they reach
486
- api.somewhere.cloud or your own origin over HTTP; use sw. The supported server-side SDK use is the packaged
487
- sign-in route, in `api/auth/[...path].ts`:
488
- `export { somewhereAuth as default } from '@somewhere-cloud/sdk/server'`, with `@somewhere-cloud/sdk`
489
- in your package.json (the `somewhere init` starter has both; docs({ topic: 'auth-client' }))