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