@sess.si/sdk 0.0.0-stage → 0.1.0-rc.10

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.
Files changed (65) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +27 -0
  4. package/README.md +327 -2
  5. package/dist/ask.d.ts +161 -0
  6. package/dist/ask.js +499 -0
  7. package/dist/cli/main.d.ts +2 -0
  8. package/dist/cli/main.js +7 -0
  9. package/dist/cli/verify.d.ts +13 -0
  10. package/dist/cli/verify.js +322 -0
  11. package/dist/client.d.ts +19 -0
  12. package/dist/client.js +43 -0
  13. package/dist/commerce/builders.d.ts +99 -0
  14. package/dist/commerce/builders.js +208 -0
  15. package/dist/commerce/currency.d.ts +4 -0
  16. package/dist/commerce/currency.js +25 -0
  17. package/dist/commerce/items.d.ts +119 -0
  18. package/dist/commerce/items.js +280 -0
  19. package/dist/commerce/lint.d.ts +16 -0
  20. package/dist/commerce/lint.js +56 -0
  21. package/dist/errors.d.ts +61 -0
  22. package/dist/errors.js +63 -0
  23. package/dist/generated/openapi.d.ts +8360 -0
  24. package/dist/generated/openapi.js +1 -0
  25. package/dist/index.d.ts +11 -0
  26. package/dist/index.js +6 -0
  27. package/dist/internal/decode.d.ts +20 -0
  28. package/dist/internal/decode.js +380 -0
  29. package/dist/internal/json.d.ts +3 -0
  30. package/dist/internal/json.js +74 -0
  31. package/dist/internal/time.d.ts +10 -0
  32. package/dist/internal/time.js +70 -0
  33. package/dist/internal/version.d.ts +2 -0
  34. package/dist/internal/version.js +2 -0
  35. package/dist/polling.d.ts +11 -0
  36. package/dist/polling.js +137 -0
  37. package/dist/qr/encoder.d.ts +10 -0
  38. package/dist/qr/encoder.js +343 -0
  39. package/dist/qr/index.d.ts +55 -0
  40. package/dist/qr/index.js +150 -0
  41. package/dist/receipts/bundle.d.ts +123 -0
  42. package/dist/receipts/bundle.js +423 -0
  43. package/dist/receipts/index.d.ts +8 -0
  44. package/dist/receipts/index.js +3 -0
  45. package/dist/receipts/json.d.ts +21 -0
  46. package/dist/receipts/json.js +151 -0
  47. package/dist/receipts/key-cache.d.ts +27 -0
  48. package/dist/receipts/key-cache.js +109 -0
  49. package/dist/receipts/renderers.d.ts +57 -0
  50. package/dist/receipts/renderers.js +153 -0
  51. package/dist/receipts/resource.d.ts +38 -0
  52. package/dist/receipts/resource.js +145 -0
  53. package/dist/receipts/verify.d.ts +112 -0
  54. package/dist/receipts/verify.js +339 -0
  55. package/dist/sessions.d.ts +18 -0
  56. package/dist/sessions.js +151 -0
  57. package/dist/transport.d.ts +30 -0
  58. package/dist/transport.js +511 -0
  59. package/dist/types.d.ts +283 -0
  60. package/dist/types.js +8 -0
  61. package/dist/webhook-resource.d.ts +12 -0
  62. package/dist/webhook-resource.js +51 -0
  63. package/dist/webhooks/index.d.ts +21 -0
  64. package/dist/webhooks/index.js +183 -0
  65. package/package.json +82 -4
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ export { Sess } from './client.js';
2
+ export { SessError } from './errors.js';
3
+ export type { SessErrorKind, SessErrorDetails, WriteOutcome } from './errors.js';
4
+ export type { AskAnswer, AskAnswerOptions, AskField, AskHandle, AskInput, AskOptions } from './ask.js';
5
+ export * from './types.js';
6
+ export { ITEMS_DEFAULT_LABELS, ITEMS_LIMITS, items, money } from './commerce/items.js';
7
+ export type { Amount, ItemLineInput, ItemPaymentInput, ItemRowInput, ItemsInput, Money, } from './commerce/items.js';
8
+ export { COMMERCE_DEFAULTS, invoice, purchaseOrder, quote, receipt, refund } from './commerce/builders.js';
9
+ export type { BillInput, RefundInput } from './commerce/builders.js';
10
+ export { lintText } from './commerce/lint.js';
11
+ export type { TextLintFinding } from './commerce/lint.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { Sess } from './client.js';
2
+ export { SessError } from './errors.js';
3
+ export * from './types.js';
4
+ export { ITEMS_DEFAULT_LABELS, ITEMS_LIMITS, items, money } from './commerce/items.js';
5
+ export { COMMERCE_DEFAULTS, invoice, purchaseOrder, quote, receipt, refund } from './commerce/builders.js';
6
+ export { lintText } from './commerce/lint.js';
@@ -0,0 +1,20 @@
1
+ import type { AcceptedResponse, CreateSessionResponse, Deliveries, Session, SessionEvents, SurfaceRevision, WebhookRegisterResponse, WebhookResponse, WebhookRotateResponse, WebhookVerifyResponse, RedeliverResponse } from '../types.js';
2
+ export declare const ulid = "[0-9A-HJKMNP-TV-Z]{26}";
3
+ export declare const sessionPattern: RegExp;
4
+ export declare function protocol(): never;
5
+ export declare function object(value: unknown): Record<string, unknown>;
6
+ export declare function string(value: unknown, pattern?: RegExp, max?: number): string;
7
+ export declare function integer(value: unknown, minimum?: number): number;
8
+ /** Keeps all additive JSON fields intact; this is a boundary decoder, not normalization. */
9
+ export declare function decodeAccepted(value: unknown): AcceptedResponse;
10
+ export declare function decodeCreate(value: unknown, allowInsecureLocalhost?: boolean): CreateSessionResponse;
11
+ export declare function isLoopback(host: string): boolean;
12
+ export declare function decodeSession(value: unknown, expectedId: string): Session;
13
+ export declare function decodeSurface(value: unknown, expectedId: string, revision: number): SurfaceRevision;
14
+ export declare function decodeEvents(value: unknown, expectedId: string): SessionEvents;
15
+ export declare function decodeWebhookRegister(value: unknown): WebhookRegisterResponse;
16
+ export declare function decodeWebhookVerify(value: unknown): WebhookVerifyResponse;
17
+ export declare function decodeWebhook(value: unknown): WebhookResponse;
18
+ export declare function decodeWebhookRotate(value: unknown): WebhookRotateResponse;
19
+ export declare function decodeDeliveries(value: unknown, expectedId: string): Deliveries;
20
+ export declare function decodeRedelivery(value: unknown, expectedEvent: string): RedeliverResponse;
@@ -0,0 +1,380 @@
1
+ import { SessError } from '../errors.js';
2
+ export const ulid = '[0-9A-HJKMNP-TV-Z]{26}';
3
+ export const sessionPattern = new RegExp(`^ses_${ulid}$`);
4
+ const eventPattern = new RegExp(`^evt_${ulid}$`);
5
+ const actionPattern = /^[a-z][a-z0-9_]{0,31}$/;
6
+ const receiptPattern = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
7
+ export function protocol() {
8
+ throw new SessError('protocol', 'The response does not match the Sess API this SDK supports.', {
9
+ code: 'INVALID_RESPONSE',
10
+ });
11
+ }
12
+ export function object(value) {
13
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
14
+ protocol();
15
+ return value;
16
+ }
17
+ export function string(value, pattern, max = 4096) {
18
+ // The wire contract uses Unicode code points, independently of UTF-8 body caps.
19
+ if (typeof value !== 'string' ||
20
+ !value.length ||
21
+ [...value].length > max ||
22
+ (pattern && !pattern.test(value)))
23
+ protocol();
24
+ return value;
25
+ }
26
+ export function integer(value, minimum = 1) {
27
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < minimum)
28
+ protocol();
29
+ return value;
30
+ }
31
+ function date(value) {
32
+ const text = string(value, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/, 32);
33
+ if (!Number.isFinite(Date.parse(text)))
34
+ protocol();
35
+ }
36
+ function nullableDate(value) {
37
+ if (value !== null)
38
+ date(value);
39
+ }
40
+ function array(value) {
41
+ if (!Array.isArray(value))
42
+ protocol();
43
+ return value;
44
+ }
45
+ function oneOf(value, values) {
46
+ if (typeof value !== 'string' || !values.includes(value))
47
+ protocol();
48
+ }
49
+ function receipt(value) {
50
+ if (value !== null)
51
+ string(value, receiptPattern, 65536);
52
+ }
53
+ function interaction(value, mode) {
54
+ const v = object(value);
55
+ if (v.mode !== mode)
56
+ protocol();
57
+ string(v.title, undefined, 200);
58
+ if (v.description !== undefined && typeof v.description !== 'string')
59
+ protocol();
60
+ const source = object(v.source);
61
+ if (mode === 'display') {
62
+ if (source.kind !== 'data')
63
+ protocol();
64
+ object(source.data);
65
+ return;
66
+ }
67
+ if (source.kind !== 'sess_surface' || v.response_policy !== 'first')
68
+ protocol();
69
+ for (const item of array(source.components)) {
70
+ const c = object(item);
71
+ oneOf(c.type, ['heading', 'text', 'record', 'field', 'items']);
72
+ if (c.type === 'heading')
73
+ string(c.text, undefined, 200);
74
+ if (c.type === 'text')
75
+ string(c.text, undefined, 4000);
76
+ if (c.type === 'record')
77
+ object(c.fields);
78
+ if (c.type === 'field') {
79
+ string(c.name, /^[a-z][a-z0-9_]{0,63}$/);
80
+ string(c.label, undefined, 200);
81
+ oneOf(object(c.schema).type, ['string', 'number', 'integer', 'boolean', 'array']);
82
+ }
83
+ // Commerce: line items in one ISO 4217 currency (Sess checks rows and totals on create).
84
+ if (c.type === 'items') {
85
+ string(c.currency, /^[A-Z]{3}$/, 3);
86
+ if (!array(c.rows).length)
87
+ protocol();
88
+ if (c.totals !== undefined)
89
+ array(c.totals);
90
+ }
91
+ }
92
+ const seen = new Set();
93
+ for (const item of array(v.actions)) {
94
+ const a = object(item);
95
+ const id = string(a.id, actionPattern);
96
+ if (seen.has(id))
97
+ protocol();
98
+ seen.add(id);
99
+ string(a.label, undefined, 200);
100
+ if (a.intent !== undefined)
101
+ oneOf(a.intent, ['submit', 'continue', 'approve', 'reject', 'request_change']);
102
+ }
103
+ if (!seen.size)
104
+ protocol();
105
+ }
106
+ /** Keeps all additive JSON fields intact; this is a boundary decoder, not normalization. */
107
+ export function decodeAccepted(value) {
108
+ const v = object(value);
109
+ string(v.event_id, eventPattern);
110
+ integer(v.sequence);
111
+ integer(v.revision);
112
+ string(v.action_id, actionPattern);
113
+ object(v.data);
114
+ if (object(v.actor).assurance !== 'link_holder')
115
+ protocol();
116
+ date(v.accepted_at);
117
+ receipt(v.receipt);
118
+ return value;
119
+ }
120
+ export function decodeCreate(value, allowInsecureLocalhost = false) {
121
+ const v = object(value);
122
+ string(v.id, sessionPattern);
123
+ integer(v.revision);
124
+ // The link's expiry; checked when present (a runtime before the link-lifetime slice omits it).
125
+ if (v.action_expires_at !== undefined)
126
+ date(v.action_expires_at);
127
+ const text = string(v.human_url, /^[^\s\u0000-\u001f\u007f]+$/, 4096);
128
+ let url;
129
+ try {
130
+ url = new URL(text);
131
+ }
132
+ catch {
133
+ return protocol();
134
+ }
135
+ if (url.username ||
136
+ url.password ||
137
+ url.hash ||
138
+ url.search ||
139
+ !(url.protocol === 'https:' ||
140
+ (allowInsecureLocalhost && url.protocol === 'http:' && isLoopback(url.hostname))))
141
+ protocol();
142
+ return value;
143
+ }
144
+ export function isLoopback(host) {
145
+ return host === 'localhost' || host === '[::1]' || /^127\.(?:\d{1,3}\.){2}\d{1,3}$/.test(host);
146
+ }
147
+ /** One accepted extension of the Sess link (Decision 0009 Amendment 10), numbered in order. */
148
+ function linkExtension(value, number) {
149
+ const v = object(value);
150
+ if (integer(v.number) !== number)
151
+ protocol();
152
+ date(v.previous_action_expires_at);
153
+ date(v.action_expires_at);
154
+ if (typeof v.from_lapsed !== 'boolean')
155
+ protocol();
156
+ date(v.extended_at);
157
+ }
158
+ /** The extension history: at most ten records, numbered 1, 2, … in order. */
159
+ function linkExtensions(value) {
160
+ const items = array(value);
161
+ if (items.length > 10)
162
+ protocol();
163
+ items.forEach((item, i) => linkExtension(item, i + 1));
164
+ }
165
+ /**
166
+ * A Session read's link timing (Decision 0009 Amendment 10), checked when present. A runtime
167
+ * before link timing omits it; the wait then keeps its earlier rule (the deadline is final).
168
+ */
169
+ function linkTiming(v) {
170
+ if (v.link_state !== undefined)
171
+ oneOf(v.link_state, ['live', 'lapsed', 'expired']);
172
+ if (v.action_expires_horizon !== undefined)
173
+ nullableDate(v.action_expires_horizon);
174
+ if (v.extensions_used !== undefined && integer(v.extensions_used, 0) > 10)
175
+ protocol();
176
+ if (v.extensions !== undefined)
177
+ linkExtensions(v.extensions);
178
+ }
179
+ export function decodeSession(value, expectedId) {
180
+ const v = object(value);
181
+ if (string(v.id, sessionPattern) !== expectedId)
182
+ protocol();
183
+ const rev = integer(v.revision);
184
+ linkTiming(v);
185
+ const mode = object(v.interaction).mode;
186
+ if (mode === 'display') {
187
+ interaction(v.interaction, 'display');
188
+ if ('status' in v || 'responses' in v)
189
+ protocol();
190
+ return value;
191
+ }
192
+ interaction(v.interaction, 'interactive');
193
+ oneOf(v.status, ['active', 'responded', 'completed']);
194
+ object(v.response_schema);
195
+ const seen = new Set();
196
+ const revisions = new Set();
197
+ let previousSequence = 0;
198
+ let previousRevision = 0;
199
+ for (const item of array(v.responses)) {
200
+ const r = decodeAccepted(item);
201
+ if (r.revision > rev ||
202
+ r.sequence <= previousSequence ||
203
+ r.revision <= previousRevision ||
204
+ seen.has(r.event_id) ||
205
+ revisions.has(r.revision))
206
+ protocol();
207
+ seen.add(r.event_id);
208
+ revisions.add(r.revision);
209
+ previousSequence = r.sequence;
210
+ previousRevision = r.revision;
211
+ }
212
+ if (v.status === 'responded' && !revisions.has(rev))
213
+ protocol();
214
+ if (v.status === 'active' && revisions.has(rev))
215
+ protocol();
216
+ return value;
217
+ }
218
+ export function decodeSurface(value, expectedId, revision) {
219
+ const v = object(value);
220
+ if (string(v.id, sessionPattern) !== expectedId || integer(v.revision) !== revision)
221
+ protocol();
222
+ if (object(v.interaction).mode === 'display') {
223
+ interaction(v.interaction, 'display');
224
+ if ('response_schema' in v || 'status' in v || 'responses' in v)
225
+ protocol();
226
+ return value;
227
+ }
228
+ interaction(v.interaction, 'interactive');
229
+ object(v.response_schema);
230
+ return value;
231
+ }
232
+ export function decodeEvents(value, expectedId) {
233
+ const v = object(value);
234
+ if (string(v.id, sessionPattern) !== expectedId)
235
+ protocol();
236
+ const seen = new Set();
237
+ let seq = 0;
238
+ for (const item of array(v.events)) {
239
+ const e = object(item);
240
+ const id = string(e.event_id, eventPattern);
241
+ const next = integer(e.sequence);
242
+ if (seen.has(id) || next <= seq)
243
+ protocol();
244
+ seen.add(id);
245
+ seq = next;
246
+ integer(e.revision);
247
+ date(e.created_at);
248
+ oneOf(e.type, ['response.accepted', 'revision.published', 'session.completed']);
249
+ const actor = object(e.actor).assurance;
250
+ if (e.type === 'response.accepted') {
251
+ if (actor !== 'link_holder')
252
+ protocol();
253
+ string(e.action_id, actionPattern);
254
+ object(e.data);
255
+ receipt(e.receipt);
256
+ }
257
+ else if (actor !== 'owner')
258
+ protocol();
259
+ }
260
+ // Decision 0009 Amendment 10: the link's extensions are listed beside the Events (never as an
261
+ // Event type), only where the deployment enables them.
262
+ if (v.link_extensions !== undefined)
263
+ linkExtensions(v.link_extensions);
264
+ return value;
265
+ }
266
+ function endpoint(value) {
267
+ const v = object(value);
268
+ string(v.id, new RegExp(`^whe_${ulid}$`));
269
+ string(v.url);
270
+ oneOf(v.status, ['pending', 'verified']);
271
+ date(v.created_at);
272
+ nullableDate(v.verified_at);
273
+ nullableDate(v.verification_expires_at);
274
+ }
275
+ function secret(value) {
276
+ const v = object(value);
277
+ string(v.kid, new RegExp(`^wk_${ulid}$`));
278
+ string(v.secret, /^whsec_[A-Za-z0-9+/]{43}=$/);
279
+ }
280
+ export function decodeWebhookRegister(value) {
281
+ const v = object(value);
282
+ endpoint(v.endpoint);
283
+ if (v.signing_secret !== null)
284
+ secret(v.signing_secret);
285
+ return value;
286
+ }
287
+ export function decodeWebhookVerify(value) {
288
+ const v = object(value);
289
+ endpoint(v.endpoint);
290
+ if (object(v.endpoint).status !== 'verified' || object(v.endpoint).verified_at === null)
291
+ protocol();
292
+ return value;
293
+ }
294
+ export function decodeWebhook(value) {
295
+ const v = object(value);
296
+ if (v.endpoint !== null)
297
+ endpoint(v.endpoint);
298
+ for (const item of array(v.signing_secrets)) {
299
+ const s = object(item);
300
+ string(s.kid);
301
+ if (typeof s.active !== 'boolean')
302
+ protocol();
303
+ nullableDate(s.retire_at);
304
+ }
305
+ const d = object(v.deliveries);
306
+ integer(d.pending, 0);
307
+ integer(d.failed, 0);
308
+ integer(d.delivered, 0);
309
+ if (d.oldest_pending_age_seconds !== null)
310
+ integer(d.oldest_pending_age_seconds, 0);
311
+ return value;
312
+ }
313
+ export function decodeWebhookRotate(value) {
314
+ const v = object(value);
315
+ secret(v.signing_secret);
316
+ if (v.previous !== null) {
317
+ const p = object(v.previous);
318
+ string(p.kid);
319
+ date(p.retire_at);
320
+ }
321
+ return value;
322
+ }
323
+ const outcomes = [
324
+ 'started',
325
+ 'delivered',
326
+ 'server_error',
327
+ 'rate_limited',
328
+ 'timeout',
329
+ 'connection',
330
+ 'dns',
331
+ 'signing_unavailable',
332
+ 'request_timeout',
333
+ 'too_early',
334
+ 'rejected',
335
+ 'redirect',
336
+ 'egress_refused',
337
+ 'endpoint_unavailable',
338
+ 'exhausted',
339
+ ];
340
+ export function decodeDeliveries(value, expectedId) {
341
+ const v = object(value);
342
+ if (string(v.id) !== expectedId)
343
+ protocol();
344
+ for (const item of array(v.deliveries))
345
+ decodeDelivery(item);
346
+ return value;
347
+ }
348
+ function decodeDelivery(item) {
349
+ const d = object(item);
350
+ string(d.delivery_id, new RegExp(`^obx_${ulid}$`));
351
+ string(d.event_id, eventPattern);
352
+ string(d.endpoint_id);
353
+ oneOf(d.kind, ['accepted', 'redelivery']);
354
+ oneOf(d.status, ['pending', 'delivered', 'failed']);
355
+ nullableDate(d.next_attempt_at);
356
+ date(d.deadline_at);
357
+ date(d.created_at);
358
+ nullableDate(d.finished_at);
359
+ if (d.last_outcome !== null)
360
+ oneOf(d.last_outcome, outcomes);
361
+ for (const item of array(d.attempts)) {
362
+ const a = object(item);
363
+ integer(a.attempt);
364
+ date(a.started_at);
365
+ nullableDate(a.finished_at);
366
+ oneOf(a.outcome, outcomes);
367
+ if (a.http_status !== null) {
368
+ const status = integer(a.http_status, 100);
369
+ if (status > 599)
370
+ protocol();
371
+ }
372
+ }
373
+ }
374
+ export function decodeRedelivery(value, expectedEvent) {
375
+ const v = object(value);
376
+ decodeDelivery(v.delivery);
377
+ if (object(v.delivery).event_id !== expectedEvent)
378
+ protocol();
379
+ return value;
380
+ }
@@ -0,0 +1,3 @@
1
+ /** Copy only ordinary JSON, never invoke accessors or toJSON coercions. */
2
+ export declare function snapshotJson<T>(input: T): T;
3
+ export declare function serializeBody(input: unknown): string;
@@ -0,0 +1,74 @@
1
+ import { SessError } from '../errors.js';
2
+ /** Copy only ordinary JSON, never invoke accessors or toJSON coercions. */
3
+ export function snapshotJson(input) {
4
+ const active = new Set();
5
+ function copy(value, depth) {
6
+ if (depth > 128)
7
+ throw new Error();
8
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
9
+ return value;
10
+ if (typeof value === 'number') {
11
+ if (!Number.isFinite(value) || Object.is(value, -0))
12
+ throw new Error();
13
+ return value;
14
+ }
15
+ if (typeof value !== 'object' || active.has(value))
16
+ throw new Error();
17
+ if (Object.getOwnPropertySymbols(value).length)
18
+ throw new Error();
19
+ // Hidden toJSON and inherited Array-subclass semantics must not be silently erased.
20
+ const descriptors = Object.getOwnPropertyDescriptors(value);
21
+ for (const [name, descriptor] of Object.entries(descriptors)) {
22
+ if (!('value' in descriptor) || (name === 'toJSON' && typeof descriptor.value === 'function'))
23
+ throw new Error();
24
+ }
25
+ active.add(value);
26
+ try {
27
+ if (Array.isArray(value)) {
28
+ if (Object.getPrototypeOf(value) !== Array.prototype)
29
+ throw new Error();
30
+ if (Object.keys(value).length !== value.length)
31
+ throw new Error();
32
+ return Array.from({ length: value.length }, (_, i) => {
33
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(i));
34
+ if (!descriptor || !('value' in descriptor))
35
+ throw new Error();
36
+ return copy(descriptor.value, depth + 1);
37
+ });
38
+ }
39
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
40
+ throw new Error();
41
+ const result = Object.create(null);
42
+ for (const key of Object.keys(value)) {
43
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
44
+ if (!('value' in descriptor))
45
+ throw new Error();
46
+ if (descriptor.value !== undefined)
47
+ result[key] = copy(descriptor.value, depth + 1);
48
+ }
49
+ return result;
50
+ }
51
+ finally {
52
+ active.delete(value);
53
+ }
54
+ }
55
+ try {
56
+ return copy(input, 0);
57
+ }
58
+ catch {
59
+ throw new SessError('configuration', 'Request must contain ordinary JSON values without coercion.', {
60
+ code: 'INVALID_JSON',
61
+ outcome: 'not_sent',
62
+ });
63
+ }
64
+ }
65
+ export function serializeBody(input) {
66
+ const serialized = JSON.stringify(snapshotJson(input));
67
+ if (Buffer.byteLength(serialized, 'utf8') > 256 * 1024) {
68
+ throw new SessError('configuration', 'Request body exceeds the 256 KiB limit.', {
69
+ code: 'PAYLOAD_TOO_LARGE',
70
+ outcome: 'not_sent',
71
+ });
72
+ }
73
+ return serialized;
74
+ }
@@ -0,0 +1,10 @@
1
+ import { SessError } from '../errors.js';
2
+ export declare function boundedNumber(value: number | undefined, fallback: number, name: string, min?: number, max?: number): number;
3
+ export declare function deadline(ms: number, parent?: AbortSignal): {
4
+ signal: AbortSignal;
5
+ dispose(): void;
6
+ };
7
+ export declare function abortError(signal: AbortSignal): SessError;
8
+ /** Enforce deadlines even when a custom fetch/provider fails to observe its signal. */
9
+ export declare function withSignal<T>(promise: Promise<T>, signal: AbortSignal): Promise<T>;
10
+ export declare function delay(ms: number, signal: AbortSignal): Promise<void>;
@@ -0,0 +1,70 @@
1
+ import { SessError } from '../errors.js';
2
+ export function boundedNumber(value, fallback, name, min = 1, max = 2_147_483_647) {
3
+ const result = value ?? fallback;
4
+ if (!Number.isSafeInteger(result) || result < min || result > max) {
5
+ throw new SessError('configuration', `${name} is outside its supported range.`, { outcome: 'not_sent' });
6
+ }
7
+ return result;
8
+ }
9
+ export function deadline(ms, parent) {
10
+ const controller = new AbortController();
11
+ const abort = () => controller.abort(parent?.reason);
12
+ if (parent?.aborted)
13
+ abort();
14
+ else
15
+ parent?.addEventListener('abort', abort, { once: true });
16
+ const timer = setTimeout(() => controller.abort(new SessError('timeout', 'Operation deadline exceeded.')), ms);
17
+ return {
18
+ signal: controller.signal,
19
+ dispose() {
20
+ clearTimeout(timer);
21
+ parent?.removeEventListener('abort', abort);
22
+ },
23
+ };
24
+ }
25
+ export function abortError(signal) {
26
+ return signal.reason instanceof SessError && signal.reason.kind === 'timeout'
27
+ ? new SessError('timeout', 'Operation deadline exceeded.')
28
+ : new SessError('aborted', 'Operation was aborted. Remote work is not cancelled.');
29
+ }
30
+ /** Enforce deadlines even when a custom fetch/provider fails to observe its signal. */
31
+ export function withSignal(promise, signal) {
32
+ return new Promise((resolve, reject) => {
33
+ const cleanup = () => signal.removeEventListener('abort', abort);
34
+ const abort = () => {
35
+ cleanup();
36
+ reject(abortError(signal));
37
+ };
38
+ if (signal.aborted) {
39
+ promise.catch(() => { });
40
+ abort();
41
+ return;
42
+ }
43
+ signal.addEventListener('abort', abort, { once: true });
44
+ promise.then((value) => {
45
+ cleanup();
46
+ resolve(value);
47
+ }, (error) => {
48
+ cleanup();
49
+ reject(error);
50
+ });
51
+ });
52
+ }
53
+ export function delay(ms, signal) {
54
+ return new Promise((resolve, reject) => {
55
+ if (signal.aborted) {
56
+ reject(abortError(signal));
57
+ return;
58
+ }
59
+ const abort = () => {
60
+ clearTimeout(timer);
61
+ signal.removeEventListener('abort', abort);
62
+ reject(abortError(signal));
63
+ };
64
+ const timer = setTimeout(() => {
65
+ signal.removeEventListener('abort', abort);
66
+ resolve();
67
+ }, ms);
68
+ signal.addEventListener('abort', abort, { once: true });
69
+ });
70
+ }
@@ -0,0 +1,2 @@
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-rc.10";
@@ -0,0 +1,2 @@
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-rc.10';
@@ -0,0 +1,11 @@
1
+ import type { RequestOptions, Session, VersionedResult, WaitOptions, WaitResult } from './types.js';
2
+ /**
3
+ * Once a Session's link has reached its end (its deadline, `action_expires_at`, or while the
4
+ * person can still extend it, its horizon), the wait reads it once more when the runtime clock is
5
+ * this far past that end, then ends: an answer accepted before the end is returned; otherwise the
6
+ * wait ends with `LINK_EXPIRED`. Two seconds covers the one-second
7
+ * resolution of the HTTP `Date` header plus an answer accepted just before the expiry whose write
8
+ * is still landing, and keeps the end prompt.
9
+ */
10
+ export declare const LINK_EXPIRY_GRACE_MS = 2000;
11
+ export declare function waitForResponse(retrieve: (options: RequestOptions) => Promise<VersionedResult<Session>>, id: string, input: WaitOptions, clientOperationTimeoutMs: number): Promise<WaitResult>;