@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,424 @@
1
+ # sw.fs — File Storage (inside deployed functions)
2
+
3
+ Read, write, delete, and manage files in the project's storage.
4
+ Call these methods directly in your function; there's no URL to build and
5
+ no key to pass. Files are PRIVATE by default — pass
6
+ `visibility: 'public'` on the write (or call the make-public action)
7
+ to serve a file at its public `/storage` URL.
8
+
9
+ App users reach a file only where a rule gives it to them. `sw.fs` acts as
10
+ the signed-in user of the request (with no valid signed-in user it throws
11
+ `AUTH_REQUIRED`, 401, before any file is touched), and that user may:
12
+
13
+ - use the files of a declared file collection, as its rules allow;
14
+ - read a public file;
15
+ - read and change a file they already own.
16
+
17
+ Nothing else. A signed-in `sw.fs` call cannot create a file outside a
18
+ collection, and cannot read or change the project's files (files you or your
19
+ functions wrote with `sw.fs.server` or your developer key): writes answer
20
+ 403 `FILE_ACCESS_DENIED`, reads 404 `NOT_FOUND`. The answer is the same
21
+ whether or not something exists at the path.
22
+
23
+ Files a function keeps for a user, like the examples below, use
24
+ `sw.fs.server` after the function's own check, with the path confined to
25
+ that user (`/uploads/${user.id}/…`). Never pass a path the caller chose.
26
+ Work that runs without a user, such as a cron or a queue message, uses
27
+ `sw.fs.server` the same way. A public file's URL stays public to everyone.
28
+
29
+ Browser uploads with per-user or per-team rules need no function: declare a
30
+ file collection in `db/schema.ts` and use `somewhere:files`
31
+ (`docs({ topic: 'declared-files' })`). `sw.fs.server.setOwner(path, userId,
32
+ { collection })` adopts an existing file into a collection.
33
+
34
+ There are two file surfaces: deployed source is read with
35
+ `project_files_list` / `project_file_read`; `sw.fs` is runtime
36
+ storage for uploads and generated files. If you want `src/App.tsx`
37
+ or `api/foo.ts`, use `project_file_read`, not `sw.fs.read`.
38
+
39
+ ## What you get out of the box (the industry-standard checklist)
40
+
41
+ - **File-level ACL (visibility).** Every file row carries a
42
+ `visibility` flag (`public` | `private`); the platform checks
43
+ it before bytes go out the door. Bucket-level ACLs alone can't
44
+ give you private-by-row.
45
+ - **Object versioning + content-addressed writes.** Every write
46
+ generates a new immutable object with a content-hash suffix and
47
+ swaps the metadata pointer atomically. A half-written file never
48
+ becomes visible.
49
+ - **Safe delete.** A delete removes the file's record first and its
50
+ stored bytes afterwards, so a deleted file is never left listed without
51
+ its bytes. If a read finds a file's bytes missing, it answers
52
+ `NOT_FOUND` and removes the record; a developer can check a whole
53
+ project with `file-tools` → `integrity-check-orphan-file-records`.
54
+ - **Versions + retention** by tier (3 / 10 / 50 / unlimited prior
55
+ versions kept).
56
+ - **Signed URLs with TTL** via `sw.fs.signedUrl(path, { expiresIn })`.
57
+ - **SSRF protection on every platform-side fetch** (render, scrape,
58
+ webhooks, AI ingest) — private and metadata IPs blocked before
59
+ the request leaves.
60
+ - **Project-wide search, glob and diff** for developers and agents:
61
+ `file-tools`.
62
+
63
+ Full reviewer-facing depth: <https://somewhere.cloud/docs/llms.txt>.
64
+
65
+ ## sw.fs.write(path, content, options?)
66
+ ```ts
67
+ // api/avatar.ts — store the signed-in user's avatar from the request body
68
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
69
+ if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
70
+ const user = await sw.auth.fromRequest(req)
71
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
72
+ const result = await sw.fs.server.write(`/uploads/${user.id}/avatar.png`, await req.arrayBuffer(), {
73
+ content_type: 'image/png'
74
+ })
75
+ // result = { ok: true, data: { path, size_bytes: 12400, content_type: 'image/png',
76
+ // version: 1, content_revision } }
77
+ // Read fields off result.data — e.g. result.data.path, result.data.size_bytes
78
+ // (size_bytes, NOT size). result.path is undefined.
79
+ return Response.json({ path: result.data.path, size_bytes: result.data.size_bytes })
80
+ }
81
+ ```
82
+
83
+ ## sw.fs.read(path, options?)
84
+ ```ts
85
+ // api/avatar/get.ts — return the signed-in user's avatar
86
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
87
+ const user = await sw.auth.fromRequest(req)
88
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
89
+ try {
90
+ const file = await sw.fs.server.read(`/uploads/${user.id}/avatar.png`)
91
+ // Success: Response object — file.arrayBuffer() / file.text() / file.json()
92
+ return new Response(file.body, { headers: { 'Content-Type': file.headers.get('Content-Type') || 'application/octet-stream' } })
93
+ } catch (err) {
94
+ // Failure: throws an error with code, status, and message. Missing files throw
95
+ // NOT_FOUND (404); an error response body is never returned as file content.
96
+ if ((err as { status?: number }).status === 404) return new Response('Not found', { status: 404 })
97
+ throw err
98
+ }
99
+ }
100
+ ```
101
+
102
+ The thrown error also applies to line-range reads. Apps deployed before this
103
+ behavior shipped need a new deploy to receive it. Reading a directory path,
104
+ such as `/uploads/<user id>/`, returns its listing as a JSON response;
105
+ `sw.fs.list` (below) returns a typed listing.
106
+
107
+ Read a line range from a stored text file (returns parsed JSON):
108
+
109
+ ```ts
110
+ // api/imports/excerpt.ts — lines 50–75 of the signed-in user's import log
111
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
112
+ const user = await sw.auth.fromRequest(req)
113
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
114
+ const slice = await sw.fs.server.read(`/logs/${user.id}/import-run.txt`, { lines: [50, 75] })
115
+ // slice = { path, content: '...', lines: [50, 75], total_lines: 420,
116
+ // content_type, version, content_revision }
117
+ return Response.json({ content: slice.content, total_lines: slice.total_lines })
118
+ }
119
+ ```
120
+
121
+ ## sw.fs.list(path, options?)
122
+ ```ts
123
+ // api/uploads/index.ts — every file under the signed-in user's folder
124
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
125
+ const user = await sw.auth.fromRequest(req)
126
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
127
+ // Directory listing. Pass { recursive: true } for the full subtree,
128
+ // or { recursive: true, depth: 2 } to cap the walk.
129
+ const all = await sw.fs.server.list(`/uploads/${user.id}/`, { recursive: true })
130
+ // all = { path, type: 'directory', recursive: true, depth: null, entries: [{ path, name,
131
+ // type, size_bytes, content_type, version, updated_at }, ...] }
132
+ // A listing without recursive also carries next_cursor.
133
+ return Response.json(all.entries.map((entry) => entry.path))
134
+ }
135
+ ```
136
+
137
+ ## sw.fs.server — explicit project-wide file access
138
+
139
+ In a deployed handler, use `sw.fs.server.read/write/list` and the other
140
+ ordinary file operations when the application intentionally needs project-wide
141
+ access. Authorize the caller in your application before choosing this view;
142
+ it does not apply the request user's ownership filter. It uses the same
143
+ signatures and result shapes as `sw.fs` and does not expose the cross-file
144
+ scanners in `file-tools`. It is also the file view for crons, queue
145
+ messages and other work without a signed-in user, where plain `sw.fs` throws
146
+ `AUTH_REQUIRED`.
147
+
148
+ ## sw.fs.dev — project-wide file view (run_code only)
149
+ `sw.fs.dev` and its search, glob and diff are described in `file-tools` →
150
+ `who-can-use-them`. Ordinary `sw.fs` calls need a
151
+ signed-in user; without one (a cron, for example) they throw `AUTH_REQUIRED`,
152
+ so use `sw.fs.server` there. A job started by a signed-in user reads and
153
+ writes files as that user. A row-bound job's grant (`sw.jobs` →
154
+ `act-on-one-row-for-the-signed-in-user`) gives its user no file access: plain
155
+ `sw.fs` is refused there. `sw.fs.server` stays your server code's explicit
156
+ project authority, so use it only after your own check.
157
+
158
+ ## sw.fs.delete(path)
159
+ ```ts
160
+ // api/uploads/remove.ts — delete one of the signed-in user's files
161
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
162
+ if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
163
+ const user = await sw.auth.fromRequest(req)
164
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
165
+ const result = await sw.fs.server.delete(`/uploads/${user.id}/old-file.txt`)
166
+ // Directory deletes are recursive. delete does not throw on a refused
167
+ // request: it resolves with the error body, so check ok.
168
+ if (!result.ok) return Response.json({ error: result.error, message: result.message }, { status: 400 })
169
+ return Response.json({ deleted: result.data.deleted })
170
+ }
171
+ ```
172
+
173
+ ## sw.fs.move(from, to, opts?)
174
+ ```ts
175
+ // api/avatar/commit.ts — make a finished upload the signed-in user's avatar
176
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
177
+ if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
178
+ const user = await sw.auth.fromRequest(req)
179
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
180
+ // Move a finished upload without sending the bytes through your function.
181
+ // overwrite replaces an existing destination in the same operation.
182
+ // Avoid a separate delete-then-move: another request can race between them.
183
+ const moved = await sw.fs.server.move(
184
+ `/uploads/${user.id}/avatar.upload`,
185
+ `/uploads/${user.id}/avatar.jpg`,
186
+ { overwrite: true }
187
+ )
188
+ // moved = { from, to }. Without overwrite, a destination collision returns
189
+ // VALIDATION_ERROR ("Destination ... already exists").
190
+ return Response.json(moved)
191
+ }
192
+ ```
193
+
194
+ ## sw.fs.copy(from, to)
195
+ ```ts
196
+ // api/drafts/duplicate.ts — copy one of the signed-in user's drafts
197
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
198
+ if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
199
+ const user = await sw.auth.fromRequest(req)
200
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
201
+ // Server-side copy. Instant — no bytes flow through your function.
202
+ const copied = await sw.fs.server.copy(
203
+ `/drafts/${user.id}/welcome.html`,
204
+ `/drafts/${user.id}/welcome-copy.html`,
205
+ )
206
+ // copied = { from, to, content_revision }
207
+ return Response.json(copied)
208
+ }
209
+ ```
210
+
211
+ ## sw.fs.versions(path)
212
+ ```ts
213
+ // api/notes/history.ts — earlier versions of the signed-in user's note
214
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
215
+ const user = await sw.auth.fromRequest(req)
216
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
217
+ const history = await sw.fs.server.versions(`/notes/${user.id}/draft.md`)
218
+ // Each write creates a new version. Earlier versions, most-recent first:
219
+ // history = { path, current_version: 7,
220
+ // versions: [{ version: 6, size_bytes, content_type, created_at }, ...] }
221
+ return Response.json(history.versions)
222
+ }
223
+ ```
224
+
225
+ ## sw.fs.restore(path, version)
226
+ ```ts
227
+ // api/notes/restore.ts — body { version }, a number from sw.fs.versions
228
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
229
+ if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
230
+ const user = await sw.auth.fromRequest(req)
231
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
232
+ const input: unknown = await req.json().catch(() => null)
233
+ const { version } = (input ?? {}) as { version?: unknown }
234
+ if (typeof version !== 'number' || !Number.isInteger(version)) return Response.json({ error: 'version' }, { status: 400 })
235
+ // Restores a previous version as the latest. Original versions stay in history.
236
+ const restored = await sw.fs.server.restore(`/notes/${user.id}/draft.md`, version)
237
+ // restored = { path, restored_version: 5, current_version: 8, content_revision }
238
+ return Response.json(restored)
239
+ }
240
+ ```
241
+
242
+ ## sw.fs.stat(path)
243
+ ```ts
244
+ // api/avatar/info.ts — metadata for the signed-in user's avatar
245
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
246
+ const user = await sw.auth.fromRequest(req)
247
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
248
+ const info = await sw.fs.server.stat(`/uploads/${user.id}/avatar.png`)
249
+ // info = { path, name, type: 'file', size_bytes, content_type, content_revision,
250
+ // visibility, version, created_at, updated_at }
251
+ return Response.json({ size_bytes: info.size_bytes, updated_at: info.updated_at })
252
+ }
253
+ ```
254
+
255
+ ## sw.fs.replace({ path, find, replace })
256
+ ```ts
257
+ // api/notes/rename-product.ts — find-and-replace in the signed-in user's note
258
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
259
+ if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
260
+ const user = await sw.auth.fromRequest(req)
261
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
262
+ // This note was written with sw.fs.server.write. Replacement archives
263
+ // the previous version, which sw.fs.server.restore can recover.
264
+ const result = await sw.fs.server.replace({
265
+ path: `/notes/${user.id}/draft.md`,
266
+ find: 'Acme Beta',
267
+ replace: 'Acme',
268
+ })
269
+ // result = { ok: true, replacements: 1, path, version: 4, size_bytes, content_revision }
270
+ // Literal match (not regex). Text files only.
271
+ return Response.json({ replacements: result.replacements })
272
+ }
273
+ ```
274
+
275
+ ## sw.fs.uploadFromRequest(req, { path, maxBytes?, allowedTypes?, fieldName?, public? })
276
+ // One-call upload handler for browser <input type="file"> forms. Parses
277
+ // multipart/form-data from the request, validates size + type, writes to
278
+ // storage, returns a short-lived signed URL for the private file by default.
279
+ // Pass public: true only for a world-readable file; then url is its permanent
280
+ // /storage URL. The result includes visibility so the caller can tell which.
281
+ //
282
+ // The whole point: the developer chooses the path, the helper handles
283
+ // every failure mode. Three lines instead of fifteen, and you never
284
+ // JSON-stringify raw bytes (which is what corrupts images on project_patch
285
+ // — use binary_files for asset deploys, sw.fs.uploadFromRequest for
286
+ // runtime uploads).
287
+
288
+ ```ts
289
+ // api/upload.ts
290
+ export default async function handler(req: Request, sw: SomewhereRuntimeContext) {
291
+ if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
292
+ const user = await sw.auth.fromRequest(req)
293
+ if (!user) return new Response('unauthorized', { status: 401 })
294
+ const { url, path, size, contentType } = await sw.fs.server.uploadFromRequest(req, {
295
+ path: `/uploads/${user.id}/${crypto.randomUUID()}.bin`,
296
+ maxBytes: 5 * 1024 * 1024, // optional, 5 MB cap
297
+ allowedTypes: ['image/png', 'image/jpeg'], // optional whitelist
298
+ fieldName: 'file', // optional, default 'file'
299
+ })
300
+ return Response.json({ url, path, size, contentType })
301
+ }
302
+ ```
303
+
304
+ // On the browser: const fd = new FormData(); fd.append('file', input.files[0])
305
+ // const r = await fetch('/api/upload', { method: 'POST', body: fd })
306
+ // const { url } = await r.json(); img.src = url
307
+ //
308
+ // Throws on every failure with a stable code in the message:
309
+ // UPLOAD_PATH_REQUIRED, UPLOAD_NOT_MULTIPART, UPLOAD_PARSE_FAILED,
310
+ // UPLOAD_FIELD_MISSING, UPLOAD_TYPE_NOT_ALLOWED, UPLOAD_FILE_EMPTY,
311
+ // UPLOAD_TOO_LARGE
312
+ // Wrap in try/catch and map to the HTTP status you want.
313
+ //
314
+ // For files larger than ~25 MB, mint a signed URL with sw.fs.uploadUrl
315
+ // instead and have the browser PUT direct — keeps the bytes off your
316
+ // function CPU.
317
+
318
+ ## sw.fs.uploadUrl({ path, maxSize?, contentType?, expiresIn? })
319
+ // Mints a short-lived signed URL the browser can PUT bytes to directly
320
+ // — without ever seeing your platform key. Use this for big uploads
321
+ // (videos, large images, archives) so the bytes don't round-trip through
322
+ // your function.
323
+ ```ts
324
+ // api/uploads/start.ts — a direct-upload URL for the signed-in user
325
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
326
+ if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
327
+ const user = await sw.auth.fromRequest(req)
328
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
329
+ const { url, multipart_url, expires_at } = await sw.fs.server.uploadUrl({
330
+ path: `/uploads/${user.id}/photo.jpg`,
331
+ maxSize: 10 * 1024 * 1024, // optional, defaults to tier max
332
+ contentType: 'image/jpeg', // optional, '*' if omitted
333
+ expiresIn: 300, // optional, seconds (default 300, max 3600)
334
+ })
335
+ return Response.json({ url, multipart_url, expires_at })
336
+ }
337
+ ```
338
+ // Browser side:
339
+ // await fetch(url, { method: 'PUT', headers: { 'Content-Type': 'image/jpeg' }, body: file })
340
+ // The PUT answers { path, size_bytes, content_type, version }.
341
+ //
342
+ // One request carries at most 100 MB. A bigger file (up to the plan's
343
+ // max_upload_mb) goes up in parts through the same URL — the response's
344
+ // multipart_url. Start, send each part, then complete:
345
+ // const s = (await (await fetch(multipart_url, { method: 'POST',
346
+ // headers: { 'Content-Type': 'application/json' },
347
+ // body: JSON.stringify({ size_bytes: file.size, content_type: file.type }) })).json()).data
348
+ // // s = { upload_id, part_size, part_count, parts_url, complete_url, abort_url, expires_at }
349
+ // for (let n = 1; n <= s.part_count; n++)
350
+ // await fetch(s.parts_url + '/' + n, { method: 'PUT',
351
+ // body: file.slice((n - 1) * s.part_size, n * s.part_size) })
352
+ // await fetch(s.complete_url, { method: 'POST' }) // → { path, size_bytes, content_type, version }
353
+ // Every part except the last is exactly part_size bytes (at most 90 MB).
354
+ // Starting uses up the URL. An upload not completed within 6 hours is
355
+ // discarded, parts included; DELETE abort_url discards it sooner. A file
356
+ // over the plan's limit is refused at start with PAYLOAD_TOO_LARGE.
357
+
358
+ ## sw.fs.signedUrl(path, { expiresIn? })
359
+ // Mints a short-lived URL anyone can GET to download the file — no
360
+ // platform key, no app-user JWT. Use for email attachments, image
361
+ // previews, share links, "download once" handoffs. Default 1h, max 7d.
362
+ ```ts
363
+ // api/invoices/link.ts — a one-hour download link for the signed-in user's invoice
364
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
365
+ if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
366
+ const user = await sw.auth.fromRequest(req)
367
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
368
+ const { url, expires_at } = await sw.fs.server.signedUrl(`/invoices/${user.id}/invoice-42.pdf`, {
369
+ expiresIn: 3600, // optional, seconds (60..604800)
370
+ })
371
+ return Response.json({ url, expires_at })
372
+ }
373
+ ```
374
+ // → url: 'https://api.somewhere.cloud/v1/fs-signed/<token>'
375
+ // → expires_at: ISO 8601 string
376
+ // Send the url in an email body, embed it in <img src=...>, etc.
377
+ // The URL stops working at expires_at; rotating JWT_SECRET invalidates
378
+ // every outstanding signed URL (bulk revocation lever).
379
+
380
+ For a smaller preview of a raster image, append `?w=384` to the signed URL.
381
+ The parameter is `w`, not `width`. Supported widths are 192, 384, 768 and 1536 pixels. Variants use WebP,
382
+ preserve aspect ratio and never upscale; the URL without `w` still returns
383
+ the original. Invalid `w` values and recognized unsupported image parameters
384
+ such as `width`, `height`, `format`, `quality` and `fit` return 400.
385
+ Other query parameters, including tracking tags and unrecognized names, are ignored.
386
+ Byte ranges work on originals; omit the `Range` header when requesting a variant.
387
+ An unsupported image type or failed transform returns the guarded original
388
+ with `X-Somewhere-Image-Variant: original`, rather than breaking the preview.
389
+ Signed downloads still verify the capability and current file revision before
390
+ using cached bytes. Cached bytes do not bypass expiry or permit another file.
391
+
392
+ ## sw.fs.public_url(path, { makePublic? })
393
+ // Returns a file's permanent, unauthenticated public URL. Asking for the
394
+ // URL does NOT silently expose a private file:
395
+ // - already-public file → returns the URL, visibility unchanged.
396
+ // - private file + makePublic → publishes it, returns the URL.
397
+ // - private file, no opt-in → throws FILE_PRIVATE (file stays private).
398
+ // For a time-limited link to a private file WITHOUT making it world-readable,
399
+ // use sw.fs.server.signedUrl(path) instead.
400
+ ```ts
401
+ // api/avatar/publish.ts — publish the signed-in user's avatar
402
+ export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
403
+ if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
404
+ const user = await sw.auth.fromRequest(req)
405
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
406
+ // This avatar was written with sw.fs.server.write.
407
+ const { public_url } = await sw.fs.server.public_url(`/uploads/${user.id}/avatar.png`, {
408
+ makePublic: true, // required to publish a private file
409
+ })
410
+ return Response.json({ public_url })
411
+ }
412
+ ```
413
+ // → public_url: 'https://myapp.somewhere.site/storage/uploads/<user id>/avatar.png'
414
+
415
+ ## Public URL
416
+ Files written with `visibility: 'public'` are served (no auth) at:
417
+ https://{subdomain}.somewhere.site/storage/{path}
418
+ Private files (the default) return 404 here — they're reachable only from
419
+ your authenticated code (sw.fs.read) or a signed URL.
420
+
421
+ ```html
422
+ <!-- Use the public URL directly in HTML -->
423
+ <img src="https://myapp.somewhere.site/storage/uploads/avatar.png" alt="Avatar" />
424
+ ```