@somewhere-cloud/cli 0.38.155 → 0.38.157
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 +8 -1
- package/dist/commands/docs.js +1 -1
- package/dist/lib/bundle.js +286 -188
- package/dist/lib/bundle.js.map +3 -3
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -3
- package/dist/docs/adopt.md +0 -39
- package/dist/docs/analytics.md +0 -161
- package/dist/docs/api-reference.md +0 -339
- package/dist/docs/api-surface.md +0 -2067
- package/dist/docs/app-mcp.md +0 -162
- package/dist/docs/architecture-patterns.md +0 -334
- package/dist/docs/auth-client.md +0 -531
- package/dist/docs/billing.md +0 -76
- package/dist/docs/browser.md +0 -639
- package/dist/docs/calendar.md +0 -298
- package/dist/docs/changes.md +0 -323
- package/dist/docs/cli.md +0 -407
- package/dist/docs/common-mistakes.md +0 -199
- package/dist/docs/connect-agent.md +0 -72
- package/dist/docs/cors.md +0 -114
- package/dist/docs/cron.md +0 -167
- package/dist/docs/database-engine.md +0 -167
- package/dist/docs/declared-data.md +0 -1656
- package/dist/docs/declared-files.md +0 -475
- package/dist/docs/deploy-intelligence.md +0 -188
- package/dist/docs/deploy.md +0 -733
- package/dist/docs/design-system.md +0 -273
- package/dist/docs/dev-environments.md +0 -496
- package/dist/docs/domain-ownership.md +0 -31
- package/dist/docs/domains.md +0 -370
- package/dist/docs/feedback.md +0 -88
- package/dist/docs/file-tools.md +0 -116
- package/dist/docs/functions.md +0 -489
- package/dist/docs/getting-started.md +0 -238
- package/dist/docs/github.md +0 -95
- package/dist/docs/google-calendar.md +0 -212
- package/dist/docs/groups.md +0 -836
- package/dist/docs/guarantees.md +0 -58
- package/dist/docs/handled-for-you.md +0 -224
- package/dist/docs/inspect.md +0 -171
- package/dist/docs/limits.md +0 -68
- package/dist/docs/live-data.md +0 -197
- package/dist/docs/live.md +0 -92
- package/dist/docs/local-dev.md +0 -30
- package/dist/docs/migration-supabase.md +0 -58
- package/dist/docs/payments.md +0 -1102
- package/dist/docs/portability.md +0 -194
- package/dist/docs/postgres.md +0 -301
- package/dist/docs/pricing-comparison.md +0 -42
- package/dist/docs/pricing.md +0 -39
- package/dist/docs/project-groups.md +0 -107
- package/dist/docs/projects.md +0 -380
- package/dist/docs/recipe-ai-agent.md +0 -112
- package/dist/docs/recipe-ai-features.md +0 -227
- package/dist/docs/recipe-ai-receipts.md +0 -783
- package/dist/docs/recipe-background-jobs.md +0 -369
- package/dist/docs/recipe-booking.md +0 -348
- package/dist/docs/recipe-csv-import.md +0 -390
- package/dist/docs/recipe-ecommerce.md +0 -127
- package/dist/docs/recipe-email.md +0 -282
- package/dist/docs/recipe-escalation.md +0 -133
- package/dist/docs/recipe-file-uploads.md +0 -159
- package/dist/docs/recipe-import-app.md +0 -110
- package/dist/docs/recipe-login.md +0 -457
- package/dist/docs/recipe-multi-chat.md +0 -198
- package/dist/docs/recipe-paid-api.md +0 -161
- package/dist/docs/recipe-pdfs.md +0 -205
- package/dist/docs/recipe-push-notifications.md +0 -107
- package/dist/docs/recipe-seo.md +0 -200
- package/dist/docs/recipe-signed-in-app.md +0 -330
- package/dist/docs/render.md +0 -99
- package/dist/docs/rooms.md +0 -554
- package/dist/docs/sdk.md +0 -287
- package/dist/docs/sdks.md +0 -24
- package/dist/docs/search.md +0 -199
- package/dist/docs/security-model.md +0 -168
- package/dist/docs/setup.md +0 -212
- package/dist/docs/smoke.md +0 -102
- package/dist/docs/speed.md +0 -298
- package/dist/docs/sql-compatibility.md +0 -96
- package/dist/docs/sw.agent.md +0 -248
- package/dist/docs/sw.ai.md +0 -1291
- package/dist/docs/sw.auth.md +0 -1811
- package/dist/docs/sw.billing.md +0 -171
- package/dist/docs/sw.db.md +0 -2128
- package/dist/docs/sw.email.md +0 -661
- package/dist/docs/sw.endpoint.md +0 -187
- package/dist/docs/sw.env.md +0 -303
- package/dist/docs/sw.fetch.md +0 -115
- package/dist/docs/sw.fs.md +0 -424
- package/dist/docs/sw.groups.md +0 -836
- package/dist/docs/sw.image.md +0 -69
- package/dist/docs/sw.jobs.md +0 -520
- package/dist/docs/sw.logs.md +0 -61
- package/dist/docs/sw.mail.md +0 -106
- package/dist/docs/sw.notifications.md +0 -78
- package/dist/docs/sw.push.md +0 -161
- package/dist/docs/sw.rateLimit.md +0 -67
- package/dist/docs/sw.web.md +0 -128
- package/dist/docs/tasks.md +0 -269
- package/dist/docs/test.md +0 -220
- package/dist/docs/tool-reference-account.md +0 -7
- package/dist/docs/tool-reference-ai.md +0 -121
- package/dist/docs/tool-reference-analytics.md +0 -37
- package/dist/docs/tool-reference-api.md +0 -19
- package/dist/docs/tool-reference-artifacts.md +0 -35
- package/dist/docs/tool-reference-auth.md +0 -163
- package/dist/docs/tool-reference-browser.md +0 -114
- package/dist/docs/tool-reference-code.md +0 -26
- package/dist/docs/tool-reference-connect.md +0 -21
- package/dist/docs/tool-reference-cron.md +0 -48
- package/dist/docs/tool-reference-db.md +0 -282
- package/dist/docs/tool-reference-domains.md +0 -107
- package/dist/docs/tool-reference-email.md +0 -55
- package/dist/docs/tool-reference-env.md +0 -19
- package/dist/docs/tool-reference-feedback.md +0 -56
- package/dist/docs/tool-reference-fs.md +0 -265
- package/dist/docs/tool-reference-github.md +0 -57
- package/dist/docs/tool-reference-groups.md +0 -85
- package/dist/docs/tool-reference-help.md +0 -29
- package/dist/docs/tool-reference-jobs.md +0 -39
- package/dist/docs/tool-reference-live.md +0 -48
- package/dist/docs/tool-reference-logs.md +0 -16
- package/dist/docs/tool-reference-payments.md +0 -44
- package/dist/docs/tool-reference-project.md +0 -706
- package/dist/docs/tool-reference-push.md +0 -78
- package/dist/docs/tool-reference-rate-limit.md +0 -18
- package/dist/docs/tool-reference-search.md +0 -68
- package/dist/docs/tool-reference-security.md +0 -42
- package/dist/docs/tool-reference-smoke.md +0 -17
- package/dist/docs/tool-reference-stock-photos.md +0 -20
- package/dist/docs/tool-reference-tasks.md +0 -73
- package/dist/docs/tool-reference-telegram.md +0 -32
- package/dist/docs/tool-reference-usage.md +0 -9
- package/dist/docs/tool-reference-web.md +0 -71
- package/dist/docs/tool-reference-webhooks.md +0 -9
- package/dist/docs/troubleshooting.md +0 -411
- package/dist/docs/typed-functions.md +0 -94
- package/dist/docs/verify-before-deploy.md +0 -67
- package/dist/docs/vs-supabase.md +0 -75
- package/dist/docs/vs-vercel.md +0 -103
package/dist/docs/recipe-seo.md
DELETED
|
@@ -1,200 +0,0 @@
|
|
|
1
|
-
# Recipe — SEO: titles, previews, sitemap
|
|
2
|
-
|
|
3
|
-
Give each page a title, a description and a link preview, let the platform
|
|
4
|
-
serve `robots.txt` and `sitemap.xml`, then check what the live release
|
|
5
|
-
actually ships. If the project has no `robots.txt` or `sitemap.xml` of its
|
|
6
|
-
own, the platform serves both: robots allows every crawler and points at the
|
|
7
|
-
sitemap, and the sitemap lists every deployed HTML page.
|
|
8
|
-
|
|
9
|
-
## 1. Title, description and link preview
|
|
10
|
-
|
|
11
|
-
Search results and link previews read the HTML the server sends. Put the
|
|
12
|
-
tags in `index.html`, which serves every route of a single-page app:
|
|
13
|
-
|
|
14
|
-
```html
|
|
15
|
-
<!-- index.html -->
|
|
16
|
-
<!doctype html>
|
|
17
|
-
<html lang="en">
|
|
18
|
-
<head>
|
|
19
|
-
<meta charset="UTF-8" />
|
|
20
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
21
|
-
<title>Notes — write it down, find it later</title>
|
|
22
|
-
<meta name="description" content="A notes app with search, sharing and export." />
|
|
23
|
-
<link rel="canonical" href="https://yourapp.com/" />
|
|
24
|
-
<meta property="og:title" content="Notes — write it down, find it later" />
|
|
25
|
-
<meta property="og:description" content="A notes app with search, sharing and export." />
|
|
26
|
-
<meta property="og:image" content="https://yourapp.com/og.png" />
|
|
27
|
-
<meta property="og:url" content="https://yourapp.com/" />
|
|
28
|
-
<meta name="twitter:card" content="summary_large_image" />
|
|
29
|
-
</head>
|
|
30
|
-
<body>
|
|
31
|
-
<div id="root"></div>
|
|
32
|
-
<script type="module" src="/src/main.tsx"></script>
|
|
33
|
-
</body>
|
|
34
|
-
</html>
|
|
35
|
-
```
|
|
36
|
-
|
|
37
|
-
Put the preview image at `public/og.png` and reference it by its full URL:
|
|
38
|
-
link-preview services don't resolve relative image paths. A 1200×630 image
|
|
39
|
-
fits the large preview card.
|
|
40
|
-
|
|
41
|
-
## 2. A different preview for a shareable page
|
|
42
|
-
|
|
43
|
-
Link-preview services read the HTML without running your JavaScript, so every
|
|
44
|
-
route of a single-page app shares the tags in `index.html`. For a page that
|
|
45
|
-
people share on its own, such as `/pricing`, ship an HTML file at
|
|
46
|
-
`pricing/index.html` with its own head and the same app script:
|
|
47
|
-
|
|
48
|
-
```html
|
|
49
|
-
<!-- pricing/index.html — served at /pricing -->
|
|
50
|
-
<!doctype html>
|
|
51
|
-
<html lang="en">
|
|
52
|
-
<head>
|
|
53
|
-
<meta charset="UTF-8" />
|
|
54
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
55
|
-
<title>Pricing — Notes</title>
|
|
56
|
-
<meta name="description" content="Free to start. Pro adds export and sharing." />
|
|
57
|
-
<link rel="canonical" href="https://yourapp.com/pricing" />
|
|
58
|
-
<meta property="og:title" content="Pricing — Notes" />
|
|
59
|
-
<meta property="og:image" content="https://yourapp.com/og-pricing.png" />
|
|
60
|
-
<meta property="og:url" content="https://yourapp.com/pricing" />
|
|
61
|
-
</head>
|
|
62
|
-
<body>
|
|
63
|
-
<div id="root"></div>
|
|
64
|
-
<script type="module" src="/src/main.tsx"></script>
|
|
65
|
-
</body>
|
|
66
|
-
</html>
|
|
67
|
-
```
|
|
68
|
-
|
|
69
|
-
The deploy compiles every HTML page's app script, so `/pricing` runs the same
|
|
70
|
-
app and your router renders the pricing route. The generated sitemap lists
|
|
71
|
-
`/pricing` too. For routes that only exist inside the client router, set the
|
|
72
|
-
tab title as the route renders:
|
|
73
|
-
|
|
74
|
-
```tsx
|
|
75
|
-
// src/pages/PricingPage.tsx
|
|
76
|
-
import { useEffect } from 'react';
|
|
77
|
-
|
|
78
|
-
export function PricingPage() {
|
|
79
|
-
useEffect(() => {
|
|
80
|
-
document.title = 'Pricing — Notes';
|
|
81
|
-
}, []);
|
|
82
|
-
return <h1>Pricing</h1>;
|
|
83
|
-
}
|
|
84
|
-
```
|
|
85
|
-
|
|
86
|
-
## 3. Sitemap and robots
|
|
87
|
-
|
|
88
|
-
The generated sitemap lists each deployed HTML page with its upload date.
|
|
89
|
-
Routes that exist only inside the client router aren't
|
|
90
|
-
deployed pages, so it can't list them: give them their own HTML file (step 2)
|
|
91
|
-
or ship your own `public/sitemap.xml`.
|
|
92
|
-
|
|
93
|
-
Shipping `public/robots.txt` or `public/sitemap.xml` replaces only that
|
|
94
|
-
generated file. Your rules are served as written, including `noindex` or
|
|
95
|
-
`Disallow` rules.
|
|
96
|
-
|
|
97
|
-
### Change notification (IndexNow)
|
|
98
|
-
|
|
99
|
-
After a release is live, the platform tells the IndexNow search engines (Bing and
|
|
100
|
-
the others that share IndexNow submissions) which public pages are new or changed
|
|
101
|
-
since the previous live release. Nothing needs to be configured.
|
|
102
|
-
|
|
103
|
-
- **Which pages:** deployed HTML pages, by the same rule as the generated sitemap.
|
|
104
|
-
A page counts when its file is new or its bytes changed; at most 1,000 URLs are
|
|
105
|
-
sent per release. When the previous release can't be read, every public page is sent.
|
|
106
|
-
- **Which hosts:** one submission per serving host, meaning the project's
|
|
107
|
-
`.somewhere.site` address and each attached custom domain. The dev slot's
|
|
108
|
-
address is never sent.
|
|
109
|
-
- **Ownership key:** each serving host answers `/<key>.txt` with the project's
|
|
110
|
-
IndexNow key, which the engines fetch to confirm the host. The key is derived from
|
|
111
|
-
the project and grants no access to it. A file you deploy at that path is served instead.
|
|
112
|
-
- **Nothing is sent** for temporary (unclaimed) or test projects, for draft, frozen,
|
|
113
|
-
archived or deleting projects, for a release that a newer release or a rollback
|
|
114
|
-
has already replaced, when `robots.txt` disallows every crawler
|
|
115
|
-
(`User-agent: *` with `Disallow: /`), or when no public page changed.
|
|
116
|
-
- **Errors never block a deploy.** An engine that is slow or refuses the
|
|
117
|
-
submission changes nothing about the release; the attempt is logged.
|
|
118
|
-
|
|
119
|
-
A submission asks the engines to recrawl those URLs. It is not indexing:
|
|
120
|
-
whether and when a page appears in results is up to each engine. Google does not
|
|
121
|
-
use IndexNow; Google Search Console handles sitemap submission for Google.
|
|
122
|
-
|
|
123
|
-
## 4. Check the live release
|
|
124
|
-
|
|
125
|
-
After a deploy, read what the active release ships:
|
|
126
|
-
|
|
127
|
-
```text
|
|
128
|
-
project_seo_check({ project_id: "my-app" })
|
|
129
|
-
```
|
|
130
|
-
|
|
131
|
-
It inspects the deployed `index.html`, `robots.txt` and `sitemap.xml` of the
|
|
132
|
-
active release, without fetching the site. Each item has a `status`:
|
|
133
|
-
|
|
134
|
-
- `automatic`: the release uses the platform fallback configuration.
|
|
135
|
-
- `app-supplied`: the release contains your file.
|
|
136
|
-
- `needs-attention`: something to fix, such as a missing title or
|
|
137
|
-
description, with a `suggestion`.
|
|
138
|
-
- `unknown`: the check couldn't inspect this item.
|
|
139
|
-
|
|
140
|
-
Open the public URLs to check the served pages and files. Verify ownership
|
|
141
|
-
and submit the sitemap in Search Console.
|
|
142
|
-
|
|
143
|
-
## 5. Server-rendered pages and redirects
|
|
144
|
-
|
|
145
|
-
For database-backed articles, return HTML from a root `[...path].ts` handler.
|
|
146
|
-
The `functions` topic's server-rendered pages recipe shows a public article
|
|
147
|
-
route alongside a React editor. Return each article's title, description,
|
|
148
|
-
canonical URL and body in that HTML; link previews do not run browser JavaScript.
|
|
149
|
-
A page handler can also return `Response.redirect(url, 301)`.
|
|
150
|
-
|
|
151
|
-
A client-only React route still renders in the browser. Use the static HTML
|
|
152
|
-
approach above for fixed pages, or the HTML handler for dynamic content.
|
|
153
|
-
Generated sitemap and IndexNow discovery cover deployed HTML files; they do
|
|
154
|
-
not enumerate database-backed article URLs. Supply a sitemap containing those
|
|
155
|
-
public URLs and check its served response alongside the articles.
|
|
156
|
-
|
|
157
|
-
## Deployed SEO metadata
|
|
158
|
-
|
|
159
|
-
`project_seo_check({ project_id })` and `GET /v1/projects/:id/seo` return the same authenticated, read-only inspection. The response identifies `release_id`, `version`,
|
|
160
|
-
`source_manifest_hash` and `compiled_artifact_digest` for the exact active
|
|
161
|
-
release. It inspects only `index.html`, `robots.txt` and `sitemap.xml`;
|
|
162
|
-
missing, changed or unverifiable release evidence is unavailable, not a pass.
|
|
163
|
-
|
|
164
|
-
Each item carries `status` (`automatic`, `app-supplied`,
|
|
165
|
-
`needs-attention`, `unknown`), `provenance`, bounded `values`,
|
|
166
|
-
a `value_count`, `values_truncated`, a `note` and optional advisory
|
|
167
|
-
`suggestion`. At most five values of 512 characters are returned per item;
|
|
168
|
-
duplicate detection retains the full count. Automatic means a platform
|
|
169
|
-
fallback is configured because an app-supplied file is absent; read the
|
|
170
|
-
public URL to confirm a request serves it. App-supplied robots rules and
|
|
171
|
-
metadata, including intentional noindex or Disallow rules, are preserved.
|
|
172
|
-
No source is edited. Inspecting a file larger than 256 KiB returns unknown.
|
|
173
|
-
|
|
174
|
-
Title, description, canonical and Open Graph values come from the deployed
|
|
175
|
-
homepage HTML. Static body text there reflects the file only: check the
|
|
176
|
-
rendered page for what is visible; crawlability stays unverified.
|
|
177
|
-
`coverage.public_response` is `unobserved`: no HTTP fetch, function
|
|
178
|
-
execution, authentication check, JavaScript rendering or crawl occurs. Client
|
|
179
|
-
routes, indexing and ranking remain unknown. Generated sitemaps include
|
|
180
|
-
static HTML paths only, not routes hidden behind a client router. Search
|
|
181
|
-
Console verification and submission are separate from this inspection.
|
|
182
|
-
|
|
183
|
-
## Automatic sitemap and robots files
|
|
184
|
-
|
|
185
|
-
If a project does not ship its own `sitemap.xml` or `robots.txt`, the
|
|
186
|
-
platform serves both automatically. The sitemap lists deployed HTML pages and
|
|
187
|
-
uses their upload times for `<lastmod>`; robots points crawlers at that
|
|
188
|
-
sitemap. Shipping either file overrides only that generated fallback. Routes
|
|
189
|
-
that exist only inside a client-side router are not separate deployed HTML
|
|
190
|
-
pages, so the generated sitemap cannot discover them. Ship crawlable HTML for
|
|
191
|
-
those routes or provide your own `sitemap.xml`.
|
|
192
|
-
|
|
193
|
-
## Going further
|
|
194
|
-
|
|
195
|
-
| Need | Where |
|
|
196
|
-
|---|---|
|
|
197
|
-
| A custom domain for the canonical URL | [Custom Domains](https://somewhere.cloud/docs/domains.txt) |
|
|
198
|
-
| How the check reports each field | `recipe-seo` → `deployed-seo-metadata` |
|
|
199
|
-
| The generated sitemap and robots files | `recipe-seo` → `automatic-sitemap-and-robots-files` |
|
|
200
|
-
| Visitor counts and top pages | `analytics` → `page-views` |
|
|
@@ -1,330 +0,0 @@
|
|
|
1
|
-
# Recipe — Sign-in, email alerts, daily reminder
|
|
2
|
-
|
|
3
|
-
Owners sign in and manage their own rows; a public form creates a row for an
|
|
4
|
-
owner and emails them; a daily job reminds owners of open rows. Shapes are
|
|
5
|
-
exact; names are yours to change. Every TypeScript file below passes
|
|
6
|
-
`somewhere typecheck` in a `somewhere init` project.
|
|
7
|
-
|
|
8
|
-
## 1. Start and sign in
|
|
9
|
-
|
|
10
|
-
Ask before destructive or paid actions unless the user already authorized them.
|
|
11
|
-
|
|
12
|
-
`somewhere init` in an empty directory: a React + TypeScript starter that
|
|
13
|
-
already signs users up and in. `api/auth/[...path].ts` is one line —
|
|
14
|
-
`export { somewhereAuth as default } from '@somewhere-cloud/sdk/server'` — and
|
|
15
|
-
`src/services/auth.ts` is the SDK client (`createSomewhereAuth()` from
|
|
16
|
-
`@somewhere-cloud/sdk/auth`). It has no email or cron code; the steps below
|
|
17
|
-
add them.
|
|
18
|
-
`POST /api/auth/signup` / `login` → `{ user: { id, email, role, display_name } }`
|
|
19
|
-
(for an account with email sign-in codes, login returns `{ mfa_required: true, mfa_token }`
|
|
20
|
-
and no session until the emailed code is entered: `sw.auth` → `email-sign-in-codes`); `GET /api/auth/me`
|
|
21
|
-
→ `{ user }` (`user: null` when signed out); errors are 4xx `{ error, message }`. In a function,
|
|
22
|
-
`await sw.auth.fromRequest(req)` → the user object itself, or `null`.
|
|
23
|
-
|
|
24
|
-
## 2. db/schema.ts
|
|
25
|
-
|
|
26
|
-
```ts
|
|
27
|
-
// db/schema.ts
|
|
28
|
-
import { schema, table, id, text, integer, owner } from 'somewhere/db';
|
|
29
|
-
|
|
30
|
-
export default schema({
|
|
31
|
-
profiles: table(
|
|
32
|
-
{ id: id(), handle: text({ unique: true }), owner_email: text() },
|
|
33
|
-
{ scope: owner() },
|
|
34
|
-
),
|
|
35
|
-
entries: table(
|
|
36
|
-
{
|
|
37
|
-
id: id(), title: text(), from_email: text(), owner_email: text(), status: text({ default: 'open' }),
|
|
38
|
-
notify_status: text({ default: 'pending' }), notify_error: text({ nullable: true }),
|
|
39
|
-
created_ms: integer(), reminded_ms: integer({ nullable: true }),
|
|
40
|
-
reminder_claimed_ms: integer({ nullable: true }), reminder_status: text({ nullable: true }),
|
|
41
|
-
},
|
|
42
|
-
{
|
|
43
|
-
scope: owner(),
|
|
44
|
-
indexes: [['status']],
|
|
45
|
-
client: { read: ['id', 'title', 'from_email', 'status', 'notify_status', 'created_ms'], update: ['status'] },
|
|
46
|
-
},
|
|
47
|
-
),
|
|
48
|
-
});
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
`owner()` adds and scopes a `user_id` column. The `entries` grant lets each
|
|
52
|
-
signed-in owner read those columns of their own rows and change `status`
|
|
53
|
-
through the generated client. It grants no create or delete, so a new entry
|
|
54
|
-
arrives only through the public form in step 4. `profiles` has no `client`
|
|
55
|
-
block, so the browser reaches it only through your functions. `somewhere typecheck`
|
|
56
|
-
types the whole runtime context (`SomewhereRuntimeContext`, including
|
|
57
|
-
`sw.email`, `sw.jobs` and `sw.logs`) and each declared table's rows from
|
|
58
|
-
this file, so the functions below need no hand-written types.
|
|
59
|
-
|
|
60
|
-
## 3. Owner pages (signed in)
|
|
61
|
-
|
|
62
|
-
The owner's page calls the generated client. Each call is scoped to the
|
|
63
|
-
signed-in owner, so it sends no user filter and needs no API file:
|
|
64
|
-
|
|
65
|
-
```ts
|
|
66
|
-
// src/services/entries.ts
|
|
67
|
-
import { data } from 'somewhere:data';
|
|
68
|
-
|
|
69
|
-
export async function listEntries() {
|
|
70
|
-
const page = await data.entries.list({ limit: 50 });
|
|
71
|
-
return page.data;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
export async function markDone(id: string) {
|
|
75
|
-
const { data: entry } = await data.entries.update(id, { status: 'done' });
|
|
76
|
-
return entry;
|
|
77
|
-
}
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
`update` returns `{ data: row, count, changes }`; a missing row and another owner's
|
|
81
|
-
row both throw `DataError` 404 `DATA_NOT_FOUND`.
|
|
82
|
-
|
|
83
|
-
Claiming a handle is how an owner opts into the public form: the handle is the
|
|
84
|
-
public address visitors submit to, and an owner without one receives nothing.
|
|
85
|
-
It stays a function, because it stores the verified session's email:
|
|
86
|
-
`sw.db.insert('profiles', { handle, owner_email: user.email }, { onConflict: 'ignore' })`
|
|
87
|
-
(`user` from `fromRequest`, none → 401 `AUTH_REQUIRED`); `changes === 0`
|
|
88
|
-
means it is taken → 409.
|
|
89
|
-
|
|
90
|
-
## 4. Public form: save first, then notify
|
|
91
|
-
|
|
92
|
-
The form addresses an owner by the handle they claimed in step 3. The function
|
|
93
|
-
looks the handle up and stores that owner's `user_id`; it never takes an owner
|
|
94
|
-
from the request.
|
|
95
|
-
|
|
96
|
-
```ts
|
|
97
|
-
// api/submit.ts — POST { handle, title, from_email } from a public page
|
|
98
|
-
export default sw.endpoint({
|
|
99
|
-
auth: 'none', // the handler applies its own access check below
|
|
100
|
-
handler: async ({ request: req }, sw) => {
|
|
101
|
-
const body = ((await req.json().catch(() => null)) ?? {}) as { handle?: unknown; title?: unknown; from_email?: unknown };
|
|
102
|
-
const { handle, title, from_email } = body;
|
|
103
|
-
if (typeof handle !== 'string' || typeof from_email !== 'string' || typeof title !== 'string'
|
|
104
|
-
|| !title.trim() || title.length > 200 || /[\r\n]/.test(title)
|
|
105
|
-
|| from_email.length > 254 || !/^[^\s@]+@[^\s@]+$/.test(from_email)) return Response.json({ error: 'bad input' }, { status: 400 });
|
|
106
|
-
// Public and unauthenticated: cap each sender (the platform-set client IP), then each owner's inbox.
|
|
107
|
-
const ip = req.headers.get('cf-connecting-ip') ?? 'unknown';
|
|
108
|
-
const perSender = await sw.rateLimit.check(`submit-ip:${ip}`, 5, 600);
|
|
109
|
-
if (!perSender.allowed) return Response.json({ error: 'too many submissions', retry_at: perSender.reset }, { status: 429 });
|
|
110
|
-
const { data: [profile] } = await sw.db.server.from('profiles', { where: { handle }, limit: 1 });
|
|
111
|
-
if (!profile) return Response.json({ error: 'unknown handle' }, { status: 404 });
|
|
112
|
-
const perOwner = await sw.rateLimit.check(`submit-to:${profile.id}`, 50, 86_400);
|
|
113
|
-
if (!perOwner.allowed) return Response.json({ error: 'too many submissions', retry_at: perOwner.reset }, { status: 429 });
|
|
114
|
-
// Server authority writes a row for someone else: name the owner column.
|
|
115
|
-
const saved = await sw.db.server.insert('entries', {
|
|
116
|
-
user_id: profile.user_id, owner_email: profile.owner_email, title: title.trim(), from_email, created_ms: Date.now(),
|
|
117
|
-
});
|
|
118
|
-
const entry = saved.data[0];
|
|
119
|
-
try {
|
|
120
|
-
const job = await sw.jobs.create({
|
|
121
|
-
handler: '/api/jobs/notify-entry',
|
|
122
|
-
payload: { entry_id: entry.id },
|
|
123
|
-
idempotency_key: `notify-entry-${entry.id}`,
|
|
124
|
-
});
|
|
125
|
-
// Job admission is awaited; the email is sent later by the signed handler.
|
|
126
|
-
await sw.logs.info('entry notification queued', { entry_id: entry.id, job_id: job.job_id });
|
|
127
|
-
return Response.json({ id: entry.id, received: true, notification: job.status }, { status: 201 });
|
|
128
|
-
} catch (error) {
|
|
129
|
-
const code = error instanceof Error && 'code' in error ? String(error.code) : 'JOB_ADMISSION_UNCONFIRMED';
|
|
130
|
-
const status = error instanceof Error && 'status' in error ? Number(error.status) : 0;
|
|
131
|
-
// A 4xx refusal (for example JOB_QUOTA_EXCEEDED or RATE_LIMITED) means no job
|
|
132
|
-
// exists: record it on the row so the owner sees it. Any other failure may
|
|
133
|
-
// still have admitted the job, so the row stays pending for its handler.
|
|
134
|
-
const refused = status >= 400 && status < 500;
|
|
135
|
-
await sw.db.server.update('entries', {
|
|
136
|
-
set: refused ? { notify_status: 'not_queued', notify_error: code } : { notify_error: code },
|
|
137
|
-
where: { id: entry.id },
|
|
138
|
-
});
|
|
139
|
-
await sw.logs.warn('entry notification not admitted', { entry_id: entry.id, code, refused });
|
|
140
|
-
// The entry is already saved. Never ask the visitor to submit it again.
|
|
141
|
-
return Response.json({ id: entry.id, received: true, notification: refused ? 'not_queued' : 'unconfirmed' }, { status: 201 });
|
|
142
|
-
}
|
|
143
|
-
},
|
|
144
|
-
});
|
|
145
|
-
```
|
|
146
|
-
|
|
147
|
-
Show **Saved; notification queued** only for `notification: 'queued'`.
|
|
148
|
-
Show **Saved; owner not notified** for `notification: 'not_queued'`. For any
|
|
149
|
-
other status, such as `indeterminate`, or `unconfirmed`, show
|
|
150
|
-
**Saved; notification not confirmed**. None of these means sent or delivered.
|
|
151
|
-
A burst of submissions can reach the account's job limits
|
|
152
|
-
(`JOB_QUOTA_EXCEEDED` or `RATE_LIMITED`, `sw.jobs` → `job-limits`). That refusal
|
|
153
|
-
is recorded on the saved entry as `notify_status: 'not_queued'` with its code in
|
|
154
|
-
`notify_error`, so the owner's list shows which entries were never notified.
|
|
155
|
-
An unconfirmed admission keeps `notify_status: 'pending'` and records the code,
|
|
156
|
-
because the job may still run. Keep the saved id and inspect the entry;
|
|
157
|
-
do not resubmit the form or replace its stable key after an unknown outcome.
|
|
158
|
-
The signed handler below observes the email result separately:
|
|
159
|
-
|
|
160
|
-
```ts
|
|
161
|
-
// api/jobs/notify-entry.ts
|
|
162
|
-
export default async function (req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
163
|
-
if (!(await sw.jobs.verifyInvocation(req))) return new Response('forbidden', { status: 403 });
|
|
164
|
-
const input: unknown = await req.json().catch(() => null);
|
|
165
|
-
const entryId = typeof input === 'object' && input !== null && 'entry_id' in input ? input.entry_id : null;
|
|
166
|
-
if (typeof entryId !== 'string' || entryId === '') {
|
|
167
|
-
return Response.json({ error: 'bad entry id' }, { status: 400 });
|
|
168
|
-
}
|
|
169
|
-
const { data: [entry] } = await sw.db.server.from('entries', { where: { id: entryId }, limit: 1 });
|
|
170
|
-
if (!entry) return Response.json({ error: 'entry not found' }, { status: 404 });
|
|
171
|
-
// A recorded outcome ends retries; an unknown send is not permission to send again.
|
|
172
|
-
if (entry.notify_status !== 'pending') return Response.json({ status: entry.notify_status });
|
|
173
|
-
let notify_status = 'unknown';
|
|
174
|
-
let notify_error: string | null = null;
|
|
175
|
-
try {
|
|
176
|
-
const sent = await sw.email.send({
|
|
177
|
-
to: entry.owner_email,
|
|
178
|
-
subject: `New entry: ${entry.title}`,
|
|
179
|
-
text: `${entry.title}\nFrom: ${entry.from_email}`,
|
|
180
|
-
idempotency_key: `entry-${entry.id}`,
|
|
181
|
-
});
|
|
182
|
-
notify_status = sent.status;
|
|
183
|
-
} catch (error) {
|
|
184
|
-
const code = error instanceof Error && 'code' in error ? String(error.code) : 'EMAIL_FAILED';
|
|
185
|
-
const status = error instanceof Error && 'status' in error ? Number(error.status) : 0;
|
|
186
|
-
notify_status = status === 422 || status === 429 ? 'failed' : 'unknown';
|
|
187
|
-
notify_error = code;
|
|
188
|
-
}
|
|
189
|
-
await sw.db.server.update('entries', { set: { notify_status, notify_error }, where: { id: entry.id } });
|
|
190
|
-
await sw.logs.info('entry notification outcome', { entry_id: entry.id, status: notify_status, code: notify_error });
|
|
191
|
-
return Response.json({ status: notify_status });
|
|
192
|
-
}
|
|
193
|
-
```
|
|
194
|
-
|
|
195
|
-
The recipient comes from the saved row, never the delivery payload. Keep the same email key on redelivery; inspect unknown results rather than
|
|
196
|
-
issuing a new key. Confirmed provider acceptance is `sent`, not delivery;
|
|
197
|
-
`captured` reaches only the controlled test inbox. `pending`,
|
|
198
|
-
`delivery_unknown` and `unknown` require inspection, not an automatic resend.
|
|
199
|
-
The row and project logs retain the outcome; a job whose runs keep failing
|
|
200
|
-
ends `failed` with its `error_code` (`sw.jobs`). The two rate limits still
|
|
201
|
-
protect submission and notification admission. The daily reminder below is separate.
|
|
202
|
-
|
|
203
|
-
## 5. Daily reminder (every plan)
|
|
204
|
-
|
|
205
|
-
Run this reminder on any plan. Set an IANA time zone when creating the
|
|
206
|
-
schedule, as shown below, or omit it to use UTC.
|
|
207
|
-
|
|
208
|
-
```ts
|
|
209
|
-
// api/jobs/remind.ts — called by the scheduler
|
|
210
|
-
export default async function (req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
211
|
-
if (!(await sw.jobs.verifyInvocation(req))) return new Response('forbidden', { status: 403 });
|
|
212
|
-
const eligible = { status: 'open', reminder_claimed_ms: null, reminded_ms: null,
|
|
213
|
-
created_ms: { lt: Date.now() - 86_400_000 } };
|
|
214
|
-
// Server reads have their own limit; generated browser list() pages allow at most 100.
|
|
215
|
-
const { data: due } = await sw.db.server.from('entries', {
|
|
216
|
-
where: eligible, limit: 200,
|
|
217
|
-
});
|
|
218
|
-
for (const row of due) {
|
|
219
|
-
const claim = await sw.db.server.update('entries', {
|
|
220
|
-
where: { ...eligible, id: row.id },
|
|
221
|
-
set: { reminder_claimed_ms: Date.now(), reminder_status: 'claimed' },
|
|
222
|
-
});
|
|
223
|
-
const entry = claim.data[0];
|
|
224
|
-
if (!entry) continue;
|
|
225
|
-
let reminder_status = 'review';
|
|
226
|
-
let reminded_ms: number | null = null;
|
|
227
|
-
let message_id: string | undefined;
|
|
228
|
-
let sendError: { code?: string } | undefined;
|
|
229
|
-
try {
|
|
230
|
-
const sent = await sw.email.send({ to: entry.owner_email, subject: 'An entry is waiting for you.',
|
|
231
|
-
text: entry.title, idempotency_key: `reminder-entry-${entry.id}` });
|
|
232
|
-
reminder_status = sent.status;
|
|
233
|
-
message_id = sent.message_id;
|
|
234
|
-
if (['sent', 'delivered', 'opened', 'clicked', 'captured'].includes(sent.status)) reminded_ms = Date.now();
|
|
235
|
-
} catch (err) {
|
|
236
|
-
sendError = err as { code?: string };
|
|
237
|
-
}
|
|
238
|
-
await sw.db.server.update('entries', { set: { reminder_status, reminded_ms }, where: { id: entry.id } });
|
|
239
|
-
await sw.logs.info('reminder outcome', { entry_id: entry.id, status: reminder_status, message_id, code: sendError?.code });
|
|
240
|
-
}
|
|
241
|
-
return Response.json({ checked: due.length });
|
|
242
|
-
}
|
|
243
|
-
```
|
|
244
|
-
|
|
245
|
-
A signed handler has no signed-in user, so it uses `sw.db.server.*`. Each
|
|
246
|
-
entry is claimed before sending, with its own stable email key. A competing
|
|
247
|
-
run gets no claimed row and skips it. `reminded_ms` records confirmed
|
|
248
|
-
acceptance or test capture, not delivery; `captured` reaches only the test inbox.
|
|
249
|
-
|
|
250
|
-
The actual send status stays on the row. A thrown send is recorded as `review`
|
|
251
|
-
because delivery could have occurred. Pending, unfamiliar or interrupted
|
|
252
|
-
attempts stay claimed for review before another attempt. Never clear a claim
|
|
253
|
-
automatically, including after an unknown send or a failed outcome update.
|
|
254
|
-
|
|
255
|
-
## 6. Deploy and verify
|
|
256
|
-
|
|
257
|
-
```bash
|
|
258
|
-
somewhere typecheck && somewhere deploy
|
|
259
|
-
somewhere cron create "0 9 * * *" /api/jobs/remind --name remind --timezone America/Los_Angeles
|
|
260
|
-
somewhere verify --url https://<project>.somewhere.site/<form-page> --flow flow.json
|
|
261
|
-
```
|
|
262
|
-
|
|
263
|
-
`flow.json` (one call, every step, one viewport: each viewport runs the whole
|
|
264
|
-
flow as its own session, so two would submit the form twice):
|
|
265
|
-
|
|
266
|
-
```json
|
|
267
|
-
{ "actions": [{ "fill": "#title", "value": "Verify entry" }, { "fill": "#from_email", "value": "v@example.com" },
|
|
268
|
-
{ "click": "#send" }, { "expect": { "selector": "#status", "text": "Received" } }], "viewports": ["desktop"] }
|
|
269
|
-
```
|
|
270
|
-
|
|
271
|
-
The flow expects your form page to have inputs `#title` and `#from_email`, a
|
|
272
|
-
`#send` button, and a `#status` element that shows "Received". For the owner
|
|
273
|
-
page add `"auth": { "user_id": "<test-user-id>" }` to a second flow, with a
|
|
274
|
-
managed test user (`somewhere docs browser`).
|
|
275
|
-
Mail to `<name>@<project>.test.somewhere.site` is read with
|
|
276
|
-
`somewhere email test-inbox <address>`. The inbox holds both sign-in email
|
|
277
|
-
and your own `sw.email.send` to a registered test user. That send returns
|
|
278
|
-
`status: 'captured'`: read the alert in that test inbox. For real addresses,
|
|
279
|
-
`sent` records acceptance by the email provider; `sw.email.status(id)`
|
|
280
|
-
reports delivery events. Treat `captured` and `sent` as successful
|
|
281
|
-
submission when displaying the form result. Use a real mailbox you control
|
|
282
|
-
when checking arrival.
|
|
283
|
-
|
|
284
|
-
### One owner, browser → reminder → inbox → database
|
|
285
|
-
|
|
286
|
-
Reuse a controlled owner who signed up through your UI as
|
|
287
|
-
`<name>@<project>.test.somewhere.site`, and sign it in at the start of
|
|
288
|
-
`owner-flow.json`. A seeded `auth: { user_id }` session is only for managed
|
|
289
|
-
test users, which expire after 24 hours, before any entry is due. The page below
|
|
290
|
-
must render that owner's entry titled "Verify reminder". Use an isolated
|
|
291
|
-
fixture with one open entry older than 24 hours and no reminder claim;
|
|
292
|
-
a newly submitted entry is not eligible for this daily reminder. The signed
|
|
293
|
-
handler claims each due row once, so inspect an unknown run instead of replaying
|
|
294
|
-
it or clearing its claim. Keep the test user's other due rows out of this fixture.
|
|
295
|
-
|
|
296
|
-
```json
|
|
297
|
-
{ "actions": [
|
|
298
|
-
{ "fill": "#auth-email", "value": "<name>@<project>.test.somewhere.site" },
|
|
299
|
-
{ "fill": "#auth-password", "value": "<test-password>" },
|
|
300
|
-
{ "click": "form:has(#auth-email) button[type=submit]" },
|
|
301
|
-
{ "expect": { "selector": "body", "text": "Verify reminder" } }],
|
|
302
|
-
"viewports": ["desktop"] }
|
|
303
|
-
```
|
|
304
|
-
|
|
305
|
-
With the recipe deployed and its `remind` schedule already created above,
|
|
306
|
-
replace the project, address and row id with that same fixture's values:
|
|
307
|
-
|
|
308
|
-
```bash
|
|
309
|
-
# Set PROJECT, OWNER_PAGE (such as /entries), TEST_EMAIL and ENTRY_ID for your fixture.
|
|
310
|
-
set -euo pipefail
|
|
311
|
-
somewhere verify --project "$PROJECT" --url "https://${PROJECT}.somewhere.site${OWNER_PAGE}" --flow owner-flow.json
|
|
312
|
-
somewhere cron run remind --project "$PROJECT" --wait
|
|
313
|
-
somewhere email test-inbox "$TEST_EMAIL" --project "$PROJECT"
|
|
314
|
-
somewhere db rows entries --project "$PROJECT" --where "id=$ENTRY_ID" --where "owner_email=$TEST_EMAIL" --json | node -e "const { rows } = JSON.parse(require('node:fs').readFileSync(0, 'utf8')); if (rows.length !== 1 || rows[0].title !== 'Verify reminder' || rows[0].reminder_status !== 'captured' || !rows[0].reminded_ms) process.exit(1)"
|
|
315
|
-
```
|
|
316
|
-
|
|
317
|
-
The inbox must contain this entry's title in the reminder message. The database
|
|
318
|
-
assertion checks the same row's recorded test capture, not inbox delivery or
|
|
319
|
-
owner isolation: `db rows` is developer inspection of managed production data;
|
|
320
|
-
its `--where` filters only the columns it returns, which omit the owner's user id.
|
|
321
|
-
The authenticated browser check exercises the owner-facing app. These are
|
|
322
|
-
separate CLI commands in one workflow, not invented `verify` step kinds.
|
|
323
|
-
Keep `owner-flow.json` with its test password out of the deployed source
|
|
324
|
-
(`echo "owner-flow.json" >> .somewhereignore`).
|
|
325
|
-
|
|
326
|
-
## 7. Use it from Claude (preview feature)
|
|
327
|
-
|
|
328
|
-
The same signed-in app can serve MCP tools at `https://<your-app-address>/mcp`,
|
|
329
|
-
so an owner can add it to Claude and work with their own rows from a chat. The
|
|
330
|
-
steps, tool examples and current limits are in `somewhere docs app-mcp`.
|
package/dist/docs/render.md
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
# Render — PDFs
|
|
2
|
-
|
|
3
|
-
Use `browser` to capture a page or render HTML into a PDF. Use
|
|
4
|
-
`sw.render.pdf` when generating a PDF from app code.
|
|
5
|
-
|
|
6
|
-
```json
|
|
7
|
-
{
|
|
8
|
-
"html": "<h1>Invoice #123</h1>",
|
|
9
|
-
"capture": { "as": "pdf", "paper": "Letter", "print_background": true }
|
|
10
|
-
}
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
The PDF defaults to Letter, portrait, with backgrounds rendered. Use
|
|
14
|
-
`capture.paper` for `A4`, `A3`, `Letter`, `Legal`, or `Tabloid`.
|
|
15
|
-
Use `capture.landscape: true` to rotate the page.
|
|
16
|
-
|
|
17
|
-
Pass `storage` with `project_id` to save the PDF to project files.
|
|
18
|
-
For a PDF artifact response from a URL or HTML, call
|
|
19
|
-
`POST /v1/render/pdf` with `url` or `html`, and optionally `format`
|
|
20
|
-
for paper size, `landscape`, `print_background`, `wait_for`,
|
|
21
|
-
`project_id`, and `storage`. Use `somewhere api POST /v1/render/pdf
|
|
22
|
-
--data-file request.json --raw` to stream the response to a file.
|
|
23
|
-
For image artifacts use `POST /v1/render/screenshot` with `url` or
|
|
24
|
-
`html` and optionally `format`, `width`, `height`, `quality`,
|
|
25
|
-
`full_page`, `wait_for`, `project_id`, and `storage`.
|
|
26
|
-
|
|
27
|
-
For private documents, use the signed-link pattern below. The full job
|
|
28
|
-
(generate, store privately, preview in the page, merge and split) is
|
|
29
|
-
covered by `recipe-pdfs`.
|
|
30
|
-
|
|
31
|
-
## Common pattern
|
|
32
|
-
|
|
33
|
-
Generate a PDF invoice on demand for a signed-in user. Renders are metered,
|
|
34
|
-
so the caller is checked before the render. Replace `invoiceHtml` with your
|
|
35
|
-
own lookup that only returns invoices belonging to the signed-in user:
|
|
36
|
-
|
|
37
|
-
```ts
|
|
38
|
-
// api/invoice-preview.ts — the page posts { invoiceId }
|
|
39
|
-
const escapeHtml = (text: string) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
40
|
-
const invoiceHtml = (invoiceId: string) => `<h1>Invoice ${escapeHtml(invoiceId)}</h1>`;
|
|
41
|
-
|
|
42
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext) {
|
|
43
|
-
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
44
|
-
const user = await sw.auth.requireUser(req);
|
|
45
|
-
const input: unknown = await req.json().catch(() => null);
|
|
46
|
-
const invoiceId = typeof input === 'object' && input !== null && 'invoiceId' in input ? input.invoiceId : undefined;
|
|
47
|
-
if (typeof invoiceId !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(invoiceId)) {
|
|
48
|
-
return Response.json({ error: 'invoiceId must be letters, digits, - or _.' }, { status: 400 });
|
|
49
|
-
}
|
|
50
|
-
// This app allows each user 20 invoice renders per hour.
|
|
51
|
-
const limit = await sw.rateLimit.check(`invoice-pdf:${user.id}`, 20, 3600);
|
|
52
|
-
if (!limit.allowed) return Response.json({ error: 'Try again later.' }, { status: 429 });
|
|
53
|
-
// sw.render.pdf returns a raw Response when no storage path is set —
|
|
54
|
-
// pipe it straight to the client.
|
|
55
|
-
return sw.render.pdf({ html: invoiceHtml(invoiceId), format: 'Letter' });
|
|
56
|
-
}
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
Or keep it as a private file and share a link that expires:
|
|
60
|
-
|
|
61
|
-
```ts
|
|
62
|
-
// api/invoice-link.ts — the page posts { invoiceId }; replace invoiceHtml with your own authorized invoice lookup
|
|
63
|
-
const escapeHtml = (text: string) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
64
|
-
const invoiceHtml = (invoiceId: string) => `<h1>Invoice ${escapeHtml(invoiceId)}</h1>`;
|
|
65
|
-
|
|
66
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext) {
|
|
67
|
-
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
68
|
-
const user = await sw.auth.requireUser(req);
|
|
69
|
-
const input: unknown = await req.json().catch(() => null);
|
|
70
|
-
const invoiceId = typeof input === 'object' && input !== null && 'invoiceId' in input ? input.invoiceId : undefined;
|
|
71
|
-
// The id becomes part of a file path, so allow only plain id characters.
|
|
72
|
-
if (typeof invoiceId !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(invoiceId)) {
|
|
73
|
-
return Response.json({ error: 'invoiceId must be letters, digits, - or _.' }, { status: 400 });
|
|
74
|
-
}
|
|
75
|
-
// This app allows each user 20 invoice renders per hour.
|
|
76
|
-
const limit = await sw.rateLimit.check(`invoice-pdf:${user.id}`, 20, 3600);
|
|
77
|
-
if (!limit.allowed) return Response.json({ error: 'Try again later.' }, { status: 429 });
|
|
78
|
-
const pdf = await sw.render.pdf({ html: invoiceHtml(invoiceId), format: 'Letter' });
|
|
79
|
-
const path = `/invoices/${user.id}/${invoiceId}.pdf`;
|
|
80
|
-
await sw.fs.server.write(path, await pdf.arrayBuffer(), { contentType: 'application/pdf' });
|
|
81
|
-
const link = await sw.fs.server.signedUrl(path, { expiresIn: 3600 });
|
|
82
|
-
return Response.json({ url: link.url });
|
|
83
|
-
}
|
|
84
|
-
```
|
|
85
|
-
|
|
86
|
-
A new file written with `sw.fs.server.write` is private unless you pass
|
|
87
|
-
`visibility: 'public'`; rewriting a file keeps its current visibility.
|
|
88
|
-
|
|
89
|
-
## Limits
|
|
90
|
-
- The page must finish loading within 30 seconds.
|
|
91
|
-
- `html` is at most 1,000,000 characters; `url` at most 2,048 characters.
|
|
92
|
-
- `wait_for` waits up to 5 seconds for its selector.
|
|
93
|
-
- Renders are metered and charged to the account balance.
|
|
94
|
-
|
|
95
|
-
## What NOT to do
|
|
96
|
-
- Don't pass a user-supplied `url` without your own allowlist. The renderer
|
|
97
|
-
refuses private and internal addresses, and prints any public page it is
|
|
98
|
-
given.
|
|
99
|
-
- Don't render on every page load — store the PDF once and serve the file.
|