@xanots/sdk 0.0.12 → 0.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -0
- package/README.md +5 -3
- package/dist/.build-fingerprint +1 -1
- package/dist/{agent-file-refresh-GQWAAOBV.js → agent-file-refresh-2LZ2YRFZ.js} +3 -3
- package/dist/bin.js +3 -3
- package/dist/{chunk-GSP2BY4F.js → chunk-BYQHCCYU.js} +1 -1
- package/dist/{chunk-AG5GCZDD.js → chunk-CII2TOE4.js} +2 -2
- package/dist/{chunk-2VTJSI6X.js → chunk-F3MRG7NI.js} +2 -2
- package/dist/{chunk-XT3XQ4PF.js → chunk-LISUHLWI.js} +11 -11
- package/dist/{chunk-QYSQ3UDO.js → chunk-MEFMTICH.js} +76 -1
- package/dist/{chunk-VPAWRBK5.js → chunk-ORZINVGQ.js} +33 -9
- package/dist/{chunk-VRNZ2NVV.js → chunk-PJNWOZMT.js} +2 -2
- package/dist/{chunk-PLE5QQOZ.js → chunk-UQMMFW32.js} +5 -5
- package/dist/{chunk-ELK7UALJ.js → chunk-UXPDQFG2.js} +2 -2
- package/dist/{chunk-VK26K7AY.js → chunk-XBIFQWZM.js} +2 -2
- package/dist/cli.js +2 -2
- package/dist/{codegen-command-Y2SPMAUW.js → codegen-command-5A6FVKUA.js} +7 -7
- package/dist/{deploy-command-XHS5PKPV.js → deploy-command-VBB7JYXH.js} +4 -4
- package/dist/index.d.ts +2 -2
- package/dist/index.js +3 -3
- package/dist/{init-command-23FFNUFT.js → init-command-SIJUH2DD.js} +5 -5
- package/dist/internal.d.ts +2 -2
- package/dist/internal.js +362 -264
- package/dist/{lock-commands-WCRC56ME.js → lock-commands-4TX3BONI.js} +3 -3
- package/dist/node.d.ts +2 -2
- package/dist/node.js +4 -4
- package/dist/{preflight-command-TZWPHBXY.js → preflight-command-MTYGPNVT.js} +4 -4
- package/dist/{release-command-WEFYRTCI.js → release-command-NXCPQDFF.js} +6 -6
- package/dist/{routes-manifest-5ZFKUQWA.js → routes-manifest-MN6XBYRE.js} +24 -13
- package/dist/{store-DAnUIi1T.d.ts → store-9Psd0jiF.d.ts} +34 -16
- package/dist/{upgrade-command-GYEIMJBG.js → upgrade-command-GSH3M3N6.js} +6 -6
- package/dist/{workspace-command-2ZTGT26W.js → workspace-command-XUOPLVQ4.js} +7 -7
- package/guides/README.md +1 -1
- package/guides/coverage.md +3 -2
- package/guides/typed-frontend.md +20 -3
- package/llms/client.md +44 -0
- package/llms/errors.md +33 -0
- package/llms/fields.md +26 -1
- package/llms/filters.md +4 -8
- package/llms/kinds-agent-mcp.md +1 -0
- package/llms/kinds-core.md +16 -2
- package/llms/kinds-knowledge.md +1 -1
- package/llms/kinds-realtime.md +3 -3
- package/llms/lambda.md +1 -1
- package/llms/legacy.md +1 -1
- package/llms/object-kinds.md +2 -2
- package/llms/statements-calls.md +25 -4
- package/llms/statements-catalog.md +1 -1
- package/llms/statements-runtime.md +20 -5
- package/llms/tests.md +3 -3
- package/llms/triggers.md +14 -2
- package/llms/values.md +2 -2
- package/llms-full.txt +362 -270
- package/llms.txt +163 -234
- package/manifest.json +4 -4
- package/package.json +1 -1
package/llms-full.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# xanots v0.0.
|
|
1
|
+
# xanots v0.0.14
|
|
2
2
|
|
|
3
3
|
> TypeScript SDK that compiles a typed Xano workspace into the importable packageExport JSON bundle.
|
|
4
4
|
|
|
@@ -15,11 +15,11 @@ TAGGED value — `ref("x")` a stack variable, `inp("x")` an input, `auth("id")`
|
|
|
15
15
|
caller, `c.*` a constant — resolved at request time; JS operators over them do not
|
|
16
16
|
compute (see Gotchas). Requests share no memory — state persists in tables or redis.
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
Authorable: statement surfaces 214/214, filters 226 (226 typed).
|
|
19
19
|
Not authorable here: branch, market_item, realtime_channel, run.job, run.service, tablemap — these cannot be authored and do not survive a pull; reasons in `coverage.objectKinds.unmodeled`.
|
|
20
20
|
|
|
21
21
|
This file is the whole always-read surface: the mental model, the deploy contract,
|
|
22
|
-
every gotcha, and control flow. Per-surface detail lives in the topic files listed
|
|
22
|
+
every cross-cutting gotcha, and control flow. Per-surface detail lives in the topic files listed
|
|
23
23
|
below — open the one whose condition matches the task, skip the rest. For
|
|
24
24
|
exhaustive per-entry detail in NEITHER — a statement's field schema with engine
|
|
25
25
|
defaults, a filter's full argument list, the `storedName` mapping — do a TARGETED
|
|
@@ -37,23 +37,25 @@ Paths are relative to this file (`node_modules/@xanots/sdk/` once installed), so
|
|
|
37
37
|
plain file read resolves them at the version you have.
|
|
38
38
|
`llms-full.txt` is everything concatenated — one fetch for a reader that cannot open files.
|
|
39
39
|
|
|
40
|
-
- [Object kinds](llms/object-kinds.md): Read when deciding WHAT to build — every authorable primitive
|
|
40
|
+
- [Object kinds](llms/object-kinds.md): Read when deciding WHAT to build — every authorable primitive, what each is, and which factory + register method builds it. Also when `register*` will not typecheck an array built by `.flatMap()`/`.concat()`.
|
|
41
41
|
- [Core def shapes](llms/kinds-core.md): Read when authoring a function, query, api group, task, workflow test, middleware, or tool — and for the `response` and `expr` shapes every one of them uses.
|
|
42
|
-
- [
|
|
42
|
+
- [Consuming defs from a client](llms/client.md): Read when a frontend imports a def (`getPath()`/`InferResponse`) or calls the deployed backend — what the import costs, `window.XANO_HOST`, local dev, file URLs, and a Node spot-check.
|
|
43
|
+
- [Error index](llms/errors.md): Read when a request, test, build, or pull fails with a message you did not write — the string, its cause, and where the fix is.
|
|
44
|
+
- [Saved unit tests, assertions, and mocks](llms/tests.md): Read when authoring a `workflowTest()` stack, when a query/function/middleware carries `tests`, when a statement needs a `mock`, or when running a deployed environment's tests.
|
|
43
45
|
- [Agent and MCP def shapes](llms/kinds-agent-mcp.md): Read when the workspace defines an `agent()` or an `mcpServer()`.
|
|
44
|
-
- [Knowledge def shape](llms/kinds-knowledge.md): Read when the workspace defines a `knowledge()` item
|
|
46
|
+
- [Knowledge def shape](llms/kinds-knowledge.md): Read when the workspace defines a `knowledge()` item for its AI agents.
|
|
45
47
|
- [Realtime def shapes](llms/kinds-realtime.md): Read when the workspace defines a `realtimeServer()`, `realtimeChannel()`, or `realtimeMessage()` handler.
|
|
46
48
|
- [Triggers](llms/triggers.md): Read when authoring any trigger. A trigger's `stack` is a callback rather than the plain array every other kind takes, so the shape does not carry over.
|
|
47
49
|
- [Array and database statements](llms/statements-data.md): Read when the stack reads or writes rows (`s.db.*`), or transforms an array in place (`s.array.map`, `s.array.union`).
|
|
48
|
-
- [Statement runtime behavior](llms/statements-runtime.md): Read when you need to know what a statement's `as:` output
|
|
50
|
+
- [Statement runtime behavior](llms/statements-runtime.md): Read when you need to know what a statement's `as:` output holds, or why a bound variable is not the shape expected.
|
|
49
51
|
- [Auth, cross-object calls, and microservices](llms/statements-calls.md): Read when the stack authenticates (the signup/login/token recipe is here), calls another object (`s.function.run`, `s.api.request`, `s.tool.call`), sends email (`s.util.send_email`), or reaches a microservice.
|
|
50
52
|
- [Value catalog](llms/values.md): Read when you need a literal, a reference, or a tag you have not used before — `c.*`, `ref`, `inp`, `auth`, `col`, and what each one encodes to.
|
|
51
|
-
- [Column and input types](llms/fields.md): Read when declaring a table column (`f.*`) or a function/query input (`input.*`) — a type's options and
|
|
53
|
+
- [Column and input types](llms/fields.md): Read when declaring a table column (`f.*`) or a function/query input (`input.*`) — a type's options and methods, and the `s.precondition` error/status contract. Also `table({ seed })` rows and `use_xdo`.
|
|
52
54
|
- [Filter catalog](llms/filters.md): Read when piping a value through `fl.*` — the full catalog with each filter's argument types.
|
|
53
|
-
- [Lambda bodies (JavaScript)](llms/lambda.md): Read when writing a JavaScript body, or weighing whether to reach for one at all — `lam.fn`, `fl.lambda`, `fl.reduce`, `s.lambda
|
|
55
|
+
- [Lambda bodies (JavaScript)](llms/lambda.md): Read when writing a JavaScript body, or weighing whether to reach for one at all — `lam.fn`, `fl.lambda`, `fl.reduce`, `s.lambda`; each surface binds a different set of identifiers.
|
|
54
56
|
- [Lock file](llms/lock.md): Read when a `xano.lock` exists or should — renaming/pruning/importing identities, seeding the lock programmatically, or asking which commands write it.
|
|
55
|
-
- [Legacy paradigms and retired statements](llms/legacy.md): Read when the code was PULLED from an existing Xano instance
|
|
56
|
-
- [Statement catalog](llms/statements-catalog.md): Read for the field signature of a specific statement — every surface, grouped by `s.*` namespace.
|
|
57
|
+
- [Legacy paradigms and retired statements](llms/legacy.md): Read when the code was PULLED from an existing Xano instance — how a codegen'd tree reads, the shapes in it that must not be "fixed", and any `raw({ name: "mvp:…" })`, `realtimeTrigger()`, or name the catalogs do not list.
|
|
58
|
+
- [Statement catalog](llms/statements-catalog.md): Read for the field signature of a specific statement — every surface, grouped by `s.*` namespace.
|
|
57
59
|
|
|
58
60
|
## Quickstart
|
|
59
61
|
|
|
@@ -125,6 +127,8 @@ operand, a `ref()` nothing binds). Each has a legitimate use, so each only warns
|
|
|
125
127
|
but nothing fails on a message no one reads, so in CI and in unattended agent builds
|
|
126
128
|
pass `--strict` (`emitBundle(app, { strict: true })` / `app.export({ strict: true })`):
|
|
127
129
|
every warning becomes a hard failure. Same bundle bytes either way.
|
|
130
|
+
Before calling the work done: `npm run typecheck`, `xanots export <entry> --strict`,
|
|
131
|
+
`xanots deploy <entry>`, then `xanots test run-all` against what deployed.
|
|
128
132
|
|
|
129
133
|
Identity: object guids derive from `(type, name)` — a query's from `(api group,
|
|
130
134
|
verb, name)` — so renames change identity.
|
|
@@ -170,90 +174,89 @@ production workspace, but confirm with the user before the first run.
|
|
|
170
174
|
|
|
171
175
|
**Frontend wiring.** `--static <dir>` injects the DEPLOYED env's backend URL as
|
|
172
176
|
`window.XANO_HOST` into EVERY html document in the build, before the app bundle runs,
|
|
173
|
-
so the frontend needs no rebuild to target an env.
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
fallback:
|
|
177
|
-
const HOST = (typeof window !== 'undefined' && window.XANO_HOST) || import.meta.env.VITE_XANO_HOST;
|
|
178
|
-
In LOCAL DEV there is no injected global, so the fallback is what answers: set
|
|
179
|
-
`VITE_XANO_HOST` in a `.env.local` beside `.env.example` at the PROJECT ROOT. The
|
|
180
|
-
scaffold's vite config sets `envDir` there (its `root` is `frontend/`, and Vite
|
|
181
|
-
resolves `.env` files against `root`) — without it the var reads as undefined, the
|
|
182
|
-
host falls back to '', and every call 404s off the dev server.
|
|
183
|
-
⚠ It is INJECTED in bracket form — `window["XANO_HOST"]="…"` — so verifying a deploy
|
|
184
|
-
by grepping `window.XANO_HOST` matches nothing and reads as a failed inject. Grep the
|
|
185
|
-
bare `XANO_HOST` token.
|
|
186
|
-
⚠ `xanots preflight` ignores the deploy login and reads `XANO_VALIDATE_INSTANCE` /
|
|
187
|
-
`XANO_VALIDATE_TOKEN` (+ optional `XANO_VALIDATE_WORKSPACE_ID`) from the environment.
|
|
188
|
-
**Displaying a stored file.** A file column comes back as `{ path, name, type, size,
|
|
189
|
-
meta, access, url }`. ⚠ Do NOT use its `url`: on a tenant-scoped environment that field
|
|
190
|
-
addresses the instance host WITHOUT the `/tenant/<name>` segment and 404s, silently —
|
|
191
|
-
as a broken `<img>`, with every API assertion still passing. Build the URL from `path`
|
|
192
|
-
instead: `fileUrl(row.avatar, HOST)` (exported from `@xanots/sdk`) returns `null` for
|
|
193
|
-
an absent file and is correct on an ephemeral and an instance workspace alike.
|
|
194
|
-
⚠ A static host serves these files verbatim, so everything injected is PUBLIC — base
|
|
177
|
+
so the frontend needs no rebuild to target an env. How to read it, local dev, verifying
|
|
178
|
+
the inject, and displaying a stored file: `llms/client.md`.
|
|
179
|
+
⚠ A static host serves its files verbatim, so everything injected is PUBLIC — base
|
|
195
180
|
URLs and publishable keys only, never secrets. Secrets go in backend env, read
|
|
196
181
|
server-side via `env(name)`.
|
|
182
|
+
⚠ `xanots preflight` ignores the deploy login and reads `XANO_VALIDATE_INSTANCE` /
|
|
183
|
+
`XANO_VALIDATE_TOKEN` (+ optional `XANO_VALIDATE_WORKSPACE_ID`) from the environment.
|
|
197
184
|
|
|
198
185
|
**Full CLI surface:** `xanots <command> --help` lists every command, flag, and
|
|
199
186
|
default; the shipped `manifest.json` carries the same in its `cli` array. This doc
|
|
200
187
|
does not duplicate it — it covers what you must know to AUTHOR a workspace.
|
|
201
|
-
**
|
|
202
|
-
(`
|
|
203
|
-
flat factory aliases (`dbAdd`, `dbQuery`, `setVar`, `mathAdd`, …) are exported
|
|
204
|
-
and identical in output; prefer `s.*` in new code so examples stay consistent.
|
|
188
|
+
**Style:** reach statements through the `s` namespace (`s.db.add`, `s.math.add`, …).
|
|
189
|
+
The flat aliases (`dbAdd`, `setVar`, …) are identical in output; prefer `s.*`.
|
|
205
190
|
|
|
206
191
|
## Gotchas
|
|
207
192
|
|
|
208
193
|
Non-obvious authoring rules:
|
|
209
194
|
|
|
195
|
+
### Values and references
|
|
196
|
+
|
|
210
197
|
- **No callback builder.** Flat def-objects + `register*`, not
|
|
211
198
|
`workspace(w => w.table(...))`. `workspace(name)` returns a named `new Xano()`;
|
|
212
199
|
tables are `table({ schema: { col: f.text() } })`.
|
|
213
|
-
- **Foreign key is `f.tableRef(table)`, not `ref`.** `ref(name)` references a
|
|
214
|
-
stack variable (a value); `f.tableRef` is the column constructor.
|
|
215
200
|
- **Reference-helper picker:** `ref` = stack var (`as:` output), `inp` = input,
|
|
216
201
|
`col` = table column (in `db.query` `where`), `auth("id")` = the caller,
|
|
217
202
|
`c.*` = a constant. Pick by what you're pointing at.
|
|
203
|
+
- **Foreign key is `f.tableRef(table)`, not `ref`.** `ref(name)` references a
|
|
204
|
+
stack variable (a value); `f.tableRef` is the column constructor.
|
|
218
205
|
- **Tagged values are DATA — a JS template literal cannot compose them.** `${ref(...)}`
|
|
219
206
|
(or `"a" + ref(...)`) stringifies the tag object at BUILD time: ``c.text(`Hi ${ref("u.name")}`)``
|
|
220
207
|
type-checks and encodes the literal text `Hi [object Object]`, served verbatim.
|
|
221
208
|
`export()` warns; `--strict` fails. Compose at RUNTIME:
|
|
222
209
|
`withFilters(c.text("Hi "), fl.concat(ref("u.name")))`, an `obj({...})`/record member,
|
|
223
210
|
or `c.expression('"Hi, " ~ $var.u.name')`.
|
|
224
|
-
-
|
|
225
|
-
|
|
226
|
-
the
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
A
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
`
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
211
|
+
- **Declare inputs with `input.<type>()`, read them with `inp("name")`.** `inp()`
|
|
212
|
+
resolves ONLY against this def's own `input` block — a value produced earlier in
|
|
213
|
+
the stack is `ref("var.field")`, not `inp("field")`. An undeclared name fails at
|
|
214
|
+
runtime with `Unable to locate input` (`export()` warns).
|
|
215
|
+
- **`get_input`/`get_raw_input` read the whole payload**, not one named input
|
|
216
|
+
(args are `{ as?, encoding?, excludeMiddleware? }` — no `name`). For a single
|
|
217
|
+
input use `inp("name")`.
|
|
218
|
+
- **To match every row, omit `where` — never pass a constant.** `where: c.bool(true)` is
|
|
219
|
+
not "no filter": a bare scalar literal states no condition and the engine reads the
|
|
220
|
+
resulting `context.search` as garbage, so it throws. An absent `where` is how "every
|
|
221
|
+
row" is spelled. A raw `Value` `where` stays the escape hatch for a clause built
|
|
222
|
+
elsewhere — `inp("clause")`, `ref("built_where")`, or `c.text("id > 0")`.
|
|
223
|
+
|
|
224
|
+
### Tables and columns
|
|
225
|
+
|
|
226
|
+
- **System columns are auto-injected.** `id` + `created_at` are prepended to
|
|
227
|
+
every table (`system: true` by default); declaring them by hand is redundant.
|
|
228
|
+
`id` is an `int` PK by default; pass `idType: "uuid"` on the table for a uuid key.
|
|
229
|
+
Both are valid targets wherever a column name is accepted — `db.query` `sort`/
|
|
230
|
+
`output`, a `db.get`/`edit`/`del` `fieldName`, etc. (the column-name type is
|
|
231
|
+
`keyof schema | "id" | "created_at"`), and both appear in `InferRow<typeof table>`.
|
|
232
|
+
- **A column named `run` is reserved.** The table deploys and reads back fine, then
|
|
233
|
+
EVERY `s.db.add` into it 400s — at any column type, with or without a value — and
|
|
234
|
+
the error names the column while complaining about the VALUE. Use `run_id`. Exact,
|
|
235
|
+
case-sensitive, one name: `Run`/`runs`/`run_id` are fine. `--strict` fails on it.
|
|
236
|
+
- **Self-referencing tables** need the bare-name form: inside `tweets`'s own
|
|
237
|
+
schema, write `f.tableRef("tweets", { type: "int" })` — the `const tweets`
|
|
238
|
+
handle isn't assigned yet, so the handle form throws "used before declaration".
|
|
239
|
+
- **Seed a table's starting rows with `table({ seed })`.** Rows typed against the
|
|
240
|
+
schema, inline (`seed: [{ name: "…" }]`) or from a file (`seedFile("./seed.json",
|
|
241
|
+
import.meta.url)`). Only `deploy` ships them, and a re-deploy re-seeds cleanly. Never
|
|
242
|
+
put secrets in `seed`. Row shape, `id` pinning, and the file rules: `llms/fields.md`.
|
|
243
|
+
- **`f.password()` defaults to `access: "internal"`, so `db.get` does NOT return it.**
|
|
244
|
+
A login stack that reads `ref("u.password")` after a plain `db.get` fails at runtime
|
|
245
|
+
with `Unable to locate var: u.password` — the column is simply absent from the row.
|
|
246
|
+
Name it in the read's `output` to pull it: `s.db.get({ table: users, fieldName: "email",
|
|
247
|
+
fieldValue: inp("email"), output: ["id", "email", "password"], as: "u" })`, then
|
|
248
|
+
`s.security.check_password`. `output` OVERRIDES column visibility — it is the only way to
|
|
249
|
+
read an `internal` column, and `export()` warns when a stack reads one a `db.get` did not
|
|
250
|
+
return.
|
|
251
|
+
- **Don't take a password through `input.password` on login — it double-hashes.**
|
|
252
|
+
An `f.password()` column hashes on write, and `input.password` *also* hashes the
|
|
253
|
+
submission on bind, so `s.security.check_password` compares two different hashes
|
|
254
|
+
and a correct password always fails (`ok:false` on a found row). Take the submitted
|
|
255
|
+
password as `input.text()` on both signup and login and pass the plaintext straight
|
|
256
|
+
to `check_password` (which does the comparison hash itself). `export()` warns.
|
|
257
|
+
|
|
258
|
+
### Reading and writing rows
|
|
259
|
+
|
|
257
260
|
- **DB reads are field-match, not `where`-expr.** `db.get`/`db.edit`/`db.del`/
|
|
258
261
|
`db.has`/`db.patch` match one field: `{ fieldName, fieldValue }` (`fieldName`
|
|
259
262
|
defaults to the PK `id`). Only `db.query` takes a `where`/`additionalWhere`
|
|
@@ -267,44 +270,73 @@ Non-obvious authoring rules:
|
|
|
267
270
|
check-in — use `db.query({ where: [expr(col("habit"), "=", ...), expr(col("date"), "=", ...)], as })`
|
|
268
271
|
(a `where` array is ANDed) and branch on the result, rather than pushing the
|
|
269
272
|
check to the client.
|
|
270
|
-
- **
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
`
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
273
|
+
- **Drilling into a maybe-null `db.get` result 500s — use `ref(path, { safe: true })`.**
|
|
274
|
+
`db.get` binds `null` on a no-match, but a nested `ref("owner.user_id")` raises a runtime
|
|
275
|
+
"Unable to locate var" (HTTP 500) when `owner` is null — an ownership guard throws instead
|
|
276
|
+
of failing cleanly. Two correct shapes:
|
|
277
|
+
- Guard existence first — `s.precondition({ expr: expr(ref("owner"), "!=", c.null()),
|
|
278
|
+
error_type: "notfound", error: c.text("Not found.") })` — then drill WITHOUT `safe`.
|
|
279
|
+
- Or drill null-safe inside an EXPRESSION or `obj()` operand:
|
|
280
|
+
`expr(ref("owner.user_id", { safe: true }), "=", auth("id"))` yields `null` (the guard
|
|
281
|
+
reads `false`) instead of 500ing. Works inside `obj({...})` too — no `s.set_var` hoist needed.
|
|
282
|
+
⚠ EXPRESSION and `obj()` operands ONLY — never a `db.*` match argument. `null` is not a
|
|
283
|
+
legal `fieldValue`/`id`, so a chained get (fetch the child row, then its parent to check
|
|
284
|
+
the owner) fails with HTTP 400 `Missing param: field_value` one statement BEFORE the guard.
|
|
285
|
+
There guarding existence first is MANDATORY. `export()` warns on a safe ref in that position.
|
|
286
|
+
⚠ That is for a base that EXISTS and may be null. If the base binds nothing at all (a typo),
|
|
287
|
+
`{ safe: true }` buries the bug as a silent `null` — `export()` warns with a did-you-mean;
|
|
288
|
+
fix the name instead.
|
|
289
|
+
|
|
290
|
+
### Stacks and calls
|
|
291
|
+
|
|
292
|
+
- **Block specials nest a `body`, not a `stack`.** `s.for`/`s.foreach`/
|
|
293
|
+
`s.while`/`s.switch`/`s.try_catch`/`s.db.transaction`/`s.expect.to_throw`
|
|
294
|
+
take their sub-stack as `body` (`try`/`catch`/`finally` for `try_catch`);
|
|
295
|
+
`s.group(body)` and `s.util.post_process(body)` take it **positionally**.
|
|
296
|
+
`s.for` is **count-bounded** (`{ as, count: <Value>, body }`), not from/to. See the
|
|
297
|
+
authored signatures in `llms/statements-data.md`.
|
|
298
|
+
- **`s.api.call` / `s.task.call` / `s.trigger.call` / `s.workflow_test.call` are
|
|
299
|
+
WORKFLOW-TEST ONLY.** Outside a `workflowTest({...})` stack the engine cannot reach
|
|
300
|
+
the target, so one in a query/function/task deploys clean and then answers the first
|
|
301
|
+
real request with `ERROR_FATAL: <Type> does not exist: <type>:<n>` — and not per
|
|
302
|
+
host kind, the same call fails identically from a function a query runs.
|
|
303
|
+
`export()` refuses them. `s.function.call`, `s.tool.call`, `s.middleware.call` and
|
|
304
|
+
`s.addon.call` run anywhere, as does `s.function.run` (the ordinary function
|
|
305
|
+
invocation). To share logic between endpoints, put it in a `defineFunction` and
|
|
306
|
+
`s.function.run` it from both.
|
|
307
|
+
- **`expect.*` is a unit-test assertion; `s.expect.*` is a workflow-test statement.**
|
|
308
|
+
A statement's `mock` is keyed by TEST NAME; an undeclared name throws. See `llms/tests.md`.
|
|
309
|
+
- **A helper returning `Statement[]` widens the stack and kills `InferResponse`.**
|
|
310
|
+
Spreading `...requireX()` where the helper is typed `Statement[]` drops the stack's TUPLE
|
|
311
|
+
type, so EVERY `ref()`/`as` in that stack — even ones after the spread — resolves to
|
|
312
|
+
`unknown` and the response types as `StackTupleWidened`. Nothing fails at the helper; it
|
|
313
|
+
surfaces where the response is consumed, often a frontend typecheck. Fix: return
|
|
314
|
+
`statements(s.a(...), s.b(...))` — its tuple survives the spread. A helper that builds
|
|
315
|
+
its array in a LOOP cannot be a tuple; declare `responseShape` on the query there.
|
|
316
|
+
- **Build regex-filter patterns with `c.regex(body, flags?)`, never `c.text`.**
|
|
317
|
+
The regex filters (`regex_test`/`regex_match`/`regex_replace`/…) are PHP `preg_*`: the
|
|
318
|
+
piped value is the PATTERN and must be delimiter-wrapped, and the ARGUMENT is the subject.
|
|
319
|
+
Correct: `withFilters(c.regex(/^[a-z-]+$/i), fl.regex_test(inp("slug")))`.
|
|
320
|
+
- A bare `c.text("^…$")` is an invalid pattern that matches *nothing* for every input,
|
|
321
|
+
so a precondition on it silently rejects all values. `c.regex(body, "i")` wraps +
|
|
322
|
+
escapes it for you (a JS `RegExp` too: `c.regex(/^…$/i)`).
|
|
323
|
+
- Reversed — subject piped, pattern in the argument — reads correctly, type-checks, and
|
|
324
|
+
answers false for EVERY input, so an `if (matches) reject` guard admits what it refuses.
|
|
325
|
+
- Build time refuses both: `withFilters` throws on a bare `c.text` pattern from ANY position
|
|
326
|
+
in the chain (a normalizer in front of the regex filter is refused too; nothing upstream
|
|
327
|
+
adds the delimiters) and on a pattern found in the subject slot; `s.expect.to_match` is the
|
|
328
|
+
same PATTERN slot, refused both ways; a `ref`/`inp` pattern is passed through untouched.
|
|
329
|
+
`export()` warns on a reversed pair in stored bytes.
|
|
330
|
+
- Better still: a native typed input (`input.email`) over hand-rolled validation.
|
|
331
|
+
- **An `auth()`-keyed limiter collapses on any host with no caller identity — at every**
|
|
332
|
+
**tier.** `s.redis.ratelimit({ key: withFilters(c.text("rl:"), fl.concat(auth("id"))) })`
|
|
333
|
+
is the per-user form, but `auth()` is `null` on a public query, a task, or a function,
|
|
334
|
+
and every caller then shares one bucket. Attaching it once at
|
|
335
|
+
`apiGroup({ middleware })` or the workspace tier is the tempting DRY move and inherits
|
|
336
|
+
the same collapse onto every member endpoint. Export warns, naming the tier.
|
|
337
|
+
|
|
338
|
+
### Identity, build, and deploy
|
|
339
|
+
|
|
308
340
|
- **Same-name siblings collide — queries excepted: their identity carries group + verb.**
|
|
309
341
|
Guids derive from `(type, name)`, so two functions (or tables, toolsets, …) sharing
|
|
310
342
|
a name derive ONE guid and `export()` throws — give them DISTINCT names. A QUERY
|
|
@@ -315,137 +347,34 @@ Non-obvious authoring rules:
|
|
|
315
347
|
is NOT a lasting fix: a lock entry cannot hold two guids, so `export --lock`
|
|
316
348
|
refuses the pair (`export()` warns even unlocked); it is for pinning identity
|
|
317
349
|
across a rename, not for sharing a name.
|
|
318
|
-
- **`export()` vs `emitBundle()` vs `writeBundle()`:** `
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
The compiler machinery (per-kind `encode*`, the registries, the bundle serializer,
|
|
331
|
-
the lock model) is on `@xanots/sdk/internal` and is never needed to author.
|
|
332
|
-
READING a bundle back is `@xanots/sdk/bundle` — a statement walker (`2.if.0` paths),
|
|
333
|
-
a structural hash, `mvp:*` catalog, `tableRefOf`.
|
|
334
|
-
- **Client bundle size / tree-shaking.** `@xanots/sdk` is `sideEffects: false` and pulls
|
|
335
|
-
no Node built-ins, so a bundler drops unused SDK exports. But importing a **def** for its
|
|
336
|
-
`getPath()`/`verb`/`getUrl()`/`getChannel()` also pulls whatever its `stack` references:
|
|
337
|
-
the `s.*`/`c.*` factory CALLS run at module load to BUILD it. Types are free.
|
|
338
|
-
⚠ A FLOOR — **~267 kB minified (~65 kB gzipped)** for the FIRST def; splitting modules
|
|
339
|
-
never removes it. The floor is the RUNTIME, not the def: a second def, or a much richer
|
|
340
|
-
one, adds ~2 kB — so reducing what a def does will not reduce it.
|
|
341
|
-
Fix: `xanots routes <entry> --emit xano/routes.gen.ts` (`paths` is an accepted alias) — verbs, paths, and sockets as
|
|
342
|
-
plain data importing NOTHING, still compile-checked: `routePath("blog/{slug}", { slug })`,
|
|
343
|
-
`channelPath("rooms/{room_id}", { room_id })`, `socketUrl("chat", baseUrl)` (tenant base
|
|
344
|
-
URLs lifted to `wss://h/ws/<tenant>:<canonical>`). A rename is a type error, not a 404.
|
|
350
|
+
- **`export()` vs `emitBundle()` vs `writeBundle()`:** `export()` returns the bundle object,
|
|
351
|
+
`emitBundle()` the pretty JSON string, `writeBundle(app, path)` writes it to disk. All
|
|
352
|
+
three run the SAME build-time checks, INCLUDING seed validation of a literal `seed: [...]`
|
|
353
|
+
array (row shape, unknown column, coercion, enum membership, the all-or-nothing `id`
|
|
354
|
+
rule). A DEFERRED seed — a thunk (`() => import("./seed.json")`) or `seedFile()` — is
|
|
355
|
+
checked only by the `xanots export`/`deploy` CLI path. Seed rows are never emitted into
|
|
356
|
+
the bundle either way; only `deploy` ships them.
|
|
357
|
+
- Entry points: the `node:fs` writers (`writeBundle`/`writeArtifact`) and lock-file I/O
|
|
358
|
+
import from `@xanots/sdk/node`, NOT the browser-safe `@xanots/sdk` entry (a frontend
|
|
359
|
+
imports defs from it for `getPath()`/`InferInput`). `@xanots/sdk/internal` is the
|
|
360
|
+
compiler machinery, never needed to author. READING a bundle back is `@xanots/sdk/bundle`
|
|
361
|
+
— a statement walker (`2.if.0` paths), a structural hash, `mvp:*` catalog, `tableRefOf`.
|
|
345
362
|
- **Intra-workspace imports use `.js` specifiers** (`../tables/links.js`), not
|
|
346
363
|
extensionless — the defs compile under `moduleResolution: bundler`. Add the `.js`.
|
|
347
|
-
- **Verifying a def outside a bundler.** Inside a bundler (Vite/webpack) importing a
|
|
348
|
-
query def to read `getPath()`/`verb` works directly. To spot-check from Node, run a REAL
|
|
349
|
-
file with `tsx <file.ts>` **from inside the project root** — not `tsx -e "import …"`
|
|
350
|
-
(its CJS-preparse mis-resolves the package `exports` map → ERR_PACKAGE_PATH_NOT_EXPORTED),
|
|
351
|
-
and not bare `node file.ts` (chokes on the `.js`-specifier intra-workspace imports the
|
|
352
|
-
xanots CLI's own loader resolves). Running from outside the project root also breaks
|
|
353
|
-
the `@xanots/sdk` specifier resolution.
|
|
354
|
-
- **A helper returning `Statement[]` widens the stack and kills `InferResponse`.**
|
|
355
|
-
Factoring a repeated guard into `function requireX(): Statement[]` and spreading it
|
|
356
|
-
(`...requireX("d")`) drops the stack's TUPLE type, so EVERY `ref()`/`as` in that stack —
|
|
357
|
-
including ones declared after the spread — resolves to `unknown` and the query's
|
|
358
|
-
response types as `StackTupleWidened`. Nothing fails at the helper: the error surfaces
|
|
359
|
-
wherever the response is consumed, often a frontend package's typecheck. Fix: return
|
|
360
|
-
`statements(s.a(...), s.b(...))` — a const-generic identity export whose tuple survives
|
|
361
|
-
the spread. A helper that builds its array in a LOOP cannot be a tuple; declare
|
|
362
|
-
`responseShape` on the query there. See `llms/statements-runtime.md`.
|
|
363
|
-
- **Block specials nest a `body`, not a `stack`.** `s.for`/`s.foreach`/
|
|
364
|
-
`s.while`/`s.switch`/`s.try_catch`/`s.db.transaction`/`s.expect.to_throw`
|
|
365
|
-
take their sub-stack as `body` (`try`/`catch`/`finally` for `try_catch`);
|
|
366
|
-
`s.group(body)` and `s.util.post_process(body)` take it **positionally**.
|
|
367
|
-
`s.for` is **count-bounded** (`{ as, count: <Value>, body }`), not from/to. See the
|
|
368
|
-
authored signatures in `llms/statements-data.md`.
|
|
369
|
-
- **MCP servers & agents are distinct root kinds** that both persist under the
|
|
370
|
-
`toolset` payload key (so a same-name pair collides). `mcpServer({...})` exposes
|
|
371
|
-
tools over MCP (auth is per-tool — no server-level gate); `agent({...})` carries a
|
|
372
|
-
typed `llm` block — and so may an `mcpServer`, since the two are ONE stored
|
|
373
|
-
object distinguished by `type`. Their `tools` take a `tool()` handle (or name), resolved to the
|
|
374
|
-
tool's guid like the call family; a raw numeric `id` is an escape hatch.
|
|
375
|
-
- **`task.schedule` is an array** of `{ startsOn, freq?, repeatEnabled?, endsOn?, endsEnabled? }`
|
|
376
|
-
(`ScheduleDef[]`), not a single `{ type, value }`. `freq` is seconds; `startsOn`/
|
|
377
|
-
`endsOn` are timestamp strings validated at encode time — `"2026-01-01T00:00:00Z"`, or
|
|
378
|
-
the space-separated `"2026-01-01 00:00:00+0000"` a pulled workspace carries. Never
|
|
379
|
-
epoch numbers, and never zoneless: the engine stores the string verbatim without
|
|
380
|
-
checking it, so one it cannot parse deploys clean and the task then never fires.
|
|
381
|
-
- **`get_input`/`get_raw_input` read the whole payload**, not one named input
|
|
382
|
-
(args are `{ as?, encoding?, excludeMiddleware? }` — no `name`). For a single
|
|
383
|
-
input use `inp("name")`.
|
|
384
|
-
- **`f.password()` defaults to `access: "internal"`, so `db.get` does NOT return it.**
|
|
385
|
-
A login stack that reads `ref("u.password")` after a plain `db.get` fails at runtime
|
|
386
|
-
with `Unable to locate var: u.password` — the column is simply absent from the row.
|
|
387
|
-
Name it in the read's `output` to pull it: `s.db.get({ table: users, fieldName: "email",
|
|
388
|
-
fieldValue: inp("email"), output: ["id", "email", "password"], as: "u" })`, then
|
|
389
|
-
`s.security.check_password`. `output` OVERRIDES column visibility — it is the only way to
|
|
390
|
-
read an `internal` column, and `export()` warns when a stack reads one a `db.get` did not
|
|
391
|
-
return.
|
|
392
|
-
- **Build regex-filter patterns with `c.regex(body, flags?)`, never `c.text`.**
|
|
393
|
-
The regex filters (`regex_test`/`regex_match`/`regex_replace`/…) are pattern-piped
|
|
394
|
-
PHP `preg_*`: the piped value is the PATTERN and must be delimiter-wrapped, and the
|
|
395
|
-
ARGUMENT is the subject. A bare `c.text("^…$")` is an invalid pattern that matches
|
|
396
|
-
*nothing* for every input, so a precondition on it silently rejects all values.
|
|
397
|
-
`c.regex(body, "i")` wraps + escapes it for you (a JS `RegExp` too: `c.regex(/^…$/i)`).
|
|
398
|
-
Reversed — subject piped, pattern in the argument — reads correctly, type-checks, and
|
|
399
|
-
answers false for EVERY input, so an `if (matches) reject` guard admits what it
|
|
400
|
-
refuses. `withFilters` throws on a bare `c.text` pattern from ANY position in
|
|
401
|
-
the chain (a normalizer in front of the regex filter is refused too; nothing upstream
|
|
402
|
-
adds the delimiters) and on a pattern found in the subject slot; `s.expect.to_match`
|
|
403
|
-
is the same PATTERN slot, refused both ways; a `ref`/`inp` pattern is passed through untouched.
|
|
404
|
-
`export()` warns on a reversed pair in stored bytes. Better still:
|
|
405
|
-
a native typed input (`input.email`) over hand-rolled validation.
|
|
406
|
-
- **Compose a rule set as SIBLINGS, not a folded chain.** `and(...rules)` takes any
|
|
407
|
-
number of terms and encodes flat; `rules.reduce((acc, r) => and(acc, r))` nests one
|
|
408
|
-
container per rule, which costs quadratic bytes (512 terms: 394 KiB flat, 21 MiB
|
|
409
|
-
folded) and is refused past 128 levels. Mixed joins: `and(or(...anyOf), ...allOf)`.
|
|
410
|
-
- **Declare inputs with `input.<type>()`, read them with `inp("name")`.** `inp()`
|
|
411
|
-
resolves ONLY against this def's own `input` block — a value produced earlier in
|
|
412
|
-
the stack is `ref("var.field")`, not `inp("field")`. An undeclared name fails at
|
|
413
|
-
runtime with `Unable to locate input` (`export()` warns).
|
|
414
|
-
- **Don't take a password through `input.password` on login — it double-hashes.**
|
|
415
|
-
An `f.password()` column hashes on write, and `input.password` *also* hashes the
|
|
416
|
-
submission on bind, so `s.security.check_password` compares two different hashes
|
|
417
|
-
and a correct password always fails (`ok:false` on a found row). Take the submitted
|
|
418
|
-
password as `input.text()` on both signup and login and pass the plaintext straight
|
|
419
|
-
to `check_password` (which does the comparison hash itself).
|
|
420
364
|
- **Agents authenticate with env vars — never `xanots login`.** `login` blocks on a
|
|
421
|
-
browser consent no agent can complete. Set
|
|
422
|
-
|
|
423
|
-
survives repeated runs.
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
"instance_base_url": …, "workspace_id": <n>,
|
|
428
|
-
|
|
365
|
+
browser consent no agent can complete. Set all three of `$XANO_INSTANCE_URL`,
|
|
366
|
+
`$XANO_WORKSPACE_ID`, `$XANO_META_TOKEN` and run `deploy`/`release` directly: no disk, no
|
|
367
|
+
rotation, so it survives repeated runs.
|
|
368
|
+
- The triple outranks every other credential (`--config` and `$XANO_REFRESH_TOKEN` included,
|
|
369
|
+
each named on stderr when displaced). Setting SOME of the three is a hard error, so a
|
|
370
|
+
misspelled secret cannot fall through to whatever credential the runner has.
|
|
371
|
+
- As a file: `{ "type": "token", "instance_base_url": …, "workspace_id": <n>,
|
|
372
|
+
"meta_api_token": … }`. The older `$XANO_REFRESH_TOKEN` + `$XANO_CLIENT_ID` pair still
|
|
373
|
+
works but ROTATES: single-use.
|
|
429
374
|
- **Event-driven objects fire on an EPHEMERAL.** A `task` (scheduled), an `mcpServer`,
|
|
430
375
|
and every trigger — `tableTrigger` included — run normally on an ephemeral env, which
|
|
431
376
|
is where `deploy` sends them. So test an event-driven design (screen-on-insert, cron
|
|
432
377
|
cleanup, MCP tool call) by deploying it and letting it run.
|
|
433
|
-
- **Zero-based numeric keys make `c.obj` a LIST.** `c.obj({ "0": "a" })` evaluates to
|
|
434
|
-
`["a"]`: a numeric key IS an index in the engine's data model, so keys that are exactly
|
|
435
|
-
`0..n-1` come back as a list with HTTP 200 and no error. Write `c.array([...])` when you
|
|
436
|
-
want the list, or prefix the keys (`"k0"`) when you want an object. A non-zero-based
|
|
437
|
-
numeric key (`{ "2": … }`) survives as a key. Export warns.
|
|
438
|
-
- **To match every row, omit `where` — never pass a constant.** `where: c.bool(true)` is
|
|
439
|
-
not "no filter": a bare scalar literal states no condition and the engine reads the
|
|
440
|
-
resulting `context.search` as garbage, so it throws. An absent `where` is how "every
|
|
441
|
-
row" is spelled. A raw `Value` `where` stays the escape hatch for a clause built
|
|
442
|
-
elsewhere — `inp("clause")`, `ref("built_where")`, or `c.text("id > 0")`.
|
|
443
|
-
- **An `auth()`-keyed limiter collapses on any host with no caller identity — at every**
|
|
444
|
-
**tier.** `s.redis.ratelimit({ key: withFilters(c.text("rl:"), fl.concat(auth("id"))) })`
|
|
445
|
-
is the per-user form, but `auth()` is `null` on a public query, a task, or a function,
|
|
446
|
-
and every caller then shares one bucket. Attaching it once at
|
|
447
|
-
`apiGroup({ middleware })` or the workspace tier is the tempting DRY move and inherits
|
|
448
|
-
the same collapse onto every member endpoint. Export warns, naming the tier.
|
|
449
378
|
|
|
450
379
|
## Statements
|
|
451
380
|
|
|
@@ -483,7 +412,7 @@ Control flow & blocks (each nests a sub-stack; block specials name it `body`):
|
|
|
483
412
|
|
|
484
413
|
# Object kinds
|
|
485
414
|
|
|
486
|
-
> Read when deciding WHAT to build — every authorable primitive
|
|
415
|
+
> Read when deciding WHAT to build — every authorable primitive, what each is, and which factory + register method builds it. Also when `register*` will not typecheck an array built by `.flatMap()`/`.concat()`.
|
|
487
416
|
|
|
488
417
|
Author with the factory, register on the Xano instance, lands under the payload key. Each line ends with a one-liner on what the primitive is.
|
|
489
418
|
|
|
@@ -504,7 +433,7 @@ Author with the factory, register on the Xano instance, lands under the payload
|
|
|
504
433
|
- mcp_server: `mcpServer` → `Xano.registerMcpServers` → payload `toolset` — An MCP server exposing a set of tools to external MCP clients.
|
|
505
434
|
- agent: `agent` → `Xano.registerAgents` → payload `toolset` — An AI agent: an LLM configuration plus the tools it can call. Invoke it from any stack (query/function/task/tool/trigger) with `s.ai.agent.run` — no public endpoint; the result is a rich envelope whose completion text is at `.result`.
|
|
506
435
|
- task: `task` → `Xano.registerTasks` → payload `task` — A scheduled background job (cron/interval) that runs a stack on a timer.
|
|
507
|
-
- workflow_test: `workflowTest` → `Xano.registerWorkflowTests` → payload `workflow_test` — An end-to-end test: a named stack with NO input and NO response that invokes other objects (`s.function.call`, `s.task.call`, `s.api.call`) and asserts on what they bind with `s.expect.*`. `datasource` defaults to `""` (an EMPTY datasource, recommended); naming one
|
|
436
|
+
- workflow_test: `workflowTest` → `Xano.registerWorkflowTests` → payload `workflow_test` — An end-to-end test: a named stack with NO input and NO response that invokes other objects (`s.function.call`, `s.task.call`, `s.api.call`) and asserts on what they bind with `s.expect.*`. `datasource` defaults to `""` (an EMPTY datasource, recommended); naming one is the clone trap described in `llms/kinds-core.md`.
|
|
508
437
|
- middleware: `middleware` → `Xano.registerMiddleware` → payload `middleware` — A reusable pre/post stack attached to a query/function/task/tool/API group to run before or after its own logic.
|
|
509
438
|
- addon: `addon` → `Xano.registerAddons` → payload `addon` — A reusable read fragment that enriches a query result by joining related table data.
|
|
510
439
|
- realtime_server: `realtimeServer` → `Xano.registerRealtimeServers` → payload `realtime_server` — A realtime (websocket) server: the canonical-addressed container that owns realtime channels. Off until `enabled: true`. Returns a handle with `getUrl(baseUrl)`/`getPath()` for the client's socket URL (`wss://<host>/ws/<canonical>`).
|
|
@@ -529,8 +458,18 @@ to survive a rename).
|
|
|
529
458
|
- `verb`: `"GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD"` (required), UPPERCASE. Anything else — most often a lowercase `"post"` — makes `query()` THROW, because Xano does NOT reject it: it stores the verb as NULL, a null verb serves as GET, and the endpoint then answers on the wrong method while the one you meant 404s `Unable to locate request.`
|
|
530
459
|
- `apiGroup`: an `apiGroup()` def handle (or its name) — binds by guid, stable across syncs. Raw numeric `apiGroupId?` is the escape hatch and wins if both given.
|
|
531
460
|
- `auth`: `false` (no auth) or an auth-table id; `responseType`: `"standard" | "stream"` (default `standard`) — any other spelling THROWS, since Xano stores an unrecognized one as NULL and a null buffers as `standard`, so a misspelled stream quietly does not stream.
|
|
532
|
-
- `name` is the endpoint PATH within the group.
|
|
533
|
-
|
|
461
|
+
- `name` is the endpoint PATH within the group.
|
|
462
|
+
- A `{param}` segment is a URL PATH PARAM bound to the input of the same name, and segments chain: `name: "blog/{slug}/review/{review_id}"` + `input: { slug: input.text(), review_id: input.int() }`. Read it with `inp("slug")` like any other input.
|
|
463
|
+
- Every `{param}` MUST have a matching input or `query()` THROWS — Xano treats an unbound marker as inert route text, so the endpoint would answer on the path and see nothing.
|
|
464
|
+
- A `{param}` need NOT be a whole segment (`"blog/post-{slug}"` routes fine), but its type must fit one segment (no object/list/json/file/geo/vector); there are no wildcards or patterns. `required: true` is NOT demanded (the engine's editor leaves path inputs unmarked).
|
|
465
|
+
- The CONVERSE is warned, not enforced: an input a `GET`/`DELETE`/`HEAD` looks ONE ROW up by (`s.db.get`/`get_by_id`/`has`/by-field edit/patch/delete) belongs in the path — `export()` warns `query.path-segment-candidate`. It still serves `?blog_id=1`, but the route is not addressable and `getPath()` types STATIC, so a caller cannot pass the value positionally. A segment is any value naming WHICH resource is wanted, not just an id (`"shop/{country}"`). An input that NARROWS A LIST (`s.db.query`) stays a query-string param.
|
|
466
|
+
- Inputs absent from the path are ordinary query-string/body params.
|
|
467
|
+
- Name charset is ONLY `A-Za-z0-9_-/{}`, max 200: a `.` (`"export.zip"`) is NOT rejected by Xano — it stores an EMPTY name that deploys clean then 404s forever, so `query()` THROWS. Use `"export_zip"` and set the extension in the response headers.
|
|
468
|
+
- **Client recipe:** `q.getPath({ params: { slug: "hello" } })` → `/api:<canonical>/blog/hello` — never interpolate by hand.
|
|
469
|
+
- `getPath` percent-encodes each value (so `?`/`#`/spaces stay in their segment) and throws on what encoding cannot contain: a `/`, and a value that IS `.`/`..` (a URL parser drops those before routing — `%2e` counts — addressing a different endpoint).
|
|
470
|
+
- The keys are typed from the literal `name`, so a typo is a compile error.
|
|
471
|
+
- The HANDLE's `q.toSearchParams(input)` drops path params for a GET; the free `query.toSearchParams(input)` has no view of the route and keeps every key.
|
|
472
|
+
- What importing a def costs a browser bundle, the `routes.gen.ts` alternative, and how to spot-check a def from Node: `llms/client.md`.
|
|
534
473
|
- `apiGroup({ name, guid?, canonical?, description?, docs?, swagger?, apiGroupEnabled?, documentation?, cors? })` — a query container; register it and bind queries to it via their `apiGroup`.
|
|
535
474
|
- `cors?`: `{ mode?, allowOrigins?: string[], allowHeaders?: string[], allowCredentials?, maxAge?, allowMethods?: { get?, post?, put?, patch?, delete?, head? } }`.
|
|
536
475
|
- `mode?`: `"default"` (the default) | `"custom"` | `"disabled"`, lowercase — a fourth value THROWS at export (`apiGroup()` itself does not check), because Xano neither rejects nor blanks it: it DROPS THE WHOLE API GROUP on import, so the deploy succeeds and every query in the group 404s. ⚠ Every OTHER field applies only under `"custom"`: `"default"` serves a FIXED permissive policy (any origin, `allow-headers: *`, `allow-credentials: true`, `max-age: 86400`) and ignores the block, so setting `maxAge`/`allowCredentials`/`allowHeaders` alone changes nothing. `"disabled"` sends no CORS headers at all, so every browser call fails.
|
|
@@ -582,11 +521,94 @@ surface — `s.conditional`/`s.while` `when` (incl. each `elif` branch), and
|
|
|
582
521
|
`ambiguous-condition`.
|
|
583
522
|
- A **filtered** operand (`withFilters(...)`) works inline in any condition/`where` (conditional,
|
|
584
523
|
while, `db.query`/addon, …) — e.g. `cmp(withFilters(col("title"), fl.trim()), "=", inp("q"))`.
|
|
524
|
+
- **Compose a rule set as SIBLINGS, not a folded chain.** `and(...rules)` takes any
|
|
525
|
+
number of terms and encodes flat; `rules.reduce((acc, r) => and(acc, r))` nests one
|
|
526
|
+
container per rule, which costs quadratic bytes (512 terms: 394 KiB flat, 21 MiB
|
|
527
|
+
folded) and is refused past 128 levels. Mixed joins: `and(or(...anyOf), ...allOf)`.
|
|
585
528
|
- e.g. `db.query({ table: posts, where: expr(col("author"), "=", auth("id")), as: "rows" })`.
|
|
586
529
|
|
|
530
|
+
# Consuming defs from a client
|
|
531
|
+
|
|
532
|
+
> Read when a frontend imports a def (`getPath()`/`InferResponse`) or calls the deployed backend — what the import costs, `window.XANO_HOST`, local dev, file URLs, and a Node spot-check.
|
|
533
|
+
|
|
534
|
+
Importing a def into a browser bundle or a Node script — for `getPath()`, `getUrl()`, `verb`, or `InferResponse` — runs its factory calls; these are the costs and the checks.
|
|
535
|
+
|
|
536
|
+
- **Client bundle size / tree-shaking.** `@xanots/sdk` is `sideEffects: false` and pulls
|
|
537
|
+
no Node built-ins, so a bundler drops unused SDK exports. But importing a **def** for its
|
|
538
|
+
`getPath()`/`verb`/`getUrl()`/`getChannel()` also pulls whatever its `stack` references:
|
|
539
|
+
the `s.*`/`c.*` factory CALLS run at module load to BUILD it. Types are free.
|
|
540
|
+
⚠ A FLOOR — **~267 kB minified (~65 kB gzipped)** for the FIRST def; splitting modules
|
|
541
|
+
never removes it. The floor is the RUNTIME, not the def: a second or much richer def
|
|
542
|
+
adds ~2 kB, so trimming a def does not shrink it.
|
|
543
|
+
Fix: `xanots routes <entry> --emit xano/routes.gen.ts` (`paths` is an accepted alias) — verbs, paths, and sockets as
|
|
544
|
+
plain data importing NOTHING, still compile-checked: `routePath("GET blog/{slug}", { slug })`
|
|
545
|
+
`channelPath("rooms/{room_id}", { room_id })`, `socketUrl("chat", baseUrl)` (tenant base
|
|
546
|
+
URLs lifted to `wss://h/ws/<tenant>:<canonical>`). A rename is a type error, not a 404.
|
|
547
|
+
- **Verifying a def outside a bundler.** Inside a bundler (Vite/webpack) importing a
|
|
548
|
+
query def to read `getPath()`/`verb` works directly. To spot-check from Node, run a REAL
|
|
549
|
+
file with `tsx <file.ts>` **from inside the project root** — not `tsx -e "import …"`
|
|
550
|
+
(its CJS-preparse mis-resolves the package `exports` map → ERR_PACKAGE_PATH_NOT_EXPORTED),
|
|
551
|
+
and not bare `node file.ts` (chokes on the `.js`-specifier intra-workspace imports the
|
|
552
|
+
xanots CLI's own loader resolves). Running from outside the project root also breaks
|
|
553
|
+
the `@xanots/sdk` specifier resolution.
|
|
554
|
+
|
|
555
|
+
**Reading the injected backend URL.** `xanots deploy <entry> --static <dir>` writes the deployed env's URL
|
|
556
|
+
into every html document: a prerendered build serves a different one per
|
|
557
|
+
route, and a route without the global renders fine while every call goes to the wrong
|
|
558
|
+
origin. Read it at runtime with a build-time fallback:
|
|
559
|
+
const HOST = (typeof window !== 'undefined' && window.XANO_HOST) || import.meta.env.VITE_XANO_HOST;
|
|
560
|
+
In LOCAL DEV there is no injected global, so the fallback is what answers: set
|
|
561
|
+
`VITE_XANO_HOST` in a `.env.local` beside `.env.example` at the PROJECT ROOT. The
|
|
562
|
+
scaffold's vite config sets `envDir` there (its `root` is `frontend/`, and Vite
|
|
563
|
+
resolves `.env` files against `root`) — without it the var reads as undefined, the
|
|
564
|
+
host falls back to '', and every call 404s off the dev server.
|
|
565
|
+
⚠ It is INJECTED in bracket form — `window["XANO_HOST"]="…"` — so verifying a deploy
|
|
566
|
+
by grepping `window.XANO_HOST` matches nothing and reads as a failed inject. Grep the
|
|
567
|
+
bare `XANO_HOST` token.
|
|
568
|
+
**Displaying a stored file.** A file column comes back as `{ path, name, type, size,
|
|
569
|
+
meta, access, url }`. ⚠ Do NOT use its `url`: on a tenant-scoped environment that field
|
|
570
|
+
addresses the instance host WITHOUT the `/tenant/<name>` segment and 404s, silently —
|
|
571
|
+
as a broken `<img>`, with every API assertion still passing. Build the URL from `path`
|
|
572
|
+
instead: `fileUrl(row.avatar, HOST)` returns `null` for
|
|
573
|
+
an absent file and is correct on an ephemeral and an instance workspace alike.
|
|
574
|
+
|
|
575
|
+
# Error index
|
|
576
|
+
|
|
577
|
+
> Read when a request, test, build, or pull fails with a message you did not write — the string, its cause, and where the fix is.
|
|
578
|
+
|
|
579
|
+
### Request-time (deployed) failures
|
|
580
|
+
|
|
581
|
+
- `Unable to locate input: <name>` — `inp()` names an undeclared input, or an attached middleware reads its own `input` (never bound). Declare it; a stack value is `ref("var.field")`; middleware reads the body with `s.util.get_all_input`. `llms.txt`; `llms/kinds-core.md`.
|
|
582
|
+
- `Unable to locate var: <a.b>` (HTTP 500) — a dotted `ref` into a null base (a `db.get` miss), or a column absent from the row (`f.password` is `internal`). Guard existence first, or use the null-safe `safe` option; name the column in `output`. `llms.txt`.
|
|
583
|
+
- `Missing var entry: <name>` inside `s.expect.to_throw` — the body runs in an isolated var stack; bind what it needs inside the body. `llms/tests.md`.
|
|
584
|
+
- `Missing param: field_value` (HTTP 400) — a `db.*` match argument resolved to `null` (a safe ref, a nullable foreign key). Guard existence before the lookup; an optional FK stores `0` and is read with field-match `db.get`. `llms.txt`; `llms/fields.md`.
|
|
585
|
+
- `Value is less than the minimum value of 1` (HTTP 400) — `db.get_by_id` given `0`; use field-match `db.get`. `llms/statements-data.md`.
|
|
586
|
+
- `Invalid op: <op>` — a `cmp` operator (`in`, `like`, …) in a RUNTIME condition, which takes the `expr` set only; write `or(expr(...), expr(...))`. `llms/kinds-core.md`.
|
|
587
|
+
- `Unsupported param format` / `Unsupported parameter reference` — an aggregate or `eval` `name` that is not a bare column, or a bare `eval` name for a joined column. `llms/statements-data.md`.
|
|
588
|
+
- `ParseError: Invalid value for param` (HTTP 400) — `contains`/`@>`/`overlaps` on a text column (use `includes`), or a joined column qualified without `tableAlias`. `llms/statements-data.md`.
|
|
589
|
+
- `ERROR_FATAL: <Type> does not exist: <type>:<n>` — `s.api.call`/`s.task.call`/`s.trigger.call`/`s.workflow_test.call` outside a workflow test; share logic via `defineFunction` + `s.function.run`. `llms.txt`.
|
|
590
|
+
- `ERROR_FATAL "Unable to decode."` — a populated JSON string where the engine expects `c.obj`'s form; write `c.obj({...})` or `obj({...})`. `llms/values.md`.
|
|
591
|
+
- `Precondition failed.` in place of your message — `error` was a bare string; pass `c.text("…")`. `llms/fields.md`.
|
|
592
|
+
- `Param: token - Text filter requires an integer, float, string or boolean value` — `s.api.call` `auth.token` given a tagged `Value`; it must be a bare string. `llms/statements-calls.md`.
|
|
593
|
+
- Every `s.db.add` into one table 400s naming a column while complaining about its VALUE — the column is named `run`. `llms.txt`.
|
|
594
|
+
- HTTP 200 with an EMPTY body where `0` was expected — a bare `returnType: "count"` of zero; wrap it as `{ count: ref("n") }`. `llms/statements-data.md`.
|
|
595
|
+
- A lambda returns error TEXT with HTTP 200 (`Could not resolve "node:crypto"`, an undefined-binding message) — the body threw; use the preloaded globals, the surface's bindings, and `capture`. `llms/lambda.md`.
|
|
596
|
+
- `Unable to locate request.` (404) on an endpoint that deployed — a lowercase verb, a `.` in the name, or a CORS `mode` typo that dropped the whole API group. `llms/kinds-core.md`.
|
|
597
|
+
- A browser call fails on a missing `access-control-allow-origin` while deploy looks fine — CORS `mode: "custom"` with `"*"` or an unmatched origin. `llms/kinds-core.md`.
|
|
598
|
+
- A websocket is closed right after the handshake — a refused `connect` gate: an empty/falsy return, a crash, or a gating trigger with no `response`. `llms/triggers.md`.
|
|
599
|
+
- `to_throw failed - response is ok` around an auth-refused call — `ERROR_CODE_ACCESS_DENIED` carries no message; the auth gate is not reachable from a workflow test. `llms/tests.md`.
|
|
600
|
+
- Output reads `Hi [object Object]` — a tagged value inside a JS template literal; compose at runtime with `withFilters` + `fl.concat`. `llms.txt`.
|
|
601
|
+
|
|
602
|
+
### Build-time and tooling failures
|
|
603
|
+
|
|
604
|
+
- `must be ES modules` — package.json says `"type": "commonjs"`; set `"type": "module"`. `llms.txt` Quickstart.
|
|
605
|
+
- A response types as `StackTupleWidened` — a `Statement[]` helper was spread into the stack; return `statements(...)`. `llms.txt`; `llms/statements-runtime.md`.
|
|
606
|
+
- `ERR_PACKAGE_PATH_NOT_EXPORTED` — `tsx -e "import …"`, or running from outside the project root; run a real file with `tsx <file.ts>` from the root. `llms/client.md`.
|
|
607
|
+
- `Missing statement: mvp:placeholder` on import — an unconfigured slot in a pulled tree; replace it with the statement it stands in for. `llms/legacy.md`.
|
|
608
|
+
|
|
587
609
|
# Saved unit tests, assertions, and mocks
|
|
588
610
|
|
|
589
|
-
> Read when authoring a `workflowTest()` stack, when a query/function/middleware carries `tests`, when a statement
|
|
611
|
+
> Read when authoring a `workflowTest()` stack, when a query/function/middleware carries `tests`, when a statement needs a `mock`, or when running a deployed environment's tests.
|
|
590
612
|
|
|
591
613
|
Named input sets run against one object, with assertions on its response — the tests the Xano editor shows. NOT `workflowTest()`, which is a standalone object with its own stack that calls other objects.
|
|
592
614
|
|
|
@@ -626,9 +648,9 @@ A statement returns a value instead of doing its work, for one named test.
|
|
|
626
648
|
|
|
627
649
|
The run is isolated in ways that make a correct test fail for reasons the failure message does not name.
|
|
628
650
|
|
|
629
|
-
- The run uses an EMPTY datasource, so **no `table({ seed })` rows exist while it runs**
|
|
651
|
+
- The run uses an EMPTY datasource, so **no `table({ seed })` rows exist while it runs** (same as a unit test, above): a read of seeded row 1 fails with its own precondition message, not an empty-database error. Build fixtures INSIDE the test.
|
|
630
652
|
- `s.api.call` does NOT raise when the endpoint answers with an error. It BINDS the error envelope (`{code, message}`) to its `as` and carries on, so a later `s.expect.to_be_defined({ expr: ref("r.field") })` reports the ASSERTION while the real failure was the call, four statements up. Assert on the envelope — `s.expect.to_contain({ expr: ref("r.code"), value: c.text("ERROR_CODE_INPUT_ERROR") })` — when a call may fail. `s.function.run` raises instead; the two disagree.
|
|
631
|
-
- `s.expect.to_throw({ body, exception? })` runs `body` in an ISOLATED var stack, so a variable bound EARLIER in the test is not visible inside it — bind what the body needs inside the body. `exception` is a `Value` whose text the raised message must CONTAIN (`c.text("already exists")`, not a bare string); omit it to accept any error.
|
|
653
|
+
- `s.expect.to_throw({ body, exception? })` runs `body` in an ISOLATED var stack, so a variable bound EARLIER in the test is not visible inside it — bind what the body needs inside the body. An outer one raises `Missing var entry: <name>` there, which the test reports as `to_throw` not matching (`export()` warns). `exception` is a `Value` whose text the raised message must CONTAIN (`c.text("already exists")`, not a bare string); omit it to accept any error.
|
|
632
654
|
- `s.expect.to_throw` catches such a call only when the error carries a MESSAGE. `ERROR_CODE_ACCESS_DENIED` arrives with an empty one, so `to_throw` around an auth-refused call reports `to_throw failed - response is ok` — which reads as a broken auth gate on a gate that works.
|
|
633
655
|
- An endpoint's `auth` gate is NOT enforced on `s.api.call`. A `query({ auth: users })` runs anyway and fails only where its stack dereferences `auth(...)`. A stack that never touches `auth(...)` runs unauthenticated and passes.
|
|
634
656
|
- Neither `auth.token` nor an `Authorization` entry in `headers` authenticates the call — a token that answers 200 over real HTTP is refused here. To cover auth-gated logic, move the body into a `defineFunction` taking the user id and `s.function.call` that; the gate itself is not reachable from a workflow test.
|
|
@@ -656,10 +678,11 @@ The run is isolated in ways that make a correct test fail for reasons the failur
|
|
|
656
678
|
- `output?`: `{ schema: Record<string, input.*>, enabled? }` — structured-output schema. `schema` is a named-field record authored with the `input.*` catalog, exactly like a `defineFunction`/`query` `input:` map (the stored `structuredOutputsSchema` is the same wire shape as function inputs). e.g. `output: { schema: { priority: input.enum(["low","high"]), summary: input.text() } }`. When you pass the agent *handle* to `s.ai.agent.run({ agent })`, `.result` is typed straight from this schema — no `resultShape` witness needed (the shape is declared once). `resultShape` remains only to override that, or to type an agent referenced by bare name.
|
|
657
679
|
- **Run + read recipe (`s.ai.agent.run`):** bind the run to a var (`s.ai.agent.run({ agent, args, as: "run" })`) — it produces a rich envelope, and the completion is at **`.result`**. Read one structured field with a dotted ref (`response: ref("run.result.priority")`) or the whole completion (`ref("run.result")`, typed from `output.schema`); persist it in a later step the same way (`s.set_var({ name, value: ref("run.result.summary") })`). `args` is a plain object of run inputs (`{ topic: inp("topic") }` — raw literals are fine, e.g. `{ max_steps: 3 }`) surfaced to the agent as `{{ $args.topic }}`. Tool-call / per-step data (when tools ran) rides `.toolCalls` / `.steps` on the same envelope — both optional, absent or empty when no tools executed.
|
|
658
680
|
- **Marketplace:** for chat history, use `@xanots/chatbot`; for vector RAG, use `@xanots/vector` (`tools: [vector.searchTool]`). Find add-ons with `xanots marketplace search <q>`.
|
|
681
|
+
- Both kinds persist under the `toolset` payload key, so a same-name `agent` + `mcpServer` pair derives ONE guid and `export()` throws — give them distinct names.
|
|
659
682
|
|
|
660
683
|
# Knowledge def shape
|
|
661
684
|
|
|
662
|
-
> Read when the workspace defines a `knowledge()` item
|
|
685
|
+
> Read when the workspace defines a `knowledge()` item for its AI agents.
|
|
663
686
|
|
|
664
687
|
- `knowledge({ name, description?, type?, mode?, enabled?, body, refs?, guid?, tags? })` — markdown the workspace's AI agents read before they act. Takes `registerKnowledge`.
|
|
665
688
|
- `body` (REQUIRED): `knowledgeFile("./runbook.md", import.meta.url)` — a path to a real markdown FILE. There is no inline-string form. The path resolves relative to the MODULE THAT DECLARES the item, not the process working directory and not the workspace entry; `import.meta.url` is required and is what makes that true.
|
|
@@ -700,11 +723,11 @@ The run is isolated in ways that make a correct test fail for reasons the failur
|
|
|
700
723
|
- `deliverTo?`: `"channel"` (default) | `"sender"` | `"others"` | `"explicit"`. ⚠ `"explicit"` still delivers to NOBODY — nothing selects recipients from inside a handler, and `s.realtime.publish` (which originates an event INTO a channel) is not a substitute.
|
|
701
724
|
- Only `"channel"`/`"others"` fan out AND are written to the `conversation` transcript — a `"sender"` response is invisible to every future joiner.
|
|
702
725
|
- **Both input surfaces read as ordinary inputs:** `inp("body")` for a payload field, `inp("room_id")` for the channel's `{room_id}`. No session lookup, no frame parsing.
|
|
703
|
-
- A path param is bound ONCE at join and read from the connection thereafter, never from the frame — a sender cannot claim a room it did not join.
|
|
726
|
+
- A path param is bound ONCE at join and read from the connection thereafter, never from the frame — a sender cannot claim a room it did not join.
|
|
704
727
|
- `s.realtime.get_session({ as })` — the CALLER's realtime session for the current frame. FLAT shape:
|
|
705
728
|
- `authenticated` bool · `client_id` text (the AUTHED ROW ID as text, `""` anonymous) · `dbo_id` int (the auth TABLE's id — NOT the user's row id; `0` anonymous — to look the caller up use `client_id`. `dbo_id` is an int in the same position and typechecks, so a gate that keys on it finds no user and refuses EVERYONE) · `socket_id` int (transport id) · `channel` text (resolved path, `""` in a server trigger) · `params` object (bound path params, `{}` when none — `ref("session.params.room_id")`) · `extras` object · `opened_at` decimal.
|
|
706
729
|
- Works in a realtime MESSAGE stack and in CHANNEL and SERVER trigger stacks; off that path it degrades to an anonymous session.
|
|
707
|
-
- For a path param prefer `inp("room_id")
|
|
730
|
+
- For a path param prefer `inp("room_id")` in a MESSAGE; a lifecycle TRIGGER has only the session. Reach for the session when you need the CONNECTION (identity/extras) — "who is this sender" on an anonymous-client channel.
|
|
708
731
|
- ⚠ THREE UNRELATED THINGS ARE CALLED A CLIENT ID: `session.client_id` (app-facing identity), `session.socket_id` (transport), and a frame's `options.client_id` (the at_least_once CURSOR handle). Conflating the first and last breaks at_least_once for anonymous clients.
|
|
709
732
|
- `s.realtime.publish({ server, channel, data, message?, authTable?, authId? })` — the PUSH direction: originate a server-authored event onto a channel from ANY stack, no client frame first.
|
|
710
733
|
- `server` is the handle or its NAME (resolved by name, not guid); `channel` is the FILLED-IN path (`channel.getChannel({ room_id: 42 })`), never the template — a constant still carrying `{param}` THROWS at author time, and a constant `server`/`channel` naming nothing this workspace registers WARNS at export.
|
|
@@ -739,7 +762,7 @@ The run is isolated in ways that make a correct test fail for reasons the failur
|
|
|
739
762
|
- **Conversation frames — the transcript hydrates the client, so DO NOT build a hydration endpoint.**
|
|
740
763
|
- On a `conversation` channel the replay is PUSHED automatically at join, unasked: `conversation_start` (`payload.count`) → the last `limit` messages, each a normal `action: "message"` frame carrying its ORIGINAL `type` and `payload` plus `conversation: true` and the original `ts` → `conversation_end`.
|
|
741
764
|
- So the client needs NO fetch, no `GET /messages`, and no table read to paint the initial view. Render `message` frames identically either way; the backfill paints itself.
|
|
742
|
-
- ⚠ `{ enabled: true }`
|
|
765
|
+
- ⚠ `{ enabled: true }` alone is a no-op: `limit` defaults to 0 and 0 means RETAIN NONE (see `conversation` above) — always pass `limit`.
|
|
743
766
|
- The POST-HANDLER broadcast payload IS the stored transcript row — a handler must broadcast everything the UI needs to render a past message (author name, id, `created_at`). Nothing else is replayed.
|
|
744
767
|
- Only `deliverTo` `"channel"`/`"others"` are RECORDED, so a `"sender"` response is invisible to every future joiner by construction.
|
|
745
768
|
- The transcript is a capped ring (`limit`, `ttl`), not storage. Persist to a table only for durability, search, or reads BEYOND that window — never merely to hydrate a joiner.
|
|
@@ -772,8 +795,20 @@ realtimeChannelTrigger, mcpServerTrigger, agentTrigger, workspaceTrigger,
|
|
|
772
795
|
errorTrigger}({ name, guid?, description?, active?, tags?, ... })`.
|
|
773
796
|
|
|
774
797
|
- `tableTrigger({ name, table?, datasources?, actions?: {insert?,update?,delete?,truncate?}, stack })` — database/table trigger. `t.new` / `t.old` are the row **after** / **before** the change; `t.action` (`insert|update|delete|truncate`), `t.datasource`. Bind `table` to a `table()` handle and `t.new("col")` / `t.old("col")` are typed to that row (misspelled column = compile error). Nullability follows the enabled actions: insert → `old` is null, delete → `new` is null, update → both, truncate → neither. Config-only (no response).
|
|
775
|
-
- `realtimeServerTrigger({ name, realtimeServer, actions?: {connect?,disconnect?}, stack?, response?, responseShape? })` — realtime SERVER lifecycle (a client connecting to / disconnecting from the server, not a message). Inputs: `t.action` (`connect|disconnect`), `t.realtime_server`, `t.client`. Bind `realtimeServer` to a `realtimeServer()` handle (or its name).
|
|
776
|
-
- `
|
|
798
|
+
- `realtimeServerTrigger({ name, realtimeServer, actions?: {connect?,disconnect?}, stack?, response?, responseShape? })` — realtime SERVER lifecycle (a client connecting to / disconnecting from the server, not a message). Inputs: `t.action` (`connect|disconnect`), `t.realtime_server`, `t.client`. Bind `realtimeServer` to a `realtimeServer()` handle (or its name).
|
|
799
|
+
- `connect` GATES the connection — a denial sends an `error` and CLOSES the socket with code 4401 before it is ever ready, so it is a real front door, not an observer; same return shape as a channel `join` below (EMPTY/FALSY DENIES — INCLUDING a gating trigger with NO `response`, which returns nothing and so refuses every client).
|
|
800
|
+
- A CRASH DENIES too — a gate that cannot answer must not admit. Both failure modes lock the door, so plan for a self-inflicted LOCKOUT (an unguarded drill into a null `db.get` raises → everyone refused), not a breach.
|
|
801
|
+
- Gating is OPT-IN: a server with no `connect` trigger accepts every connection.
|
|
802
|
+
- `disconnect` is OBSERVATIONAL (return ignored, throws swallowed — cleanup must always complete).
|
|
803
|
+
- Both are SERVER-scoped, so `s.realtime.get_session` works but carries no channel path and no bound params.
|
|
804
|
+
- `realtimeChannelTrigger({ name, channel, actions?: {join?,leave?,deliver?}, stack?, response?, responseShape? })` — realtime CHANNEL lifecycle. Inputs: `t.action` (`join|leave|deliver`), `t.channel`, `t.payload`, `t.client`. Bind `channel` to a `realtimeChannel()` handle — a bare path is NOT accepted (it is unique only within its server). The three actions have DIFFERENT postures, and the posture decides what the stack should return:
|
|
805
|
+
- `join` GATES the join (it runs BEFORE the client becomes a member, so a denial means it never sees a fan-out) — return `{ allowed: c.bool(true) }` (optional `reason` reaches the client) or any truthy value to admit, and an EMPTY OR FALSY RETURN DENIES, so a stack that just falls through — or a gating trigger with NO `response` — refuses everyone, and a CRASH DENIES too. ONCE the object carries an `allowed` key admission needs STRICTLY `true` — a computed `1`/`"yes"` there DENIES. That is the inverse of a crashing message, which still delivers, and of `deliver` below.
|
|
806
|
+
- A lifecycle trigger's inputs are PINNED to those four, so a channel PATH PARAM is NOT among them — `inp("room_id")` RAISES, which crashes the gate and so REFUSES every client; take the param from `s.realtime.get_session` (`ref("session.params.room_id")`).
|
|
807
|
+
- A gate establishes NO auth, so `ref("auth.id")` reads 0 even when authenticated — identity is `t.client("permissions.dbo_id")` or the session. A SERVER connect/disconnect has no channel, so no params at all.
|
|
808
|
+
- `leave` is OBSERVATIONAL (return ignored, throws swallowed).
|
|
809
|
+
- `deliver` GATES delivery PER RECIPIENT — the per-viewer redaction tool and the most expensive action here (a stack per recipient per message), and it needs `delivery.perRecipient` on the channel to run at all — BOTH HALVES are required, so a `deliver` trigger on a channel without the flag NEVER RUNS and every subscriber receives the UNREDACTED payload (no error, no log line); `export()` warns on each half alone.
|
|
810
|
+
- **`deliver`'s RETURN VALUES DO NOT READ LIKE A FILTER:** ONLY an explicit NULL drops the message for that recipient; an OBJECT replaces that recipient's payload; ANYTHING ELSE — INCLUDING `false`, `0`, `""` — DELIVERS IT UNCHANGED, as does a crash. So `return false` from a yes/no redaction check SENDS the message it was written to suppress — return null instead.
|
|
811
|
+
- The delivered payload arrives NESTED, so read `t.payload("<field>")`, and `t.client` is the SENDER while `s.realtime.get_session` describes the RECIPIENT this run is for.
|
|
777
812
|
- `mcpServerTrigger({ name, mcpServer, stack?, response?, responseShape? })` / `agentTrigger({ name, agent, stack?, response?, responseShape? })` — toolset connection. Bind with the `mcpServer()`/`agent()` def handle (or its name) — it resolves to the toolset guid at export. Raw numeric `objId` is the escape hatch, rarely right: ids are assigned at import, so a handle passed to `objId` is a type error, and binding nothing deploys a trigger that never fires. Inputs: `t.toolset` (`t.toolset("name")`), `t.tools`. Response-bearing; the default stack copies `toolset`/`tools` into vars and returns them.
|
|
778
813
|
- `workspaceTrigger({ name, actions?: {branch_live?,branch_merge?,branch_new?}, stack? })` — branch lifecycle. Inputs: `t.to_branch`, `t.from_branch`, `t.action`. Config-only.
|
|
779
814
|
- `errorTrigger({ name, stack? })` — error-signature trigger. Inputs: `t.event` (`new|regression|fixed`), `t.id`, `t.signature`, `t.error` (`t.error("code")`/`t.error("message")`), `t.caller`, `t.statement`, `t.actor`, `t.count`, `t.first_seen`, `t.last_seen`, `t.fixed_at`. Config-only.
|
|
@@ -846,7 +881,7 @@ primary key `id`):
|
|
|
846
881
|
|
|
847
882
|
# Statement runtime behavior
|
|
848
883
|
|
|
849
|
-
> Read when you need to know what a statement's `as:` output
|
|
884
|
+
> Read when you need to know what a statement's `as:` output holds, or why a bound variable is not the shape expected.
|
|
850
885
|
|
|
851
886
|
Runtime behavior (what the `as:` output holds, and misses):
|
|
852
887
|
|
|
@@ -884,12 +919,27 @@ Runtime behavior (what the `as:` output holds, and misses):
|
|
|
884
919
|
- Attaching a typed `addon({ table, output })` handle merges its alias (the last `as` segment) onto the row in `InferResponse`: `{cols}` for `single`, `{cols}[]` for `list`, `number` for `count`, `boolean` for `exists`, and for `aggregate` an array keyed by the `group`/`eval` aliases (`unknown` values; `unknown` when neither is declared).
|
|
885
920
|
- An attachment-level `output` narrows an object/array graft further. A bare-NAME reference grafts `unknown` — narrow it at the call site.
|
|
886
921
|
- ⚠ An alias that shadows an existing column on the queried table throws at build time; rename with a `_` prefix.
|
|
887
|
-
- **Middleware attachment** runs a reusable `middleware({...})` before/after a host's own stack.
|
|
888
|
-
-
|
|
889
|
-
-
|
|
922
|
+
- **Middleware attachment** runs a reusable `middleware({...})` before/after a host's own stack. Distinct from `s.middleware.call` (inline invoke).
|
|
923
|
+
- Attach with the host's `middleware: { pre, post }` field on `query`/`function`/`task`/`tool`/`apiGroup` (NOT triggers): each phase is an ordered list of middleware refs (def handle or name), or `{ middleware, active: false }` to keep an entry disabled.
|
|
924
|
+
- Providing a phase **overrides** it (sets the stored `pre_customize`/`post_customize` flag); omitting a phase **inherits** the parent tier's chain — the engine resolves Query → API Group → Workspace at request time (override, not merge; the API-Group tier applies to queries — functions/tasks/tools have no API-group binding and inherit straight from the workspace).
|
|
925
|
+
- Prefer a def handle over a bare name when the middleware pins an explicit `guid`.
|
|
926
|
+
- `pre: middleware.clear()` (an empty list) overrides with nothing — stop inheriting.
|
|
927
|
+
- Workspace-level defaults are the terminal tier: `workspaceConfig({ middleware: { query: { pre }, function, task, tool } })` emits the flat `{host}_{phase}` map (no `_customize` flags) — setting it replaces the whole workspace map, so unlisted hosts are cleared; omit the field to leave existing workspace middleware untouched.
|
|
928
|
+
- **Middleware request context.** A `pre` middleware runs **after** auth resolution, so `auth()` is available inside the middleware when the host is authenticated (its `auth` names an auth table); on a public host `auth()` is `null`.
|
|
929
|
+
- This matters for the canonical use — a rate limit keyed by `auth("id")`: on an authenticated endpoint the bucket is per-user, but attach the same middleware to a public endpoint and every anonymous caller keys under the same `null` id (one shared bucket), silently.
|
|
930
|
+
- To catch that, `export()` **warns** (never blocks) when a middleware whose stack references `auth()` is directly attached to a host where `auth()` may be null — a `query` with no auth table, a `task` (scheduled, never authenticated), or a `function`/`tool` (whose auth is caller-dependent). An authenticated query (its own `auth` table set) is skipped.
|
|
931
|
+
- The check is direct-attachment only; a middleware reaching a public query via API-group/workspace tier inheritance is not caught.
|
|
932
|
+
- **Rate-limit recipe (the canonical middleware).** Per-user rate limiting is the most common middleware. Author it with `s.redis.ratelimit` and a **composite key** built via the filter chain — `"prefix" + auth("id")` does not exist, you build the key: `middleware({ name: "write_rl", exceptionPolicy: "rethrow", stack: [ s.redis.ratelimit({ key: withFilters(c.text("rl:write:"), fl.concat(auth("id"))), max: c.int(10), ttl: c.int(30), error: c.text("Too fast.") }) ] })`.
|
|
933
|
+
- `exceptionPolicy` defaults to `"rethrow"`, which is what makes a tripped limit abort with HTTP 429; `"silent"` would let the over-limit request through.
|
|
934
|
+
- Attach it with `middleware: { pre: [writeRl] }` on an **authenticated** host (its `auth` set) so `auth("id")` keys per-user; on a public host `auth("id")` is null and every caller shares one bucket (`export()` warns — see request context above).
|
|
935
|
+
- **Shared-bucket rule:** co-attaching one middleware object to N hosts means all N share the *same* key ⇒ *one* counter — `max: 10` is a global per-user budget across them, not 10-per-host. Vary the key (fold in the host/action name) for an independent limit per host.
|
|
890
936
|
- **Middleware `exceptionPolicy`** governs what a **throw** in the middleware stack does to the request (XanoTS passes the value through; the Xano engine interprets it). `"rethrow"` is the **default** — the throw aborts the request and surfaces the authored `error`/status (a tripped `s.redis.ratelimit` → HTTP 429); the `post` chain still runs. `"silent"` swallows the throw, so a guard set to it is **not enforced** — advisory middleware only. `"critical"` is `"rethrow"` plus skipping the `post` chain. The only difference between `rethrow` and `critical` is whether `post` runs — no status or logging change.
|
|
891
937
|
|
|
892
|
-
- **Request history** controls per-object execution capture (the request/task/trigger debugger). Authored as a single scalar `history` field on any primitive: `false` off, `true` on at the default capture depth, a number = capture depth (how many statement executions are recorded per history record — NOT record retention), `"all"` unlimited.
|
|
938
|
+
- **Request history** controls per-object execution capture (the request/task/trigger debugger). Authored as a single scalar `history` field on any primitive: `false` off, `true` on at the default capture depth, a number = capture depth (how many statement executions are recorded per history record — NOT record retention), `"all"` unlimited.
|
|
939
|
+
- **Omit `history` to inherit** — the engine resolves object → container → workspace at request time (a query inherits from its API group, a tool from its toolset envelope, everything else straight from the workspace). Any authored value stops inheriting for that object.
|
|
940
|
+
- Per-kind defaults (when inheriting): query/task/tool capture ON, function/trigger/middleware OFF; default depth 100.
|
|
941
|
+
- Container tiers are authorable too — `apiGroup({ history })` sets the `query_*` default its queries inherit, and an agent/mcp_server/toolset `history` sets the `tool_*` default its tools inherit.
|
|
942
|
+
- Workspace-level defaults are the terminal tier: `workspaceConfig({ history: { query, function, task, tool, trigger, middleware } })` emits the flat `{objType}_enabled`/`{objType}_limit` map (no inherit flag) — setting it is wholesale (unlisted types fall back to their engine default), so declare every default you want to keep; omit the field to leave existing workspace history untouched.
|
|
893
943
|
|
|
894
944
|
- **Workspace environment variables** set a tenant's env vars through the workspace object: `workspaceConfig({ env: { STRIPE_KEY: process.env.STRIPE_KEY!, APP_BASE_URL: "https://…" } })`. Author them as a name→value MAP. Read a var back with `env("NAME")` (→ `$env.NAME`), which compiles to tag "setting" with the plain name. Values are SECRETS: prefer sourcing from `process.env` over committing literals, and don't commit a compiled bundle with real values. `deploy` REPLACES the tenant's env with the declared map; `release` (merge) is ADD-ONLY — it creates missing keys but does NOT update or remove existing ones, so changing a value in code and releasing leaves the live value unchanged. Omit `env` to leave existing env untouched. The separate `settings` field is a plain object.
|
|
895
945
|
|
|
@@ -908,8 +958,20 @@ Auth & calls:
|
|
|
908
958
|
- `s.security.create_guid({ as? })` — bind a fresh GUID string. Takes nothing else.
|
|
909
959
|
- `s.function.run({ fn, input?, as?, runtime? })` / `s.function.call({ fn, input?, as? })` — run another function; `input` is keyed by the target's input names.
|
|
910
960
|
- `runtime?` runs it in the BACKGROUND: `{ mode: "async-shared" }` or `{ mode: "async-dedicated", cpu?, memory?, timeout?, maxRetry? }` (resources read at dedicated only). An async call DOES NOT return the result — it dispatches and continues, so `as` binds nothing; collect with `s.await({ ids })`. Omit for a normal call. Same block on `s.ai.agent.run`.
|
|
911
|
-
- `s.api.call({ api, input?, headers?, auth?, as? })` — invoke an endpoint.
|
|
912
|
-
- `
|
|
961
|
+
- `s.api.call({ api, input?, headers?, auth?, as? })` — invoke an endpoint. WORKFLOW-TEST ONLY (see Gotchas in `llms.txt`).
|
|
962
|
+
- `api` takes the `query()` def HANDLE (or a `{ name, guid }` pair) — a bare name is refused, because a query's identity is composed from its api group, verb, and name.
|
|
963
|
+
- `headers` REPLACES the request headers the callee sees and takes the same shapes as `s.api.request`'s — a `{ "Name": value }` record (values may be tagged), a `string[]` of `"Name: value"` lines, or one `Value`.
|
|
964
|
+
- `auth` is `{ token, ignoreExpiration? }`: `token` must be a BARE STRING — a tagged `Value` deploys clean and then fails the run with `Param: token - Text filter requires an integer, float, string or boolean value`, since the engine stores that slot as plain text and never evaluates it.
|
|
965
|
+
- Neither slot authenticates the call today; see `llms/tests.md` for what a workflow-test run actually sees.
|
|
966
|
+
- `s.api.request({ url, method?, params?, headers?, timeout?, follow_location?, verify_host?, verify_peer?, ca_certificate?, certificate?, certificate_pass?, private_key?, private_key_pass?, description?, output?, as? })` — external HTTP request (`mvp:api_request`). Ergonomic types, each also accepting a dynamic `Value`:
|
|
967
|
+
- `method` suggests the 7 verbs (GET/POST/PUT/DELETE/HEAD/OPTIONS/PATCH).
|
|
968
|
+
- `params` a plain JSON object **or** a FLAT record whose values are tagged `Value`s (`{ count: ref("count") }`, each lifted via a `set` filter — the same record-of-values shape `response: { key: value }` takes); a tagged value NESTED inside an object or array THROWS at encode, so wrap a structured body in `obj({...})`, which encodes any depth as one `const:expr2` (→ query string for GET/HEAD/OPTIONS, body otherwise).
|
|
969
|
+
- `headers` a `{ "Name": value }` record whose values may be tagged (`{ "x-api-key": env("KEY") }`, each pair joined to a `"Name: value"` line) **or** a `string[]` of full header lines — prefer a header over a `?key=` query param for a credential — a URL travels into access logs, proxies and `Referer`.
|
|
970
|
+
- ⚠ Neither spelling is envelope-safe: the `as` envelope's `request` half mirrors `url`, `params` AND `headers`, so never return it raw from a credentialed request — read `response.result`.
|
|
971
|
+
- A NAME outside the header-token charset is refused, and a LITERAL value carrying a newline is refused; a value may hold `:` and spaces (`Bearer a: b` is a valid value). A TAGGED value cannot be checked at build time, so strip CRLF from caller-controlled input before this slot. Literal pairs lead the emitted array and computed ones follow, so the wire order is not the record's key order.
|
|
972
|
+
- `timeout` a `number` in seconds (1–86400), and `follow_location`/`verify_host`/`verify_peer` booleans.
|
|
973
|
+
- `description` (Settings tab) and `output` filters (Output tab) ride the envelope. SSL cert interdependencies (certificate↔private_key, ca_certificate→verify_peer) are checked at build time when statically provable, else by the engine at runtime.
|
|
974
|
+
- The `as` result is typed as the `{request, response}` envelope (`response.status: number`, `response.result: unknown`), so `InferResponse` resolves a `ref` to it. Same typed result on `webflow.request` and `microservice.request`.
|
|
913
975
|
- `s.stream.from_request({ url, method?, …tls, as? })` — streaming external HTTP request (`mvp:streaming_api_request`); same typed field surface as `s.api.request` (no description/output envelope). `url` is REQUIRED — it shares `api.request`'s engine declaration, which has no default.
|
|
914
976
|
- `s.util.send_email({ to, subject, message, from?, cc?, bcc?, reply_to?, service_provider?, api_key?, scheduled_at?, as? })` — send email from the stack. `service_provider` is `"xano"` (the built-in mailer — needs NO `api_key` and no configuration, and does not require a verified sender) or `"resend"` (pass the key as `api_key: env("RESEND_API_KEY")`). Prefer this over hand-rolling `s.api.request` against a mail provider.
|
|
915
977
|
- `s.webflow.request({ path, method?, …tls, as? })` — Webflow API request (`mvp:connect_webflow_api_request`); like `s.api.request` but addressed by `path` (host is engine-supplied), and `path` is REQUIRED — the engine rejects an empty one. No `headers`: the engine builds its own from the workspace's Webflow connection and ignores an authored value.
|
|
@@ -920,9 +982,18 @@ Auth & calls:
|
|
|
920
982
|
|
|
921
983
|
Microservices (the `microservice()` def and the statement that calls it):
|
|
922
984
|
|
|
923
|
-
- `microservice({ name, kind, … })` — two mutually exclusive shapes via `kind`: `builtin` declares containers (image/ports/resources/env/command/args) plus optional `ingresses`, and `helm` points at a chart and its `values` — passing both throws.
|
|
985
|
+
- `microservice({ name, kind, … })` — two mutually exclusive shapes via `kind`: `builtin` declares containers (image/ports/resources/env/command/args) plus optional `ingresses`, and `helm` points at a chart and its `values` — passing both throws.
|
|
986
|
+
- EARLY SURFACE, expected to change — every export of a workspace declaring one prints a notice saying so.
|
|
987
|
+
- `configs`/`volumes` are typed and `@deprecated` but NOT deployable: the engine rejects an import carrying either, so `export()` fails the build rather than letting the deploy fatal.
|
|
988
|
+
- Put a value the workload reads in a container's `env`, and storage in a container's own `volumes` (`emptyDir`/`persistent`/`config`).
|
|
989
|
+
- Container names are free-form — they need not match the microservice name, which is what a stack addresses.
|
|
924
990
|
- SECRETS RIDE ALONG — `chart.values` and `registryAuth.dockerconfigjson` are carried into the bundle, and into a pulled tree, verbatim (they must be, or a pulled microservice could not be redeployed). Both are stored strings with NO deploy-time indirection: `process.env.X` in the def resolves at EXPORT and writes the literal into the bundle, so it is not a way to keep the credential out. Either leave `registryAuth` unset (public image, or a credential attached outside this workspace) or treat the bundle and any pulled tree as secret material — keep them out of git, or rotate after. Export prints a notice per microservice carrying either field; `--strict` does not promote it. For a secret a STACK reads, the mapped surface is `workspaceConfig({ env })` + `env("NAME")`.
|
|
925
|
-
- `s.microservice.request({ host, path, port?, method?, params?, headers?, timeout?, follow_location?, as? })` — in-cluster microservice call (`mvp:microservice_request`); no TLS fields.
|
|
991
|
+
- `s.microservice.request({ host, path, port?, method?, params?, headers?, timeout?, follow_location?, as? })` — in-cluster microservice call (`mvp:microservice_request`); no TLS fields.
|
|
992
|
+
- ONLY `host`+`path` required; the rest default to the engine's values (`GET`/`{}`/`[]`/`10`/`true`), always emitted.
|
|
993
|
+
- Pass the `microservice()` DEF as `host` — it binds by NAME (how the engine resolves it), so a rename fixes every call site and the port is checked before deploy.
|
|
994
|
+
- `port?` folds into `host` as `"name:port"`: a def exposing ONE `servicePort` resolves automatically, SEVERAL requires it.
|
|
995
|
+
- A raw `"name:port"` string works, unvalidated, and is the only way to reach an instance-level microservice.
|
|
996
|
+
- `tenantDeploy: "manual"` on the def imports the row without starting the workload.
|
|
926
997
|
- `s.workflow_test.call({ workflowTest, datasource?, as? })` — run another workflow test from inside one, which is the only place it runs (see Gotchas in `llms.txt`). The odd one out: NO `input` (a workflow test takes none), and it carries `datasource?` instead — same clone caveat as the kind's own field.
|
|
927
998
|
|
|
928
999
|
# Value catalog
|
|
@@ -935,11 +1006,11 @@ Microservices (the `microservice()` def and the statement that calls it):
|
|
|
935
1006
|
- `c.blank(tag: "const:<type>") => Value` — The editor's UNCONFIGURED value box (stored value ""), emitted by codegen for a pulled workspace — do not author it. NOT a zero or an empty collection: the engine reads "" and "0" differently, so c.blank("const:int") ≠ c.int(0) and neither canonicalizes into the other. Constant tags except const/const:obj, whose blanks are c.text("")/c.obj(null).
|
|
936
1007
|
- `c.bool(b: boolean) => Value` — Boolean constant → tag "const:bool".
|
|
937
1008
|
- `c.null(tag?: "const:null" | "const:obj") => Value` — Null constant, stored value "null". Bare c.null() is tag "const:null". c.null("const:obj") is the OBJECT-TYPED null the engine writes into a db.* statement's @meta slot — different stored bytes from c.obj(null), which is the blank object (value ""), though both evaluate to null. Codegen emits whichever spelling the workspace stored; do not swap one for the other.
|
|
938
|
-
- `c.obj(o?: Json | null) => Value` — Object constant → tag "const:obj". A populated one stores an empty {} carrying one `set` filter per key — the editor's form, and the only populated form the engine reads back (a populated JSON string arrives truncated and fails the request with ERROR_FATAL "Unable to decode."). ⚠ a ZERO-BASED numeric key is an INDEX in the engine's data model, so c.obj({"0":"a"}) evaluates to the list ["a"] (a non-zero-based one like {"2":…} survives as a key) — that is the platform, not this encoding. No argument = the empty object {} — use this one. Explicit null = the legacy blank form the engine evaluates to null, NOT {}; it exists only so a pulled workspace round-trips, do not author it. Plain JSON literals only — a nested tagged value (inp/ref/auth/c.*) is rejected; for a computed object response use a record of values, not c.obj.
|
|
1009
|
+
- `c.obj(o?: Json | null) => Value` — Object constant → tag "const:obj". A populated one stores an empty {} carrying one `set` filter per key — the editor's form, and the only populated form the engine reads back (a populated JSON string arrives truncated and fails the request with ERROR_FATAL "Unable to decode."). ⚠ a ZERO-BASED numeric key is an INDEX in the engine's data model, so c.obj({"0":"a"}) evaluates to the list ["a"] (a non-zero-based one like {"2":…} survives as a key) — that is the platform, not this encoding. Write c.array([...]) for a list, or prefix the keys ("k0") for an object; `export()` warns. No argument = the empty object {} — use this one. Explicit null = the legacy blank form the engine evaluates to null, NOT {}; it exists only so a pulled workspace round-trips, do not author it. Plain JSON literals only — a nested tagged value (inp/ref/auth/c.*) is rejected; for a computed object response use a record of values, not c.obj.
|
|
939
1010
|
- `c.array(a: Json[]) => Value` — Array constant (JSON string) → tag "const:array". Plain JSON literals only — a nested tagged value is rejected, same as c.obj.
|
|
940
1011
|
- `c.expression(source: string) => Value` — Xano Expression Engine source, passed through VERBATIM → tag "const:expr2". The string IS the expression: c.expression('"Hi, " ~ $input.name'), c.expression("$var.price * $var.qty"). ⚠️ NOT VALIDATED — never parsed or type-checked, invisible to InferResponse, and untouched by a rename that updates every typed ref(); a typo surfaces at runtime or as a wrong answer. Use it ONLY for syntax the typed surfaces cannot express (~ concatenation, inline arithmetic, conditionals) — prefer ref/inp/col, withFilters+fl.*, and obj() (which BUILDS a checked expression). Not the expr() condition builder.
|
|
941
1012
|
- `c.now() => Value` — Current time as epoch-ms — the engine-native const:epochms constant (no filter). Valid inline as a where/cmp operand. For cutoff math (cutoff = now - max_age) either compare inline or, for reuse/readability, hoist it into an s.set_var and compare against the var.
|
|
942
|
-
- `obj(fields: Record<string, Value | nested>) => ObjValue<typeof fields>` — Dynamic object value → tag "const:expr2" (an object-literal expression string). The dynamic sibling of c.obj: members may be inp/ref/auth/col values, env()/setting()/sys.*, c.now(), c.* constants, nested records, or arrays — and each member may carry a FILTER CHAIN (withFilters + fl.*), which renders as the expression pipe `$var.row|get:"a.b"`.
|
|
1013
|
+
- `obj(fields: Record<string, Value | nested>) => ObjValue<typeof fields>` — Dynamic object value → tag "const:expr2" (an object-literal expression string). The dynamic sibling of c.obj: members may be inp/ref/auth/col values, env()/setting()/sys.*, c.now(), c.* constants, nested records, or arrays — and each member may carry a FILTER CHAIN (withFilters + fl.*), which renders as the expression pipe `$var.row|get:"a.b"`. A null-safe ref(path, { safe: true }) works inside an obj() member directly. The member record rides the return type, so InferResponse resolves each member the way it resolves a top-level response key — `response: { user: obj({ id: ref("row.id") }) }` derives `{ user: { id: Col | null } }`, and a raw nested object literal (`response: { user: { id: ref("row.id") } }`, auto-wrapped through this) derives the same. A constant record or list has two spellings that both work and render identically: bare (`{ a: 1 }`, `[]`) or `c.obj(...)`/`c.array([...])` — prefer the bare form. NEST WITH A RAW RECORD, not an inner obj() call: an inner call yields a const:expr2 value, which the expression serializer has no spelling for and THROWS. The legacy blank `c.obj(null)` is refused here (it evaluates to null, not {}) — write c.null() or c.obj(). Still rejected: a filter ARGUMENT that carries its own chain or is a c.now() (a trailing | binds to the whole value, not one argument, and c.now() needs one), a DISABLED filter (an expression string cannot record that), and the output/response/toolset/reg tags — build those in a prior step and ref() them. Use for e.g. s.ai.agent.run args.
|
|
943
1014
|
- `ref(name: string, opts?: { safe?: boolean }) => Value` — Reference a stack variable → tag "var". Pass { safe: true } for null-safe nested access — a dotted ref("owner.user_id", { safe: true }) compiles through the get filter so it resolves to null instead of raising "Unable to locate var" when the base is null.
|
|
944
1015
|
- `inp(name: string) => Value` — Reference a function/endpoint input → tag "input". Resolves ONLY against the `input` block of the def it sits in — a value produced earlier in the stack is `ref("var.field")`, not `inp("field")`. A name that is not declared here deploys clean and fails at runtime with ERROR_FATAL "Unable to locate input: <name>" on every branch that reads it; `export()` warns, and `--strict` fails the build. Sending the name in the request does NOT rescue it — an undeclared input is never bound, so the call fails identically with the value present. A dotted path drills INTO a declared input (`inp("action.amount")` needs a declared `action`).
|
|
945
1016
|
- `col(name: string) => Value` — Reference a table column → tag "col".
|
|
@@ -957,7 +1028,7 @@ Tags: const, const:int, const:decimal, const:bool, const:array, const:obj, const
|
|
|
957
1028
|
|
|
958
1029
|
# Column and input types
|
|
959
1030
|
|
|
960
|
-
> Read when declaring a table column (`f.*`) or a function/query input (`input.*`) — a type's options and
|
|
1031
|
+
> Read when declaring a table column (`f.*`) or a function/query input (`input.*`) — a type's options and methods, and the `s.precondition` error/status contract. Also `table({ seed })` rows and `use_xdo`.
|
|
961
1032
|
|
|
962
1033
|
Author table columns + function/API inputs with the typed catalog: `f.<type>(opts?)`
|
|
963
1034
|
for columns, `input.<type>(opts?)` for inputs. Common opts: `required`, `nullable`,
|
|
@@ -1002,6 +1073,31 @@ any `SearchOp`: give the table `index: [{ type: "vector", fields: [{ name: "embe
|
|
|
1002
1073
|
queries it.
|
|
1003
1074
|
`{ array: true }` makes any `f.*` scalar a **list column** — `f.text({ array: true })`
|
|
1004
1075
|
surfaces as `string[]` in `InferRow<typeof table>` (the column analogue of `input.list`).
|
|
1076
|
+
**Seed a table's starting rows with `table({ seed })`.** `seed` takes rows
|
|
1077
|
+
typed against the table's schema as a WRITE shape (a column without
|
|
1078
|
+
`required: true`, and the system columns, may be omitted; `null` needs
|
|
1079
|
+
`nullable: true`) — inline (`seed: [{ name: "…" }]`), a FILE
|
|
1080
|
+
(`seed: seedFile("./seed.json", import.meta.url)`; path resolves against the DECLARING
|
|
1081
|
+
file), or a thunk (`seed: () => import("./seed.json")`, async ok, `.default` unwrapped).
|
|
1082
|
+
Inline rows are TYPED against the schema at compile time; a `seedFile`/thunk seed is
|
|
1083
|
+
NOT — the JSON is opaque to the typechecker, and the `xanots export`/`deploy` CLI
|
|
1084
|
+
validates it instead, naming the row index, the offending column, and the known
|
|
1085
|
+
columns. ⚠ Prefer `seedFile` for a file: a thunk's `import()` sits in
|
|
1086
|
+
YOUR module, so a bundler emits the JSON as a served chunk. NEITHER is a secrecy
|
|
1087
|
+
boundary — a bundler that inlines the asset ships them either way. Never put secrets
|
|
1088
|
+
in `seed`. `deploy --static` REFUSES a build carrying internal/sensitive seed values;
|
|
1089
|
+
`--allow-seed-in-static` overrides for deliberately public demo credentials.
|
|
1090
|
+
Deploy is a full replace, so re-deploying re-seeds
|
|
1091
|
+
cleanly (no duplication). Omit `id` and rows auto-number `1..N` (int PK) or take
|
|
1092
|
+
a stable derived uuid (uuid PK); supplying `id` pins it (engine preserves it,
|
|
1093
|
+
resets an int sequence past the max). All-or-nothing — mixing explicit and
|
|
1094
|
+
omitted `id` throws. A `system:false` PK is the author's to supply. Pinning is
|
|
1095
|
+
`seed`-only — `s.db.bulk.add` DROPS `id` unless `allowIdField: true`.
|
|
1096
|
+
**`use_xdo` storage mode.** Workspace setting (`registerWorkspace({ use_xdo })`,
|
|
1097
|
+
default `false`) controlling whether fields are stored as JSON under the `xdo`
|
|
1098
|
+
column (`true`, adds a `gin(xdo)` index) or as real columns (`false`, no gin).
|
|
1099
|
+
Tables inherit it; override per-table with `table({ useXdo })`. Resolved at
|
|
1100
|
+
`export()`, so the workspace and tables can be registered in any order.
|
|
1005
1101
|
A **column `default` must stay within the BMP** — a 4-byte character (codepoint > U+FFFF,
|
|
1006
1102
|
e.g. an emoji) is mangled into invalid UTF-8 by the engine's default pipeline and is rejected
|
|
1007
1103
|
at export rather than 500ing at deploy (Postgres `22021`); BMP defaults (accents, `€`, most
|
|
@@ -1110,14 +1206,10 @@ statement, and one CANNOT be synthesized in the SDK (it would compile to this sa
|
|
|
1110
1206
|
database with a single `s.db.direct_query` UPDATE (`SET clicks = clicks + 1 WHERE …`),
|
|
1111
1207
|
which the DB applies atomically. Reserve the pipeline form for low-contention counters
|
|
1112
1208
|
where a rare lost update is acceptable.
|
|
1113
|
-
⚠ `direct_query` needs the table's PHYSICAL Postgres name, which the typed surface
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
created afresh and the id in its name moves each time, on the same unchanged project. So
|
|
1118
|
-
the safe counter drops out of the typed surface: resolve the physical name from
|
|
1119
|
-
`information_schema` inside the request that uses it, and never store, cache or hardcode
|
|
1120
|
-
one. A typed atomic path needs an engine change.
|
|
1209
|
+
⚠ `direct_query` needs the table's PHYSICAL Postgres name, which the typed surface does NOT
|
|
1210
|
+
expose and which is NOT STABLE across deploys — resolve it from `information_schema` inside
|
|
1211
|
+
the request that uses it, never store or hardcode one (rules under `s.db.direct_query` in
|
|
1212
|
+
`llms/statements-data.md`). A typed atomic path needs an engine change.
|
|
1121
1213
|
|
|
1122
1214
|
- `fl.add(value: decimal): decimal`
|
|
1123
1215
|
- `fl.append(value: <T>, path: text): <T>[]`
|
|
@@ -1257,7 +1349,7 @@ Variadic filters — they take arguments, but no declared list, so the count is
|
|
|
1257
1349
|
|
|
1258
1350
|
# Lambda bodies (JavaScript)
|
|
1259
1351
|
|
|
1260
|
-
> Read when writing a JavaScript body, or weighing whether to reach for one at all — `lam.fn`, `fl.lambda`, `fl.reduce`, `s.lambda
|
|
1352
|
+
> Read when writing a JavaScript body, or weighing whether to reach for one at all — `lam.fn`, `fl.lambda`, `fl.reduce`, `s.lambda`; each surface binds a different set of identifiers.
|
|
1261
1353
|
|
|
1262
1354
|
**A lambda is an escape hatch, not a default.** The body runs outside the request's own
|
|
1263
1355
|
runtime, and a workspace has a BOUNDED pool of lambda workers every lambda in it shares
|
|
@@ -1402,7 +1494,7 @@ object. CI: `--frozen-lock` fails instead of changing the lock.
|
|
|
1402
1494
|
|
|
1403
1495
|
# Legacy paradigms and retired statements
|
|
1404
1496
|
|
|
1405
|
-
> Read when the code was PULLED from an existing Xano instance
|
|
1497
|
+
> Read when the code was PULLED from an existing Xano instance — how a codegen'd tree reads, the shapes in it that must not be "fixed", and any `raw({ name: "mvp:…" })`, `realtimeTrigger()`, or name the catalogs do not list.
|
|
1406
1498
|
|
|
1407
1499
|
Older paradigms this SDK still supports and still emits when it decodes an existing
|
|
1408
1500
|
workspace. **Do not author these.** They are listed by name only so you recognize them
|
|
@@ -1446,7 +1538,7 @@ var VALUES ride inline in `xano/workspace.ts`, so treat a pulled tree as secret-
|
|
|
1446
1538
|
|
|
1447
1539
|
# Statement catalog
|
|
1448
1540
|
|
|
1449
|
-
> Read for the field signature of a specific statement — every surface, grouped by `s.*` namespace.
|
|
1541
|
+
> Read for the field signature of a specific statement — every surface, grouped by `s.*` namespace.
|
|
1450
1542
|
|
|
1451
1543
|
### (top-level)
|
|
1452
1544
|
|