Getting started? Read https://somewhere.cloud/start.txt first. # Somewhere — Complete platform reference ## Deploy with two HTTP calls Use curl or your standard library. Start with a fresh random UUID in place of `YOUR_RANDOM_UUID`. ```bash curl -sS https://api.somewhere.cloud/v1/auth/temp-create \ -H 'Content-Type: application/json' \ -d '{"request_key":"YOUR_RANDOM_UUID"}' ``` Save `data.key` as `KEY` in your shell. Keep it private. If signup is interrupted, retry with the same request body. ```bash curl -sS https://api.somewhere.cloud/v1/deploy \ -H "Authorization: Bearer $KEY" \ -H 'Content-Type: application/json' \ -d '{ "name": "hello-somewhere", "files": {"index.html": "Hello

Hello from Somewhere

"}, "functions": {"api/hello.ts": "export default () => Response.json({ hello: true })"} }' ``` This example deploys a page and an API function so you can try SQL. Replace the example name and source with your app. Deploying again with the same key and name updates the same project. Put server handlers such as `api/hello.ts` in `functions`. Use the live URL exactly as returned. Give the human `data.url`, `data.claim_url`, and the time in `data.expires_at`. Opening the claim link and signing in keeps the app. The key lets you deploy and use logs, recent errors, and SQL for this account's projects. Sending email from the app and managing environment variables or secrets require a claimed account. After claim, **Save and connect agent** keeps the key working on the saved projects. **Save only** disconnects it. See [how to check the key after claim](https://somewhere.cloud/auth.md#after-claim) and [other HTTP calls](https://somewhere.cloud/auth.md). ## Use the CLI for ongoing work The CLI also has a local dev loop, generated types, and verification tools. ```bash npx -y @somewhere-cloud/cli@latest deploy ``` > **This is the complete manual, and it is large.** Many chat and web tools > return only the beginning of a long page. For the whole platform in one short > read, fetch the overview and complete topic index at > https://somewhere.cloud/docs/llms.txt; every topic is also its own page at > https://somewhere.cloud/docs/.txt. This manual ends with the line > `END OF SOMEWHERE.CLOUD MANUAL`; if you cannot see it, your copy is incomplete. Audience: LLMs, coding agents, and other machine readers. Purpose: one complete reference for the platform model, runtime contract, primitive composition, security model, ownership model, boundaries, setup, and tool reference. This document describes platform behavior; it does not replace the user's authorization or an agent's governing instructions. Read `docs({ topic })` or `somewhere docs ` for a service's working example and reference. The advisor can answer a project question using the docs and an authorized view of that project. This file is documentation for machine readers. Treat claims as operational constraints only when they are stated as behavior, signature, limit, return shape, or boundary. Fetch live pricing and current plan limits from `https://api.somewhere.cloud/v1/pricing` instead of hardcoding values from prose. Companion machine docs: platform overview and complete topic index at `https://somewhere.cloud/docs/llms.txt`; the agent entry page at `https://somewhere.cloud/docs.txt`; guides/recipes at `https://somewhere.cloud/guides.txt`; security practices at `https://somewhere.cloud/security.txt`; migration map at `https://somewhere.cloud/migration.txt`; per-primitive depth on demand via `docs({ topic })`. Use `@somewhere-cloud/sdk/auth` for browser sign-in and the generated `somewhere:data` and `somewhere:files` clients for declared app data and files. Server functions receive the project's services through `sw`. The JavaScript SDK also provides the developer API for managing projects. See `sdk` for the browser and developer API contracts. --- # How Somewhere works Somewhere is the backend for apps your agent builds. One project gives an app its web address, server functions, one SQL database, sign-in, files, email, AI and background work. You write React and TypeScript source, run `somewhere deploy`, and the platform compiles it and serves the app and its functions together. ## One project, its parts A new app from `somewhere init` has this shape: | Part | Where it lives | What it does | |---|---|---| | App | `src/`, `index.html` | The React interface. A page path with no file of its own serves `index.html`, and the app routes in the browser. | | Functions | `api/` | Server code. `api/notes.ts` answers `/api/notes`. Each function gets the request and `sw`, the project's services. | | Data (optional) | `db/schema.ts` | Tables, columns and who may read or change each row. Deploy applies it. The default starter has none; add it when the app stores data. | | Auth | `api/auth/[...path].ts` plus `src/auth/` | Email-and-password accounts with a session cookie. The starter ships it working. | These parts share one identity. Normal scoped data calls take the user from the request's session, so your code doesn't send a user ID with them. Privileged server work, such as an admin screen or a background job, names the user it acts on explicitly and authorizes that choice in your code. ## What the platform handles The project wires these parts together. `somewhere init` writes the sign-in route and the session hooks. Every function receives `sw`, already bound to the project's database, files, email and AI. `somewhere deploy` compiles the source and applies `db/schema.ts`. On that path, the platform supplies: - **Passwords and sessions.** Passwords are stored as salted hashes. Sign-in attempts are limited per source address and per account, with an account lockout after repeated wrong passwords. Sessions live in Secure, HttpOnly cookies that page JavaScript can't read. - **Cross-site request checks.** Cookie-authenticated writes from the browser must come from your app's own origin. A normal `fetch` from your page already sends it. - **Data access.** A table is closed to the browser until its declaration grants operations and columns. On an `owner()` table, normal operations act for the signed-in user. Rows get their owner from the verified session, never from browser input. - **Configuration and secrets.** New environment values are private by default and encrypted at rest. Once live configuration is in place, a changed key reaches new requests within 60 seconds, with no deploy. - **Outbound requests.** `fetch` calls from functions block private and metadata addresses, and redirects are checked again. - **Built-in services.** The database, auth, files, AI and transactional email are reached through `sw` without provider keys. Email has a test inbox for `*.test.somewhere.site` addresses. - **Deploys.** Raw source compiles on the platform, schema changes apply, and `somewhere verify` checks the live app in a real browser. ## What you decide - **Who may run a privileged action.** Check the caller in the function before it changes anything. Server-authority database calls skip row permissions on purpose, so they need your check. - **What's public.** Public reads, shared tables and public configuration values are explicit choices in your source. - **Effects that must not repeat.** A caller or a job can retry a request. Give actions such as sending email or charging a card an idempotency key, or make them safe to run twice. ## Design choices - **Data model:** one SQL database per project, scoped per user by declaration. Need Postgres for an existing dataset? Attach it. → `database-engine`, `postgres` - **Declared data:** schema and access rules live in one file that ships with the source, so the app, its tools and the platform read the same contract. → `declared-data` - **Secure by default:** scoped APIs carry the normal protections, and you add authorization to the privileged actions. → `security-model` - **Handled for you:** the full list of setup and operations the platform performs. → `handled-for-you` - **You can leave:** download a full database dump, your source and your users' accounts. → `portability` ## Reading these docs A primitive topic opens with a summary that lists its named sections. Ask for one section, or for the full reference, when you need more depth. A recipe returns the whole job on the first call. An explicit summary or section request still works for recipes too. ```bash somewhere docs sw.auth # first view somewhere docs sw.auth --section password-reset # one section ``` From MCP, use `docs({ topic: 'sw.auth', section: 'password-reset' })`. The full topic index lists every primitive, recipe and reference page with a line on when to load it. Read next: **Start an app**, then **Functions**, **Env vars and secrets**, **Data** and **Auth**. For questions about your own project, `somewhere advisor ""` answers with that project in view. --- # 1. Design premise If a backend were specified from zero for an application with end users, the records describing one user would not be split across unrelated systems. Identity, application data, payment state, email, files, notifications, and background work all describe the same actor and the same project. somewhere.cloud is specified as one backend namespace over those primitives. Consequences of that premise: - End-user identity and the application database share the same project boundary. - A signup creates a user record that application code can query and join. - Payment state is written back to the app-user record and project payment ledger by platform webhook handling. - Files can be scoped to the user and project that wrote them. - Email can be sent from the same runtime that knows the user and their payment/account state. - Background jobs, queues, cron handlers, live-view invalidations, push notifications, and analytics are bound to the same project identity. - Ownership checks can be enforced at the platform boundary instead of relying only on application-written predicates. - Deploy analysis can read the actual source using platform-specific knowledge of `sw.*` semantics. The breadth is intentional. The primitive set is the set of backend capabilities that normally need to coordinate around project identity, user identity, authorization, data ownership, delivery state, and billing state. The coordination is part of the platform surface, not an external integration project. --- # 2. Runtime mental model ## 2.1 Function signature A JSON route in api/ is export default sw.endpoint({ auth, handler }) with auth set explicitly. TypeScript infers the handler inputs and sw context. auth: 'none' marks a deliberately public route. ```ts export default sw.endpoint({ auth: 'none', handler: async () => ({ ok: true }) }); ``` `sw` is also the project-scoped platform binding passed to the handler. Return a JSON value and the endpoint wrapper sends the response. Database row operations use these fields: ```js r.data // array of row objects (empty array on writes) r.count // number of rows in r.data r.changes // rows affected by INSERT, UPDATE, or DELETE ``` Do not use `.rows` or `.results` for database return values. Composed calls (`sw.db.from`, `insert`, `update`, `remove`, `count`) resolve to a `Result` — `{ data, error }`, with `count`/`changes` on row operations — and `sw.db.count`'s number is `.data`. On the server, refusals and failures throw with a `code`; a result that is returned carries `error: null`. ## 2.2 Direct HTTP handlers `sw.endpoint({ auth, body, rateLimit, handler })` can perform auth, body validation, rate limiting, CORS handling, and error formatting before invoking `handler`. The bare `export default async function(req, sw)` form is also supported. It receives a Web `Request` and returns a Web `Response`, useful for streaming or access to exact webhook bytes. ## 2.3 One binding The `sw` binding includes these primitive groups: - `sw.db` — relational database, migrations, batches, table metadata, scoped queries, export, and change webhooks. - `sw.auth` — end-user signup, login, session validation, refresh, password reset, email verification, magic links, OAuth, visitor sessions, user admin operations and lifecycle webhooks. - `sw.fs` — object/file storage, versioning, signed URLs, uploads, search, diffs, moves, copies, restores, and public URLs. - `sw.email` — outbound email send and delivery event visibility. - `sw.ai` — chat, embeddings, transcription, TTS, image generation, moderation, tool loops, conversation history, structured output, model catalog, and per-user memory. - `sw.agent` — canonical inline and durable multi-step model/tool execution, checkpoints, status, and cancellation. - `sw.payments` — checkout, onboarding, plan tracking, refunds, cancellations, transactions, billing portal, and event ledger. - `sw.billing` — define an app's plans and the features each grants, then gate by a stable feature name (`await sw.billing.has(feature)` on the server; `` for presentation); the plan a user is on is set by the payments webhook automatically. - `sw.jobs`, `sw.queue`, `sw.cron` — durable background jobs, fire-and-forget work, and scheduled functions. - `sw.push`, `sw.notifications` — web-push delivery to already-registered subscriptions and notification fan-out helpers. Live updates to a browser come from `sw.rooms.live` declared lists; there is no caller-named channel API in a function. - `sw.search` — semantic and full-text search surfaces. - `sw.render`, `sw.web`, `sw.image` — screenshots, PDFs, public web reading, and image transforms. - `sw.rateLimit`, `sw.analytics`, `sw.logs`, `sw.env`, `sw.tasks` — rate-limit counters, event analytics, runtime logs, project environment values (server-only by default; explicitly public browser-prefixed values compile into browser code), and per-project ticket/task state. ## 2.4 Internal and external access Inside a deployed function, use `sw.*`. The binding is already scoped to the project. No developer key is required inside runtime code. Outside a deployed function, use one of the external surfaces: - MCP tools at `https://mcp.somewhere.cloud/mcp`. - CLI commands through the `somewhere` binary. - REST API paths under `/v1/*` with an appropriate developer key or app-user JWT. Do not call `https://api.somewhere.cloud/v1/*` from inside a deployed function when an equivalent `sw.*` primitive exists. Runtime code should use the binding. ## 2.5 Deploy input Deploy raw source. Valid inputs include `.ts`, `.tsx`, `.js`, `.jsx`, `.html`, `.css`, static assets, and function files under `api/` or other documented function paths. The platform compiles your source at deploy time. Prebuilt output still deploys, with a warning, and loses source round-trips (export, find/replace patches, design tokens, the visual editor); `somewhere deploy --prebuilt`, the project setting, or `allow_bundled: true` accepts that trade-off and drops the warning. ## 2.6 Runtime transparency and networking Functions run in a Workers-compatible Web runtime, not a Node server process. The compiler passes `node:*` standard-library compatibility imports and `cloudflare:workers`; common `node:*` modules include `crypto`, `buffer`, `events`, `path`, `stream`, `string_decoder`, `util`, and `url`. Standard Web APIs include Request/Response/Headers, URL/URLSearchParams, fetch, WebSocket, crypto, text encoders, streams, Blob/FormData, timers, and AbortController. Plain `fetch()` reaches public HTTP and HTTPS hosts; the runtime refuses a destination in a private, loopback, link-local or metadata range, as written (`SSRF_BLOCKED`) or as resolved (`DNS_LOOKUP_FAILED`), and re-checks each redirect it follows. Behind it, the platform's outbound guard refuses a request that reaches it with a literal blocked target (non-public address or internal hostname, embedded credentials, non-HTTP scheme, port other than 80, 443 or 1024 and above) with a 403 before it leaves. `sw.fetch()` adds resolved-address checks before connecting, redirect validation, bounded timeouts/redirects, structured results, logging, and safe idempotent retries; resolution is checked at request time, not continuously. Raw TCP sockets and listening ports are not part of the customer runtime contract; use HTTPS or an outbound WebSocket. ## 2.7 Verify before deploy Use local `somewhere typecheck` for TypeScript; `somewhere deploy-check` for the real server-side compiler; `somewhere run ``` Put the preview image at `public/og.png` and reference it by its full URL: link-preview services don't resolve relative image paths. A 1200×630 image fits the large preview card. ## 2. A different preview for a shareable page Link-preview services read the HTML without running your JavaScript, so every route of a single-page app shares the tags in `index.html`. For a page that people share on its own, such as `/pricing`, ship an HTML file at `pricing/index.html` with its own head and the same app script: ```html Pricing — Notes
``` The deploy compiles every HTML page's app script, so `/pricing` runs the same app and your router renders the pricing route. The generated sitemap lists `/pricing` too. For routes that only exist inside the client router, set the tab title as the route renders: ```tsx // src/pages/PricingPage.tsx import { useEffect } from 'react'; export function PricingPage() { useEffect(() => { document.title = 'Pricing — Notes'; }, []); return

Pricing

; } ``` ## 3. Sitemap and robots The generated sitemap lists each deployed HTML page with its upload date. Routes that exist only inside the client router aren't deployed pages, so it can't list them: give them their own HTML file (step 2) or ship your own `public/sitemap.xml`. Shipping `public/robots.txt` or `public/sitemap.xml` replaces only that generated file. Your rules are served as written, including `noindex` or `Disallow` rules. ### Change notification (IndexNow) After a release is live, the platform tells the IndexNow search engines (Bing and the others that share IndexNow submissions) which public pages are new or changed since the previous live release. Nothing needs to be configured. - **Which pages:** deployed HTML pages, by the same rule as the generated sitemap. A page counts when its file is new or its bytes changed; at most 1,000 URLs are sent per release. When the previous release can't be read, every public page is sent. - **Which hosts:** one submission per serving host, meaning the project's `.somewhere.site` address and each attached custom domain. The dev slot's address is never sent. - **Ownership key:** each serving host answers `/.txt` with the project's IndexNow key, which the engines fetch to confirm the host. The key is derived from the project and grants no access to it. A file you deploy at that path is served instead. - **Nothing is sent** for temporary (unclaimed) or test projects, for draft, frozen, archived or deleting projects, for a release that a newer release or a rollback has already replaced, when `robots.txt` disallows every crawler (`User-agent: *` with `Disallow: /`), or when no public page changed. - **Errors never block a deploy.** An engine that is slow or refuses the submission changes nothing about the release; the attempt is logged. A submission asks the engines to recrawl those URLs. It is not indexing: whether and when a page appears in results is up to each engine. Google does not use IndexNow; Google Search Console handles sitemap submission for Google. ## 4. Check the live release After a deploy, read what the active release ships: ```text project_seo_check({ project_id: "my-app" }) ``` It inspects the deployed `index.html`, `robots.txt` and `sitemap.xml` of the active release, without fetching the site. Each item has a `status`: - `automatic`: the release uses the platform fallback configuration. - `app-supplied`: the release contains your file. - `needs-attention`: something to fix, such as a missing title or description, with a `suggestion`. - `unknown`: the check couldn't inspect this item. Open the public URLs to check the served pages and files. Verify ownership and submit the sitemap in Search Console. ## 5. Server-rendered pages and redirects For database-backed articles, return HTML from a root `[...path].ts` handler. The `functions` topic's server-rendered pages recipe shows a public article route alongside a React editor. Return each article's title, description, canonical URL and body in that HTML; link previews do not run browser JavaScript. A page handler can also return `Response.redirect(url, 301)`. A client-only React route still renders in the browser. Use the static HTML approach above for fixed pages, or the HTML handler for dynamic content. Generated sitemap and IndexNow discovery cover deployed HTML files; they do not enumerate database-backed article URLs. Supply a sitemap containing those public URLs and check its served response alongside the articles. ## Deployed SEO metadata `project_seo_check({ project_id })` and `GET /v1/projects/:id/seo` return the same authenticated, read-only inspection. The response identifies `release_id`, `version`, `source_manifest_hash` and `compiled_artifact_digest` for the exact active release. It inspects only `index.html`, `robots.txt` and `sitemap.xml`; missing, changed or unverifiable release evidence is unavailable, not a pass. Each item carries `status` (`automatic`, `app-supplied`, `needs-attention`, `unknown`), `provenance`, bounded `values`, a `value_count`, `values_truncated`, a `note` and optional advisory `suggestion`. At most five values of 512 characters are returned per item; duplicate detection retains the full count. Automatic means a platform fallback is configured because an app-supplied file is absent; read the public URL to confirm a request serves it. App-supplied robots rules and metadata, including intentional noindex or Disallow rules, are preserved. No source is edited. Inspecting a file larger than 256 KiB returns unknown. Title, description, canonical and Open Graph values come from the deployed homepage HTML. Static body text there reflects the file only: check the rendered page for what is visible; crawlability stays unverified. `coverage.public_response` is `unobserved`: no HTTP fetch, function execution, authentication check, JavaScript rendering or crawl occurs. Client routes, indexing and ranking remain unknown. Generated sitemaps include static HTML paths only, not routes hidden behind a client router. Search Console verification and submission are separate from this inspection. ## Automatic sitemap and robots files If a project does not ship its own `sitemap.xml` or `robots.txt`, the platform serves both automatically. The sitemap lists deployed HTML pages and uses their upload times for ``; robots points crawlers at that sitemap. Shipping either file overrides only that generated fallback. Routes that exist only inside a client-side router are not separate deployed HTML pages, so the generated sitemap cannot discover them. Ship crawlable HTML for those routes or provide your own `sitemap.xml`. ## Going further | Need | Where | |---|---| | A custom domain for the canonical URL | [Custom Domains](https://somewhere.cloud/docs/domains.txt) | | How the check reports each field | `recipe-seo` → `deployed-seo-metadata` | | The generated sitemap and robots files | `recipe-seo` → `automatic-sitemap-and-robots-files` | | Visitor counts and top pages | `analytics` → `page-views` | --- ## Topic: Recipe — CSV import (recipe-csv-import) Page: https://somewhere.cloud/docs/recipe-csv-import.txt ## Import contacts from a CSV Upload a CSV as a signed-in user and import contacts in one request. A repeat import updates that user's contacts by email. ### 1. db/schema.ts Choose `unique: true` only for a permanent uniqueness rule. Deploy refuses to remove the constraint later. ```ts // db/schema.ts import { files, id, integer, owner, schema, table, text, timestamp } from 'somewhere/db'; export default schema({ imports: table( { id: id(), file_id: text({ unique: true }), status: text({ default: 'running' }), rows_stored: integer({ default: 0 }), error: text({ nullable: true }), created_at: timestamp({ default: 'now' }), }, { scope: owner(), client: { read: ['id', 'file_id', 'status', 'rows_stored', 'error', 'created_at'] } }, ), contacts: table( { id: id(), email: text(), name: text(), import_id: text() }, { scope: owner(), unique: [['user_id', 'email']], indexes: [['import_id']], client: { read: ['id', 'name', 'email'] } }, ), }, { files: { csv_uploads: files({ path: '/csv-uploads', scope: owner(), client: { read: true, upload: true }, limits: { maxSize: '2MB', types: ['text/csv'] }, }), }, }); ``` `owner()` scopes uploads and rows to the signed-in user. The fixed `upload.csv` name lets the endpoint find the upload by ID. The composite unique key gives each user one contact per email address. ### 2. The CSV reader ```ts // api/_lib/csv.ts — comma-separated text: quoted fields, "" escapes, commas and line breaks inside quotes, LF or CRLF export class CsvError extends Error {} /** maxRecords counts the header row. */ export function parseCsv(text: string, maxRecords: number): string[][] { const records: string[][] = []; let record: string[] = []; let field = ''; let state: 'start' | 'plain' | 'quoted' | 'closed' = 'start'; const endField = () => { record.push(field); field = ''; state = 'start'; }; const endRecord = () => { endField(); if (record.length > 1 || record[0] !== '') records.push(record); // skip blank lines if (records.length > maxRecords) throw new CsvError(`The file has more than ${maxRecords - 1} rows below the header.`); record = []; }; for (let i = text.charCodeAt(0) === 0xfeff ? 1 : 0; i < text.length; i++) { const ch = text[i]; if (state === 'quoted') { if (ch !== '"') field += ch; else if (text[i + 1] === '"') { field += '"'; i++; } else state = 'closed'; } else if (ch === ',') endField(); else if (ch === '\n') endRecord(); else if (ch === '\r' && text[i + 1] === '\n') { endRecord(); i++; } else if (ch === '"' && state === 'start') state = 'quoted'; else if (ch === '"' || ch === '\r' || state === 'closed') throw new CsvError(`Row ${records.length + 1} is not valid CSV.`); else { field += ch; state = 'plain'; } } if (state === 'quoted') throw new CsvError('A quoted field is not closed.'); if (state !== 'start' || field !== '' || record.length > 0) endRecord(); return records; } export type ContactRow = { name: string; email: string }; /** Checks every row before any is written; a CsvError names the row to fix. */ export function contactsFromCsv(text: string, maxRows: number): ContactRow[] { const [header, ...rows] = parseCsv(text, maxRows + 1); if (header?.map((h) => h.trim().toLowerCase()).join(',') !== 'name,email') throw new CsvError('The first row must be: name,email'); return rows.map((row, index) => { const [name = '', email = ''] = row.map((value) => value.trim()); if (row.length !== 2 || !name || name.length > 200 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { throw new CsvError(`Row ${index + 2}: expected a name and an email address.`); } return { name, email: email.toLowerCase() }; }); } ``` ### 3. Import the file and report it ```ts // api/imports.ts — POST { file_id } imports one uploaded CSV; GET ?file_id= reports it import { type ContactRow, CsvError, contactsFromCsv } from './_lib/csv'; const MAX_ROWS = 2000; // this example's cap: one request reads, checks and writes the whole file const BATCH = 100; // sw.db.tx takes 1–100 writes export default sw.endpoint({ auth: 'required', handler: async ({ request, user }, sw) => { if (request.method === 'GET') { const fileId = new URL(request.url).searchParams.get('file_id'); if (!fileId) return Response.json({ error: 'Pass ?file_id=.' }, { status: 400 }); // Runs as this user: another user's import is not found. const { data: found } = await sw.db.from('imports', { where: { file_id: fileId }, limit: 1 }); const row = found[0]; if (!row) return Response.json({ error: 'No such import for this account.' }, { status: 404 }); return Response.json({ status: row.status, rows_stored: Number(row.rows_stored), error: row.error }); } if (request.method !== 'POST') return new Response('Use GET or POST.', { status: 405, headers: { Allow: 'GET, POST' } }); const input = (await request.json().catch(() => null)) as { file_id?: unknown } | null; const fileId = input?.file_id; if (typeof fileId !== 'string' || !/^[A-Za-z0-9-]{8,64}$/.test(fileId)) { return Response.json({ error: 'Send the file_id from the upload result.' }, { status: 400 }); } // 20 per hour per user is this example's choice. const allowance = await sw.rateLimit.check(`csv-import:${user.id}`, 20, 3600); if (!allowance.allowed) return Response.json({ error: 'Try again later.' }, { status: 429 }); let text: string; try { // Runs as this user: another user's upload is not found. const file = await sw.fs.read(`/csv-uploads/${fileId}/upload.csv`); text = new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer()); } catch (error) { if (error instanceof Error && 'status' in error && error.status === 404) { return Response.json({ error: 'No such upload for this account.' }, { status: 404 }); } if (error instanceof TypeError) return Response.json({ error: 'Save the file as CSV UTF-8 and upload it again.' }, { status: 422 }); throw error; } await sw.db.insert('imports', { file_id: fileId }, { onConflict: 'ignore' }); const finish = async (status: 'complete' | 'failed', rowsStored: number, error: string | null, httpStatus: number) => { await sw.db.update('imports', { where: { file_id: fileId }, set: { status, rows_stored: rowsStored, error } }); return Response.json({ status, rows_stored: rowsStored, error }, { status: httpStatus }); }; let contacts: ContactRow[]; try { contacts = contactsFromCsv(text, MAX_ROWS); } catch (error) { if (error instanceof CsvError) return finish('failed', 0, error.message, 422); throw error; } // Each batch is one atomic write as this user. An address already stored for this user is updated. for (let start = 0; start < contacts.length; start += BATCH) { await sw.db.tx(contacts.slice(start, start + BATCH).map((contact) => ({ op: 'insert' as const, table: 'contacts', values: { ...contact, import_id: fileId }, options: { onConflict: 'update' as const }, }))); } return finish('complete', contacts.length, null, 200); }, }); ``` The endpoint validates the whole file before writing contacts. Each batch is atomic. A retry with the same file ID safely updates any contacts the earlier batches stored. The last row for a repeated email supplies its name. ### 4. The page ```ts // src/services/csv-import.ts import { files } from 'somewhere:files'; export type ImportState = { status: string; rows_stored: number | null; error: string | null }; /** Upload a CSV and import it. Returns the import's result. */ export async function importCsv(file: File): Promise { if (!file.name.toLowerCase().endsWith('.csv')) throw new Error('Choose a .csv file.'); const { data: uploaded, error } = await files.csv_uploads.upload(file, { name: 'upload.csv', contentType: 'text/csv' }); if (error) throw new Error(error.message); const response = await fetch('/api/imports', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ file_id: uploaded.id }), }); const result = (await response.json().catch(() => null)) as (ImportState & { error?: string | null }) | null; if (response.status === 422 && result) return { ...result, file_id: uploaded.id }; if (!response.ok || typeof result?.status !== 'string') throw new Error(result?.error ?? `Could not import the file (${response.status}).`); return { ...result, file_id: uploaded.id }; } /** Read one import's recorded result. */ export async function readCsvImport(fileId: string): Promise { const response = await fetch(`/api/imports?file_id=${encodeURIComponent(fileId)}`); if (response.status === 404) return null; const result = (await response.json().catch(() => null)) as ImportState | null; if (!response.ok || typeof result?.status !== 'string') throw new Error(`Could not read the import (${response.status}).`); return result; } ``` Call `importCsv` from a file input. Show `rows_stored` on completion or `error` on failure. Upload a corrected file to retry a validation failure. After a timeout, use `readCsvImport` to check the result and retry a still running import with the same file ID. ### 5. Check it ```bash somewhere typecheck && somewhere deploy somewhere db rows contacts ``` Upload three valid contacts. Expect three rows. Re-upload with one name changed and check that the count stays at three. A missing email should fail before any contacts are written. A second user should see only their own contacts. For a background import, run `somewhere docs example csv-import-background`. ## Larger files Start with the schema, parser, import status endpoint, and browser service from `somewhere docs example csv-import`. Add these files to run it in a background job. The job reads the upload first using the starting user's file access. That access lasts 10 minutes from `sw.jobs.verifyInvocation`. The job uses `sw.db.server` for writes and sets the owner from the verified job payload. ```ts // api/import-jobs.ts — POST { file_id } queues the import of one uploaded CSV export default sw.endpoint({ auth: 'required', body: { file_id: 'string' }, rateLimit: '20/hour', handler: async ({ user, body }, sw) => { const fileId = body.file_id; if (!/^[A-Za-z0-9-]{8,64}$/.test(fileId)) { return Response.json({ error: 'Send the file_id from the upload result.' }, { status: 400 }); } try { // Runs as this user, reading only the first line: another user's upload is not found. await sw.fs.read(`/csv-uploads/${fileId}/upload.csv`, { lines: [1, 1] }); } catch (error) { if (error instanceof Error && 'status' in error && error.status === 404) { return Response.json({ error: 'No such upload for this account.' }, { status: 404 }); } throw error; } await sw.db.insert('imports', { file_id: fileId }, { onConflict: 'ignore' }); // One job per user and file: a repeated POST returns the same job. const job = await sw.jobs.create({ handler: '/api/jobs/import-csv', idempotency_key: `csv-import:${user.id}:${fileId}`, payload: { file_id: fileId, user_id: user.id }, timeout_seconds: 120, }); return Response.json({ job_id: job.job_id, file_id: fileId }, { status: 202 }); }, }); ``` ```ts // api/jobs/import-csv.ts — runs only when the platform delivers the job import { type ContactRow, CsvError, contactsFromCsv } from '../_lib/csv'; const MAX_ROWS = 20_000; const BATCH = 100; // sw.db.server.tx takes 1–100 writes const IN_FLIGHT = 4; export default async function importCsvJob(request: Request, sw: SomewhereRuntimeContext): Promise { if (!(await sw.jobs.verifyInvocation(request))) return Response.json({ error: 'forbidden' }, { status: 403 }); const payload = (await request.json().catch(() => null)) as { file_id?: unknown; user_id?: unknown } | null; const fileId = payload?.file_id; const userId = payload?.user_id; if (typeof fileId !== 'string' || !fileId || typeof userId !== 'string' || !userId) { return Response.json({ error: 'Invalid payload.' }, { status: 400 }); } const finish = async (status: 'complete' | 'failed', rowsStored: number, error: string | null) => { await sw.db.server.update('imports', { where: { file_id: fileId, user_id: userId }, set: { status, rows_stored: rowsStored, error } }); return Response.json({ status, rows_stored: rowsStored, error }); }; let contacts: ContactRow[]; try { // First, while the starting user's file authority is fresh. const file = await sw.fs.read(`/csv-uploads/${fileId}/upload.csv`); contacts = contactsFromCsv(new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer()), MAX_ROWS); } catch (error) { if (error instanceof CsvError) return finish('failed', 0, error.message); if (error instanceof TypeError) return finish('failed', 0, 'Save the file as CSV UTF-8 and upload it again.'); throw error; } // Keep the last occurrence of each normalized email so batches can run independently. const uniqueContacts = [...new Map(contacts.map(contact => [contact.email, contact])).values()]; for (let start = 0; start < uniqueContacts.length; start += BATCH * IN_FLIGHT) { const writes: Promise[] = []; for (let batch = 0; batch < IN_FLIGHT; batch++) { const offset = start + batch * BATCH; const chunk = uniqueContacts.slice(offset, offset + BATCH); if (chunk.length === 0) break; writes.push(sw.db.server.tx(chunk.map(contact => ({ op: 'insert' as const, table: 'contacts', values: { ...contact, import_id: fileId, user_id: userId }, options: { onConflict: 'update' as const }, })))); } await Promise.all(writes); } return finish('complete', contacts.length, null); } ``` Raise the collection's `limits.maxSize` within your plan's per-file ceiling. Change the browser service to POST the upload's `file_id` to `/api/import-jobs`, then poll `readCsvImport(file_id)` until it finishes. A validation failure records `failed` and writes no contacts. A thrown error can retry within the job deadline. Each retry upserts the same contacts. If the import is still running after the deadline, upload again to start a new job. Time your largest file before raising the row cap. To load a dataset once as the developer, not from the app, use the `db_import_csv` tool with a CSV already in your project files. If a batch fails, the error gives the number of rows already imported and the CSV line to resume from. Keep the header and import only the remaining rows. If the error says a write could not be confirmed, check the table before trying again. --- ## Topic: Recipe — PDFs (recipe-pdfs) Page: https://somewhere.cloud/docs/recipe-pdfs.txt Write the document as HTML and CSS, and `sw.render.pdf` prints it in a real browser: web fonts, flexbox, tables and page breaks render the way they do on screen. This recipe makes an invoice for the signed-in user, stores it as a private file, previews it in the page and merges PDFs in a function. ## 1. Generate and store an invoice ```ts // db/schema.ts import { id, integer, owner, schema, table, text } from 'somewhere/db'; export default schema({ invoices: table( { id: id(), number: text(), customer: text(), amount_cents: integer() }, { scope: owner(), client: { read: ['id', 'number', 'customer', 'amount_cents'] } }, ), }); ``` ```ts // api/invoices/[id].ts — POST renders the invoice PDF; GET returns it const escape = (value: string) => value.replace(/[&<>"']/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[ch]!); export default async function invoicePdf(request: Request, sw: SomewhereRuntimeContext): Promise { const user = await sw.auth.fromRequest(request); if (!user) return Response.json({ error: 'Sign in.' }, { status: 401 }); const id = new URL(request.url).pathname.split('/').pop() ?? ''; if (!/^\d+$/.test(id)) return Response.json({ error: 'Unknown invoice.' }, { status: 404 }); const path = `/invoices/${user.id}/${id}.pdf`; if (request.method === 'GET') { try { return await sw.fs.server.read(path); // streams the stored PDF with its content type } catch (error) { if (error instanceof Error && 'status' in error && error.status === 404) { return Response.json({ error: 'Generate the PDF first.' }, { status: 404 }); } throw error; } } if (request.method !== 'POST') return new Response('Use GET or POST.', { status: 405, headers: { Allow: 'GET, POST' } }); // owner(): only this user's invoice is found. const { data } = await sw.db.from('invoices', { where: { id }, limit: 1 }); const invoice = data[0]; if (!invoice) return Response.json({ error: 'Unknown invoice.' }, { status: 404 }); const html = `

Invoice ${escape(invoice.number)}

Billed to${escape(invoice.customer)}
Total$${(Number(invoice.amount_cents) / 100).toFixed(2)}
`; const pdf = await sw.render.pdf({ html, format: 'A4', print_background: true }); await sw.fs.server.write(path, await pdf.arrayBuffer(), { contentType: 'application/pdf' }); return Response.json({ path }, { status: 201 }); } ``` `sw.render.pdf({ html })` returns the PDF as a `Response`. `sw.fs.server.write` stores it as a private file, so only your functions read it. The path holds the signed-in user's id, taken from the session, so one user's request can never name another user's file. Escape every value you put into the HTML. Render once and store the file; serve the stored copy after that. Options: `format` is `'A4'`, `'A3'`, `'Letter'` (the default), `'Legal'` or `'Tabloid'`; `landscape: true` rotates the page; `print_background: true` prints background colours and images; `wait_for: ''` waits up to 5 seconds for an element before printing. Pass `url` instead of `html` to print a public page. `html` is at most 1,000,000 characters, and the page must finish loading within 30 seconds. Renders are metered and charged to the account balance. ## 2. Preview it in the page Load the stored PDF from your own function, same origin, and draw it with PDF.js. It draws to a canvas, so the preview looks the same on phones and desktops. ```tsx // src/ui/InvoicePreview.tsx — npm install pdfjs-dist (version 5 or later) import { useEffect, useRef, useState } from 'react'; import * as pdfjs from 'pdfjs-dist'; pdfjs.GlobalWorkerOptions.workerSrc = `https://unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`; export function InvoicePreview({ invoiceId }: { invoiceId: string }) { return ; } function InvoicePreviewPage({ invoiceId }: { invoiceId: string }) { const canvas = useRef(null); const [error, setError] = useState(null); useEffect(() => { let cancelled = false; let renderTask: { cancel(): void } | null = null; const loadingTask = pdfjs.getDocument({ url: `/api/invoices/${invoiceId}` }); (async () => { const doc = await loadingTask.promise; const page = await doc.getPage(1); const target = canvas.current; if (cancelled || !target) return; const viewport = page.getViewport({ scale: 1.5 }); target.width = viewport.width; target.height = viewport.height; const task = page.render({ canvas: target, viewport }); renderTask = task; await task.promise; })().catch((reason: unknown) => { if (cancelled) return; // a replaced or unmounted preview reports nothing setError(reason instanceof Error ? reason.message : 'Could not load the PDF.'); }); return () => { cancelled = true; renderTask?.cancel(); // cancels the previous render loadingTask.destroy().catch(() => {}); // releases the loading task and worker }; }, [invoiceId]); return ( <> {error &&

{error}

}