@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
|
@@ -1,390 +0,0 @@
|
|
|
1
|
-
# Recipe — CSV import
|
|
2
|
-
|
|
3
|
-
> **Verified end to end on 2026-11-05:** this recipe, copied unchanged into a
|
|
4
|
-
> new `somewhere init` app and deployed, imported a three-row file as one user;
|
|
5
|
-
> a repeat, an overlapping file, a file missing an email and a second user each
|
|
6
|
-
> behaved as section 5 states.
|
|
7
|
-
|
|
8
|
-
A signed-in user uploads a CSV of contacts and sees how many rows were stored.
|
|
9
|
-
The browser sends the file straight to storage, and one endpoint reads it,
|
|
10
|
-
checks every row, then writes them in atomic batches as that user. Importing
|
|
11
|
-
the same file again, or another file with some of the same addresses, updates
|
|
12
|
-
those contacts instead of adding duplicates. Every write goes through the
|
|
13
|
-
tables' declared access, so a user can only ever create or update their own
|
|
14
|
-
contacts.
|
|
15
|
-
|
|
16
|
-
## 1. db/schema.ts
|
|
17
|
-
|
|
18
|
-
```ts
|
|
19
|
-
// db/schema.ts
|
|
20
|
-
import { files, id, integer, owner, schema, table, text, timestamp } from 'somewhere/db';
|
|
21
|
-
|
|
22
|
-
export default schema({
|
|
23
|
-
imports: table(
|
|
24
|
-
{
|
|
25
|
-
id: id(), file_id: text({ unique: true }), status: text({ default: 'running' }),
|
|
26
|
-
rows_stored: integer({ default: 0 }), error: text({ nullable: true }), created_at: timestamp({ default: 'now' }),
|
|
27
|
-
},
|
|
28
|
-
{ scope: owner(), client: { read: ['id', 'file_id', 'status', 'rows_stored', 'error', 'created_at'] } },
|
|
29
|
-
),
|
|
30
|
-
contacts: table(
|
|
31
|
-
{ id: id(), email: text(), name: text(), import_id: text() },
|
|
32
|
-
{ scope: owner(), unique: [['user_id', 'email']], indexes: [['import_id']], client: { read: ['id', 'name', 'email'] } },
|
|
33
|
-
),
|
|
34
|
-
}, {
|
|
35
|
-
files: {
|
|
36
|
-
csv_uploads: files({
|
|
37
|
-
path: '/csv-uploads',
|
|
38
|
-
scope: owner(),
|
|
39
|
-
client: { read: true, upload: true },
|
|
40
|
-
limits: { maxSize: '2MB', types: ['text/csv'] },
|
|
41
|
-
}),
|
|
42
|
-
},
|
|
43
|
-
});
|
|
44
|
-
```
|
|
45
|
-
|
|
46
|
-
`owner()` on all three gives each user their own uploads, import rows and
|
|
47
|
-
contacts. The browser can upload and read; only your functions write rows.
|
|
48
|
-
`unique: [['user_id', 'email']]` makes an email address one contact per user:
|
|
49
|
-
`user_id` is the owner column the platform fills, so two users can each have
|
|
50
|
-
a contact with the same address. The collection accepts no browser replace or
|
|
51
|
-
delete, so the file an import reads is the file the user uploaded. The page
|
|
52
|
-
stores every upload as `upload.csv` under its own file id, so the function
|
|
53
|
-
builds the file's path from the id alone, never from a name the browser sends.
|
|
54
|
-
`'2MB'` is this example's cap; your plan's per-file ceiling is in `limits`.
|
|
55
|
-
|
|
56
|
-
## 2. The CSV reader
|
|
57
|
-
|
|
58
|
-
```ts
|
|
59
|
-
// api/_lib/csv.ts — comma-separated text: quoted fields, "" escapes, commas and line breaks inside quotes, LF or CRLF
|
|
60
|
-
export class CsvError extends Error {}
|
|
61
|
-
|
|
62
|
-
/** maxRecords counts the header row. */
|
|
63
|
-
export function parseCsv(text: string, maxRecords: number): string[][] {
|
|
64
|
-
const records: string[][] = [];
|
|
65
|
-
let record: string[] = [];
|
|
66
|
-
let field = '';
|
|
67
|
-
let state: 'start' | 'plain' | 'quoted' | 'closed' = 'start';
|
|
68
|
-
const endField = () => { record.push(field); field = ''; state = 'start'; };
|
|
69
|
-
const endRecord = () => {
|
|
70
|
-
endField();
|
|
71
|
-
if (record.length > 1 || record[0] !== '') records.push(record); // skip blank lines
|
|
72
|
-
if (records.length > maxRecords) throw new CsvError(`The file has more than ${maxRecords - 1} rows below the header.`);
|
|
73
|
-
record = [];
|
|
74
|
-
};
|
|
75
|
-
for (let i = text.charCodeAt(0) === 0xfeff ? 1 : 0; i < text.length; i++) {
|
|
76
|
-
const ch = text[i];
|
|
77
|
-
if (state === 'quoted') {
|
|
78
|
-
if (ch !== '"') field += ch;
|
|
79
|
-
else if (text[i + 1] === '"') { field += '"'; i++; }
|
|
80
|
-
else state = 'closed';
|
|
81
|
-
} else if (ch === ',') endField();
|
|
82
|
-
else if (ch === '\n') endRecord();
|
|
83
|
-
else if (ch === '\r' && text[i + 1] === '\n') { endRecord(); i++; }
|
|
84
|
-
else if (ch === '"' && state === 'start') state = 'quoted';
|
|
85
|
-
else if (ch === '"' || ch === '\r' || state === 'closed') throw new CsvError(`Row ${records.length + 1} is not valid CSV.`);
|
|
86
|
-
else { field += ch; state = 'plain'; }
|
|
87
|
-
}
|
|
88
|
-
if (state === 'quoted') throw new CsvError('A quoted field is not closed.');
|
|
89
|
-
if (state !== 'start' || field !== '' || record.length > 0) endRecord();
|
|
90
|
-
return records;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
export type ContactRow = { name: string; email: string };
|
|
94
|
-
|
|
95
|
-
/** Checks every row before any is written; a CsvError names the row to fix. */
|
|
96
|
-
export function contactsFromCsv(text: string, maxRows: number): ContactRow[] {
|
|
97
|
-
const [header, ...rows] = parseCsv(text, maxRows + 1);
|
|
98
|
-
if (header?.map((h) => h.trim().toLowerCase()).join(',') !== 'name,email') throw new CsvError('The first row must be: name,email');
|
|
99
|
-
return rows.map((row, index) => {
|
|
100
|
-
const [name = '', email = ''] = row.map((value) => value.trim());
|
|
101
|
-
if (row.length !== 2 || !name || name.length > 200 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
|
102
|
-
throw new CsvError(`Row ${index + 2}: expected a name and an email address.`);
|
|
103
|
-
}
|
|
104
|
-
return { name, email: email.toLowerCase() };
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
```
|
|
108
|
-
|
|
109
|
-
A file under `api/_lib/` is bundled into the functions that import it and is
|
|
110
|
-
never served as a route. Values come back as strings, unchanged. The
|
|
111
|
-
request below and the background job in **Larger files** both use
|
|
112
|
-
`contactsFromCsv`, so they accept and refuse the same files.
|
|
113
|
-
|
|
114
|
-
## 3. Import the file and report it
|
|
115
|
-
|
|
116
|
-
```ts
|
|
117
|
-
// api/imports.ts — POST { file_id } imports one uploaded CSV; GET ?file_id= reports it
|
|
118
|
-
import { type ContactRow, CsvError, contactsFromCsv } from './_lib/csv';
|
|
119
|
-
|
|
120
|
-
const MAX_ROWS = 2000; // this example's cap: one request reads, checks and writes the whole file
|
|
121
|
-
const BATCH = 100; // sw.db.tx takes 1–100 writes
|
|
122
|
-
|
|
123
|
-
export default sw.endpoint({
|
|
124
|
-
auth: 'none', // the handler applies its own access check below
|
|
125
|
-
handler: async ({ request }, sw) => {
|
|
126
|
-
const user = await sw.auth.fromRequest(request);
|
|
127
|
-
if (!user) return Response.json({ error: 'Sign in.' }, { status: 401 });
|
|
128
|
-
|
|
129
|
-
if (request.method === 'GET') {
|
|
130
|
-
const fileId = new URL(request.url).searchParams.get('file_id');
|
|
131
|
-
if (!fileId) return Response.json({ error: 'Pass ?file_id=<file id>.' }, { status: 400 });
|
|
132
|
-
// Runs as this user: another user's import is not found.
|
|
133
|
-
const { data: found } = await sw.db.from('imports', { where: { file_id: fileId }, limit: 1 });
|
|
134
|
-
const row = found[0];
|
|
135
|
-
if (!row) return Response.json({ error: 'No such import for this account.' }, { status: 404 });
|
|
136
|
-
return Response.json({ status: row.status, rows_stored: Number(row.rows_stored), error: row.error });
|
|
137
|
-
}
|
|
138
|
-
if (request.method !== 'POST') return new Response('Use GET or POST.', { status: 405, headers: { Allow: 'GET, POST' } });
|
|
139
|
-
|
|
140
|
-
const input = (await request.json().catch(() => null)) as { file_id?: unknown } | null;
|
|
141
|
-
const fileId = input?.file_id;
|
|
142
|
-
if (typeof fileId !== 'string' || !/^[A-Za-z0-9-]{8,64}$/.test(fileId)) {
|
|
143
|
-
return Response.json({ error: 'Send the file_id from the upload result.' }, { status: 400 });
|
|
144
|
-
}
|
|
145
|
-
// 20 per hour per user is this example's choice.
|
|
146
|
-
const allowance = await sw.rateLimit.check(`csv-import:${user.id}`, 20, 3600);
|
|
147
|
-
if (!allowance.allowed) return Response.json({ error: 'Try again later.' }, { status: 429 });
|
|
148
|
-
|
|
149
|
-
let text: string;
|
|
150
|
-
try {
|
|
151
|
-
// Runs as this user: another user's upload is not found.
|
|
152
|
-
const file = await sw.fs.read(`/csv-uploads/${fileId}/upload.csv`);
|
|
153
|
-
text = new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer());
|
|
154
|
-
} catch (error) {
|
|
155
|
-
if (error instanceof Error && 'status' in error && error.status === 404) {
|
|
156
|
-
return Response.json({ error: 'No such upload for this account.' }, { status: 404 });
|
|
157
|
-
}
|
|
158
|
-
if (error instanceof TypeError) return Response.json({ error: 'Save the file as CSV UTF-8 and upload it again.' }, { status: 422 });
|
|
159
|
-
throw error;
|
|
160
|
-
}
|
|
161
|
-
await sw.db.insert('imports', { file_id: fileId }, { onConflict: 'ignore' });
|
|
162
|
-
const finish = async (status: 'complete' | 'failed', rowsStored: number, error: string | null, httpStatus: number) => {
|
|
163
|
-
await sw.db.update('imports', { where: { file_id: fileId }, set: { status, rows_stored: rowsStored, error } });
|
|
164
|
-
return Response.json({ status, rows_stored: rowsStored, error }, { status: httpStatus });
|
|
165
|
-
};
|
|
166
|
-
|
|
167
|
-
let contacts: ContactRow[];
|
|
168
|
-
try {
|
|
169
|
-
contacts = contactsFromCsv(text, MAX_ROWS);
|
|
170
|
-
} catch (error) {
|
|
171
|
-
if (error instanceof CsvError) return finish('failed', 0, error.message, 422);
|
|
172
|
-
throw error;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
// Each batch is one atomic write as this user. An address already stored for this user is updated.
|
|
176
|
-
for (let start = 0; start < contacts.length; start += BATCH) {
|
|
177
|
-
await sw.db.tx(contacts.slice(start, start + BATCH).map((contact) => ({
|
|
178
|
-
op: 'insert' as const,
|
|
179
|
-
table: 'contacts',
|
|
180
|
-
values: { ...contact, import_id: fileId },
|
|
181
|
-
options: { onConflict: 'update' as const },
|
|
182
|
-
})));
|
|
183
|
-
}
|
|
184
|
-
return finish('complete', contacts.length, null, 200);
|
|
185
|
-
},
|
|
186
|
-
});
|
|
187
|
-
```
|
|
188
|
-
|
|
189
|
-
The import checks every row before it writes any, so a bad file stores
|
|
190
|
-
nothing and the import row says which row to fix. Each batch is atomic. The
|
|
191
|
-
insert runs as the signed-in user: the platform fills `user_id`, and
|
|
192
|
-
`onConflict: 'update'` updates the user's existing contact with the same
|
|
193
|
-
email (its name and `import_id`) instead of adding a second one. Two rows of
|
|
194
|
-
one file with the same address leave one contact with the later row's name.
|
|
195
|
-
Repeating the request, or importing an overlapping file, never creates a
|
|
196
|
-
duplicate. A lost connection part-way through leaves the batches that landed
|
|
197
|
-
stored; sending the same `file_id` again finishes the import, and
|
|
198
|
-
`rows_stored` counts the rows of the file.
|
|
199
|
-
|
|
200
|
-
The conflict update follows the table's declared access, like every
|
|
201
|
-
caller-scoped write. Under `owner()` the matching row is always the user's
|
|
202
|
-
own, because `user_id` is part of the unique key. If the contacts table is
|
|
203
|
-
shared with `anyOf(owner(), grant({ ... }))`
|
|
204
|
-
(`docs({ topic: 'declared-data', section: 'per-owner-sharing' })`), the same
|
|
205
|
-
code works unchanged: each person's import still updates only their own
|
|
206
|
-
contacts. With a unique key that does not include `user_id`, an address
|
|
207
|
-
stored by someone else refuses the batch with 403 `POLICY_AUTHORITY_REQUIRED`
|
|
208
|
-
unless their rule lets this user update it: see `sw.db` → Upserts.
|
|
209
|
-
|
|
210
|
-
## 4. The page
|
|
211
|
-
|
|
212
|
-
```ts
|
|
213
|
-
// src/services/csv-import.ts
|
|
214
|
-
import { files } from 'somewhere:files';
|
|
215
|
-
|
|
216
|
-
export type ImportState = { status: string; rows_stored: number | null; error: string | null };
|
|
217
|
-
|
|
218
|
-
/** Upload a CSV and import it. Returns the import's result. */
|
|
219
|
-
export async function importCsv(file: File): Promise<ImportState & { file_id: string }> {
|
|
220
|
-
if (!file.name.toLowerCase().endsWith('.csv')) throw new Error('Choose a .csv file.');
|
|
221
|
-
const { data: uploaded, error } = await files.csv_uploads.upload(file, { name: 'upload.csv', contentType: 'text/csv' });
|
|
222
|
-
if (error) throw new Error(error.message);
|
|
223
|
-
const response = await fetch('/api/imports', {
|
|
224
|
-
method: 'POST',
|
|
225
|
-
headers: { 'content-type': 'application/json' },
|
|
226
|
-
body: JSON.stringify({ file_id: uploaded.id }),
|
|
227
|
-
});
|
|
228
|
-
const result = (await response.json().catch(() => null)) as (ImportState & { error?: string | null }) | null;
|
|
229
|
-
if (response.status === 422 && result) return { ...result, file_id: uploaded.id };
|
|
230
|
-
if (!response.ok || typeof result?.status !== 'string') throw new Error(result?.error ?? `Could not import the file (${response.status}).`);
|
|
231
|
-
return { ...result, file_id: uploaded.id };
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
/** Read one import's recorded result. */
|
|
235
|
-
export async function readCsvImport(fileId: string): Promise<ImportState | null> {
|
|
236
|
-
const response = await fetch(`/api/imports?file_id=${encodeURIComponent(fileId)}`);
|
|
237
|
-
if (response.status === 404) return null;
|
|
238
|
-
const result = (await response.json().catch(() => null)) as ImportState | null;
|
|
239
|
-
if (!response.ok || typeof result?.status !== 'string') throw new Error(`Could not read the import (${response.status}).`);
|
|
240
|
-
return result;
|
|
241
|
-
}
|
|
242
|
-
```
|
|
243
|
-
|
|
244
|
-
Browsers label `.csv` files differently, so the page checks the extension and
|
|
245
|
-
sends the declared `text/csv` type itself, under the fixed name `upload.csv`.
|
|
246
|
-
The import still rejects anything that is not valid UTF-8 CSV. Call
|
|
247
|
-
`importCsv` from a file input:
|
|
248
|
-
|
|
249
|
-
- `complete` shows `rows_stored`.
|
|
250
|
-
- `failed` shows `error` (a bad header, an invalid row, not CSV). Nothing was
|
|
251
|
-
stored; upload the corrected file, which gets a new file id.
|
|
252
|
-
- A thrown error (a lost connection, a timeout) may come after some batches
|
|
253
|
-
were stored. `readCsvImport` shows `running` for an import that did not
|
|
254
|
-
finish; send the same file id again to finish it.
|
|
255
|
-
|
|
256
|
-
## 5. Check it
|
|
257
|
-
|
|
258
|
-
```bash
|
|
259
|
-
somewhere typecheck && somewhere deploy
|
|
260
|
-
somewhere db rows contacts
|
|
261
|
-
```
|
|
262
|
-
|
|
263
|
-
`contacts` is a declared table in the managed database. Use
|
|
264
|
-
`somewhere db rows contacts` to read its rows. `somewhere db query` reads the
|
|
265
|
-
separate raw SQL database.
|
|
266
|
-
|
|
267
|
-
Upload a three-row file: the import shows `complete` and `rows_stored: 3`,
|
|
268
|
-
and `db rows contacts` ends with `3 of 3 rows`. Upload the same file again,
|
|
269
|
-
or one that repeats an address with a new name: the count stays the same and
|
|
270
|
-
the name changes. Upload a file with a missing email on row 3: it shows
|
|
271
|
-
`failed` with `Row 3: expected a name and an email address.` and stores
|
|
272
|
-
nothing. A second user importing the same addresses gets their own contacts
|
|
273
|
-
and sees none of the first user's imports or contacts.
|
|
274
|
-
|
|
275
|
-
## Larger files
|
|
276
|
-
|
|
277
|
-
Each import above runs in one function request under the request limits in
|
|
278
|
-
`limits`. This recipe's caps (2 MB, 2,000 rows) keep its read, check and 20
|
|
279
|
-
batched writes small. Raise them only after timing a full import on your
|
|
280
|
-
deployed function. For files too large for one request, run the same import
|
|
281
|
-
as a background job. The file stays in file storage: the job reads it by its
|
|
282
|
-
file id, and the database holds only the import row and the contacts.
|
|
283
|
-
|
|
284
|
-
A job started from a signed-in user's request reads files as that user, so
|
|
285
|
-
the handler reads the upload with plain `sw.fs`, exactly as `api/imports.ts`
|
|
286
|
-
does, and another user's upload is not found
|
|
287
|
-
(`docs({ topic: 'sw.fs' })`, which also covers `sw.fs.server`).
|
|
288
|
-
That user authority lasts 10 minutes from `sw.jobs.verifyInvocation`, so the
|
|
289
|
-
handler reads the file first. Writes use `sw.db.server`, which needs no user
|
|
290
|
-
authority and lasts the whole job, and which does not apply the tables'
|
|
291
|
-
declared access: every write names `user_id`, taken from the verified session
|
|
292
|
-
when the job was started. Add one endpoint and one handler beside the files
|
|
293
|
-
above; the page keeps reading the result from `GET /api/imports?file_id=`.
|
|
294
|
-
|
|
295
|
-
```ts
|
|
296
|
-
// api/import-jobs.ts — POST { file_id } queues the import of one uploaded CSV
|
|
297
|
-
export default async function importJobs(request: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
298
|
-
if (request.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
299
|
-
const user = await sw.auth.fromRequest(request);
|
|
300
|
-
if (!user) return Response.json({ error: 'Sign in.' }, { status: 401 });
|
|
301
|
-
const input = (await request.json().catch(() => null)) as { file_id?: unknown } | null;
|
|
302
|
-
const fileId = input?.file_id;
|
|
303
|
-
if (typeof fileId !== 'string' || !/^[A-Za-z0-9-]{8,64}$/.test(fileId)) {
|
|
304
|
-
return Response.json({ error: 'Send the file_id from the upload result.' }, { status: 400 });
|
|
305
|
-
}
|
|
306
|
-
const allowance = await sw.rateLimit.check(`csv-import:${user.id}`, 20, 3600);
|
|
307
|
-
if (!allowance.allowed) return Response.json({ error: 'Try again later.' }, { status: 429 });
|
|
308
|
-
try {
|
|
309
|
-
// Runs as this user, reading only the first line: another user's upload is not found.
|
|
310
|
-
await sw.fs.read(`/csv-uploads/${fileId}/upload.csv`, { lines: [1, 1] });
|
|
311
|
-
} catch (error) {
|
|
312
|
-
if (error instanceof Error && 'status' in error && error.status === 404) {
|
|
313
|
-
return Response.json({ error: 'No such upload for this account.' }, { status: 404 });
|
|
314
|
-
}
|
|
315
|
-
throw error;
|
|
316
|
-
}
|
|
317
|
-
await sw.db.insert('imports', { file_id: fileId }, { onConflict: 'ignore' });
|
|
318
|
-
// One job per user and file: a repeated POST returns the same job.
|
|
319
|
-
const job = await sw.jobs.create({
|
|
320
|
-
handler: '/api/jobs/import-csv',
|
|
321
|
-
idempotency_key: `csv-import:${user.id}:${fileId}`,
|
|
322
|
-
payload: { file_id: fileId, user_id: user.id },
|
|
323
|
-
timeout_seconds: 900,
|
|
324
|
-
});
|
|
325
|
-
return Response.json({ job_id: job.job_id, file_id: fileId }, { status: 202 });
|
|
326
|
-
}
|
|
327
|
-
```
|
|
328
|
-
|
|
329
|
-
```ts
|
|
330
|
-
// api/jobs/import-csv.ts — runs only when the platform delivers the job
|
|
331
|
-
import { type ContactRow, CsvError, contactsFromCsv } from '../_lib/csv';
|
|
332
|
-
|
|
333
|
-
const MAX_ROWS = 50_000; // this example's cap: time a full import on your deployed app before raising it
|
|
334
|
-
const BATCH = 100; // sw.db.server.tx takes 1–100 writes
|
|
335
|
-
|
|
336
|
-
export default async function importCsvJob(request: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
337
|
-
if (!(await sw.jobs.verifyInvocation(request))) return Response.json({ error: 'forbidden' }, { status: 403 });
|
|
338
|
-
const payload = (await request.json().catch(() => null)) as { file_id?: unknown; user_id?: unknown } | null;
|
|
339
|
-
const fileId = payload?.file_id;
|
|
340
|
-
const userId = payload?.user_id;
|
|
341
|
-
if (typeof fileId !== 'string' || !fileId || typeof userId !== 'string' || !userId) {
|
|
342
|
-
return Response.json({ error: 'Invalid payload.' }, { status: 400 });
|
|
343
|
-
}
|
|
344
|
-
const finish = async (status: 'complete' | 'failed', rowsStored: number, error: string | null) => {
|
|
345
|
-
await sw.db.server.update('imports', { where: { file_id: fileId, user_id: userId }, set: { status, rows_stored: rowsStored, error } });
|
|
346
|
-
return Response.json({ status, rows_stored: rowsStored, error });
|
|
347
|
-
};
|
|
348
|
-
|
|
349
|
-
let contacts: ContactRow[];
|
|
350
|
-
try {
|
|
351
|
-
// First, while the starting user's file authority is fresh.
|
|
352
|
-
const file = await sw.fs.read(`/csv-uploads/${fileId}/upload.csv`);
|
|
353
|
-
contacts = contactsFromCsv(new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer()), MAX_ROWS);
|
|
354
|
-
} catch (error) {
|
|
355
|
-
if (error instanceof CsvError) return finish('failed', 0, error.message);
|
|
356
|
-
if (error instanceof TypeError) return finish('failed', 0, 'Save the file as CSV UTF-8 and upload it again.');
|
|
357
|
-
throw error;
|
|
358
|
-
}
|
|
359
|
-
// Server authority, scoped by hand to the user who started the job.
|
|
360
|
-
for (let start = 0; start < contacts.length; start += BATCH) {
|
|
361
|
-
await sw.db.server.tx(contacts.slice(start, start + BATCH).map((contact) => ({
|
|
362
|
-
op: 'insert' as const,
|
|
363
|
-
table: 'contacts',
|
|
364
|
-
values: { ...contact, import_id: fileId, user_id: userId },
|
|
365
|
-
options: { onConflict: 'update' as const },
|
|
366
|
-
})));
|
|
367
|
-
}
|
|
368
|
-
return finish('complete', contacts.length, null);
|
|
369
|
-
}
|
|
370
|
-
```
|
|
371
|
-
|
|
372
|
-
To use it, raise `limits.maxSize` on `csv_uploads` within your plan's
|
|
373
|
-
per-file ceiling (`limits`), and have the page post the upload's `file_id`
|
|
374
|
-
to `/api/import-jobs` instead of `/api/imports`, then call
|
|
375
|
-
`readCsvImport(file_id)` every few seconds until the status is no longer
|
|
376
|
-
`running`. A bad file ends the import `failed` with the same messages as
|
|
377
|
-
above and stores nothing; that is the import's answer, so the handler returns
|
|
378
|
-
200 and the job is not retried. An error the handler throws is retried within
|
|
379
|
-
the job's 900-second deadline, and every retry is safe: `unique: [['user_id',
|
|
380
|
-
'email']]` with `onConflict: 'update'` turns a repeated batch into the same
|
|
381
|
-
contacts. An import still `running` after that deadline did not finish (for
|
|
382
|
-
example `JOB_TIMEOUT`): the batches that landed are kept, and uploading the
|
|
383
|
-
file again, which gets a new file id, finishes it without duplicates. Job
|
|
384
|
-
retries, timeouts and status: `docs({ topic: 'sw.jobs' })`.
|
|
385
|
-
|
|
386
|
-
To load a dataset once as the developer, not from the app,
|
|
387
|
-
use the `db_import_csv` tool with a CSV already in your project files. If a batch
|
|
388
|
-
fails, the error gives the number of rows already imported and the CSV line to
|
|
389
|
-
resume from. Keep the header and import only the remaining rows. If the error says
|
|
390
|
-
a write could not be confirmed, check the table before trying again.
|
|
@@ -1,127 +0,0 @@
|
|
|
1
|
-
# Recipe — Fixed-price catalog checkout
|
|
2
|
-
|
|
3
|
-
Start Stripe checkout for an always-available catalog. This small recipe
|
|
4
|
-
intentionally stops at checkout creation: it does not fulfill an order, send a
|
|
5
|
-
confirmation, or reserve and decrement limited inventory.
|
|
6
|
-
|
|
7
|
-
This example intentionally keeps catalog rows private and returns only a checkout
|
|
8
|
-
URL. For a browsable catalog, declare publicRead with selected active rows/fields
|
|
9
|
-
and use the generated client. Anonymous results can be cached for up to
|
|
10
|
-
120 seconds. For a catalog that must be fresh, use a page handler with
|
|
11
|
-
`sw.db.server.from`, an active-products filter, selected public fields and
|
|
12
|
-
`Cache-Control: no-store`.
|
|
13
|
-
|
|
14
|
-
## Database schema
|
|
15
|
-
|
|
16
|
-
```ts
|
|
17
|
-
// db/schema.ts
|
|
18
|
-
import { schema, table, id, text, integer, boolean, timestamp, serverOnly } from 'somewhere/db';
|
|
19
|
-
|
|
20
|
-
export default schema({
|
|
21
|
-
products: table({
|
|
22
|
-
id: id(),
|
|
23
|
-
name: text(),
|
|
24
|
-
description: text({ nullable: true }),
|
|
25
|
-
price_cents: integer(),
|
|
26
|
-
image_url: text({ nullable: true }),
|
|
27
|
-
active: boolean({ default: true }),
|
|
28
|
-
created_at: timestamp({ default: 'now' }),
|
|
29
|
-
}, { scope: serverOnly() }),
|
|
30
|
-
});
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
## Function: api/checkout.ts — create checkout
|
|
34
|
-
|
|
35
|
-
```ts
|
|
36
|
-
// api/checkout.ts
|
|
37
|
-
type CartItem = { product_id: string; quantity: number };
|
|
38
|
-
|
|
39
|
-
function isCartItem(item: unknown): item is CartItem {
|
|
40
|
-
if (typeof item !== 'object' || item === null) return false;
|
|
41
|
-
return 'product_id' in item && typeof item.product_id === 'string'
|
|
42
|
-
&& 'quantity' in item && typeof item.quantity === 'number'
|
|
43
|
-
&& Number.isInteger(item.quantity) && item.quantity >= 1 && item.quantity <= 99;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export default async function checkout(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
47
|
-
if (req.method !== 'POST') {
|
|
48
|
-
return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
49
|
-
}
|
|
50
|
-
const body: unknown = await req.json().catch(() => null);
|
|
51
|
-
if (typeof body !== 'object' || body === null || !('items' in body)
|
|
52
|
-
|| !Array.isArray(body.items) || body.items.length < 1 || body.items.length > 20
|
|
53
|
-
|| !body.items.every(isCartItem) || !('customer_email' in body)
|
|
54
|
-
|| typeof body.customer_email !== 'string') {
|
|
55
|
-
return Response.json({ error: 'invalid_cart' }, { status: 400 });
|
|
56
|
-
}
|
|
57
|
-
const { items, customer_email } = body;
|
|
58
|
-
const ids = items.map(item => item.product_id);
|
|
59
|
-
if (new Set(ids).size !== ids.length) {
|
|
60
|
-
return Response.json({ error: 'duplicate_product' }, { status: 400 });
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// Public endpoint: cap checkout sessions per caller.
|
|
64
|
-
const ip = req.headers.get('cf-connecting-ip') || 'unknown';
|
|
65
|
-
const allowance = await sw.rateLimit.check(`checkout:${ip}`, 10, 600);
|
|
66
|
-
if (!allowance.allowed) {
|
|
67
|
-
return Response.json({ error: 'too_many_checkouts', retry_at: allowance.reset }, { status: 429 });
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
// Read active products and their current prices from the server-only catalog.
|
|
71
|
-
const { data: products } = await sw.db.server.from('products', {
|
|
72
|
-
columns: ['id', 'name', 'price_cents'],
|
|
73
|
-
where: { id: { in: ids }, active: true },
|
|
74
|
-
limit: 20,
|
|
75
|
-
});
|
|
76
|
-
const byId = new Map(products.map(product => [product.id, product]));
|
|
77
|
-
const lineItems: SomewherePaymentsLineItem[] = [];
|
|
78
|
-
for (const item of items) {
|
|
79
|
-
const product = byId.get(item.product_id);
|
|
80
|
-
if (!product) return Response.json({ error: 'product_unavailable' }, { status: 400 });
|
|
81
|
-
lineItems.push({ amount: product.price_cents, currency: 'usd', name: product.name, quantity: item.quantity });
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
const result = await sw.payments.checkout({
|
|
85
|
-
mode: 'payment',
|
|
86
|
-
line_items: lineItems,
|
|
87
|
-
success_url: new URL('/thanks', req.url).toString(),
|
|
88
|
-
cancel_url: new URL('/cart', req.url).toString(),
|
|
89
|
-
customer_email,
|
|
90
|
-
});
|
|
91
|
-
if (!result.url) return Response.json({ error: 'checkout_unavailable' }, { status: 502 });
|
|
92
|
-
return Response.json({ status: 'pending_payment', checkout_url: result.url });
|
|
93
|
-
}
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
## Notes
|
|
97
|
-
|
|
98
|
-
- **Inventory.** This recipe is for products that remain available. A limited-
|
|
99
|
-
stock store needs a reservation design that handles expiry, payment failure,
|
|
100
|
-
and compensation; do not add a guarded decrement to this flow and call it an
|
|
101
|
-
inventory guarantee.
|
|
102
|
-
- **Payment mode.** To try the handler before connecting a payment account,
|
|
103
|
-
set `env: 'dev'` in the `sw.payments.checkout` options. A production
|
|
104
|
-
function defaults to live payments and requires a connected account. A
|
|
105
|
-
preview checkout uses test payments, but its
|
|
106
|
-
payment callbacks are withheld from your project webhook; test fulfillment in
|
|
107
|
-
development.
|
|
108
|
-
- **Fulfillment.** This example creates checkout. When it settles, your
|
|
109
|
-
project webhook receives `payment.completed` with its
|
|
110
|
-
`checkout_session_id`, amount and currency
|
|
111
|
-
([Payment events](/docs/payments#webhook-events-what-each-flow-actually-emits));
|
|
112
|
-
verify the signature and match the session, amount, currency and mode to
|
|
113
|
-
your saved order. Save `session_id`, `amount_total_cents` and
|
|
114
|
-
`stripe_mode` from the checkout response, and the currency your server
|
|
115
|
-
created it with. Test and live events
|
|
116
|
-
share the project webhook. Apply order and stock changes in the same
|
|
117
|
-
transaction as a unique fulfillment record for the checkout session;
|
|
118
|
-
duplicate deliveries then leave them unchanged. On duplicates too, call
|
|
119
|
-
`sw.jobs.create` for confirmation email with the same
|
|
120
|
-
`idempotency_key`; it returns the existing job or admits the missing one.
|
|
121
|
-
Keep fulfillment out of this checkout handler.
|
|
122
|
-
- **Cart persistence.** Store the cart in the browser. For logged-in carts,
|
|
123
|
-
gate behind `sw.auth.requireUser` and use a separately declared owner table.
|
|
124
|
-
- **Catalog discovery.** Create a product index once with
|
|
125
|
-
`search_index_create`, then `search_upsert` whenever a product changes.
|
|
126
|
-
|
|
127
|
-
Related topics: `payments`, `sw.billing`, `sw.db`, `search`.
|