@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,511 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { SessError, attachRecovery, lengthMessage } from './errors.js';
3
+ import { isLoopback } from './internal/decode.js';
4
+ import { serializeBody } from './internal/json.js';
5
+ import { abortError, boundedNumber, deadline, delay, withSignal } from './internal/time.js';
6
+ import { SDK_VERSION } from './internal/version.js';
7
+ const transientStatuses = new Set([408, 429, 500, 502, 503, 504]);
8
+ const rejections = {
9
+ 400: ['INVALID_SCHEMA', 'UNKNOWN_COMPONENT', 'WEBHOOK_INVALID_URL'],
10
+ 401: ['UNAUTHORIZED'],
11
+ 403: ['ACTION_NOT_ALLOWED'],
12
+ 404: ['NOT_FOUND', 'SESSION_NOT_FOUND'],
13
+ 409: [
14
+ 'SESSION_REVISION_CONFLICT',
15
+ 'IDEMPOTENCY_CONFLICT',
16
+ 'SESSION_COMPLETED',
17
+ 'WEBHOOK_NOT_CONFIGURED',
18
+ 'RESPONSE_LIMIT_REACHED',
19
+ ],
20
+ 412: ['SESSION_REVISION_CONFLICT'],
21
+ 413: ['PAYLOAD_TOO_LARGE'],
22
+ 422: ['VALIDATION_FAILED', 'WEBHOOK_VERIFICATION_FAILED'],
23
+ 428: ['PRECONDITION_REQUIRED'],
24
+ // A plan limit refuses the create before anything is written: nothing is created. It is not a
25
+ // rate limit; a plain 429 (no code, or RATE_LIMITED) stays transient and its outcome uncertain.
26
+ 429: ['PLAN_LIMIT_REACHED'],
27
+ };
28
+ /** A 401 UNAUTHORIZED: Sess refused the API key. */
29
+ const UNAUTHORIZED_MESSAGE = 'Sess did not accept your API key. Check SESS_API_KEY and the portal you made it on.';
30
+ /** RFC 9110 product tokens (`name` or `name/version`), separated by single spaces. */
31
+ const PRODUCT = "[!#$%&'*+.^_`|~0-9A-Za-z-]+(?:/[!#$%&'*+.^_`|~0-9A-Za-z-]+)?";
32
+ const PRODUCTS = new RegExp(`^${PRODUCT}(?: ${PRODUCT})*$`);
33
+ /**
34
+ * The User-Agent: a wrapping client's tokens, then `sess-sdk/<version>`, then the runtime's
35
+ * `node/<version>` when there is one. Sess classifies the creating client by these tokens.
36
+ */
37
+ function userAgent(prefix) {
38
+ if (prefix !== undefined && (typeof prefix !== 'string' || prefix.length > 256 || !PRODUCTS.test(prefix)))
39
+ throw new SessError('configuration', 'userAgent must be one or more product tokens such as my-app/1.2.0, separated by single spaces.', { outcome: 'not_sent' });
40
+ const node = typeof process === 'undefined' ? undefined : process.versions?.node;
41
+ return [prefix, `sess-sdk/${SDK_VERSION}`, typeof node === 'string' ? `node/${node}` : undefined]
42
+ .filter((token) => token !== undefined)
43
+ .join(' ');
44
+ }
45
+ function credential(value) {
46
+ if (typeof value !== 'string' || !/^[\x21-\x7e]{1,4096}$/.test(value)) {
47
+ throw new SessError('configuration', 'Supply a Sess API key on the server. It must not be empty or contain whitespace or control characters.', { code: 'INVALID_API_KEY', outcome: 'not_sent' });
48
+ }
49
+ return value;
50
+ }
51
+ export function strongETag(value) {
52
+ return typeof value === 'string' && /^"[\x21\x23-\x7e\x80-\xff]{0,1024}"$/.test(value);
53
+ }
54
+ export function pathSegment(value) {
55
+ if (typeof value !== 'string' ||
56
+ !value.length ||
57
+ value.length > 512 ||
58
+ /[\u0000-\u0020\u007f]/.test(value) ||
59
+ value === '.' ||
60
+ value === '..') {
61
+ throw new SessError('configuration', 'Resource ID must be a nonempty path segment.', {
62
+ outcome: 'not_sent',
63
+ });
64
+ }
65
+ try {
66
+ return encodeURIComponent(value);
67
+ }
68
+ catch {
69
+ throw new SessError('configuration', 'Resource ID has invalid encoding.', { outcome: 'not_sent' });
70
+ }
71
+ }
72
+ function origin(input, allowInsecure) {
73
+ const text = input ?? 'https://api.sess.si';
74
+ let url;
75
+ try {
76
+ url = new URL(text);
77
+ }
78
+ catch {
79
+ throw new SessError('configuration', 'baseUrl must be a trusted absolute API origin.', {
80
+ outcome: 'not_sent',
81
+ });
82
+ }
83
+ if (text !== text.trim() ||
84
+ /[\u0000-\u0020\u007f\\]/.test(text) ||
85
+ url.username ||
86
+ url.password ||
87
+ url.search ||
88
+ url.hash ||
89
+ url.pathname !== '/' ||
90
+ !(url.protocol === 'https:' || (url.protocol === 'http:' && allowInsecure && isLoopback(url.hostname)))) {
91
+ throw new SessError('configuration', 'baseUrl requires HTTPS and an origin without credentials, path, query, or fragment. Only explicit loopback development may use HTTP.', { outcome: 'not_sent' });
92
+ }
93
+ return url.origin;
94
+ }
95
+ /** The request id the Sess API assigns: `req_` and a random UUID. */
96
+ const SESS_REQUEST_ID = /^req_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
97
+ function safeText(value, pattern, key, opaqueIdentifier = false) {
98
+ if (typeof value !== 'string' ||
99
+ !pattern.test(value) ||
100
+ /sess_(?:sk|mg|tk|mk)_|whsec_|eyJ/.test(value) ||
101
+ // A request identifier holding a run of 22 or more base64url characters may carry a reflected
102
+ // human-link token (22 for /n/ short links, 43 for /s/ links, alone or glued to more token
103
+ // characters), so it is withheld. Sess's own request ids, req_ and a lowercase UUID, are kept.
104
+ (opaqueIdentifier && /[A-Za-z0-9_-]{22,}/.test(value) && !SESS_REQUEST_ID.test(value)) ||
105
+ (key && value.includes(key)))
106
+ return undefined;
107
+ return value;
108
+ }
109
+ /** A JSON pointer into the request body: no controls or bidirectional overrides. */
110
+ const POINTER = /^(?:\/[^\u0000-\u001f\u007f-\u009f‪-‮⁦-⁩/]{0,128}){1,16}$/;
111
+ const count = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
112
+ /**
113
+ * The length detail of a 400 INVALID_SCHEMA for a value over its limit (field, limit, length):
114
+ * all three or none. Every other error carries none.
115
+ */
116
+ function lengthDetail(remote, code, key) {
117
+ if (code !== 'INVALID_SCHEMA')
118
+ return {};
119
+ const field = safeText(remote.field, POINTER, key);
120
+ const limit = count(remote.limit);
121
+ const length = count(remote.length);
122
+ return field !== undefined && limit !== undefined && length !== undefined && length > limit
123
+ ? { field, limit, length }
124
+ : {};
125
+ }
126
+ const lengthFields = (e) => e.field !== undefined ? { field: e.field, limit: e.limit, length: e.length } : {};
127
+ export function retryAfter(header) {
128
+ if (header === null)
129
+ return undefined;
130
+ if (/^\d+$/.test(header.trim())) {
131
+ const ms = Number(header.trim()) * 1000;
132
+ return Number.isSafeInteger(ms) ? ms : undefined;
133
+ }
134
+ // HTTP-date only; Date.parse alone also accepts misleading values such as "1.5".
135
+ if (!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(header))
136
+ return undefined;
137
+ const date = Date.parse(header);
138
+ return Number.isFinite(date) ? Math.max(0, date - Date.now()) : undefined;
139
+ }
140
+ /** An IMF-fixdate HTTP `Date` header in milliseconds since the epoch, or undefined. */
141
+ export function httpDate(header) {
142
+ if (header === null || !/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(header))
143
+ return undefined;
144
+ const date = Date.parse(header);
145
+ return Number.isFinite(date) ? date : undefined;
146
+ }
147
+ async function readBody(response, maxBytes, signal) {
148
+ if (!response.body)
149
+ return '';
150
+ const reader = response.body.getReader();
151
+ const parts = [];
152
+ let bytes = 0;
153
+ let done = false;
154
+ try {
155
+ while (true) {
156
+ const result = await withSignal(reader.read().catch(() => {
157
+ throw new SessError('transport', 'API response stream failed.');
158
+ }), signal);
159
+ if (result.done) {
160
+ done = true;
161
+ break;
162
+ }
163
+ bytes += result.value.byteLength;
164
+ if (bytes > maxBytes)
165
+ throw new SessError('protocol', 'Response body exceeds the configured byte limit.', {
166
+ code: 'RESPONSE_TOO_LARGE',
167
+ });
168
+ parts.push(result.value);
169
+ }
170
+ try {
171
+ return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(parts, bytes));
172
+ }
173
+ catch {
174
+ throw new SessError('protocol', 'Response contains invalid UTF-8.', { code: 'INVALID_RESPONSE' });
175
+ }
176
+ }
177
+ finally {
178
+ if (!done)
179
+ void reader.cancel().catch(() => { });
180
+ try {
181
+ reader.releaseLock();
182
+ }
183
+ catch {
184
+ /* cancelled reader may still settle */
185
+ }
186
+ }
187
+ }
188
+ /** Shared policy for owner operations and unauthenticated receipt-key reads. */
189
+ export class Transport {
190
+ baseUrl;
191
+ receiptIssuer;
192
+ expectedWorkspaceId;
193
+ operationTimeoutMs;
194
+ allowInsecureLocalhost;
195
+ #apiKey;
196
+ #fetch;
197
+ #timeoutMs;
198
+ #maxRetries;
199
+ #maxResponseBytes;
200
+ #onRequestEvent;
201
+ #userAgent;
202
+ constructor(options) {
203
+ if (!options || typeof options !== 'object')
204
+ throw new SessError('configuration', 'Sess options with apiKey are required.', { outcome: 'not_sent' });
205
+ this.#apiKey = typeof options.apiKey === 'function' ? options.apiKey : credential(options.apiKey);
206
+ this.allowInsecureLocalhost = options.allowInsecureLocalhost === true;
207
+ this.baseUrl = origin(options.baseUrl, this.allowInsecureLocalhost);
208
+ this.receiptIssuer = options.receiptIssuer ?? this.baseUrl;
209
+ if (typeof this.receiptIssuer !== 'string' ||
210
+ !this.receiptIssuer.length ||
211
+ this.receiptIssuer.length > 2048 ||
212
+ /[\u0000-\u0020\u007f]/.test(this.receiptIssuer))
213
+ throw new SessError('configuration', 'receiptIssuer must be a trusted nonempty protocol identity.', {
214
+ outcome: 'not_sent',
215
+ });
216
+ if (options.expectedWorkspaceId !== undefined &&
217
+ (typeof options.expectedWorkspaceId !== 'string' ||
218
+ !/^[A-Za-z0-9_:-]{1,128}$/.test(options.expectedWorkspaceId)))
219
+ throw new SessError('configuration', 'expectedWorkspaceId must be a trusted workspace identifier.', {
220
+ outcome: 'not_sent',
221
+ });
222
+ this.expectedWorkspaceId = options.expectedWorkspaceId;
223
+ this.#fetch = options.fetch ?? globalThis.fetch;
224
+ if (typeof this.#fetch !== 'function')
225
+ throw new SessError('configuration', 'A compatible fetch implementation is required.', {
226
+ outcome: 'not_sent',
227
+ });
228
+ this.#timeoutMs = boundedNumber(options.timeoutMs, 12000, 'timeoutMs');
229
+ this.operationTimeoutMs = boundedNumber(options.operationTimeoutMs, 30000, 'operationTimeoutMs');
230
+ this.#maxRetries = boundedNumber(options.maxRetries, 2, 'maxRetries', 0, 10);
231
+ this.#maxResponseBytes = boundedNumber(options.maxResponseBytes, 16 * 1024 * 1024, 'maxResponseBytes', 1, 256 * 1024 * 1024);
232
+ this.#userAgent = userAgent(options.userAgent);
233
+ this.#onRequestEvent = options.onRequestEvent;
234
+ if (this.#onRequestEvent !== undefined && typeof this.#onRequestEvent !== 'function')
235
+ throw new SessError('configuration', 'onRequestEvent must be a function.', { outcome: 'not_sent' });
236
+ }
237
+ async request(operation, inputOptions = {}) {
238
+ // Capture every mutable input before the first asynchronous boundary.
239
+ const op = { ...operation };
240
+ const options = { ...inputOptions };
241
+ const isWrite = op.method !== 'GET';
242
+ const body = op.body === undefined ? undefined : serializeBody(op.body);
243
+ const timeoutMs = boundedNumber(options.timeoutMs, this.#timeoutMs, 'timeoutMs');
244
+ const totalMs = boundedNumber(options.operationTimeoutMs, this.operationTimeoutMs, 'operationTimeoutMs');
245
+ const retries = boundedNumber(options.maxRetries, this.#maxRetries, 'maxRetries', 0, 10);
246
+ const maxBytes = boundedNumber(options.maxResponseBytes, this.#maxResponseBytes, 'maxResponseBytes', 1, 256 * 1024 * 1024);
247
+ if ('headers' in options || 'baseUrl' in options || 'apiKey' in options)
248
+ throw new SessError('configuration', 'Per-request authentication, host, and header overrides are not supported.', { outcome: 'not_sent' });
249
+ if (options.signal !== undefined && !(options.signal instanceof AbortSignal))
250
+ throw new SessError('configuration', 'signal must be an AbortSignal.', { outcome: 'not_sent' });
251
+ if (!op.path.startsWith('/') ||
252
+ op.path.startsWith('//') ||
253
+ op.path.includes('#') ||
254
+ op.path.includes('?'))
255
+ throw new SessError('configuration', 'Invalid API resource path.', { outcome: 'not_sent' });
256
+ const headers = { Accept: 'application/json', 'User-Agent': this.#userAgent };
257
+ if (body !== undefined)
258
+ headers['Content-Type'] = 'application/json';
259
+ let idempotencyKey;
260
+ if (op.retry === 'mutation') {
261
+ if (!strongETag(op.ifMatch))
262
+ throw new SessError('configuration', 'Publish and complete require an original strong quoted If-Match ETag.', { code: 'INVALID_IF_MATCH', outcome: 'not_sent' });
263
+ if (op.idempotencyKey !== undefined && typeof op.idempotencyKey !== 'string')
264
+ throw new SessError('configuration', 'idempotencyKey must be a primitive string.', {
265
+ outcome: 'not_sent',
266
+ });
267
+ idempotencyKey = op.idempotencyKey === undefined ? randomUUID() : op.idempotencyKey;
268
+ if (!/^[A-Za-z0-9_.:-]{1,128}$/.test(idempotencyKey))
269
+ throw new SessError('configuration', 'idempotencyKey must contain 1–128 characters using only letters, digits, underscore, period, colon, or hyphen.', { outcome: 'not_sent' });
270
+ headers['If-Match'] = op.ifMatch;
271
+ headers['Idempotency-Key'] = idempotencyKey;
272
+ }
273
+ const started = performance.now();
274
+ const expires = started + totalMs;
275
+ const whole = deadline(totalMs, options.signal);
276
+ let attempts = 0;
277
+ let dispatched = false;
278
+ let key;
279
+ let possiblePriorWrite = false;
280
+ try {
281
+ if (whole.signal.aborted)
282
+ throw abortError(whole.signal);
283
+ if (op.authenticated !== false) {
284
+ const suppliedKey = new Promise((resolve) => {
285
+ resolve(typeof this.#apiKey === 'function' ? this.#apiKey() : this.#apiKey);
286
+ }).catch(() => {
287
+ throw new SessError('configuration', 'The API credential provider did not supply a usable key.', {
288
+ code: 'CREDENTIAL_PROVIDER_FAILED',
289
+ outcome: 'not_sent',
290
+ });
291
+ });
292
+ key = credential(await withSignal(suppliedKey, whole.signal));
293
+ headers.Authorization = `Bearer ${key}`;
294
+ }
295
+ const budget = op.retry === 'never' ? 0 : retries;
296
+ for (;;) {
297
+ if (whole.signal.aborted)
298
+ throw abortError(whole.signal);
299
+ attempts++;
300
+ const attempt = deadline(Math.min(timeoutMs, Math.max(1, Math.ceil(expires - performance.now()))), whole.signal);
301
+ let retryable = false;
302
+ let response;
303
+ let error;
304
+ let recoveryBody;
305
+ try {
306
+ dispatched = true;
307
+ const pendingResponse = Promise.resolve()
308
+ .then(() => this.#fetch(`${this.baseUrl}${op.path}`, {
309
+ method: op.method,
310
+ headers: { ...headers },
311
+ ...(body !== undefined ? { body } : {}),
312
+ redirect: 'manual',
313
+ credentials: 'omit',
314
+ signal: attempt.signal,
315
+ }))
316
+ .catch(() => {
317
+ if (attempt.signal.aborted)
318
+ throw abortError(attempt.signal);
319
+ throw new SessError('transport', 'API transport failed.');
320
+ });
321
+ pendingResponse.then((r) => {
322
+ if (attempt.signal.aborted)
323
+ void r.body?.cancel().catch(() => { });
324
+ }, () => { });
325
+ response = await withSignal(pendingResponse, attempt.signal);
326
+ if (response.redirected || (response.status >= 300 && response.status < 400)) {
327
+ void response.body?.cancel().catch(() => { });
328
+ throw new SessError('protocol', 'Redirected API responses are refused.', {
329
+ code: 'REDIRECT_REFUSED',
330
+ status: response.status,
331
+ });
332
+ }
333
+ const requestId = safeText(response.headers.get('x-request-id'), /^[A-Za-z0-9._:-]{1,128}$/, key, true);
334
+ const retryAfterMs = retryAfter(response.headers.get('retry-after'));
335
+ const mediaType = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
336
+ const text = await readBody(response, response.ok ? maxBytes : Math.min(maxBytes, 65536), attempt.signal);
337
+ if (!response.ok) {
338
+ let remote = {};
339
+ if (mediaType === 'application/json') {
340
+ try {
341
+ const value = JSON.parse(text);
342
+ if (value.error && typeof value.error === 'object')
343
+ remote = value.error;
344
+ }
345
+ catch {
346
+ /* gateway/unusable body remains redacted */
347
+ }
348
+ }
349
+ const code = safeText(remote.code, /^[A-Z][A-Z0-9_]{0,95}$/, key);
350
+ const reason = safeText(remote.reason, /^[a-z_]{1,40}$/, key);
351
+ const remoteId = safeText(remote.request_id, /^[A-Za-z0-9._:-]{1,128}$/, key, true) ?? requestId;
352
+ const rejected = code !== undefined && rejections[response.status]?.includes(code);
353
+ // A definite coded refusal is final: repeating it cannot succeed, so it is never retried.
354
+ retryable = transientStatuses.has(response.status) && !rejected;
355
+ const length = lengthDetail(remote, code, key);
356
+ const message = length.field !== undefined
357
+ ? lengthMessage(length.field, length.limit, length.length)
358
+ : response.status === 401 && code === 'UNAUTHORIZED'
359
+ ? UNAUTHORIZED_MESSAGE
360
+ : 'The Sess API returned an error. See the status and code fields.';
361
+ throw new SessError('api', message, {
362
+ code,
363
+ reason,
364
+ ...length,
365
+ status: response.status,
366
+ requestId: remoteId,
367
+ retryAfterMs,
368
+ outcome: isWrite ? (rejected && !possiblePriorWrite ? 'rejected' : 'unknown') : undefined,
369
+ });
370
+ }
371
+ if (response.status !== op.status)
372
+ throw new SessError('protocol', 'Unexpected API success status.', {
373
+ code: 'INVALID_RESPONSE',
374
+ status: response.status,
375
+ });
376
+ let data;
377
+ if (op.parse) {
378
+ if (mediaType !== 'application/json')
379
+ throw new SessError('protocol', 'Expected an application/json response.', {
380
+ code: 'INVALID_RESPONSE',
381
+ });
382
+ let parsed;
383
+ try {
384
+ parsed = JSON.parse(text);
385
+ }
386
+ catch {
387
+ throw new SessError('protocol', 'Response is not valid JSON.', { code: 'INVALID_RESPONSE' });
388
+ }
389
+ data = op.parse(parsed);
390
+ if (op.name === 'sessions.create')
391
+ recoveryBody = data;
392
+ }
393
+ else {
394
+ if (text.length !== 0)
395
+ throw new SessError('protocol', 'Expected an empty API success body.', {
396
+ code: 'INVALID_RESPONSE',
397
+ });
398
+ data = undefined;
399
+ }
400
+ const etag = response.headers.get('etag') ?? undefined;
401
+ if ((op.versioned || etag !== undefined) && !strongETag(etag))
402
+ throw new SessError('protocol', 'API response is missing a valid strong ETag.', {
403
+ code: 'INVALID_ETAG',
404
+ });
405
+ const workspaceHeader = response.headers.get('sess-workspace-id');
406
+ if (workspaceHeader !== null && !/^[A-Za-z0-9_:-]{1,128}$/.test(workspaceHeader))
407
+ throw new SessError('protocol', 'API response has an invalid workspace context.', {
408
+ code: 'INVALID_WORKSPACE_CONTEXT',
409
+ });
410
+ const serverDate = httpDate(response.headers.get('date'));
411
+ const meta = {
412
+ status: response.status,
413
+ attempts,
414
+ ...(serverDate !== undefined ? { serverDate } : {}),
415
+ ...(etag ? { etag } : {}),
416
+ ...(requestId ? { requestId } : {}),
417
+ ...(workspaceHeader ? { workspaceId: workspaceHeader } : {}),
418
+ ...(idempotencyKey ? { idempotencyKey } : {}),
419
+ };
420
+ this.#observe(op.name, started, attempts, meta);
421
+ return { data, meta };
422
+ }
423
+ catch (e) {
424
+ if (e instanceof SessError)
425
+ error = e;
426
+ else {
427
+ error = new SessError(attempt.signal.aborted ? abortError(attempt.signal).kind : 'transport', attempt.signal.aborted
428
+ ? 'Request deadline or caller cancellation ended the local request.'
429
+ : 'API transport failed.');
430
+ retryable = true;
431
+ }
432
+ if (error.kind === 'timeout' || error.kind === 'transport')
433
+ retryable = true;
434
+ const outcome = isWrite ? (error.outcome ?? 'unknown') : undefined;
435
+ if (outcome === 'unknown')
436
+ possiblePriorWrite = true;
437
+ const details = {
438
+ code: error.code,
439
+ reason: error.reason,
440
+ ...lengthFields(error),
441
+ status: error.status ?? response?.status,
442
+ requestId: error.requestId,
443
+ retryAfterMs: error.retryAfterMs,
444
+ operation: op.name,
445
+ attempts,
446
+ outcome,
447
+ idempotencyKey,
448
+ };
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.'
451
+ : error.message, details);
452
+ if (recoveryBody)
453
+ attachRecovery(error, recoveryBody);
454
+ this.#observe(op.name, started, attempts, details);
455
+ }
456
+ finally {
457
+ attempt.dispose();
458
+ }
459
+ if (!retryable || attempts > budget || whole.signal.aborted || options.signal?.aborted)
460
+ throw error;
461
+ const backoffMs = Math.ceil(200 * 2 ** (attempts - 1) + Math.random() * 100);
462
+ const waitMs = Math.max(backoffMs, error.retryAfterMs ?? 0);
463
+ if (waitMs >= expires - performance.now())
464
+ throw error;
465
+ await delay(waitMs, whole.signal);
466
+ }
467
+ }
468
+ catch (e) {
469
+ if (!(e instanceof SessError))
470
+ throw new SessError('transport', 'API operation failed.', {
471
+ operation: op.name,
472
+ attempts,
473
+ outcome: isWrite ? (dispatched ? 'unknown' : 'not_sent') : undefined,
474
+ idempotencyKey,
475
+ });
476
+ if (e.operation)
477
+ 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.'
480
+ : e.message, {
481
+ code: e.code,
482
+ reason: e.reason,
483
+ ...lengthFields(e),
484
+ operation: op.name,
485
+ attempts,
486
+ outcome: isWrite ? (dispatched ? 'unknown' : 'not_sent') : undefined,
487
+ idempotencyKey,
488
+ });
489
+ }
490
+ finally {
491
+ whole.dispose();
492
+ }
493
+ }
494
+ #observe(operation, started, attempt, meta) {
495
+ try {
496
+ const result = this.#onRequestEvent?.(Object.freeze({
497
+ operation,
498
+ attempt,
499
+ durationMs: performance.now() - started,
500
+ status: meta.status,
501
+ code: meta.code,
502
+ requestId: meta.requestId,
503
+ }));
504
+ // An async callback's rejected promise cannot change request semantics either.
505
+ Promise.resolve(result).catch(() => { });
506
+ }
507
+ catch {
508
+ /* optional observer failures are isolated */
509
+ }
510
+ }
511
+ }