@sess.si/sdk 0.1.0 → 0.2.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,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 — 2026-11-06
4
+
5
+ - A rating in `sess.ask`: a field `{ type: 'rating' }` asks for a whole number from 1 to `max`.
6
+ `max` is 2 to 10, default 5; the person sees stars up to 5 and numbered choices above. `low`
7
+ and `high` are optional words at the two ends, at most 24 characters each. The answer is the
8
+ number chosen. In the types for `sessions.create()` and `publish()`, a field takes
9
+ `rating: { low?, high? }` with the schema exactly `{ type: 'integer', minimum: 1, maximum: N }`,
10
+ N from 2 to 10.
11
+ - Respondents in `sess.ask`: add `respondents: { max }` and the same question goes to many people
12
+ through one link, a Sess Ask. Each person who starts gets their own page. The handle is
13
+ `{ askId, link, max, expiresAt, read(), close() }`. `read()` returns the Ask's status and
14
+ counts, and one page of respondents, each with their answer verified by its signed receipt and
15
+ typed by the fields. `close()` ends the Ask; those who answered keep their pages and receipts.
16
+ Advanced: `name`, `expires_in`, `respondent_expires_in` and `auto_complete` in `respondents`,
17
+ and `sess.asks.retrieve()` and `sess.asks.close()` to read or close an Ask by its ID (raw
18
+ records, not yet verified). Creation is attempted once and never retried. Without
19
+ `respondents`, `sess.ask` is unchanged.
20
+ - The runtime dependencies are unchanged. The default `User-Agent` names the new version.
21
+
22
+ ## 0.1.1 — 2026-11-04
23
+
24
+ - The npm package page only: `keywords`, and `homepage` now points at the docs quickstart. The API
25
+ is that of 0.1.0, unchanged, and so are the runtime dependencies. The default `User-Agent` names
26
+ the new version.
27
+
3
28
  ## 0.1.0 — 2026-10-31
4
29
 
5
30
  - The first stable release, published to the `latest` dist-tag. The API is that of
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.0
17
+ npm install --save-exact @sess.si/sdk@0.2.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,9 @@ async function askShort(question: string) {
120
120
  }
121
121
  ```
122
122
 
123
- **Release status:** `0.1.0` is the first stable release, served under the `latest` dist-tag.
124
- `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.2.0` is the current release, served under the `latest` dist-tag. It adds
124
+ the rating field and respondents to `sess.ask`. `next` stays at the last release candidate,
125
+ `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
126
 
127
127
  ## Commerce
128
128
 
@@ -242,10 +242,10 @@ exact Surface and input, and the issuer's public keys. Check it on your own comp
242
242
  trust (never the keys inside the bundle):
243
243
 
244
244
  ```sh
245
- npx -p @sess.si/sdk@0.1.0 sess verify bundle.json --issuer https://api.sess.si --keys sess-receipt-keys.json
245
+ npx -p @sess.si/sdk@0.2.0 sess verify bundle.json --issuer https://api.sess.si --keys sess-receipt-keys.json
246
246
  ```
247
247
 
248
- The `sess` command first ships in `0.1.0-rc.5`; any later version, `0.1.0` included, has it.
248
+ The `sess` command first ships in `0.1.0-rc.5`; any later version, `0.2.0` included, has it.
249
249
 
250
250
  You'll see `Valid decision bundle.` and what was accepted, when, on which revision; or `Invalid`
251
251
  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
+ }
package/dist/asks.js ADDED
@@ -0,0 +1,100 @@
1
+ import { SessError } from './errors.js';
2
+ import { Transport, pathSegment } from './transport.js';
3
+ import { decodeAsk, decodeAskClose, decodeAskCreate } from './internal/decode.js';
4
+ /** The fewest respondents an Ask takes, and the shortest lifetime, in seconds (the ceilings are the plan's). */
5
+ export const ASK_RESPONDENTS_FLOOR = 2;
6
+ const LIFETIME_FLOOR_SECONDS = 30;
7
+ function notSent(message) {
8
+ return new SessError('configuration', message, { outcome: 'not_sent' });
9
+ }
10
+ function seconds(value) {
11
+ return (value === undefined ||
12
+ (typeof value === 'number' && Number.isSafeInteger(value) && value >= LIFETIME_FLOOR_SECONDS));
13
+ }
14
+ /** The query of one page; checked before the request is sent. */
15
+ export function pageQuery(options) {
16
+ const { cursor, limit } = options;
17
+ if (cursor !== undefined && (typeof cursor !== 'string' || !/^[\x21-\x7e]{1,200}$/.test(cursor)))
18
+ throw notSent('cursor must be the next_cursor of the page before.');
19
+ if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1 || limit > 100))
20
+ throw notSent('limit must be a whole number from 1 to 100.');
21
+ if (cursor === undefined && limit === undefined)
22
+ return undefined;
23
+ return {
24
+ ...(cursor !== undefined ? { cursor } : {}),
25
+ ...(limit !== undefined ? { limit: String(limit) } : {}),
26
+ };
27
+ }
28
+ /**
29
+ * `POST /v1/asks`, attempted once: a lost reply may mean creation succeeded, and it is never
30
+ * retried here (an unused Ask reserves nothing, so creating again is safe). Internal: the one
31
+ * public way to create an Ask is `sess.ask({ ..., respondents })`; there is no second create verb.
32
+ */
33
+ export function createAsk(transport, body, options = {}) {
34
+ if ('idempotencyKey' in options || 'ifMatch' in options)
35
+ return Promise.reject(notSent('Ask creation does not support idempotency keys or If-Match.'));
36
+ const max = body.respondents.max;
37
+ if (!Number.isSafeInteger(max) || max < ASK_RESPONDENTS_FLOOR)
38
+ return Promise.reject(notSent(`respondents.max must be a whole number, at least ${ASK_RESPONDENTS_FLOOR}.`));
39
+ for (const key of ['expires_in', 'respondent_expires_in'])
40
+ if (!seconds(body[key]))
41
+ return Promise.reject(notSent(`${key} must be a whole number of seconds, at least 30.`));
42
+ return transport.request({
43
+ name: 'asks.create',
44
+ method: 'POST',
45
+ path: '/v1/asks',
46
+ body,
47
+ status: 201,
48
+ retry: 'never',
49
+ parse: (value) => decodeAskCreate(value, transport.allowInsecureLocalhost),
50
+ }, options);
51
+ }
52
+ /**
53
+ * Advanced: read or close an Ask by its ID (`/v1/asks/{id}`), for example after a restart. The
54
+ * handle from `sess.ask({ ..., respondents })` has the same read and close, with typed, verified
55
+ * answers; prefer it.
56
+ */
57
+ export class Asks {
58
+ #transport;
59
+ constructor(transport) {
60
+ this.#transport = transport;
61
+ }
62
+ /**
63
+ * Reads an Ask: open or closed, its counts, and one page of respondents with their accepted
64
+ * answers. Returning an answer here is that respondent's retrieval, as a Session read is.
65
+ * The answers are not yet receipt-verified; the handle's `read()` verifies them.
66
+ */
67
+ retrieve(id, options = {}) {
68
+ const { cursor: _cursor, limit: _limit, ...requestOptions } = options;
69
+ let query;
70
+ try {
71
+ query = pageQuery(options);
72
+ }
73
+ catch (error) {
74
+ return Promise.reject(error);
75
+ }
76
+ return this.#transport.request({
77
+ name: 'asks.retrieve',
78
+ method: 'GET',
79
+ path: `/v1/asks/${pathSegment(id)}`,
80
+ ...(query ? { query } : {}),
81
+ status: 200,
82
+ retry: 'safe',
83
+ parse: (value) => decodeAsk(value, id),
84
+ }, requestOptions);
85
+ }
86
+ /**
87
+ * Closes an Ask now: no one new can start; respondents who have not answered have their links
88
+ * ended. Closing a closed Ask changes nothing, so this is safe to repeat.
89
+ */
90
+ close(id, options) {
91
+ return this.#transport.request({
92
+ name: 'asks.close',
93
+ method: 'POST',
94
+ path: `/v1/asks/${pathSegment(id)}/close`,
95
+ status: 200,
96
+ retry: 'safe',
97
+ parse: (value) => decodeAskClose(value, id),
98
+ }, options);
99
+ }
100
+ }
package/dist/client.d.ts CHANGED
@@ -1,14 +1,24 @@
1
1
  import type { SessOptions } from './types.js';
2
2
  import { Sessions } from './sessions.js';
3
+ import { Asks } from './asks.js';
3
4
  import { WebhookResource } from './webhook-resource.js';
4
5
  import { createReceiptResource } from './receipts/resource.js';
5
- import { type AskAnswer, type AskField, type AskHandle, type AskInput, type AskOptions } from './ask.js';
6
+ import { type AskAnswer, type AskField, type AskHandle, type AskInput, type AskOptions, type AskRespondents, type AskRespondentsAnswer, type AskRespondentsHandle, type AskRespondentsInput } from './ask.js';
6
7
  /** Server-side client. Construction has no network or installation side effects. */
7
8
  export declare class Sess {
9
+ #private;
8
10
  readonly sessions: Sessions;
9
11
  readonly webhooks: WebhookResource;
10
12
  readonly receipts: ReturnType<typeof createReceiptResource>;
13
+ /** Advanced: read or close an Ask by its ID. Create one with `sess.ask({ ..., respondents })`. */
14
+ readonly asks: Asks;
11
15
  constructor(options: SessOptions);
16
+ /**
17
+ * Asks many people one question through one link: with `respondents`, Sess creates an Ask, and
18
+ * each person who starts gets their own page. The handle carries the link to share before any
19
+ * wait; `read()` returns each respondent's verified, typed answer and `close()` ends it.
20
+ */
21
+ ask<const F extends readonly AskField[], const R extends AskRespondents>(input: AskRespondentsInput<F, R>, options?: AskOptions): Promise<AskRespondentsHandle<AskRespondentsAnswer<F, R>>>;
12
22
  /**
13
23
  * Asks one question with simple typed fields. Invalid input fails before credential lookup or
14
24
  * network access. The Session is created once with the whole interaction, and the returned
package/dist/client.js CHANGED
@@ -1,16 +1,21 @@
1
1
  import { Transport } from './transport.js';
2
2
  import { Sessions } from './sessions.js';
3
+ import { Asks, createAsk } from './asks.js';
3
4
  import { WebhookResource } from './webhook-resource.js';
4
5
  import { createReceiptResource } from './receipts/resource.js';
5
- import { ask } from './ask.js';
6
+ import { ask, } from './ask.js';
6
7
  /** Server-side client. Construction has no network or installation side effects. */
7
8
  export class Sess {
8
9
  sessions;
9
10
  webhooks;
10
11
  receipts;
12
+ /** Advanced: read or close an Ask by its ID. Create one with `sess.ask({ ..., respondents })`. */
13
+ asks;
14
+ #ask;
11
15
  constructor(options) {
12
16
  const transport = new Transport(options);
13
17
  this.sessions = new Sessions(transport);
18
+ this.asks = new Asks(transport);
14
19
  this.webhooks = new WebhookResource(transport);
15
20
  this.receipts = createReceiptResource({
16
21
  baseUrl: transport.baseUrl,
@@ -29,15 +34,15 @@ export class Sess {
29
34
  parse: (value) => value,
30
35
  }, requestOptions),
31
36
  });
37
+ this.#ask = {
38
+ sessions: this.sessions,
39
+ receipts: this.receipts,
40
+ asks: this.asks,
41
+ createAsk: (body, requestOptions) => createAsk(transport, body, requestOptions),
42
+ };
32
43
  Object.freeze(this);
33
44
  }
34
- /**
35
- * Asks one question with simple typed fields. Invalid input fails before credential lookup or
36
- * network access. The Session is created once with the whole interaction, and the returned
37
- * handle carries the private link before any wait. `answer()` verifies the answer, checks that it
38
- * is still current, completes the Session and returns the typed values.
39
- */
40
45
  ask(input, options) {
41
- return ask(this.sessions, this.receipts, input, options);
46
+ return ask(this.#ask, input, options);
42
47
  }
43
48
  }
package/dist/index.d.ts CHANGED
@@ -2,6 +2,8 @@ export { Sess } from './client.js';
2
2
  export { SessError } from './errors.js';
3
3
  export type { SessErrorKind, SessErrorDetails, WriteOutcome } from './errors.js';
4
4
  export type { AskAnswer, AskAnswerOptions, AskField, AskHandle, AskInput, AskOptions } from './ask.js';
5
+ export type { AskClosed, AskRead, AskRespondent, AskRespondents, AskRespondentsAnswer, AskRespondentsHandle, AskRespondentsInput, } from './ask.js';
6
+ export type { AskReadOptions, Asks } from './asks.js';
5
7
  export * from './types.js';
6
8
  export { ITEMS_DEFAULT_LABELS, ITEMS_LIMITS, items, money } from './commerce/items.js';
7
9
  export type { Amount, ItemLineInput, ItemPaymentInput, ItemRowInput, ItemsInput, Money, } from './commerce/items.js';
@@ -1,4 +1,4 @@
1
- import type { AcceptedResponse, CreateSessionResponse, Deliveries, Session, SessionEvents, SurfaceRevision, WebhookRegisterResponse, WebhookResponse, WebhookRotateResponse, WebhookVerifyResponse, RedeliverResponse } from '../types.js';
1
+ import type { AcceptedResponse, AskCloseResponse, AskResponse, CreateAskResponse, CreateSessionResponse, Deliveries, Session, SessionEvents, SurfaceRevision, WebhookRegisterResponse, WebhookResponse, WebhookRotateResponse, WebhookVerifyResponse, RedeliverResponse } from '../types.js';
2
2
  export declare const ulid = "[0-9A-HJKMNP-TV-Z]{26}";
3
3
  export declare const sessionPattern: RegExp;
4
4
  export declare function protocol(): never;
@@ -8,6 +8,13 @@ export declare function integer(value: unknown, minimum?: number): number;
8
8
  /** Keeps all additive JSON fields intact; this is a boundary decoder, not normalization. */
9
9
  export declare function decodeAccepted(value: unknown): AcceptedResponse;
10
10
  export declare function decodeCreate(value: unknown, allowInsecureLocalhost?: boolean): CreateSessionResponse;
11
+ export declare const askPattern: RegExp;
12
+ /** `POST /v1/asks`: the Ask's id, round one, its one link, its deadline and cap. */
13
+ export declare function decodeAskCreate(value: unknown, allowInsecureLocalhost?: boolean): CreateAskResponse;
14
+ /** `POST /v1/asks/{id}/close`: the Ask after the close, without respondents. */
15
+ export declare function decodeAskClose(value: unknown, expectedId: string): AskCloseResponse;
16
+ /** `GET /v1/asks/{id}`: one page of respondents; each answer is an ordinary accepted response. */
17
+ export declare function decodeAsk(value: unknown, expectedId: string): AskResponse;
11
18
  export declare function isLoopback(host: string): boolean;
12
19
  export declare function decodeSession(value: unknown, expectedId: string): Session;
13
20
  export declare function decodeSurface(value: unknown, expectedId: string, revision: number): SurfaceRevision;
@@ -124,7 +124,12 @@ export function decodeCreate(value, allowInsecureLocalhost = false) {
124
124
  // The link's expiry; checked when present (a runtime before the link-lifetime slice omits it).
125
125
  if (v.action_expires_at !== undefined)
126
126
  date(v.action_expires_at);
127
- const text = string(v.human_url, /^[^\s\u0000-\u001f\u007f]+$/, 4096);
127
+ humanLink(v.human_url, allowInsecureLocalhost);
128
+ return value;
129
+ }
130
+ /** A human link: absolute HTTPS (HTTP only on explicit loopback), no credentials, query or fragment. */
131
+ function humanLink(value, allowInsecureLocalhost) {
132
+ const text = string(value, /^[^\s\u0000-\u001f\u007f]+$/, 4096);
128
133
  let url;
129
134
  try {
130
135
  url = new URL(text);
@@ -139,6 +144,75 @@ export function decodeCreate(value, allowInsecureLocalhost = false) {
139
144
  !(url.protocol === 'https:' ||
140
145
  (allowInsecureLocalhost && url.protocol === 'http:' && isLoopback(url.hostname))))
141
146
  protocol();
147
+ }
148
+ export const askPattern = new RegExp(`^ask_${ulid}$`);
149
+ const ASK_REFUSALS = ['full', 'closed', 'deadline', 'minimum_time', 'burst', 'paused', 'network'];
150
+ /** `POST /v1/asks`: the Ask's id, round one, its one link, its deadline and cap. */
151
+ export function decodeAskCreate(value, allowInsecureLocalhost = false) {
152
+ const v = object(value);
153
+ string(v.id, askPattern);
154
+ if (integer(v.revision) !== 1)
155
+ protocol();
156
+ humanLink(v.human_url, allowInsecureLocalhost);
157
+ date(v.action_expires_at);
158
+ integer(v.max);
159
+ return value;
160
+ }
161
+ function askSummary(v, expectedId) {
162
+ if (string(v.id, askPattern) !== expectedId)
163
+ protocol();
164
+ oneOf(v.status, ['open', 'closed']);
165
+ if (v.status === 'open' ? v.closed_by !== null || v.closed_at !== null : v.closed_by === null)
166
+ protocol();
167
+ if (v.closed_by !== null)
168
+ oneOf(v.closed_by, ['max', 'owner', 'deadline']);
169
+ nullableDate(v.closed_at);
170
+ integer(v.max);
171
+ date(v.action_expires_at);
172
+ if (typeof v.auto_complete !== 'boolean')
173
+ protocol();
174
+ const counts = object(v.counts);
175
+ for (const key of ['started', 'answered', 'completed'])
176
+ integer(counts[key], 0);
177
+ const refused = object(counts.refused);
178
+ for (const key of ASK_REFUSALS)
179
+ integer(refused[key], 0);
180
+ }
181
+ /** `POST /v1/asks/{id}/close`: the Ask after the close, without respondents. */
182
+ export function decodeAskClose(value, expectedId) {
183
+ const v = object(value);
184
+ askSummary(v, expectedId);
185
+ if ('sessions' in v)
186
+ protocol();
187
+ return value;
188
+ }
189
+ /** `GET /v1/asks/{id}`: one page of respondents; each answer is an ordinary accepted response. */
190
+ export function decodeAsk(value, expectedId) {
191
+ const v = object(value);
192
+ askSummary(v, expectedId);
193
+ const seen = new Set();
194
+ for (const item of array(v.sessions)) {
195
+ const s = object(item);
196
+ const id = string(s.id, sessionPattern);
197
+ if (seen.has(id))
198
+ protocol();
199
+ seen.add(id);
200
+ oneOf(s.status, ['active', 'responded', 'completed', 'purged']);
201
+ const revision = integer(s.revision);
202
+ date(s.started_at);
203
+ nullableDate(s.completed_at);
204
+ const revisions = new Set();
205
+ for (const response of array(s.responses)) {
206
+ const r = decodeAccepted(response);
207
+ if (r.revision > revision || revisions.has(r.revision))
208
+ protocol();
209
+ revisions.add(r.revision);
210
+ }
211
+ if (s.status === 'purged' && revisions.size)
212
+ protocol();
213
+ }
214
+ if (v.next_cursor !== null)
215
+ string(v.next_cursor, undefined, 200);
142
216
  return value;
143
217
  }
144
218
  export function isLoopback(host) {
@@ -1,2 +1,2 @@
1
1
  /** This package's version, sent in the User-Agent header. Tests check it against package.json. */
2
- export declare const SDK_VERSION = "0.1.0";
2
+ export declare const SDK_VERSION = "0.2.0";
@@ -1,2 +1,2 @@
1
1
  /** This package's version, sent in the User-Agent header. Tests check it against package.json. */
2
- export const SDK_VERSION = '0.1.0';
2
+ export const SDK_VERSION = '0.2.0';
@@ -3,6 +3,8 @@ export interface Operation<T> {
3
3
  name: string;
4
4
  method: 'GET' | 'POST' | 'PATCH' | 'PUT';
5
5
  path: string;
6
+ /** Query parameters, encoded here; the path itself never carries a query. */
7
+ query?: Readonly<Record<string, string>>;
6
8
  status: number;
7
9
  parse?: (value: unknown) => T;
8
10
  body?: unknown;
package/dist/transport.js CHANGED
@@ -4,6 +4,9 @@ import { isLoopback } from './internal/decode.js';
4
4
  import { serializeBody } from './internal/json.js';
5
5
  import { abortError, boundedNumber, deadline, delay, withSignal } from './internal/time.js';
6
6
  import { SDK_VERSION } from './internal/version.js';
7
+ /** Creations, attempted once: an uncertain outcome is `unknown_outcome` and is never retried here. */
8
+ const CREATES = new Set(['sessions.create', 'asks.create']);
9
+ const ASK_CREATE_UNKNOWN = 'Ask creation may have succeeded. It was not retried automatically; an unused Ask reserves nothing, so you may create it again.';
7
10
  const transientStatuses = new Set([408, 429, 500, 502, 503, 504]);
8
11
  const rejections = {
9
12
  400: ['INVALID_SCHEMA', 'UNKNOWN_COMPONENT', 'WEBHOOK_INVALID_URL'],
@@ -253,6 +256,8 @@ export class Transport {
253
256
  op.path.includes('#') ||
254
257
  op.path.includes('?'))
255
258
  throw new SessError('configuration', 'Invalid API resource path.', { outcome: 'not_sent' });
259
+ const query = op.query === undefined ? '' : new URLSearchParams({ ...op.query }).toString();
260
+ const search = query ? `?${query}` : '';
256
261
  const headers = { Accept: 'application/json', 'User-Agent': this.#userAgent };
257
262
  if (body !== undefined)
258
263
  headers['Content-Type'] = 'application/json';
@@ -305,7 +310,7 @@ export class Transport {
305
310
  try {
306
311
  dispatched = true;
307
312
  const pendingResponse = Promise.resolve()
308
- .then(() => this.#fetch(`${this.baseUrl}${op.path}`, {
313
+ .then(() => this.#fetch(`${this.baseUrl}${op.path}${search}`, {
309
314
  method: op.method,
310
315
  headers: { ...headers },
311
316
  ...(body !== undefined ? { body } : {}),
@@ -446,8 +451,11 @@ export class Transport {
446
451
  outcome,
447
452
  idempotencyKey,
448
453
  };
449
- error = new SessError(op.name === 'sessions.create' && outcome === 'unknown' ? 'unknown_outcome' : error.kind, op.name === 'sessions.create' && outcome === 'unknown'
450
- ? 'Session creation may have succeeded. Do not automatically create again; inspect recovery information if available.'
454
+ const uncertainCreate = CREATES.has(op.name) && outcome === 'unknown';
455
+ error = new SessError(uncertainCreate ? 'unknown_outcome' : error.kind, uncertainCreate
456
+ ? op.name === 'asks.create'
457
+ ? ASK_CREATE_UNKNOWN
458
+ : 'Session creation may have succeeded. Do not automatically create again; inspect recovery information if available.'
451
459
  : error.message, details);
452
460
  if (recoveryBody)
453
461
  attachRecovery(error, recoveryBody);
@@ -475,8 +483,10 @@ export class Transport {
475
483
  });
476
484
  if (e.operation)
477
485
  throw e;
478
- throw new SessError(op.name === 'sessions.create' && dispatched ? 'unknown_outcome' : e.kind, op.name === 'sessions.create' && dispatched
479
- ? 'Session creation may have succeeded. Do not automatically create again.'
486
+ throw new SessError(CREATES.has(op.name) && dispatched ? 'unknown_outcome' : e.kind, CREATES.has(op.name) && dispatched
487
+ ? op.name === 'asks.create'
488
+ ? ASK_CREATE_UNKNOWN
489
+ : 'Session creation may have succeeded. Do not automatically create again.'
480
490
  : e.message, {
481
491
  code: e.code,
482
492
  reason: e.reason,
package/dist/types.d.ts CHANGED
@@ -148,6 +148,15 @@ export type SurfaceComponent = (Component<'heading'> & {
148
148
  option_labels?: {
149
149
  [key: string]: string;
150
150
  };
151
+ /**
152
+ * A rating: with it the schema must be exactly `{ type: 'integer', minimum: 1, maximum: N }`,
153
+ * N from 2 to 10 (stars up to 5, numbered choices above; the answer is the integer).
154
+ * `low` and `high` are optional words at the two ends: a word or two; at most 24 each.
155
+ */
156
+ rating?: {
157
+ low?: string;
158
+ high?: string;
159
+ };
151
160
  schema: FieldSchema;
152
161
  }) | ItemsComponent;
153
162
  type DocumentedAction = RawPublishSessionRequest['interaction']['actions'][number] & {
@@ -197,6 +206,77 @@ export type CreateSessionRequest = {
197
206
  export type PublishSessionRequest = {
198
207
  interaction: InteractiveInteraction;
199
208
  };
209
+ /** `POST /v1/asks`: round one as an interactive create takes it, plus the respondents. */
210
+ export interface CreateAskRequest {
211
+ interaction: InteractiveInteraction;
212
+ respondents: {
213
+ /**
214
+ * How many people may start: at least 2, at most the plan's active-Session limit (Free 25,
215
+ * Starter 50, Pro 100; a trial Ask 2). Exact: it is checked when a person starts.
216
+ */
217
+ max: number;
218
+ /** Advanced: one required "Your name" text field, named `name`, before the first field. Default false. */
219
+ name?: boolean;
220
+ };
221
+ /** Advanced: the one deadline, whole seconds from creation, 30 up to the plan's link lifetime. Absent: that lifetime. */
222
+ expires_in?: number;
223
+ /** Advanced: each respondent's link life from their Start, at least 30 seconds, clamped to what remains. Absent: what remains of the Ask. */
224
+ respondent_expires_in?: number;
225
+ /** Advanced: default true, a respondent's Session completes when its answer is accepted. */
226
+ auto_complete?: boolean;
227
+ }
228
+ export interface CreateAskResponse {
229
+ id: string;
230
+ revision: number;
231
+ /** The link to share with everyone who should answer. Returned once; keep it out of logs. */
232
+ human_url: string;
233
+ /** The Ask's deadline (ISO 8601): from it no one new may start. */
234
+ action_expires_at: string;
235
+ max: number;
236
+ }
237
+ /** Derived at read time: Starts admitted, respondents answered and completed, Starts refused by reason. */
238
+ export interface AskCounts {
239
+ started: number;
240
+ answered: number;
241
+ completed: number;
242
+ refused: {
243
+ full: number;
244
+ closed: number;
245
+ deadline: number;
246
+ minimum_time: number;
247
+ burst: number;
248
+ paused: number;
249
+ network: number;
250
+ };
251
+ }
252
+ /** One respondent as `GET /v1/asks/{id}` lists it: an ordinary Session, or its tombstone once purged. */
253
+ export interface AskRespondentRecord {
254
+ id: string;
255
+ status: 'active' | 'responded' | 'completed' | 'purged';
256
+ revision: number;
257
+ started_at: string;
258
+ completed_at: string | null;
259
+ /** Every accepted answer, in order (none for a tombstone). */
260
+ responses: AcceptedResponse[];
261
+ }
262
+ /** `POST /v1/asks/{id}/close`: the Ask after the close (no answers). */
263
+ export interface AskCloseResponse {
264
+ id: string;
265
+ status: 'open' | 'closed';
266
+ /** Which closed it: `max` (the last place was started), `owner` (you) or `deadline`. Null while open. */
267
+ closed_by: 'max' | 'owner' | 'deadline' | null;
268
+ closed_at: string | null;
269
+ max: number;
270
+ action_expires_at: string;
271
+ auto_complete: boolean;
272
+ counts: AskCounts;
273
+ }
274
+ /** `GET /v1/asks/{id}`: one page of respondents in Start order. */
275
+ export interface AskResponse extends AskCloseResponse {
276
+ sessions: AskRespondentRecord[];
277
+ /** Pass as `cursor` to read the next page; null on the last page. */
278
+ next_cursor: string | null;
279
+ }
200
280
  export interface ResponseMeta {
201
281
  status: number;
202
282
  requestId?: string;
package/package.json CHANGED
@@ -1,9 +1,19 @@
1
1
  {
2
2
  "name": "@sess.si/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Ask a person from your server and continue with their verified answer. Sess API client with receipt and webhook verification.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
7
+ "keywords": [
8
+ "mcp",
9
+ "agent",
10
+ "human-in-the-loop",
11
+ "approval",
12
+ "form",
13
+ "receipt",
14
+ "claude",
15
+ "openai"
16
+ ],
7
17
  "repository": {
8
18
  "type": "git",
9
19
  "url": "git+https://github.com/w1991e/sess-sdk.git"
@@ -11,7 +21,7 @@
11
21
  "bugs": {
12
22
  "url": "https://github.com/w1991e/sess-sdk/issues"
13
23
  },
14
- "homepage": "https://github.com/w1991e/sess-sdk#readme",
24
+ "homepage": "https://docs.sess.si/quickstart/",
15
25
  "engines": {
16
26
  "node": ">=22.14.0"
17
27
  },