@getxflow/cli 1.4.0 → 1.5.0

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.
@@ -1,735 +1,719 @@
1
- ---
2
- name: xflow
3
- description: Build, deploy and publish apps on the XFlow platform with the xflow CLI. Use whenever a folder has xflow.json (the project root or an app folder in apps/), and for any task that touches a project and its apps, deployment, publishing, rollback, source sync, who may open an app or call a function, sign-in inside a public app, the project database or SQL migrations, cloud functions, schedules, environment variables and secrets, file storage and uploads of photos, video or PDFs, connected accounts of external services, production errors and logs, UI built on the template components, or a public page on xflowpage.ru (a landing page, presentation or invoice for people outside the organization).
4
- ---
5
-
6
- # XFlow
7
-
8
- Hosting for web apps. The code lives in an ordinary repository on the developer machine, the
9
- CLI sends the sources, the platform builds them in a clean sandbox, serves each app at its own
10
- address and runs its backend: one database and cloud functions per project.
11
-
12
- No `xflow.json` in the folder or above it means it is not bound to a project yet:
13
- `xflow projects list` names the projects of the organization with their ids, `xflow link <id>`
14
- binds the folder to one (an empty folder gets the whole project), and `xflow init` starts a new
15
- project with its first app. A person signed in to several organizations names the one that gets it:
16
- `xflow init <dir> --org <name>` (ask them which one if unsure; `xflow org` lists them).
17
-
18
- ## First rule
19
-
20
- Check commands and flags against `xflow help` and `xflow help <command>`, not against
21
- memory. If a command is not in the help output, it does not exist: guessing flags is
22
- pointless. The CLI prints a hint with almost every error, read it in full, it usually
23
- contains the fix.
24
-
25
- The public documentation, in Russian, goes deeper than this file: its table of contents is
26
- https://docs.getxflow.com/llms.txt, every page has a Markdown copy. Read the page you need
27
- instead of guessing; give the person https://docs.getxflow.com when they ask how something works.
28
-
29
- ## Keeping these instructions current
30
-
31
- These instructions ship with xflow CLI 1.4.0, so the copy you are reading can be older than
32
- the CLI answering your commands.
33
-
34
- When the CLI says this file does not match it, run `xflow skills --refresh` and then **read
35
- again the file it names**: refreshing only writes to disk, and until you re-read it you are
36
- still working from the old rules. Do it yourself, no need to ask.
37
-
38
- Updating the CLI is not yours. `xflow update` replaces a program shared by every project on
39
- the machine: offer the update in your summary. The exception is a platform refusing the CLI as too old (`outdated_cli`):
40
- nothing runs until it is updated, so say what you are doing and run it.
41
-
42
- ## Hard rules
43
-
44
- These mistakes cost the most because nothing fails at the moment they are made, or
45
- the error points away from the cause. The sections below carry the details.
46
-
47
- 1. Read environment variables literally: `process.env.API_KEY`. Destructuring
48
- (`const { API_KEY } = process.env`), a name built from an expression, `?.` and
49
- spreading the environment all read as no mention of the variable at all. The
50
- build rejects them, and `xflow env check` names them before that.
51
- 2. A value written with `xflow env set` reaches the functions on the next
52
- `xflow deploy functions`, not at the moment it is written.
53
- 3. Never delete a `functions/<name>/` directory unless the user asked for that
54
- function to go. The next deploy removes it from the cloud together with its keys and
55
- schedules, and that is final.
56
- 4. A function an app calls needs that app in its `callers` in the root
57
- `xflow.json`. Without it the call answers 404 `not_bound`, and a new function is not
58
- reachable from anywhere.
59
- 5. Every function called by an app open to anyone can be called by
60
- anybody on the internet with curl. Write it as such, see **Your function is open to the
61
- whole internet**.
62
- 6. An already applied migration is never re-run, and `xflow db migrate` refuses a
63
- name it already holds with different content. A schema change is always a new file.
64
- 7. When `xflow db migrate` answers `db_write_locked`, or an INSERT or CREATE TABLE in a
65
- function fails with `permission denied` (42501), the database is over its plan size and
66
- Postgres itself refuses. Reads, updates and deletes keep working, so the fix is deleting data
67
- (`xflow db exec` or a migration), never a rewrite of the SQL. Write comes back within the hour. The limit
68
- is shared by the organization: `xflow db list` shows the size of each project database.
69
- 8. Heavy media does not travel with the sources. Photos, video and PDFs go up with
70
- `xflow storage push`, not into the repository: the archive is capped at 10 MB.
71
-
72
- ## Projects and apps
73
-
74
- - A project is a box: one database with its migrations, the cloud functions, secrets and
75
- members. It has no code of its own.
76
- - An app is code the platform builds and serves at `https://<id>--<org>.xflowpage.ru`
77
- (`<id>` is six random characters the platform gives the app, `<org>` the name of the
78
- organization): its own versions, its own access level. A project holds one or more apps,
79
- and all of them use the same database and the same functions.
80
- - A project without apps is fine (`xflow init --no-app`): its functions are workflows, woken
81
- by a schedule, by an outside service holding a key, or by `xflow functions invoke`.
82
- - `xflow projects get` shows the apps with their folders, addresses and access levels, and
83
- who may call each function.
84
-
85
- ## Folder layout
86
-
87
- One folder per project, apps in subfolders:
88
-
89
- clinic/
90
- xflow.json projectId, and who may call each function
91
- package.json dependencies of the functions
92
- functions/<name>/index.ts cloud functions, shared by every app
93
- migrations/0001_init.sql the one database of the project
94
- apps/
95
- priem/ an app: a Vite project with its own xflow.json (appId, build)
96
- zapis/
97
-
98
- - Two kinds of history: the project root (functions, migrations, `xflow.json`) is one, each
99
- app is another. `apps/**` never travels with the root, the root never travels with an app.
100
- - An app sees only its own folder when it is built. What two apps share is data and logic,
101
- and that lives in functions. Functions never go inside an app folder: the build refuses
102
- `functions/` there (`functions-in-app`).
103
- - `xflow apps add <folder>` creates an app, lays the template into `apps/<folder>` and prints
104
- its address. Never create an app folder by hand: without its `appId` it is nobody's.
105
- `--color <color>` sets the tile the user sees in the project; a wrong one is answered with
106
- the list of colors. Its icon and a later color change belong to the person in the web
107
- interface.
108
- - Rename an app folder freely: the app is its `appId`.
109
- - Commands follow the folder you stand in: inside `apps/zapis` they mean that app, anywhere
110
- else in the project they mean the project. `--project <id>` and `--app <id>` name them
111
- without a folder.
112
- - Neither `xflow.json` is edited by hand except `functions.<name>.callers` in the root one.
113
-
114
- ## Plan limits
115
-
116
- The organization runs on a plan with limits: apps, functions, pages, active connections,
117
- people in the organization, database and file storage, function minutes, builds per month and at once, schedules
118
- (one count for all projects of the organization) and how often they may run, and which access levels an app may have. Most are finite; a plan
119
- may leave one uncapped, and then `whoami` prints `no limit` instead of a ceiling.
120
- `xflow whoami` prints every one of them next to what is used, and the rights of your own key
121
- with them: destroying data (a migration or `db exec`), deleting files from storage, moving a database and
122
- linking a connected account each need a right. Reading it before a long task turns a refusal
123
- halfway through the work into a sentence said before it starts.
124
-
125
- - Connections are counted while active: switching an unused one off frees the seat without
126
- deleting it.
127
- - Function minutes are shared by the whole organization: every app, page and schedule spends
128
- them. When they run out, every function of the organization stops (`functions_stopped`).
129
- - An unpaid plan stops the functions at once, and five days later freezes the organization:
130
- every command except `xflow whoami` answers `subscription_blocked`,
131
- apps and pages show a "suspended" page. Nothing is deleted and no code fixes it: tell the
132
- person that the owner pays the invoice in the organization settings, section «Тариф» (Plan).
133
- - The cap on how long one function call may run is written into the function when it is
134
- deployed, so a plan change reaches the cloud only with the next `xflow deploy functions` of
135
- each project, in both directions.
136
- - One function runs at most a plan-set number of calls at once: Free 5, Start 15, Business 35
137
- per cloud zone (the cloud has three, the spread is not promised). A call over it gets 429 at
138
- once: fan out in batches of that size, never all items of a list in parallel.
139
-
140
- A limit refusal is not a bad request. The CLI prints a line starting with `Plan limit:`, the
141
- API answers `code: "forbidden"` with a `limit` object (`code`, `used`, `limit`). Retrying, renaming or rewriting the code changes nothing: tell the user
142
- what ran out and stop, only the owner lifts it. A schedule refused for running too often is one
143
- of these too, not a bad cron string: the minimum interval comes from the plan, never guess it.
144
-
145
- ## Deploying
146
-
147
- 1. Change the code. In an app folder `npm run typecheck` is a two-second check, `npm run build`
148
- a fast way to see build errors early: the platform builds again in its own sandbox.
149
- 2. `xflow deploy functions -m "what changed"` sends the project root, checks it, applies the
150
- new migrations, ships the functions and their callers. A migration that fails or would
151
- destroy data stops it before any function ships: settle it with `xflow db migrate`
152
- (`--allow-destructive`), then deploy again. `xflow db migrate` alone changes the schema
153
- without shipping code. Every app runs the new code the moment it finishes: there is
154
- no staging and no publish step for server code. Say so to the user.
155
- 3. `xflow deploy apps/zapis -m "what changed"` sends and builds one app; inside `apps/zapis` a
156
- plain `xflow deploy` does the same. In the root a plain `xflow deploy` refuses and names the
157
- targets. The comment is required: one short line in the language the user speaks.
158
- 4. `xflow publish` in the app folder (or with `--app <id>`) shows that build to visitors.
159
-
160
- A change that touches data and screens goes in this order: the functions (with the migration),
161
- then every app that shows it. `xflow deploy apps/...` warns when the root holds changes nobody
162
- deployed.
163
-
164
- - A build of an app is not shown to visitors until `xflow publish`. Publishing points the
165
- address at a build and takes a second; `xflow publish <number>` (or `xflow rollback <number>`)
166
- points it at an older kept build, and that is the rollback. The very first build of a new
167
- app publishes itself.
168
- - Only the app moves on publish and rollback. Functions come back with
169
- `xflow deploy functions --revision N -m "why"` (`xflow deployments functions` lists the revisions);
170
- `--project <id>` names the project without a folder.
171
- - Files of the **three latest successful builds** of each app are kept, plus the live one;
172
- `xflow deployments` marks the rest `no pages`. The history keeps 30 builds, a revision stays
173
- while its build is in it or it is among the 10 latest. Keep anything you must not lose in
174
- your own git repository.
175
- - Give a person the app address the CLI printed, or the project page it printed. Name builds
176
- by their number.
177
- - `xflow status` says how the local copies differ from the server. A deploy rejected before
178
- the build starts means the server holds a revision this folder has never seen: fetch it next
179
- to yours (`xflow pull --into ./server-copy`), merge in git, deploy again. `--force` sends this
180
- folder over it anyway; the overwritten revision is kept while it is among the last 10, and the
181
- deploy prints the `xflow pull --revision <N>` line that brings it back. A folder with no record of the server revision (a fresh clone, a CI checkout) is
182
- not rejected: its first deploy goes on top and says so.
183
- - A deploy that would delete functions gone from the sources refuses until somebody agrees;
184
- `--allow-removals` is the only way past it without a terminal. Reaching for it to get a
185
- build running means you deleted something the user never asked you to: put the directories
186
- back. If the removal is intended, name the functions and let the user answer.
187
-
188
- ## Build gate
189
-
190
- Before the sandbox starts, the platform checks the sources. Everything below blocks the build,
191
- all violations come back together with files and lines, and a rejected attempt costs nothing.
192
-
193
- An app:
194
-
195
- - `package.json` with the build script named in its `xflow.json` (`npm run build` by default),
196
- a `vite.config.*` and `vite` in dependencies. No server frameworks: `next`, `nuxt`, Remix,
197
- `@sveltejs/kit`, `astro`.
198
- - `index.html` in the app root with `id="root"` and the script that loads `src/main.tsx`
199
- (`.ts`, `.jsx`, `.js` count too). Code under `src/`; root `app/`, `pages/`, `next/` are rejected.
200
- - Keep `base` in `vite.config.js` as the template has it: the platform serves each build from
201
- `/_b/<key>/`, and a build whose `index.html` points elsewhere is refused.
202
- - The built app at most 15 MB unpacked, the sources at most 10 MB.
203
- - File names in latin letters, digits, spaces and `. - _ ~` only: `логотип.png` breaks the build.
204
- - Call functions through `xflow.functions.invoke`, never a hardcoded function address.
205
- - No keys or tokens in the sources, no server modules (`fs`, `express`, `http`, `child_process`).
206
- - Outside `src/components/ui` and `src/components/blocks`: no `alert()`, `confirm()`,
207
- `prompt()` (use Dialog and Toast), no `console.log` (visitors read the console;
208
- only crashes and 5xx reach the logs).
209
- - A library that needs a provider (`@tanstack/react-query`, `react-redux`, `sonner`,
210
- `react-hot-toast`, `react-dnd`) must have it mounted. A missing provider builds fine and
211
- gives visitors a white screen.
212
- - The platform files stay byte for byte as they arrived: `src/lib/platform-auth.ts`,
213
- `src/contexts/platform-auth-context.tsx`, `src/hooks/use-platform-auth.ts`,
214
- `src/utils/error-logger.ts`, `src/lib/xflow.ts`. The code keeps calling `initPlatformAuth()`
215
- and `initErrorLogger()` and importing `index.css`, and the Tailwind
216
- `content` globs keep covering `src/**`. A rejection names the revision to take the original
217
- from: `xflow pull --revision N --into ./original`, then copy the file back.
218
-
219
- The project root: function names are lowercase latin letters, digits and hyphens, up to 41
220
- characters (`send-mail`, not `sendMail`); every name under `functions` in `xflow.json` has its
221
- `functions/<name>/index.ts`; every caller is an app folder of this project (`unknown-caller`).
222
-
223
- Passes with a line `Unfinished:` instead of blocking: the template's page title, no
224
- `<link rel="icon">` in `index.html`, an `exports.access` left in a function (it does nothing).
225
- Fix the first two before you tell the person the app is done.
226
-
227
- ## The template is a starter kit
228
-
229
- - `src/components/ui` and `src/components/blocks` are a starting set: change them, restyle them
230
- or delete what you do not use. Any colors, your own color scheme, inline styles, a single
231
- theme without dark mode: all allowed.
232
- - The template looks like the xflow interface: warm grays, hairline controls (`ctl-solid`,
233
- `ctl-raised`, `ctl-inset`, `ctl-select`), segments (`seg-track`, `seg-on`) and surfaces
234
- (`surface-raised`, `surface-pop`, `surface-modal`) in `src/index.css`.
235
- - While any template component is left, the theme token names in `:root` of `src/index.css`
236
- and their `hsl(var(--name))` mapping in the Tailwind config stay: those components paint with
237
- them. Values change freely; they are HSL components (`216 95% 40%`), not `#hex`. Your own
238
- colors go under new names.
239
- - Images and other assets: import them from `src/` (`import logo from './assets/logo.png'`)
240
- so the build puts them next to the code. An absolute path into `public/` (`/logo.png`) goes
241
- through the access check of the app and fails inside the xflow frame in Safari.
242
-
243
- ## Who opens an app
244
-
245
- A person sets this in the web interface; you cannot, and you should not ask for a way around.
246
-
247
- | Level | Who gets in |
248
- |---|---|
249
- | Project members | people who have access to the project |
250
- | Anyone with the link | anybody, no sign-in at all |
251
-
252
- - The plan decides which levels exist: on Free an app opens only inside xflow, Start adds the
253
- direct address and "Anyone with the link".
254
- - At the closed level the platform signs people in, and a function receives the person in
255
- `event.xflow.user` (`id`, `role` in the organization, `name`, `access` to the project).
256
- Keep roles inside the app (doctor, receptionist) in your own table keyed by `user.id`.
257
- - People outside the organization (patients, pickers, clients) are not xflow accounts: make the
258
- app "Anyone with the link" and give it its own sign-in, see below.
259
- - At "Anyone with the link" the platform signs nobody in: `event.xflow.user` is null for
260
- visitors. Accounts, sign-in and who sees which rows are the code of your app, see below.
261
- - `usePlatformAuth()` in the frontend knows the person only inside the xflow frame, and even
262
- there it is a hint for drawing the interface, edited from the console by anyone. On the
263
- direct address it answers `anonymous`. Guard data in the function, by `event.xflow`.
264
-
265
- ## Which functions an app may call
266
-
267
- The root `xflow.json` names the callers of each function:
268
-
269
- {
270
- "projectId": "…",
271
- "functions": {
272
- "list-slots": { "callers": ["zapis", "priem"] },
273
- "book-slot": { "callers": ["zapis"] }
274
- }
275
- }
276
-
277
- - A caller is an app folder of this project (`apps/zapis` is `"zapis"`); a page is never
278
- a caller. A function without callers is left out of `functions` or given `"callers": []`,
279
- the same thing.
280
- - A function nobody lists has no callers: no app reaches it. That is a workflow,
281
- run by a schedule, a key or `xflow functions invoke`.
282
- - Callers ship with `xflow deploy functions` and come back with its `--revision N`.
283
- - The app calls `xflow.functions.invoke('book-slot', { body })` from `src/lib/xflow.ts`. The call
284
- goes to `/_fn/book-slot` on the app's own address: no function addresses, tokens or keys in
285
- the bundle, nothing to rebuild when a function changes.
286
- - A refusal throws `XFlowError` with `status` and `code`: `not_bound` (404, add the caller and
287
- deploy functions), `not_found` (404, the function is not deployed), `login_required` and
288
- `invalid_credential` (401, the visitor has to sign in again), `no_access`, `role_too_low`,
289
- `functions_stopped` (403, minutes ran out or the plan is unpaid: a person settles it),
290
- `rate_limited` (429), `unavailable` (503, retry later). Branch on `code`, never on the message.
291
-
292
- ## Your function is open to the whole internet
293
-
294
- A function is open when an app at "Anyone with the link" is among its callers. `xflow deploy functions` says so in a line of its own, `xflow functions list`
295
- prints `open`, the web interface marks it.
296
-
297
- Open means anybody can call it with curl, without your app: the browser is not a gate.
298
- Hiding the address, checking `Origin` or `Referer`, a token baked into the bundle: all of it is
299
- readable or forgeable and protects nothing. Write every open function as if the request came
300
- from a stranger, because it may:
301
-
302
- - Check every input: types, lengths, allowed values; refuse fields you do not expect. Put input
303
- into SQL as parameters only (`$1`), never into the text.
304
- - Return only what this caller needs: no `select *` into a response, no rows of other people,
305
- no internal fields, no stack traces.
306
- - Make writes safe to repeat: take a request id from the client and put a unique index on it,
307
- so a retry or a replay changes nothing.
308
- - Deduplicate and limit per visitor where it costs: `event.xflow.ip` is the visitor's address,
309
- set by the platform proxy and not by the caller. The proxy caps requests per address; the
310
- organization pays for every minute a function runs.
311
- - A form open to strangers needs a captcha: Cloudflare Turnstile, with the token checked in the
312
- function against `https://challenges.cloudflare.com/turnstile/v0/siteverify` and the secret
313
- from `xflow env set`. The site key is public and stays in the source. A check in the browser
314
- checks nothing.
315
- - `minRole` on an open function refuses every anonymous visitor (`login_required`): use it only
316
- where members call.
317
-
318
- ## Sign-in in a public app
319
-
320
- At the closed levels do none of this: the platform already knows the person.
321
-
322
- - Passwords: store only a hash, `crypto.scrypt` from Node with a random salt per user, compare
323
- with `crypto.timingSafeEqual`. Never log a password, never return it, never keep it in the
324
- browser.
325
- - Session: after sign-in the function makes a random token (`crypto.randomBytes(32)`), stores
326
- its SHA-256 and an expiry in a table and returns the token in the response body. The app keeps
327
- it in `localStorage` and sends it on every call in the `X-Session` header. Not a cookie: Cloud
328
- Functions drop `Cookie` and `Set-Cookie` both ways. `localStorage` belongs to one address, a
329
- neighbouring `*.xflowpage.ru` site does not read it.
330
- - Any script on the page reads that token, so: an expiry of hours that each call extends,
331
- sign-out and a password change delete the session rows, no user text rendered as HTML
332
- (`dangerouslySetInnerHTML`), no scripts loaded from outside the build.
333
- - Never put the token into an address (`?session=`, a link): it stays in history and logs. A file
334
- the function makes for this person is fetched with the header and opened as a `blob:` URL.
335
- - Not the `Authorization` header: `/_fn` replaces it with the platform's own. Nor headers named
336
- `X-Xflow-*`, `X-Project-Pass`, `X-Server-Key`, `X-Function-Key`: the platform strips them.
337
- - Every function that serves a signed-in visitor reads `X-Session` from `event.headers` (match
338
- the name in any case), finds the session and filters rows by that user in SQL. A hidden button
339
- is not access control.
340
- - Count failed sign-ins per email and per `event.xflow.ip` in a table and slow them down.
341
- - Never in the frontend: keys, secrets, the list of users, hashes, a role check that is the only
342
- guard.
343
- - The platform sends no email for your app: confirmation and reset letters need a mail provider
344
- whose key goes into `xflow env set`.
345
- - `xflow dev` does not carry `X-Session` and calls functions as you (a member).
346
- Try the sign-in on the app address.
347
-
348
- ## Page or app
349
-
350
- - A page is finished static files at `https://<name>.xflowpage.ru`: public, live the moment it
351
- is uploaded, no build, no publish step, no database. A landing page, a presentation, an invoice.
352
- - An app is source the platform builds: versions and publish, access levels, a database through
353
- functions. Anything people sign in to, enter data into or come back to.
354
- - Keep the sources of a page outside the project folder, or list them in `.xflowignore`: the
355
- root travels with `deploy functions`.
356
- - A page has no backend. A form or a lookup for strangers is an app at "Anyone with the link"
357
- (a paid plan): the platform checks every call to its functions.
358
- - A function key on a page is allowed, and it opens that function to every visitor: an HTML
359
- form posts to `https://fn.xflowpage.ru/<projectId>/<name>?key=...`, fetch cannot read the
360
- answer (no CORS). Nothing guards it but the function's own checks: say so to the user.
361
-
362
- ## Cloud functions
363
-
364
- `functions/<name>/index.ts` in the project root exports `handler` (`index.js` and `index.mjs`
365
- are read too), `export const handler` and `exports.handler` both work. The request arrives as
366
- `event.httpMethod`, `event.headers`, `event.queryStringParameters` and `event.body`, a string
367
- (`JSON.parse` it; `event.isBase64Encoded` marks a binary body). The handler returns
368
- `{ statusCode, body }` where `body` is a JSON string, and may add `headers`.
369
- `xflow functions list` shows status, callers, `open`, keys, last call and last error.
370
-
371
- - Dependencies (`pg`, a mail client) go into the root `package.json`; the platform installs them
372
- on every deploy, and a lock file next to it makes that exact.
373
- - Code shared by functions lives in a root folder such as `lib/`, imported by relative path: each
374
- function is bundled with what it imports. A folder in `functions/` without `index.*` is not a
375
- function. Read `process.env` in `functions/<name>/` itself: `xflow env check` looks only there.
376
-
377
- Keep one shape inside that string across the project: `{ success: true, data }` when it worked,
378
- `{ success: false, error: { message, code } }` when it did not. Branch the frontend on
379
- `error.code`, never on `error.message`.
380
-
381
- A function whose code and variables did not change is not shipped again, and one that fails to
382
- ship fails the whole deploy.
383
-
384
- Debugging a deployed function is two commands: `xflow functions invoke <name>` calls it as you,
385
- through the platform, and prints the body alone, ready for a pipe (`--data '{"a":1}'`, `--data-file
386
- body.json`, `--method GET`; 4xx and 5xx exit non-zero; Windows PowerShell 5.1 prepends a BOM when
387
- piping to another program, so read it with `ConvertFrom-Json` or Python's `utf-8-sig`); `xflow functions logs <name>` shows
388
- the crashes and 5xx answers with stacks and console output, the latest 10 (`--limit N` for more).
389
- Only failed calls are logged. Empty output does not clear a function that fails at module start,
390
- runs over its time cap or out of memory: those never reach the logs, `invoke` shows them.
391
-
392
- The body has to be JSON and the CLI checks it before calling. In PowerShell the double quotes
393
- never reach the CLI (`--data '{"a":1}'` arrives as `{a:1}`): escape them (`--data '{\"a\":1}'`)
394
- or pass a file. It bites `--payload` of a schedule the same way. A command that worked writes
395
- nothing to stderr, so a red line there means it really failed.
396
-
397
- ### Who is calling
398
-
399
- The platform checks every call before your code runs and hands the answer over in `event.xflow`:
400
-
401
- ```js
402
- exports.handler = async (event) => {
403
- const { caller, slug, user, ip } = event.xflow
404
- // caller: 'app' (an app of this project), 'service' (another function of this
405
- // project), 'external' (an outside service with a key), 'schedule',
406
- // 'platform' (a person through xflow functions invoke or the web interface)
407
- // slug: the address name of the calling app (<id>--<org>), null otherwise
408
- // user: { id, role, name, access } of a signed-in person, null for anonymous
409
- // visitors and keys. access: 'view' | 'edit' on this project
410
- // ip: the visitor's address, null for a schedule
411
- }
412
- ```
413
-
414
- Never trust an identity that arrives in the body or in a header of the request: the page lives
415
- on someone else's computer. `event.xflow` is the only identity the platform stands behind.
416
-
417
- Project access is separate from the role: a person who only views the project (`access:
418
- 'view'`) still reaches every function. A function that writes refuses them:
419
-
420
- ```js
421
- if (event.xflow.user && event.xflow.user.access !== 'edit') {
422
- return { statusCode: 403, body: JSON.stringify({ error: 'Read-only access' }) }
423
- }
424
- ```
425
-
426
- To remember who did something, store `user.id` and `user.name` in the row: the name is never
427
- empty, and the app has no other way to look up other people.
428
-
429
- A function that changes data should say who may call it instead of checking the role by hand:
430
-
431
- ```js
432
- exports.minRole = 'developer' // 'member' | 'developer' | 'owner'
433
- ```
434
-
435
- The platform refuses anything below that role before your code runs; it applies to people
436
- (apps, `functions invoke`), not to keys and schedules. `member` is the people who only
437
- use the apps (clinic employees, managers), `developer` and `owner` build them. In the web
438
- interface these roles are called «Просмотр» (`member`), «Редактор» (`developer`) and «Админ»
439
- (`owner`). Without the line
440
- every member of the project can call the function. Losing access
441
- closes the function within a minute.
442
-
443
- - Another function of the project: `fetch(`${process.env.XFLOW_FN_URL}/<name>`, { headers:
444
- { 'X-Server-Key': process.env.XFLOW_SERVER_KEY } })`. The key opens the functions of its own
445
- project only, whatever their callers.
446
- - An outside service (a payment webhook, a bot, a CRM) calls
447
- `https://fn.xflowpage.ru/<projectId>/<name>` (`xflow functions list` prints it) with a key of
448
- that function in `X-Function-Key` or `?key=`. Keys are issued by a person on the function's
449
- screen in the web interface, never by you: ask the user. A function holds at most two keys,
450
- the second one to replace the first without downtime.
451
- - `exports.access` does nothing any more: who may call is `callers`.
452
-
453
- ## Secrets and connected accounts
454
-
455
- Keys and passwords live on the platform, not in the repository: `xflow env set SMTP_PASSWORD=…`
456
- writes one, `xflow env` lists the names, `xflow env check` names the variables your functions
457
- read but the platform does not have. Values never come back out: the only place they exist is
458
- inside the running function. Apps get no variables at all.
459
-
460
- A variable goes to the whole organization unless you say otherwise: `--scope project` keeps it
461
- to this project alone, `--scope organization` is the default, and a third word is refused.
462
- Pick the narrow one for anything that belongs to one project. These commands see only what
463
- this project can see, so `env rm` reports a variable of another project missing even though
464
- names are unique within the organization.
465
-
466
- `DATABASE_URL` and every name starting with `XFLOW` are filled in by the platform: writing them
467
- is refused.
468
-
469
- Some variables come from a connected account instead of from you. Credentials of an account
470
- linked to the project show up in `xflow env` marked read-only, under a prefix chosen at link
471
- time (`YANDEX_DIRECT_TOKEN`, `YANDEX_DIRECT_CLIENT_LOGIN`): read them like any other variable.
472
- If calls to that service start failing on authorisation, `xflow status` says whether the token
473
- is merely expiring (any deploy of the functions renews it) or the account was disconnected on
474
- the provider's side, which only a human can reconnect.
475
-
476
- `xflow connections` lists those accounts: the ones linked to this project, with the alias and
477
- the state of the access, and the ones the organization has but this project does not use yet,
478
- marked `available, not linked`. Check it before telling anyone a service is unavailable.
479
-
480
- `xflow connections link "Яндекс Метрика" --as YANDEX_METRIKA` is that link and
481
- `xflow connections unlink YANDEX_METRIKA` undoes it; `xflow help connections` has the naming
482
- rules. In the project folder unlink refuses while a function still reads one of the variables,
483
- naming those functions, so read that list before reaching for `--yes`.
484
-
485
- Linking needs the `connections:link` right on the key, and only accounts granted to the owner
486
- of the key personally can be linked at all. A key cannot grant it to itself: ask the person.
487
- Connecting a new account and switching one off stay with a person too.
488
-
489
- ### Asking an API what it returns
490
-
491
- ```
492
- xflow connections call WB /api/v1/supplier/stocks?dateFrom=2026-09-01
493
- xflow connections call "Яндекс Метрика" /management/v1/counters
494
- xflow connections call OZON /v1/product/list --method POST --data '{}' \
495
- --header '{"Client-Id":"{CLIENT_ID}"}'
496
- ```
497
-
498
- The platform attaches the credentials and makes the request itself: no deploy, and the key never
499
- reaches you. A linked account is called by its alias, an `available, not linked` one by its
500
- name: linking first is not needed to look. Calling is looking, not wiring: to use the account
501
- in code, link it and deploy functions.
502
-
503
- `{NAME}` in the path or in a header value is filled in from the fields of the connection. Take
504
- the names from `xflow connections`, which prints them in braces: an invented name is left in the
505
- text and the request goes out anyway, into somebody's live account. Ask for the shape, not the
506
- volume: one day and `limit=1`; `--json | jq '.response.body | keys'` gives the field names
507
- without the body entering your context. `POST` and `DELETE` change things in a live account and
508
- nothing undoes that: ask the person first when the endpoint is not clearly a read.
509
-
510
- ## Schedules
511
-
512
- `xflow schedules set report "0 3 ? * * *"` runs a function daily at 03:00. Six fields, UTC,
513
- and exactly one of day-of-month / day-of-week must be `?`. A run reaches the handler as a POST
514
- with `event.xflow.caller === 'schedule'`, and `--payload '{"mode":"full"}'` (or
515
- `--payload-file body.json`) is its body. The function has to be deployed first.
516
- A schedule is the function plus its cron: `set` with the same pair only changes the payload, a
517
- new cron is one more schedule next to the old one. The plan caps the count for the whole
518
- organization, so take the old one off with `xflow schedules rm report "<old cron>"`.
519
-
520
- ```
521
- xflow env set SMTP_PASSWORD=... # secrets first: values ride the next deploy
522
- # write functions/report/index.ts, reading process.env.SMTP_PASSWORD literally
523
- xflow deploy functions -m "Nightly report"
524
- xflow schedules set report "0 3 ? * * *" --payload '{"mode":"full"}'
525
- xflow functions invoke report # run it once
526
- xflow functions logs report # crashes of real runs
527
- ```
528
-
529
- ## Database
530
-
531
- Schema changes are files: `migrations/0001_init.sql`, `migrations/0002_orders.sql` in the
532
- project root, applied in filename order by `xflow db migrate` from any folder of the project.
533
- `xflow db status` shows what is applied and what waits. Never edit an applied file, write a new
534
- migration instead. Every project has exactly one database of its own, shared by all its apps and
535
- functions.
536
-
537
- The browser never reaches the database directly. The app reads and writes through a cloud
538
- function, and inside the handler the connection string is already there:
539
-
540
- ```js
541
- const { Client } = require('pg')
542
- const db = new Client({ connectionString: process.env.DATABASE_URL })
543
- ```
544
-
545
- The platform passes `DATABASE_URL` only to functions that mention it and sets the project schema
546
- on every connection, so plain table names (`select * from tasks`) hit your project.
547
-
548
- `migrations/` says what you did; `xflow db schema [table]` says what is in the database now, and
549
- `xflow db query 'select ...'` reads it inside a READ ONLY transaction (as many rows as its
550
- own `limit` asks, 50 without one, 300 at most; `--json` prints long values whole). Single quotes hold in PowerShell, bash
551
- and zsh, cmd.exe wants double ones; a query with quotes of its own goes in a `.sql` file outside
552
- the project, `xflow db query ../q.sql`.
553
-
554
- A one-off data fix is `xflow db exec 'update ...'` (or `../fix.sql`), not a migration: one
555
- INSERT, UPDATE, DELETE or MERGE, saved at once, never re-run, no trace in the migration history.
556
- Schema changes are refused there. Deleting rows, or updating more than 100 in a table (cascades
557
- and triggers count), asks for `--allow-destructive`, and deleting also for the right below.
558
- There is no undo: read the rows with `db query` first.
559
-
560
- The platform keeps no database history and no backups, so anything that destroys data
561
- (`DROP TABLE`, `DROP COLUMN`, `TRUNCATE`, `DELETE`) needs both the `--allow-destructive` flag and
562
- the right to destroy data on the key, which is off by default and only its owner turns on. It is
563
- judged by the result, not the text: a migration that dropped or emptied a table, dropped a column
564
- or deleted rows is rolled back, however the SQL was written. `BEGIN`/`COMMIT` in a migration are
565
- refused: each one already runs in its own transaction. When the refusal is about the right, the flag changes nothing: say what
566
- needs deleting and why, and let the person decide. With both in place the affected tables are
567
- dumped first (up to 50 000 rows each) and kept for 7 days; getting a dump back is a request to
568
- the person, no command does it. Check with `--dry-run`.
569
-
570
- An organization can have own database servers. `xflow db list` names the server of each project
571
- database (`platform` is the common one) and the own servers with the room used.
572
- - A new project with its database on a chosen server: `xflow init --server <name>`.
573
- - An existing one: `xflow db move --to <name> --yes`. Writes close while it
574
- copies, usually a couple of minutes; the platform switches the functions itself. It needs the
575
- right to move databases, off on the key by default: refused for the right, say what should move
576
- where and why, and the person turns it on or moves it in the «Базы данных» (Databases) section.
577
- - Buying, paying for and deleting servers are the person's, in the web interface.
578
-
579
- Code stays the same on an own server: pass `DATABASE_URL` as is, without an `ssl` option. While
580
- an own server is not running, migrations and queries say so and functions that use the database
581
- time out: tell the person instead of retrying.
582
-
583
- An own server comes tuned and guarded, so do not tune it from migrations:
584
- - Installed: `pgcrypto`, `pg_trgm`, `unaccent`, `citext`, `btree_gin`, `btree_gist`,
585
- `pg_stat_statements`. `gen_random_uuid()` is built in everywhere, `uuidv7()` on an own server.
586
- Never `uuid-ossp`. Anything else (`postgis`, `pgvector`) is a request to the person.
587
- - A statement is cut after 30 seconds, waiting for a lock after 3, a transaction left open after
588
- 30. A query that needs longer is a wrong query (a missing index, or a report that belongs in a
589
- scheduled function writing a summary table). A scheduled job that genuinely needs more runs
590
- `SET statement_timeout = '5min'` on its own connection. A database that used `citext` or
591
- another extension type cannot move back to `platform`.
592
- - A restart on a plan change takes about a minute.
593
-
594
- Calls of one project run at the same time in one process. A `Client`, even one made at module
595
- level, gets its own pooled connection for each call, so `connect()` twice is fine. Keep
596
- per-request data out of module-level variables. Session state (`SET` without `LOCAL`, temp tables,
597
- advisory locks) lasts until the call ends, and a transaction left open is rolled back: set what
598
- the call needs inside the handler. A `Client` that listens for `notification` keeps its own
599
- connection.
600
-
601
- ## File storage
602
-
603
- **Static assets of an app** (product photos, video, PDFs, big artwork) you upload yourself:
604
-
605
- ```bash
606
- xflow storage push ./media --to media # a folder, its structure kept
607
- xflow storage ls # what is there, with addresses and sizes
608
- ```
609
-
610
- `push` prints the address of every file (`/_files/<id>`) and skips what is already stored under
611
- the same path and size; `--replace` overwrites a file whose size differs and keeps its address.
612
- Use the address as is inside an app: the app's own host serves it to whoever may open the app,
613
- including anonymous visitors of a public one. Icons, fonts and small artwork stay in the
614
- repository.
615
-
616
- Deleting needs a right of its own, off by default, so `xflow storage rm` may answer that the key
617
- was not granted it. Ask the person and do not look for a way around: whatever the users of the
618
- app uploaded lives in the same folders, and there is no undo. A folder is
619
- `xflow storage rm --folder <path> --yes`.
620
-
621
- **Files that users of the app upload** go through a cloud function of your own: it asks the
622
- platform for a one-time link, the browser sends the bytes straight to storage, and a second call
623
- records the file:
624
-
625
- ```js
626
- const link = await fetch(`${process.env.XFLOW_API_URL}/api/storage/project/upload-url`, {
627
- method: 'POST',
628
- headers: {
629
- 'Content-Type': 'application/json',
630
- 'X-Server-Key': process.env.XFLOW_SERVER_KEY,
631
- },
632
- body: JSON.stringify({ fileName, fileSize, contentType, folderPath: 'invoices' }),
633
- }).then((r) => r.json())
634
- ```
635
-
636
- `confirm` takes the returned `s3Key` and answers with the file and its address; `delete` takes
637
- that same `url`. No endpoint lists files back, so write the address into a table of your own in
638
- the same call. What a visitor may do with files is decided inside that function; never send the
639
- key to the frontend.
640
-
641
- - A name already taken in that folder is refused before the link is issued; `overwrite: true`
642
- replaces the bytes and keeps the address.
643
- - 200 MB per file and the storage quota of the organization, checked again on `confirm`.
644
- - Confirm only after the PUT has finished, and send on the PUT exactly the `Content-Type` you
645
- named: the link is signed for it, a different or missing type gets 403.
646
- - Assets only: pages, scripts and executables (`html`, `js`, `exe`, …) are refused with
647
- `forbidden_type`.
648
-
649
- A refusal comes back as `{ error, code }` (`invalid_name`, `file_too_large`, `quota_exceeded`,
650
- `not_uploaded`, `duplicate_name`, `forbidden_type`, `not_found`, …): branch on `code`.
651
-
652
- ## Pages
653
-
654
- A page is a public static site at `https://<name>.xflowpage.ru`, outside projects. Anyone with
655
- the address opens it, without signing in.
656
-
657
- - `xflow pages create "Price list" ./dist` makes a page with the built site on it and prints its
658
- address: there are no empty pages. `--slug price-list` picks the name, otherwise it comes from
659
- the title with a random tail.
660
- - `xflow pages deploy <page> <folder|.zip|.html> -m "what changed"` uploads a new version.
661
- - **Both are public the moment the command finishes**: no draft, no publish step.
662
- - `xflow pages status <page>` lists the versions, `xflow pages rollback <page> <N>` puts one back
663
- in seconds; the files of the last 5 are kept.
664
- - `xflow pages rm <page> --yes` deletes the page: the address goes empty and every version is
665
- gone for good, without `--yes` the command names what goes and stops. The name stays reserved
666
- for the organization. A page put up to try something out is yours to take down when you are
667
- done: do not leave it standing.
668
- - Names are 3-40 characters. At most 100 pages per organization, 20 new and 200 uploads a day,
669
- 10 seconds between uploads of one page: batch changes into one upload.
670
- - Static files only, what the build writes (`dist`), never a folder with `package.json`. At most
671
- 5 MB zipped, 25 MB unpacked, 1000 files. Everything a page shows travels inside it: project
672
- file storage does not serve pages.
673
- - A backend for a page: see **Page or app**.
674
- - Everything in a page is readable by every visitor. A known key format gets the upload refused,
675
- anything else simply leaks.
676
- - Search engines are asked not to index pages or apps: do not promise SEO.
677
- - The tab icon is the platform's on every page: do not spend a request on a favicon of your own.
678
- - A page is deleted by whoever made it, or by the owner of the organization. Switching a page
679
- off for a while is for a person, in the platform interface.
680
-
681
- ## Organizations and keys
682
-
683
- One key per organization, stored side by side: `xflow org` lists them, `xflow org switch
684
- <name|id>` changes the active one, `xflow help org` has the precedence rules.
685
-
686
- Inside a project folder commands follow the organization the folder is bound to, whatever the
687
- active one is. `--project <id>` and `--app <id>` ignore the folder whole (`xflow help project`
688
- lists the commands that take them). A "not found" on a project you know exists usually means the
689
- key belongs to another organization: check `xflow org`; signing in to a missing organization is
690
- `xflow login`, and that needs a person with a browser.
691
-
692
- A key has its owner's level in each project. With view-only access reading works (`projects
693
- get`, logs, `db query`, `pull`), and every change fails with `Your access to this project is
694
- view-only`. That is not a bug to work around: tell the person, edit access is theirs to ask for.
695
-
696
- ## Do not
697
-
698
- - Deploy with `--force` without checking `xflow status` first.
699
- - Invent platform commands: what is not in `xflow help` does not exist.
700
- - Ask for a way to change an app's access level or issue a function key: that is the person's.
701
-
702
- ## App design
703
-
704
- - Take a block from `src/components/blocks` or a primitive from `src/components/ui` before
705
- writing your own layout; replace or delete them when the design needs something else.
706
- - Dropdowns, checkboxes, radios and dates through `Select`, `Checkbox`, `RadioGroup`,
707
- `DatePicker` from `src/components/ui`: a bare `<select>` opens the system list in Safari
708
- and Firefox, out of the app's style.
709
- - Every screen starts with a clear header; header, filters and content in one column.
710
- - Draw all four states: loading, error, empty, data. An empty screen says what appears here and
711
- offers an action.
712
- - Colour only when it communicates: status, action, error, success. Grey carries the structure.
713
- - Density over air: people scan and compare. Numbers in a column, `tabular-nums`.
714
- - Name the shape first: list, list with detail, dashboard, form, board.
715
- - Seed 5-10 believable rows in the first migration: a screen with zero rows looks unfinished.
716
- - Give the app its own page title and icon.
717
-
718
- ## Errors from a deployed app
719
-
720
- `xflow logs` prints what broke in the browser on the app addresses: unhandled errors, rejected
721
- promises and 5xx responses; in an app folder that app, in the project root every app.
722
- `xflow functions logs` prints function crashes. A person sees the same in the web interface:
723
- browser errors in the «Ошибки» (Errors) panel of the app, function crashes on the «Ошибки» tab
724
- of the function's screen. The last 200 records of each stream are kept.
725
-
726
- Run an app locally with `xflow dev` in its folder, not a bare `npm run dev`: every `/_fn/<name>`
727
- call then goes to the platform as this app, with the same callers and access as on its address,
728
- and a function someone else deployed answers at once. A bare `npm run dev` has no key, so its
729
- function calls fail. The server answers `127.0.0.1` alone, because it holds that key. A local
730
- run reports nothing to the logs.
731
-
732
- ## Environment
733
-
734
- For CI and agent runs: `XFLOW_TOKEN` replaces `xflow login`, `XFLOW_API_URL` points at another
735
- platform host. There is no `.env` from the platform: the bundle carries no tokens or addresses.
1
+ ---
2
+ name: xflow
3
+ description: Build, deploy and publish apps on the XFlow platform with the xflow CLI. Use whenever a folder has xflow.json (the project root or an app folder in apps/), and for any task that touches a project and its apps, deployment, publishing, rollback, source sync, who may open an app or call a function, sign-in inside a public app, the project database or SQL migrations, cloud functions, schedules, environment variables and secrets, file storage and uploads of photos, video or PDFs, connected accounts of external services, production errors and logs, UI built on the template components, or a public page on xflowpage.ru (a landing page, presentation or invoice for people outside the organization).
4
+ ---
5
+
6
+ # XFlow
7
+
8
+ Hosting for web apps. The code lives in an ordinary repository on the developer machine, the
9
+ CLI sends the sources, the platform builds them in a clean sandbox, serves each app at its own
10
+ address and runs its backend: one database and cloud functions per project.
11
+
12
+ No `xflow.json` in the folder or above it means it is not bound to a project yet:
13
+ `xflow projects list` names the projects of the organization with their ids, `xflow link <id>`
14
+ binds the folder to one (an empty folder gets the whole project), and `xflow init` starts a new
15
+ project with its first app. A person signed in to several organizations names the one that gets it:
16
+ `xflow init <dir> --org <name>` (ask them which one if unsure; `xflow org` lists them).
17
+
18
+ ## First rule
19
+
20
+ Check commands and flags against `xflow help` and `xflow help <command>`, not against
21
+ memory. If a command is not in the help output, it does not exist: guessing flags is
22
+ pointless. The CLI prints a hint with almost every error, read it in full, it usually
23
+ contains the fix.
24
+
25
+ The public documentation, in Russian, goes deeper than this file: its table of contents is
26
+ https://docs.getxflow.com/llms.txt, every page has a Markdown copy. Read the page you need
27
+ instead of guessing; give the person https://docs.getxflow.com when they ask how something works.
28
+
29
+ ## Keeping these instructions current
30
+
31
+ These instructions ship with xflow CLI 1.5.0, so the copy you are reading can be older than
32
+ the CLI answering your commands.
33
+
34
+ When the CLI says this file does not match it, run `xflow skills --refresh` and then **read
35
+ again the file it names**: refreshing only writes to disk, and until you re-read it you are
36
+ still working from the old rules. Do it yourself, no need to ask.
37
+
38
+ Updating the CLI is not yours. `xflow update` replaces a program shared by every project on
39
+ the machine: offer the update in your summary. The exception is a platform refusing the CLI as too old (`outdated_cli`):
40
+ nothing runs until it is updated, so say what you are doing and run it.
41
+
42
+ ## Hard rules
43
+
44
+ These mistakes cost the most because nothing fails at the moment they are made, or
45
+ the error points away from the cause. The sections below carry the details.
46
+
47
+ 1. Read environment variables literally: `process.env.API_KEY`. Destructuring
48
+ (`const { API_KEY } = process.env`), a name built from an expression, `?.` and
49
+ spreading the environment all read as no mention of the variable at all. The
50
+ build rejects them, and `xflow env check` names them before that.
51
+ 2. A value written with `xflow env set` reaches the functions on the next
52
+ `xflow deploy functions`, not at the moment it is written.
53
+ 3. Never delete a `functions/<name>/` directory unless the user asked for that
54
+ function to go. The next deploy removes it from the cloud together with its keys and
55
+ schedules, and that is final.
56
+ 4. A function an app calls needs that app in its `callers` in the root
57
+ `xflow.json`. Without it the call answers 404 `not_bound`, and a new function is not
58
+ reachable from anywhere.
59
+ 5. Every function called by an app open to anyone can be called by
60
+ anybody on the internet with curl. Write it as such, see **Your function is open to the
61
+ whole internet**.
62
+ 6. An already applied migration is never re-run, and `xflow db migrate` refuses a
63
+ name it already holds with different content. A schema change is always a new file.
64
+ 7. When `xflow db migrate` answers `db_write_locked`, or an INSERT or CREATE TABLE in a
65
+ function fails with `database size limit ... reached` (53100), the database is over its plan
66
+ size and Postgres itself refuses. Reads, updates and deletes keep working, so the fix is deleting data
67
+ (`xflow db exec` or a migration), never a rewrite of the SQL. Write comes back within the hour. The limit
68
+ is shared by the organization: `xflow db list` shows the size of each project database.
69
+ 8. Heavy media does not travel with the sources. Photos, video and PDFs go up with
70
+ `xflow storage push`, not into the repository: the archive is capped at 10 MB.
71
+
72
+ ## Projects and apps
73
+
74
+ - A project is a box: one database with its migrations, the cloud functions, secrets and
75
+ members. It has no code of its own.
76
+ - An app is code the platform builds and serves at `https://<id>--<org>.xflowpage.ru`
77
+ (`<id>` is six random characters the platform gives the app, `<org>` the name of the
78
+ organization): its own versions, its own access level. A project holds one or more apps,
79
+ and all of them use the same database and the same functions.
80
+ - A project without apps is fine (`xflow init --no-app`): its functions are workflows, woken
81
+ by a schedule, by an outside service holding a key, or by `xflow functions invoke`.
82
+ - `xflow projects get` shows the apps with their folders, addresses and access levels, and
83
+ who may call each function.
84
+
85
+ ## Folder layout
86
+
87
+ One folder per project, apps in subfolders:
88
+
89
+ clinic/
90
+ xflow.json projectId, and who may call each function
91
+ package.json dependencies of the functions
92
+ functions/<name>/index.ts cloud functions, shared by every app
93
+ migrations/0001_init.sql the one database of the project
94
+ apps/
95
+ priem/ an app: a Vite project with its own xflow.json (appId, build)
96
+ zapis/
97
+
98
+ - Two kinds of history: the project root (functions, migrations, `xflow.json`) is one, each
99
+ app is another. `apps/**` never travels with the root, the root never travels with an app.
100
+ - An app sees only its own folder when it is built. What two apps share is data and logic,
101
+ and that lives in functions. Functions never go inside an app folder: the build refuses
102
+ `functions/` there (`functions-in-app`).
103
+ - `xflow apps add <folder>` creates an app, lays the template into `apps/<folder>` and prints
104
+ its address. Never create an app folder by hand: without its `appId` it is nobody's.
105
+ `--color <color>` sets the tile the user sees in the project; a wrong one is answered with
106
+ the list of colors. Its icon and a later color change belong to the person in the web
107
+ interface.
108
+ - Rename an app folder freely: the app is its `appId`.
109
+ - Commands follow the folder you stand in: inside `apps/zapis` they mean that app, anywhere
110
+ else in the project they mean the project. `--project <id>` and `--app <id>` name them
111
+ without a folder.
112
+ - Neither `xflow.json` is edited by hand except `functions.<name>.callers` in the root one.
113
+
114
+ ## Plan limits
115
+
116
+ The organization runs on a plan with limits: apps, functions, pages, active connections,
117
+ people in the organization, database and file storage, function minutes, builds per month and at once, schedules
118
+ (one count for all projects of the organization) and how often they may run, and which access levels an app may have. Most are finite; a plan
119
+ may leave one uncapped, and then `whoami` prints `no limit` instead of a ceiling.
120
+ `xflow whoami` prints every one of them next to what is used, and the rights of your own key
121
+ with them: destroying data (a migration or `db exec`), deleting files from storage, moving a database and
122
+ linking a connected account each need a right. Reading it before a long task turns a refusal
123
+ halfway through the work into a sentence said before it starts.
124
+
125
+ - Connections are counted while active: switching an unused one off frees the seat without
126
+ deleting it.
127
+ - Function minutes are shared by the whole organization: every app, page and schedule spends
128
+ them. When they run out, every function of the organization stops (`functions_stopped`).
129
+ - An unpaid plan stops the functions at once, and five days later freezes the organization:
130
+ every command except `xflow whoami` answers `subscription_blocked`,
131
+ apps and pages show a "suspended" page. Nothing is deleted and no code fixes it: tell the
132
+ person that the owner pays the invoice in the organization settings, section «Тариф» (Plan).
133
+ - The cap on how long one function call may run is written into the function when it is
134
+ deployed, so a plan change reaches the cloud only with the next `xflow deploy functions` of
135
+ each project, in both directions.
136
+ - One function runs at most a plan-set number of calls at once: Free 5, Start 15, Business 35
137
+ per cloud zone (the cloud has three, the spread is not promised). A call over it gets 429 at
138
+ once: fan out in batches of that size, never all items of a list in parallel.
139
+
140
+ A limit refusal is not a bad request. The CLI prints a line starting with `Plan limit:`, the
141
+ API answers `code: "forbidden"` with a `limit` object (`code`, `used`, `limit`). Retrying, renaming or rewriting the code changes nothing: tell the user
142
+ what ran out and stop, only the owner lifts it. A schedule refused for running too often is one
143
+ of these too, not a bad cron string: the minimum interval comes from the plan, never guess it.
144
+
145
+ ## Deploying
146
+
147
+ 1. Change the code. In an app folder `npm run typecheck` is a two-second check, `npm run build`
148
+ a fast way to see build errors early: the platform builds again in its own sandbox.
149
+ 2. `xflow deploy functions -m "what changed"` sends the project root, checks it, applies the
150
+ new migrations, ships the functions and their callers. A migration that fails or would
151
+ destroy data stops it before any function ships: settle it with `xflow db migrate`
152
+ (`--allow-destructive`), then deploy again. `xflow db migrate` alone changes the schema
153
+ without shipping code. Every app runs the new code the moment it finishes: there is
154
+ no staging and no publish step for server code. Say so to the user.
155
+ 3. `xflow deploy apps/zapis -m "what changed"` sends and builds one app; inside `apps/zapis` a
156
+ plain `xflow deploy` does the same. In the root a plain `xflow deploy` refuses and names the
157
+ targets. The comment is required: one short line in the language the user speaks.
158
+ 4. `xflow publish` in the app folder (or with `--app <id>`) shows that build to visitors.
159
+
160
+ A change that touches data and screens goes in this order: the functions (with the migration),
161
+ then every app that shows it. `xflow deploy apps/...` warns when the root holds changes nobody
162
+ deployed.
163
+
164
+ - A build of an app is not shown to visitors until `xflow publish`. Publishing points the
165
+ address at a build and takes a second; `xflow publish <number>` (or `xflow rollback <number>`)
166
+ points it at an older kept build, and that is the rollback. The very first build of a new
167
+ app publishes itself.
168
+ - Only the app moves on publish and rollback. Functions come back with
169
+ `xflow deploy functions --revision N -m "why"` (`xflow deployments functions` lists the revisions);
170
+ `--project <id>` names the project without a folder.
171
+ - Files of the **three latest successful builds** of each app are kept, plus the live one;
172
+ `xflow deployments` marks the rest `no pages`. The history keeps 30 builds, a revision stays
173
+ while its build is in it or it is among the 10 latest. Keep anything you must not lose in
174
+ your own git repository.
175
+ - Give a person the app address the CLI printed, or the project page it printed. Name builds
176
+ by their number.
177
+ - `xflow status` says how the local copies differ from the server. A deploy rejected before
178
+ the build starts means the server holds a revision this folder has never seen: fetch it next
179
+ to yours (`xflow pull --into ./server-copy`), merge in git, deploy again. `--force` sends this
180
+ folder over it anyway; the overwritten revision is kept while it is among the last 10, and the
181
+ deploy prints the `xflow pull --revision <N>` line that brings it back. A folder with no record of the server revision (a fresh clone, a CI checkout) is
182
+ not rejected: its first deploy goes on top and says so.
183
+ - A deploy that would delete functions gone from the sources refuses until somebody agrees;
184
+ `--allow-removals` is the only way past it without a terminal. Reaching for it to get a
185
+ build running means you deleted something the user never asked you to: put the directories
186
+ back. If the removal is intended, name the functions and let the user answer.
187
+
188
+ ## Build gate
189
+
190
+ Before the sandbox starts, the platform checks the sources. Everything below blocks the build,
191
+ all violations come back together with files and lines, and a rejected attempt costs nothing.
192
+
193
+ An app:
194
+
195
+ - `package.json` with the build script named in its `xflow.json` (`npm run build` by default),
196
+ a `vite.config.*` and `vite` in dependencies. No server frameworks: `next`, `nuxt`, Remix,
197
+ `@sveltejs/kit`, `astro`.
198
+ - `index.html` in the app root with `id="root"` and the script that loads `src/main.tsx`
199
+ (`.ts`, `.jsx`, `.js` count too). Code under `src/`; root `app/`, `pages/`, `next/` are rejected.
200
+ - Keep `base` in `vite.config.js` as the template has it: the platform serves each build from
201
+ `/_b/<key>/`, and a build whose `index.html` points elsewhere is refused.
202
+ - The built app at most 15 MB unpacked, the sources at most 10 MB.
203
+ - File names in latin letters, digits, spaces and `. - _ ~` only: `логотип.png` breaks the build.
204
+ - Call functions through `xflow.functions.invoke`, never a hardcoded function address.
205
+ - No keys or tokens in the sources, no server modules (`fs`, `express`, `http`, `child_process`).
206
+ - Outside `src/components/ui` and `src/components/blocks`: no `alert()`, `confirm()`,
207
+ `prompt()` (use Dialog and Toast), no `console.log` (visitors read the console;
208
+ only crashes and 5xx reach the logs).
209
+ - A library that needs a provider (`@tanstack/react-query`, `react-redux`, `sonner`,
210
+ `react-hot-toast`, `react-dnd`) must have it mounted. A missing provider builds fine and
211
+ gives visitors a white screen.
212
+ - The platform files stay byte for byte as they arrived: `src/lib/platform-auth.ts`,
213
+ `src/contexts/platform-auth-context.tsx`, `src/hooks/use-platform-auth.ts`,
214
+ `src/utils/error-logger.ts`, `src/lib/xflow.ts`. The code keeps calling `initPlatformAuth()`
215
+ and `initErrorLogger()` and importing `index.css`, and the Tailwind
216
+ `content` globs keep covering `src/**`. A rejection names the revision to take the original
217
+ from: `xflow pull --revision N --into ./original`, then copy the file back.
218
+
219
+ The project root: function names are lowercase latin letters, digits and hyphens, up to 41
220
+ characters (`send-mail`, not `sendMail`); every name under `functions` in `xflow.json` has its
221
+ `functions/<name>/index.ts`; every caller is an app folder of this project (`unknown-caller`).
222
+
223
+ Passes with a line `Unfinished:` instead of blocking: the template's page title, no
224
+ `<link rel="icon">` in `index.html`, an `exports.access` left in a function (it does nothing).
225
+ Fix the first two before you tell the person the app is done.
226
+
227
+ ## The template is a starter kit
228
+
229
+ - `src/components/ui` and `src/components/blocks` are a starting set: change them, restyle them
230
+ or delete what you do not use. Any colors, your own color scheme, inline styles, a single
231
+ theme without dark mode: all allowed.
232
+ - The template looks like the xflow interface: warm grays, hairline controls (`ctl-solid`,
233
+ `ctl-raised`, `ctl-inset`, `ctl-select`), segments (`seg-track`, `seg-on`) and surfaces
234
+ (`surface-raised`, `surface-pop`, `surface-modal`) in `src/index.css`.
235
+ - While any template component is left, the theme token names in `:root` of `src/index.css`
236
+ and their `hsl(var(--name))` mapping in the Tailwind config stay: those components paint with
237
+ them. Values change freely; they are HSL components (`216 95% 40%`), not `#hex`. Your own
238
+ colors go under new names.
239
+ - Images and other assets: import them from `src/` (`import logo from './assets/logo.png'`)
240
+ so the build puts them next to the code. An absolute path into `public/` (`/logo.png`) goes
241
+ through the access check of the app and fails inside the xflow frame in Safari.
242
+
243
+ ## Who opens an app
244
+
245
+ A person sets this in the web interface; you cannot, and you should not ask for a way around.
246
+
247
+ | Level | Who gets in |
248
+ |---|---|
249
+ | Project members | people who have access to the project |
250
+ | Anyone with the link | anybody, no sign-in at all |
251
+
252
+ - The plan decides which levels exist: on Free an app opens only inside xflow, Start adds the
253
+ direct address and "Anyone with the link".
254
+ - At the closed level the platform signs people in, and a function receives the person in
255
+ `event.xflow.user` (`id`, `role` in the organization, `name`, `access` to the project).
256
+ Keep roles inside the app (doctor, receptionist) in your own table keyed by `user.id`.
257
+ - People outside the organization (patients, pickers, clients) are not xflow accounts: make the
258
+ app "Anyone with the link" and give it its own sign-in, see below.
259
+ - At "Anyone with the link" the platform signs nobody in: `event.xflow.user` is null for
260
+ visitors. Accounts, sign-in and who sees which rows are the code of your app, see below.
261
+ - `usePlatformAuth()` in the frontend knows the person only inside the xflow frame, and even
262
+ there it is a hint for drawing the interface, edited from the console by anyone. On the
263
+ direct address it answers `anonymous`. Guard data in the function, by `event.xflow`.
264
+
265
+ ## Which functions an app may call
266
+
267
+ The root `xflow.json` names the callers of each function:
268
+
269
+ {
270
+ "projectId": "…",
271
+ "functions": {
272
+ "list-slots": { "callers": ["zapis", "priem"] },
273
+ "book-slot": { "callers": ["zapis"] }
274
+ }
275
+ }
276
+
277
+ - A caller is an app folder of this project (`apps/zapis` is `"zapis"`); a page is never
278
+ a caller. A function without callers is left out of `functions` or given `"callers": []`,
279
+ the same thing.
280
+ - A function nobody lists has no callers: no app reaches it. That is a workflow,
281
+ run by a schedule, a key or `xflow functions invoke`.
282
+ - Callers ship with `xflow deploy functions` and come back with its `--revision N`.
283
+ - The app calls `xflow.functions.invoke('book-slot', { body })` from `src/lib/xflow.ts`. The call
284
+ goes to `/_fn/book-slot` on the app's own address: no function addresses, tokens or keys in
285
+ the bundle, nothing to rebuild when a function changes.
286
+ - A refusal throws `XFlowError` with `status` and `code`: `not_bound` (404, add the caller and
287
+ deploy functions), `not_found` (404, the function is not deployed), `login_required` and
288
+ `invalid_credential` (401, the visitor has to sign in again), `no_access`, `role_too_low`,
289
+ `functions_stopped` (403, minutes ran out or the plan is unpaid: a person settles it),
290
+ `rate_limited` (429), `unavailable` (503, retry later). Branch on `code`, never on the message.
291
+
292
+ ## Your function is open to the whole internet
293
+
294
+ A function is open when an app at "Anyone with the link" is among its callers. `xflow deploy functions` says so in a line of its own, `xflow functions list`
295
+ prints `open`, the web interface marks it.
296
+
297
+ Open means anybody can call it with curl, without your app: the browser is not a gate.
298
+ Hiding the address, checking `Origin` or `Referer`, a token baked into the bundle: all of it is
299
+ readable or forgeable and protects nothing. Write every open function as if the request came
300
+ from a stranger, because it may:
301
+
302
+ - Check every input: types, lengths, allowed values; refuse fields you do not expect. Put input
303
+ into SQL as parameters only (`$1`), never into the text.
304
+ - Return only what this caller needs: no `select *` into a response, no rows of other people,
305
+ no internal fields, no stack traces.
306
+ - Make writes safe to repeat: take a request id from the client and put a unique index on it,
307
+ so a retry or a replay changes nothing.
308
+ - Deduplicate and limit per visitor where it costs: `event.xflow.ip` is the visitor's address,
309
+ set by the platform proxy and not by the caller. The proxy caps requests per address; the
310
+ organization pays for every minute a function runs.
311
+ - A form open to strangers needs a captcha: Cloudflare Turnstile, with the token checked in the
312
+ function against `https://challenges.cloudflare.com/turnstile/v0/siteverify` and the secret
313
+ from `xflow env set`. The site key is public and stays in the source. A check in the browser
314
+ checks nothing.
315
+ - `minRole` on an open function refuses every anonymous visitor (`login_required`): use it only
316
+ where members call.
317
+
318
+ ## Sign-in in a public app
319
+
320
+ At the closed levels do none of this: the platform already knows the person.
321
+
322
+ - Passwords: store only a hash, `crypto.scrypt` from Node with a random salt per user, compare
323
+ with `crypto.timingSafeEqual`. Never log a password, never return it, never keep it in the
324
+ browser.
325
+ - Session: after sign-in the function makes a random token (`crypto.randomBytes(32)`), stores
326
+ its SHA-256 and an expiry in a table and returns the token in the response body. The app keeps
327
+ it in `localStorage` and sends it on every call in the `X-Session` header. Not a cookie: Cloud
328
+ Functions drop `Cookie` and `Set-Cookie` both ways. `localStorage` belongs to one address, a
329
+ neighbouring `*.xflowpage.ru` site does not read it.
330
+ - Any script on the page reads that token, so: an expiry of hours that each call extends,
331
+ sign-out and a password change delete the session rows, no user text rendered as HTML
332
+ (`dangerouslySetInnerHTML`), no scripts loaded from outside the build.
333
+ - Never put the token into an address (`?session=`, a link): it stays in history and logs. A file
334
+ the function makes for this person is fetched with the header and opened as a `blob:` URL.
335
+ - Not the `Authorization` header: `/_fn` replaces it with the platform's own. Nor headers named
336
+ `X-Xflow-*`, `X-Project-Pass`, `X-Server-Key`, `X-Function-Key`: the platform strips them.
337
+ - Every function that serves a signed-in visitor reads `X-Session` from `event.headers` (match
338
+ the name in any case), finds the session and filters rows by that user in SQL. A hidden button
339
+ is not access control.
340
+ - Count failed sign-ins per email and per `event.xflow.ip` in a table and slow them down.
341
+ - Never in the frontend: keys, secrets, the list of users, hashes, a role check that is the only
342
+ guard.
343
+ - The platform sends no email for your app: confirmation and reset letters need a mail provider
344
+ whose key goes into `xflow env set`.
345
+ - `xflow dev` does not carry `X-Session` and calls functions as you (a member).
346
+ Try the sign-in on the app address.
347
+
348
+ ## Page or app
349
+
350
+ - A page is finished static files at `https://<name>.xflowpage.ru`: public, live the moment it
351
+ is uploaded, no build, no publish step, no database. A landing page, a presentation, an invoice.
352
+ - An app is source the platform builds: versions and publish, access levels, a database through
353
+ functions. Anything people sign in to, enter data into or come back to.
354
+ - Keep the sources of a page outside the project folder, or list them in `.xflowignore`: the
355
+ root travels with `deploy functions`.
356
+ - A page has no backend. A form or a lookup for strangers is an app at "Anyone with the link"
357
+ (a paid plan): the platform checks every call to its functions.
358
+ - A function key on a page is allowed, and it opens that function to every visitor: an HTML
359
+ form posts to `https://fn.xflowpage.ru/<projectId>/<name>?key=...`, fetch cannot read the
360
+ answer (no CORS). Nothing guards it but the function's own checks: say so to the user.
361
+
362
+ ## Cloud functions
363
+
364
+ `functions/<name>/index.ts` in the project root exports `handler` (`index.js` and `index.mjs`
365
+ are read too), `export const handler` and `exports.handler` both work. The request arrives as
366
+ `event.httpMethod`, `event.headers`, `event.queryStringParameters` and `event.body`, a string
367
+ (`JSON.parse` it; `event.isBase64Encoded` marks a binary body). The handler returns
368
+ `{ statusCode, body }` where `body` is a JSON string, and may add `headers`.
369
+ `xflow functions list` shows status, callers, `open`, keys, last call and last error.
370
+
371
+ - Dependencies (`pg`, a mail client) go into the root `package.json`; the platform installs them
372
+ on every deploy, and a lock file next to it makes that exact.
373
+ - Code shared by functions lives in a root folder such as `lib/`, imported by relative path: each
374
+ function is bundled with what it imports. A folder in `functions/` without `index.*` is not a
375
+ function. Read `process.env` in `functions/<name>/` itself: `xflow env check` looks only there.
376
+
377
+ Keep one shape inside that string across the project: `{ success: true, data }` when it worked,
378
+ `{ success: false, error: { message, code } }` when it did not. Branch the frontend on
379
+ `error.code`, never on `error.message`.
380
+
381
+ A function whose code and variables did not change is not shipped again, and one that fails to
382
+ ship fails the whole deploy.
383
+
384
+ Debugging a deployed function is two commands: `xflow functions invoke <name>` calls it as you,
385
+ through the platform, and prints the body alone, ready for a pipe (`--data '{"a":1}'`, `--data-file
386
+ body.json`, `--method GET`; 4xx and 5xx exit non-zero; Windows PowerShell 5.1 prepends a BOM when
387
+ piping to another program, so read it with `ConvertFrom-Json` or Python's `utf-8-sig`); `xflow functions logs <name>` shows
388
+ the crashes and 5xx answers with stacks and console output, the latest 10 (`--limit N` for more).
389
+ Only failed calls are logged. Empty output does not clear a function that fails at module start,
390
+ runs over its time cap or out of memory: those never reach the logs, `invoke` shows them.
391
+
392
+ The body has to be JSON and the CLI checks it before calling. In PowerShell the double quotes
393
+ never reach the CLI (`--data '{"a":1}'` arrives as `{a:1}`): escape them (`--data '{\"a\":1}'`)
394
+ or pass a file. It bites `--payload` of a schedule the same way. A command that worked writes
395
+ nothing to stderr, so a red line there means it really failed.
396
+
397
+ ### Who is calling
398
+
399
+ The platform checks every call before your code runs and hands the answer over in `event.xflow`:
400
+
401
+ ```js
402
+ exports.handler = async (event) => {
403
+ const { caller, slug, user, ip } = event.xflow
404
+ // caller: 'app' (an app of this project), 'service' (another function of this
405
+ // project), 'external' (an outside service with a key), 'schedule',
406
+ // 'platform' (a person through xflow functions invoke or the web interface)
407
+ // slug: the address name of the calling app (<id>--<org>), null otherwise
408
+ // user: { id, role, name, access } of a signed-in person, null for anonymous
409
+ // visitors and keys. access: 'view' | 'edit' on this project
410
+ // ip: the visitor's address, null for a schedule
411
+ }
412
+ ```
413
+
414
+ Never trust an identity that arrives in the body or in a header of the request: the page lives
415
+ on someone else's computer. `event.xflow` is the only identity the platform stands behind.
416
+
417
+ Project access is separate from the role: a person who only views the project (`access:
418
+ 'view'`) still reaches every function. A function that writes refuses them:
419
+
420
+ ```js
421
+ if (event.xflow.user && event.xflow.user.access !== 'edit') {
422
+ return { statusCode: 403, body: JSON.stringify({ error: 'Read-only access' }) }
423
+ }
424
+ ```
425
+
426
+ To remember who did something, store `user.id` and `user.name` in the row: the name is never
427
+ empty, and the app has no other way to look up other people.
428
+
429
+ A function that changes data should say who may call it instead of checking the role by hand:
430
+
431
+ ```js
432
+ exports.minRole = 'developer' // 'member' | 'developer' | 'owner'
433
+ ```
434
+
435
+ The platform refuses anything below that role before your code runs; it applies to people
436
+ (apps, `functions invoke`), not to keys and schedules. `member` is the people who only
437
+ use the apps (clinic employees, managers), `developer` and `owner` build them. In the web
438
+ interface these roles are called «Просмотр» (`member`), «Редактор» (`developer`) and «Админ»
439
+ (`owner`). Without the line
440
+ every member of the project can call the function. Losing access
441
+ closes the function within a minute.
442
+
443
+ - Another function of the project: `fetch(`${process.env.XFLOW_FN_URL}/<name>`, { headers:
444
+ { 'X-Server-Key': process.env.XFLOW_SERVER_KEY } })`. The key opens the functions of its own
445
+ project only, whatever their callers.
446
+ - An outside service (a payment webhook, a bot, a CRM) calls
447
+ `https://fn.xflowpage.ru/<projectId>/<name>` (`xflow functions list` prints it) with a key of
448
+ that function in `X-Function-Key` or `?key=`. Keys are issued by a person on the function's
449
+ screen in the web interface, never by you: ask the user. A function holds at most two keys,
450
+ the second one to replace the first without downtime.
451
+ - `exports.access` does nothing any more: who may call is `callers`.
452
+
453
+ ## Secrets and connected accounts
454
+
455
+ Keys and passwords live on the platform, not in the repository: `xflow env set SMTP_PASSWORD=…`
456
+ writes one, `xflow env` lists the names, `xflow env check` names the variables your functions
457
+ read but the platform does not have. Values never come back out: the only place they exist is
458
+ inside the running function. Apps get no variables at all.
459
+
460
+ A variable goes to the whole organization unless you say otherwise: `--scope project` keeps it
461
+ to this project alone, `--scope organization` is the default, and a third word is refused.
462
+ Pick the narrow one for anything that belongs to one project. These commands see only what
463
+ this project can see, so `env rm` reports a variable of another project missing even though
464
+ names are unique within the organization.
465
+
466
+ `DATABASE_URL` and every name starting with `XFLOW` are filled in by the platform: writing them
467
+ is refused.
468
+
469
+ Some variables come from a connected account instead of from you. Credentials of an account
470
+ linked to the project show up in `xflow env` marked read-only, under a prefix chosen at link
471
+ time (`YANDEX_DIRECT_TOKEN`, `YANDEX_DIRECT_CLIENT_LOGIN`): read them like any other variable.
472
+ If calls to that service start failing on authorisation, `xflow status` says whether the token
473
+ is merely expiring (any deploy of the functions renews it) or the account was disconnected on
474
+ the provider's side, which only a human can reconnect.
475
+
476
+ `xflow connections` lists those accounts: the ones linked to this project, with the alias and
477
+ the state of the access, and the ones the organization has but this project does not use yet,
478
+ marked `available, not linked`. Check it before telling anyone a service is unavailable.
479
+
480
+ `xflow connections link "Яндекс Метрика" --as YANDEX_METRIKA` is that link and
481
+ `xflow connections unlink YANDEX_METRIKA` undoes it; `xflow help connections` has the naming
482
+ rules. In the project folder unlink refuses while a function still reads one of the variables,
483
+ naming those functions, so read that list before reaching for `--yes`.
484
+
485
+ Linking needs the `connections:link` right on the key, and only accounts granted to the owner
486
+ of the key personally can be linked at all. A key cannot grant it to itself: ask the person.
487
+ Connecting a new account and switching one off stay with a person too.
488
+
489
+ ### Asking an API what it returns
490
+
491
+ ```
492
+ xflow connections call WB /api/v1/supplier/stocks?dateFrom=2026-09-01
493
+ xflow connections call "Яндекс Метрика" /management/v1/counters
494
+ xflow connections call OZON /v1/product/list --method POST --data '{}' \
495
+ --header '{"Client-Id":"{CLIENT_ID}"}'
496
+ ```
497
+
498
+ The platform attaches the credentials and makes the request itself: no deploy, and the key never
499
+ reaches you. A linked account is called by its alias, an `available, not linked` one by its
500
+ name: linking first is not needed to look. Calling is looking, not wiring: to use the account
501
+ in code, link it and deploy functions.
502
+
503
+ `{NAME}` in the path or in a header value is filled in from the fields of the connection. Take
504
+ the names from `xflow connections`, which prints them in braces: an invented name is left in the
505
+ text and the request goes out anyway, into somebody's live account. Ask for the shape, not the
506
+ volume: one day and `limit=1`; `--json | jq '.response.body | keys'` gives the field names
507
+ without the body entering your context. `POST` and `DELETE` change things in a live account and
508
+ nothing undoes that: ask the person first when the endpoint is not clearly a read.
509
+
510
+ ## Schedules
511
+
512
+ `xflow schedules set report "0 3 ? * * *"` runs a function daily at 03:00. Six fields, UTC,
513
+ and exactly one of day-of-month / day-of-week must be `?`. A run reaches the handler as a POST
514
+ with `event.xflow.caller === 'schedule'`, and `--payload '{"mode":"full"}'` (or
515
+ `--payload-file body.json`) is its body. The function has to be deployed first.
516
+ A schedule is the function plus its cron: `set` with the same pair only changes the payload, a
517
+ new cron is one more schedule next to the old one. The plan caps the count for the whole
518
+ organization, so take the old one off with `xflow schedules rm report "<old cron>"`.
519
+
520
+ ```
521
+ xflow env set SMTP_PASSWORD=... # secrets first: values ride the next deploy
522
+ # write functions/report/index.ts, reading process.env.SMTP_PASSWORD literally
523
+ xflow deploy functions -m "Nightly report"
524
+ xflow schedules set report "0 3 ? * * *" --payload '{"mode":"full"}'
525
+ xflow functions invoke report # run it once
526
+ xflow functions logs report # crashes of real runs
527
+ ```
528
+
529
+ ## Database
530
+
531
+ Schema changes are files: `migrations/0001_init.sql`, `migrations/0002_orders.sql` in the
532
+ project root, applied in filename order by `xflow db migrate` from any folder of the project.
533
+ `xflow db status` shows what is applied and what waits. Never edit an applied file, write a new
534
+ migration instead. Every project has exactly one database of its own, shared by all its apps and
535
+ functions.
536
+
537
+ The browser never reaches the database directly. The app reads and writes through a cloud
538
+ function, and inside the handler the connection string is already there:
539
+
540
+ ```js
541
+ const { Client } = require('pg')
542
+ const db = new Client({ connectionString: process.env.DATABASE_URL })
543
+ ```
544
+
545
+ The platform passes `DATABASE_URL` only to functions that mention it and sets the project schema
546
+ on every connection, so plain table names (`select * from tasks`) hit your project.
547
+
548
+ `migrations/` says what you did; `xflow db schema [table]` says what is in the database now, and
549
+ `xflow db query 'select ...'` reads it inside a READ ONLY transaction (as many rows as its
550
+ own `limit` asks, 50 without one, 300 at most; `--json` prints long values whole). Single quotes hold in PowerShell, bash
551
+ and zsh, cmd.exe wants double ones; a query with quotes of its own goes in a `.sql` file outside
552
+ the project, `xflow db query ../q.sql`.
553
+
554
+ A one-off data fix is `xflow db exec 'update ...'` (or `../fix.sql`), not a migration: one
555
+ INSERT, UPDATE, DELETE or MERGE, saved at once, never re-run, no trace in the migration history.
556
+ Schema changes are refused there. Deleting rows, or updating more than 100 in a table (cascades
557
+ and triggers count), asks for `--allow-destructive`, and deleting also for the right below.
558
+ There is no undo: read the rows with `db query` first.
559
+
560
+ The platform keeps no database history and no backups, so anything that destroys data
561
+ (`DROP TABLE`, `DROP COLUMN`, `TRUNCATE`, `DELETE`) needs both the `--allow-destructive` flag and
562
+ the right to destroy data on the key, which is off by default and only its owner turns on. It is
563
+ judged by the result, not the text: a migration that dropped or emptied a table, dropped a column
564
+ or deleted rows is rolled back, however the SQL was written. `BEGIN`/`COMMIT` in a migration are
565
+ refused: each one already runs in its own transaction. When the refusal is about the right, the flag changes nothing: say what
566
+ needs deleting and why, and let the person decide. With both in place the affected tables are
567
+ dumped first (up to 50 000 rows each) and kept for 7 days; getting a dump back is a request to
568
+ the person, no command does it. Check with `--dry-run`.
569
+
570
+ Pass `DATABASE_URL` as is, without an `ssl` option. The database is PostgreSQL 18, so do not
571
+ tune it from migrations:
572
+ - Installed: `pg_trgm`. `gen_random_uuid()` and `uuidv7()` are built in. Never `uuid-ossp`.
573
+ Anything else (`postgis`, `pgvector`) is a request to the person.
574
+ - A statement is cut after 30 seconds, waiting for a lock after 10, a transaction left open after
575
+ 60. A query that needs longer is a wrong query (a missing index, or a report that belongs in a
576
+ scheduled function writing a summary table).
577
+
578
+ Calls of one project run at the same time in one process. A `Client`, even one made at module
579
+ level, gets its own pooled connection for each call, so `connect()` twice is fine. Keep
580
+ per-request data out of module-level variables. Session state (`SET` without `LOCAL`, temp tables,
581
+ advisory locks) lasts until the call ends, and a transaction left open is rolled back: set what
582
+ the call needs inside the handler. A `Client` that listens for `notification` keeps its own
583
+ connection.
584
+
585
+ ## File storage
586
+
587
+ **Static assets of an app** (product photos, video, PDFs, big artwork) you upload yourself:
588
+
589
+ ```bash
590
+ xflow storage push ./media --to media # a folder, its structure kept
591
+ xflow storage ls # what is there, with addresses and sizes
592
+ ```
593
+
594
+ `push` prints the address of every file (`/_files/<id>`) and skips what is already stored under
595
+ the same path and size; `--replace` overwrites a file whose size differs and keeps its address.
596
+ Use the address as is inside an app: the app's own host serves it to whoever may open the app,
597
+ including anonymous visitors of a public one. Icons, fonts and small artwork stay in the
598
+ repository.
599
+
600
+ Deleting needs a right of its own, off by default, so `xflow storage rm` may answer that the key
601
+ was not granted it. Ask the person and do not look for a way around: whatever the users of the
602
+ app uploaded lives in the same folders, and there is no undo. A folder is
603
+ `xflow storage rm --folder <path> --yes`.
604
+
605
+ **Files that users of the app upload** go through a cloud function of your own: it asks the
606
+ platform for a one-time link, the browser sends the bytes straight to storage, and a second call
607
+ records the file:
608
+
609
+ ```js
610
+ const link = await fetch(`${process.env.XFLOW_API_URL}/api/storage/project/upload-url`, {
611
+ method: 'POST',
612
+ headers: {
613
+ 'Content-Type': 'application/json',
614
+ 'X-Server-Key': process.env.XFLOW_SERVER_KEY,
615
+ },
616
+ body: JSON.stringify({ fileName, fileSize, contentType, folderPath: 'invoices' }),
617
+ }).then((r) => r.json())
618
+ ```
619
+
620
+ `confirm` takes the returned `s3Key` and answers with the file and its address; `delete` takes
621
+ that same `url`. No endpoint lists files back, so write the address into a table of your own in
622
+ the same call. What a visitor may do with files is decided inside that function; never send the
623
+ key to the frontend.
624
+
625
+ - A name already taken in that folder is refused before the link is issued; `overwrite: true`
626
+ replaces the bytes and keeps the address.
627
+ - 200 MB per file and the storage quota of the organization, checked again on `confirm`.
628
+ - Confirm only after the PUT has finished, and send on the PUT exactly the `Content-Type` you
629
+ named: the link is signed for it, a different or missing type gets 403.
630
+ - Assets only: pages, scripts and executables (`html`, `js`, `exe`, …) are refused with
631
+ `forbidden_type`.
632
+
633
+ A refusal comes back as `{ error, code }` (`invalid_name`, `file_too_large`, `quota_exceeded`,
634
+ `not_uploaded`, `duplicate_name`, `forbidden_type`, `not_found`, …): branch on `code`.
635
+
636
+ ## Pages
637
+
638
+ A page is a public static site at `https://<name>.xflowpage.ru`, outside projects. Anyone with
639
+ the address opens it, without signing in.
640
+
641
+ - `xflow pages create "Price list" ./dist` makes a page with the built site on it and prints its
642
+ address: there are no empty pages. `--slug price-list` picks the name, otherwise it comes from
643
+ the title with a random tail.
644
+ - `xflow pages deploy <page> <folder|.zip|.html> -m "what changed"` uploads a new version.
645
+ - **Both are public the moment the command finishes**: no draft, no publish step.
646
+ - `xflow pages status <page>` lists the versions, `xflow pages rollback <page> <N>` puts one back
647
+ in seconds; the files of the last 5 are kept.
648
+ - `xflow pages rm <page> --yes` deletes the page: the address goes empty and every version is
649
+ gone for good, without `--yes` the command names what goes and stops. The name stays reserved
650
+ for the organization. A page put up to try something out is yours to take down when you are
651
+ done: do not leave it standing.
652
+ - Names are 3-40 characters. At most 100 pages per organization, 20 new and 200 uploads a day,
653
+ 10 seconds between uploads of one page: batch changes into one upload.
654
+ - Static files only, what the build writes (`dist`), never a folder with `package.json`. At most
655
+ 5 MB zipped, 25 MB unpacked, 1000 files. Everything a page shows travels inside it: project
656
+ file storage does not serve pages.
657
+ - A backend for a page: see **Page or app**.
658
+ - Everything in a page is readable by every visitor. A known key format gets the upload refused,
659
+ anything else simply leaks.
660
+ - Search engines are asked not to index pages or apps: do not promise SEO.
661
+ - The tab icon is the platform's on every page: do not spend a request on a favicon of your own.
662
+ - A page is deleted by whoever made it, or by the owner of the organization. Switching a page
663
+ off for a while is for a person, in the platform interface.
664
+
665
+ ## Organizations and keys
666
+
667
+ One key per organization, stored side by side: `xflow org` lists them, `xflow org switch
668
+ <name|id>` changes the active one, `xflow help org` has the precedence rules.
669
+
670
+ Inside a project folder commands follow the organization the folder is bound to, whatever the
671
+ active one is. `--project <id>` and `--app <id>` ignore the folder whole (`xflow help project`
672
+ lists the commands that take them). A "not found" on a project you know exists usually means the
673
+ key belongs to another organization: check `xflow org`; signing in to a missing organization is
674
+ `xflow login`, and that needs a person with a browser.
675
+
676
+ A key has its owner's level in each project. With view-only access reading works (`projects
677
+ get`, logs, `db query`, `pull`), and every change fails with `Your access to this project is
678
+ view-only`. That is not a bug to work around: tell the person, edit access is theirs to ask for.
679
+
680
+ ## Do not
681
+
682
+ - Deploy with `--force` without checking `xflow status` first.
683
+ - Invent platform commands: what is not in `xflow help` does not exist.
684
+ - Ask for a way to change an app's access level or issue a function key: that is the person's.
685
+
686
+ ## App design
687
+
688
+ - Take a block from `src/components/blocks` or a primitive from `src/components/ui` before
689
+ writing your own layout; replace or delete them when the design needs something else.
690
+ - Dropdowns, checkboxes, radios and dates through `Select`, `Checkbox`, `RadioGroup`,
691
+ `DatePicker` from `src/components/ui`: a bare `<select>` opens the system list in Safari
692
+ and Firefox, out of the app's style.
693
+ - Every screen starts with a clear header; header, filters and content in one column.
694
+ - Draw all four states: loading, error, empty, data. An empty screen says what appears here and
695
+ offers an action.
696
+ - Colour only when it communicates: status, action, error, success. Grey carries the structure.
697
+ - Density over air: people scan and compare. Numbers in a column, `tabular-nums`.
698
+ - Name the shape first: list, list with detail, dashboard, form, board.
699
+ - Seed 5-10 believable rows in the first migration: a screen with zero rows looks unfinished.
700
+ - Give the app its own page title and icon.
701
+
702
+ ## Errors from a deployed app
703
+
704
+ `xflow logs` prints what broke in the browser on the app addresses: unhandled errors, rejected
705
+ promises and 5xx responses; in an app folder that app, in the project root every app.
706
+ `xflow functions logs` prints function crashes. A person sees the same in the web interface:
707
+ browser errors in the «Ошибки» (Errors) panel of the app, function crashes on the «Ошибки» tab
708
+ of the function's screen. The last 200 records of each stream are kept.
709
+
710
+ Run an app locally with `xflow dev` in its folder, not a bare `npm run dev`: every `/_fn/<name>`
711
+ call then goes to the platform as this app, with the same callers and access as on its address,
712
+ and a function someone else deployed answers at once. A bare `npm run dev` has no key, so its
713
+ function calls fail. The server answers `127.0.0.1` alone, because it holds that key. A local
714
+ run reports nothing to the logs.
715
+
716
+ ## Environment
717
+
718
+ For CI and agent runs: `XFLOW_TOKEN` replaces `xflow login`, `XFLOW_API_URL` points at another
719
+ platform host. There is no `.env` from the platform: the bundle carries no tokens or addresses.