@somewhere-cloud/cli 0.38.154 → 0.38.155

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/docs/adopt.md +39 -0
  3. package/dist/docs/analytics.md +161 -0
  4. package/dist/docs/api-reference.md +339 -0
  5. package/dist/docs/api-surface.md +2067 -0
  6. package/dist/docs/app-mcp.md +162 -0
  7. package/dist/docs/architecture-patterns.md +334 -0
  8. package/dist/docs/auth-client.md +531 -0
  9. package/dist/docs/billing.md +76 -0
  10. package/dist/docs/browser.md +639 -0
  11. package/dist/docs/calendar.md +298 -0
  12. package/dist/docs/changes.md +323 -0
  13. package/dist/docs/cli.md +407 -0
  14. package/dist/docs/common-mistakes.md +199 -0
  15. package/dist/docs/connect-agent.md +72 -0
  16. package/dist/docs/cors.md +114 -0
  17. package/dist/docs/cron.md +167 -0
  18. package/dist/docs/database-engine.md +167 -0
  19. package/dist/docs/declared-data.md +1656 -0
  20. package/dist/docs/declared-files.md +475 -0
  21. package/dist/docs/deploy-intelligence.md +188 -0
  22. package/dist/docs/deploy.md +733 -0
  23. package/dist/docs/design-system.md +273 -0
  24. package/dist/docs/dev-environments.md +496 -0
  25. package/dist/docs/domain-ownership.md +31 -0
  26. package/dist/docs/domains.md +370 -0
  27. package/dist/docs/feedback.md +88 -0
  28. package/dist/docs/file-tools.md +116 -0
  29. package/dist/docs/functions.md +489 -0
  30. package/dist/docs/getting-started.md +238 -0
  31. package/dist/docs/github.md +95 -0
  32. package/dist/docs/google-calendar.md +212 -0
  33. package/dist/docs/groups.md +836 -0
  34. package/dist/docs/guarantees.md +58 -0
  35. package/dist/docs/handled-for-you.md +224 -0
  36. package/dist/docs/inspect.md +171 -0
  37. package/dist/docs/limits.md +68 -0
  38. package/dist/docs/live-data.md +197 -0
  39. package/dist/docs/live.md +92 -0
  40. package/dist/docs/local-dev.md +30 -0
  41. package/dist/docs/migration-supabase.md +58 -0
  42. package/dist/docs/payments.md +1102 -0
  43. package/dist/docs/portability.md +194 -0
  44. package/dist/docs/postgres.md +301 -0
  45. package/dist/docs/pricing-comparison.md +42 -0
  46. package/dist/docs/pricing.md +39 -0
  47. package/dist/docs/project-groups.md +107 -0
  48. package/dist/docs/projects.md +380 -0
  49. package/dist/docs/recipe-ai-agent.md +112 -0
  50. package/dist/docs/recipe-ai-features.md +227 -0
  51. package/dist/docs/recipe-ai-receipts.md +783 -0
  52. package/dist/docs/recipe-background-jobs.md +369 -0
  53. package/dist/docs/recipe-booking.md +348 -0
  54. package/dist/docs/recipe-csv-import.md +390 -0
  55. package/dist/docs/recipe-ecommerce.md +127 -0
  56. package/dist/docs/recipe-email.md +282 -0
  57. package/dist/docs/recipe-escalation.md +133 -0
  58. package/dist/docs/recipe-file-uploads.md +159 -0
  59. package/dist/docs/recipe-import-app.md +110 -0
  60. package/dist/docs/recipe-login.md +457 -0
  61. package/dist/docs/recipe-multi-chat.md +198 -0
  62. package/dist/docs/recipe-paid-api.md +161 -0
  63. package/dist/docs/recipe-pdfs.md +205 -0
  64. package/dist/docs/recipe-push-notifications.md +107 -0
  65. package/dist/docs/recipe-seo.md +200 -0
  66. package/dist/docs/recipe-signed-in-app.md +330 -0
  67. package/dist/docs/render.md +99 -0
  68. package/dist/docs/rooms.md +554 -0
  69. package/dist/docs/sdk.md +287 -0
  70. package/dist/docs/sdks.md +24 -0
  71. package/dist/docs/search.md +199 -0
  72. package/dist/docs/security-model.md +168 -0
  73. package/dist/docs/setup.md +212 -0
  74. package/dist/docs/smoke.md +102 -0
  75. package/dist/docs/speed.md +298 -0
  76. package/dist/docs/sql-compatibility.md +96 -0
  77. package/dist/docs/sw.agent.md +248 -0
  78. package/dist/docs/sw.ai.md +1291 -0
  79. package/dist/docs/sw.auth.md +1811 -0
  80. package/dist/docs/sw.billing.md +171 -0
  81. package/dist/docs/sw.db.md +2128 -0
  82. package/dist/docs/sw.email.md +661 -0
  83. package/dist/docs/sw.endpoint.md +187 -0
  84. package/dist/docs/sw.env.md +303 -0
  85. package/dist/docs/sw.fetch.md +115 -0
  86. package/dist/docs/sw.fs.md +424 -0
  87. package/dist/docs/sw.groups.md +836 -0
  88. package/dist/docs/sw.image.md +69 -0
  89. package/dist/docs/sw.jobs.md +520 -0
  90. package/dist/docs/sw.logs.md +61 -0
  91. package/dist/docs/sw.mail.md +106 -0
  92. package/dist/docs/sw.notifications.md +78 -0
  93. package/dist/docs/sw.push.md +161 -0
  94. package/dist/docs/sw.rateLimit.md +67 -0
  95. package/dist/docs/sw.web.md +128 -0
  96. package/dist/docs/tasks.md +269 -0
  97. package/dist/docs/test.md +220 -0
  98. package/dist/docs/tool-reference-account.md +7 -0
  99. package/dist/docs/tool-reference-ai.md +121 -0
  100. package/dist/docs/tool-reference-analytics.md +37 -0
  101. package/dist/docs/tool-reference-api.md +19 -0
  102. package/dist/docs/tool-reference-artifacts.md +35 -0
  103. package/dist/docs/tool-reference-auth.md +163 -0
  104. package/dist/docs/tool-reference-browser.md +114 -0
  105. package/dist/docs/tool-reference-code.md +26 -0
  106. package/dist/docs/tool-reference-connect.md +21 -0
  107. package/dist/docs/tool-reference-cron.md +48 -0
  108. package/dist/docs/tool-reference-db.md +282 -0
  109. package/dist/docs/tool-reference-domains.md +107 -0
  110. package/dist/docs/tool-reference-email.md +55 -0
  111. package/dist/docs/tool-reference-env.md +19 -0
  112. package/dist/docs/tool-reference-feedback.md +56 -0
  113. package/dist/docs/tool-reference-fs.md +265 -0
  114. package/dist/docs/tool-reference-github.md +57 -0
  115. package/dist/docs/tool-reference-groups.md +85 -0
  116. package/dist/docs/tool-reference-help.md +29 -0
  117. package/dist/docs/tool-reference-jobs.md +39 -0
  118. package/dist/docs/tool-reference-live.md +48 -0
  119. package/dist/docs/tool-reference-logs.md +16 -0
  120. package/dist/docs/tool-reference-payments.md +44 -0
  121. package/dist/docs/tool-reference-project.md +706 -0
  122. package/dist/docs/tool-reference-push.md +78 -0
  123. package/dist/docs/tool-reference-rate-limit.md +18 -0
  124. package/dist/docs/tool-reference-search.md +68 -0
  125. package/dist/docs/tool-reference-security.md +42 -0
  126. package/dist/docs/tool-reference-smoke.md +17 -0
  127. package/dist/docs/tool-reference-stock-photos.md +20 -0
  128. package/dist/docs/tool-reference-tasks.md +73 -0
  129. package/dist/docs/tool-reference-telegram.md +32 -0
  130. package/dist/docs/tool-reference-usage.md +9 -0
  131. package/dist/docs/tool-reference-web.md +71 -0
  132. package/dist/docs/tool-reference-webhooks.md +9 -0
  133. package/dist/docs/troubleshooting.md +411 -0
  134. package/dist/docs/typed-functions.md +94 -0
  135. package/dist/docs/verify-before-deploy.md +67 -0
  136. package/dist/docs/vs-supabase.md +75 -0
  137. package/dist/docs/vs-vercel.md +103 -0
  138. package/dist/lib/bundle.js +303 -221
  139. package/dist/lib/bundle.js.map +3 -3
  140. package/dist/types/lib/test-session.d.ts +8 -0
  141. package/npm-shrinkwrap.json +2 -2
  142. package/package.json +3 -2
@@ -0,0 +1,238 @@
1
+ # Start an app
2
+
3
+ ## Start an app
4
+
5
+ The generated AGENTS.md holds the call shapes and access patterns for a typical app.
6
+ Teams are built-in groups: `somewhere docs sw.groups --section team-example`.
7
+ To run an existing public repo in your own account, use `somewhere docs adopt`.
8
+
9
+ Somewhere's product and documentation live at somewhere.cloud. Deployed apps
10
+ use their own *.somewhere.site address or an attached custom domain.
11
+
12
+
13
+ Build a React app with sign-in, server functions and its own SQL database in
14
+ one project. Somewhere compiles and hosts the source, manages sessions, and
15
+ enforces the access rules you declare. [How Somewhere works](https://somewhere.cloud/docs/api-reference.txt#how-somewhere-works)
16
+ explains the whole platform; this page gets your first screen online.
17
+
18
+ Start with the screen people will use, then connect each feature to real data.
19
+ Build the core action first: for a reading list, save a book and find it again.
20
+ Keep extra feeds, admin views and settings screens as follow-ups unless the
21
+ user asked for them.
22
+
23
+ You deploy TypeScript and React source. Somewhere compiles it and serves the app
24
+ and its functions together.
25
+
26
+ Your data and code are yours: `somewhere pull` returns the source, `somewhere db dump`
27
+ writes the raw SQL database as one `.sql` file, `db_export` returns one table as
28
+ CSV, and a project can attach PostgreSQL in your own Neon account. Managed-database
29
+ tables are not in the dump or CSV export yet; the `portability` topic lists what
30
+ each path covers and its limits.
31
+
32
+ ### Choose your starting point
33
+
34
+ **Working on an app already live on Somewhere?** Start with
35
+ `somewhere pull <app>` in a fresh folder. In a connected chat, read the live
36
+ source with `project_export` before editing.
37
+
38
+ **Publishing a first app with plain HTTP?** [Deploy with two HTTP calls](https://somewhere.cloud/docs/start.txt) gives you a live app, claim link and expiry without an account.
39
+
40
+ **Building in Claude or ChatGPT without a terminal?** Connect Somewhere through
41
+ [MCP](https://somewhere.cloud/mcp). Ask your agent to create a project with
42
+ `project_create`: it starts live with the same starter as `somewhere init`,
43
+ and your agent changes it with `project_patch`. The [MCP guide](https://somewhere.cloud/docs/setup.txt)
44
+ shows the tool flow. Use the same design-first approach below; your agent handles
45
+ the files and checks through the connected tools.
46
+
47
+ **Working in an editor or terminal?** Use the starter below. It includes the
48
+ auth route, React hooks, design tokens and UI components.
49
+
50
+ ### Create your project
51
+
52
+ In an empty folder, the starter needs no account.
53
+
54
+ Ask before destructive or paid actions unless the user already authorized them.
55
+
56
+ Importing CSV? Use `somewhere docs recipe-csv-import --full` for an upload, a background job and retry-safe batch writes.
57
+
58
+ ```bash
59
+ mkdir reading-list
60
+ cd reading-list
61
+ npx -y @somewhere-cloud/cli@latest init --name reading-list
62
+ ```
63
+
64
+ Init writes the starter and installs its pinned dependencies. If you are
65
+ signed in, it also creates a project and links this folder. If you are signed
66
+ out, deploy publishes a temporary app and prints its live URL, claim link and
67
+ expiry.
68
+
69
+ ```bash
70
+ npx -y @somewhere-cloud/cli@latest deploy
71
+ ```
72
+ The `setup` guide covers remote environments.
73
+
74
+ Keep `.somewhere.json` in Git. It records which project this folder deploys
75
+ to and holds no credentials. To publish your own copy of someone else's app:
76
+
77
+ Run `npx -y @somewhere-cloud/cli@latest deploy --new` from the clone. It
78
+ creates a project in your account, or a temporary project when signed out,
79
+ and updates the clone's link. Use a folder name suitable for the new app's
80
+ address. The CLI uses that name to generate the address.
81
+
82
+ The starter's `package.json` pins the CLI version that wrote it in the
83
+ `@somewhere-cloud/cli` devDependency. A newer CLI reports a pin mismatch in one
84
+ line and keeps control of deploy. Other commands can use the installed pin.
85
+ `somewhere upgrade` moves the project to the running version and lists what changed.
86
+
87
+ The starter gives you one working sign-in path. Keep it while you build:
88
+
89
+ | Start here | What to change |
90
+ |---|---|
91
+ | `src/pages/HomePage.tsx` | The first signed-in screen. |
92
+ | `src/styles/tokens.css` | Colors, typography, spacing and shape. |
93
+ | `src/styles/app.css` | Shared classes such as `.panel`, `.field`, `.button` and `.muted`. |
94
+ | `src/ui/` | Views: `AppShell` (the app's frame; it shows at once, before the session is known), `AuthCard`, and `Alert` and `EmptyState` in `feedback.tsx`. |
95
+ | `src/services/` | Calls between your UI and its backend. |
96
+ | `api/` | Server functions. The starter's auth route already lives here. |
97
+
98
+ ### Design the screen
99
+
100
+ Choose a visual direction before adding features, with one distinctive idea
101
+ rather than "clean and modern". For a reading list, try a library card: cream
102
+ paper, an oxblood accent and a serif display face. Set it in the starter's
103
+ tokens so the screen and every component share it:
104
+
105
+ ```css
106
+ /* src/styles/tokens.css — change these values inside :root */
107
+ --color-bg: #f6f0e4;
108
+ --color-accent: #7a1f2b;
109
+ --color-focus: #7a1f2b;
110
+ --font-display: "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif;
111
+ ```
112
+
113
+ The file also defines `--color-surface`, `--color-text`, `--color-muted`,
114
+ `--color-border`, `--font-body`, the `--text-*` sizes, the `--space-*` scale and
115
+ two radii. `app.css` reads them all. The `design-system` guide covers palettes,
116
+ type and layout.
117
+
118
+ Replace the starter's home page with a small first screen:
119
+
120
+ ```tsx
121
+ // src/pages/HomePage.tsx
122
+ import type { User } from '../../types/auth';
123
+ import { SignedInLayout } from './SignedInLayout';
124
+
125
+ const sampleBooks = [
126
+ { id: 'earthsea', title: 'A Wizard of Earthsea', author: 'Ursula K. Le Guin' },
127
+ { id: 'piranesi', title: 'Piranesi', author: 'Susanna Clarke' },
128
+ ];
129
+
130
+ export function HomePage({ user }: { user: User }) {
131
+ return (
132
+ <SignedInLayout user={user}>
133
+ <section className="panel" aria-labelledby="reading-list-title">
134
+ <h1 id="reading-list-title">Your next good book</h1>
135
+ <p className="muted">A small shelf of things you want to read.</p>
136
+ <ul>
137
+ {sampleBooks.map((book) => (
138
+ <li key={book.id}>
139
+ <strong>{book.title}</strong> — {book.author}
140
+ </li>
141
+ ))}
142
+ </ul>
143
+ </section>
144
+ </SignedInLayout>
145
+ );
146
+ }
147
+ ```
148
+
149
+ `SignedInLayout` puts the screen inside `AppShell`, which has the app name and
150
+ the sign-out button. The two books are sample content, visible to every
151
+ signed-in account.
152
+
153
+ ### Put it online
154
+
155
+ ```bash
156
+ npx somewhere typecheck
157
+ npx somewhere deploy
158
+ ```
159
+
160
+ Deploy publishes the source in this folder and prints the live URL. Open it,
161
+ create an account or sign in, and check the reading-list screen on a phone and
162
+ on a desktop. Don't bundle the source yourself; the platform runs the frontend
163
+ build.
164
+
165
+ Share the live URL now so the user can react to the screen. For a static site,
166
+ the page may already do the whole job; verify it and stop there. For this
167
+ reading-list app, the next step is to make the shelf personal.
168
+
169
+ ### Connect one feature at a time
170
+
171
+ Use **Data** next: declare a books table in `db/schema.ts` with `owner()` and a
172
+ `client` block, and replace the sample array with calls to the generated
173
+ `somewhere:data` client. Those calls return the signed-in user's rows, with no
174
+ API file. A public enquiry form uses declared `client.intake` to write for
175
+ a published profile's owner (`declared-data` →
176
+ `send-an-enquiry-to-a-public-profile`). Read **Functions** for an authorized
177
+ write the declaration cannot express, or for a side effect such as email. Keep
178
+ `owner()`/`group()` and the client for everything else.
179
+ The default `somewhere init` starter has no `db/schema.ts`: create it at the
180
+ project root, or run `somewhere init --name my-app --features private-data`
181
+ to start with a schema.
182
+ `recipe-signed-in-app` shows a validated server write, email and a reminder.
183
+
184
+ | Schema reference | Contract |
185
+ |---|---|
186
+ | Columns | `id`, `text`, `number`, `integer`, `boolean`, `timestamp`, `json`, `blob`; options: `nullable`, `default`, `unique`, `references`, `onDelete`. |
187
+ | Tables | `scope`, `indexes`, `unique: [['org_id','email']]`, `client`. |
188
+ | Scopes | `owner`, `group`, `appRole`, `shared`, `member`, `anyOf`, `parent`, `serverOnly`. |
189
+ | Operations | Browser: `list`, `get`, `create`, `update`, `delete`, `aggregate`. Functions: `from(table, { where })`, `insert(table, values)`, `update(table, { where, set })`, `remove(table, { where })`, `count`, `aggregate`; plain objects, not fluent chains. |
190
+
191
+ Keep the screen, auth and shared components you already have. Add one working
192
+ data path, check it with two separate accounts, and then move on to the next
193
+ feature.
194
+
195
+ If the feature needs an external service key, see **Env vars and secrets**.
196
+ Read server secrets inside the handler. After the first production deploy,
197
+ changes reach new requests within 60 seconds without another deploy.
198
+ Older apps need one source deploy to enable this behavior; the CLI tells you
199
+ when that is needed.
200
+
201
+ ### Work locally and verify the result
202
+
203
+ After the first deploy, install Vite with `npm install -D vite` if the frontend
204
+ doesn't already have it. `somewhere dev` serves the frontend at
205
+ `http://localhost:8787` with hot reload. Its API requests go to your deployed
206
+ project, so data you save during local development is written to that
207
+ project's database. Server-function changes take effect when you deploy.
208
+
209
+ Deploy the schema before using it locally. `somewhere dev` calls the deployed project; it does not apply schema changes.
210
+
211
+ As you connect the screen:
212
+
213
+ - Reuse the starter's components and styles. Extract a helper or component when
214
+ it removes real duplication; keep server handlers separate from browser code.
215
+ - Show loading, empty and error states. After a mutation, update the affected
216
+ view; clear user-specific cached data on sign-out or account change.
217
+ - For shared data that changes live, use a live view instead of adding a polling
218
+ loop; see `live-data`.
219
+ - Put service keys in project secrets, not source files or app tables. Set them through
220
+ the dashboard or CLI as shown in **Env vars and secrets**, not through chat.
221
+
222
+ Use `somewhere verify` for the browser checks, and inspect failures with
223
+ `somewhere logs` and `somewhere errors`. Check the real user action too: sign
224
+ in, save a book, reload, and confirm that another account sees only its own
225
+ shelf. Once the requested flow works, share what you checked and let the user
226
+ try it before adding more features.
227
+
228
+ ## Instructions for connecting an agent
229
+
230
+ `GET /v1/agent/instructions` (no key needed) returns the one copy of the
231
+ text a person pastes into their agent, per place it runs (`hosted`,
232
+ `local`, `connector`): `{ instructions: [{ id, label, blurb, paste, next }],
233
+ start_url, connector: { url, claude_url, chatgpt_url, claude_directory_url } }`.
234
+ Show it as it is rather than writing your own version.
235
+
236
+ ## Available docs topics
237
+
238
+ The complete topic index lists every topic: https://somewhere.cloud/docs/llms.txt.
@@ -0,0 +1,95 @@
1
+ # GitHub push-to-deploy
2
+
3
+ Connect a repository to a project and every push to the tracked branch
4
+ deploys automatically — the same raw-source pipeline as `somewhere deploy`.
5
+ Live for every project; no tier gate.
6
+
7
+ ## Preferred path: GitHub App
8
+
9
+ The dashboard's Import from GitHub flow and `somewhere git connect` use the
10
+ GitHub App. A human grants an account/repository on GitHub once; the platform
11
+ stores the installation identity, mints short-lived tokens when needed, and
12
+ receives signed App-level push events. No PAT paste and no manual repository
13
+ webhook are required.
14
+
15
+ CLI:
16
+
17
+ somewhere git connect owner/name [--project my-app] [--branch main] [--root web]
18
+ somewhere git status [--project my-app]
19
+ somewhere git disconnect [--project my-app]
20
+
21
+ `git connect` opens GitHub only when consent is missing, resumes
22
+ automatically, deploys the selected branch's current HEAD immediately, waits
23
+ for that exact commit, and prints commit, status, logs, and live URL. All
24
+ three commands support `--json`, and `git disconnect` stops future pushes
25
+ from deploying while leaving the currently deployed site live.
26
+ Pass `--yes` to confirm the disconnect in a non-interactive shell.
27
+
28
+ MCP / REST App flow:
29
+
30
+ github_app_install({ return_to? })
31
+ → { install_url } // give this link to the human
32
+
33
+ github_installations({})
34
+ → { app_configured, installations: [{ installation_id, account_login }] }
35
+
36
+ github_list_repos({ installation_id: 123 })
37
+ → [{ name, private, default_branch, ... }]
38
+
39
+ github_connect({
40
+ project_id: "my-app",
41
+ repo: "owner/name",
42
+ installation_id: 123,
43
+ branch: "main",
44
+ deploy_head: true
45
+ })
46
+ → { repo, branch, via_app: true,
47
+ initial_deploy: { status: "deploying", commit_sha, commit_message } }
48
+
49
+ Poll `github_status` for that exact commit until `last_status` is
50
+ `deployed` or `failed`. Dashboard import and the CLI perform this wait;
51
+ until that terminal status, a `connected` import is still pending.
52
+
53
+ ## REST connect shape
54
+
55
+ POST /v1/github/connect
56
+ {
57
+ "project_id": "my-app",
58
+ "repo": "owner/name",
59
+ "branch": "main", // optional, default "main"
60
+ "root_dir": "web", // optional — deploy one subfolder (monorepos)
61
+ "installation_id": 123, // preferred — caller-owned App installation
62
+ "deploy_head": true // resolve + deploy branch HEAD immediately
63
+ }
64
+ → { repo, branch, root_dir, hook_installed, via_app, initial_deploy }
65
+
66
+ For compatibility, `github_token` still installs a per-repository webhook
67
+ and supports private repositories without an App installation. With neither
68
+ App installation nor token, public repositories can use the returned
69
+ `manual_setup` URL + secret. Both webhook forms verify the raw GitHub HMAC
70
+ before dispatching a deploy.
71
+
72
+ ## Status + disconnect
73
+
74
+ GET /v1/github/connection?project_id=…
75
+ → { connected, repo, branch, root_dir, hook_installed, via_app,
76
+ last_commit_sha, last_commit_message,
77
+ last_status: "deploying" | "deployed" | "failed", last_error }
78
+
79
+ DELETE /v1/github/connection?project_id=… // current site stays live
80
+
81
+ ## What deploys
82
+
83
+ A push to the tracked branch deploys the repo (or `root_dir` subfolder) as
84
+ raw source. Pushes to other branches are ignored. GitHub-driven versions record
85
+ deploy source `github` plus the GitHub commit SHA and first-line message.
86
+
87
+ - Vite/React SPAs deploy unchanged.
88
+ - Monorepos: set `root_dir` to the app folder.
89
+ - Env var changes reach new requests within 60 seconds, without a push.
90
+ When saving a value answers `requires_deploy: true`, the project needs one
91
+ production deploy from source first; a push is one.
92
+ - Next.js SSR is not supported; use a Vite SPA plus functions.
93
+ - GitHub's archive of the whole repository cannot exceed 100 MB. The limit
94
+ applies before `root_dir` picks a folder, so for a larger repository deploy the
95
+ folder with `somewhere deploy`. Files over 5 MB are skipped.
@@ -0,0 +1,212 @@
1
+ # Google Calendar — add events to a user's own calendar
2
+
3
+ A signed-in user of your app connects their Google Calendar and chooses one
4
+ calendar they own. Your functions then add, update and delete the app's own
5
+ events in that calendar, from a request or from a scheduled job when the user
6
+ is away. The platform owns the Google client, keeps the user's grant, and calls
7
+ Google for you. You do not create a Google Cloud project, request scopes, or
8
+ store tokens, and no token or calendar id ever reaches your code.
9
+
10
+ It covers only events your app created, in the one calendar the person chose.
11
+ Your app cannot list, read or change their other events, see free/busy,
12
+ invite attendees, or use other Google services. Writes answer the event's id
13
+ and when Google recorded the change, never its contents. `sw.calendar` is
14
+ something else: atomic booking holds inside your own app
15
+ (`docs({ topic: 'calendar' })`).
16
+
17
+ The calls are `sw.connect.googleCalendar.*`, in server functions:
18
+
19
+ | Call | Result |
20
+ |---|---|
21
+ | `connect(request, { return_to })` | A redirect `Response`. Return it from your connect endpoint. |
22
+ | `status({ user_id? })` | `{ connected: false }` or `{ connected: true, reconnect_needed, calendar: { name, time_zone }, connected_at }`. The person's main calendar is named "Primary calendar". |
23
+ | `createEvent({ user_id?, event })` | `{ id, updated }` |
24
+ | `updateEvent({ user_id?, event_id, event })` | `{ id, updated }`. Only the fields you pass change. |
25
+ | `deleteEvent({ user_id?, event_id })` | `{ deleted }`, which is `false` when it was already gone |
26
+ | `disconnect({ user_id? })` | `{ disconnected, google_permissions_url }`. This app loses access at once. |
27
+
28
+ **Who a call is for.** In a request, every call acts for the signed-in caller,
29
+ and `user_id` is left out. A signed-in caller naming another `user_id` is
30
+ refused with `IDENTITY_CLAIM_NOT_ALLOWED`. `user_id` is accepted only inside a
31
+ scheduled job (`docs({ topic: 'cron' })`) or a background job
32
+ (`docs({ topic: 'sw.jobs' })`). The platform checks that the call comes from a
33
+ running job of your app. Anywhere else, `user_id` is refused with `JOB_REQUIRED`,
34
+ so a public endpoint can never act for someone a visitor names.
35
+
36
+ ## Recipe: put a user's events in their Google Calendar and keep them updated from a scheduled job
37
+
38
+ ### 1. Connect: one endpoint and one link
39
+
40
+ ```ts
41
+ // api/calendar/connect.ts — open it in the signed-in person's browser
42
+ export default async function (req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
43
+ const user = await sw.auth.fromRequest(req)
44
+ if (!user) return Response.redirect(new URL('/signin', req.url).toString(), 302)
45
+ return sw.connect.googleCalendar.connect(req, { return_to: '/settings' })
46
+ }
47
+ ```
48
+
49
+ ```html
50
+ <a href="/api/calendar/connect">Connect Google Calendar</a>
51
+ ```
52
+
53
+ The same endpoint starts and finishes the connection:
54
+
55
+ 1. The person's browser opens it.
56
+ 2. They approve access at Google.
57
+ 3. They choose a calendar on the platform's page.
58
+ 4. Their browser comes back to this endpoint.
59
+ 5. It finishes for the same signed-in person, in the same browser, and sends them to `return_to` with `?google_calendar=`:
60
+
61
+ | Value | Meaning |
62
+ |---|---|
63
+ | `connected` | Done. |
64
+ | `cancelled` | They said no. |
65
+ | `missing_permission` | They unticked a permission at Google, so nothing was connected. Ask them to connect again and allow all of them. |
66
+ | `failed` | It did not complete. Examples: the link expired after 30 minutes, it was finished in another browser, or Google refused. Try again. |
67
+
68
+ Use your app's own address or a custom domain attached to it. Localhost and
69
+ preview addresses are refused. `return_to` is a path on the same site.
70
+
71
+ ### 2. Show the state
72
+
73
+ ```ts
74
+ // api/calendar/status.ts
75
+ export default sw.endpoint({
76
+ auth: 'required',
77
+ handler: async (_input, sw) => sw.connect.googleCalendar.status(),
78
+ });
79
+ ```
80
+
81
+ `reconnect_needed: true` means the person removed the app's access in their
82
+ Google account, or Google ended it. Show the Connect link again.
83
+
84
+ If a person connects again with the same Google account and the same
85
+ calendar, your app can still update the events it added before. With another
86
+ account or calendar, those earlier events can no longer be changed through the
87
+ app.
88
+
89
+ ### 3. Write events with ids you choose, so updates find them
90
+
91
+ Give each event an `id` from your own record. It is 1 to 200 letters, digits
92
+ or `.` `_` `:` `-`. A later run then updates the same event instead of adding a
93
+ copy. Only events created through `createEvent` for this person can be updated
94
+ or deleted. Any other id answers `GOOGLE_CALENDAR_EVENT_NOT_FOUND`.
95
+
96
+ ```ts
97
+ // api/_calendar.ts — shared helper (files starting with _ are import-only)
98
+ type Game = { id: string; title: string; start: string; end: string; place: string }
99
+
100
+ /** Create the event, or update it when it already exists. */
101
+ export async function putGame(sw: SomewhereRuntimeContext, userId: string, game: Game): Promise<void> {
102
+ const event_id = 'game-' + game.id
103
+ const event = { title: game.title, start: game.start, end: game.end, location: game.place }
104
+ try {
105
+ await sw.connect.googleCalendar.updateEvent({ user_id: userId, event_id, event })
106
+ } catch (err) {
107
+ if ((err as { code?: string }).code !== 'GOOGLE_CALENDAR_EVENT_NOT_FOUND') throw err
108
+ await sw.connect.googleCalendar.createEvent({ user_id: userId, event: { id: event_id, ...event } })
109
+ }
110
+ }
111
+ ```
112
+
113
+ Times are ISO date-times with an offset (`2026-12-01T19:30:00-08:00`), or
114
+ a local time plus `time_zone: 'America/Los_Angeles'`. An all-day event takes
115
+ `all_day: true`, with `start` and `end` as `YYYY-MM-DD`; `end` is the day
116
+ after the last day. Event fields are `id`, `title`, `description`,
117
+ `location`, `start`, `end`, `all_day` and `time_zone`.
118
+
119
+ If `createEvent` fails with `GOOGLE_CALENDAR_UNAVAILABLE`, call it again with
120
+ the same `id`. You get the one event, never a copy.
121
+
122
+ ### 4. Keep them updated from a scheduled job
123
+
124
+ Create a schedule that calls this endpoint (`docs({ topic: 'cron' })`). Inside
125
+ that run, `user_id` is accepted. The same code in an ordinary request answers
126
+ `JOB_REQUIRED`.
127
+
128
+ ```ts
129
+ // api/jobs/calendar-sync.ts — called by a schedule
130
+ import { putGame } from '../_calendar'
131
+
132
+ export default sw.endpoint({
133
+ auth: 'none', // the platform's invocation signature authorizes it below
134
+ handler: async ({ request }, sw) => {
135
+ if (!(await sw.jobs.verifyInvocation(request))) return new Response('forbidden', { status: 403 })
136
+ const { data: people } = await sw.db.server.from('calendar_follows', { limit: 500 })
137
+ const { data: games } = await sw.db.server.from('games', { where: { changed: true }, limit: 100 })
138
+ let updated = 0, reconnect = 0
139
+ for (const person of people) {
140
+ try {
141
+ for (const g of games) {
142
+ await putGame(sw, String(person.user_id), { id: String(g.id), title: String(g.title), start: String(g.start), end: String(g.end), place: String(g.place) })
143
+ updated++
144
+ }
145
+ } catch (err) {
146
+ const code = (err as { code?: string }).code
147
+ if (code === 'GOOGLE_CALENDAR_RECONNECT_REQUIRED' || code === 'GOOGLE_CALENDAR_NOT_CONNECTED') { reconnect++; continue }
148
+ throw err
149
+ }
150
+ }
151
+ return { updated, reconnect }
152
+ },
153
+ });
154
+ ```
155
+
156
+ `calendar_follows` is your own table of who wants calendar updates. Make it an
157
+ `owner()` table, so `user_id` is the person. Anyone who has not connected, or
158
+ must reconnect, is skipped and counted, and the page shows them the Connect
159
+ link.
160
+
161
+ ### 5. Disconnect
162
+
163
+ ```ts
164
+ // api/calendar/disconnect.ts
165
+ export default sw.endpoint({
166
+ auth: 'required',
167
+ handler: async (_input, sw) => sw.connect.googleCalendar.disconnect(),
168
+ });
169
+ ```
170
+
171
+ On disconnect, this app loses access at once. Events already in the calendar
172
+ stay, because they belong to the person. Access also ends in the same way when:
173
+
174
+ - a user of your app is deleted;
175
+ - the project is deleted;
176
+ - the project is transferred to a new owner. People connect again after a transfer.
177
+
178
+ Show the person this, with the link `disconnect()` returns: "When your last
179
+ Somewhere connection to this Google account ends, we ask Google to withdraw
180
+ Somewhere's access and then delete the token. You can also remove Somewhere in
181
+ your Google Account at any time: myaccount.google.com/permissions."
182
+
183
+ ## Errors
184
+
185
+ Every error has `code`, `message` and `retry`.
186
+
187
+ | `code` | Status | What to do |
188
+ |---|---|---|
189
+ | `GOOGLE_CALENDAR_NOT_CONNECTED` | 409 | The person has not connected. Show the Connect link. |
190
+ | `GOOGLE_CALENDAR_RECONNECT_REQUIRED` | 409 | Access ended. They removed it at Google, Google ended it, or the chosen calendar is no longer theirs. They connect again. |
191
+ | `GOOGLE_CALENDAR_EVENT_NOT_FOUND` | 404 | This app has no event with that id for this person, or it was deleted. Create it. |
192
+ | `GOOGLE_CALENDAR_EVENT_EXISTS` | 409 | The app already created an event with that id. Update it, or use another id. |
193
+ | `GOOGLE_CALENDAR_INVALID_EVENT` | 400 | The message names the field. |
194
+ | `GOOGLE_CALENDAR_RATE_LIMITED` | 429 | `retry: true` with `retry_after_ms`. Wait, then retry. |
195
+ | `GOOGLE_CALENDAR_UNAVAILABLE` | 503 | `retry: true`. Google did not answer. |
196
+ | `JOB_REQUIRED` | 403 | `user_id` outside a scheduled or background job. |
197
+ | `IDENTITY_CLAIM_NOT_ALLOWED` | 400 | A signed-in caller named a different `user_id`. |
198
+ | `AUTH_REQUIRED` | 401 | `connect` without a signed-in caller, or another call with neither a signed-in caller nor `user_id`. |
199
+ | `APP_USER_NOT_FOUND` | 404 | `user_id` is not a user of this app. |
200
+ | `VALIDATION_ERROR` | 400 | `connect` from localhost, a preview, or another site; or `return_to` is not a path. |
201
+ | `DRAFT_SIDE_EFFECTS_BLOCKED` | 409 | Called from a draft preview. It works once the draft is promoted. |
202
+ | `GOOGLE_CALENDAR_NOT_AVAILABLE` | 404 | Google Calendar is not available to this app. |
203
+
204
+ ## Limits
205
+
206
+ - One connected calendar per person per app, chosen by the person. To change it, they connect again.
207
+ - Only calendars the person owns, not calendars shared with them.
208
+ - 600 Google Calendar calls a minute per app.
209
+ - 10 connect attempts per person every 10 minutes, and 300 per app every hour.
210
+ - Calls are not charged.
211
+ - Agents connected to your app cannot connect a calendar: the person does.
212
+ - A temporary (unclaimed) app cannot use Google Calendar. Claim it first.