@somewhere-cloud/cli 0.38.154 → 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.
- package/CHANGELOG.md +7 -0
- package/dist/docs/adopt.md +39 -0
- package/dist/docs/analytics.md +161 -0
- package/dist/docs/api-reference.md +339 -0
- package/dist/docs/api-surface.md +2067 -0
- package/dist/docs/app-mcp.md +162 -0
- package/dist/docs/architecture-patterns.md +334 -0
- package/dist/docs/auth-client.md +531 -0
- package/dist/docs/billing.md +76 -0
- package/dist/docs/browser.md +639 -0
- package/dist/docs/calendar.md +298 -0
- package/dist/docs/changes.md +323 -0
- package/dist/docs/cli.md +407 -0
- package/dist/docs/common-mistakes.md +199 -0
- package/dist/docs/connect-agent.md +72 -0
- package/dist/docs/cors.md +114 -0
- package/dist/docs/cron.md +167 -0
- package/dist/docs/database-engine.md +167 -0
- package/dist/docs/declared-data.md +1656 -0
- package/dist/docs/declared-files.md +475 -0
- package/dist/docs/deploy-intelligence.md +188 -0
- package/dist/docs/deploy.md +733 -0
- package/dist/docs/design-system.md +273 -0
- package/dist/docs/dev-environments.md +496 -0
- package/dist/docs/domain-ownership.md +31 -0
- package/dist/docs/domains.md +370 -0
- package/dist/docs/feedback.md +88 -0
- package/dist/docs/file-tools.md +116 -0
- package/dist/docs/functions.md +489 -0
- package/dist/docs/getting-started.md +238 -0
- package/dist/docs/github.md +95 -0
- package/dist/docs/google-calendar.md +212 -0
- package/dist/docs/groups.md +836 -0
- package/dist/docs/guarantees.md +58 -0
- package/dist/docs/handled-for-you.md +224 -0
- package/dist/docs/inspect.md +171 -0
- package/dist/docs/limits.md +68 -0
- package/dist/docs/live-data.md +197 -0
- package/dist/docs/live.md +92 -0
- package/dist/docs/local-dev.md +30 -0
- package/dist/docs/migration-supabase.md +58 -0
- package/dist/docs/payments.md +1102 -0
- package/dist/docs/portability.md +194 -0
- package/dist/docs/postgres.md +301 -0
- package/dist/docs/pricing-comparison.md +42 -0
- package/dist/docs/pricing.md +39 -0
- package/dist/docs/project-groups.md +107 -0
- package/dist/docs/projects.md +380 -0
- package/dist/docs/recipe-ai-agent.md +112 -0
- package/dist/docs/recipe-ai-features.md +227 -0
- package/dist/docs/recipe-ai-receipts.md +783 -0
- package/dist/docs/recipe-background-jobs.md +369 -0
- package/dist/docs/recipe-booking.md +348 -0
- package/dist/docs/recipe-csv-import.md +390 -0
- package/dist/docs/recipe-ecommerce.md +127 -0
- package/dist/docs/recipe-email.md +282 -0
- package/dist/docs/recipe-escalation.md +133 -0
- package/dist/docs/recipe-file-uploads.md +159 -0
- package/dist/docs/recipe-import-app.md +110 -0
- package/dist/docs/recipe-login.md +457 -0
- package/dist/docs/recipe-multi-chat.md +198 -0
- package/dist/docs/recipe-paid-api.md +161 -0
- package/dist/docs/recipe-pdfs.md +205 -0
- package/dist/docs/recipe-push-notifications.md +107 -0
- package/dist/docs/recipe-seo.md +200 -0
- package/dist/docs/recipe-signed-in-app.md +330 -0
- package/dist/docs/render.md +99 -0
- package/dist/docs/rooms.md +554 -0
- package/dist/docs/sdk.md +287 -0
- package/dist/docs/sdks.md +24 -0
- package/dist/docs/search.md +199 -0
- package/dist/docs/security-model.md +168 -0
- package/dist/docs/setup.md +212 -0
- package/dist/docs/smoke.md +102 -0
- package/dist/docs/speed.md +298 -0
- package/dist/docs/sql-compatibility.md +96 -0
- package/dist/docs/sw.agent.md +248 -0
- package/dist/docs/sw.ai.md +1291 -0
- package/dist/docs/sw.auth.md +1811 -0
- package/dist/docs/sw.billing.md +171 -0
- package/dist/docs/sw.db.md +2128 -0
- package/dist/docs/sw.email.md +661 -0
- package/dist/docs/sw.endpoint.md +187 -0
- package/dist/docs/sw.env.md +303 -0
- package/dist/docs/sw.fetch.md +115 -0
- package/dist/docs/sw.fs.md +424 -0
- package/dist/docs/sw.groups.md +836 -0
- package/dist/docs/sw.image.md +69 -0
- package/dist/docs/sw.jobs.md +520 -0
- package/dist/docs/sw.logs.md +61 -0
- package/dist/docs/sw.mail.md +106 -0
- package/dist/docs/sw.notifications.md +78 -0
- package/dist/docs/sw.push.md +161 -0
- package/dist/docs/sw.rateLimit.md +67 -0
- package/dist/docs/sw.web.md +128 -0
- package/dist/docs/tasks.md +269 -0
- package/dist/docs/test.md +220 -0
- package/dist/docs/tool-reference-account.md +7 -0
- package/dist/docs/tool-reference-ai.md +121 -0
- package/dist/docs/tool-reference-analytics.md +37 -0
- package/dist/docs/tool-reference-api.md +19 -0
- package/dist/docs/tool-reference-artifacts.md +35 -0
- package/dist/docs/tool-reference-auth.md +163 -0
- package/dist/docs/tool-reference-browser.md +114 -0
- package/dist/docs/tool-reference-code.md +26 -0
- package/dist/docs/tool-reference-connect.md +21 -0
- package/dist/docs/tool-reference-cron.md +48 -0
- package/dist/docs/tool-reference-db.md +282 -0
- package/dist/docs/tool-reference-domains.md +107 -0
- package/dist/docs/tool-reference-email.md +55 -0
- package/dist/docs/tool-reference-env.md +19 -0
- package/dist/docs/tool-reference-feedback.md +56 -0
- package/dist/docs/tool-reference-fs.md +265 -0
- package/dist/docs/tool-reference-github.md +57 -0
- package/dist/docs/tool-reference-groups.md +85 -0
- package/dist/docs/tool-reference-help.md +29 -0
- package/dist/docs/tool-reference-jobs.md +39 -0
- package/dist/docs/tool-reference-live.md +48 -0
- package/dist/docs/tool-reference-logs.md +16 -0
- package/dist/docs/tool-reference-payments.md +44 -0
- package/dist/docs/tool-reference-project.md +706 -0
- package/dist/docs/tool-reference-push.md +78 -0
- package/dist/docs/tool-reference-rate-limit.md +18 -0
- package/dist/docs/tool-reference-search.md +68 -0
- package/dist/docs/tool-reference-security.md +42 -0
- package/dist/docs/tool-reference-smoke.md +17 -0
- package/dist/docs/tool-reference-stock-photos.md +20 -0
- package/dist/docs/tool-reference-tasks.md +73 -0
- package/dist/docs/tool-reference-telegram.md +32 -0
- package/dist/docs/tool-reference-usage.md +9 -0
- package/dist/docs/tool-reference-web.md +71 -0
- package/dist/docs/tool-reference-webhooks.md +9 -0
- package/dist/docs/troubleshooting.md +411 -0
- package/dist/docs/typed-functions.md +94 -0
- package/dist/docs/verify-before-deploy.md +67 -0
- package/dist/docs/vs-supabase.md +75 -0
- package/dist/docs/vs-vercel.md +103 -0
- package/dist/lib/bundle.js +303 -221
- package/dist/lib/bundle.js.map +3 -3
- package/dist/types/lib/test-session.d.ts +8 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +3 -2
|
@@ -0,0 +1,489 @@
|
|
|
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, '&')
|
|
343
|
+
.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
|
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' }))
|