@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.
Files changed (95) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +9 -0
  4. package/README.md +136 -2
  5. package/dist/client.d.ts +12 -0
  6. package/dist/client.d.ts.map +1 -0
  7. package/dist/client.js +34 -0
  8. package/dist/client.js.map +1 -0
  9. package/dist/errors.d.ts +40 -0
  10. package/dist/errors.d.ts.map +1 -0
  11. package/dist/errors.js +52 -0
  12. package/dist/errors.js.map +1 -0
  13. package/dist/generated/openapi.d.ts +2462 -0
  14. package/dist/generated/openapi.d.ts.map +1 -0
  15. package/dist/generated/openapi.js +2 -0
  16. package/dist/generated/openapi.js.map +1 -0
  17. package/dist/index.d.ts +5 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +4 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/internal/decode.d.ts +21 -0
  22. package/dist/internal/decode.d.ts.map +1 -0
  23. package/dist/internal/decode.js +333 -0
  24. package/dist/internal/decode.js.map +1 -0
  25. package/dist/internal/json.d.ts +4 -0
  26. package/dist/internal/json.d.ts.map +1 -0
  27. package/dist/internal/json.js +75 -0
  28. package/dist/internal/json.js.map +1 -0
  29. package/dist/internal/time.d.ts +11 -0
  30. package/dist/internal/time.d.ts.map +1 -0
  31. package/dist/internal/time.js +71 -0
  32. package/dist/internal/time.js.map +1 -0
  33. package/dist/polling.d.ts +3 -0
  34. package/dist/polling.d.ts.map +1 -0
  35. package/dist/polling.js +61 -0
  36. package/dist/polling.js.map +1 -0
  37. package/dist/receipts/index.d.ts +5 -0
  38. package/dist/receipts/index.d.ts.map +1 -0
  39. package/dist/receipts/index.js +2 -0
  40. package/dist/receipts/index.js.map +1 -0
  41. package/dist/receipts/json.d.ts +22 -0
  42. package/dist/receipts/json.d.ts.map +1 -0
  43. package/dist/receipts/json.js +152 -0
  44. package/dist/receipts/json.js.map +1 -0
  45. package/dist/receipts/key-cache.d.ts +28 -0
  46. package/dist/receipts/key-cache.d.ts.map +1 -0
  47. package/dist/receipts/key-cache.js +110 -0
  48. package/dist/receipts/key-cache.js.map +1 -0
  49. package/dist/receipts/resource.d.ts +39 -0
  50. package/dist/receipts/resource.d.ts.map +1 -0
  51. package/dist/receipts/resource.js +119 -0
  52. package/dist/receipts/resource.js.map +1 -0
  53. package/dist/receipts/verify.d.ts +90 -0
  54. package/dist/receipts/verify.d.ts.map +1 -0
  55. package/dist/receipts/verify.js +294 -0
  56. package/dist/receipts/verify.js.map +1 -0
  57. package/dist/sessions.d.ts +19 -0
  58. package/dist/sessions.d.ts.map +1 -0
  59. package/dist/sessions.js +145 -0
  60. package/dist/sessions.js.map +1 -0
  61. package/dist/transport.d.ts +29 -0
  62. package/dist/transport.d.ts.map +1 -0
  63. package/dist/transport.js +447 -0
  64. package/dist/transport.js.map +1 -0
  65. package/dist/types.d.ts +149 -0
  66. package/dist/types.d.ts.map +1 -0
  67. package/dist/types.js +9 -0
  68. package/dist/types.js.map +1 -0
  69. package/dist/webhook-resource.d.ts +13 -0
  70. package/dist/webhook-resource.d.ts.map +1 -0
  71. package/dist/webhook-resource.js +52 -0
  72. package/dist/webhook-resource.js.map +1 -0
  73. package/dist/webhooks/index.d.ts +22 -0
  74. package/dist/webhooks/index.d.ts.map +1 -0
  75. package/dist/webhooks/index.js +184 -0
  76. package/dist/webhooks/index.js.map +1 -0
  77. package/package.json +74 -4
  78. package/src/client.ts +41 -0
  79. package/src/errors.ts +96 -0
  80. package/src/generated/openapi.ts +2578 -0
  81. package/src/index.ts +4 -0
  82. package/src/internal/decode.ts +317 -0
  83. package/src/internal/json.ts +64 -0
  84. package/src/internal/time.ts +85 -0
  85. package/src/polling.ts +77 -0
  86. package/src/receipts/index.ts +16 -0
  87. package/src/receipts/json.ts +168 -0
  88. package/src/receipts/key-cache.ts +143 -0
  89. package/src/receipts/resource.ts +227 -0
  90. package/src/receipts/verify.ts +468 -0
  91. package/src/sessions.ts +227 -0
  92. package/src/transport.ts +524 -0
  93. package/src/types.ts +135 -0
  94. package/src/webhook-resource.ts +81 -0
  95. package/src/webhooks/index.ts +246 -0
@@ -0,0 +1,145 @@
1
+ import { SessError } from './errors.js';
2
+ import { Transport, pathSegment } from './transport.js';
3
+ import { decodeCreate, decodeDeliveries, decodeEvents, decodeSession, decodeSurface, decodeRedelivery, } from './internal/decode.js';
4
+ import { boundedNumber } from './internal/time.js';
5
+ import { waitForResponse } from './polling.js';
6
+ function mutationIdentity(options) {
7
+ const source = options ?? {};
8
+ if (typeof source !== 'object' || Array.isArray(source))
9
+ throw new SessError('configuration', 'Mutation options must be an object.', { outcome: 'not_sent' });
10
+ // Inspect the two replay identity fields before spreading/accessing caller options.
11
+ // Accessor or inherited identities are not immutable primitive options.
12
+ for (const name of ['ifMatch', 'idempotencyKey']) {
13
+ const descriptor = Object.getOwnPropertyDescriptor(source, name);
14
+ if ((name in source && !descriptor) ||
15
+ (descriptor && !('value' in descriptor)) ||
16
+ (name === 'idempotencyKey' && descriptor && typeof descriptor.value !== 'string'))
17
+ throw new SessError('configuration', 'Mutation identity options must be primitive string data properties.', { outcome: 'not_sent' });
18
+ }
19
+ const { ifMatch, idempotencyKey, ...requestOptions } = source;
20
+ return { ifMatch, idempotencyKey, requestOptions };
21
+ }
22
+ export class Sessions {
23
+ #transport;
24
+ constructor(transport) {
25
+ this.#transport = transport;
26
+ }
27
+ /** Creates once. A lost reply may mean creation succeeded; no retry is safe. */
28
+ create(body, options = {}) {
29
+ if ('idempotencyKey' in options || 'ifMatch' in options)
30
+ return Promise.reject(new SessError('configuration', 'Session creation does not support idempotency keys or If-Match.', {
31
+ outcome: 'not_sent',
32
+ }));
33
+ return this.#transport.request({
34
+ name: 'sessions.create',
35
+ method: 'POST',
36
+ path: '/v1/sessions',
37
+ body,
38
+ status: 201,
39
+ versioned: true,
40
+ retry: 'never',
41
+ parse: (value) => decodeCreate(value, this.#transport.allowInsecureLocalhost),
42
+ }, options);
43
+ }
44
+ retrieve(id, options) {
45
+ return this.#transport.request({
46
+ name: 'sessions.retrieve',
47
+ method: 'GET',
48
+ path: `/v1/sessions/${pathSegment(id)}`,
49
+ status: 200,
50
+ versioned: true,
51
+ retry: 'safe',
52
+ parse: (value) => decodeSession(value, id),
53
+ }, options);
54
+ }
55
+ /** Full next interaction, with the original concurrency and replay identity. */
56
+ async publish(id, body, options) {
57
+ const { ifMatch, idempotencyKey, requestOptions } = mutationIdentity(options);
58
+ return this.#transport.request({
59
+ name: 'sessions.publish',
60
+ method: 'PATCH',
61
+ path: `/v1/sessions/${pathSegment(id)}`,
62
+ body,
63
+ ifMatch,
64
+ idempotencyKey,
65
+ status: 200,
66
+ versioned: true,
67
+ retry: 'mutation',
68
+ parse: (value) => {
69
+ const session = decodeSession(value, id);
70
+ if (!('status' in session) || session.status !== 'active')
71
+ throw new SessError('protocol', 'Publish did not return an active interactive Session.', {
72
+ code: 'INVALID_RESPONSE',
73
+ });
74
+ return session;
75
+ },
76
+ }, requestOptions);
77
+ }
78
+ async complete(id, options) {
79
+ const { ifMatch, idempotencyKey, requestOptions } = mutationIdentity(options);
80
+ return this.#transport.request({
81
+ name: 'sessions.complete',
82
+ method: 'POST',
83
+ path: `/v1/sessions/${pathSegment(id)}/complete`,
84
+ ifMatch,
85
+ idempotencyKey,
86
+ status: 200,
87
+ versioned: true,
88
+ retry: 'mutation',
89
+ parse: (value) => {
90
+ const session = decodeSession(value, id);
91
+ if (!('status' in session) || session.status !== 'completed')
92
+ throw new SessError('protocol', 'Complete did not return a completed interactive Session.', {
93
+ code: 'INVALID_RESPONSE',
94
+ });
95
+ return session;
96
+ },
97
+ }, requestOptions);
98
+ }
99
+ listEvents(id, options) {
100
+ return this.#transport.request({
101
+ name: 'sessions.listEvents',
102
+ method: 'GET',
103
+ path: `/v1/sessions/${pathSegment(id)}/events`,
104
+ status: 200,
105
+ retry: 'safe',
106
+ parse: (value) => decodeEvents(value, id),
107
+ }, options);
108
+ }
109
+ retrieveSurface(id, revision, options) {
110
+ boundedNumber(revision, 0, 'revision');
111
+ return this.#transport.request({
112
+ name: 'sessions.retrieveSurface',
113
+ method: 'GET',
114
+ path: `/v1/sessions/${pathSegment(id)}/surfaces/${revision}`,
115
+ status: 200,
116
+ retry: 'safe',
117
+ parse: (value) => decodeSurface(value, id, revision),
118
+ }, options);
119
+ }
120
+ listDeliveries(id, options) {
121
+ return this.#transport.request({
122
+ name: 'sessions.listDeliveries',
123
+ method: 'GET',
124
+ path: `/v1/sessions/${pathSegment(id)}/deliveries`,
125
+ status: 200,
126
+ retry: 'safe',
127
+ parse: (value) => decodeDeliveries(value, id),
128
+ }, options);
129
+ }
130
+ redeliverEvent(id, eventId, options) {
131
+ return this.#transport.request({
132
+ name: 'sessions.redeliverEvent',
133
+ method: 'POST',
134
+ path: `/v1/sessions/${pathSegment(id)}/events/${pathSegment(eventId)}/redeliver`,
135
+ status: 202,
136
+ retry: 'never',
137
+ parse: (value) => decodeRedelivery(value, eventId),
138
+ }, options);
139
+ }
140
+ /** Read-only, restartable wait for exactly one immutable revision. */
141
+ waitForResponse(id, options) {
142
+ return waitForResponse((requestOptions) => this.retrieve(id, requestOptions), id, options, this.#transport.operationTimeoutMs);
143
+ }
144
+ }
145
+ //# sourceMappingURL=sessions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sessions.js","sourceRoot":"","sources":["../src/sessions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,aAAa,EACb,gBAAgB,GACjB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE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BAAyB;YAC/B,MAAM,EAAE,MAAM;YACd,IAAI,EAAE,gBAAgB,WAAW,CAAC,EAAE,CAAC,WAAW,WAAW,CAAC,OAAO,CAAC,YAAY;YAChF,MAAM,EAAE,GAAG;YACX,KAAK,EAAE,OAAO;YACd,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,gBAAgB,CAAC,KAAK,EAAE,OAAO,CAAC;SACnD,EACD,OAAO,CACR,CAAC;IACJ,CAAC;IACD,sEAAsE;IACtE,eAAe,CAAC,EAAU,EAAE,OAAoB;QAC9C,OAAO,eAAe,CACpB,CAAC,cAAc,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,cAAc,CAAC,EACrD,EAAE,EACF,OAAO,EACP,IAAI,CAAC,UAAU,CAAC,kBAAkB,CACnC,CAAC;IACJ,CAAC;CACF"}
@@ -0,0 +1,29 @@
1
+ import type { ApiResult, RequestOptions, SessOptions } from './types.js';
2
+ export interface Operation<T> {
3
+ name: string;
4
+ method: 'GET' | 'POST' | 'PATCH' | 'PUT';
5
+ path: string;
6
+ status: number;
7
+ parse?: (value: unknown) => T;
8
+ body?: unknown;
9
+ versioned?: boolean;
10
+ retry: 'safe' | 'mutation' | 'never';
11
+ ifMatch?: string;
12
+ idempotencyKey?: string;
13
+ authenticated?: boolean;
14
+ }
15
+ export declare function strongETag(value: unknown): value is string;
16
+ export declare function pathSegment(value: string): string;
17
+ export declare function retryAfter(header: string | null): number | undefined;
18
+ /** Shared policy for owner operations and unauthenticated receipt-key reads. */
19
+ export declare class Transport {
20
+ #private;
21
+ readonly baseUrl: string;
22
+ readonly receiptIssuer: string;
23
+ readonly expectedWorkspaceId?: string;
24
+ readonly operationTimeoutMs: number;
25
+ readonly allowInsecureLocalhost: boolean;
26
+ constructor(options: SessOptions);
27
+ request<T>(operation: Operation<T>, inputOptions?: RequestOptions): Promise<ApiResult<T>>;
28
+ }
29
+ //# sourceMappingURL=transport.d.ts.map
@@ -0,0 +1 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AAC,CAAC,EAAE,YAAY,GAAE,cAAmB,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;CAySpG"}
@@ -0,0 +1,447 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { SessError, attachRecovery } 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
+ const transientStatuses = new Set([408, 429, 500, 502, 503, 504]);
7
+ const rejections = {
8
+ 400: ['INVALID_SCHEMA', 'UNKNOWN_COMPONENT', 'WEBHOOK_INVALID_URL'],
9
+ 401: ['UNAUTHORIZED'],
10
+ 403: ['ACTION_NOT_ALLOWED'],
11
+ 404: ['NOT_FOUND', 'SESSION_NOT_FOUND'],
12
+ 409: [
13
+ 'SESSION_REVISION_CONFLICT',
14
+ 'IDEMPOTENCY_CONFLICT',
15
+ 'SESSION_COMPLETED',
16
+ 'WEBHOOK_NOT_CONFIGURED',
17
+ 'RESPONSE_LIMIT_REACHED',
18
+ ],
19
+ 412: ['SESSION_REVISION_CONFLICT'],
20
+ 413: ['PAYLOAD_TOO_LARGE'],
21
+ 422: ['VALIDATION_FAILED', 'WEBHOOK_VERIFICATION_FAILED'],
22
+ 428: ['PRECONDITION_REQUIRED'],
23
+ };
24
+ function credential(value) {
25
+ if (typeof value !== 'string' || !/^[\x21-\x7e]{1,4096}$/.test(value)) {
26
+ throw new SessError('configuration', 'Supply a nonempty server-side SESS API key without whitespace or control characters.', { code: 'INVALID_API_KEY', outcome: 'not_sent' });
27
+ }
28
+ return value;
29
+ }
30
+ export function strongETag(value) {
31
+ return typeof value === 'string' && /^"[\x21\x23-\x7e\x80-\xff]{0,1024}"$/.test(value);
32
+ }
33
+ export function pathSegment(value) {
34
+ if (typeof value !== 'string' ||
35
+ !value.length ||
36
+ value.length > 512 ||
37
+ /[\u0000-\u0020\u007f]/.test(value) ||
38
+ value === '.' ||
39
+ value === '..') {
40
+ throw new SessError('configuration', 'Resource ID must be a nonempty path segment.', {
41
+ outcome: 'not_sent',
42
+ });
43
+ }
44
+ try {
45
+ return encodeURIComponent(value);
46
+ }
47
+ catch {
48
+ throw new SessError('configuration', 'Resource ID has invalid encoding.', { outcome: 'not_sent' });
49
+ }
50
+ }
51
+ function origin(input, allowInsecure) {
52
+ const text = input ?? 'https://api.sess.si';
53
+ let url;
54
+ try {
55
+ url = new URL(text);
56
+ }
57
+ catch {
58
+ throw new SessError('configuration', 'baseUrl must be a trusted absolute API origin.', {
59
+ outcome: 'not_sent',
60
+ });
61
+ }
62
+ if (text !== text.trim() ||
63
+ /[\u0000-\u0020\u007f\\]/.test(text) ||
64
+ url.username ||
65
+ url.password ||
66
+ url.search ||
67
+ url.hash ||
68
+ url.pathname !== '/' ||
69
+ !(url.protocol === 'https:' || (url.protocol === 'http:' && allowInsecure && isLoopback(url.hostname)))) {
70
+ 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' });
71
+ }
72
+ return url.origin;
73
+ }
74
+ function safeText(value, pattern, key, opaqueIdentifier = false) {
75
+ if (typeof value !== 'string' ||
76
+ !pattern.test(value) ||
77
+ /sess_(?:sk|mg|tk|mk)_|whsec_|eyJ/.test(value) ||
78
+ (opaqueIdentifier && /^[A-Za-z0-9_-]{43}$/.test(value)) ||
79
+ (key && value.includes(key)))
80
+ return undefined;
81
+ return value;
82
+ }
83
+ export function retryAfter(header) {
84
+ if (header === null)
85
+ return undefined;
86
+ if (/^\d+$/.test(header.trim())) {
87
+ const ms = Number(header.trim()) * 1000;
88
+ return Number.isSafeInteger(ms) ? ms : undefined;
89
+ }
90
+ // HTTP-date only; Date.parse alone also accepts misleading values such as "1.5".
91
+ if (!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(header))
92
+ return undefined;
93
+ const date = Date.parse(header);
94
+ return Number.isFinite(date) ? Math.max(0, date - Date.now()) : undefined;
95
+ }
96
+ async function readBody(response, maxBytes, signal) {
97
+ if (!response.body)
98
+ return '';
99
+ const reader = response.body.getReader();
100
+ const parts = [];
101
+ let bytes = 0;
102
+ let done = false;
103
+ try {
104
+ while (true) {
105
+ const result = await withSignal(reader.read().catch(() => {
106
+ throw new SessError('transport', 'API response stream failed.');
107
+ }), signal);
108
+ if (result.done) {
109
+ done = true;
110
+ break;
111
+ }
112
+ bytes += result.value.byteLength;
113
+ if (bytes > maxBytes)
114
+ throw new SessError('protocol', 'Response body exceeds the configured byte limit.', {
115
+ code: 'RESPONSE_TOO_LARGE',
116
+ });
117
+ parts.push(result.value);
118
+ }
119
+ try {
120
+ return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(parts, bytes));
121
+ }
122
+ catch {
123
+ throw new SessError('protocol', 'Response contains invalid UTF-8.', { code: 'INVALID_RESPONSE' });
124
+ }
125
+ }
126
+ finally {
127
+ if (!done)
128
+ void reader.cancel().catch(() => { });
129
+ try {
130
+ reader.releaseLock();
131
+ }
132
+ catch {
133
+ /* cancelled reader may still settle */
134
+ }
135
+ }
136
+ }
137
+ /** Shared policy for owner operations and unauthenticated receipt-key reads. */
138
+ export class Transport {
139
+ baseUrl;
140
+ receiptIssuer;
141
+ expectedWorkspaceId;
142
+ operationTimeoutMs;
143
+ allowInsecureLocalhost;
144
+ #apiKey;
145
+ #fetch;
146
+ #timeoutMs;
147
+ #maxRetries;
148
+ #maxResponseBytes;
149
+ #onRequestEvent;
150
+ constructor(options) {
151
+ if (!options || typeof options !== 'object')
152
+ throw new SessError('configuration', 'Sess options with apiKey are required.', { outcome: 'not_sent' });
153
+ this.#apiKey = typeof options.apiKey === 'function' ? options.apiKey : credential(options.apiKey);
154
+ this.allowInsecureLocalhost = options.allowInsecureLocalhost === true;
155
+ this.baseUrl = origin(options.baseUrl, this.allowInsecureLocalhost);
156
+ this.receiptIssuer = options.receiptIssuer ?? this.baseUrl;
157
+ if (typeof this.receiptIssuer !== 'string' ||
158
+ !this.receiptIssuer.length ||
159
+ this.receiptIssuer.length > 2048 ||
160
+ /[\u0000-\u0020\u007f]/.test(this.receiptIssuer))
161
+ throw new SessError('configuration', 'receiptIssuer must be a trusted nonempty protocol identity.', {
162
+ outcome: 'not_sent',
163
+ });
164
+ if (options.expectedWorkspaceId !== undefined &&
165
+ (typeof options.expectedWorkspaceId !== 'string' ||
166
+ !/^[A-Za-z0-9_:-]{1,128}$/.test(options.expectedWorkspaceId)))
167
+ throw new SessError('configuration', 'expectedWorkspaceId must be a trusted workspace identifier.', {
168
+ outcome: 'not_sent',
169
+ });
170
+ this.expectedWorkspaceId = options.expectedWorkspaceId;
171
+ this.#fetch = options.fetch ?? globalThis.fetch;
172
+ if (typeof this.#fetch !== 'function')
173
+ throw new SessError('configuration', 'A compatible fetch implementation is required.', {
174
+ outcome: 'not_sent',
175
+ });
176
+ this.#timeoutMs = boundedNumber(options.timeoutMs, 12000, 'timeoutMs');
177
+ this.operationTimeoutMs = boundedNumber(options.operationTimeoutMs, 30000, 'operationTimeoutMs');
178
+ this.#maxRetries = boundedNumber(options.maxRetries, 2, 'maxRetries', 0, 10);
179
+ this.#maxResponseBytes = boundedNumber(options.maxResponseBytes, 16 * 1024 * 1024, 'maxResponseBytes', 1, 256 * 1024 * 1024);
180
+ this.#onRequestEvent = options.onRequestEvent;
181
+ if (this.#onRequestEvent !== undefined && typeof this.#onRequestEvent !== 'function')
182
+ throw new SessError('configuration', 'onRequestEvent must be a function.', { outcome: 'not_sent' });
183
+ }
184
+ async request(operation, inputOptions = {}) {
185
+ // Capture every mutable input before the first asynchronous boundary.
186
+ const op = { ...operation };
187
+ const options = { ...inputOptions };
188
+ const isWrite = op.method !== 'GET';
189
+ const body = op.body === undefined ? undefined : serializeBody(op.body);
190
+ const timeoutMs = boundedNumber(options.timeoutMs, this.#timeoutMs, 'timeoutMs');
191
+ const totalMs = boundedNumber(options.operationTimeoutMs, this.operationTimeoutMs, 'operationTimeoutMs');
192
+ const retries = boundedNumber(options.maxRetries, this.#maxRetries, 'maxRetries', 0, 10);
193
+ const maxBytes = boundedNumber(options.maxResponseBytes, this.#maxResponseBytes, 'maxResponseBytes', 1, 256 * 1024 * 1024);
194
+ if ('headers' in options || 'baseUrl' in options || 'apiKey' in options)
195
+ throw new SessError('configuration', 'Per-request authentication, host, and header overrides are not supported.', { outcome: 'not_sent' });
196
+ if (options.signal !== undefined && !(options.signal instanceof AbortSignal))
197
+ throw new SessError('configuration', 'signal must be an AbortSignal.', { outcome: 'not_sent' });
198
+ if (!op.path.startsWith('/') ||
199
+ op.path.startsWith('//') ||
200
+ op.path.includes('#') ||
201
+ op.path.includes('?'))
202
+ throw new SessError('configuration', 'Invalid API resource path.', { outcome: 'not_sent' });
203
+ const headers = { Accept: 'application/json' };
204
+ if (body !== undefined)
205
+ headers['Content-Type'] = 'application/json';
206
+ let idempotencyKey;
207
+ if (op.retry === 'mutation') {
208
+ if (!strongETag(op.ifMatch))
209
+ throw new SessError('configuration', 'Publish and complete require an original strong quoted If-Match ETag.', { code: 'INVALID_IF_MATCH', outcome: 'not_sent' });
210
+ if (op.idempotencyKey !== undefined && typeof op.idempotencyKey !== 'string')
211
+ throw new SessError('configuration', 'idempotencyKey must be a primitive string.', {
212
+ outcome: 'not_sent',
213
+ });
214
+ idempotencyKey = op.idempotencyKey === undefined ? randomUUID() : op.idempotencyKey;
215
+ if (!/^[A-Za-z0-9_.:-]{1,128}$/.test(idempotencyKey))
216
+ throw new SessError('configuration', 'idempotencyKey must contain 1–128 characters using only letters, digits, underscore, period, colon, or hyphen.', { outcome: 'not_sent' });
217
+ headers['If-Match'] = op.ifMatch;
218
+ headers['Idempotency-Key'] = idempotencyKey;
219
+ }
220
+ const started = performance.now();
221
+ const expires = started + totalMs;
222
+ const whole = deadline(totalMs, options.signal);
223
+ let attempts = 0;
224
+ let dispatched = false;
225
+ let key;
226
+ let possiblePriorWrite = false;
227
+ try {
228
+ if (whole.signal.aborted)
229
+ throw abortError(whole.signal);
230
+ if (op.authenticated !== false) {
231
+ const suppliedKey = new Promise((resolve) => {
232
+ resolve(typeof this.#apiKey === 'function' ? this.#apiKey() : this.#apiKey);
233
+ }).catch(() => {
234
+ throw new SessError('configuration', 'The API credential provider did not supply a usable key.', {
235
+ code: 'CREDENTIAL_PROVIDER_FAILED',
236
+ outcome: 'not_sent',
237
+ });
238
+ });
239
+ key = credential(await withSignal(suppliedKey, whole.signal));
240
+ headers.Authorization = `Bearer ${key}`;
241
+ }
242
+ const budget = op.retry === 'never' ? 0 : retries;
243
+ for (;;) {
244
+ if (whole.signal.aborted)
245
+ throw abortError(whole.signal);
246
+ attempts++;
247
+ const attempt = deadline(Math.min(timeoutMs, Math.max(1, Math.ceil(expires - performance.now()))), whole.signal);
248
+ let retryable = false;
249
+ let response;
250
+ let error;
251
+ let recoveryBody;
252
+ try {
253
+ dispatched = true;
254
+ const pendingResponse = Promise.resolve()
255
+ .then(() => this.#fetch(`${this.baseUrl}${op.path}`, {
256
+ method: op.method,
257
+ headers: { ...headers },
258
+ ...(body !== undefined ? { body } : {}),
259
+ redirect: 'manual',
260
+ credentials: 'omit',
261
+ signal: attempt.signal,
262
+ }))
263
+ .catch(() => {
264
+ if (attempt.signal.aborted)
265
+ throw abortError(attempt.signal);
266
+ throw new SessError('transport', 'API transport failed.');
267
+ });
268
+ pendingResponse.then((r) => {
269
+ if (attempt.signal.aborted)
270
+ void r.body?.cancel().catch(() => { });
271
+ }, () => { });
272
+ response = await withSignal(pendingResponse, attempt.signal);
273
+ if (response.redirected || (response.status >= 300 && response.status < 400)) {
274
+ void response.body?.cancel().catch(() => { });
275
+ throw new SessError('protocol', 'Redirected API responses are refused.', {
276
+ code: 'REDIRECT_REFUSED',
277
+ status: response.status,
278
+ });
279
+ }
280
+ const requestId = safeText(response.headers.get('x-request-id'), /^[A-Za-z0-9._:-]{1,128}$/, key, true);
281
+ const retryAfterMs = retryAfter(response.headers.get('retry-after'));
282
+ const mediaType = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
283
+ const text = await readBody(response, response.ok ? maxBytes : Math.min(maxBytes, 65536), attempt.signal);
284
+ if (!response.ok) {
285
+ let remote = {};
286
+ if (mediaType === 'application/json') {
287
+ try {
288
+ const value = JSON.parse(text);
289
+ if (value.error && typeof value.error === 'object')
290
+ remote = value.error;
291
+ }
292
+ catch {
293
+ /* gateway/unusable body remains redacted */
294
+ }
295
+ }
296
+ const code = safeText(remote.code, /^[A-Z][A-Z0-9_]{0,95}$/, key);
297
+ const reason = safeText(remote.reason, /^[a-z_]{1,40}$/, key);
298
+ const remoteId = safeText(remote.request_id, /^[A-Za-z0-9._:-]{1,128}$/, key, true) ?? requestId;
299
+ const rejected = code !== undefined && rejections[response.status]?.includes(code);
300
+ retryable = transientStatuses.has(response.status);
301
+ throw new SessError('api', 'SESS API request failed. Inspect the safe status and code fields.', {
302
+ code,
303
+ reason,
304
+ status: response.status,
305
+ requestId: remoteId,
306
+ retryAfterMs,
307
+ outcome: isWrite ? (rejected && !possiblePriorWrite ? 'rejected' : 'unknown') : undefined,
308
+ });
309
+ }
310
+ if (response.status !== op.status)
311
+ throw new SessError('protocol', 'Unexpected API success status.', {
312
+ code: 'INVALID_RESPONSE',
313
+ status: response.status,
314
+ });
315
+ let data;
316
+ if (op.parse) {
317
+ if (mediaType !== 'application/json')
318
+ throw new SessError('protocol', 'Expected an application/json response.', {
319
+ code: 'INVALID_RESPONSE',
320
+ });
321
+ let parsed;
322
+ try {
323
+ parsed = JSON.parse(text);
324
+ }
325
+ catch {
326
+ throw new SessError('protocol', 'Response is not valid JSON.', { code: 'INVALID_RESPONSE' });
327
+ }
328
+ data = op.parse(parsed);
329
+ if (op.name === 'sessions.create')
330
+ recoveryBody = data;
331
+ }
332
+ else {
333
+ if (text.length !== 0)
334
+ throw new SessError('protocol', 'Expected an empty API success body.', {
335
+ code: 'INVALID_RESPONSE',
336
+ });
337
+ data = undefined;
338
+ }
339
+ const etag = response.headers.get('etag') ?? undefined;
340
+ if ((op.versioned || etag !== undefined) && !strongETag(etag))
341
+ throw new SessError('protocol', 'API response is missing a valid strong ETag.', {
342
+ code: 'INVALID_ETAG',
343
+ });
344
+ const workspaceHeader = response.headers.get('sess-workspace-id');
345
+ if (workspaceHeader !== null && !/^[A-Za-z0-9_:-]{1,128}$/.test(workspaceHeader))
346
+ throw new SessError('protocol', 'API response has an invalid workspace context.', {
347
+ code: 'INVALID_WORKSPACE_CONTEXT',
348
+ });
349
+ const meta = {
350
+ status: response.status,
351
+ attempts,
352
+ ...(etag ? { etag } : {}),
353
+ ...(requestId ? { requestId } : {}),
354
+ ...(workspaceHeader ? { workspaceId: workspaceHeader } : {}),
355
+ ...(idempotencyKey ? { idempotencyKey } : {}),
356
+ };
357
+ this.#observe(op.name, started, attempts, meta);
358
+ return { data, meta };
359
+ }
360
+ catch (e) {
361
+ if (e instanceof SessError)
362
+ error = e;
363
+ else {
364
+ error = new SessError(attempt.signal.aborted ? abortError(attempt.signal).kind : 'transport', attempt.signal.aborted
365
+ ? 'Request deadline or caller cancellation ended the local request.'
366
+ : 'API transport failed.');
367
+ retryable = true;
368
+ }
369
+ if (error.kind === 'timeout' || error.kind === 'transport')
370
+ retryable = true;
371
+ const outcome = isWrite ? (error.outcome ?? 'unknown') : undefined;
372
+ if (outcome === 'unknown')
373
+ possiblePriorWrite = true;
374
+ const details = {
375
+ code: error.code,
376
+ reason: error.reason,
377
+ status: error.status ?? response?.status,
378
+ requestId: error.requestId,
379
+ retryAfterMs: error.retryAfterMs,
380
+ operation: op.name,
381
+ attempts,
382
+ outcome,
383
+ idempotencyKey,
384
+ };
385
+ error = new SessError(op.name === 'sessions.create' && outcome === 'unknown' ? 'unknown_outcome' : error.kind, op.name === 'sessions.create' && outcome === 'unknown'
386
+ ? 'Session creation may have succeeded. Do not automatically create again; inspect recovery information if available.'
387
+ : error.message, details);
388
+ if (recoveryBody)
389
+ attachRecovery(error, recoveryBody);
390
+ this.#observe(op.name, started, attempts, details);
391
+ }
392
+ finally {
393
+ attempt.dispose();
394
+ }
395
+ if (!retryable || attempts > budget || whole.signal.aborted || options.signal?.aborted)
396
+ throw error;
397
+ const backoffMs = Math.ceil(200 * 2 ** (attempts - 1) + Math.random() * 100);
398
+ const waitMs = Math.max(backoffMs, error.retryAfterMs ?? 0);
399
+ if (waitMs >= expires - performance.now())
400
+ throw error;
401
+ await delay(waitMs, whole.signal);
402
+ }
403
+ }
404
+ catch (e) {
405
+ if (!(e instanceof SessError))
406
+ throw new SessError('transport', 'API operation failed.', {
407
+ operation: op.name,
408
+ attempts,
409
+ outcome: isWrite ? (dispatched ? 'unknown' : 'not_sent') : undefined,
410
+ idempotencyKey,
411
+ });
412
+ if (e.operation)
413
+ throw e;
414
+ throw new SessError(op.name === 'sessions.create' && dispatched ? 'unknown_outcome' : e.kind, op.name === 'sessions.create' && dispatched
415
+ ? 'Session creation may have succeeded. Do not automatically create again.'
416
+ : e.message, {
417
+ code: e.code,
418
+ reason: e.reason,
419
+ operation: op.name,
420
+ attempts,
421
+ outcome: isWrite ? (dispatched ? 'unknown' : 'not_sent') : undefined,
422
+ idempotencyKey,
423
+ });
424
+ }
425
+ finally {
426
+ whole.dispose();
427
+ }
428
+ }
429
+ #observe(operation, started, attempt, meta) {
430
+ try {
431
+ const result = this.#onRequestEvent?.(Object.freeze({
432
+ operation,
433
+ attempt,
434
+ durationMs: performance.now() - started,
435
+ status: meta.status,
436
+ code: meta.code,
437
+ requestId: meta.requestId,
438
+ }));
439
+ // An async callback's rejected promise cannot change request semantics either.
440
+ Promise.resolve(result).catch(() => { });
441
+ }
442
+ catch {
443
+ /* optional observer failures are isolated */
444
+ }
445
+ }
446
+ }
447
+ //# sourceMappingURL=transport.js.map