@proveanything/smartlinks 2.0.31 → 2.0.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,628 +1,629 @@
1
- # Server functions ("edge functions")
2
-
3
- > **SmartLinks SDK 2.x** (current `latest`). Part of the installable-app platform
4
- > (author → register → install → run → test). Install `@proveanything/smartlinks@^2`.
5
-
6
- A **server function** is arbitrary server-side JavaScript your app deploys directly into
7
- SmartLinks. It runs on the SmartLinks servers — with access to the full SDK, to your app's
8
- secrets, and to outbound network — so you can do things a browser app can't: validate and
9
- write on the server, call third-party systems with credentials the client never sees, react
10
- to events, and run scheduled work.
11
-
12
- Every server function has the **same shape**, no matter how it's triggered or where it runs:
13
-
14
- ```ts
15
- export async function myFunction(ctx, event) {
16
- // ctx — a SmartLinks SDK pre-scoped to your declared authority, plus secrets, caller, fetch, log
17
- // event — the trigger payload (the HTTP body, the event, or the cron tick)
18
- return { ok: true } // returned to the caller (http) or recorded as the run result (event/cron)
19
- }
20
- ```
21
-
22
- You never receive a raw API key or a superuser client. The platform builds `ctx` fresh for
23
- each invocation and **pre-scopes every handle to exactly what your function declared** — this
24
- is how a function stays safe even when it runs with elevated authority.
25
-
26
- ---
27
-
28
- ## Declaring a function
29
-
30
- Functions are declared in your `app.manifest.json` under `functions`, and the handlers ship
31
- in a bundle alongside your widgets/containers:
32
-
33
- ```jsonc
34
- {
35
- "functions": {
36
- "files": { "js": { "umd": "dist/functions.umd.js" } },
37
- "definitions": [
38
- {
39
- "name": "submitCompetitionEntry",
40
- "description": "Validate a competition entry and record it server-side.",
41
- "trigger": { "type": "http", "methods": ["POST"] },
42
- "visibility": "public", // WHO may call it
43
- "authority": "collection", // WHOSE authority it runs as
44
- "elevated": true, // required ack for public + collection
45
- "capabilities": ["sl:records:write", "network:api.recaptcha.net"],
46
- "apiVersion": "2026-09"
47
- },
48
- {
49
- "name": "onProofCreated",
50
- "trigger": { "type": "event", "eventTypes": ["proof.created"] },
51
- "capabilities": ["sl:records:write", "secrets:crm-key", "network"]
52
- },
53
- {
54
- "name": "nightlyReconcile",
55
- "trigger": { "type": "cron", "schedule": "0 2 * * *" },
56
- "capabilities": ["sl:products:read", "sl:records:write"]
57
- }
58
- ]
59
- }
60
- }
61
- ```
62
-
63
- Each definition maps to an exported handler of the same `name` (override with `handler`).
64
-
65
- ## Building the functions bundle
66
-
67
- The handlers ship as a **self-contained UMD** — one file, all dependencies compiled in, no
68
- `require`/`import` of platform or Node modules (see [Runtime](#runtime--what-your-function-can-use)).
69
- Your functions entry just **named-exports** each handler:
70
-
71
- ```js
72
- // src/functions/index.js — the functions entry
73
- export async function submitCompetitionEntry(ctx, event) { /* … */ }
74
- export async function onProofCreated(ctx, event) { /* … */ }
75
- ```
76
-
77
- Build it to `dist/functions.umd.js` with a Vite lib build — **UMD format, nothing externalised**
78
- (so it's self-contained), and don't wipe the widgets you built into the same `dist/`:
79
-
80
- ```ts
81
- // vite.functions.config.ts
82
- import { defineConfig } from 'vite'
83
- export default defineConfig({
84
- build: {
85
- lib: { entry: 'src/functions/index.js', formats: ['umd'], name: 'functions',
86
- fileName: () => 'functions.umd.js' },
87
- outDir: 'dist',
88
- emptyOutDir: false, // co-exist with the widgets/containers build
89
- rollupOptions: { external: [] } // bundle everything — no Node/platform externals
90
- },
91
- })
92
- ```
93
-
94
- ```jsonc
95
- // package.json — build widgets/containers as usual, then the functions bundle
96
- "scripts": {
97
- "build": "vite build && vite build --config vite.functions.config.ts"
98
- }
99
- ```
100
-
101
- That emits `dist/functions.umd.js` (matching `functions.files.js.umd`), whose named exports the
102
- platform pairs with your manifest `definitions`. Then **deploy** it — for dev,
103
- `smartlinks-publish` uploads `dist/` and registers in one step (see
104
- [Deploying & registering](deploying-apps.md)).
105
-
106
- ---
107
-
108
- ## The two security questions every function answers
109
-
110
- Server-side code needs two questions answered up front. SmartLinks makes both **explicit and
111
- declarative** — you state them in the manifest, and the platform enforces them. This is the
112
- same split every extensible platform lands on (Salesforce `with/without sharing`, Shopify
113
- online/offline tokens, Lambda's invoke-policy vs execution-role).
114
-
115
- ### 1. `visibility` — who is allowed to call it? *(http only)*
116
-
117
- | Value | Meaning |
118
- |---|---|
119
- | `admin` *(default)* | Callable only from an authenticated admin surface. |
120
- | `public` | Publicly callable — no authenticated user required. |
121
-
122
- ### 2. `authority` — whose authority does it run as?
123
-
124
- This decides what `ctx.sl` can do.
125
-
126
- | Value | `ctx.sl` is scoped to | Use when |
127
- |---|---|---|
128
- | `caller` *(default)* | The **invoking user** (their session/JWT). Can only do what that user could. | Admin actions that should respect the user's own permissions and be attributed to them. |
129
- | `collection` | A **collection-admin principal for _this_ collection only** — never a global superuser. | A privileged server-side action a public/anonymous caller can't be trusted to do directly. |
130
-
131
- `authority` **defaults to `caller`** — secure by default. `event`- and `cron`-triggered
132
- functions have no external caller, so they always run as `collection`.
133
-
134
- ### The combinations
135
-
136
- - **`http` + `admin` + `caller`** — a delegated admin function; runs as the signed-in admin.
137
- - **`http` + `public` + `caller`** — runs as the anonymous/public user (limited). The safe public default.
138
- - **`http` + `public` + `collection`** — publicly callable, runs with collection authority.
139
- The powerful one (e.g. "submit competition entry" needs to validate then write a record no
140
- anonymous user may write directly). **Your responsibility:** validate the input and prevent
141
- abuse — see below.
142
- - **`event` / `cron`** — background work; runs as `collection`.
143
-
144
- > ### ⚠️ Public + collection authority is the sharp edge
145
- > A `public` + `collection` function is reachable by anyone and runs with elevated authority.
146
- > The platform shrinks the blast radius for you — the authority is capped to **this one
147
- > collection**, and further capped by your declared **capabilities** (a competition-entry
148
- > function that declares only `sl:records:write` cannot delete products or read other
149
- > secrets, even though it's "elevated"). But **validating the request is still your job**:
150
- > check the payload, rate-limit using `ctx.caller`, guard against replay. Treat the function
151
- > body as a trust boundary.
152
- >
153
- > Because it's the sharp edge, a `public` + `collection` function must **explicitly opt in**
154
- > with `elevated: true` in its declaration — a conscious acknowledgment that you're exposing
155
- > collection authority to public callers. Without it, install/validation fails.
156
-
157
- ---
158
-
159
- ## Capabilities — least privilege, declared and capped
160
-
161
- `capabilities` is the allow-list of what your function may reach. It is surfaced at install
162
- time for consent and **enforced at runtime** — including for `collection`-authority functions.
163
- Declare the minimum you need.
164
-
165
- | Capability | Grants |
166
- |---|---|
167
- | `sl:<resource>:read` / `sl:<resource>:write` | SDK access to that resource, e.g. `sl:products:read`, `sl:records:write`, `sl:attestations:write`, `sl:contacts:write`. |
168
- | `network` | `ctx.fetch` to any host. |
169
- | `network:<host>` | `ctx.fetch` to that host only (repeat for several). Prefer this over blanket `network`. |
170
- | `secrets:<ref>` | `ctx.secrets.get('<ref>')` for that one secret ref. |
171
-
172
- If you don't declare `network`, `ctx.fetch` is absent. If you don't declare a `secrets:<ref>`,
173
- `ctx.secrets.get('<ref>')` returns `null`.
174
-
175
- ---
176
-
177
- ## The `ctx` object
178
-
179
- ```ts
180
- interface ServerFunctionContext {
181
- collectionId: string
182
- appId: string
183
-
184
- /** SmartLinks SDK, pre-scoped to your declared `authority`. Capabilities cap what it may do.
185
- * Key resources: `sl.appRecords` (per-app records), `sl.appData` (general/app-wide config +
186
- * data — URLs, flags, counters, arrays), `sl.products`, `sl.attestations`. */
187
- sl: SmartLinks
188
-
189
- /** Capability-gated secrets (need `secrets:<ref>`). `get(ref)` resolves the collection's OWN
190
- * secret first, then the app-level one; `app(ref)` reads the app-level secret only. */
191
- secrets: { get(ref: string): Promise<string | null>; app(ref: string): Promise<string | null> }
192
-
193
- /** Who invoked this function. */
194
- caller: {
195
- userId: string | null // null for anonymous/public/system calls
196
- anonymous: boolean
197
- origin?: string | null // http
198
- ip?: string | null // http
199
- via: 'http' | 'event' | 'cron'
200
- }
201
-
202
- /** Outbound HTTP — present only if you declared `network` (host-scoped if `network:<host>`). */
203
- fetch: typeof fetch
204
-
205
- /** Structured logging — returned inline on the admin surface and recorded as an
206
- * execution activity event (owner Errors & Activity console). See "Seeing your
207
- * function's runs and logs" below. */
208
- log: (message: string, data?: Record<string, any>) => void
209
- }
210
- ```
211
-
212
- **Use `ctx.sl` for anything SmartLinks** — it is the same SDK surface you use client-side,
213
- already authenticated as your declared authority and scoped to the collection. Do **not** try
214
- to construct your own SDK client or carry your own key; that's what `ctx.sl` is for, and it's
215
- the only way authority stays correct.
216
-
217
- ### Calling a function from your app (client side)
218
-
219
- From a page/UI, invoke an `http`-trigger function with the SDK — no manual fetch, no URL building:
220
-
221
- ```ts
222
- // public function (runs on the caller's authority — signed-in owner, else public):
223
- const res = await SL.functions.call(collectionId, 'increment', { /* becomes event.body */ })
224
- // admin surface (needs an admin session):
225
- const res = await SL.functions.callAdmin(collectionId, 'recomputeTotals', { … })
226
- ```
227
-
228
- `res` is whatever your handler returns. See the `edge-function-test` example for a full page +
229
- function + manifest.
230
-
231
- #### Functions are ALWAYS app-scoped
232
-
233
- A function belongs to an app, so the canonical route carries the appId:
234
- `POST /collection/:collectionId/app/:appId/functions/:name`. Two different installed apps can each
235
- ship a function of the same name without clashing.
236
-
237
- The SDK fills the appId in for you. Initialize with your app's id once, then call by bare name —
238
- the SDK routes it app-scoped:
239
-
240
- ```ts
241
- SL.initializeApi({ baseURL, appId: 'my-counter-app' }) // usually done by the host/bootstrap
242
- await SL.functions.call(collectionId, 'pressCounter') // → /collection/:c/app/my-counter-app/functions/pressCounter
243
- ```
244
-
245
- To call a *different* app's function, pass the appId explicitly:
246
-
247
- ```ts
248
- await SL.functions.call(collectionId, 'pressCounter', {}, { appId: 'some-other-app' })
249
- ```
250
-
251
- **The app does NOT have to be enabled on the collection.** Because the appId is explicit, the
252
- function is resolved directly from the app's release — so you can test an app on any collection
253
- before installing it (and without it showing up in that collection's menus). Enabling an app is
254
- currently just a UX courtesy (dropdowns/menus), not a gate on running its functions. For a build
255
- that isn't the default `stable` channel — e.g. a **dev** app you haven't installed — pass the
256
- channel:
257
-
258
- ```ts
259
- await SL.functions.call(collectionId, 'pressCounter', {}, { appId: 'my-counter-app', channel: 'dev' })
260
- ```
261
-
262
- If no appId is available (not set on init, none passed), the call falls back to the **deprecated
263
- flat path** `/collection/:c/functions/:name`, which searches only the collection's **enabled** apps,
264
- resolves by bare name, and **rejects with `409 AMBIGUOUS_FUNCTION`** when more than one defines that
265
- name (a first-party builtin still wins). Always prefer an appId.
266
-
267
- > There is no such thing as an app-less function. First-party builtins (e.g. the `functions.ping`
268
- > diagnostic) belong to the reserved `smartlinks` app. A "global" function is just an app enabled on
269
- > the `global` collection and called at `/collection/global/app/:appId/functions/:name` — same two
270
- > facets (collection + app), with `global` as the sentinel collection.
271
-
272
- ---
273
-
274
- ## Exposing a function to the AI agent
275
-
276
- An `http` function can be offered to the AI agent as a **callable tool**, alongside the built-in
277
- tools. The model calls it, the server runs it, and the result is fed back into the loop. Opt in from
278
- the manifest with an `agent` block (full reference: [agent-tools.md](agent-tools.md)):
279
-
280
- ```jsonc
281
- {
282
- "name": "getLoyaltyBalance",
283
- "trigger": { "type": "http" },
284
- "visibility": "admin",
285
- "authority": "caller",
286
- "capabilities": ["sl:records:read"],
287
- "agent": {
288
- "tool": true,
289
- "title": "Loyalty balance",
290
- "description": "Look up a member's current loyalty points balance.",
291
- "input": {
292
- "type": "object",
293
- "properties": { "memberId": { "type": "string" } },
294
- "required": ["memberId"]
295
- },
296
- "approval": "auto" // 'require' = human confirms before each call
297
- }
298
- }
299
- ```
300
-
301
- The agent becomes **just another caller surface** — your function's `visibility`, `authority`, and
302
- `capabilities` are enforced exactly as on the http route. Nothing new is granted. The agent's tool
303
- arguments arrive as the function's request `body`, and whatever you return becomes the tool result the
304
- model sees. `approval: "require"` tools are held back from the autonomous server-side loop until the
305
- human-approval UX ships.
306
-
307
- Include your app's functions in an agent run:
308
-
309
- ```ts
310
- // Agentic Responses:
311
- await SL.ai.chat.responses.create(collectionId, {
312
- model: 'balanced', input: 'What is member 42's balance?',
313
- server_tools: true, // built-in tools
314
- app_functions: { appId: 'my-loyalty-app' }, // + this app's ai.tool functions
315
- })
316
-
317
- // Or the one-shot agent loop:
318
- await SL.ai.agent.run(collectionId, {
319
- input: '…', appFunctions: { appId: 'my-loyalty-app' },
320
- })
321
- ```
322
-
323
- On the **consumer surface**, a `visibility: "public"` function reaches a public assistant via the
324
- public agent loop — the caller runs as the signed-in consumer (`'owner'`, send the authKit bearer) or
325
- anonymous (`'public'`):
326
-
327
- ```ts
328
- await SL.ai.publicClient.agentRun(collectionId, {
329
- input: '…',
330
- appFunctions: { appId: 'my-app' }, // this app's public agent tools
331
- server_tools: ['web.search'], // built-ins are an explicit allowlist on the public surface
332
- })
333
- ```
334
-
335
- `channel` (default `'stable'`, pass `'dev'` to test a dev build) and `only: string[]` narrow which
336
- functions are exposed. Only `http` functions with `agent.tool: true` are eligible; `event`/`cron`
337
- functions never are. A built-in tool of the same name wins the clash.
338
-
339
- ### One unified toolbelt
340
-
341
- Rather than juggling `server_tools` + `app_functions`, declare everything in one `toolbelt` — built-in
342
- tools, one **or several** apps' functions, and (reserved, staged) front-end client tools:
343
-
344
- ```ts
345
- await SL.ai.chat.responses.create(collectionId, {
346
- input: '…',
347
- toolbelt: {
348
- builtins: ['web.search', 'document.read'], // true = all, [names] = subset, omit = none
349
- appFunctions: [{ appId: 'loyalty' }, { appId: 'catalog' }], // several apps at once
350
- // clientTools: [ … ] // reserved — the client-tool bridge is staged
351
- },
352
- })
353
- ```
354
-
355
- The same `toolbelt` works on `ai.agent.run` and `ai.publicClient.agentRun` (on the public surface
356
- `builtins` is an explicit allowlist — `true` is treated as none). Precedence on a name clash: a
357
- built-in wins, then earlier `appFunctions` sources win over later ones.
358
-
359
- > Directly (no model): every function is also callable deterministically — `SL.functions.call` /
360
- > `callAdmin` (above), the same way the built-in tools are callable via `SL.ai.tools.run`.
361
-
362
- ---
363
-
364
- ## Runtime — what your function can use
365
-
366
- Your function runs in a **web-standard sandbox** (think Cloudflare Workers / Deno), **not
367
- Node**. Concretely it targets the **WinterTC Minimum Common Web Platform API** (WinterTC is the
368
- Ecma International technical committee for this, formerly WinterCG) — the same surface those
369
- runtimes guarantee — so what you can rely on is portable, and the future isolated runner will
370
- host the same bundle unchanged.
371
-
372
- **Available globals** (no import needed):
373
- - **Data / encoding:** `JSON`, `URL`, `URLSearchParams`, `TextEncoder` / `TextDecoder`,
374
- `atob` / `btoa`, `Buffer`, `structuredClone`.
375
- - **Crypto:** `crypto` (Web Crypto) — `crypto.subtle` for hashing / HMAC / encrypt / sign /
376
- verify, `crypto.getRandomValues`, `crypto.randomUUID`.
377
- - **HTTP:** `fetch`, `Headers`, `Request`, `Response`, `FormData`, `Blob`, `File`,
378
- `AbortController` / `AbortSignal` (use one for **request timeouts**).
379
- - **Streams & timing:** `ReadableStream` / `WritableStream` / `TransformStream`,
380
- `CompressionStream` / `DecompressionStream` (gzip/deflate for third-party payloads), the timer
381
- functions, `queueMicrotask`, `performance`, `console`.
382
- - **Runtime identity:** `navigator.userAgent` reports the runtime key (currently
383
- `"SmartLinks-Functions"`) — use it if a portable dependency needs to feature-detect the host.
384
- It stays stable when functions move to the isolated runner.
385
-
386
- **Not available:** `require` / `import` of platform or Node modules, `process`, `fs`, and the
387
- Node built-ins (`node:crypto`, `node:http`, …). There is no ambient database, key, or network
388
- handle — everything the platform gives you comes through **`ctx`**.
389
-
390
- **Dependencies:** bundle them. Your build must produce a **self-contained** UMD (deps compiled
391
- in), and those deps must be **edge-compatible** — pure JS / Web APIs. A library that reaches for
392
- Node built-ins (e.g. `axios`'s Node adapter, anything using `node:crypto`) will fail to load.
393
- Prefer the platform primitives above over a dependency; when you do need one, pick edge-safe:
394
-
395
- | Need | Native? | Recommended (bundle, edge-safe) |
396
- |---|---|---|
397
- | JSON | **native** — `JSON.parse/stringify` | — |
398
- | XML parse / build | no | `fast-xml-parser` |
399
- | CSV | no | `papaparse` |
400
- | Schema validation of inputs | no | `zod` |
401
- | JWT (sign/verify for a third-party API) | Web Crypto can, verbosely | `jose` |
402
- | Hash / HMAC / encrypt | **native** — `crypto.subtle` | — |
403
- | PDF **text** extraction (cheap first-pass, no AI) | no | `unpdf` — a serverless/WASM pdf.js build with no Node deps; `import { extractText } from 'unpdf'`. Text only. |
404
-
405
- > **PDFs in a server function:** for a cheap text-layer check use `unpdf` (edge-safe, WASM). For
406
- > anything heavier — rendering pages, vision extraction, **barcode/QR decode**, or prepress/spot-colour
407
- > inspection — call the platform tools `pdf.render` / `pdf.extract` / `pdf.decodeBarcodes` /
408
- > `pdf.inspectGraphics` via `ai.tools.run`; those run in the full platform runtime, not the sandbox.
409
-
410
- **The common actions, and how to do each:**
411
-
412
- | You want to… | Use | Requires |
413
- |---|---|---|
414
- | Call a third-party API (GET/POST) | `ctx.fetch(url, init)` — the standard Fetch API | capability `network` or `network:<host>` |
415
- | Read a secret (API key, signing key) | `await ctx.secrets.get('<ref>')` | capability `secrets:<ref>` |
416
- | Hash / HMAC-sign / verify / encrypt | `crypto.subtle` (Web Crypto) | — |
417
- | Random id / bytes | `crypto.randomUUID()` / `crypto.getRandomValues()` | — |
418
- | Read or write SmartLinks data | `ctx.sl.*` (records, products, attestations, …) | the matching `sl:<res>:<read\|write>` |
419
- | Read/write your app's own data (config, URLs, counters, arrays) | `ctx.sl.appData.get()` / `ctx.sl.appData.set({…})` — collection-scoped by default; `ctx.sl.appData.global.*` (or `{ scope:'global' }`, or declare `dataScope:'global'`) for the app-wide bucket. It's your OWN namespace, so **any** authority may read/write it | `sl:data:read` / `sl:data:write` |
420
- | Read ANOTHER app's data (as the caller may see it) | `ctx.sl.app('other-app').data.get()` — caller-authority, this collection, public-filtered, read-only | `sl:data:read` |
421
- | Guarantee a UNIQUE claim (pool of numbers, one-per-user, idempotency key) | `ctx.sl.appRecords.create({ ref: 'ball:57' })` — the DB unique index rejects a duplicate `ref` (catch = "already taken") | `sl:records:write` |
422
-
423
- Notes:
424
- - **Talking to the SmartLinks core is `ctx.sl`, not HTTP.** The common pattern — *validate /
425
- process, then act on the core* — is: check the input, then call `ctx.sl.appRecords.create(…)`,
426
- `ctx.sl.products.update(…)`, etc. `ctx.sl` is already authenticated as your declared authority
427
- and capped by your capabilities, so you never construct a SmartLinks API URL or carry a key.
428
- Use `fetch`/`ctx.fetch` for *third-party* servers; use `ctx.sl` for SmartLinks itself.
429
- - **There is one `fetch`, and it is capability-gated.** Whether you call the global `fetch` or
430
- `ctx.fetch`, the behaviour is identical: the call **throws** unless your declared `network`
431
- (or `network:<host>`) capability covers the target host — the same way Deno's `fetch` throws
432
- without `--allow-net`. There is no ungated escape hatch. Declare the hosts you need.
433
- - **Secrets are read-only at runtime.** You fetch a secret you declared; you do **not** set or
434
- rotate secrets from a function — that's an admin/deploy-time operation on the platform.
435
- - **Signing a webhook / verifying a signature** is `crypto.subtle` with an HMAC key imported
436
- from a secret — no Node `crypto` needed.
437
-
438
- ---
439
-
440
- ## Worked example — a public competition entry
441
-
442
- ```ts
443
- // dist/functions — handler for the manifest definition above
444
- export async function submitCompetitionEntry(ctx, event) {
445
- const { name, email, answer, captchaToken } = event.body || {}
446
-
447
- // 1. Validate — this is YOUR job on a public function.
448
- if (!email || !answer) return { ok: false, error: 'missing_fields' }
449
-
450
- // 2. Use a declared secret + declared host to verify a captcha.
451
- const secret = await ctx.secrets.get('recaptcha-secret')
452
- const verify = await ctx.fetch('https://api.recaptcha.net/verify', {
453
- method: 'POST',
454
- body: new URLSearchParams({ secret, response: captchaToken }),
455
- }).then(r => r.json())
456
- if (!verify.success) return { ok: false, error: 'captcha_failed' }
457
-
458
- // 3. Write with collection authority — something an anonymous caller can't do directly.
459
- const entry = await ctx.sl.appRecords.create({
460
- recordType: 'competition-entry',
461
- data: { name, email, answer, ip: ctx.caller.ip, submittedAt: new Date().toISOString() },
462
- })
463
-
464
- ctx.log('entry recorded', { entryId: entry.id })
465
- return { ok: true, entryId: entry.id }
466
- }
467
- ```
468
-
469
- Declared as `public` + `collection` + `['sl:records:write', 'secrets:recaptcha-secret',
470
- 'network:api.recaptcha.net']`, this function is publicly callable, verifies the request
471
- itself, and writes a record no anonymous user could write — but it cannot touch products,
472
- other secrets, or any other collection.
473
-
474
- ---
475
-
476
- ## Invoking an http function
477
-
478
- An `http` function is called by POSTing to the app-scoped functions endpoint on the
479
- surface that matches its `visibility`:
480
-
481
- ```
482
- POST /admin/collection/:collectionId/app/:appId/functions/:name # visibility: admin (collection-admin auth)
483
- POST /public/collection/:collectionId/app/:appId/functions/:name # visibility: public (auth optional)
484
- GET /{admin|public}/collection/:collectionId/app/:appId/functions # list this app's functions on the surface
485
- ```
486
-
487
- The app-scoped route resolves the app **directly by id**, so the app need not be enabled on the
488
- collection — handy for testing an un-installed (dev) app. Add `?channel=dev` (default `stable`) to
489
- pick the release. Enablement (`appConfig.apps[]`) currently only controls menus/discovery, not
490
- whether a function can run.
491
-
492
- The bare-name form (`/collection/:c/functions/:name`, no `/app/:appId`) is a **deprecated alias**:
493
- it searches only the collection's **enabled** apps, resolves by name, lets a first-party builtin
494
- win, and returns `409 AMBIGUOUS_FUNCTION` when two enabled apps define the same name. Prefer the
495
- app-scoped route (the SDK emits it automatically once an appId is set — see "Calling a function
496
- from your app").
497
-
498
- > **Security note (first-party model, today):** because enablement is not an auth gate, any app's
499
- > function can be invoked on any collection by id. That's fine while all apps are first-party and
500
- > trusted. When untrusted third-party apps arrive, gate *elevated* (`public` + `collection`)
501
- > invocation of a **non-enabled** app behind install/consent — the app-scoped resolver is the seam.
502
-
503
- The handler receives the request as `event`: `event.body` (parsed JSON), `event.query`,
504
- `event.headers`, `event.rawBody` (raw bytes, for XML/form/other inputs), and `event.contentType`.
505
- A function only runs on its own surface — calling an `admin` function on the public endpoint is a
506
- `403`. `GET` on either endpoint lists the functions callable on that surface.
507
-
508
- **Response contract — your return IS the response (no envelope):**
509
- - Return a **plain value** → it becomes the JSON body, HTTP `200`. (`SL.functions.call()` gives you
510
- that value directly — `res.value`, not `res.result.value`.)
511
- - Return a web-standard **`Response`** → passed through verbatim: your status, headers, content-type
512
- and body (XML, CSV, text, binary, redirect, custom status). `Response` is a runtime global.
513
- ```js
514
- return new Response(toXml(data), { status: 200, headers: { "content-type": "application/xml" } })
515
- ```
516
- - **Throw** → HTTP `500` `{ error: "FUNCTION_ERROR", message, code }`. For *expected* errors (400/404/
517
- 409…), return a `Response` with your own status + body.
518
-
519
- One rule: **plain object ⇒ 200; want any other status/headers/content-type ⇒ return a `Response`.**
520
- Timing comes back in an `X-SL-Function-Duration-Ms` header (admin surface); your `ctx.log` lines land
521
- in the collection's Errors & Activity feed — the body stays purely your output.
522
-
523
- The admin surface is collection-admin gated, so an admin function's `caller` authority runs
524
- at admin level, attributed to the signed-in admin. The public surface resolves auth if a
525
- token is present (→ `owner`) and treats its absence as anonymous (→ `public`); a
526
- `collection`-authority function runs elevated regardless.
527
-
528
- ### Before it will resolve
529
-
530
- An http call returns `404 FUNCTION_NOT_FOUND` unless **both** of these are true (this is the
531
- most common first-run surprise):
532
-
533
- 1. **The app's release is registered on the channel** the collection follows (see
534
- [deploying-apps.md](deploying-apps.md)) — that's what publishes the function bundle into
535
- the registry the runtime loads from.
536
- 2. **The app is enabled on the collection** (`appConfig.apps[]`, on that same channel — see
537
- [appConfig.md](appConfig.md)).
538
-
539
- So the end-to-end path is: *write → register the release → enable on a collection → call.*
540
-
541
- ### Seeing your function's runs and logs
542
-
543
- Every invocation is recorded as an **execution** activity event, carrying your `ctx.log`
544
- lines. Where to look, easiest first:
545
-
546
- - **Admin-surface response** — timing comes back in the `X-SL-Function-Duration-Ms` header (logs are in Errors & Activity, not the body).
547
- - **Deployed test mode** — see below; real run, isolated logging.
548
- - **Owner console** — the collection's **Advanced → Errors & Activity → events** tab,
549
- filtered to **source = execution**: each run shows as `function <name> ok` (or an error),
550
- and the detail carries your `ctx.log` output. (Telemetry is streamed, so allow a few
551
- seconds.)
552
-
553
- ## Testing & preview
554
-
555
- You don't have to deploy to find out whether a function works. There are three levels of
556
- fidelity — use them in order.
557
-
558
- ### 1. Local harness (fast, offline)
559
-
560
- `@proveanything/smartlinks/testing` builds a `ctx` that **enforces the declared capability
561
- envelope**, so a function fails locally the same way it would in production — the common
562
- "I forgot to declare `sl:records:write`" bug is caught before you deploy, not after.
563
-
564
- ```ts
565
- import { createFunctionTestContext } from '@proveanything/smartlinks/testing'
566
- import manifest from '../public/app.manifest.json'
567
- import { submitCompetitionEntry } from '../src/functions'
568
-
569
- const def = manifest.functions.definitions.find(d => d.name === 'submitCompetitionEntry')
570
-
571
- const ctx = createFunctionTestContext({
572
- def, // capabilities enforced come from the manifest itself
573
- caller: { userId: 'tester' },
574
- secrets: { 'recaptcha-secret': 'test-value' }, // fixtures — real secrets are server-only
575
- })
576
-
577
- const res = await submitCompetitionEntry(ctx, { method: 'POST', body: { email: 'a@b.com', answer: '42' } })
578
- // ctx.sl.appRecords.create(...) throws CapabilityError unless `def` declares sl:records:write
579
- ```
580
-
581
- Pass the **`def`** (not a hand-typed capability list) so "tested" can't drift from
582
- "declared". By default `ctx.sl` methods return a stub result (pure unit test — no network);
583
- inject `sl` to delegate to your live SDK for real reads/writes:
584
-
585
- ```ts
586
- const ctx = createFunctionTestContext({
587
- def,
588
- sl: { appRecords: { create: (fields) => mySdk.app.records.create(fields) } },
589
- })
590
- ```
591
-
592
- ### 2. Deployed test mode (high fidelity, safe)
593
-
594
- Register to the `dev` channel and invoke on the real server — real secrets, real data —
595
- without a live run *(coming next)*: a test invocation is forced to `caller` authority,
596
- side-effecting writes are dry-run, and the traffic is logged separately from live metrics.
597
-
598
- ### 3. Live
599
-
600
- Point a real collection at the channel and invoke for real.
601
-
602
- ### What differs across the three
603
-
604
- | | Capabilities | `ctx.sl` | Secrets | Authority | Writes |
605
- |---|---|---|---|---|---|
606
- | **Local harness** | Enforced (from `def`) | Stub, or your injected SDK | Fixtures you pass | Informational | Whatever your impl does |
607
- | **Deployed test** | Enforced | Real (test-scoped) | Real | Forced to `caller` | Dry-run |
608
- | **Live** | Enforced | Real | Real | As declared | Real |
609
-
610
- ### Recommended CI pattern
611
-
612
- 1. **Unit** — run each handler through `createFunctionTestContext` (no network); assert
613
- behaviour *and* that capabilities are sufficient (an under-declared capability throws).
614
- 2. **Post-deploy smoke** — after registering to `dev`, hit each function once in test mode.
615
-
616
- ## Where functions run (and why it doesn't change how you write them)
617
-
618
- SmartLinks runs first-party (trusted) functions **in-process** and untrusted third-party
619
- functions in an **isolated runner**. The difference is enforcement, not authoring:
620
-
621
- - **In-process** trusts the author; `ctx` is built directly.
622
- - **Isolated runner** enforces the `authority` boundary and `capabilities` at the container
623
- edge — `ctx.sl` is a proxy over the declared authority, `ctx.fetch` is filtered to the
624
- declared hosts, and there is no ambient filesystem, network, or environment.
625
-
626
- Because the **contract is identical**, a function you write today runs unchanged if it later
627
- moves lanes. Write to the `ctx` contract and declare your capabilities honestly, and the
628
- platform takes care of the rest.
1
+ # Server functions ("edge functions")
2
+
3
+ > **SmartLinks SDK 2.x** (current `latest`). Part of the installable-app platform
4
+ > (author → register → install → run → test). Install `@proveanything/smartlinks@^2`.
5
+
6
+ A **server function** is arbitrary server-side JavaScript your app deploys directly into
7
+ SmartLinks. It runs on the SmartLinks servers — with access to the full SDK, to your app's
8
+ secrets, and to outbound network — so you can do things a browser app can't: validate and
9
+ write on the server, call third-party systems with credentials the client never sees, react
10
+ to events, and run scheduled work.
11
+
12
+ Every server function has the **same shape**, no matter how it's triggered or where it runs:
13
+
14
+ ```ts
15
+ export async function myFunction(ctx, event) {
16
+ // ctx — a SmartLinks SDK pre-scoped to your declared authority, plus secrets, caller, fetch, log
17
+ // event — the trigger payload (the HTTP body, the event, or the cron tick)
18
+ return { ok: true } // returned to the caller (http) or recorded as the run result (event/cron)
19
+ }
20
+ ```
21
+
22
+ You never receive a raw API key or a superuser client. The platform builds `ctx` fresh for
23
+ each invocation and **pre-scopes every handle to exactly what your function declared** — this
24
+ is how a function stays safe even when it runs with elevated authority.
25
+
26
+ ---
27
+
28
+ ## Declaring a function
29
+
30
+ Functions are declared in your `app.manifest.json` under `functions`, and the handlers ship
31
+ in a bundle alongside your widgets/containers:
32
+
33
+ ```jsonc
34
+ {
35
+ "functions": {
36
+ "files": { "js": { "umd": "dist/functions.umd.js" } },
37
+ "definitions": [
38
+ {
39
+ "name": "submitCompetitionEntry",
40
+ "description": "Validate a competition entry and record it server-side.",
41
+ "trigger": { "type": "http", "methods": ["POST"] },
42
+ "visibility": "public", // WHO may call it
43
+ "authority": "collection", // WHOSE authority it runs as
44
+ "elevated": true, // required ack for public + collection
45
+ "capabilities": ["sl:records:write", "network:api.recaptcha.net"],
46
+ "apiVersion": "2026-09"
47
+ },
48
+ {
49
+ "name": "onProofCreated",
50
+ "trigger": { "type": "event", "eventTypes": ["proof.created"] },
51
+ "capabilities": ["sl:records:write", "secrets:crm-key", "network"]
52
+ },
53
+ {
54
+ "name": "nightlyReconcile",
55
+ "trigger": { "type": "cron", "schedule": "0 2 * * *" },
56
+ "capabilities": ["sl:products:read", "sl:records:write"]
57
+ }
58
+ ]
59
+ }
60
+ }
61
+ ```
62
+
63
+ Each definition maps to an exported handler of the same `name` (override with `handler`).
64
+
65
+ ## Building the functions bundle
66
+
67
+ The handlers ship as a **self-contained UMD** — one file, all dependencies compiled in, no
68
+ `require`/`import` of platform or Node modules (see [Runtime](#runtime--what-your-function-can-use)).
69
+ Your functions entry just **named-exports** each handler:
70
+
71
+ ```js
72
+ // src/functions/index.js — the functions entry
73
+ export async function submitCompetitionEntry(ctx, event) { /* … */ }
74
+ export async function onProofCreated(ctx, event) { /* … */ }
75
+ ```
76
+
77
+ Build it to `dist/functions.umd.js` with a Vite lib build — **UMD format, nothing externalised**
78
+ (so it's self-contained), and don't wipe the widgets you built into the same `dist/`:
79
+
80
+ ```ts
81
+ // vite.functions.config.ts
82
+ import { defineConfig } from 'vite'
83
+ export default defineConfig({
84
+ build: {
85
+ lib: { entry: 'src/functions/index.js', formats: ['umd'], name: 'functions',
86
+ fileName: () => 'functions.umd.js' },
87
+ outDir: 'dist',
88
+ emptyOutDir: false, // co-exist with the widgets/containers build
89
+ rollupOptions: { external: [] } // bundle everything — no Node/platform externals
90
+ },
91
+ })
92
+ ```
93
+
94
+ ```jsonc
95
+ // package.json — build widgets/containers as usual, then the functions bundle
96
+ "scripts": {
97
+ "build": "vite build && vite build --config vite.functions.config.ts"
98
+ }
99
+ ```
100
+
101
+ That emits `dist/functions.umd.js` (matching `functions.files.js.umd`), whose named exports the
102
+ platform pairs with your manifest `definitions`. Then **deploy** it — for dev,
103
+ `smartlinks-publish` uploads `dist/` and registers in one step (see
104
+ [Deploying & registering](deploying-apps.md)).
105
+
106
+ ---
107
+
108
+ ## The two security questions every function answers
109
+
110
+ Server-side code needs two questions answered up front. SmartLinks makes both **explicit and
111
+ declarative** — you state them in the manifest, and the platform enforces them. This is the
112
+ same split every extensible platform lands on (Salesforce `with/without sharing`, Shopify
113
+ online/offline tokens, Lambda's invoke-policy vs execution-role).
114
+
115
+ ### 1. `visibility` — who is allowed to call it? *(http only)*
116
+
117
+ | Value | Meaning |
118
+ |---|---|
119
+ | `admin` *(default)* | Callable only from an authenticated admin surface. |
120
+ | `public` | Publicly callable — no authenticated user required. |
121
+
122
+ ### 2. `authority` — whose authority does it run as?
123
+
124
+ This decides what `ctx.sl` can do.
125
+
126
+ | Value | `ctx.sl` is scoped to | Use when |
127
+ |---|---|---|
128
+ | `caller` *(default)* | The **invoking user** (their session/JWT). Can only do what that user could. | Admin actions that should respect the user's own permissions and be attributed to them. |
129
+ | `collection` | A **collection-admin principal for _this_ collection only** — never a global superuser. | A privileged server-side action a public/anonymous caller can't be trusted to do directly. |
130
+
131
+ `authority` **defaults to `caller`** — secure by default. `event`- and `cron`-triggered
132
+ functions have no external caller, so they always run as `collection`.
133
+
134
+ ### The combinations
135
+
136
+ - **`http` + `admin` + `caller`** — a delegated admin function; runs as the signed-in admin.
137
+ - **`http` + `public` + `caller`** — runs as the anonymous/public user (limited). The safe public default.
138
+ - **`http` + `public` + `collection`** — publicly callable, runs with collection authority.
139
+ The powerful one (e.g. "submit competition entry" needs to validate then write a record no
140
+ anonymous user may write directly). **Your responsibility:** validate the input and prevent
141
+ abuse — see below.
142
+ - **`event` / `cron`** — background work; runs as `collection`.
143
+
144
+ > ### ⚠️ Public + collection authority is the sharp edge
145
+ > A `public` + `collection` function is reachable by anyone and runs with elevated authority.
146
+ > The platform shrinks the blast radius for you — the authority is capped to **this one
147
+ > collection**, and further capped by your declared **capabilities** (a competition-entry
148
+ > function that declares only `sl:records:write` cannot delete products or read other
149
+ > secrets, even though it's "elevated"). But **validating the request is still your job**:
150
+ > check the payload, rate-limit using `ctx.caller`, guard against replay. Treat the function
151
+ > body as a trust boundary.
152
+ >
153
+ > Because it's the sharp edge, a `public` + `collection` function must **explicitly opt in**
154
+ > with `elevated: true` in its declaration — a conscious acknowledgment that you're exposing
155
+ > collection authority to public callers. Without it, install/validation fails.
156
+
157
+ ---
158
+
159
+ ## Capabilities — least privilege, declared and capped
160
+
161
+ `capabilities` is the allow-list of what your function may reach. It is surfaced at install
162
+ time for consent and **enforced at runtime** — including for `collection`-authority functions.
163
+ Declare the minimum you need.
164
+
165
+ | Capability | Grants |
166
+ |---|---|
167
+ | `sl:<resource>:read` / `sl:<resource>:write` | SDK access to that resource, e.g. `sl:products:read`, `sl:records:write`, `sl:attestations:write`, `sl:contacts:write`. |
168
+ | `network` | `ctx.fetch` to any host. |
169
+ | `network:<host>` | `ctx.fetch` to that host only (repeat for several). Prefer this over blanket `network`. |
170
+ | `secrets:<ref>` | `ctx.secrets.get('<ref>')` for that one secret ref. |
171
+
172
+ If you don't declare `network`, `ctx.fetch` is absent. If you don't declare a `secrets:<ref>`,
173
+ `ctx.secrets.get('<ref>')` returns `null`.
174
+
175
+ ---
176
+
177
+ ## The `ctx` object
178
+
179
+ ```ts
180
+ interface ServerFunctionContext {
181
+ collectionId: string
182
+ appId: string
183
+
184
+ /** SmartLinks SDK, pre-scoped to your declared `authority`. Capabilities cap what it may do.
185
+ * Key resources: `sl.appRecords` (per-app records), `sl.appData` (general/app-wide config +
186
+ * data — URLs, flags, counters, arrays), `sl.products`, `sl.attestations`. */
187
+ sl: SmartLinks
188
+
189
+ /** Capability-gated secrets (need `secrets:<ref>`). `get(ref)` resolves the collection's OWN
190
+ * secret first, then the app-level one; `app(ref)` reads the app-level secret only. */
191
+ secrets: { get(ref: string): Promise<string | null>; app(ref: string): Promise<string | null> }
192
+
193
+ /** Who invoked this function. */
194
+ caller: {
195
+ userId: string | null // null for anonymous/public/system calls
196
+ anonymous: boolean
197
+ origin?: string | null // http
198
+ ip?: string | null // http
199
+ via: 'http' | 'event' | 'cron'
200
+ }
201
+
202
+ /** Outbound HTTP — present only if you declared `network` (host-scoped if `network:<host>`). */
203
+ fetch: typeof fetch
204
+
205
+ /** Structured logging — returned inline on the admin surface and recorded as an
206
+ * execution activity event (owner Errors & Activity console). See "Seeing your
207
+ * function's runs and logs" below. */
208
+ log: (message: string, data?: Record<string, any>) => void
209
+ }
210
+ ```
211
+
212
+ **Use `ctx.sl` for anything SmartLinks** — it is the same SDK surface you use client-side,
213
+ already authenticated as your declared authority and scoped to the collection. Do **not** try
214
+ to construct your own SDK client or carry your own key; that's what `ctx.sl` is for, and it's
215
+ the only way authority stays correct.
216
+
217
+ ### Calling a function from your app (client side)
218
+
219
+ From a page/UI, invoke an `http`-trigger function with the SDK — no manual fetch, no URL building:
220
+
221
+ ```ts
222
+ // public function (runs on the caller's authority — signed-in owner, else public):
223
+ const res = await SL.functions.call(collectionId, 'increment', { /* becomes event.body */ })
224
+ // admin surface (needs an admin session):
225
+ const res = await SL.functions.callAdmin(collectionId, 'recomputeTotals', { … })
226
+ ```
227
+
228
+ `res` is whatever your handler returns. See the `edge-function-test` example for a full page +
229
+ function + manifest.
230
+
231
+ #### Functions are ALWAYS app-scoped
232
+
233
+ A function belongs to an app, so the canonical route carries the appId:
234
+ `POST /collection/:collectionId/app/:appId/functions/:name`. Two different installed apps can each
235
+ ship a function of the same name without clashing.
236
+
237
+ The SDK fills the appId in for you. Initialize with your app's id once, then call by bare name —
238
+ the SDK routes it app-scoped:
239
+
240
+ ```ts
241
+ SL.initializeApi({ baseURL, appId: 'my-counter-app' }) // usually done by the host/bootstrap
242
+ await SL.functions.call(collectionId, 'pressCounter') // → /collection/:c/app/my-counter-app/functions/pressCounter
243
+ ```
244
+
245
+ To call a *different* app's function, pass the appId explicitly:
246
+
247
+ ```ts
248
+ await SL.functions.call(collectionId, 'pressCounter', {}, { appId: 'some-other-app' })
249
+ ```
250
+
251
+ **The app does NOT have to be enabled on the collection.** Because the appId is explicit, the
252
+ function is resolved directly from the app's release — so you can test an app on any collection
253
+ before installing it (and without it showing up in that collection's menus). Enabling an app is
254
+ currently just a UX courtesy (dropdowns/menus), not a gate on running its functions. For a build
255
+ that isn't the default `stable` channel — e.g. a **dev** app you haven't installed — pass the
256
+ channel:
257
+
258
+ ```ts
259
+ await SL.functions.call(collectionId, 'pressCounter', {}, { appId: 'my-counter-app', channel: 'dev' })
260
+ ```
261
+
262
+ If no appId is available (not set on init, none passed), the call falls back to the **deprecated
263
+ flat path** `/collection/:c/functions/:name`, which searches only the collection's **enabled** apps,
264
+ resolves by bare name, and **rejects with `409 AMBIGUOUS_FUNCTION`** when more than one defines that
265
+ name (a first-party builtin still wins). Always prefer an appId.
266
+
267
+ > There is no such thing as an app-less function. First-party builtins (e.g. the `functions.ping`
268
+ > diagnostic) belong to the reserved `smartlinks` app. A "global" function is just an app enabled on
269
+ > the `global` collection and called at `/collection/global/app/:appId/functions/:name` — same two
270
+ > facets (collection + app), with `global` as the sentinel collection.
271
+
272
+ ---
273
+
274
+ ## Exposing a function to the AI agent
275
+
276
+ An `http` function can be offered to the AI agent as a **callable tool**, alongside the built-in
277
+ tools. The model calls it, the server runs it, and the result is fed back into the loop. Opt in from
278
+ the manifest with an `agent` block (full reference: [agent-tools.md](agent-tools.md)):
279
+
280
+ ```jsonc
281
+ {
282
+ "name": "getLoyaltyBalance",
283
+ "trigger": { "type": "http" },
284
+ "visibility": "admin",
285
+ "authority": "caller",
286
+ "capabilities": ["sl:records:read"],
287
+ "agent": {
288
+ "tool": true,
289
+ "title": "Loyalty balance",
290
+ "description": "Look up a member's current loyalty points balance.",
291
+ "input": {
292
+ "type": "object",
293
+ "properties": { "memberId": { "type": "string" } },
294
+ "required": ["memberId"]
295
+ },
296
+ "approval": "auto" // 'require' = human confirms before each call
297
+ }
298
+ }
299
+ ```
300
+
301
+ The agent becomes **just another caller surface** — your function's `visibility`, `authority`, and
302
+ `capabilities` are enforced exactly as on the http route. Nothing new is granted. The agent's tool
303
+ arguments arrive as the function's request `body`, and whatever you return becomes the tool result the
304
+ model sees. `approval: "require"` tools are held back from the autonomous server-side loop until the
305
+ human-approval UX ships.
306
+
307
+ Include your app's functions in an agent run:
308
+
309
+ ```ts
310
+ // Agentic Responses:
311
+ await SL.ai.chat.responses.create(collectionId, {
312
+ model: 'balanced', input: 'What is member 42's balance?',
313
+ server_tools: true, // built-in tools
314
+ app_functions: { appId: 'my-loyalty-app' }, // + this app's ai.tool functions
315
+ })
316
+
317
+ // Or the one-shot agent loop:
318
+ await SL.ai.agent.run(collectionId, {
319
+ input: '…', appFunctions: { appId: 'my-loyalty-app' },
320
+ })
321
+ ```
322
+
323
+ On the **consumer surface**, a `visibility: "public"` function reaches a public assistant via the
324
+ public agent loop — the caller runs as the signed-in consumer (`'owner'`, send the authKit bearer) or
325
+ anonymous (`'public'`):
326
+
327
+ ```ts
328
+ await SL.ai.publicClient.agentRun(collectionId, {
329
+ input: '…',
330
+ appFunctions: { appId: 'my-app' }, // this app's public agent tools
331
+ server_tools: ['web.search'], // built-ins are an explicit allowlist on the public surface
332
+ })
333
+ ```
334
+
335
+ `channel` (default `'stable'`, pass `'dev'` to test a dev build) and `only: string[]` narrow which
336
+ functions are exposed. Only `http` functions with `agent.tool: true` are eligible; `event`/`cron`
337
+ functions never are. A built-in tool of the same name wins the clash.
338
+
339
+ ### One unified toolbelt
340
+
341
+ Rather than juggling `server_tools` + `app_functions`, declare everything in one `toolbelt` — built-in
342
+ tools, one **or several** apps' functions, and (reserved, staged) front-end client tools:
343
+
344
+ ```ts
345
+ await SL.ai.chat.responses.create(collectionId, {
346
+ input: '…',
347
+ toolbelt: {
348
+ builtins: ['web.search', 'document.read'], // true = all, [names] = subset, omit = none
349
+ appFunctions: [{ appId: 'loyalty' }, { appId: 'catalog' }], // several apps at once
350
+ // clientTools: [ … ] // reserved — the client-tool bridge is staged
351
+ },
352
+ })
353
+ ```
354
+
355
+ The same `toolbelt` works on `ai.agent.run` and `ai.publicClient.agentRun` (on the public surface
356
+ `builtins` is an explicit allowlist — `true` is treated as none). Precedence on a name clash: a
357
+ built-in wins, then earlier `appFunctions` sources win over later ones.
358
+
359
+ > Directly (no model): every function is also callable deterministically — `SL.functions.call` /
360
+ > `callAdmin` (above), the same way the built-in tools are callable via `SL.ai.tools.run`.
361
+
362
+ ---
363
+
364
+ ## Runtime — what your function can use
365
+
366
+ Your function runs in a **web-standard sandbox** (think Cloudflare Workers / Deno), **not
367
+ Node**. Concretely it targets the **WinterTC Minimum Common Web Platform API** (WinterTC is the
368
+ Ecma International technical committee for this, formerly WinterCG) — the same surface those
369
+ runtimes guarantee — so what you can rely on is portable, and the future isolated runner will
370
+ host the same bundle unchanged.
371
+
372
+ **Available globals** (no import needed):
373
+ - **Data / encoding:** `JSON`, `URL`, `URLSearchParams`, `TextEncoder` / `TextDecoder`,
374
+ `atob` / `btoa`, `Buffer`, `structuredClone`.
375
+ - **Crypto:** `crypto` (Web Crypto) — `crypto.subtle` for hashing / HMAC / encrypt / sign /
376
+ verify, `crypto.getRandomValues`, `crypto.randomUUID`.
377
+ - **HTTP:** `fetch`, `Headers`, `Request`, `Response`, `FormData`, `Blob`, `File`,
378
+ `AbortController` / `AbortSignal` (use one for **request timeouts**).
379
+ - **Streams & timing:** `ReadableStream` / `WritableStream` / `TransformStream`,
380
+ `CompressionStream` / `DecompressionStream` (gzip/deflate for third-party payloads), the timer
381
+ functions, `queueMicrotask`, `performance`, `console`.
382
+ - **Runtime identity:** `navigator.userAgent` reports the runtime key (currently
383
+ `"SmartLinks-Functions"`) — use it if a portable dependency needs to feature-detect the host.
384
+ It stays stable when functions move to the isolated runner.
385
+
386
+ **Not available:** `require` / `import` of platform or Node modules, `process`, `fs`, and the
387
+ Node built-ins (`node:crypto`, `node:http`, …). There is no ambient database, key, or network
388
+ handle — everything the platform gives you comes through **`ctx`**.
389
+
390
+ **Dependencies:** bundle them. Your build must produce a **self-contained** UMD (deps compiled
391
+ in), and those deps must be **edge-compatible** — pure JS / Web APIs. A library that reaches for
392
+ Node built-ins (e.g. `axios`'s Node adapter, anything using `node:crypto`) will fail to load.
393
+ Prefer the platform primitives above over a dependency; when you do need one, pick edge-safe:
394
+
395
+ | Need | Native? | Recommended (bundle, edge-safe) |
396
+ |---|---|---|
397
+ | JSON | **native** — `JSON.parse/stringify` | — |
398
+ | XML parse / build | no | `fast-xml-parser` |
399
+ | CSV | no | `papaparse` |
400
+ | Schema validation of inputs | no | `zod` |
401
+ | JWT (sign/verify for a third-party API) | Web Crypto can, verbosely | `jose` |
402
+ | Hash / HMAC / encrypt | **native** — `crypto.subtle` | — |
403
+ | PDF **text** extraction (cheap first-pass, no AI) | no | `unpdf` — a serverless/WASM pdf.js build with no Node deps; `import { extractText } from 'unpdf'`. Text only. |
404
+
405
+ > **PDFs in a server function:** for a cheap text-layer check use `unpdf` (edge-safe, WASM). For
406
+ > anything heavier — rendering pages, vision extraction, **barcode/QR decode**, or prepress/spot-colour
407
+ > inspection, **OCR of small print** — call the platform tools `pdf.render` / `pdf.extract` /
408
+ > `pdf.decodeBarcodes` / `pdf.inspectGraphics` / `image.ocr` via `ai.tools.run`; those run in the full
409
+ > platform runtime, not the sandbox.
410
+
411
+ **The common actions, and how to do each:**
412
+
413
+ | You want to… | Use | Requires |
414
+ |---|---|---|
415
+ | Call a third-party API (GET/POST) | `ctx.fetch(url, init)` — the standard Fetch API | capability `network` or `network:<host>` |
416
+ | Read a secret (API key, signing key) | `await ctx.secrets.get('<ref>')` | capability `secrets:<ref>` |
417
+ | Hash / HMAC-sign / verify / encrypt | `crypto.subtle` (Web Crypto) | — |
418
+ | Random id / bytes | `crypto.randomUUID()` / `crypto.getRandomValues()` | — |
419
+ | Read or write SmartLinks data | `ctx.sl.*` (records, products, attestations, …) | the matching `sl:<res>:<read\|write>` |
420
+ | Read/write your app's own data (config, URLs, counters, arrays) | `ctx.sl.appData.get()` / `ctx.sl.appData.set({…})` — collection-scoped by default; `ctx.sl.appData.global.*` (or `{ scope:'global' }`, or declare `dataScope:'global'`) for the app-wide bucket. It's your OWN namespace, so **any** authority may read/write it | `sl:data:read` / `sl:data:write` |
421
+ | Read ANOTHER app's data (as the caller may see it) | `ctx.sl.app('other-app').data.get()` — caller-authority, this collection, public-filtered, read-only | `sl:data:read` |
422
+ | Guarantee a UNIQUE claim (pool of numbers, one-per-user, idempotency key) | `ctx.sl.appRecords.create({ ref: 'ball:57' })` — the DB unique index rejects a duplicate `ref` (catch = "already taken") | `sl:records:write` |
423
+
424
+ Notes:
425
+ - **Talking to the SmartLinks core is `ctx.sl`, not HTTP.** The common pattern — *validate /
426
+ process, then act on the core* — is: check the input, then call `ctx.sl.appRecords.create(…)`,
427
+ `ctx.sl.products.update(…)`, etc. `ctx.sl` is already authenticated as your declared authority
428
+ and capped by your capabilities, so you never construct a SmartLinks API URL or carry a key.
429
+ Use `fetch`/`ctx.fetch` for *third-party* servers; use `ctx.sl` for SmartLinks itself.
430
+ - **There is one `fetch`, and it is capability-gated.** Whether you call the global `fetch` or
431
+ `ctx.fetch`, the behaviour is identical: the call **throws** unless your declared `network`
432
+ (or `network:<host>`) capability covers the target host — the same way Deno's `fetch` throws
433
+ without `--allow-net`. There is no ungated escape hatch. Declare the hosts you need.
434
+ - **Secrets are read-only at runtime.** You fetch a secret you declared; you do **not** set or
435
+ rotate secrets from a function — that's an admin/deploy-time operation on the platform.
436
+ - **Signing a webhook / verifying a signature** is `crypto.subtle` with an HMAC key imported
437
+ from a secret — no Node `crypto` needed.
438
+
439
+ ---
440
+
441
+ ## Worked example — a public competition entry
442
+
443
+ ```ts
444
+ // dist/functions — handler for the manifest definition above
445
+ export async function submitCompetitionEntry(ctx, event) {
446
+ const { name, email, answer, captchaToken } = event.body || {}
447
+
448
+ // 1. Validate — this is YOUR job on a public function.
449
+ if (!email || !answer) return { ok: false, error: 'missing_fields' }
450
+
451
+ // 2. Use a declared secret + declared host to verify a captcha.
452
+ const secret = await ctx.secrets.get('recaptcha-secret')
453
+ const verify = await ctx.fetch('https://api.recaptcha.net/verify', {
454
+ method: 'POST',
455
+ body: new URLSearchParams({ secret, response: captchaToken }),
456
+ }).then(r => r.json())
457
+ if (!verify.success) return { ok: false, error: 'captcha_failed' }
458
+
459
+ // 3. Write with collection authority — something an anonymous caller can't do directly.
460
+ const entry = await ctx.sl.appRecords.create({
461
+ recordType: 'competition-entry',
462
+ data: { name, email, answer, ip: ctx.caller.ip, submittedAt: new Date().toISOString() },
463
+ })
464
+
465
+ ctx.log('entry recorded', { entryId: entry.id })
466
+ return { ok: true, entryId: entry.id }
467
+ }
468
+ ```
469
+
470
+ Declared as `public` + `collection` + `['sl:records:write', 'secrets:recaptcha-secret',
471
+ 'network:api.recaptcha.net']`, this function is publicly callable, verifies the request
472
+ itself, and writes a record no anonymous user could write — but it cannot touch products,
473
+ other secrets, or any other collection.
474
+
475
+ ---
476
+
477
+ ## Invoking an http function
478
+
479
+ An `http` function is called by POSTing to the app-scoped functions endpoint on the
480
+ surface that matches its `visibility`:
481
+
482
+ ```
483
+ POST /admin/collection/:collectionId/app/:appId/functions/:name # visibility: admin (collection-admin auth)
484
+ POST /public/collection/:collectionId/app/:appId/functions/:name # visibility: public (auth optional)
485
+ GET /{admin|public}/collection/:collectionId/app/:appId/functions # list this app's functions on the surface
486
+ ```
487
+
488
+ The app-scoped route resolves the app **directly by id**, so the app need not be enabled on the
489
+ collection — handy for testing an un-installed (dev) app. Add `?channel=dev` (default `stable`) to
490
+ pick the release. Enablement (`appConfig.apps[]`) currently only controls menus/discovery, not
491
+ whether a function can run.
492
+
493
+ The bare-name form (`/collection/:c/functions/:name`, no `/app/:appId`) is a **deprecated alias**:
494
+ it searches only the collection's **enabled** apps, resolves by name, lets a first-party builtin
495
+ win, and returns `409 AMBIGUOUS_FUNCTION` when two enabled apps define the same name. Prefer the
496
+ app-scoped route (the SDK emits it automatically once an appId is set — see "Calling a function
497
+ from your app").
498
+
499
+ > **Security note (first-party model, today):** because enablement is not an auth gate, any app's
500
+ > function can be invoked on any collection by id. That's fine while all apps are first-party and
501
+ > trusted. When untrusted third-party apps arrive, gate *elevated* (`public` + `collection`)
502
+ > invocation of a **non-enabled** app behind install/consent — the app-scoped resolver is the seam.
503
+
504
+ The handler receives the request as `event`: `event.body` (parsed JSON), `event.query`,
505
+ `event.headers`, `event.rawBody` (raw bytes, for XML/form/other inputs), and `event.contentType`.
506
+ A function only runs on its own surface — calling an `admin` function on the public endpoint is a
507
+ `403`. `GET` on either endpoint lists the functions callable on that surface.
508
+
509
+ **Response contract — your return IS the response (no envelope):**
510
+ - Return a **plain value** → it becomes the JSON body, HTTP `200`. (`SL.functions.call()` gives you
511
+ that value directly — `res.value`, not `res.result.value`.)
512
+ - Return a web-standard **`Response`** → passed through verbatim: your status, headers, content-type
513
+ and body (XML, CSV, text, binary, redirect, custom status). `Response` is a runtime global.
514
+ ```js
515
+ return new Response(toXml(data), { status: 200, headers: { "content-type": "application/xml" } })
516
+ ```
517
+ - **Throw** → HTTP `500` `{ error: "FUNCTION_ERROR", message, code }`. For *expected* errors (400/404/
518
+ 409…), return a `Response` with your own status + body.
519
+
520
+ One rule: **plain object ⇒ 200; want any other status/headers/content-type ⇒ return a `Response`.**
521
+ Timing comes back in an `X-SL-Function-Duration-Ms` header (admin surface); your `ctx.log` lines land
522
+ in the collection's Errors & Activity feed — the body stays purely your output.
523
+
524
+ The admin surface is collection-admin gated, so an admin function's `caller` authority runs
525
+ at admin level, attributed to the signed-in admin. The public surface resolves auth if a
526
+ token is present (→ `owner`) and treats its absence as anonymous (→ `public`); a
527
+ `collection`-authority function runs elevated regardless.
528
+
529
+ ### Before it will resolve
530
+
531
+ An http call returns `404 FUNCTION_NOT_FOUND` unless **both** of these are true (this is the
532
+ most common first-run surprise):
533
+
534
+ 1. **The app's release is registered on the channel** the collection follows (see
535
+ [deploying-apps.md](deploying-apps.md)) — that's what publishes the function bundle into
536
+ the registry the runtime loads from.
537
+ 2. **The app is enabled on the collection** (`appConfig.apps[]`, on that same channel — see
538
+ [appConfig.md](appConfig.md)).
539
+
540
+ So the end-to-end path is: *write → register the release → enable on a collection → call.*
541
+
542
+ ### Seeing your function's runs and logs
543
+
544
+ Every invocation is recorded as an **execution** activity event, carrying your `ctx.log`
545
+ lines. Where to look, easiest first:
546
+
547
+ - **Admin-surface response** — timing comes back in the `X-SL-Function-Duration-Ms` header (logs are in Errors & Activity, not the body).
548
+ - **Deployed test mode** — see below; real run, isolated logging.
549
+ - **Owner console** — the collection's **Advanced → Errors & Activity → events** tab,
550
+ filtered to **source = execution**: each run shows as `function <name> ok` (or an error),
551
+ and the detail carries your `ctx.log` output. (Telemetry is streamed, so allow a few
552
+ seconds.)
553
+
554
+ ## Testing & preview
555
+
556
+ You don't have to deploy to find out whether a function works. There are three levels of
557
+ fidelity — use them in order.
558
+
559
+ ### 1. Local harness (fast, offline)
560
+
561
+ `@proveanything/smartlinks/testing` builds a `ctx` that **enforces the declared capability
562
+ envelope**, so a function fails locally the same way it would in production — the common
563
+ "I forgot to declare `sl:records:write`" bug is caught before you deploy, not after.
564
+
565
+ ```ts
566
+ import { createFunctionTestContext } from '@proveanything/smartlinks/testing'
567
+ import manifest from '../public/app.manifest.json'
568
+ import { submitCompetitionEntry } from '../src/functions'
569
+
570
+ const def = manifest.functions.definitions.find(d => d.name === 'submitCompetitionEntry')
571
+
572
+ const ctx = createFunctionTestContext({
573
+ def, // capabilities enforced come from the manifest itself
574
+ caller: { userId: 'tester' },
575
+ secrets: { 'recaptcha-secret': 'test-value' }, // fixtures — real secrets are server-only
576
+ })
577
+
578
+ const res = await submitCompetitionEntry(ctx, { method: 'POST', body: { email: 'a@b.com', answer: '42' } })
579
+ // ctx.sl.appRecords.create(...) throws CapabilityError unless `def` declares sl:records:write
580
+ ```
581
+
582
+ Pass the **`def`** (not a hand-typed capability list) so "tested" can't drift from
583
+ "declared". By default `ctx.sl` methods return a stub result (pure unit test — no network);
584
+ inject `sl` to delegate to your live SDK for real reads/writes:
585
+
586
+ ```ts
587
+ const ctx = createFunctionTestContext({
588
+ def,
589
+ sl: { appRecords: { create: (fields) => mySdk.app.records.create(fields) } },
590
+ })
591
+ ```
592
+
593
+ ### 2. Deployed test mode (high fidelity, safe)
594
+
595
+ Register to the `dev` channel and invoke on the real server — real secrets, real data —
596
+ without a live run *(coming next)*: a test invocation is forced to `caller` authority,
597
+ side-effecting writes are dry-run, and the traffic is logged separately from live metrics.
598
+
599
+ ### 3. Live
600
+
601
+ Point a real collection at the channel and invoke for real.
602
+
603
+ ### What differs across the three
604
+
605
+ | | Capabilities | `ctx.sl` | Secrets | Authority | Writes |
606
+ |---|---|---|---|---|---|
607
+ | **Local harness** | Enforced (from `def`) | Stub, or your injected SDK | Fixtures you pass | Informational | Whatever your impl does |
608
+ | **Deployed test** | Enforced | Real (test-scoped) | Real | Forced to `caller` | Dry-run |
609
+ | **Live** | Enforced | Real | Real | As declared | Real |
610
+
611
+ ### Recommended CI pattern
612
+
613
+ 1. **Unit** — run each handler through `createFunctionTestContext` (no network); assert
614
+ behaviour *and* that capabilities are sufficient (an under-declared capability throws).
615
+ 2. **Post-deploy smoke** — after registering to `dev`, hit each function once in test mode.
616
+
617
+ ## Where functions run (and why it doesn't change how you write them)
618
+
619
+ SmartLinks runs first-party (trusted) functions **in-process** and untrusted third-party
620
+ functions in an **isolated runner**. The difference is enforcement, not authoring:
621
+
622
+ - **In-process** trusts the author; `ctx` is built directly.
623
+ - **Isolated runner** enforces the `authority` boundary and `capabilities` at the container
624
+ edge — `ctx.sl` is a proxy over the declared authority, `ctx.fetch` is filtered to the
625
+ declared hosts, and there is no ambient filesystem, network, or environment.
626
+
627
+ Because the **contract is identical**, a function you write today runs unchanged if it later
628
+ moves lanes. Write to the `ctx` contract and declare your capabilities honestly, and the
629
+ platform takes care of the rest.