@veriforms/webapp-sdk 0.1.2 → 0.1.4

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/README.md CHANGED
@@ -5,25 +5,41 @@ Typed access to the VeriForms web app runtime, for web apps built in code
5
5
 
6
6
  ## Install
7
7
 
8
+ The VeriForms CLI writes the project (batch 236c): `vf app init <appId>` for a web app created with
9
+ "Build in code" — or `vf app convert <appId> --to-code`, which switches an existing one first — writes
10
+ `package.json` (this package, `@veriforms/webapp-react` and `@veriforms/webapp-vite` at one version,
11
+ React 18.3.1, date-fns, clsx, TypeScript and Vite 6), `vite.config.ts`, `tsconfig.json`,
12
+ `src/pages/main.tsx`, the app's `config.json` and `veriforms.webapp.json` into `./<appId>`. Then:
13
+
14
+ ```sh
15
+ cd <appId>
16
+ npm install
17
+ vf app types # vf-app.d.ts from config.json
18
+ vf app dev # your code against the draft, preview data only
19
+ vf app build # tsc --noEmit, then vite build into vf-build/
20
+ vf app push # the build becomes the DRAFT
21
+ ```
22
+
23
+ By hand, in a project of your own: the three packages at the same version, React and React DOM at
24
+ exactly 18.3.1, and a Vite the plugin accepts (6.x):
25
+
8
26
  ```sh
9
27
  npm i @veriforms/webapp-sdk @veriforms/webapp-react react@18.3.1 react-dom@18.3.1
10
- npm i -D @veriforms/webapp-vite vite
28
+ npm i -D @veriforms/webapp-vite vite@6
11
29
  ```
12
30
 
13
- During the pilot the packages are on npm as **restricted**: only accounts the `@veriforms` scope
14
- grants access can install them (run `npm login` with such an account, or put a read token into
15
- `.npmrc`). Without access, use the pilot kit (`tools/webapp-starter/make-pilot-kit.mjs`). Public at
16
- general availability. The three packages are released together at one version
31
+ The packages are public on npm (owner decision 2026-12-03). Web apps built in code are open to
32
+ the Enterprise and Enterprise Plus plans and to other accounts VeriForms enabled (owner decision
33
+ 2026-12-04).
34
+ The three packages are released together at one version
17
35
  (`webapp-react` names the SDK exactly). Install React at the version the platform serves (18.3.1) —
18
36
  the upload compares your `package-lock.json`.
19
37
 
20
- **Status:** pilot — published restricted (tag `webapp-v<version>`, `.github/workflows/webapp-release.yml`);
21
- public at general availability.
22
- **Availability:** web apps built in code are open only to platform administrators and
23
- accounts an administrator enabled, until the owner confirms general availability
24
- (concept §0.1). No public npm release and no public docs before then.
25
- It becomes useful to customers with phase 2, when the gateway can serve a web app
26
- built in code. Until then, VeriForms developers can already use it and its types.
38
+ **Status:** published public (tag `webapp-v<version>`, `.github/workflows/webapp-release.yml`).
39
+ **Availability:** web apps built in code are included in Enterprise and Enterprise Plus and open
40
+ to other accounts a platform administrator enabled (owner decision 2026-12-04; the switch is
41
+ `CwaCode:Availability`, read by `CodeWebAppsGate`). Server functions (`src/server/`) stay
42
+ platform-administrator only.
27
43
 
28
44
  ## What it is
29
45
 
@@ -65,11 +81,13 @@ location.href = pageLink('admin'); // every area is its own page, gated by the
65
81
  | `db.update(source, id, patch, version?, {clientToken}?)` | `customdb-write` | `VF.db.update` (version → 409 row_changed when someone changed the row) |
66
82
  | `data.list(source, params?)` | `veriforms-data` | `VF.data.list` → `{Rows, Count, Truncated}` |
67
83
  | `fetchSource(source, params?)` | `veriflow`, `http`, `demo` | `VF.fetch` |
84
+ | `knowledge.search(source, question)` (0.1.3) | `knowledge` | `VF.fetch` with `?q=` → `{status, message, passages, sourceLine}` (`sourceLine` always text with `ok`, 0.1.4) |
85
+ | `values.get(keys?)` (0.1.4) | `"values"` in config.json | `GET {base}/values?keys=…` → `{key: text}`; refusals are a `ValuesError` (`value_not_declared`, `value_not_found`) |
68
86
  | `send(source, body, {clientToken}?)` | submission, webhook, workflow, veriflow, customdb-write | `VF.send` (repeat-safe) |
69
87
  | `runAction(source, opts?)` | `workflow`, `veriflow`, `webhook` | `VF.runAction` |
70
88
  | `form.render(target, source, opts?)`, `form.submitPartial` | submission, customdb-write | `VF.form.*` |
71
89
  | `pay.start / status / pendingId / receiptLink` | `veriforms-payment` | `VF.pay.*` |
72
- | `user()`, `signIn()`, `signOut()` | — | `VF.user`, `VF.signIn`, `VF.signOut` |
90
+ | `user()`, `signIn()`, `signOut()`, `signInSecurity()` (0.1.3) | — | `VF.user`, `VF.signIn`, `VF.signOut`, `VF.signInSecurity` |
73
91
  | `access.has(role)`, `access.can(source)`, `access.level()`, `access.signedIn()` | — | `VF.access` |
74
92
  | `pageLink(name, '?…' \| '#…')`, `currentPage()`, `appLink()`, `file()` | — | `VF.pageLink`, `VF.page`, `VF.appLink`, `VF.file` |
75
93
  | `t()`, `theme()`, `newClientToken()`, `onDataChanged(listener)` | — | `VF.t`, `VF.theme.current`, `VF.newClientToken`, `vf:data-changed` |
@@ -99,12 +117,15 @@ there is no key for "anyone who is signed in". So the pattern is three things:
99
117
  "dataSources": {
100
118
  "myBookings": { "type": "customdb", "table": "bookings", "select": ["_id", "item", "day"],
101
119
  "rowRules": { "member": { "column": "booked_by", "equals": "$visitor.email" } } },
102
- "book": { "type": "customdb-write", "table": "bookings",
120
+ "book": { "type": "customdb-write", "table": "bookings", "mode": "insert",
103
121
  "fields": { "item": { "type": "string", "required": true }, "booked_by": { "type": "server-user" } },
104
122
  "rowRules": { "member": { "column": "booked_by", "equals": "$visitor.email" } } }
105
123
  }
106
124
  ```
107
125
 
126
+ A `customdb-write` source always names its `"mode"` — `"insert"`, `"upsert"` or `"update"`: there is
127
+ no default, the server refuses a config without it, and so does `vf app types` (it never assumes one).
128
+
108
129
  1. the role is declared under `"roles"` (a `rowRules` key that is not a
109
130
  declared role is refused when the config is saved);
110
131
  2. the rule compares a column with `"$visitor.email"`, the signed-in address —
@@ -119,6 +140,37 @@ The app must offer sign-in: restricted, or open to anyone with optional sign-in
119
140
  (`set_cwa_access` with `methods`, e.g. `["code"]`) — otherwise the save refuses
120
141
  the rule (`sign_in_not_offered`).
121
142
 
143
+ ### Knowledge bases: answers with their source
144
+
145
+ A `knowledge` source asks one of the space's knowledge bases a question
146
+ (`"base"`: the base's id, optional `"topK"` 1–8). `knowledge.search` resolves
147
+ with `status: "ok"` and the passages — each with the document, web page or
148
+ table row it comes from — and `sourceLine`, the citation the server built
149
+ ("Quelle: …" / "Source: …"). Show that line under anything you build from the
150
+ passages; never write a citation yourself. `"no_match"` (nothing in the base
151
+ answers it) and `"empty"` (nothing indexed yet) come with a `message` and no
152
+ passages: show the message, never an invented answer.
153
+
154
+ A refusal is an error, never an empty answer: `knowledge.search` rejects with a
155
+ `KnowledgeSearchError` whose `code` says why — `knowledge_base_internal` (an
156
+ app whose visitors are not members of the space may only use a public base an
157
+ admin confirmed), `knowledge_base_unconfirmed_app`, `knowledge_base_missing`,
158
+ `knowledge_ai_unavailable` — and `isKnowledgeRefusal(e)` is true for those.
159
+ `kind: "unavailable"` means the search could not run just now. Every search is
160
+ metered to the space's AI budget (as "Knowledge base: search from a web app").
161
+
162
+ ```ts
163
+ import { knowledge, isKnowledgeRefusal } from '@veriforms/webapp-sdk';
164
+
165
+ try {
166
+ const answer = await knowledge.search('faq', question);
167
+ if (answer.status === 'ok') show(answer.passages, answer.sourceLine);
168
+ else showNote(answer.message);
169
+ } catch (e) {
170
+ showNote(isKnowledgeRefusal(e) ? e.message : 'The search is not available just now.');
171
+ }
172
+ ```
173
+
122
174
  ### The draft shows preview data only
123
175
 
124
176
  `vf app dev` and the builder's draft preview never read or change real rows. A
@@ -36,7 +36,8 @@
36
36
  "customdb",
37
37
  "customdb-write",
38
38
  "workflow",
39
- "veriforms-roles"
39
+ "veriforms-roles",
40
+ "knowledge"
40
41
  ]
41
42
  },
42
43
  "veriflowId": {
@@ -322,7 +323,9 @@
322
323
  },
323
324
  "callableFrom": {
324
325
  "type": "string",
325
- "enum": ["server"],
326
+ "enum": [
327
+ "server"
328
+ ],
326
329
  "description": "\"server\": only the app's server functions may call this source, not the page directly (server functions are in a pilot: only platform administrators push and release them). Absent = page and server functions."
327
330
  },
328
331
  "anyoneMayRun": {
@@ -438,6 +441,16 @@
438
441
  "type": "string",
439
442
  "minLength": 10
440
443
  }
444
+ },
445
+ "base": {
446
+ "type": "string",
447
+ "description": "knowledge: the knowledge base's id (from list_knowledge_bases). The page asks with ?q=…; the API looks the base up in the app's own space."
448
+ },
449
+ "topK": {
450
+ "type": "integer",
451
+ "minimum": 1,
452
+ "maximum": 8,
453
+ "description": "knowledge: how many passages to return (1–8)."
441
454
  }
442
455
  },
443
456
  "patternProperties": {
package/dist/index.d.ts CHANGED
@@ -15,7 +15,7 @@
15
15
  *
16
16
  * Concept: docs/webapp-builder/CWA-CODE-APPS-CONCEPT.md (§4.2).
17
17
  */
18
- export declare const SDK_VERSION = "0.1.2";
18
+ export declare const SDK_VERSION = "0.1.4";
19
19
  /**
20
20
  * Augmented by the `vf-app.d.ts` that `vf app types` generates:
21
21
  *
@@ -64,11 +64,15 @@ export type SourceShape = {
64
64
  type: 'veriforms-payment';
65
65
  } | {
66
66
  type: 'veriforms-roles';
67
+ } | {
68
+ type: 'knowledge';
67
69
  };
68
70
  export interface AppShape {
69
71
  sources: Record<string, SourceShape>;
70
72
  pages: string;
71
73
  roles: string;
74
+ /** The Definitions values config.json declares in "values" (since 0.1.4). */
75
+ values: string;
72
76
  }
73
77
  /** What an app without generated types looks like: anything goes, nothing is checked. */
74
78
  interface UntypedSource {
@@ -84,6 +88,7 @@ interface UntypedApp {
84
88
  sources: Record<string, UntypedSource>;
85
89
  pages: string;
86
90
  roles: string;
91
+ values: string;
87
92
  }
88
93
  /** The app this code is typed against: the generated one, or {@link UntypedApp}. */
89
94
  export type App = Register extends {
@@ -117,6 +122,8 @@ export type ActionKey = SourceKey<'workflow' | 'veriflow' | 'webhook'>;
117
122
  export type PaymentKey = SourceKey<'veriforms-payment'>;
118
123
  /** A source {@link form.render} can draw a form for. */
119
124
  export type FormKey = SourceKey<'veriforms-submission' | 'customdb-write'>;
125
+ /** A source a page asks questions with {@link knowledge.search}: one of the space's knowledge bases (since 0.1.3). */
126
+ export type KnowledgeKey = SourceKey<'knowledge'>;
120
127
  /** A page of this web app ('main' or '' is the main page). */
121
128
  export type PageName = (App extends {
122
129
  pages: infer P;
@@ -125,6 +132,10 @@ export type PageName = (App extends {
125
132
  export type RoleName = App extends {
126
133
  roles: infer R;
127
134
  } ? R : string;
135
+ /** A value the app's config.json declares in "values" (a Definitions key such as company.iban), since 0.1.4. */
136
+ export type ValueKey = App extends {
137
+ values: infer V;
138
+ } ? V : string;
128
139
  export type RowOf<K> = SourceOf<K> extends {
129
140
  row: infer R;
130
141
  } ? R : Record<string, unknown>;
@@ -219,8 +230,18 @@ export interface UserInfo {
219
230
  name: string | null;
220
231
  roles: RoleName[];
221
232
  level: string | null;
222
- via: string | null;
233
+ /**
234
+ * How the visitor signed in: `'code'` (the e-mail code, or an owner-set list password), `'passkey'`,
235
+ * `'account'` (VeriForms account), `'sso'`, `'company'` — or `'preview'` in the builder preview. A passkey
236
+ * proves the e-mail address exactly like the code: never grant anything because via is `'passkey'`.
237
+ */
238
+ via: 'code' | 'passkey' | 'account' | 'sso' | 'company' | 'preview' | (string & {}) | null;
223
239
  signInOffered: boolean;
240
+ /**
241
+ * This visitor can save and manage passkeys here (since 0.1.3): anonymous, or signed in by the e-mail code or a
242
+ * passkey, on an app that offers the e-mail code. Then a link to {@link signInSecurity} is worth showing.
243
+ */
244
+ passkeysOffered?: boolean;
224
245
  preview?: boolean;
225
246
  }
226
247
  export interface ActionResult {
@@ -288,6 +309,7 @@ export interface VfRuntime {
288
309
  user(): Promise<unknown>;
289
310
  signIn(path?: string): void;
290
311
  signOut(path?: string): void;
312
+ signInSecurity(path?: string): void;
291
313
  appLink(target: string, path?: string): string;
292
314
  pageLink(name?: string, suffix?: string): string;
293
315
  page: string;
@@ -306,6 +328,11 @@ export interface VfRuntime {
306
328
  };
307
329
  t(key: string, vars?: Record<string, unknown>): string;
308
330
  newClientToken(): string;
331
+ /** The page's addresses: base (the app's path on this plane) and fileQuery (the draft preview's token). */
332
+ bridge?: {
333
+ base?: string;
334
+ fileQuery?: string;
335
+ };
309
336
  }
310
337
  /**
311
338
  * Thrown when the page has no VeriForms runtime, or the runtime lacks a
@@ -345,6 +372,120 @@ export declare const data: {
345
372
  };
346
373
  /** Reads a source: an Automation (veriflow), an http upstream or demo data. */
347
374
  export declare function fetchSource<K extends ReadKey>(source: K, params?: Partial<ParamsOf<K>> & NoUndeclaredParams): Promise<ResultOf<K>>;
375
+ /**
376
+ * How a knowledge search ended, as the gateway answers it (KnowledgeSourceClient.SearchAsync):
377
+ * `ok` has passages; `no_match` (nothing in the base answers the question) and `empty` (the base
378
+ * holds no indexed document yet) have none and a message to show — never an invented answer.
379
+ */
380
+ export declare const KNOWLEDGE_STATUSES: readonly ["ok", "no_match", "empty"];
381
+ export type KnowledgeStatus = typeof KNOWLEDGE_STATUSES[number];
382
+ /** One passage of a knowledge base, with what it was cited from. */
383
+ export interface KnowledgePassage {
384
+ /** The document it comes from (file name, page title, FAQ entry); null for a table row. */
385
+ document: string | null;
386
+ /** The web page it was read from, when the base indexed one. */
387
+ url: string | null;
388
+ /** The Custom Databases table, for a passage built from a table row. */
389
+ table: string | null;
390
+ rowId: number | null;
391
+ /** Its place in the document (0-based). */
392
+ position: number;
393
+ /** How well it answers the question (higher is better); compare within one answer only. */
394
+ score: number;
395
+ text: string;
396
+ }
397
+ /** The passage keys, in the gateway's order (pinned against KnowledgeSourceClient.cs by test/pins.test.ts). */
398
+ export declare const KNOWLEDGE_PASSAGE_FIELDS: readonly ["document", "url", "table", "rowId", "position", "score", "text"];
399
+ /**
400
+ * What {@link knowledge.search} resolves with. `sourceLine` is the server-built citation ("Quelle: …" /
401
+ * "Source: …"), always there with `ok` (since 0.1.4 typed so): show it under any answer built from the
402
+ * passages — never write a citation yourself.
403
+ */
404
+ export type KnowledgeAnswer = {
405
+ status: 'ok';
406
+ message: string | null;
407
+ passages: KnowledgePassage[];
408
+ sourceLine: string;
409
+ } | {
410
+ status: 'no_match' | 'empty';
411
+ message: string | null;
412
+ passages: [];
413
+ sourceLine: null;
414
+ };
415
+ /** The answer's keys (pinned against KnowledgeSourceClient.cs by test/pins.test.ts). */
416
+ export declare const KNOWLEDGE_ANSWER_FIELDS: readonly ["status", "message", "passages", "sourceLine"];
417
+ /**
418
+ * The codes a knowledge source is REFUSED with — the base, not the question: an internal base on an
419
+ * app whose visitors are not workspace members (`knowledge_base_internal`), a public base no admin
420
+ * confirmed (`knowledge_base_unconfirmed_app`), AI not available on the plan or switched off
421
+ * (`knowledge_ai_unavailable`), a base that does not exist (`knowledge_base_missing`). Pinned against
422
+ * KnowledgeSourceClient.RuleCodes and KnowledgeWebApps by test/pins.test.ts.
423
+ */
424
+ export declare const KNOWLEDGE_REFUSAL_CODES: readonly ["knowledge_base_internal", "knowledge_base_unconfirmed_app", "knowledge_ai_unavailable", "knowledge_base_missing"];
425
+ export type KnowledgeRefusalCode = typeof KNOWLEDGE_REFUSAL_CODES[number];
426
+ /**
427
+ * - `refused`: the server will not search this base for this app (one of {@link KNOWLEDGE_REFUSAL_CODES},
428
+ * or the visitor may not use the source) — asking again changes nothing; show `message`.
429
+ * - `question`: no question was asked (`query_required`).
430
+ * - `unavailable`: the search could not run just now, or its answer could not be read — try later.
431
+ */
432
+ export type KnowledgeErrorKind = 'refused' | 'question' | 'unavailable';
433
+ /**
434
+ * Every way a knowledge search does not answer. A refusal is an ERROR, never an empty answer: an empty
435
+ * list would read as "the base knows nothing about it", which is a different, false, statement.
436
+ */
437
+ export declare class KnowledgeSearchError extends Error {
438
+ readonly code: string;
439
+ readonly source: string;
440
+ readonly status?: number | undefined;
441
+ readonly kind: KnowledgeErrorKind;
442
+ constructor(code: string, source: string, message: string, status?: number | undefined, options?: {
443
+ cause?: unknown;
444
+ });
445
+ }
446
+ /** True for a knowledge search the server refused (the base's rule, a missing base, no access). */
447
+ export declare function isKnowledgeRefusal(e: unknown): e is KnowledgeSearchError & {
448
+ kind: 'refused';
449
+ };
450
+ /** Questions to the space's knowledge bases, through a `knowledge` source. */
451
+ export declare const knowledge: {
452
+ /**
453
+ * Asks the source's knowledge base one question. Resolves with the passages and the server-built
454
+ * source line (`ok`), or with `no_match` / `empty` and a message to show. Rejects with a
455
+ * {@link KnowledgeSearchError} when the search is refused or cannot run — see {@link isKnowledgeRefusal}.
456
+ * Each search is metered to the space's AI budget.
457
+ */
458
+ search<K extends KnowledgeKey>(source: K, question: string): Promise<KnowledgeAnswer>;
459
+ };
460
+ /**
461
+ * The codes a values read is refused with (the gateway's GET {base}/values, ServeController.Values):
462
+ * a key config.json does not declare in "values" (`value_not_declared`, 403), a declared value the
463
+ * space does not serve — missing, not marked "may be shown in web apps", another application's
464
+ * (`value_not_found` and the resolver's codes, 502). Pinned against the gateway by test/pins.test.ts.
465
+ */
466
+ export declare const VALUE_REFUSAL_CODES: readonly ["value_not_declared", "value_not_found", "values_unavailable"];
467
+ /** A values read that did not answer every key: refused, unreadable or unreachable. Never an empty text. */
468
+ export declare class ValuesError extends Error {
469
+ readonly code: string;
470
+ readonly keys: string[];
471
+ readonly status?: number | undefined;
472
+ constructor(code: string, keys: string[], message: string, status?: number | undefined, options?: {
473
+ cause?: unknown;
474
+ });
475
+ }
476
+ /** Definitions values: settings, fees, an IBAN — the same for every visitor, edited in VeriForms, never in the page. */
477
+ export declare const values: {
478
+ /**
479
+ * The values of `keys` (or every value config.json declares), each as TEXT exactly as
480
+ * `{{value:<key>}}` puts it in the config — formatted; parse a number yourself. Resolves with every
481
+ * key asked for, or rejects with a {@link ValuesError} naming the code and the keys: a key that is
482
+ * not declared, a value that cannot be served, or an answer without one of the keys. Works on the
483
+ * served planes and on the draft (the builder's preview, `vf app dev`).
484
+ */
485
+ get<K extends ValueKey>(keys?: readonly K[]): Promise<Record<K, string>>;
486
+ };
487
+ /** True for a values read the server refused (an undeclared key, a value it does not serve). */
488
+ export declare function isValuesError(e: unknown): e is ValuesError;
348
489
  /**
349
490
  * Posts to a source with one clientToken for the visitor's one action, and asks
350
491
  * again with the same token when the answer did not settle anything. A rejection
@@ -379,6 +520,12 @@ export declare function user(): Promise<UserInfo>;
379
520
  /** Sends the visitor to the platform's sign-in, and back to `path` (default: here). */
380
521
  export declare function signIn(path?: string): void;
381
522
  export declare function signOut(path?: string): void;
523
+ /**
524
+ * Sends the visitor to the platform's "Sign-in & security" page — their passkeys: rename, remove, add, remove all —
525
+ * and its Back link returns to `path` (default: here). A page of the platform, never a passkey dialog in page code
526
+ * (the gateway runs every ceremony). Since 0.1.3; show it when `(await user()).passkeysOffered`.
527
+ */
528
+ export declare function signInSecurity(path?: string): void;
382
529
  /** What the visitor may do, as the server told the page. The server checks every call again. */
383
530
  export declare const access: {
384
531
  has(role: RoleName): boolean;
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@
15
15
  *
16
16
  * Concept: docs/webapp-builder/CWA-CODE-APPS-CONCEPT.md (§4.2).
17
17
  */
18
- export const SDK_VERSION = '0.1.2';
18
+ export const SDK_VERSION = '0.1.4';
19
19
  export function isVfRequestError(e) {
20
20
  return e instanceof Error;
21
21
  }
@@ -104,6 +104,176 @@ export const data = {
104
104
  export function fetchSource(source, params) {
105
105
  return fn('fetch')(source, params ? { params: params } : {});
106
106
  }
107
+ // ─────────────────────────────────────────────────────────────────────────────
108
+ // Knowledge bases (a `knowledge` source, since 0.1.3)
109
+ // ─────────────────────────────────────────────────────────────────────────────
110
+ /**
111
+ * How a knowledge search ended, as the gateway answers it (KnowledgeSourceClient.SearchAsync):
112
+ * `ok` has passages; `no_match` (nothing in the base answers the question) and `empty` (the base
113
+ * holds no indexed document yet) have none and a message to show — never an invented answer.
114
+ */
115
+ export const KNOWLEDGE_STATUSES = ['ok', 'no_match', 'empty'];
116
+ /** The passage keys, in the gateway's order (pinned against KnowledgeSourceClient.cs by test/pins.test.ts). */
117
+ export const KNOWLEDGE_PASSAGE_FIELDS = ['document', 'url', 'table', 'rowId', 'position', 'score', 'text'];
118
+ /** The answer's keys (pinned against KnowledgeSourceClient.cs by test/pins.test.ts). */
119
+ export const KNOWLEDGE_ANSWER_FIELDS = ['status', 'message', 'passages', 'sourceLine'];
120
+ /**
121
+ * The codes a knowledge source is REFUSED with — the base, not the question: an internal base on an
122
+ * app whose visitors are not workspace members (`knowledge_base_internal`), a public base no admin
123
+ * confirmed (`knowledge_base_unconfirmed_app`), AI not available on the plan or switched off
124
+ * (`knowledge_ai_unavailable`), a base that does not exist (`knowledge_base_missing`). Pinned against
125
+ * KnowledgeSourceClient.RuleCodes and KnowledgeWebApps by test/pins.test.ts.
126
+ */
127
+ export const KNOWLEDGE_REFUSAL_CODES = [
128
+ 'knowledge_base_internal', 'knowledge_base_unconfirmed_app', 'knowledge_ai_unavailable', 'knowledge_base_missing',
129
+ ];
130
+ /**
131
+ * Every way a knowledge search does not answer. A refusal is an ERROR, never an empty answer: an empty
132
+ * list would read as "the base knows nothing about it", which is a different, false, statement.
133
+ */
134
+ export class KnowledgeSearchError extends Error {
135
+ constructor(code, source, message, status, options) {
136
+ super(message);
137
+ this.code = code;
138
+ this.source = source;
139
+ this.status = status;
140
+ this.name = 'KnowledgeSearchError';
141
+ if (options && 'cause' in options)
142
+ this.cause = options.cause;
143
+ this.kind = KNOWLEDGE_REFUSAL_CODES.includes(code) || status === 401 || status === 403 || status === 404
144
+ ? 'refused'
145
+ : code === 'query_required' || status === 400 ? 'question' : 'unavailable';
146
+ }
147
+ }
148
+ /** True for a knowledge search the server refused (the base's rule, a missing base, no access). */
149
+ export function isKnowledgeRefusal(e) {
150
+ return e instanceof KnowledgeSearchError && e.kind === 'refused';
151
+ }
152
+ const isPassage = (p) => !!p && typeof p === 'object'
153
+ && typeof p.text === 'string' && typeof p.position === 'number';
154
+ /** The gateway's answer, checked: anything else is a loud failure, never an empty answer. */
155
+ function readKnowledgeAnswer(source, raw) {
156
+ const a = raw;
157
+ const unreadable = () => new KnowledgeSearchError('knowledge_answer_unreadable', source, `@veriforms/webapp-sdk ${SDK_VERSION}: the answer of knowledge source "${source}" could not be read.`);
158
+ if (!a || typeof a !== 'object' || !KNOWLEDGE_STATUSES.includes(a.status)
159
+ || !Array.isArray(a.passages) || !a.passages.every(isPassage))
160
+ throw unreadable();
161
+ const message = typeof a.message === 'string' ? a.message : null;
162
+ if (a.status === 'ok') {
163
+ // An ok answer always carries the server-built line (KnowledgeCitations.SourceLineOf over its passages):
164
+ // without it the page would show an answer with no source, so it is unreadable, never null (batch 236c).
165
+ if (a.passages.length === 0 || typeof a.sourceLine !== 'string' || !a.sourceLine)
166
+ throw unreadable();
167
+ return { status: 'ok', message, passages: a.passages, sourceLine: a.sourceLine };
168
+ }
169
+ if (a.passages.length > 0)
170
+ throw unreadable();
171
+ return { status: a.status, message, passages: [], sourceLine: null };
172
+ }
173
+ /** Questions to the space's knowledge bases, through a `knowledge` source. */
174
+ export const knowledge = {
175
+ /**
176
+ * Asks the source's knowledge base one question. Resolves with the passages and the server-built
177
+ * source line (`ok`), or with `no_match` / `empty` and a message to show. Rejects with a
178
+ * {@link KnowledgeSearchError} when the search is refused or cannot run — see {@link isKnowledgeRefusal}.
179
+ * Each search is metered to the space's AI budget.
180
+ */
181
+ async search(source, question) {
182
+ const q = typeof question === 'string' ? question.trim() : '';
183
+ if (!q)
184
+ throw new KnowledgeSearchError('query_required', source, 'Ask a question: knowledge.search(source, "…").', 400);
185
+ const call = fn('fetch');
186
+ let raw;
187
+ try {
188
+ raw = await call(source, { params: { q } });
189
+ }
190
+ catch (e) {
191
+ const err = e;
192
+ const data = (err && typeof err === 'object' ? err.data : undefined);
193
+ const code = typeof err?.code === 'string' ? err.code : typeof data?.code === 'string' ? data.code : 'knowledge_unavailable';
194
+ const message = typeof data?.message === 'string' ? data.message : err instanceof Error ? err.message : String(e);
195
+ throw new KnowledgeSearchError(code, source, message, typeof err?.status === 'number' ? err.status : undefined, { cause: e });
196
+ }
197
+ return readKnowledgeAnswer(source, raw);
198
+ },
199
+ };
200
+ // ─────────────────────────────────────────────────────────────────────────────
201
+ // Values (Definitions), since 0.1.4
202
+ // ─────────────────────────────────────────────────────────────────────────────
203
+ /**
204
+ * The codes a values read is refused with (the gateway's GET {base}/values, ServeController.Values):
205
+ * a key config.json does not declare in "values" (`value_not_declared`, 403), a declared value the
206
+ * space does not serve — missing, not marked "may be shown in web apps", another application's
207
+ * (`value_not_found` and the resolver's codes, 502). Pinned against the gateway by test/pins.test.ts.
208
+ */
209
+ export const VALUE_REFUSAL_CODES = ['value_not_declared', 'value_not_found', 'values_unavailable'];
210
+ /** A values read that did not answer every key: refused, unreadable or unreachable. Never an empty text. */
211
+ export class ValuesError extends Error {
212
+ constructor(code, keys, message, status, options) {
213
+ super(message, options);
214
+ this.code = code;
215
+ this.keys = keys;
216
+ this.status = status;
217
+ this.name = 'ValuesError';
218
+ }
219
+ }
220
+ /** Definitions values: settings, fees, an IBAN — the same for every visitor, edited in VeriForms, never in the page. */
221
+ export const values = {
222
+ /**
223
+ * The values of `keys` (or every value config.json declares), each as TEXT exactly as
224
+ * `{{value:<key>}}` puts it in the config — formatted; parse a number yourself. Resolves with every
225
+ * key asked for, or rejects with a {@link ValuesError} naming the code and the keys: a key that is
226
+ * not declared, a value that cannot be served, or an answer without one of the keys. Works on the
227
+ * served planes and on the draft (the builder's preview, `vf app dev`).
228
+ */
229
+ async get(keys) {
230
+ const bridge = runtime().bridge;
231
+ if (!bridge || typeof bridge.base !== 'string')
232
+ throw new SdkRuntimeMismatchError('bridge.base');
233
+ const asked = [...new Set((keys ?? []).map(k => String(k).trim()).filter(Boolean))];
234
+ const query = bridge.fileQuery ?? '';
235
+ const url = `${bridge.base}/values${query}${asked.length ? `${query.includes('?') ? '&' : '?'}keys=${asked.map(encodeURIComponent).join(',')}` : ''}`;
236
+ let res;
237
+ try {
238
+ res = await fetch(url, { credentials: 'same-origin', headers: { Accept: 'application/json' } });
239
+ }
240
+ catch (e) {
241
+ throw new ValuesError('values_unavailable', asked, `@veriforms/webapp-sdk ${SDK_VERSION}: the values could not be read (${e.message}).`, undefined, { cause: e });
242
+ }
243
+ let body;
244
+ try {
245
+ body = await res.json();
246
+ }
247
+ catch {
248
+ body = undefined;
249
+ }
250
+ const b = (body && typeof body === 'object' ? body : {});
251
+ if (!res.ok) {
252
+ const code = typeof b.code === 'string' ? b.code : 'values_unavailable';
253
+ const named = Array.isArray(b.keys) ? b.keys.filter((k) => typeof k === 'string') : asked;
254
+ throw new ValuesError(code, named, typeof b.message === 'string' ? b.message : `The values could not be read (${res.status}).`, res.status);
255
+ }
256
+ const got = b.values;
257
+ if (!got || typeof got !== 'object' || Array.isArray(got)) {
258
+ throw new ValuesError('values_unreadable', asked, `@veriforms/webapp-sdk ${SDK_VERSION}: the values answer could not be read.`, res.status);
259
+ }
260
+ const map = got;
261
+ // Every key asked for is in the answer as text — a missing one is a fault, never "".
262
+ const missing = asked.filter(k => typeof map[k] !== 'string');
263
+ if (missing.length) {
264
+ throw new ValuesError('value_not_found', missing, `The values answer has no text for ${missing.join(', ')}.`, res.status);
265
+ }
266
+ const out = {};
267
+ for (const [k, v] of Object.entries(map))
268
+ if (typeof v === 'string')
269
+ out[k] = v;
270
+ return out;
271
+ },
272
+ };
273
+ /** True for a values read the server refused (an undeclared key, a value it does not serve). */
274
+ export function isValuesError(e) {
275
+ return e instanceof ValuesError;
276
+ }
107
277
  /**
108
278
  * Posts to a source with one clientToken for the visitor's one action, and asks
109
279
  * again with the same token when the answer did not settle anything. A rejection
@@ -154,6 +324,12 @@ export function user() {
154
324
  /** Sends the visitor to the platform's sign-in, and back to `path` (default: here). */
155
325
  export function signIn(path) { fn('signIn')(path); }
156
326
  export function signOut(path) { fn('signOut')(path); }
327
+ /**
328
+ * Sends the visitor to the platform's "Sign-in & security" page — their passkeys: rename, remove, add, remove all —
329
+ * and its Back link returns to `path` (default: here). A page of the platform, never a passkey dialog in page code
330
+ * (the gateway runs every ceremony). Since 0.1.3; show it when `(await user()).passkeysOffered`.
331
+ */
332
+ export function signInSecurity(path) { fn('signInSecurity')(path); }
157
333
  /** What the visitor may do, as the server told the page. The server checks every call again. */
158
334
  export const access = {
159
335
  has(role) { return fn('access.has')(role); },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veriforms/webapp-sdk",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Typed access to the VeriForms web app runtime (window.VF) for web apps built in code: data sources, tables, submissions, actions, payments, sign-in and pages.",
5
5
  "keywords": [
6
6
  "veriforms",