@sess.si/sdk 0.0.0-stage → 0.1.0-rc.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/LICENSE +201 -0
- package/NOTICE +9 -0
- package/README.md +136 -2
- package/dist/client.d.ts +12 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +34 -0
- package/dist/client.js.map +1 -0
- package/dist/errors.d.ts +40 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +52 -0
- package/dist/errors.js.map +1 -0
- package/dist/generated/openapi.d.ts +2462 -0
- package/dist/generated/openapi.d.ts.map +1 -0
- package/dist/generated/openapi.js +2 -0
- package/dist/generated/openapi.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/decode.d.ts +21 -0
- package/dist/internal/decode.d.ts.map +1 -0
- package/dist/internal/decode.js +333 -0
- package/dist/internal/decode.js.map +1 -0
- package/dist/internal/json.d.ts +4 -0
- package/dist/internal/json.d.ts.map +1 -0
- package/dist/internal/json.js +75 -0
- package/dist/internal/json.js.map +1 -0
- package/dist/internal/time.d.ts +11 -0
- package/dist/internal/time.d.ts.map +1 -0
- package/dist/internal/time.js +71 -0
- package/dist/internal/time.js.map +1 -0
- package/dist/polling.d.ts +3 -0
- package/dist/polling.d.ts.map +1 -0
- package/dist/polling.js +61 -0
- package/dist/polling.js.map +1 -0
- package/dist/receipts/index.d.ts +5 -0
- package/dist/receipts/index.d.ts.map +1 -0
- package/dist/receipts/index.js +2 -0
- package/dist/receipts/index.js.map +1 -0
- package/dist/receipts/json.d.ts +22 -0
- package/dist/receipts/json.d.ts.map +1 -0
- package/dist/receipts/json.js +152 -0
- package/dist/receipts/json.js.map +1 -0
- package/dist/receipts/key-cache.d.ts +28 -0
- package/dist/receipts/key-cache.d.ts.map +1 -0
- package/dist/receipts/key-cache.js +110 -0
- package/dist/receipts/key-cache.js.map +1 -0
- package/dist/receipts/resource.d.ts +39 -0
- package/dist/receipts/resource.d.ts.map +1 -0
- package/dist/receipts/resource.js +119 -0
- package/dist/receipts/resource.js.map +1 -0
- package/dist/receipts/verify.d.ts +90 -0
- package/dist/receipts/verify.d.ts.map +1 -0
- package/dist/receipts/verify.js +294 -0
- package/dist/receipts/verify.js.map +1 -0
- package/dist/sessions.d.ts +19 -0
- package/dist/sessions.d.ts.map +1 -0
- package/dist/sessions.js +145 -0
- package/dist/sessions.js.map +1 -0
- package/dist/transport.d.ts +29 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/transport.js +447 -0
- package/dist/transport.js.map +1 -0
- package/dist/types.d.ts +149 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +9 -0
- package/dist/types.js.map +1 -0
- package/dist/webhook-resource.d.ts +13 -0
- package/dist/webhook-resource.d.ts.map +1 -0
- package/dist/webhook-resource.js +52 -0
- package/dist/webhook-resource.js.map +1 -0
- package/dist/webhooks/index.d.ts +22 -0
- package/dist/webhooks/index.d.ts.map +1 -0
- package/dist/webhooks/index.js +184 -0
- package/dist/webhooks/index.js.map +1 -0
- package/package.json +74 -4
- package/src/client.ts +41 -0
- package/src/errors.ts +96 -0
- package/src/generated/openapi.ts +2578 -0
- package/src/index.ts +4 -0
- package/src/internal/decode.ts +317 -0
- package/src/internal/json.ts +64 -0
- package/src/internal/time.ts +85 -0
- package/src/polling.ts +77 -0
- package/src/receipts/index.ts +16 -0
- package/src/receipts/json.ts +168 -0
- package/src/receipts/key-cache.ts +143 -0
- package/src/receipts/resource.ts +227 -0
- package/src/receipts/verify.ts +468 -0
- package/src/sessions.ts +227 -0
- package/src/transport.ts +524 -0
- package/src/types.ts +135 -0
- package/src/webhook-resource.ts +81 -0
- package/src/webhooks/index.ts +246 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
import { SessError } from '../errors.js';
|
|
2
|
+
import type {
|
|
3
|
+
AcceptedResponse,
|
|
4
|
+
CreateSessionResponse,
|
|
5
|
+
Deliveries,
|
|
6
|
+
InteractiveSession,
|
|
7
|
+
Session,
|
|
8
|
+
SessionEvents,
|
|
9
|
+
SurfaceRevision,
|
|
10
|
+
WebhookRegisterResponse,
|
|
11
|
+
WebhookResponse,
|
|
12
|
+
WebhookRotateResponse,
|
|
13
|
+
WebhookVerifyResponse,
|
|
14
|
+
RedeliverResponse,
|
|
15
|
+
} from '../types.js';
|
|
16
|
+
|
|
17
|
+
export const ulid = '[0-9A-HJKMNP-TV-Z]{26}';
|
|
18
|
+
export const sessionPattern = new RegExp(`^ses_${ulid}$`);
|
|
19
|
+
const eventPattern = new RegExp(`^evt_${ulid}$`);
|
|
20
|
+
const actionPattern = /^[a-z][a-z0-9_]{0,31}$/;
|
|
21
|
+
const receiptPattern = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
22
|
+
export function protocol(): never {
|
|
23
|
+
throw new SessError('protocol', 'Response does not match the supported SESS contract.', {
|
|
24
|
+
code: 'INVALID_RESPONSE',
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
export function object(value: unknown): Record<string, unknown> {
|
|
28
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) protocol();
|
|
29
|
+
return value as Record<string, unknown>;
|
|
30
|
+
}
|
|
31
|
+
export function string(value: unknown, pattern?: RegExp, max = 4096): string {
|
|
32
|
+
// The wire contract uses Unicode code points, independently of UTF-8 body caps.
|
|
33
|
+
if (
|
|
34
|
+
typeof value !== 'string' ||
|
|
35
|
+
!value.length ||
|
|
36
|
+
[...value].length > max ||
|
|
37
|
+
(pattern && !pattern.test(value))
|
|
38
|
+
)
|
|
39
|
+
protocol();
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
export function integer(value: unknown, minimum = 1): number {
|
|
43
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < minimum) protocol();
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
function date(value: unknown): void {
|
|
47
|
+
const text = string(value, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/, 32);
|
|
48
|
+
if (!Number.isFinite(Date.parse(text))) protocol();
|
|
49
|
+
}
|
|
50
|
+
function nullableDate(value: unknown): void {
|
|
51
|
+
if (value !== null) date(value);
|
|
52
|
+
}
|
|
53
|
+
function array(value: unknown): unknown[] {
|
|
54
|
+
if (!Array.isArray(value)) protocol();
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
function oneOf(value: unknown, values: readonly string[]): void {
|
|
58
|
+
if (typeof value !== 'string' || !values.includes(value)) protocol();
|
|
59
|
+
}
|
|
60
|
+
function receipt(value: unknown): void {
|
|
61
|
+
if (value !== null) string(value, receiptPattern, 65536);
|
|
62
|
+
}
|
|
63
|
+
function interaction(value: unknown, mode: 'display' | 'interactive'): void {
|
|
64
|
+
const v = object(value);
|
|
65
|
+
if (v.mode !== mode) protocol();
|
|
66
|
+
string(v.title, undefined, 200);
|
|
67
|
+
if (v.description !== undefined && typeof v.description !== 'string') protocol();
|
|
68
|
+
const source = object(v.source);
|
|
69
|
+
if (mode === 'display') {
|
|
70
|
+
if (source.kind !== 'data') protocol();
|
|
71
|
+
object(source.data);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (source.kind !== 'sess_surface' || v.response_policy !== 'first') protocol();
|
|
75
|
+
for (const item of array(source.components)) {
|
|
76
|
+
const c = object(item);
|
|
77
|
+
oneOf(c.type, ['heading', 'text', 'record', 'field']);
|
|
78
|
+
if (c.type === 'heading') string(c.text, undefined, 200);
|
|
79
|
+
if (c.type === 'text') string(c.text, undefined, 4000);
|
|
80
|
+
if (c.type === 'record') object(c.fields);
|
|
81
|
+
if (c.type === 'field') {
|
|
82
|
+
string(c.name, /^[a-z][a-z0-9_]{0,63}$/);
|
|
83
|
+
string(c.label, undefined, 200);
|
|
84
|
+
oneOf(object(c.schema).type, ['string', 'number', 'integer', 'boolean', 'array']);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const seen = new Set<string>();
|
|
88
|
+
for (const item of array(v.actions)) {
|
|
89
|
+
const a = object(item);
|
|
90
|
+
const id = string(a.id, actionPattern);
|
|
91
|
+
if (seen.has(id)) protocol();
|
|
92
|
+
seen.add(id);
|
|
93
|
+
string(a.label, undefined, 200);
|
|
94
|
+
if (a.intent !== undefined)
|
|
95
|
+
oneOf(a.intent, ['submit', 'continue', 'approve', 'reject', 'request_change']);
|
|
96
|
+
}
|
|
97
|
+
if (!seen.size) protocol();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Keeps all additive JSON fields intact; this is a boundary decoder, not normalization. */
|
|
101
|
+
export function decodeAccepted(value: unknown): AcceptedResponse {
|
|
102
|
+
const v = object(value);
|
|
103
|
+
string(v.event_id, eventPattern);
|
|
104
|
+
integer(v.sequence);
|
|
105
|
+
integer(v.revision);
|
|
106
|
+
string(v.action_id, actionPattern);
|
|
107
|
+
object(v.data);
|
|
108
|
+
if (object(v.actor).assurance !== 'link_holder') protocol();
|
|
109
|
+
date(v.accepted_at);
|
|
110
|
+
receipt(v.receipt);
|
|
111
|
+
return value as AcceptedResponse;
|
|
112
|
+
}
|
|
113
|
+
export function decodeCreate(value: unknown, allowInsecureLocalhost = false): CreateSessionResponse {
|
|
114
|
+
const v = object(value);
|
|
115
|
+
string(v.id, sessionPattern);
|
|
116
|
+
integer(v.revision);
|
|
117
|
+
const text = string(v.human_url, /^[^\s\u0000-\u001f\u007f]+$/, 4096);
|
|
118
|
+
let url: URL;
|
|
119
|
+
try {
|
|
120
|
+
url = new URL(text);
|
|
121
|
+
} catch {
|
|
122
|
+
return protocol();
|
|
123
|
+
}
|
|
124
|
+
if (
|
|
125
|
+
url.username ||
|
|
126
|
+
url.password ||
|
|
127
|
+
url.hash ||
|
|
128
|
+
url.search ||
|
|
129
|
+
!(
|
|
130
|
+
url.protocol === 'https:' ||
|
|
131
|
+
(allowInsecureLocalhost && url.protocol === 'http:' && isLoopback(url.hostname))
|
|
132
|
+
)
|
|
133
|
+
)
|
|
134
|
+
protocol();
|
|
135
|
+
return value as CreateSessionResponse;
|
|
136
|
+
}
|
|
137
|
+
export function isLoopback(host: string): boolean {
|
|
138
|
+
return host === 'localhost' || host === '[::1]' || /^127\.(?:\d{1,3}\.){2}\d{1,3}$/.test(host);
|
|
139
|
+
}
|
|
140
|
+
export function decodeSession(value: unknown, expectedId: string): Session {
|
|
141
|
+
const v = object(value);
|
|
142
|
+
if (string(v.id, sessionPattern) !== expectedId) protocol();
|
|
143
|
+
const rev = integer(v.revision);
|
|
144
|
+
const mode = object(v.interaction).mode;
|
|
145
|
+
if (mode === 'display') {
|
|
146
|
+
interaction(v.interaction, 'display');
|
|
147
|
+
if ('status' in v || 'responses' in v) protocol();
|
|
148
|
+
return value as Session;
|
|
149
|
+
}
|
|
150
|
+
interaction(v.interaction, 'interactive');
|
|
151
|
+
oneOf(v.status, ['active', 'responded', 'completed']);
|
|
152
|
+
object(v.response_schema);
|
|
153
|
+
const seen = new Set<string>();
|
|
154
|
+
const revisions = new Set<number>();
|
|
155
|
+
let previousSequence = 0;
|
|
156
|
+
let previousRevision = 0;
|
|
157
|
+
for (const item of array(v.responses)) {
|
|
158
|
+
const r = decodeAccepted(item);
|
|
159
|
+
if (
|
|
160
|
+
r.revision > rev ||
|
|
161
|
+
r.sequence <= previousSequence ||
|
|
162
|
+
r.revision <= previousRevision ||
|
|
163
|
+
seen.has(r.event_id) ||
|
|
164
|
+
revisions.has(r.revision)
|
|
165
|
+
)
|
|
166
|
+
protocol();
|
|
167
|
+
seen.add(r.event_id);
|
|
168
|
+
revisions.add(r.revision);
|
|
169
|
+
previousSequence = r.sequence;
|
|
170
|
+
previousRevision = r.revision;
|
|
171
|
+
}
|
|
172
|
+
if (v.status === 'responded' && !revisions.has(rev)) protocol();
|
|
173
|
+
if (v.status === 'active' && revisions.has(rev)) protocol();
|
|
174
|
+
return value as InteractiveSession;
|
|
175
|
+
}
|
|
176
|
+
export function decodeSurface(value: unknown, expectedId: string, revision: number): SurfaceRevision {
|
|
177
|
+
const v = object(value);
|
|
178
|
+
if (string(v.id, sessionPattern) !== expectedId || integer(v.revision) !== revision) protocol();
|
|
179
|
+
if (object(v.interaction).mode === 'display') {
|
|
180
|
+
interaction(v.interaction, 'display');
|
|
181
|
+
if ('response_schema' in v || 'status' in v || 'responses' in v) protocol();
|
|
182
|
+
return value as SurfaceRevision;
|
|
183
|
+
}
|
|
184
|
+
interaction(v.interaction, 'interactive');
|
|
185
|
+
object(v.response_schema);
|
|
186
|
+
return value as SurfaceRevision;
|
|
187
|
+
}
|
|
188
|
+
export function decodeEvents(value: unknown, expectedId: string): SessionEvents {
|
|
189
|
+
const v = object(value);
|
|
190
|
+
if (string(v.id, sessionPattern) !== expectedId) protocol();
|
|
191
|
+
const seen = new Set<string>();
|
|
192
|
+
let seq = 0;
|
|
193
|
+
for (const item of array(v.events)) {
|
|
194
|
+
const e = object(item);
|
|
195
|
+
const id = string(e.event_id, eventPattern);
|
|
196
|
+
const next = integer(e.sequence);
|
|
197
|
+
if (seen.has(id) || next <= seq) protocol();
|
|
198
|
+
seen.add(id);
|
|
199
|
+
seq = next;
|
|
200
|
+
integer(e.revision);
|
|
201
|
+
date(e.created_at);
|
|
202
|
+
oneOf(e.type, ['response.accepted', 'revision.published', 'session.completed']);
|
|
203
|
+
const actor = object(e.actor).assurance;
|
|
204
|
+
if (e.type === 'response.accepted') {
|
|
205
|
+
if (actor !== 'link_holder') protocol();
|
|
206
|
+
string(e.action_id, actionPattern);
|
|
207
|
+
object(e.data);
|
|
208
|
+
receipt(e.receipt);
|
|
209
|
+
} else if (actor !== 'owner') protocol();
|
|
210
|
+
}
|
|
211
|
+
return value as SessionEvents;
|
|
212
|
+
}
|
|
213
|
+
function endpoint(value: unknown): void {
|
|
214
|
+
const v = object(value);
|
|
215
|
+
string(v.id, new RegExp(`^whe_${ulid}$`));
|
|
216
|
+
string(v.url);
|
|
217
|
+
oneOf(v.status, ['pending', 'verified']);
|
|
218
|
+
date(v.created_at);
|
|
219
|
+
nullableDate(v.verified_at);
|
|
220
|
+
nullableDate(v.verification_expires_at);
|
|
221
|
+
}
|
|
222
|
+
function secret(value: unknown): void {
|
|
223
|
+
const v = object(value);
|
|
224
|
+
string(v.kid, new RegExp(`^wk_${ulid}$`));
|
|
225
|
+
string(v.secret, /^whsec_[A-Za-z0-9+/]{43}=$/);
|
|
226
|
+
}
|
|
227
|
+
export function decodeWebhookRegister(value: unknown): WebhookRegisterResponse {
|
|
228
|
+
const v = object(value);
|
|
229
|
+
endpoint(v.endpoint);
|
|
230
|
+
if (v.signing_secret !== null) secret(v.signing_secret);
|
|
231
|
+
return value as WebhookRegisterResponse;
|
|
232
|
+
}
|
|
233
|
+
export function decodeWebhookVerify(value: unknown): WebhookVerifyResponse {
|
|
234
|
+
const v = object(value);
|
|
235
|
+
endpoint(v.endpoint);
|
|
236
|
+
if (object(v.endpoint).status !== 'verified' || object(v.endpoint).verified_at === null) protocol();
|
|
237
|
+
return value as WebhookVerifyResponse;
|
|
238
|
+
}
|
|
239
|
+
export function decodeWebhook(value: unknown): WebhookResponse {
|
|
240
|
+
const v = object(value);
|
|
241
|
+
if (v.endpoint !== null) endpoint(v.endpoint);
|
|
242
|
+
for (const item of array(v.signing_secrets)) {
|
|
243
|
+
const s = object(item);
|
|
244
|
+
string(s.kid);
|
|
245
|
+
if (typeof s.active !== 'boolean') protocol();
|
|
246
|
+
nullableDate(s.retire_at);
|
|
247
|
+
}
|
|
248
|
+
const d = object(v.deliveries);
|
|
249
|
+
integer(d.pending, 0);
|
|
250
|
+
integer(d.failed, 0);
|
|
251
|
+
integer(d.delivered, 0);
|
|
252
|
+
if (d.oldest_pending_age_seconds !== null) integer(d.oldest_pending_age_seconds, 0);
|
|
253
|
+
return value as WebhookResponse;
|
|
254
|
+
}
|
|
255
|
+
export function decodeWebhookRotate(value: unknown): WebhookRotateResponse {
|
|
256
|
+
const v = object(value);
|
|
257
|
+
secret(v.signing_secret);
|
|
258
|
+
if (v.previous !== null) {
|
|
259
|
+
const p = object(v.previous);
|
|
260
|
+
string(p.kid);
|
|
261
|
+
date(p.retire_at);
|
|
262
|
+
}
|
|
263
|
+
return value as WebhookRotateResponse;
|
|
264
|
+
}
|
|
265
|
+
const outcomes = [
|
|
266
|
+
'started',
|
|
267
|
+
'delivered',
|
|
268
|
+
'server_error',
|
|
269
|
+
'rate_limited',
|
|
270
|
+
'timeout',
|
|
271
|
+
'connection',
|
|
272
|
+
'dns',
|
|
273
|
+
'signing_unavailable',
|
|
274
|
+
'request_timeout',
|
|
275
|
+
'too_early',
|
|
276
|
+
'rejected',
|
|
277
|
+
'redirect',
|
|
278
|
+
'egress_refused',
|
|
279
|
+
'endpoint_unavailable',
|
|
280
|
+
'exhausted',
|
|
281
|
+
];
|
|
282
|
+
export function decodeDeliveries(value: unknown, expectedId: string): Deliveries {
|
|
283
|
+
const v = object(value);
|
|
284
|
+
if (string(v.id) !== expectedId) protocol();
|
|
285
|
+
for (const item of array(v.deliveries)) decodeDelivery(item);
|
|
286
|
+
return value as Deliveries;
|
|
287
|
+
}
|
|
288
|
+
function decodeDelivery(item: unknown): void {
|
|
289
|
+
const d = object(item);
|
|
290
|
+
string(d.delivery_id, new RegExp(`^obx_${ulid}$`));
|
|
291
|
+
string(d.event_id, eventPattern);
|
|
292
|
+
string(d.endpoint_id);
|
|
293
|
+
oneOf(d.kind, ['accepted', 'redelivery']);
|
|
294
|
+
oneOf(d.status, ['pending', 'delivered', 'failed']);
|
|
295
|
+
nullableDate(d.next_attempt_at);
|
|
296
|
+
date(d.deadline_at);
|
|
297
|
+
date(d.created_at);
|
|
298
|
+
nullableDate(d.finished_at);
|
|
299
|
+
if (d.last_outcome !== null) oneOf(d.last_outcome, outcomes);
|
|
300
|
+
for (const item of array(d.attempts)) {
|
|
301
|
+
const a = object(item);
|
|
302
|
+
integer(a.attempt);
|
|
303
|
+
date(a.started_at);
|
|
304
|
+
nullableDate(a.finished_at);
|
|
305
|
+
oneOf(a.outcome, outcomes);
|
|
306
|
+
if (a.http_status !== null) {
|
|
307
|
+
const status = integer(a.http_status, 100);
|
|
308
|
+
if (status > 599) protocol();
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
export function decodeRedelivery(value: unknown, expectedEvent: string): RedeliverResponse {
|
|
313
|
+
const v = object(value);
|
|
314
|
+
decodeDelivery(v.delivery);
|
|
315
|
+
if (object(v.delivery).event_id !== expectedEvent) protocol();
|
|
316
|
+
return value as RedeliverResponse;
|
|
317
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { SessError } from '../errors.js';
|
|
2
|
+
|
|
3
|
+
/** Copy only ordinary JSON, never invoke accessors or toJSON coercions. */
|
|
4
|
+
export function snapshotJson<T>(input: T): T {
|
|
5
|
+
const active = new Set<object>();
|
|
6
|
+
function copy(value: unknown, depth: number): unknown {
|
|
7
|
+
if (depth > 128) throw new Error();
|
|
8
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
|
|
9
|
+
if (typeof value === 'number') {
|
|
10
|
+
if (!Number.isFinite(value) || Object.is(value, -0)) throw new Error();
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
if (typeof value !== 'object' || active.has(value)) throw new Error();
|
|
14
|
+
if (Object.getOwnPropertySymbols(value).length) throw new Error();
|
|
15
|
+
// Hidden toJSON and inherited Array-subclass semantics must not be silently erased.
|
|
16
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
17
|
+
for (const [name, descriptor] of Object.entries(descriptors)) {
|
|
18
|
+
if (!('value' in descriptor) || (name === 'toJSON' && typeof descriptor.value === 'function'))
|
|
19
|
+
throw new Error();
|
|
20
|
+
}
|
|
21
|
+
active.add(value);
|
|
22
|
+
try {
|
|
23
|
+
if (Array.isArray(value)) {
|
|
24
|
+
if (Object.getPrototypeOf(value) !== Array.prototype) throw new Error();
|
|
25
|
+
if (Object.keys(value).length !== value.length) throw new Error();
|
|
26
|
+
return Array.from({ length: value.length }, (_, i) => {
|
|
27
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, String(i));
|
|
28
|
+
if (!descriptor || !('value' in descriptor)) throw new Error();
|
|
29
|
+
return copy(descriptor.value, depth + 1);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
|
|
33
|
+
throw new Error();
|
|
34
|
+
const result: Record<string, unknown> = Object.create(null) as Record<string, unknown>;
|
|
35
|
+
for (const key of Object.keys(value)) {
|
|
36
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key)!;
|
|
37
|
+
if (!('value' in descriptor)) throw new Error();
|
|
38
|
+
if (descriptor.value !== undefined) result[key] = copy(descriptor.value, depth + 1);
|
|
39
|
+
}
|
|
40
|
+
return result;
|
|
41
|
+
} finally {
|
|
42
|
+
active.delete(value);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
return copy(input, 0) as T;
|
|
47
|
+
} catch {
|
|
48
|
+
throw new SessError('configuration', 'Request must contain ordinary JSON values without coercion.', {
|
|
49
|
+
code: 'INVALID_JSON',
|
|
50
|
+
outcome: 'not_sent',
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function serializeBody(input: unknown): string {
|
|
56
|
+
const serialized = JSON.stringify(snapshotJson(input));
|
|
57
|
+
if (Buffer.byteLength(serialized, 'utf8') > 256 * 1024) {
|
|
58
|
+
throw new SessError('configuration', 'Request body exceeds the 256 KiB limit.', {
|
|
59
|
+
code: 'PAYLOAD_TOO_LARGE',
|
|
60
|
+
outcome: 'not_sent',
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
return serialized;
|
|
64
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { SessError } from '../errors.js';
|
|
2
|
+
|
|
3
|
+
export function boundedNumber(
|
|
4
|
+
value: number | undefined,
|
|
5
|
+
fallback: number,
|
|
6
|
+
name: string,
|
|
7
|
+
min = 1,
|
|
8
|
+
max = 2_147_483_647,
|
|
9
|
+
): number {
|
|
10
|
+
const result = value ?? fallback;
|
|
11
|
+
if (!Number.isSafeInteger(result) || result < min || result > max) {
|
|
12
|
+
throw new SessError('configuration', `${name} is outside its supported range.`, { outcome: 'not_sent' });
|
|
13
|
+
}
|
|
14
|
+
return result;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function deadline(ms: number, parent?: AbortSignal): { signal: AbortSignal; dispose(): void } {
|
|
18
|
+
const controller = new AbortController();
|
|
19
|
+
const abort = () => controller.abort(parent?.reason);
|
|
20
|
+
if (parent?.aborted) abort();
|
|
21
|
+
else parent?.addEventListener('abort', abort, { once: true });
|
|
22
|
+
const timer = setTimeout(
|
|
23
|
+
() => controller.abort(new SessError('timeout', 'Operation deadline exceeded.')),
|
|
24
|
+
ms,
|
|
25
|
+
);
|
|
26
|
+
return {
|
|
27
|
+
signal: controller.signal,
|
|
28
|
+
dispose() {
|
|
29
|
+
clearTimeout(timer);
|
|
30
|
+
parent?.removeEventListener('abort', abort);
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function abortError(signal: AbortSignal): SessError {
|
|
36
|
+
return signal.reason instanceof SessError && signal.reason.kind === 'timeout'
|
|
37
|
+
? new SessError('timeout', 'Operation deadline exceeded.')
|
|
38
|
+
: new SessError('aborted', 'Operation was aborted. Remote work is not cancelled.');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Enforce deadlines even when a custom fetch/provider fails to observe its signal. */
|
|
42
|
+
export function withSignal<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
43
|
+
return new Promise<T>((resolve, reject) => {
|
|
44
|
+
const cleanup = () => signal.removeEventListener('abort', abort);
|
|
45
|
+
const abort = () => {
|
|
46
|
+
cleanup();
|
|
47
|
+
reject(abortError(signal));
|
|
48
|
+
};
|
|
49
|
+
if (signal.aborted) {
|
|
50
|
+
promise.catch(() => {});
|
|
51
|
+
abort();
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
55
|
+
promise.then(
|
|
56
|
+
(value) => {
|
|
57
|
+
cleanup();
|
|
58
|
+
resolve(value);
|
|
59
|
+
},
|
|
60
|
+
(error: unknown) => {
|
|
61
|
+
cleanup();
|
|
62
|
+
reject(error);
|
|
63
|
+
},
|
|
64
|
+
);
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function delay(ms: number, signal: AbortSignal): Promise<void> {
|
|
69
|
+
return new Promise((resolve, reject) => {
|
|
70
|
+
if (signal.aborted) {
|
|
71
|
+
reject(abortError(signal));
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const abort = () => {
|
|
75
|
+
clearTimeout(timer);
|
|
76
|
+
signal.removeEventListener('abort', abort);
|
|
77
|
+
reject(abortError(signal));
|
|
78
|
+
};
|
|
79
|
+
const timer = setTimeout(() => {
|
|
80
|
+
signal.removeEventListener('abort', abort);
|
|
81
|
+
resolve();
|
|
82
|
+
}, ms);
|
|
83
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
84
|
+
});
|
|
85
|
+
}
|
package/src/polling.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { SessError } from './errors.js';
|
|
2
|
+
import { abortError, boundedNumber, deadline, delay } from './internal/time.js';
|
|
3
|
+
import { isInteractiveSession } from './types.js';
|
|
4
|
+
import type { RequestOptions, Session, VersionedResult, WaitOptions, WaitResult } from './types.js';
|
|
5
|
+
|
|
6
|
+
export async function waitForResponse(
|
|
7
|
+
retrieve: (options: RequestOptions) => Promise<VersionedResult<Session>>,
|
|
8
|
+
id: string,
|
|
9
|
+
input: WaitOptions,
|
|
10
|
+
clientOperationTimeoutMs: number,
|
|
11
|
+
): Promise<WaitResult> {
|
|
12
|
+
if (!input || typeof input !== 'object')
|
|
13
|
+
throw new SessError('configuration', 'waitForResponse requires an exact revision.');
|
|
14
|
+
const options = { ...input };
|
|
15
|
+
const revision = boundedNumber(options.revision, 0, 'revision');
|
|
16
|
+
const timeoutMs = boundedNumber(options.timeoutMs, 10 * 60_000, 'timeoutMs');
|
|
17
|
+
const intervalMs = boundedNumber(options.intervalMs, 1500, 'intervalMs', 1000);
|
|
18
|
+
if (options.operationTimeoutMs !== undefined && typeof options.operationTimeoutMs !== 'number')
|
|
19
|
+
throw new SessError('configuration', 'operationTimeoutMs must be a positive integer duration.', {
|
|
20
|
+
outcome: 'not_sent',
|
|
21
|
+
});
|
|
22
|
+
// Validate before clamping so malformed overrides cannot become usable durations.
|
|
23
|
+
const operationTimeoutMs = boundedNumber(
|
|
24
|
+
options.operationTimeoutMs,
|
|
25
|
+
clientOperationTimeoutMs,
|
|
26
|
+
'operationTimeoutMs',
|
|
27
|
+
);
|
|
28
|
+
const budget = deadline(timeoutMs, options.signal);
|
|
29
|
+
const expires = performance.now() + timeoutMs;
|
|
30
|
+
const ended = (code: string, message: string) =>
|
|
31
|
+
new SessError('wait_ended', message, { code, sessionId: id, revision });
|
|
32
|
+
try {
|
|
33
|
+
for (;;) {
|
|
34
|
+
if (budget.signal.aborted) throw abortError(budget.signal);
|
|
35
|
+
const remainingMs = Math.ceil(expires - performance.now());
|
|
36
|
+
if (remainingMs <= 0)
|
|
37
|
+
throw ended('WAIT_TIMEOUT', 'Human wait timed out. Resume using the same Session and revision.');
|
|
38
|
+
const current = await retrieve({
|
|
39
|
+
signal: budget.signal,
|
|
40
|
+
operationTimeoutMs: Math.min(operationTimeoutMs, remainingMs),
|
|
41
|
+
maxRetries: options.maxRetries,
|
|
42
|
+
maxResponseBytes: options.maxResponseBytes,
|
|
43
|
+
});
|
|
44
|
+
if (!isInteractiveSession(current.data))
|
|
45
|
+
throw ended('NOT_INTERACTIVE', 'A display Session has no accepted human responses.');
|
|
46
|
+
const session = current.data;
|
|
47
|
+
const response = session.responses.find((item) => item.revision === revision);
|
|
48
|
+
// Retained history remains readable after a later revision or completion.
|
|
49
|
+
if (response) return { session, response, meta: current.meta };
|
|
50
|
+
if (session.status === 'completed')
|
|
51
|
+
throw ended(
|
|
52
|
+
'CLOSED_WITHOUT_RESPONSE',
|
|
53
|
+
'Session completed without an accepted response for this revision.',
|
|
54
|
+
);
|
|
55
|
+
if (session.revision > revision)
|
|
56
|
+
throw ended('REVISION_SUPERSEDED', 'The requested unanswered revision was superseded.');
|
|
57
|
+
await delay(
|
|
58
|
+
Math.min(
|
|
59
|
+
intervalMs + Math.floor(Math.random() * 150),
|
|
60
|
+
Math.max(1, Math.ceil(expires - performance.now())),
|
|
61
|
+
),
|
|
62
|
+
budget.signal,
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (options.signal?.aborted)
|
|
67
|
+
throw new SessError('aborted', 'Human wait was aborted. The Session remains available.', {
|
|
68
|
+
sessionId: id,
|
|
69
|
+
revision,
|
|
70
|
+
});
|
|
71
|
+
if (budget.signal.aborted || performance.now() >= expires)
|
|
72
|
+
throw ended('WAIT_TIMEOUT', 'Human wait timed out. Resume using the same Session and revision.');
|
|
73
|
+
throw error;
|
|
74
|
+
} finally {
|
|
75
|
+
budget.dispose();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export { verifyDecisionReceipt } from './verify.js';
|
|
2
|
+
export type {
|
|
3
|
+
ReceiptClaims,
|
|
4
|
+
ReceiptPublicKey,
|
|
5
|
+
ReceiptKeySet,
|
|
6
|
+
ReceiptKeyResolver,
|
|
7
|
+
VerifyDecisionReceiptInput,
|
|
8
|
+
VerifyDecisionReceiptOptions,
|
|
9
|
+
} from './verify.js';
|
|
10
|
+
export type { DeepReadonly } from './json.js';
|
|
11
|
+
export type {
|
|
12
|
+
ReceiptResource,
|
|
13
|
+
VerifyResponseInput,
|
|
14
|
+
VerifiedResponse,
|
|
15
|
+
VerificationRequestOptions,
|
|
16
|
+
} from './resource.js';
|