@contello/client 2.2.2 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1135 +1,967 @@
1
- // src/client.ts
1
+ import { createOperationTelemetry, graphqlOperationAttributes, injectTraceContext } from "@contello/opentelemetry";
2
2
  import { createClient } from "graphql-ws";
3
-
4
- // src/async-iterable-utils.ts
5
- var MAX_BACKOFF_MS = 3e4;
6
- var JITTER_MIN_MS = 300;
7
- var JITTER_MAX_MS = 3e3;
3
+ import { Agent, request } from "undici";
4
+ //#region src/async-iterable-utils.ts
5
+ const MAX_BACKOFF_MS = 3e4;
6
+ const JITTER_MIN_MS$1 = 300;
7
+ const JITTER_MAX_MS$1 = 3e3;
8
+ /**
9
+ * Returns the first value yielded by `iter`, then disposes the iterator. Throws if the iterable
10
+ * completes without yielding. Equivalent of rxjs's `firstValueFrom` for AsyncIterables.
11
+ */
8
12
  async function firstAsync(iter) {
9
- const it = iter[Symbol.asyncIterator]();
10
- try {
11
- const result = await it.next();
12
- if (result.done) {
13
- throw new Error("firstAsync: async iterable completed without yielding a value");
14
- }
15
- return result.value;
16
- } finally {
17
- await it.return?.();
18
- }
19
- }
13
+ const it = iter[Symbol.asyncIterator]();
14
+ try {
15
+ const result = await it.next();
16
+ if (result.done) throw new Error("firstAsync: async iterable completed without yielding a value");
17
+ return result.value;
18
+ } finally {
19
+ await it.return?.();
20
+ }
21
+ }
22
+ /** Lazy map over an async iterable. Cleanup propagates: breaking the outer iter disposes the inner. */
20
23
  async function* mapAsync(iter, fn) {
21
- for await (const value of iter) {
22
- yield fn(value);
23
- }
24
+ for await (const value of iter) yield fn(value);
24
25
  }
26
+ /** Lazy filter over an async iterable. */
25
27
  async function* filterAsync(iter, predicate) {
26
- for await (const value of iter) {
27
- if (predicate(value)) {
28
- yield value;
29
- }
30
- }
28
+ for await (const value of iter) if (predicate(value)) yield value;
31
29
  }
30
+ /**
31
+ * Concatenates all elements of all arrays yielded by `iter` into a single array. Used to support
32
+ * subscriptions that emit chunks of items before completing.
33
+ */
32
34
  async function collectAsync(iter) {
33
- const out = [];
34
- for await (const chunk of iter) {
35
- out.push(...chunk);
36
- }
37
- return out;
38
- }
35
+ const out = [];
36
+ for await (const chunk of iter) out.push(...chunk);
37
+ return out;
38
+ }
39
+ /**
40
+ * Exponential backoff with jitter. `attempt` starts at 0 → ~1s+jitter, 1 → ~2s+jitter, etc.,
41
+ * capped at 30s. Returns a Promise that resolves after the delay.
42
+ */
39
43
  function exponentialBackoff(attempt) {
40
- const base = Math.min(Math.pow(2, attempt) * 1e3, MAX_BACKOFF_MS);
41
- const jitter = Math.floor(Math.random() * (JITTER_MAX_MS - JITTER_MIN_MS) + JITTER_MIN_MS);
42
- return delay(base + jitter);
44
+ return delay(Math.min(Math.pow(2, attempt) * 1e3, MAX_BACKOFF_MS) + Math.floor(Math.random() * (JITTER_MAX_MS$1 - JITTER_MIN_MS$1) + JITTER_MIN_MS$1));
43
45
  }
44
46
  function delay(ms, signal) {
45
- if (signal?.aborted) {
46
- return Promise.reject(signal.reason);
47
- }
48
- return new Promise((resolve, reject) => {
49
- const timer = setTimeout(() => {
50
- signal?.removeEventListener("abort", onAbort);
51
- resolve();
52
- }, ms);
53
- const onAbort = () => {
54
- clearTimeout(timer);
55
- reject(signal.reason);
56
- };
57
- signal?.addEventListener("abort", onAbort, { once: true });
58
- });
59
- }
47
+ if (signal?.aborted) return Promise.reject(signal.reason);
48
+ return new Promise((resolve, reject) => {
49
+ const timer = setTimeout(() => {
50
+ signal?.removeEventListener("abort", onAbort);
51
+ resolve();
52
+ }, ms);
53
+ const onAbort = () => {
54
+ clearTimeout(timer);
55
+ reject(signal.reason);
56
+ };
57
+ signal?.addEventListener("abort", onAbort, { once: true });
58
+ });
59
+ }
60
+ /**
61
+ * Runs `fn` with exponential-backoff retry on rejection. Returns once `fn` resolves successfully.
62
+ * `signal` aborts both the in-flight `fn` (if it observes the signal) and the backoff wait.
63
+ */
60
64
  async function runWithBackoff(fn, signal) {
61
- let attempt = 0;
62
- for (; ; ) {
63
- if (signal?.aborted) {
64
- throw signal.reason;
65
- }
66
- try {
67
- await fn();
68
- return;
69
- } catch {
70
- await exponentialBackoffWithSignal(attempt, signal);
71
- attempt++;
72
- }
73
- }
65
+ let attempt = 0;
66
+ for (;;) {
67
+ if (signal?.aborted) throw signal.reason;
68
+ try {
69
+ await fn();
70
+ return;
71
+ } catch {
72
+ await exponentialBackoffWithSignal(attempt, signal);
73
+ attempt++;
74
+ }
75
+ }
74
76
  }
75
77
  function exponentialBackoffWithSignal(attempt, signal) {
76
- const base = Math.min(Math.pow(2, attempt) * 1e3, MAX_BACKOFF_MS);
77
- const jitter = Math.floor(Math.random() * (JITTER_MAX_MS - JITTER_MIN_MS) + JITTER_MIN_MS);
78
- return delay(base + jitter, signal);
78
+ return delay(Math.min(Math.pow(2, attempt) * 1e3, MAX_BACKOFF_MS) + Math.floor(Math.random() * (JITTER_MAX_MS$1 - JITTER_MIN_MS$1) + JITTER_MIN_MS$1), signal);
79
79
  }
80
+ /**
81
+ * Long-running stream wrapper: subscribes via `factory()`, yields every value, and on error or
82
+ * unexpected completion re-subscribes with exponential backoff. Stops only when `signal` aborts.
83
+ * Designed for subscriptions that should stay open across reconnects (e.g. the watcher).
84
+ */
80
85
  async function* asyncKeepalive(factory, signal) {
81
- let attempt = 0;
82
- while (!signal?.aborted) {
83
- try {
84
- for await (const value of factory()) {
85
- if (signal?.aborted) {
86
- return;
87
- }
88
- yield value;
89
- attempt = 0;
90
- }
91
- attempt = 0;
92
- } catch (error) {
93
- if (signal?.aborted) {
94
- return;
95
- }
96
- void error;
97
- await exponentialBackoffWithSignal(attempt, signal);
98
- attempt++;
99
- }
100
- }
101
- }
102
-
103
- // src/diagnostics.ts
104
- import dc from "diagnostics_channel";
105
- var channels = {
106
- start: "@contello/client:start",
107
- end: "@contello/client:end",
108
- error: "@contello/client:error",
109
- /** subscribe to decorate outgoing GraphQL WebSocket messages (e.g. inject traceparent) */
110
- message: "@contello/client:message"
111
- };
112
- var onStart = dc.channel(channels.start);
113
- var onEnd = dc.channel(channels.end);
114
- var onError = dc.channel(channels.error);
115
- var onMessage = dc.channel(channels.message);
116
- function hasOperationSubscribers() {
117
- return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
118
- }
119
- function wrap(name, fn) {
120
- if (!hasOperationSubscribers()) {
121
- return fn();
122
- }
123
- const start = performance.now();
124
- onStart.publish({ name });
125
- let result;
126
- try {
127
- result = fn();
128
- } catch (error) {
129
- onError.publish({ name, error, durationMs: performance.now() - start });
130
- throw error;
131
- }
132
- if (result instanceof Promise) {
133
- return result.then(
134
- (r) => {
135
- onEnd.publish({ name, durationMs: performance.now() - start });
136
- return r;
137
- },
138
- (error) => {
139
- onError.publish({ name, error, durationMs: performance.now() - start });
140
- throw error;
141
- }
142
- );
143
- }
144
- onEnd.publish({ name, durationMs: performance.now() - start });
145
- return result;
146
- }
147
- function decorateMessage(message) {
148
- if (!onMessage.hasSubscribers) {
149
- return message;
150
- }
151
- const msg = { message };
152
- onMessage.publish(msg);
153
- return msg.message;
154
- }
155
-
156
- // src/http.ts
157
- import { Agent, request as undiciRequest } from "undici";
158
- var SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
159
- var FORWARDED_PROXY_HEADERS = /* @__PURE__ */ new Set([
160
- "content-type",
161
- "content-length",
162
- "content-range",
163
- "content-encoding",
164
- "accept-ranges",
165
- "cache-control",
166
- "etag",
167
- "last-modified",
168
- "expires",
169
- "age"
86
+ let attempt = 0;
87
+ while (!signal?.aborted) try {
88
+ for await (const value of factory()) {
89
+ if (signal?.aborted) return;
90
+ yield value;
91
+ attempt = 0;
92
+ }
93
+ attempt = 0;
94
+ } catch (error) {
95
+ if (signal?.aborted) return;
96
+ await exponentialBackoffWithSignal(attempt, signal);
97
+ attempt++;
98
+ }
99
+ }
100
+ //#endregion
101
+ //#region src/http.ts
102
+ const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
103
+ const FORWARDED_PROXY_HEADERS = /* @__PURE__ */ new Set([
104
+ "content-type",
105
+ "content-length",
106
+ "content-range",
107
+ "content-encoding",
108
+ "accept-ranges",
109
+ "cache-control",
110
+ "etag",
111
+ "last-modified",
112
+ "expires",
113
+ "age"
170
114
  ]);
171
115
  function assertSafeSegment(segment, kind) {
172
- if (!SAFE_SEGMENT.test(segment) || segment === "." || segment === "..") {
173
- throw new Error(`invalid ${kind}`);
174
- }
116
+ if (!SAFE_SEGMENT.test(segment) || segment === "." || segment === "..") throw new Error(`invalid ${kind}`);
175
117
  }
176
118
  function assertSafeAssetPath(path, kind) {
177
- if (path === "") {
178
- throw new Error(`invalid ${kind}`);
179
- }
180
- for (const segment of path.split("/")) {
181
- assertSafeSegment(segment, kind);
182
- }
119
+ if (path === "") throw new Error(`invalid ${kind}`);
120
+ for (const segment of path.split("/")) assertSafeSegment(segment, kind);
183
121
  }
184
122
  function createHttpAgent(options) {
185
- return new Agent({
186
- pipelining: options?.pipelining ?? 10,
187
- allowH2: options?.allowH2 ?? true,
188
- maxConcurrentStreams: options?.maxConcurrentStreams ?? 128,
189
- keepAliveTimeout: options?.keepAliveTimeout ?? 6e4,
190
- autoSelectFamily: true,
191
- autoSelectFamilyAttemptTimeout: 25
192
- });
123
+ return new Agent({
124
+ pipelining: options?.pipelining ?? 10,
125
+ allowH2: options?.allowH2 ?? true,
126
+ maxConcurrentStreams: options?.maxConcurrentStreams ?? 128,
127
+ keepAliveTimeout: options?.keepAliveTimeout ?? 6e4,
128
+ autoSelectFamily: true,
129
+ autoSelectFamilyAttemptTimeout: 25
130
+ });
193
131
  }
194
132
  async function downloadFile(agent, url, token, fileId) {
195
- assertSafeSegment(fileId, "file id");
196
- const response = await undiciRequest(`${url}/api/v1/assets/files/${fileId}`, {
197
- headers: { token },
198
- dispatcher: agent
199
- });
200
- if (response.statusCode < 200 || response.statusCode >= 300) {
201
- safeDestroyBody(response.body);
202
- throw new Error(`download failed: ${response.statusCode}`);
203
- }
204
- const mimeType = firstHeader(response.headers, "content-type") ?? "application/octet-stream";
205
- const size = Number(firstHeader(response.headers, "content-length") ?? 0);
206
- return {
207
- mimeType,
208
- size,
209
- bytes: async () => new Uint8Array(await response.body.arrayBuffer()),
210
- stream: () => toWebStream(response.body)
211
- };
133
+ assertSafeSegment(fileId, "file id");
134
+ const response = await request(`${url}/api/v1/assets/files/${fileId}`, {
135
+ headers: { token },
136
+ dispatcher: agent
137
+ });
138
+ if (response.statusCode < 200 || response.statusCode >= 300) {
139
+ safeDestroyBody(response.body);
140
+ throw new Error(`download failed: ${response.statusCode}`);
141
+ }
142
+ return {
143
+ mimeType: firstHeader(response.headers, "content-type") ?? "application/octet-stream",
144
+ size: Number(firstHeader(response.headers, "content-length") ?? 0),
145
+ bytes: async () => new Uint8Array(await response.body.arrayBuffer()),
146
+ stream: () => toWebStream(response.body)
147
+ };
212
148
  }
213
149
  async function proxyHls(agent, url, token, path, signal) {
214
- assertSafeAssetPath(path, "hls path");
215
- const response = await undiciRequest(`${url}/api/v1/assets/video/hls/${path}`, {
216
- headers: { token },
217
- dispatcher: agent,
218
- signal: signal ?? null
219
- });
220
- return buildProxyResult(response, signal);
150
+ assertSafeAssetPath(path, "hls path");
151
+ return buildProxyResult(await request(`${url}/api/v1/assets/video/hls/${path}`, {
152
+ headers: { token },
153
+ dispatcher: agent,
154
+ signal: signal ?? null
155
+ }), signal);
221
156
  }
222
157
  function buildProxyResult(response, signal) {
223
- const headers = new Headers();
224
- for (const [key, value] of Object.entries(response.headers)) {
225
- if (!FORWARDED_PROXY_HEADERS.has(key.toLowerCase())) {
226
- continue;
227
- }
228
- if (Array.isArray(value)) {
229
- for (const v of value) headers.append(key, v);
230
- } else if (value !== null && value !== void 0) {
231
- headers.set(key, String(value));
232
- }
233
- }
234
- return {
235
- status: response.statusCode,
236
- headers,
237
- stream: () => toWebStream(response.body, signal)
238
- };
158
+ const headers = new Headers();
159
+ for (const [key, value] of Object.entries(response.headers)) {
160
+ if (!FORWARDED_PROXY_HEADERS.has(key.toLowerCase())) continue;
161
+ if (Array.isArray(value)) for (const v of value) headers.append(key, v);
162
+ else if (value !== null && value !== void 0) headers.set(key, value);
163
+ }
164
+ return {
165
+ status: response.statusCode,
166
+ headers,
167
+ stream: () => toWebStream(response.body, signal)
168
+ };
239
169
  }
240
170
  function firstHeader(headers, key) {
241
- const v = headers[key];
242
- return Array.isArray(v) ? v[0] : v;
171
+ const v = headers[key];
172
+ return Array.isArray(v) ? v[0] : v;
243
173
  }
244
174
  function safeDestroyBody(body) {
245
- try {
246
- body.on("error", () => {
247
- });
248
- body.destroy();
249
- } catch {
250
- }
175
+ try {
176
+ body.on("error", () => {});
177
+ body.destroy();
178
+ } catch {}
251
179
  }
252
180
  function toWebStream(body, signal) {
253
- let closed = false;
254
- const cleanup = () => {
255
- if (!closed) {
256
- closed = true;
257
- signal?.removeEventListener("abort", cleanup);
258
- safeDestroyBody(body);
259
- }
260
- };
261
- return new ReadableStream({
262
- start(controller) {
263
- signal?.addEventListener("abort", cleanup);
264
- body.on("data", (chunk) => {
265
- if (!closed && !signal?.aborted) {
266
- try {
267
- controller.enqueue(chunk);
268
- } catch {
269
- cleanup();
270
- }
271
- }
272
- });
273
- body.on("end", () => {
274
- if (!closed && !signal?.aborted) {
275
- closed = true;
276
- signal?.removeEventListener("abort", cleanup);
277
- try {
278
- controller.close();
279
- } catch {
280
- }
281
- }
282
- });
283
- body.on("error", (err) => {
284
- cleanup();
285
- if (err.name === "AbortError") {
286
- try {
287
- controller.close();
288
- } catch {
289
- }
290
- return;
291
- }
292
- try {
293
- controller.error(err);
294
- } catch {
295
- }
296
- });
297
- },
298
- cancel() {
299
- cleanup();
300
- }
301
- });
302
- }
303
-
304
- // src/ping.ts
305
- var PING_QUERY = `query ContelloPing { contelloPing { response } }`;
181
+ let closed = false;
182
+ const cleanup = () => {
183
+ if (closed) return;
184
+ closed = true;
185
+ signal?.removeEventListener("abort", cleanup);
186
+ safeDestroyBody(body);
187
+ };
188
+ return new ReadableStream({
189
+ start(controller) {
190
+ signal?.addEventListener("abort", cleanup);
191
+ body.on("data", (chunk) => {
192
+ if (closed || signal?.aborted) return;
193
+ try {
194
+ controller.enqueue(chunk);
195
+ } catch {
196
+ cleanup();
197
+ }
198
+ });
199
+ body.on("end", () => {
200
+ if (closed || signal?.aborted) return;
201
+ closed = true;
202
+ signal?.removeEventListener("abort", cleanup);
203
+ try {
204
+ controller.close();
205
+ } catch {}
206
+ });
207
+ body.on("error", (err) => {
208
+ cleanup();
209
+ if (err.name === "AbortError") {
210
+ try {
211
+ controller.close();
212
+ } catch {}
213
+ return;
214
+ }
215
+ try {
216
+ controller.error(err);
217
+ } catch {}
218
+ });
219
+ },
220
+ cancel() {
221
+ cleanup();
222
+ }
223
+ });
224
+ }
225
+ //#endregion
226
+ //#region src/ping.ts
227
+ const PING_QUERY = `query ContelloPing { contelloPing { response } }`;
306
228
  async function ping(execute) {
307
- const data = await execute(PING_QUERY);
308
- if (data.contelloPing.response !== "pong") {
309
- throw new Error(`unexpected ping response: ${data.contelloPing.response}`);
310
- }
229
+ const data = await execute(PING_QUERY);
230
+ if (data.contelloPing.response !== "pong") throw new Error(`unexpected ping response: ${data.contelloPing.response}`);
311
231
  }
312
-
313
- // src/pool.ts
314
- var DEFAULT_CONNECT_TIMEOUT = 1e4;
232
+ //#endregion
233
+ //#region src/pool.ts
234
+ const DEFAULT_CONNECT_TIMEOUT = 1e4;
315
235
  var ConnectionPool = class {
316
- constructor(_createClient, _poolSize, _connectTimeout = DEFAULT_CONNECT_TIMEOUT) {
317
- this._createClient = _createClient;
318
- this._poolSize = _poolSize;
319
- this._connectTimeout = _connectTimeout;
320
- }
321
- _clients = [];
322
- _connected = [];
323
- _currentIndex = 0;
324
- async connect() {
325
- const ready = [];
326
- for (let i = 0; i < this._poolSize; i++) {
327
- const index = i;
328
- const client = this._createClient(`${i + 1}`);
329
- this._clients.push(client);
330
- this._connected.push(false);
331
- client.on("connected", () => {
332
- this._connected[index] = true;
333
- });
334
- client.on("closed", () => {
335
- this._connected[index] = false;
336
- });
337
- ready.push(
338
- new Promise((resolve) => {
339
- let settled = false;
340
- const done = () => {
341
- if (settled) {
342
- return;
343
- }
344
- settled = true;
345
- offConnected();
346
- clearTimeout(timer);
347
- resolve();
348
- };
349
- const offConnected = client.on("connected", done);
350
- const timer = setTimeout(done, this._connectTimeout);
351
- timer.unref?.();
352
- })
353
- );
354
- }
355
- await Promise.all(ready);
356
- }
357
- get() {
358
- if (this._clients.length === 0) {
359
- throw new Error("@contello/client: connection pool is empty \u2014 call client.init() first");
360
- }
361
- for (let i = 0; i < this._clients.length; i++) {
362
- const index = (this._currentIndex + i) % this._clients.length;
363
- if (this._connected[index]) {
364
- this._currentIndex = (index + 1) % this._clients.length;
365
- return this._clients[index];
366
- }
367
- }
368
- const client = this._clients[this._currentIndex];
369
- this._currentIndex = (this._currentIndex + 1) % this._clients.length;
370
- return client;
371
- }
372
- async disconnect() {
373
- const closed = this._clients.map(
374
- (client) => new Promise((resolve) => {
375
- const unsubscribe = client.on("closed", () => {
376
- unsubscribe();
377
- resolve();
378
- });
379
- client.dispose();
380
- })
381
- );
382
- this._clients = [];
383
- this._connected = [];
384
- this._currentIndex = 0;
385
- await Promise.all(closed);
386
- }
236
+ _createClient;
237
+ _poolSize;
238
+ _connectTimeout;
239
+ _clients = [];
240
+ _connected = [];
241
+ _currentIndex = 0;
242
+ constructor(_createClient, _poolSize, _connectTimeout = DEFAULT_CONNECT_TIMEOUT) {
243
+ this._createClient = _createClient;
244
+ this._poolSize = _poolSize;
245
+ this._connectTimeout = _connectTimeout;
246
+ }
247
+ async connect() {
248
+ const ready = [];
249
+ for (let i = 0; i < this._poolSize; i++) {
250
+ const index = i;
251
+ const client = this._createClient(String(i + 1));
252
+ this._clients.push(client);
253
+ this._connected.push(false);
254
+ client.on("connected", () => {
255
+ this._connected[index] = true;
256
+ });
257
+ client.on("closed", () => {
258
+ this._connected[index] = false;
259
+ });
260
+ ready.push(new Promise((resolve) => {
261
+ let settled = false;
262
+ const done = () => {
263
+ if (settled) return;
264
+ settled = true;
265
+ offConnected();
266
+ clearTimeout(timer);
267
+ resolve();
268
+ };
269
+ const offConnected = client.on("connected", done);
270
+ const timer = setTimeout(done, this._connectTimeout);
271
+ timer.unref?.();
272
+ }));
273
+ }
274
+ await Promise.all(ready);
275
+ }
276
+ get() {
277
+ if (this._clients.length === 0) throw new Error("@contello/client: connection pool is empty — call client.init() first");
278
+ for (let i = 0; i < this._clients.length; i++) {
279
+ const index = (this._currentIndex + i) % this._clients.length;
280
+ if (this._connected[index] === true) {
281
+ this._currentIndex = (index + 1) % this._clients.length;
282
+ return this._clients[index];
283
+ }
284
+ }
285
+ const client = this._clients[this._currentIndex];
286
+ this._currentIndex = (this._currentIndex + 1) % this._clients.length;
287
+ return client;
288
+ }
289
+ async disconnect() {
290
+ const closed = this._clients.map((client) => new Promise((resolve) => {
291
+ const unsubscribe = client.on("closed", () => {
292
+ unsubscribe();
293
+ resolve();
294
+ });
295
+ client.dispose();
296
+ }));
297
+ this._clients = [];
298
+ this._connected = [];
299
+ this._currentIndex = 0;
300
+ await Promise.all(closed);
301
+ }
387
302
  };
388
-
389
- // src/scalars.ts
390
- var LOCAL_DATE_TIME_KEYS = ["year", "month", "day", "hour", "minute", "second"];
391
- var LOCAL_DATE_KEYS = ["year", "month", "day"];
392
- var DATE_TIME_REGEX = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;
393
- var DATE_REGEX = /^(\d{4})-(\d{2})-(\d{2})/;
303
+ //#endregion
304
+ //#region src/telemetry.ts
305
+ const { wrap } = createOperationTelemetry("@contello/client");
306
+ //#endregion
307
+ //#region src/scalars.ts
308
+ const LOCAL_DATE_TIME_KEYS = [
309
+ "year",
310
+ "month",
311
+ "day",
312
+ "hour",
313
+ "minute",
314
+ "second"
315
+ ];
316
+ const LOCAL_DATE_KEYS = [
317
+ "year",
318
+ "month",
319
+ "day"
320
+ ];
321
+ const DATE_TIME_REGEX = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;
322
+ const DATE_REGEX = /^(\d{4})-(\d{2})-(\d{2})/;
394
323
  function pad2(n) {
395
- return n.toString().padStart(2, "0");
324
+ return n.toString().padStart(2, "0");
396
325
  }
397
326
  function pad4(n) {
398
- return n.toString().padStart(4, "0");
327
+ return n.toString().padStart(4, "0");
399
328
  }
400
329
  function hasExactKeys(value, keys) {
401
- const ownKeys = Object.keys(value);
402
- if (ownKeys.length !== keys.length) {
403
- return false;
404
- }
405
- for (const key of keys) {
406
- if (!Object.prototype.hasOwnProperty.call(value, key)) {
407
- return false;
408
- }
409
- }
410
- return true;
330
+ if (Object.keys(value).length !== keys.length) return false;
331
+ for (const key of keys) if (!Object.prototype.hasOwnProperty.call(value, key)) return false;
332
+ return true;
411
333
  }
412
334
  function allNumbers(value, keys) {
413
- for (const key of keys) {
414
- if (typeof value[key] !== "number") {
415
- return false;
416
- }
417
- }
418
- return true;
335
+ for (const key of keys) if (typeof value[key] !== "number") return false;
336
+ return true;
419
337
  }
420
338
  function isLocalDateTime(value) {
421
- return !!value && typeof value === "object" && !Array.isArray(value) && hasExactKeys(value, LOCAL_DATE_TIME_KEYS) && allNumbers(value, LOCAL_DATE_TIME_KEYS);
339
+ return !!value && typeof value === "object" && !Array.isArray(value) && hasExactKeys(value, LOCAL_DATE_TIME_KEYS) && allNumbers(value, LOCAL_DATE_TIME_KEYS);
422
340
  }
423
341
  function isLocalDate(value) {
424
- return !!value && typeof value === "object" && !Array.isArray(value) && hasExactKeys(value, LOCAL_DATE_KEYS) && allNumbers(value, LOCAL_DATE_KEYS);
342
+ return !!value && typeof value === "object" && !Array.isArray(value) && hasExactKeys(value, LOCAL_DATE_KEYS) && allNumbers(value, LOCAL_DATE_KEYS);
425
343
  }
426
344
  function decodeLocalDateTime(value) {
427
- const match = DATE_TIME_REGEX.exec(value);
428
- if (!match) {
429
- throw new Error(`@contello/client: cannot decode LocalDateTime from "${value}"`);
430
- }
431
- return {
432
- year: Number(match[1]),
433
- month: Number(match[2]),
434
- day: Number(match[3]),
435
- hour: Number(match[4]),
436
- minute: Number(match[5]),
437
- second: Number(match[6])
438
- };
345
+ const match = DATE_TIME_REGEX.exec(value);
346
+ if (!match) throw new Error(`@contello/client: cannot decode LocalDateTime from "${value}"`);
347
+ return {
348
+ year: Number(match[1]),
349
+ month: Number(match[2]),
350
+ day: Number(match[3]),
351
+ hour: Number(match[4]),
352
+ minute: Number(match[5]),
353
+ second: Number(match[6])
354
+ };
439
355
  }
440
356
  function decodeLocalDate(value) {
441
- const match = DATE_REGEX.exec(value);
442
- if (!match) {
443
- throw new Error(`@contello/client: cannot decode LocalDate from "${value}"`);
444
- }
445
- return {
446
- year: Number(match[1]),
447
- month: Number(match[2]),
448
- day: Number(match[3])
449
- };
357
+ const match = DATE_REGEX.exec(value);
358
+ if (!match) throw new Error(`@contello/client: cannot decode LocalDate from "${value}"`);
359
+ return {
360
+ year: Number(match[1]),
361
+ month: Number(match[2]),
362
+ day: Number(match[3])
363
+ };
450
364
  }
451
365
  function encodeLocalDateTime(value) {
452
- return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T${pad2(value.hour)}:${pad2(value.minute)}:${pad2(value.second)}Z`;
366
+ return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T${pad2(value.hour)}:${pad2(value.minute)}:${pad2(value.second)}Z`;
453
367
  }
454
368
  function encodeLocalDate(value) {
455
- return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T00:00:00Z`;
456
- }
457
-
458
- // src/transform-variables.ts
369
+ return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T00:00:00Z`;
370
+ }
371
+ //#endregion
372
+ //#region src/transform-variables.ts
373
+ /**
374
+ * encodes outgoing variables: LocalDateTime / LocalDate POJOs become wire strings.
375
+ * detection is by shape — generated input types use the struct types, so consumers
376
+ * pass structs in the right places, and stray objects with the same shape would be
377
+ * an extremely unusual coincidence.
378
+ */
459
379
  function transformVariables(value) {
460
- if (value === null || value === void 0) {
461
- return value;
462
- }
463
- if (Array.isArray(value)) {
464
- return value.map((item) => transformVariables(item));
465
- }
466
- if (typeof value !== "object") {
467
- return value;
468
- }
469
- if (isLocalDateTime(value)) {
470
- return encodeLocalDateTime(value);
471
- }
472
- if (isLocalDate(value)) {
473
- return encodeLocalDate(value);
474
- }
475
- const obj = value;
476
- const out = {};
477
- for (const key of Object.keys(obj)) {
478
- out[key] = transformVariables(obj[key]);
479
- }
480
- return out;
481
- }
482
-
483
- // src/rpc.ts
380
+ if (value === null || value === void 0) return value;
381
+ if (Array.isArray(value)) return value.map((item) => transformVariables(item));
382
+ if (typeof value !== "object") return value;
383
+ if (isLocalDateTime(value)) return encodeLocalDateTime(value);
384
+ if (isLocalDate(value)) return encodeLocalDate(value);
385
+ const obj = value;
386
+ const out = {};
387
+ for (const [key, val] of Object.entries(obj)) out[key] = transformVariables(val);
388
+ return out;
389
+ }
390
+ //#endregion
391
+ //#region src/rpc.ts
484
392
  function buildRpc(operations, subscribe) {
485
- const rpc = {};
486
- for (const [name, def] of Object.entries(operations)) {
487
- rpc[name] = def.kind === "subscription" ? (variables) => subscribe(def.document, transformVariables(variables)) : (variables) => wrap(`rpc:${name}`, () => firstAsync(subscribe(def.document, transformVariables(variables))));
488
- }
489
- return rpc;
490
- }
491
-
492
- // src/source-subscription.ts
493
- var cache = /* @__PURE__ */ new WeakMap();
393
+ const rpc = {};
394
+ for (const [name, def] of Object.entries(operations)) rpc[name] = def.kind === "subscription" ? (variables) => subscribe(def.document, transformVariables(variables)) : (variables) => {
395
+ const vars = transformVariables(variables);
396
+ return wrap(`rpc:${name}`, () => firstAsync(subscribe(def.document, vars)), graphqlOperationAttributes(def.document, vars));
397
+ };
398
+ return rpc;
399
+ }
400
+ //#endregion
401
+ //#region src/source-subscription.ts
402
+ const cache = /* @__PURE__ */ new WeakMap();
494
403
  function createSelection(source) {
495
- const spread = `{ ...${source.fragment} }`;
496
- switch (source.__cardinality) {
497
- case "singleton": {
498
- return `subscription { source: ${source.subscription} ${spread} }`;
499
- }
500
- case "entity": {
501
- return `subscription($ids: [ID!]) { source: ${source.subscription}(request: { filter: { ids: $ids } }) ${spread} }`;
502
- }
503
- case "route": {
504
- return `subscription($ids: [ID!], $paths: [String!]) { source: ${source.subscription}(request: { ids: $ids, paths: $paths }) ${spread} }`;
505
- }
506
- case "asset": {
507
- return `subscription($ids: [ID!]) { source: ${source.subscription}(filter: { ids: $ids }) ${spread} }`;
508
- }
509
- case "i18nMessage": {
510
- return `subscription($collection: String!, $ids: [ID!]) { source: ${source.subscription}(collectionReferenceName: $collection, ids: $ids) ${spread} }`;
511
- }
512
- }
404
+ const spread = `{ ...${source.fragment} }`;
405
+ switch (source.__cardinality) {
406
+ case "singleton": return `subscription { source: ${source.subscription} ${spread} }`;
407
+ case "entity": return `subscription($ids: [ID!]) { source: ${source.subscription}(request: { filter: { ids: $ids } }) ${spread} }`;
408
+ case "route": return `subscription($ids: [ID!], $paths: [String!]) { source: ${source.subscription}(request: { ids: $ids, paths: $paths }) ${spread} }`;
409
+ case "asset": return `subscription($ids: [ID!]) { source: ${source.subscription}(filter: { ids: $ids }) ${spread} }`;
410
+ case "i18nMessage": return `subscription($collection: String!, $ids: [ID!]) { source: ${source.subscription}(collectionReferenceName: $collection, ids: $ids) ${spread} }`;
411
+ }
513
412
  }
514
413
  function createSourceSubscription(source) {
515
- const cached = cache.get(source);
516
- if (cached !== void 0) {
517
- return cached;
518
- }
519
- const doc = `${source.document}
520
- ${createSelection(source)}`;
521
- cache.set(source, doc);
522
- return doc;
523
- }
524
-
525
- // src/sources.ts
414
+ const cached = cache.get(source);
415
+ if (cached !== void 0) return cached;
416
+ const doc = `${source.document}\n${createSelection(source)}`;
417
+ cache.set(source, doc);
418
+ return doc;
419
+ }
420
+ //#endregion
421
+ //#region src/sources.ts
526
422
  function createSources(sources, subscribe) {
527
- const out = {};
528
- for (const [name, source] of Object.entries(sources)) {
529
- const def = source;
530
- const doc = createSourceSubscription(def);
531
- switch (def.__cardinality) {
532
- case "singleton": {
533
- out[name] = {
534
- fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)))
535
- };
536
- break;
537
- }
538
- case "entity": {
539
- out[name] = {
540
- fetch: (vars) => wrap(
541
- `source:${name}`,
542
- () => collectAsync(
543
- mapAsync(
544
- subscribe(doc, transformVariables({ ids: vars?.ids })),
545
- (r) => r.source
546
- )
547
- )
548
- )
549
- };
550
- break;
551
- }
552
- case "route": {
553
- out[name] = {
554
- fetch: (vars) => wrap(
555
- `source:${name}`,
556
- () => collectAsync(
557
- mapAsync(
558
- subscribe(doc, transformVariables({ ids: vars?.ids, paths: vars?.paths })),
559
- (r) => r.source
560
- )
561
- )
562
- )
563
- };
564
- break;
565
- }
566
- case "asset": {
567
- out[name] = {
568
- fetch: (vars) => wrap(
569
- `source:${name}`,
570
- () => collectAsync(
571
- mapAsync(
572
- subscribe(doc, transformVariables({ ids: vars?.ids })),
573
- (r) => r.source
574
- )
575
- )
576
- )
577
- };
578
- break;
579
- }
580
- case "i18nMessage": {
581
- out[name] = {
582
- fetch: (vars) => wrap(
583
- `source:${name}`,
584
- () => collectAsync(
585
- mapAsync(
586
- subscribe(
587
- doc,
588
- transformVariables({ collection: vars.collection, ids: vars.ids })
589
- ),
590
- (r) => r.source
591
- )
592
- )
593
- )
594
- };
595
- break;
596
- }
597
- }
598
- }
599
- return out;
600
- }
601
-
602
- // src/transform-response.ts
603
- var FLAT_PREFIX = "_flat_";
604
- var LDT_PREFIX = "_ldt_";
605
- var LD_PREFIX = "_ld_";
606
- var MODEL_SUFFIXES = ["Entity", "Component"];
423
+ const out = {};
424
+ for (const [name, source] of Object.entries(sources)) {
425
+ const def = source;
426
+ const accessor = createSourceAccessor(name, def, createSourceSubscription(def), subscribe);
427
+ if (accessor) out[name] = accessor;
428
+ }
429
+ return out;
430
+ }
431
+ function createSourceAccessor(name, def, doc, subscribe) {
432
+ switch (def.__cardinality) {
433
+ case "singleton": return { fetch: () => wrap(`source:${name}`, () => firstAsync(mapAsync(subscribe(doc), (r) => r.source)), graphqlOperationAttributes(doc)) };
434
+ case "entity": return { fetch: (vars) => {
435
+ const variables = transformVariables({ ids: vars?.ids });
436
+ return wrap(`source:${name}`, () => collectAsync(mapAsync(subscribe(doc, variables), (r) => r.source)), graphqlOperationAttributes(doc, variables));
437
+ } };
438
+ case "route": return { fetch: (vars) => {
439
+ const variables = transformVariables({
440
+ ids: vars?.ids,
441
+ paths: vars?.paths
442
+ });
443
+ return wrap(`source:${name}`, () => collectAsync(mapAsync(subscribe(doc, variables), (r) => r.source)), graphqlOperationAttributes(doc, variables));
444
+ } };
445
+ case "asset": return { fetch: (vars) => {
446
+ const variables = transformVariables({ ids: vars?.ids });
447
+ return wrap(`source:${name}`, () => collectAsync(mapAsync(subscribe(doc, variables), (r) => r.source)), graphqlOperationAttributes(doc, variables));
448
+ } };
449
+ case "i18nMessage": return { fetch: (vars) => {
450
+ const variables = transformVariables({
451
+ collection: vars.collection,
452
+ ids: vars.ids
453
+ });
454
+ return wrap(`source:${name}`, () => collectAsync(mapAsync(subscribe(doc, variables), (r) => r.source)), graphqlOperationAttributes(doc, variables));
455
+ } };
456
+ }
457
+ }
458
+ //#endregion
459
+ //#region src/transform-response.ts
460
+ const FLAT_PREFIX = "_flat_";
461
+ const LDT_PREFIX = "_ldt_";
462
+ const LD_PREFIX = "_ld_";
463
+ const MODEL_SUFFIXES = ["Entity", "Component"];
607
464
  function decodeValue(value, decoder) {
608
- if (value === null || value === void 0) {
609
- return value;
610
- }
611
- if (Array.isArray(value)) {
612
- return value.map((item) => decodeValue(item, decoder));
613
- }
614
- if (typeof value === "string") {
615
- return decoder(value);
616
- }
617
- return value;
465
+ if (value === null || value === void 0) return value;
466
+ if (Array.isArray(value)) return value.map((item) => decodeValue(item, decoder));
467
+ if (typeof value === "string") return decoder(value);
468
+ return value;
618
469
  }
619
470
  function deriveModel(typename) {
620
- for (const suffix of MODEL_SUFFIXES) {
621
- if (typename.endsWith(suffix)) {
622
- const stripped = typename.slice(0, -suffix.length);
623
- return stripped.charAt(0).toLowerCase() + stripped.slice(1);
624
- }
625
- }
626
- return void 0;
627
- }
471
+ for (const suffix of MODEL_SUFFIXES) if (typename.endsWith(suffix)) {
472
+ const stripped = typename.slice(0, -suffix.length);
473
+ return stripped.charAt(0).toLowerCase() + stripped.slice(1);
474
+ }
475
+ }
476
+ /**
477
+ * transforms a GraphQL response in a single depth-first pass:
478
+ * - resolves `_flat_{field}` companions into nested component arrays (refs are
479
+ * matched against the companion map by `_flatId`, at any nesting depth — the
480
+ * companion lists the whole subtree, so one map serves every ref below it)
481
+ * - injects `__model` on objects with entity/component `__typename`
482
+ * - decodes managed scalar aliases (`_ldt_` / `_ld_`) into structured values
483
+ *
484
+ * a `seen` set guards against shared or cyclic references so every object is
485
+ * visited exactly once.
486
+ */
628
487
  function transformResponse(data) {
629
- transformNode(data, void 0, /* @__PURE__ */ new WeakSet());
630
- return data;
488
+ transformNode(data, void 0, /* @__PURE__ */ new WeakSet());
489
+ return data;
631
490
  }
632
491
  function transformNode(value, flatMap, seen) {
633
- if (!value || typeof value !== "object") {
634
- return;
635
- }
636
- if (seen.has(value)) {
637
- return;
638
- }
639
- seen.add(value);
640
- if (Array.isArray(value)) {
641
- for (const item of value) {
642
- transformNode(item, flatMap, seen);
643
- }
644
- return;
645
- }
646
- const obj = value;
647
- const typename = obj["__typename"];
648
- if (typeof typename === "string") {
649
- const model = deriveModel(typename);
650
- if (model) {
651
- obj["__model"] = model;
652
- }
653
- }
654
- let ownMap;
655
- for (const key of Object.keys(obj)) {
656
- if (!key.startsWith(FLAT_PREFIX)) {
657
- continue;
658
- }
659
- const flatArray = obj[key];
660
- delete obj[key];
661
- if (!flatArray) {
662
- continue;
663
- }
664
- if (!ownMap) {
665
- ownMap = flatMap ? new Map(flatMap) : /* @__PURE__ */ new Map();
666
- }
667
- for (const component of flatArray) {
668
- if (component._flatId) {
669
- ownMap.set(component._flatId, component);
670
- }
671
- }
672
- }
673
- const resolveMap = ownMap ?? flatMap;
674
- for (const key of Object.keys(obj)) {
675
- if (key.startsWith(LDT_PREFIX)) {
676
- obj[key.slice(LDT_PREFIX.length)] = decodeValue(obj[key], decodeLocalDateTime);
677
- delete obj[key];
678
- continue;
679
- }
680
- if (key.startsWith(LD_PREFIX)) {
681
- obj[key.slice(LD_PREFIX.length)] = decodeValue(obj[key], decodeLocalDate);
682
- delete obj[key];
683
- continue;
684
- }
685
- const inner = obj[key];
686
- if (resolveMap && Array.isArray(inner) && inner.length > 0 && inner[0]?._flatId !== void 0) {
687
- obj[key] = resolveRefs(inner, resolveMap);
688
- }
689
- transformNode(obj[key], resolveMap, seen);
690
- }
492
+ if (!value || typeof value !== "object") return;
493
+ if (seen.has(value)) return;
494
+ seen.add(value);
495
+ if (Array.isArray(value)) {
496
+ for (const item of value) transformNode(item, flatMap, seen);
497
+ return;
498
+ }
499
+ const obj = value;
500
+ const typename = obj["__typename"];
501
+ if (typeof typename === "string") {
502
+ const model = deriveModel(typename);
503
+ if (model) obj["__model"] = model;
504
+ }
505
+ let ownMap;
506
+ for (const key of Object.keys(obj)) {
507
+ if (!key.startsWith(FLAT_PREFIX)) continue;
508
+ const flatArray = obj[key];
509
+ delete obj[key];
510
+ if (!flatArray) continue;
511
+ if (!ownMap) ownMap = flatMap ? new Map(flatMap) : /* @__PURE__ */ new Map();
512
+ for (const component of flatArray) if (component._flatId) ownMap.set(component._flatId, component);
513
+ }
514
+ const resolveMap = ownMap ?? flatMap;
515
+ for (const key of Object.keys(obj)) {
516
+ if (key.startsWith(LDT_PREFIX)) {
517
+ obj[key.slice(5)] = decodeValue(obj[key], decodeLocalDateTime);
518
+ delete obj[key];
519
+ continue;
520
+ }
521
+ if (key.startsWith(LD_PREFIX)) {
522
+ obj[key.slice(4)] = decodeValue(obj[key], decodeLocalDate);
523
+ delete obj[key];
524
+ continue;
525
+ }
526
+ const inner = obj[key];
527
+ if (resolveMap && Array.isArray(inner) && inner.length > 0 && inner[0]?._flatId !== void 0) obj[key] = resolveRefs(inner, resolveMap);
528
+ transformNode(obj[key], resolveMap, seen);
529
+ }
691
530
  }
692
531
  function resolveRefs(refs, flatMap) {
693
- const resolved = [];
694
- for (const ref of refs) {
695
- if (!ref._flatId) {
696
- continue;
697
- }
698
- const component = flatMap.get(ref._flatId);
699
- if (component) {
700
- resolved.push(component);
701
- }
702
- }
703
- return resolved;
704
- }
705
-
706
- // src/upload.ts
707
- var DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024;
532
+ const resolved = [];
533
+ for (const ref of refs) {
534
+ if (!ref._flatId) continue;
535
+ const component = flatMap.get(ref._flatId);
536
+ if (component) resolved.push(component);
537
+ }
538
+ return resolved;
539
+ }
540
+ //#endregion
541
+ //#region src/upload.ts
542
+ const DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024;
708
543
  function isUint8Array(data) {
709
- return data instanceof Uint8Array;
544
+ return data instanceof Uint8Array;
710
545
  }
711
546
  function upload(url, project, token, data, meta, options) {
712
- const chunkSize = options?.chunkSize ?? DEFAULT_CHUNK_SIZE;
713
- const wsUrl = `${url.replace(/^http/i, "ws")}/api/v1/assets/ws`;
714
- const size = isUint8Array(data) ? data.length : meta.size;
715
- return new Promise((resolve, reject) => {
716
- const ws = new WebSocket(wsUrl, "contello-file-upload-v1");
717
- let done = false;
718
- const cleanup = () => {
719
- options?.abort?.removeEventListener("abort", abortHandler);
720
- };
721
- const abortHandler = () => {
722
- if (!done) {
723
- ws.close();
724
- reject(new Error("upload aborted"));
725
- }
726
- };
727
- options?.abort?.addEventListener("abort", abortHandler);
728
- function sendBuffer(buf) {
729
- let offset = 0;
730
- while (offset < buf.length) {
731
- const chunk = buf.subarray(offset, offset + chunkSize);
732
- ws.send(chunk);
733
- offset += chunk.length;
734
- }
735
- ws.send(JSON.stringify({ type: "done" }));
736
- }
737
- const MAX_BUFFER_SIZE = 8 * 1024 * 1024;
738
- function waitForBufferedDrain() {
739
- return new Promise((resolveDrain, rejectDrain) => {
740
- const check = () => {
741
- if (options?.abort?.aborted) {
742
- rejectDrain(new Error("upload aborted"));
743
- return;
744
- }
745
- if (ws.bufferedAmount <= MAX_BUFFER_SIZE) {
746
- resolveDrain();
747
- return;
748
- }
749
- setTimeout(check, 50);
750
- };
751
- check();
752
- });
753
- }
754
- async function sendStream(stream) {
755
- const reader = stream.getReader();
756
- try {
757
- while (true) {
758
- const { done: streamDone, value } = await reader.read();
759
- if (streamDone) break;
760
- await waitForBufferedDrain();
761
- ws.send(value);
762
- }
763
- ws.send(JSON.stringify({ type: "done" }));
764
- } catch (error) {
765
- reject(error);
766
- ws.close();
767
- }
768
- }
769
- ws.addEventListener("open", () => {
770
- const initFrame = {
771
- type: "init",
772
- metadata: { ...meta, ...size === void 0 ? {} : { size }, projectRef: project },
773
- token
774
- };
775
- ws.send(JSON.stringify(initFrame));
776
- });
777
- ws.addEventListener("message", (event) => {
778
- const message = JSON.parse(String(event.data));
779
- if (message.type === "ack") {
780
- if (isUint8Array(data)) {
781
- sendBuffer(data);
782
- } else {
783
- sendStream(data);
784
- }
785
- return;
786
- }
787
- if (message.type === "done") {
788
- done = true;
789
- cleanup();
790
- ws.close();
791
- resolve(message.id);
792
- }
793
- });
794
- ws.addEventListener("error", () => {
795
- cleanup();
796
- reject(new Error("upload websocket error"));
797
- });
798
- ws.addEventListener("close", () => {
799
- cleanup();
800
- if (!done) {
801
- reject(new Error("connection closed before upload completed"));
802
- }
803
- });
804
- });
805
- }
806
-
807
- // src/utils.ts
808
- var MAX_DELAY_MS = 3e4;
809
- var JITTER_MIN_MS2 = 300;
810
- var JITTER_MAX_MS2 = 3e3;
547
+ const chunkSize = options?.chunkSize ?? DEFAULT_CHUNK_SIZE;
548
+ const wsUrl = `${url.replace(/^http/i, "ws")}/api/v1/assets/ws`;
549
+ const size = isUint8Array(data) ? data.length : meta.size;
550
+ return new Promise((resolve, reject) => {
551
+ const ws = new WebSocket(wsUrl, "contello-file-upload-v1");
552
+ let done = false;
553
+ const cleanup = () => {
554
+ options?.abort?.removeEventListener("abort", abortHandler);
555
+ };
556
+ const abortHandler = () => {
557
+ if (done) return;
558
+ ws.close();
559
+ reject(/* @__PURE__ */ new Error("upload aborted"));
560
+ };
561
+ options?.abort?.addEventListener("abort", abortHandler);
562
+ function sendBuffer(buf) {
563
+ let offset = 0;
564
+ while (offset < buf.length) {
565
+ const chunk = buf.subarray(offset, offset + chunkSize);
566
+ ws.send(chunk);
567
+ offset += chunk.length;
568
+ }
569
+ ws.send(JSON.stringify({ type: "done" }));
570
+ }
571
+ const MAX_BUFFER_SIZE = 8 * 1024 * 1024;
572
+ function waitForBufferedDrain() {
573
+ return new Promise((resolveDrain, rejectDrain) => {
574
+ const check = () => {
575
+ if (options?.abort?.aborted) {
576
+ rejectDrain(/* @__PURE__ */ new Error("upload aborted"));
577
+ return;
578
+ }
579
+ if (ws.bufferedAmount <= MAX_BUFFER_SIZE) {
580
+ resolveDrain();
581
+ return;
582
+ }
583
+ setTimeout(check, 50);
584
+ };
585
+ check();
586
+ });
587
+ }
588
+ async function sendStream(stream) {
589
+ const reader = stream.getReader();
590
+ try {
591
+ while (true) {
592
+ const { done: streamDone, value } = await reader.read();
593
+ if (streamDone) break;
594
+ await waitForBufferedDrain();
595
+ ws.send(value);
596
+ }
597
+ ws.send(JSON.stringify({ type: "done" }));
598
+ } catch (error) {
599
+ reject(error);
600
+ ws.close();
601
+ }
602
+ }
603
+ ws.addEventListener("open", () => {
604
+ const initFrame = {
605
+ type: "init",
606
+ metadata: {
607
+ ...meta,
608
+ ...size !== void 0 && { size },
609
+ projectRef: project
610
+ },
611
+ token
612
+ };
613
+ ws.send(JSON.stringify(initFrame));
614
+ });
615
+ ws.addEventListener("message", (event) => {
616
+ const message = JSON.parse(String(event.data));
617
+ if (message.type === "ack") {
618
+ if (isUint8Array(data)) sendBuffer(data);
619
+ else sendStream(data);
620
+ return;
621
+ }
622
+ if (message.type === "done") {
623
+ done = true;
624
+ cleanup();
625
+ ws.close();
626
+ resolve(message.id);
627
+ }
628
+ });
629
+ ws.addEventListener("error", () => {
630
+ cleanup();
631
+ reject(/* @__PURE__ */ new Error("upload websocket error"));
632
+ });
633
+ ws.addEventListener("close", () => {
634
+ cleanup();
635
+ if (!done) reject(/* @__PURE__ */ new Error("connection closed before upload completed"));
636
+ });
637
+ });
638
+ }
639
+ //#endregion
640
+ //#region src/utils.ts
641
+ const MAX_DELAY_MS = 3e4;
642
+ const JITTER_MIN_MS = 300;
643
+ const JITTER_MAX_MS = 3e3;
811
644
  function wsRetryWait(retries) {
812
- const delay2 = Math.min(Math.pow(2, retries) * 1e3, MAX_DELAY_MS) + Math.floor(Math.random() * (JITTER_MAX_MS2 - JITTER_MIN_MS2) + JITTER_MIN_MS2);
813
- return new Promise((resolve) => setTimeout(resolve, delay2));
645
+ const delay = Math.min(Math.pow(2, retries) * 1e3, MAX_DELAY_MS) + Math.floor(Math.random() * (JITTER_MAX_MS - JITTER_MIN_MS) + JITTER_MIN_MS);
646
+ return new Promise((resolve) => setTimeout(resolve, delay));
814
647
  }
815
-
816
- // src/client.ts
648
+ //#endregion
649
+ //#region src/client.ts
817
650
  var ContelloClient = class {
818
- _pool;
819
- _rpc;
820
- _sources;
821
- _url;
822
- _project;
823
- _token;
824
- _agent;
825
- constructor(options) {
826
- const { url, project, token, schema, connections = 1, connectionEvents } = options;
827
- this._url = url;
828
- this._project = project;
829
- this._token = token;
830
- this._agent = createHttpAgent(options.http);
831
- const websocketUrl = `${url}/graphql/projects/${project}`.replace(/^http/i, "ws");
832
- let state = "disconnected";
833
- let connectedCount = 0;
834
- const onConnectionUp = () => {
835
- connectedCount++;
836
- if (connectedCount === connections && state !== "connected") {
837
- state = "connected";
838
- options.onConnected?.();
839
- }
840
- };
841
- const onConnectionDown = () => {
842
- if (connectedCount > 0) {
843
- connectedCount--;
844
- }
845
- if (state === "connected") {
846
- state = "reconnecting";
847
- options.onReconnecting?.();
848
- }
849
- };
850
- this._pool = new ConnectionPool((id) => {
851
- const context = Object.freeze({ connectionId: id, websocketUrl });
852
- return createClient({
853
- url: websocketUrl,
854
- connectionParams: { token },
855
- lazy: false,
856
- keepAlive: 3e4,
857
- retryAttempts: Infinity,
858
- retryWait: wsRetryWait,
859
- shouldRetry: () => true,
860
- jsonMessageReplacer: (key, value) => {
861
- if (!key) {
862
- return decorateMessage(value);
863
- }
864
- return value;
865
- },
866
- ...options.onError ? { onNonLazyError: (e) => options.onError(e) } : {},
867
- on: {
868
- connected: () => {
869
- onConnectionUp();
870
- connectionEvents?.onConnected?.(context);
871
- },
872
- connecting: () => {
873
- connectionEvents?.onConnecting?.(context);
874
- },
875
- closed: () => {
876
- onConnectionDown();
877
- connectionEvents?.onClosed?.(context);
878
- },
879
- ...options.onError || connectionEvents?.onError ? {
880
- error: (e) => {
881
- options.onError?.(e);
882
- connectionEvents?.onError?.(context, e);
883
- }
884
- } : {}
885
- }
886
- });
887
- }, connections);
888
- this._rpc = schema?.operations ? buildRpc(schema.operations, (q, v) => this.subscribe(q, v)) : void 0;
889
- this._sources = schema?.sources ? createSources(schema.sources, (q, v) => this.subscribe(q, v)) : void 0;
890
- }
891
- get rpc() {
892
- if (!this._rpc) {
893
- throw new Error("@contello/client: .rpc accessed without a schema containing operations");
894
- }
895
- return this._rpc;
896
- }
897
- get sources() {
898
- if (!this._sources) {
899
- throw new Error("@contello/client: .sources accessed without a schema containing sources");
900
- }
901
- return this._sources;
902
- }
903
- async init() {
904
- await this._pool.connect();
905
- }
906
- async destroy() {
907
- await this._pool.disconnect();
908
- await this._agent.close();
909
- }
910
- async ping() {
911
- return ping((query) => firstAsync(this.subscribe(query)));
912
- }
913
- /**
914
- * Open a subscription on the websocket. Each `[Symbol.asyncIterator]()` call (the implicit one
915
- * from `for await`, or via `rxjs.from(this)`) starts a fresh server subscription and tears it
916
- * down when the iterator is returned (`break`, error, or explicit stop).
917
- */
918
- subscribe(query, variables) {
919
- const pool = this._pool;
920
- return {
921
- [Symbol.asyncIterator]() {
922
- const wsClient = pool.get();
923
- const queue = [];
924
- let pending;
925
- let done = false;
926
- let error;
927
- const unsubscribe = wsClient.subscribe(
928
- { query, variables },
929
- {
930
- next(msg) {
931
- const value = transformResponse(msg.data);
932
- if (value === void 0 || value === null) {
933
- return;
934
- }
935
- if (pending) {
936
- const p = pending;
937
- pending = void 0;
938
- p.resolve({ value, done: false });
939
- } else {
940
- queue.push(value);
941
- }
942
- },
943
- error(err) {
944
- done = true;
945
- error = err;
946
- if (pending) {
947
- const p = pending;
948
- pending = void 0;
949
- p.reject(err);
950
- }
951
- },
952
- complete() {
953
- done = true;
954
- if (pending) {
955
- const p = pending;
956
- pending = void 0;
957
- p.resolve({ value: void 0, done: true });
958
- }
959
- }
960
- }
961
- );
962
- return {
963
- next() {
964
- if (queue.length > 0) {
965
- return Promise.resolve({ value: queue.shift(), done: false });
966
- }
967
- if (error !== void 0) {
968
- return Promise.reject(error);
969
- }
970
- if (done) {
971
- return Promise.resolve({ value: void 0, done: true });
972
- }
973
- return new Promise((resolve, reject) => {
974
- pending = { resolve, reject };
975
- });
976
- },
977
- return() {
978
- unsubscribe();
979
- return Promise.resolve({ value: void 0, done: true });
980
- },
981
- throw(err) {
982
- unsubscribe();
983
- return Promise.reject(err);
984
- }
985
- };
986
- }
987
- };
988
- }
989
- download(fileId) {
990
- return wrap("@contello/client:download", () => downloadFile(this._agent, this._url, this._token, fileId));
991
- }
992
- proxyHls(path, signal) {
993
- return wrap("@contello/client:proxyHls", () => proxyHls(this._agent, this._url, this._token, path, signal));
994
- }
995
- upload(data, meta, options) {
996
- return wrap(
997
- "@contello/client:upload",
998
- () => upload(this._url, this._project, this._token, data, meta, options)
999
- );
1000
- }
1001
- execute(query, variables) {
1002
- return wrap("@contello/client:execute", () => firstAsync(this.subscribe(query, variables)));
1003
- }
651
+ _pool;
652
+ _rpc;
653
+ _sources;
654
+ _url;
655
+ _project;
656
+ _token;
657
+ _agent;
658
+ constructor(options) {
659
+ const { url, project, token, schema, connections = 1, connectionEvents } = options;
660
+ this._url = url;
661
+ this._project = project;
662
+ this._token = token;
663
+ this._agent = createHttpAgent(options.http);
664
+ const websocketUrl = `${url}/graphql/projects/${project}`.replace(/^http/i, "ws");
665
+ let state = "disconnected";
666
+ let connectedCount = 0;
667
+ const onConnectionUp = () => {
668
+ connectedCount++;
669
+ if (connectedCount === connections && state !== "connected") {
670
+ state = "connected";
671
+ options.onConnected?.();
672
+ }
673
+ };
674
+ const onConnectionDown = () => {
675
+ if (connectedCount > 0) connectedCount--;
676
+ if (state === "connected") {
677
+ state = "reconnecting";
678
+ options.onReconnecting?.();
679
+ }
680
+ };
681
+ this._pool = new ConnectionPool((id) => {
682
+ const context = Object.freeze({
683
+ connectionId: id,
684
+ websocketUrl
685
+ });
686
+ return createClient({
687
+ url: websocketUrl,
688
+ connectionParams: { token },
689
+ lazy: false,
690
+ keepAlive: 3e4,
691
+ retryAttempts: Infinity,
692
+ retryWait: wsRetryWait,
693
+ shouldRetry: () => true,
694
+ jsonMessageReplacer: (key, value) => {
695
+ if (!key) return injectTraceContext(value);
696
+ return value;
697
+ },
698
+ ...options.onError && { onNonLazyError: (e) => options.onError(e) },
699
+ on: {
700
+ connected: () => {
701
+ onConnectionUp();
702
+ connectionEvents?.onConnected?.(context);
703
+ },
704
+ connecting: () => {
705
+ connectionEvents?.onConnecting?.(context);
706
+ },
707
+ closed: () => {
708
+ onConnectionDown();
709
+ connectionEvents?.onClosed?.(context);
710
+ },
711
+ ...(options.onError || connectionEvents?.onError) && { error: (e) => {
712
+ options.onError?.(e);
713
+ connectionEvents?.onError?.(context, e);
714
+ } }
715
+ }
716
+ });
717
+ }, connections);
718
+ this._rpc = schema?.operations ? buildRpc(schema.operations, (q, v) => this.subscribe(q, v)) : void 0;
719
+ this._sources = schema?.sources ? createSources(schema.sources, (q, v) => this.subscribe(q, v)) : void 0;
720
+ }
721
+ get rpc() {
722
+ if (!this._rpc) throw new Error("@contello/client: .rpc accessed without a schema containing operations");
723
+ return this._rpc;
724
+ }
725
+ get sources() {
726
+ if (!this._sources) throw new Error("@contello/client: .sources accessed without a schema containing sources");
727
+ return this._sources;
728
+ }
729
+ async init() {
730
+ await this._pool.connect();
731
+ }
732
+ async destroy() {
733
+ await this._pool.disconnect();
734
+ await this._agent.close();
735
+ }
736
+ async ping() {
737
+ return ping((query) => firstAsync(this.subscribe(query)));
738
+ }
739
+ /**
740
+ * Open a subscription on the websocket. Each `[Symbol.asyncIterator]()` call (the implicit one
741
+ * from `for await`, or via `rxjs.from(this)`) starts a fresh server subscription and tears it
742
+ * down when the iterator is returned (`break`, error, or explicit stop).
743
+ */
744
+ subscribe(query, variables) {
745
+ const pool = this._pool;
746
+ return { [Symbol.asyncIterator]() {
747
+ const wsClient = pool.get();
748
+ const queue = [];
749
+ let pending;
750
+ let done = false;
751
+ let error;
752
+ const unsubscribe = wsClient.subscribe({
753
+ query,
754
+ variables
755
+ }, {
756
+ next(msg) {
757
+ const value = transformResponse(msg.data);
758
+ if (value === void 0 || value === null) return;
759
+ if (pending) {
760
+ const p = pending;
761
+ pending = void 0;
762
+ p.resolve({
763
+ value,
764
+ done: false
765
+ });
766
+ } else queue.push(value);
767
+ },
768
+ error(err) {
769
+ done = true;
770
+ error = err;
771
+ if (pending) {
772
+ const p = pending;
773
+ pending = void 0;
774
+ p.reject(err);
775
+ }
776
+ },
777
+ complete() {
778
+ done = true;
779
+ if (pending) {
780
+ const p = pending;
781
+ pending = void 0;
782
+ p.resolve({
783
+ value: void 0,
784
+ done: true
785
+ });
786
+ }
787
+ }
788
+ });
789
+ return {
790
+ next() {
791
+ if (queue.length > 0) return Promise.resolve({
792
+ value: queue.shift(),
793
+ done: false
794
+ });
795
+ if (error !== void 0) return Promise.reject(error);
796
+ if (done) return Promise.resolve({
797
+ value: void 0,
798
+ done: true
799
+ });
800
+ return new Promise((resolve, reject) => {
801
+ pending = {
802
+ resolve,
803
+ reject
804
+ };
805
+ });
806
+ },
807
+ return() {
808
+ unsubscribe();
809
+ return Promise.resolve({
810
+ value: void 0,
811
+ done: true
812
+ });
813
+ },
814
+ throw(err) {
815
+ unsubscribe();
816
+ return Promise.reject(err);
817
+ }
818
+ };
819
+ } };
820
+ }
821
+ download(fileId) {
822
+ return wrap("@contello/client:download", () => downloadFile(this._agent, this._url, this._token, fileId));
823
+ }
824
+ proxyHls(path, signal) {
825
+ return wrap("@contello/client:proxyHls", () => proxyHls(this._agent, this._url, this._token, path, signal));
826
+ }
827
+ upload(data, meta, options) {
828
+ return wrap("@contello/client:upload", () => upload(this._url, this._project, this._token, data, meta, options));
829
+ }
830
+ execute(query, variables) {
831
+ return wrap("@contello/client:execute", () => firstAsync(this.subscribe(query, variables)), graphqlOperationAttributes(query, variables));
832
+ }
1004
833
  };
1005
834
  function createContelloClient(options) {
1006
- return new ContelloClient(options);
835
+ return new ContelloClient(options);
1007
836
  }
1008
-
1009
- // src/async-iterable-subject.ts
837
+ //#endregion
838
+ //#region src/async-iterable-subject.ts
1010
839
  function createAsyncIterableSubject() {
1011
- const consumers = /* @__PURE__ */ new Set();
1012
- let status = { state: "open" };
1013
- const next = (value) => {
1014
- if (status.state !== "open") {
1015
- return;
1016
- }
1017
- for (const consumer of consumers) {
1018
- if (consumer.kind === "listener") {
1019
- consumer.next?.(value);
1020
- } else if (consumer.pending) {
1021
- const p = consumer.pending;
1022
- consumer.pending = void 0;
1023
- p.resolve({ value, done: false });
1024
- } else {
1025
- consumer.queue.push(value);
1026
- }
1027
- }
1028
- };
1029
- const error = (err) => {
1030
- if (status.state !== "open") {
1031
- return;
1032
- }
1033
- status = { state: "errored", err };
1034
- for (const consumer of consumers) {
1035
- if (consumer.kind === "listener") {
1036
- consumer.error?.(err);
1037
- } else if (consumer.pending) {
1038
- const p = consumer.pending;
1039
- consumer.pending = void 0;
1040
- p.reject(err);
1041
- }
1042
- }
1043
- consumers.clear();
1044
- };
1045
- const complete = () => {
1046
- if (status.state !== "open") {
1047
- return;
1048
- }
1049
- status = { state: "completed" };
1050
- for (const consumer of consumers) {
1051
- if (consumer.kind === "listener") {
1052
- consumer.complete?.();
1053
- } else if (consumer.pending) {
1054
- const p = consumer.pending;
1055
- consumer.pending = void 0;
1056
- p.resolve({ value: void 0, done: true });
1057
- }
1058
- }
1059
- consumers.clear();
1060
- };
1061
- const subscribe = (observerOrNext) => {
1062
- if (status.state !== "open") {
1063
- return () => {
1064
- };
1065
- }
1066
- const observer = typeof observerOrNext === "function" ? { next: observerOrNext } : observerOrNext;
1067
- const consumer = { kind: "listener", ...observer };
1068
- consumers.add(consumer);
1069
- return () => {
1070
- consumers.delete(consumer);
1071
- };
1072
- };
1073
- const iterable = {
1074
- [Symbol.asyncIterator]() {
1075
- if (status.state === "errored") {
1076
- const err = status.err;
1077
- return {
1078
- next: () => Promise.reject(err),
1079
- return: () => Promise.resolve({ value: void 0, done: true })
1080
- };
1081
- }
1082
- if (status.state === "completed") {
1083
- return {
1084
- next: () => Promise.resolve({ value: void 0, done: true }),
1085
- return: () => Promise.resolve({ value: void 0, done: true })
1086
- };
1087
- }
1088
- const consumer = { kind: "iterator", queue: [] };
1089
- consumers.add(consumer);
1090
- return {
1091
- next() {
1092
- if (consumer.queue.length > 0) {
1093
- return Promise.resolve({ value: consumer.queue.shift(), done: false });
1094
- }
1095
- if (status.state === "errored") {
1096
- return Promise.reject(status.err);
1097
- }
1098
- if (status.state === "completed") {
1099
- return Promise.resolve({ value: void 0, done: true });
1100
- }
1101
- return new Promise((resolve, reject) => {
1102
- consumer.pending = { resolve, reject };
1103
- });
1104
- },
1105
- return() {
1106
- consumers.delete(consumer);
1107
- if (consumer.pending) {
1108
- const p = consumer.pending;
1109
- consumer.pending = void 0;
1110
- p.resolve({ value: void 0, done: true });
1111
- }
1112
- return Promise.resolve({ value: void 0, done: true });
1113
- },
1114
- throw(err) {
1115
- consumers.delete(consumer);
1116
- return Promise.reject(err);
1117
- }
1118
- };
1119
- }
1120
- };
1121
- return Object.assign(iterable, { next, error, complete, subscribe });
1122
- }
1123
- export {
1124
- ContelloClient,
1125
- asyncKeepalive,
1126
- collectAsync,
1127
- createAsyncIterableSubject,
1128
- createContelloClient,
1129
- createSourceSubscription,
1130
- exponentialBackoff,
1131
- filterAsync,
1132
- firstAsync,
1133
- mapAsync,
1134
- runWithBackoff
1135
- };
840
+ const consumers = /* @__PURE__ */ new Set();
841
+ let status = { state: "open" };
842
+ const next = (value) => {
843
+ if (status.state !== "open") return;
844
+ for (const consumer of consumers) if (consumer.kind === "listener") consumer.next?.(value);
845
+ else if (consumer.pending) {
846
+ const p = consumer.pending;
847
+ consumer.pending = void 0;
848
+ p.resolve({
849
+ value,
850
+ done: false
851
+ });
852
+ } else consumer.queue.push(value);
853
+ };
854
+ const error = (err) => {
855
+ if (status.state !== "open") return;
856
+ status = {
857
+ state: "errored",
858
+ err
859
+ };
860
+ for (const consumer of consumers) if (consumer.kind === "listener") consumer.error?.(err);
861
+ else if (consumer.pending) {
862
+ const p = consumer.pending;
863
+ consumer.pending = void 0;
864
+ p.reject(err);
865
+ }
866
+ consumers.clear();
867
+ };
868
+ const complete = () => {
869
+ if (status.state !== "open") return;
870
+ status = { state: "completed" };
871
+ for (const consumer of consumers) if (consumer.kind === "listener") consumer.complete?.();
872
+ else if (consumer.pending) {
873
+ const p = consumer.pending;
874
+ consumer.pending = void 0;
875
+ p.resolve({
876
+ value: void 0,
877
+ done: true
878
+ });
879
+ }
880
+ consumers.clear();
881
+ };
882
+ const subscribe = (observerOrNext) => {
883
+ if (status.state !== "open") return () => {};
884
+ const consumer = {
885
+ kind: "listener",
886
+ ...typeof observerOrNext === "function" ? { next: observerOrNext } : observerOrNext
887
+ };
888
+ consumers.add(consumer);
889
+ return () => {
890
+ consumers.delete(consumer);
891
+ };
892
+ };
893
+ return Object.assign({ [Symbol.asyncIterator]() {
894
+ if (status.state === "errored") {
895
+ const err = status.err;
896
+ return {
897
+ next: () => Promise.reject(err),
898
+ return: () => Promise.resolve({
899
+ value: void 0,
900
+ done: true
901
+ })
902
+ };
903
+ }
904
+ if (status.state === "completed") return {
905
+ next: () => Promise.resolve({
906
+ value: void 0,
907
+ done: true
908
+ }),
909
+ return: () => Promise.resolve({
910
+ value: void 0,
911
+ done: true
912
+ })
913
+ };
914
+ const consumer = {
915
+ kind: "iterator",
916
+ queue: []
917
+ };
918
+ consumers.add(consumer);
919
+ return {
920
+ next() {
921
+ if (consumer.queue.length > 0) return Promise.resolve({
922
+ value: consumer.queue.shift(),
923
+ done: false
924
+ });
925
+ if (status.state === "errored") return Promise.reject(status.err);
926
+ if (status.state === "completed") return Promise.resolve({
927
+ value: void 0,
928
+ done: true
929
+ });
930
+ return new Promise((resolve, reject) => {
931
+ consumer.pending = {
932
+ resolve,
933
+ reject
934
+ };
935
+ });
936
+ },
937
+ return() {
938
+ consumers.delete(consumer);
939
+ if (consumer.pending) {
940
+ const p = consumer.pending;
941
+ consumer.pending = void 0;
942
+ p.resolve({
943
+ value: void 0,
944
+ done: true
945
+ });
946
+ }
947
+ return Promise.resolve({
948
+ value: void 0,
949
+ done: true
950
+ });
951
+ },
952
+ throw(err) {
953
+ consumers.delete(consumer);
954
+ return Promise.reject(err);
955
+ }
956
+ };
957
+ } }, {
958
+ next,
959
+ error,
960
+ complete,
961
+ subscribe
962
+ });
963
+ }
964
+ //#endregion
965
+ export { ContelloClient, asyncKeepalive, collectAsync, createAsyncIterableSubject, createContelloClient, createSourceSubscription, exponentialBackoff, filterAsync, firstAsync, mapAsync, runWithBackoff };
966
+
967
+ //# sourceMappingURL=index.js.map