@sess.si/sdk 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0 — 2026-11-08
4
+
5
+ - Receipt v2: `verifyDecisionReceipt` and `receipts.verifyResponse()` verify receipts of type
6
+ `sess-receipt-2+jwt`, which commit by hash (`surface.revision_hash`) to the round's
7
+ `revision_envelope`: when the round was published and, when one of your API keys published it,
8
+ that key's ID and its label at the time. A receipt v2 is verified only with its envelope:
9
+ `verifyResponse()` passes the response's own `revision_envelope`, and `verifyDecisionReceipt`
10
+ takes it as `revisionEnvelope`. A missing, malformed or different envelope is refused with
11
+ code `REVISION_ENVELOPE_MISMATCH`, after the issuer, audience, expiry and signature checks.
12
+ Receipt v1 (`sess-receipt+jwt`) is verified exactly as before.
13
+ - `AcceptedResponse.revision_envelope`, `SessionEvent.revision_envelope` (`GET
14
+ /v1/sessions/{id}/events`) and the `response.accepted` webhook message's `revision_envelope`:
15
+ present beside a receipt v2, absent beside a receipt v1. `verifyWebhook` accepts the member.
16
+ New types `RevisionEnvelope`, `ReceiptClaimsV1` and `ReceiptClaimsV2`; `ReceiptClaims` is now
17
+ their union.
18
+ - `verifyDecisionBundle` and `sess verify` read bundle-v2 (a receipt v2 with its envelope) as well
19
+ as bundle-v1, with the new reason `revision`. A valid bundle-v2 result carries
20
+ `surface.revision_hash` and the verified `revision_envelope`. A bundle `version` above 2 is
21
+ `unsupported_version`. The receipt-v2 and bundle-v2 specifications and the bundle-v2
22
+ conformance corpus are copies from Sess commit `c67c792`.
23
+ - The runtime dependencies are unchanged. The default `User-Agent` names the new version.
24
+
25
+ ## 0.2.0 — 2026-11-06
26
+
27
+ - A rating in `sess.ask`: a field `{ type: 'rating' }` asks for a whole number from 1 to `max`.
28
+ `max` is 2 to 10, default 5; the person sees stars up to 5 and numbered choices above. `low`
29
+ and `high` are optional words at the two ends, at most 24 characters each. The answer is the
30
+ number chosen. In the types for `sessions.create()` and `publish()`, a field takes
31
+ `rating: { low?, high? }` with the schema exactly `{ type: 'integer', minimum: 1, maximum: N }`,
32
+ N from 2 to 10.
33
+ - Respondents in `sess.ask`: add `respondents: { max }` and the same question goes to many people
34
+ through one link, a Sess Ask. Each person who starts gets their own page. The handle is
35
+ `{ askId, link, max, expiresAt, read(), close() }`. `read()` returns the Ask's status and
36
+ counts, and one page of respondents, each with their answer verified by its signed receipt and
37
+ typed by the fields. `close()` ends the Ask; those who answered keep their pages and receipts.
38
+ Advanced: `name`, `expires_in`, `respondent_expires_in` and `auto_complete` in `respondents`,
39
+ and `sess.asks.retrieve()` and `sess.asks.close()` to read or close an Ask by its ID (raw
40
+ records, not yet verified). Creation is attempted once and never retried. Without
41
+ `respondents`, `sess.ask` is unchanged.
42
+ - The runtime dependencies are unchanged. The default `User-Agent` names the new version.
43
+
3
44
  ## 0.1.1 — 2026-11-04
4
45
 
5
46
  - The npm package page only: `keywords`, and `homepage` now points at the docs quickstart. The API
package/README.md CHANGED
@@ -14,7 +14,7 @@ terminal with a verified receipt.
14
14
  **Install** the SDK in your own server project:
15
15
 
16
16
  ```sh
17
- npm install --save-exact @sess.si/sdk@0.1.1
17
+ npm install --save-exact @sess.si/sdk@0.3.0
18
18
  ```
19
19
 
20
20
  ## Ask a person
@@ -47,8 +47,8 @@ before anything waits. The link is a bearer capability: deliver it only to the p
47
47
  logs or analytics. `answer()` waits for the person (ten minutes by default), verifies the signed
48
48
  receipt against the exact question, checks that the answer is still the current step, completes the
49
49
  Session and returns the values typed from your fields. Completion closes the Session: the link no
50
- longer accepts answers. Field types are `text`, `number`, `integer`, `boolean`, `choice` and
51
- `multi_choice` ([API reference](docs/api.md#ask-one-question)).
50
+ longer accepts answers. Field types are `text`, `number`, `integer`, `boolean`, `choice`,
51
+ `multi_choice` and `rating` ([API reference](docs/api.md#ask-one-question)).
52
52
 
53
53
  If the wait times out (`wait_ended`, code `WAIT_TIMEOUT`) or you abort it, nothing changes remotely:
54
54
  call `answer()` again on the same handle. An error with `outcome: "unknown"` means completion is not
@@ -120,9 +120,10 @@ async function askShort(question: string) {
120
120
  }
121
121
  ```
122
122
 
123
- **Release status:** `0.1.1` is the current release, served under the `latest` dist-tag. Its API is
124
- that of `0.1.0`, the first stable release. `next` stays at the last release candidate, `0.1.0-rc.10`. The [changelog](CHANGELOG.md) describes
125
- each version; `npm view @sess.si/sdk dist-tags` shows what the registry serves now.
123
+ **Release status:** `0.3.0` is the current release, served under the `latest` dist-tag. It
124
+ verifies receipt v2, which commits to the record of the round it answered, and still verifies
125
+ receipt v1. `next` stays at the last release candidate,
126
+ `0.1.0-rc.10`. The [changelog](CHANGELOG.md) describes each version; `npm view @sess.si/sdk dist-tags` shows what the registry serves now.
126
127
 
127
128
  ## Commerce
128
129
 
@@ -242,10 +243,10 @@ exact Surface and input, and the issuer's public keys. Check it on your own comp
242
243
  trust (never the keys inside the bundle):
243
244
 
244
245
  ```sh
245
- npx -p @sess.si/sdk@0.1.1 sess verify bundle.json --issuer https://api.sess.si --keys sess-receipt-keys.json
246
+ npx -p @sess.si/sdk@0.3.0 sess verify bundle.json --issuer https://api.sess.si --keys sess-receipt-keys.json
246
247
  ```
247
248
 
248
- The `sess` command first ships in `0.1.0-rc.5`; any later version, `0.1.1` included, has it.
249
+ The `sess` command first ships in `0.1.0-rc.5`; any later version, `0.3.0` included, has it.
249
250
 
250
251
  You'll see `Valid decision bundle.` and what was accepted, when, on which revision; or `Invalid`
251
252
  and the first reason. Exit status is 0 valid, 1 invalid, 2 usage error; add `--json` for the full
package/dist/ask.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { ReceiptResource } from './receipts/resource.js';
2
2
  import type { Sessions } from './sessions.js';
3
- import type { InteractiveInteraction, RequestOptions } from './types.js';
3
+ import { type AskReadOptions, type Asks } from './asks.js';
4
+ import type { ApiResult, AskCounts, AskRespondentRecord, CreateAskRequest, CreateAskResponse, InteractiveInteraction, RequestOptions } from './types.js';
4
5
  interface AskFieldBase {
5
6
  /** Key of this field in the answer: `^[a-z][a-z0-9_]{0,63}$`. */
6
7
  readonly name: string;
@@ -26,6 +27,19 @@ export type AskField = (AskFieldBase & {
26
27
  }) | (AskFieldBase & {
27
28
  readonly type: 'boolean';
28
29
  readonly default?: boolean;
30
+ }) | (AskFieldBase & {
31
+ /**
32
+ * A rating: a whole number from 1 to `max`. The person sees stars up to 5 and numbered
33
+ * choices above it; the answer is the chosen number.
34
+ */
35
+ readonly type: 'rating';
36
+ /** The largest choice, 2–10. Default 5 (five stars). */
37
+ readonly max?: number;
38
+ /** Optional words by the lowest choice: a word or two; at most 24. Example: `Not likely` */
39
+ readonly low?: string;
40
+ /** Optional words by the highest choice: a word or two; at most 24. Example: `Very likely` */
41
+ readonly high?: string;
42
+ readonly default?: number;
29
43
  }) | (AskFieldBase & {
30
44
  readonly type: 'choice';
31
45
  /** 1–100 choices. The words shown for one choice: short; at most 60. Example: `Next Monday` */
@@ -63,7 +77,7 @@ export interface AskInput<F extends readonly AskField[] = readonly AskField[]> {
63
77
  type AskValue<T> = T extends {
64
78
  type: 'text';
65
79
  } ? string : T extends {
66
- type: 'number' | 'integer';
80
+ type: 'number' | 'integer' | 'rating';
67
81
  } ? number : T extends {
68
82
  type: 'boolean';
69
83
  } ? boolean : T extends {
@@ -92,6 +106,109 @@ export type AskAnswer<F extends readonly AskField[]> = Simplify<{
92
106
  } & {
93
107
  readonly [P in F[number] as AlwaysPresent<P> extends true ? never : P['name']]?: AskValue<P>;
94
108
  }>;
109
+ /**
110
+ * One link that many people can answer, each on their own page (a Sess Ask). Each person who
111
+ * starts gets an ordinary Session of their own; a respondent is a browser, not a person.
112
+ */
113
+ export interface AskRespondents {
114
+ /**
115
+ * How many people may start: at least 2, at most your plan's active-Session limit (Free 25,
116
+ * Starter 50, Pro 100; Sess checks the ceiling). The cap is exact: it is checked when a person
117
+ * starts, so it cannot be overshot. The Ask closes at the last place.
118
+ */
119
+ readonly max: number;
120
+ /**
121
+ * Advanced: adds one required "Your name" text field, named `name`, before the first field; the
122
+ * answer then has `name`. Typed data to compare, never verified. Default false.
123
+ */
124
+ readonly name?: boolean;
125
+ /**
126
+ * Advanced: the one deadline, in whole seconds from creation, from 30 up to your plan's link
127
+ * lifetime: after it no one new may start, and every respondent's link has ended. Absent: the
128
+ * plan's lifetime.
129
+ */
130
+ readonly expires_in?: number;
131
+ /**
132
+ * Advanced: each respondent's link life from their Start, in whole seconds, at least 30; Sess
133
+ * clamps it to the plan's limit and to what remains of the Ask. Absent: what remains of the Ask.
134
+ */
135
+ readonly respondent_expires_in?: number;
136
+ /**
137
+ * Advanced: true (the default), each respondent's Session completes when their answer is
138
+ * accepted. False: you continue each respondent with `sess.sessions` (publish, then complete).
139
+ */
140
+ readonly auto_complete?: boolean;
141
+ }
142
+ /** A question for many people: the same question and fields, and `respondents` instead of `expires_in`. */
143
+ export type AskRespondentsInput<F extends readonly AskField[] = readonly AskField[], R extends AskRespondents = AskRespondents> = Omit<AskInput<F>, 'expires_in'> & {
144
+ readonly respondents: R;
145
+ };
146
+ type RespondentName<R> = R extends {
147
+ readonly name: true;
148
+ } ? {
149
+ readonly name: string;
150
+ } : R extends {
151
+ readonly name?: false | undefined;
152
+ } ? {} : {
153
+ readonly name?: string;
154
+ };
155
+ /** One respondent's answer: the fields' answer, with `name` first when `respondents.name` is true. */
156
+ export type AskRespondentsAnswer<F extends readonly AskField[], R> = Simplify<RespondentName<R> & AskAnswer<F>>;
157
+ /** One respondent: an ordinary Session of their own, and their verified answer once given. */
158
+ export interface AskRespondent<T> {
159
+ /** Their Session, for continuing them through `sess.sessions` (with `auto_complete: false`). */
160
+ readonly sessionId: string;
161
+ /** Their Session's status; `purged` once its content was deleted after its retention. */
162
+ readonly status: AskRespondentRecord['status'];
163
+ /** Their Session's current revision. */
164
+ readonly revision: number;
165
+ /** When they started (ISO 8601). */
166
+ readonly startedAt: string;
167
+ readonly completedAt: string | null;
168
+ /**
169
+ * Their answer to the question, verified by its signed receipt and typed by the fields. Null
170
+ * until they answer, and for a purged respondent.
171
+ */
172
+ readonly answer: T | null;
173
+ }
174
+ /** One read of an Ask: its state and counts, and one page of respondents in the order they started. */
175
+ export interface AskRead<T> {
176
+ /** `closed` once its last place was started, you closed it, or its deadline passed. */
177
+ readonly status: 'open' | 'closed';
178
+ readonly closedBy: 'max' | 'owner' | 'deadline' | null;
179
+ readonly closedAt: string | null;
180
+ /** Started, answered and completed respondents, and Starts refused by reason. */
181
+ readonly counts: Readonly<AskCounts>;
182
+ readonly respondents: readonly AskRespondent<T>[];
183
+ /** Pass as `cursor` to `read()` for the next page; null on the last page. */
184
+ readonly nextCursor: string | null;
185
+ }
186
+ /** The Ask after `close()`. */
187
+ export type AskClosed = Omit<AskRead<never>, 'respondents' | 'nextCursor'>;
188
+ /** A question for many people: its one link now, and their answers whenever you read them. */
189
+ export interface AskRespondentsHandle<T> {
190
+ /** The Ask's ID, to read or close it later with `sess.asks`. */
191
+ readonly askId: string;
192
+ /**
193
+ * The one link to share with everyone who should answer. Each person gets their own page. Keep
194
+ * it out of logs.
195
+ */
196
+ readonly link: string;
197
+ readonly max: number;
198
+ /** The deadline (`action_expires_at`, ISO 8601): from it no one new may start. */
199
+ readonly expiresAt: string;
200
+ /**
201
+ * Reads the Ask: whether it is open, its counts, and each respondent with their verified, typed
202
+ * answer. Returning an answer here is that respondent's retrieval, as reading a Session is.
203
+ * Up to 100 respondents a page; pass `nextCursor` as `cursor` for the next.
204
+ */
205
+ read(options?: AskReadOptions): Promise<AskRead<T>>;
206
+ /**
207
+ * Closes the Ask now: no one new can start. Respondents who have not answered have their links
208
+ * ended; those who answered keep their pages and receipts. Closing a closed Ask changes nothing.
209
+ */
210
+ close(options?: RequestOptions): Promise<AskClosed>;
211
+ }
95
212
  export interface AskOptions extends RequestOptions {
96
213
  /** Trusted expected receipt audience for this question; defaults to the client configuration. */
97
214
  expectedWorkspaceId?: string;
@@ -126,7 +243,7 @@ export interface AskHandle<T> {
126
243
  */
127
244
  answer(options?: AskAnswerOptions): Promise<T>;
128
245
  }
129
- declare const TYPES: readonly ["text", "number", "integer", "boolean", "choice", "multi_choice"];
246
+ declare const TYPES: readonly ["text", "number", "integer", "boolean", "choice", "multi_choice", "rating"];
130
247
  type AskType = (typeof TYPES)[number];
131
248
  /** Internal compiled field: what an accepted answer is checked against. */
132
249
  interface CompiledField {
@@ -142,6 +259,17 @@ export interface CompiledAsk {
142
259
  fields: readonly CompiledField[];
143
260
  /** The link lifetime in seconds, when the question set one. */
144
261
  expiresIn?: number;
262
+ /** Only for a question with `respondents` (an Ask). */
263
+ respondents?: CompiledRespondents;
264
+ }
265
+ interface CompiledRespondents {
266
+ /** The create body's members besides `interaction`, exactly as given (Sess applies the defaults). */
267
+ body: Omit<CreateAskRequest, 'interaction'>;
268
+ /**
269
+ * Round one as each respondent's Session stores it: the interaction, with Sess's "Your name"
270
+ * field before the first field when `name` is true.
271
+ */
272
+ surface: InteractiveInteraction;
145
273
  }
146
274
  /** The shortest link lifetime Sess accepts, in seconds (the ceiling is the plan's). */
147
275
  export declare const LINK_LIFETIME_FLOOR_SECONDS = 30;
@@ -156,6 +284,16 @@ export declare function compileAsk(input: unknown): CompiledAsk;
156
284
  * always a list, and an empty optional value is absent.
157
285
  */
158
286
  export declare function checkAnswer(fields: readonly CompiledField[], data: unknown): Readonly<Record<string, unknown>>;
159
- /** Validates locally, creates once (the link is available before any wait) and returns the handle. */
160
- export declare function ask<T>(sessions: Sessions, receipts: ReceiptResource, input: unknown, options?: AskOptions): Promise<AskHandle<T>>;
287
+ /** What `ask` needs from the client. */
288
+ export interface AskContext {
289
+ sessions: Sessions;
290
+ receipts: ReceiptResource;
291
+ asks: Asks;
292
+ createAsk(body: CreateAskRequest, options: RequestOptions): Promise<ApiResult<CreateAskResponse>>;
293
+ }
294
+ /**
295
+ * Validates locally, creates once (the link is available before any wait) and returns the handle:
296
+ * one Session for one person, or with `respondents` one Ask for many.
297
+ */
298
+ export declare function ask<T>(context: AskContext, input: unknown, options?: AskOptions): Promise<AskHandle<T> | AskRespondentsHandle<T>>;
161
299
  export {};
package/dist/ask.js CHANGED
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
2
2
  import { inspect } from 'node:util';
3
3
  import { SessError, lengthMessage } from './errors.js';
4
4
  import { canonicalJson } from './receipts/json.js';
5
+ import { ASK_RESPONDENTS_FLOOR } from './asks.js';
5
6
  import { isInteractiveSession } from './types.js';
6
7
  import { withSignal } from './internal/time.js';
7
8
  /** The runtime byte limit for one stored interaction. */
@@ -21,12 +22,18 @@ const LIMITS = Object.freeze({
21
22
  submitLabel: 24,
22
23
  label: 60,
23
24
  option: 60,
25
+ /** A rating's end label (`low`, `high`). */
26
+ ratingLabel: 24,
24
27
  });
25
- const TYPES = ['text', 'number', 'integer', 'boolean', 'choice', 'multi_choice'];
28
+ /** A rating's largest choice: 2–10, default 5 (stars up to 5, numbered above). */
29
+ const RATING = Object.freeze({ min: 2, max: 10, default: 5 });
30
+ const TYPES = ['text', 'number', 'integer', 'boolean', 'choice', 'multi_choice', 'rating'];
26
31
  const FIELD_NAME = /^[a-z][a-z0-9_]{0,63}$/;
27
32
  const RESERVED = new Set(['__proto__', 'constructor', 'prototype']);
28
33
  // Plain text: no C0/C1 controls other than tab and newline, no bidirectional overrides.
29
34
  const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f‪-‮⁦-⁩]/;
35
+ /** Sess's respondent name field (`respondents.name: true`), exactly as the runtime adds it. */
36
+ const NAME_FIELD = Object.freeze({ name: 'name', label: 'Your name', maxLength: 80 });
30
37
  /** The shortest link lifetime Sess accepts, in seconds (the ceiling is the plan's). */
31
38
  export const LINK_LIFETIME_FLOOR_SECONDS = 30;
32
39
  function invalid(path, problem) {
@@ -144,6 +151,7 @@ function validValue(field, value) {
144
151
  return typeof value === 'string' && value.isWellFormed() && codePoints(value) <= LIMITS.textMax;
145
152
  case 'number':
146
153
  case 'integer':
154
+ case 'rating':
147
155
  return (typeof value === 'number' &&
148
156
  Number.isFinite(value) &&
149
157
  (field.type === 'number' || Number.isInteger(value)) &&
@@ -161,7 +169,20 @@ function validValue(field, value) {
161
169
  }
162
170
  function compileField(raw, path, names) {
163
171
  const f = object(raw, path);
164
- closed(f, path, ['name', 'label', 'type', 'required', 'options', 'default', 'multiline', 'minimum', 'maximum'], ['name', 'label', 'type']);
172
+ closed(f, path, [
173
+ 'name',
174
+ 'label',
175
+ 'type',
176
+ 'required',
177
+ 'options',
178
+ 'default',
179
+ 'multiline',
180
+ 'minimum',
181
+ 'maximum',
182
+ 'max',
183
+ 'low',
184
+ 'high',
185
+ ], ['name', 'label', 'type']);
165
186
  if (typeof f.name !== 'string' || !FIELD_NAME.test(f.name) || RESERVED.has(f.name))
166
187
  invalid(`${path}.name`, 'must match ^[a-z][a-z0-9_]{0,63}$');
167
188
  const name = f.name;
@@ -179,13 +200,30 @@ function compileField(raw, path, names) {
179
200
  invalid(`${path}.multiline`, 'is only allowed for text');
180
201
  if ((f.minimum !== undefined || f.maximum !== undefined) && type !== 'number' && type !== 'integer')
181
202
  invalid(path, 'minimum/maximum are only allowed for number and integer');
203
+ if ((f.max !== undefined || f.low !== undefined || f.high !== undefined) && type !== 'rating')
204
+ invalid(path, 'max/low/high are only allowed for rating');
182
205
  for (const key of ['required', 'multiline'])
183
206
  if (f[key] !== undefined && typeof f[key] !== 'boolean')
184
207
  invalid(`${path}.${key}`, 'must be a boolean');
185
208
  const required = f.required === undefined ? type !== 'boolean' : f.required === true;
186
209
  const compiled = { name, type, required };
187
210
  let schema;
211
+ let rating;
188
212
  switch (type) {
213
+ case 'rating': {
214
+ const max = f.max === undefined ? RATING.default : f.max;
215
+ if (typeof max !== 'number' || !Number.isInteger(max) || max < RATING.min || max > RATING.max)
216
+ invalid(`${path}.max`, `must be a whole number from ${RATING.min} to ${RATING.max}`);
217
+ compiled.minimum = 1;
218
+ compiled.maximum = max;
219
+ // Sess's rating: exactly this schema, and the end labels only when given.
220
+ schema = { type: 'integer', minimum: 1, maximum: max };
221
+ rating = {
222
+ ...(f.low !== undefined ? { low: text(f.low, `${path}.low`, LIMITS.ratingLabel) } : {}),
223
+ ...(f.high !== undefined ? { high: text(f.high, `${path}.high`, LIMITS.ratingLabel) } : {}),
224
+ };
225
+ break;
226
+ }
189
227
  case 'text':
190
228
  schema = { type: 'string' };
191
229
  break;
@@ -234,6 +272,7 @@ function compileField(raw, path, names) {
234
272
  required,
235
273
  schema,
236
274
  ...(f.multiline !== undefined ? { multiline: f.multiline } : {}),
275
+ ...(rating !== undefined ? { rating } : {}),
237
276
  ...(f.default !== undefined ? { value: f.default } : {}),
238
277
  };
239
278
  return { component, compiled: Object.freeze(compiled) };
@@ -244,7 +283,9 @@ function compileField(raw, path, names) {
244
283
  */
245
284
  export function compileAsk(input) {
246
285
  const a = object(plain(input, ''), 'input');
247
- closed(a, 'input', ['question', 'details', 'fields', 'submit_label', 'expires_in'], ['question', 'fields']);
286
+ closed(a, 'input', ['question', 'details', 'fields', 'submit_label', 'expires_in', 'respondents'], ['question', 'fields']);
287
+ if (a.respondents !== undefined && a.expires_in !== undefined)
288
+ invalid('expires_in', 'is for one person’s link; with respondents, use respondents.expires_in');
248
289
  const expiresIn = a.expires_in;
249
290
  if (expiresIn !== undefined &&
250
291
  (typeof expiresIn !== 'number' ||
@@ -275,12 +316,68 @@ export function compileAsk(input) {
275
316
  };
276
317
  if (Buffer.byteLength(JSON.stringify(interaction), 'utf8') > SURFACE_LIMIT_BYTES)
277
318
  invalid('input', `exceeds the ${SURFACE_LIMIT_BYTES}-byte Surface limit`);
319
+ if (a.respondents === undefined)
320
+ return {
321
+ interaction,
322
+ fields: Object.freeze(compiled),
323
+ ...(expiresIn !== undefined ? { expiresIn: expiresIn } : {}),
324
+ };
325
+ const respondents = compileRespondents(a.respondents, names);
326
+ const named = respondents.respondents.name === true;
278
327
  return {
279
328
  interaction,
280
- fields: Object.freeze(compiled),
281
- ...(expiresIn !== undefined ? { expiresIn: expiresIn } : {}),
329
+ fields: Object.freeze(named
330
+ ? [Object.freeze({ name: NAME_FIELD.name, type: 'text', required: true }), ...compiled]
331
+ : compiled),
332
+ respondents: {
333
+ body: respondents,
334
+ surface: named ? withNameField(interaction) : interaction,
335
+ },
282
336
  };
283
337
  }
338
+ function lifetime(value, path) {
339
+ if (value === undefined)
340
+ return undefined;
341
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < LINK_LIFETIME_FLOOR_SECONDS)
342
+ invalid(path, `must be a whole number of seconds, at least ${LINK_LIFETIME_FLOOR_SECONDS}`);
343
+ return value;
344
+ }
345
+ /** `respondents`: the floor of `max` and of each lifetime is checked here; every ceiling is the plan's. */
346
+ function compileRespondents(raw, names) {
347
+ const r = object(raw, 'respondents');
348
+ closed(r, 'respondents', ['max', 'name', 'expires_in', 'respondent_expires_in', 'auto_complete'], ['max']);
349
+ if (typeof r.max !== 'number' || !Number.isSafeInteger(r.max) || r.max < ASK_RESPONDENTS_FLOOR)
350
+ invalid('respondents.max', `must be a whole number, at least ${ASK_RESPONDENTS_FLOOR}`);
351
+ for (const key of ['name', 'auto_complete'])
352
+ if (r[key] !== undefined && typeof r[key] !== 'boolean')
353
+ invalid(`respondents.${key}`, 'must be a boolean');
354
+ if (r.name === true && names.has(NAME_FIELD.name))
355
+ invalid('respondents.name', 'adds a field named "name"; rename the field that has it');
356
+ const expiresIn = lifetime(r.expires_in, 'respondents.expires_in');
357
+ const respondentExpiresIn = lifetime(r.respondent_expires_in, 'respondents.respondent_expires_in');
358
+ // Only what was given is sent: Sess applies the decision's defaults (no name field, the plan's
359
+ // lifetime, what remains of the Ask, auto-complete).
360
+ return {
361
+ respondents: { max: r.max, ...(r.name !== undefined ? { name: r.name } : {}) },
362
+ ...(expiresIn !== undefined ? { expires_in: expiresIn } : {}),
363
+ ...(respondentExpiresIn !== undefined ? { respondent_expires_in: respondentExpiresIn } : {}),
364
+ ...(r.auto_complete !== undefined ? { auto_complete: r.auto_complete } : {}),
365
+ };
366
+ }
367
+ /** Sess's "Your name" field, before the first field of round one (the runtime's own insertion). */
368
+ function withNameField(interaction) {
369
+ const components = interaction.source.components;
370
+ const at = components.findIndex((c) => c.type === 'field');
371
+ const next = [...components];
372
+ next.splice(at < 0 ? next.length : at, 0, {
373
+ type: 'field',
374
+ name: NAME_FIELD.name,
375
+ label: NAME_FIELD.label,
376
+ required: true,
377
+ schema: { type: 'string', minLength: 1, maxLength: NAME_FIELD.maxLength },
378
+ });
379
+ return { ...interaction, source: { ...interaction.source, components: next } };
380
+ }
284
381
  /**
285
382
  * Checks verified answer data against the compiled fields and returns a frozen copy in field
286
383
  * order. It follows the runtime decoding: a checkbox is always present, a multiple choice is
@@ -469,8 +566,129 @@ class Handle {
469
566
  return this.toJSON();
470
567
  }
471
568
  }
472
- /** Validates locally, creates once (the link is available before any wait) and returns the handle. */
473
- export async function ask(sessions, receipts, input, options = {}) {
569
+ /** At most this many respondents' receipts are verified at once during one read. */
570
+ const VERIFY_CONCURRENCY = 4;
571
+ class RespondentsHandle {
572
+ askId;
573
+ max;
574
+ expiresAt;
575
+ #link;
576
+ #asks;
577
+ #receipts;
578
+ #expectedWorkspaceId;
579
+ #fields;
580
+ #surface;
581
+ /** Answers already verified, by Session and event, with the exact accepted record they came from. */
582
+ #verified = new Map();
583
+ constructor(context) {
584
+ this.askId = context.created.id;
585
+ this.max = context.created.max;
586
+ this.expiresAt = context.created.action_expires_at;
587
+ this.#link = context.created.human_url;
588
+ this.#asks = context.asks;
589
+ this.#receipts = context.receipts;
590
+ this.#expectedWorkspaceId = context.expectedWorkspaceId;
591
+ this.#fields = context.compiled.fields;
592
+ // Each respondent's Session stores round one with its only response policy.
593
+ this.#surface = canonicalJson({ ...context.compiled.respondents.surface, response_policy: 'first' });
594
+ this.read = this.read.bind(this);
595
+ this.close = this.close.bind(this);
596
+ Object.freeze(this);
597
+ }
598
+ get link() {
599
+ return this.#link;
600
+ }
601
+ async read(options = {}) {
602
+ if (!options || typeof options !== 'object')
603
+ throw new SessError('configuration', 'read options must be an object.', { outcome: 'not_sent' });
604
+ const page = (await this.#asks.retrieve(this.askId, options)).data;
605
+ const signal = options.signal;
606
+ const respondents = new Array(page.sessions.length);
607
+ let next = 0;
608
+ const work = async () => {
609
+ while (next < page.sessions.length) {
610
+ const index = next++;
611
+ const record = page.sessions[index];
612
+ respondents[index] = Object.freeze({
613
+ sessionId: record.id,
614
+ status: record.status,
615
+ revision: record.revision,
616
+ startedAt: record.started_at,
617
+ completedAt: record.completed_at,
618
+ answer: await this.#answer(record, signal),
619
+ });
620
+ }
621
+ };
622
+ await Promise.all(Array.from({ length: Math.min(VERIFY_CONCURRENCY, page.sessions.length) }, work));
623
+ return Object.freeze({
624
+ ...summary(page),
625
+ respondents: Object.freeze(respondents),
626
+ nextCursor: page.next_cursor,
627
+ });
628
+ }
629
+ async close(options) {
630
+ return summary((await this.#asks.close(this.askId, options)).data);
631
+ }
632
+ /** A respondent's answer to round one, verified by its receipt and bound to this question. */
633
+ async #answer(record, signal) {
634
+ const accepted = record.status === 'purged' ? undefined : record.responses.find((r) => r.revision === 1);
635
+ if (!accepted)
636
+ return null;
637
+ const key = `${record.id}:${accepted.event_id}`;
638
+ const exact = canonicalJson(accepted);
639
+ const known = this.#verified.get(key);
640
+ if (known) {
641
+ if (known.record !== exact)
642
+ throw new SessError('receipt_verification', 'A respondent’s answer changed after it was verified.', {
643
+ code: 'RECORD_BINDING_MISMATCH',
644
+ sessionId: record.id,
645
+ });
646
+ return known.value;
647
+ }
648
+ const verified = await this.#receipts.verifyResponse({
649
+ sessionId: record.id,
650
+ response: accepted,
651
+ ...(this.#expectedWorkspaceId !== undefined
652
+ ? { expectedWorkspaceId: this.#expectedWorkspaceId }
653
+ : {}),
654
+ }, signal ? { signal } : {});
655
+ const response = verified.response;
656
+ if (response.event_id !== accepted.event_id ||
657
+ response.revision !== 1 ||
658
+ response.action_id !== 'submit' ||
659
+ verified.surface.id !== record.id ||
660
+ verified.surface.revision !== 1 ||
661
+ canonicalJson(verified.surface.interaction) !== this.#surface)
662
+ throw new SessError('receipt_verification', 'A respondent’s verified answer is not bound to this question.', {
663
+ code: 'RECORD_BINDING_MISMATCH',
664
+ sessionId: record.id,
665
+ });
666
+ const value = checkAnswer(this.#fields, response.data);
667
+ this.#verified.set(key, { record: exact, value });
668
+ return value;
669
+ }
670
+ /** The link is omitted from serialization and inspection. */
671
+ toJSON() {
672
+ return { askId: this.askId, max: this.max, expiresAt: this.expiresAt };
673
+ }
674
+ [inspect.custom]() {
675
+ return this.toJSON();
676
+ }
677
+ }
678
+ function summary(ask) {
679
+ return Object.freeze({
680
+ status: ask.status,
681
+ closedBy: ask.closed_by,
682
+ closedAt: ask.closed_at,
683
+ counts: Object.freeze({ ...ask.counts, refused: Object.freeze({ ...ask.counts.refused }) }),
684
+ });
685
+ }
686
+ /**
687
+ * Validates locally, creates once (the link is available before any wait) and returns the handle:
688
+ * one Session for one person, or with `respondents` one Ask for many.
689
+ */
690
+ export async function ask(context, input, options = {}) {
691
+ const { sessions, receipts } = context;
474
692
  const compiled = compileAsk(input);
475
693
  if (!options || typeof options !== 'object')
476
694
  throw new SessError('configuration', 'ask options must be an object.', { outcome: 'not_sent' });
@@ -480,6 +698,17 @@ export async function ask(sessions, receipts, input, options = {}) {
480
698
  throw new SessError('configuration', 'expectedWorkspaceId must be a trusted workspace identifier.', {
481
699
  outcome: 'not_sent',
482
700
  });
701
+ if (compiled.respondents) {
702
+ // One Ask, created once with the whole round one; an uncertain outcome is unknown_outcome.
703
+ const created = await context.createAsk({ interaction: compiled.interaction, ...compiled.respondents.body }, requestOptions);
704
+ return new RespondentsHandle({
705
+ created: created.data,
706
+ asks: context.asks,
707
+ receipts,
708
+ expectedWorkspaceId,
709
+ compiled,
710
+ });
711
+ }
483
712
  // Creation carries the whole interaction and is attempted once. An uncertain outcome surfaces as
484
713
  // the unknown_outcome error of the client and is never retried here.
485
714
  const created = await sessions.create({
package/dist/asks.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { Transport } from './transport.js';
2
+ import type { ApiResult, AskCloseResponse, AskResponse, CreateAskRequest, CreateAskResponse, RequestOptions } from './types.js';
3
+ /** The fewest respondents an Ask takes, and the shortest lifetime, in seconds (the ceilings are the plan's). */
4
+ export declare const ASK_RESPONDENTS_FLOOR = 2;
5
+ /** One page of an Ask read. */
6
+ export interface AskReadOptions extends RequestOptions {
7
+ /** The `next_cursor` of the page before. */
8
+ cursor?: string;
9
+ /** Respondents per page, 1–100 (default 100). */
10
+ limit?: number;
11
+ }
12
+ /** The query of one page; checked before the request is sent. */
13
+ export declare function pageQuery(options: AskReadOptions): Record<string, string> | undefined;
14
+ /**
15
+ * `POST /v1/asks`, attempted once: a lost reply may mean creation succeeded, and it is never
16
+ * retried here (an unused Ask reserves nothing, so creating again is safe). Internal: the one
17
+ * public way to create an Ask is `sess.ask({ ..., respondents })`; there is no second create verb.
18
+ */
19
+ export declare function createAsk(transport: Transport, body: CreateAskRequest, options?: RequestOptions): Promise<ApiResult<CreateAskResponse>>;
20
+ /**
21
+ * Advanced: read or close an Ask by its ID (`/v1/asks/{id}`), for example after a restart. The
22
+ * handle from `sess.ask({ ..., respondents })` has the same read and close, with typed, verified
23
+ * answers; prefer it.
24
+ */
25
+ export declare class Asks {
26
+ #private;
27
+ constructor(transport: Transport);
28
+ /**
29
+ * Reads an Ask: open or closed, its counts, and one page of respondents with their accepted
30
+ * answers. Returning an answer here is that respondent's retrieval, as a Session read is.
31
+ * The answers are not yet receipt-verified; the handle's `read()` verifies them.
32
+ */
33
+ retrieve(id: string, options?: AskReadOptions): Promise<ApiResult<AskResponse>>;
34
+ /**
35
+ * Closes an Ask now: no one new can start; respondents who have not answered have their links
36
+ * ended. Closing a closed Ask changes nothing, so this is safe to repeat.
37
+ */
38
+ close(id: string, options?: RequestOptions): Promise<ApiResult<AskCloseResponse>>;
39
+ }