@contello/client 1.0.2 → 1.1.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/cli.js CHANGED
@@ -4,7 +4,7 @@
4
4
  var command = process.argv[2];
5
5
  switch (command) {
6
6
  case "generate":
7
- await import("./generate-KEYVGQHL.js");
7
+ await import("./generate-GMV2AJ66.js");
8
8
  break;
9
9
  default:
10
10
  console.error(command ? `unknown command: ${command}` : "usage: contello-client <command>");
@@ -149,6 +149,7 @@ async function introspectSchema(url, project, token) {
149
149
  // src/generate/operation-types.ts
150
150
  import {
151
151
  Kind as Kind2,
152
+ doTypesOverlap as checkTypesOverlap,
152
153
  isCompositeType,
153
154
  isEnumType,
154
155
  isInterfaceType,
@@ -314,6 +315,11 @@ ${nested.slice(2)}`);
314
315
  if (fragment?.selectionSet) {
315
316
  const fragmentType = schema.getType(fragment.typeCondition.name.value);
316
317
  if (fragmentType && isCompositeType(fragmentType)) {
318
+ if (!checkTypesOverlap(schema, parentType, fragmentType)) {
319
+ throw new Error(
320
+ `fragment "${fragmentName}" (on ${fragmentType.name}) cannot be spread on type "${parentType.name}"`
321
+ );
322
+ }
317
323
  const nextVisited = new Set(visited);
318
324
  nextVisited.add(fragmentName);
319
325
  const fragmentResult = resolveSelectionSet(
@@ -629,6 +635,13 @@ function isComponentUnion(schema, typeName) {
629
635
  const type = schema.getType(typeName);
630
636
  return !!type && isUnionType2(type) && type.name === COMPONENT_UNION;
631
637
  }
638
+ function isComponentSubtype(schema, typeName) {
639
+ const union = schema.getType(COMPONENT_UNION);
640
+ if (!union || !isUnionType2(union)) {
641
+ return false;
642
+ }
643
+ return union.getTypes().some((t) => t.name === typeName);
644
+ }
632
645
  function getNamedTypeName(type) {
633
646
  if (isNonNullType3(type)) return getNamedTypeName(type.ofType);
634
647
  if (isListType3(type)) return getNamedTypeName(type.ofType);
@@ -740,7 +753,8 @@ function transformFragment(schema, fragment, fragments) {
740
753
  selectionSet = addFlatRefSelections(selectionSet);
741
754
  }
742
755
  if (isObjectType3(type)) {
743
- selectionSet = transformSelectionSet(schema, selectionSet, typeName, fragments, true);
756
+ const refsOnly = isComponentSubtype(schema, typeName);
757
+ selectionSet = transformSelectionSet(schema, selectionSet, typeName, fragments, refsOnly);
744
758
  } else if (isUnionType2(type)) {
745
759
  const newSelections = selectionSet.selections.map((sel) => {
746
760
  if (sel.kind === Kind3.INLINE_FRAGMENT && sel.typeCondition && sel.selectionSet) {
package/dist/index.cjs CHANGED
@@ -92,26 +92,122 @@ function decorateMessage(message) {
92
92
  return msg.message;
93
93
  }
94
94
 
95
- // src/download.ts
96
- async function downloadFile(url, token, fileId) {
97
- const response = await fetch(`${url}/api/v1/assets/files/${fileId}`, {
98
- headers: { token }
95
+ // src/http.ts
96
+ var import_undici = require("undici");
97
+ function createHttpAgent(options) {
98
+ return new import_undici.Agent({
99
+ pipelining: options?.pipelining ?? 10,
100
+ allowH2: options?.allowH2 ?? true,
101
+ maxConcurrentStreams: options?.maxConcurrentStreams ?? 128,
102
+ keepAliveTimeout: options?.keepAliveTimeout ?? 6e4,
103
+ autoSelectFamily: true,
104
+ autoSelectFamilyAttemptTimeout: 25
99
105
  });
100
- if (!response.ok) {
101
- throw new Error(`download failed: ${response.status} ${response.statusText}`);
102
- }
103
- if (!response.body) {
104
- throw new Error("download response has no body");
106
+ }
107
+ async function downloadFile(agent, url, token, fileId) {
108
+ const response = await (0, import_undici.request)(`${url}/api/v1/assets/files/${fileId}`, {
109
+ headers: { token },
110
+ dispatcher: agent
111
+ });
112
+ if (response.statusCode < 200 || response.statusCode >= 300) {
113
+ safeDestroyBody(response.body);
114
+ throw new Error(`download failed: ${response.statusCode}`);
105
115
  }
106
- const mimeType = response.headers.get("content-type") ?? "application/octet-stream";
107
- const size = Number(response.headers.get("content-length") ?? 0);
116
+ const mimeType = firstHeader(response.headers, "content-type") ?? "application/octet-stream";
117
+ const size = Number(firstHeader(response.headers, "content-length") ?? 0);
108
118
  return {
109
119
  mimeType,
110
120
  size,
111
- bytes: () => response.arrayBuffer().then((buf) => new Uint8Array(buf)),
112
- stream: () => response.body
121
+ bytes: async () => new Uint8Array(await response.body.arrayBuffer()),
122
+ stream: () => toWebStream(response.body)
113
123
  };
114
124
  }
125
+ async function proxyHls(agent, url, token, path, signal) {
126
+ const response = await (0, import_undici.request)(`${url}/api/v1/assets/video/hls/${path}`, {
127
+ headers: { token },
128
+ dispatcher: agent,
129
+ signal: signal ?? null
130
+ });
131
+ return buildProxyResult(response, signal);
132
+ }
133
+ function buildProxyResult(response, signal) {
134
+ const headers = new Headers();
135
+ for (const [key, value] of Object.entries(response.headers)) {
136
+ if (Array.isArray(value)) {
137
+ for (const v of value) headers.append(key, v);
138
+ } else if (value != null) {
139
+ headers.set(key, String(value));
140
+ }
141
+ }
142
+ return {
143
+ status: response.statusCode,
144
+ headers,
145
+ stream: () => toWebStream(response.body, signal)
146
+ };
147
+ }
148
+ function firstHeader(headers, key) {
149
+ const v = headers[key];
150
+ return Array.isArray(v) ? v[0] : v;
151
+ }
152
+ function safeDestroyBody(body) {
153
+ try {
154
+ body.on("error", () => {
155
+ });
156
+ body.destroy();
157
+ } catch {
158
+ }
159
+ }
160
+ function toWebStream(body, signal) {
161
+ let closed = false;
162
+ const cleanup = () => {
163
+ if (!closed) {
164
+ closed = true;
165
+ signal?.removeEventListener("abort", cleanup);
166
+ safeDestroyBody(body);
167
+ }
168
+ };
169
+ return new ReadableStream({
170
+ start(controller) {
171
+ signal?.addEventListener("abort", cleanup);
172
+ body.on("data", (chunk) => {
173
+ if (!closed && !signal?.aborted) {
174
+ try {
175
+ controller.enqueue(chunk);
176
+ } catch {
177
+ cleanup();
178
+ }
179
+ }
180
+ });
181
+ body.on("end", () => {
182
+ if (!closed && !signal?.aborted) {
183
+ closed = true;
184
+ signal?.removeEventListener("abort", cleanup);
185
+ try {
186
+ controller.close();
187
+ } catch {
188
+ }
189
+ }
190
+ });
191
+ body.on("error", (err) => {
192
+ cleanup();
193
+ if (err.name === "AbortError") {
194
+ try {
195
+ controller.close();
196
+ } catch {
197
+ }
198
+ return;
199
+ }
200
+ try {
201
+ controller.error(err);
202
+ } catch {
203
+ }
204
+ });
205
+ },
206
+ cancel() {
207
+ cleanup();
208
+ }
209
+ });
210
+ }
115
211
 
116
212
  // src/ping.ts
117
213
  var PING_QUERY = `query ContelloPing { contelloPing { response } }`;
@@ -368,11 +464,13 @@ var ContelloClient = class {
368
464
  _url;
369
465
  _project;
370
466
  _token;
467
+ _agent;
371
468
  constructor(options) {
372
469
  const { url, project, token, operations, connections = 1, connectionEvents } = options;
373
470
  this._url = url;
374
471
  this._project = project;
375
472
  this._token = token;
473
+ this._agent = createHttpAgent(options.http);
376
474
  const websocketUrl = `${url}/graphql/projects/${project}`.replace(/^http/i, "ws");
377
475
  let state = "disconnected";
378
476
  let connectedCount = 0;
@@ -443,6 +541,7 @@ var ContelloClient = class {
443
541
  }
444
542
  async destroy() {
445
543
  await this._pool.disconnect();
544
+ await this._agent.close();
446
545
  }
447
546
  async ping() {
448
547
  return ping((query) => (0, import_rxjs2.firstValueFrom)(this.subscribe(query)));
@@ -454,7 +553,10 @@ var ContelloClient = class {
454
553
  );
455
554
  }
456
555
  download(fileId) {
457
- return wrap("@contello/client:download", () => downloadFile(this._url, this._token, fileId));
556
+ return wrap("@contello/client:download", () => downloadFile(this._agent, this._url, this._token, fileId));
557
+ }
558
+ proxyHls(path, signal) {
559
+ return wrap("@contello/client:proxyHls", () => proxyHls(this._agent, this._url, this._token, path, signal));
458
560
  }
459
561
  upload(data, meta, options) {
460
562
  return wrap(
package/dist/index.d.cts CHANGED
@@ -1,12 +1,23 @@
1
1
  import { Observable } from 'rxjs';
2
2
  import { ReadableStream as ReadableStream$1 } from 'node:stream/web';
3
3
 
4
+ type HttpAgentOptions = {
5
+ pipelining?: number | undefined;
6
+ allowH2?: boolean | undefined;
7
+ maxConcurrentStreams?: number | undefined;
8
+ keepAliveTimeout?: number | undefined;
9
+ };
4
10
  type DownloadResult = {
5
11
  mimeType: string;
6
12
  size: number;
7
13
  bytes(): Promise<Uint8Array>;
8
14
  stream(): ReadableStream<Uint8Array>;
9
15
  };
16
+ type ProxyResult = {
17
+ status: number;
18
+ headers: Headers;
19
+ stream(): ReadableStream<Uint8Array>;
20
+ };
10
21
 
11
22
  type OperationKind = 'query' | 'mutation' | 'subscription';
12
23
  type OperationDef<TResult = unknown, TVariables = Record<string, unknown>, TKind extends OperationKind = OperationKind> = {
@@ -57,6 +68,7 @@ type ContelloClientOptions<T extends OperationMap | undefined = undefined> = {
57
68
  token: string;
58
69
  operations?: T | undefined;
59
70
  connections?: number | undefined;
71
+ http?: HttpAgentOptions | undefined;
60
72
  onConnected?: (() => void) | undefined;
61
73
  onReconnecting?: (() => void) | undefined;
62
74
  onError?: ((error: unknown) => void) | undefined;
@@ -68,6 +80,7 @@ declare class ContelloClient<T extends OperationMap | undefined = undefined> {
68
80
  private _url;
69
81
  private _project;
70
82
  private _token;
83
+ private _agent;
71
84
  constructor(options: ContelloClientOptions<T>);
72
85
  get rpc(): T extends OperationMap ? Rpc<T> : never;
73
86
  init(): Promise<void>;
@@ -75,9 +88,10 @@ declare class ContelloClient<T extends OperationMap | undefined = undefined> {
75
88
  ping(): Promise<void>;
76
89
  subscribe<TData>(query: string, variables?: Record<string, unknown> | undefined): Observable<TData>;
77
90
  download(fileId: string): Promise<DownloadResult>;
91
+ proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;
78
92
  upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;
79
93
  execute<TData>(query: string, variables?: Record<string, unknown> | undefined): Promise<TData>;
80
94
  }
81
95
  declare function createContelloClient<T extends OperationMap | undefined = undefined>(options: ContelloClientOptions<T>): ContelloClient<T>;
82
96
 
83
- export { type ConnectionContext, type ConnectionEvents, ContelloClient, type ContelloClientOptions, type DownloadResult, type OperationDef, type OperationKind, type OperationMap, type Rpc, type UploadData, type UploadMetadata, type UploadOptions, createContelloClient };
97
+ export { type ConnectionContext, type ConnectionEvents, ContelloClient, type ContelloClientOptions, type DownloadResult, type HttpAgentOptions, type OperationDef, type OperationKind, type OperationMap, type ProxyResult, type Rpc, type UploadData, type UploadMetadata, type UploadOptions, createContelloClient };
package/dist/index.d.ts CHANGED
@@ -1,12 +1,23 @@
1
1
  import { Observable } from 'rxjs';
2
2
  import { ReadableStream as ReadableStream$1 } from 'node:stream/web';
3
3
 
4
+ type HttpAgentOptions = {
5
+ pipelining?: number | undefined;
6
+ allowH2?: boolean | undefined;
7
+ maxConcurrentStreams?: number | undefined;
8
+ keepAliveTimeout?: number | undefined;
9
+ };
4
10
  type DownloadResult = {
5
11
  mimeType: string;
6
12
  size: number;
7
13
  bytes(): Promise<Uint8Array>;
8
14
  stream(): ReadableStream<Uint8Array>;
9
15
  };
16
+ type ProxyResult = {
17
+ status: number;
18
+ headers: Headers;
19
+ stream(): ReadableStream<Uint8Array>;
20
+ };
10
21
 
11
22
  type OperationKind = 'query' | 'mutation' | 'subscription';
12
23
  type OperationDef<TResult = unknown, TVariables = Record<string, unknown>, TKind extends OperationKind = OperationKind> = {
@@ -57,6 +68,7 @@ type ContelloClientOptions<T extends OperationMap | undefined = undefined> = {
57
68
  token: string;
58
69
  operations?: T | undefined;
59
70
  connections?: number | undefined;
71
+ http?: HttpAgentOptions | undefined;
60
72
  onConnected?: (() => void) | undefined;
61
73
  onReconnecting?: (() => void) | undefined;
62
74
  onError?: ((error: unknown) => void) | undefined;
@@ -68,6 +80,7 @@ declare class ContelloClient<T extends OperationMap | undefined = undefined> {
68
80
  private _url;
69
81
  private _project;
70
82
  private _token;
83
+ private _agent;
71
84
  constructor(options: ContelloClientOptions<T>);
72
85
  get rpc(): T extends OperationMap ? Rpc<T> : never;
73
86
  init(): Promise<void>;
@@ -75,9 +88,10 @@ declare class ContelloClient<T extends OperationMap | undefined = undefined> {
75
88
  ping(): Promise<void>;
76
89
  subscribe<TData>(query: string, variables?: Record<string, unknown> | undefined): Observable<TData>;
77
90
  download(fileId: string): Promise<DownloadResult>;
91
+ proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;
78
92
  upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;
79
93
  execute<TData>(query: string, variables?: Record<string, unknown> | undefined): Promise<TData>;
80
94
  }
81
95
  declare function createContelloClient<T extends OperationMap | undefined = undefined>(options: ContelloClientOptions<T>): ContelloClient<T>;
82
96
 
83
- export { type ConnectionContext, type ConnectionEvents, ContelloClient, type ContelloClientOptions, type DownloadResult, type OperationDef, type OperationKind, type OperationMap, type Rpc, type UploadData, type UploadMetadata, type UploadOptions, createContelloClient };
97
+ export { type ConnectionContext, type ConnectionEvents, ContelloClient, type ContelloClientOptions, type DownloadResult, type HttpAgentOptions, type OperationDef, type OperationKind, type OperationMap, type ProxyResult, type Rpc, type UploadData, type UploadMetadata, type UploadOptions, createContelloClient };
package/dist/index.js CHANGED
@@ -55,26 +55,122 @@ function decorateMessage(message) {
55
55
  return msg.message;
56
56
  }
57
57
 
58
- // src/download.ts
59
- async function downloadFile(url, token, fileId) {
60
- const response = await fetch(`${url}/api/v1/assets/files/${fileId}`, {
61
- headers: { token }
58
+ // src/http.ts
59
+ import { Agent, request as undiciRequest } from "undici";
60
+ function createHttpAgent(options) {
61
+ return new Agent({
62
+ pipelining: options?.pipelining ?? 10,
63
+ allowH2: options?.allowH2 ?? true,
64
+ maxConcurrentStreams: options?.maxConcurrentStreams ?? 128,
65
+ keepAliveTimeout: options?.keepAliveTimeout ?? 6e4,
66
+ autoSelectFamily: true,
67
+ autoSelectFamilyAttemptTimeout: 25
62
68
  });
63
- if (!response.ok) {
64
- throw new Error(`download failed: ${response.status} ${response.statusText}`);
65
- }
66
- if (!response.body) {
67
- throw new Error("download response has no body");
69
+ }
70
+ async function downloadFile(agent, url, token, fileId) {
71
+ const response = await undiciRequest(`${url}/api/v1/assets/files/${fileId}`, {
72
+ headers: { token },
73
+ dispatcher: agent
74
+ });
75
+ if (response.statusCode < 200 || response.statusCode >= 300) {
76
+ safeDestroyBody(response.body);
77
+ throw new Error(`download failed: ${response.statusCode}`);
68
78
  }
69
- const mimeType = response.headers.get("content-type") ?? "application/octet-stream";
70
- const size = Number(response.headers.get("content-length") ?? 0);
79
+ const mimeType = firstHeader(response.headers, "content-type") ?? "application/octet-stream";
80
+ const size = Number(firstHeader(response.headers, "content-length") ?? 0);
71
81
  return {
72
82
  mimeType,
73
83
  size,
74
- bytes: () => response.arrayBuffer().then((buf) => new Uint8Array(buf)),
75
- stream: () => response.body
84
+ bytes: async () => new Uint8Array(await response.body.arrayBuffer()),
85
+ stream: () => toWebStream(response.body)
76
86
  };
77
87
  }
88
+ async function proxyHls(agent, url, token, path, signal) {
89
+ const response = await undiciRequest(`${url}/api/v1/assets/video/hls/${path}`, {
90
+ headers: { token },
91
+ dispatcher: agent,
92
+ signal: signal ?? null
93
+ });
94
+ return buildProxyResult(response, signal);
95
+ }
96
+ function buildProxyResult(response, signal) {
97
+ const headers = new Headers();
98
+ for (const [key, value] of Object.entries(response.headers)) {
99
+ if (Array.isArray(value)) {
100
+ for (const v of value) headers.append(key, v);
101
+ } else if (value != null) {
102
+ headers.set(key, String(value));
103
+ }
104
+ }
105
+ return {
106
+ status: response.statusCode,
107
+ headers,
108
+ stream: () => toWebStream(response.body, signal)
109
+ };
110
+ }
111
+ function firstHeader(headers, key) {
112
+ const v = headers[key];
113
+ return Array.isArray(v) ? v[0] : v;
114
+ }
115
+ function safeDestroyBody(body) {
116
+ try {
117
+ body.on("error", () => {
118
+ });
119
+ body.destroy();
120
+ } catch {
121
+ }
122
+ }
123
+ function toWebStream(body, signal) {
124
+ let closed = false;
125
+ const cleanup = () => {
126
+ if (!closed) {
127
+ closed = true;
128
+ signal?.removeEventListener("abort", cleanup);
129
+ safeDestroyBody(body);
130
+ }
131
+ };
132
+ return new ReadableStream({
133
+ start(controller) {
134
+ signal?.addEventListener("abort", cleanup);
135
+ body.on("data", (chunk) => {
136
+ if (!closed && !signal?.aborted) {
137
+ try {
138
+ controller.enqueue(chunk);
139
+ } catch {
140
+ cleanup();
141
+ }
142
+ }
143
+ });
144
+ body.on("end", () => {
145
+ if (!closed && !signal?.aborted) {
146
+ closed = true;
147
+ signal?.removeEventListener("abort", cleanup);
148
+ try {
149
+ controller.close();
150
+ } catch {
151
+ }
152
+ }
153
+ });
154
+ body.on("error", (err) => {
155
+ cleanup();
156
+ if (err.name === "AbortError") {
157
+ try {
158
+ controller.close();
159
+ } catch {
160
+ }
161
+ return;
162
+ }
163
+ try {
164
+ controller.error(err);
165
+ } catch {
166
+ }
167
+ });
168
+ },
169
+ cancel() {
170
+ cleanup();
171
+ }
172
+ });
173
+ }
78
174
 
79
175
  // src/ping.ts
80
176
  var PING_QUERY = `query ContelloPing { contelloPing { response } }`;
@@ -331,11 +427,13 @@ var ContelloClient = class {
331
427
  _url;
332
428
  _project;
333
429
  _token;
430
+ _agent;
334
431
  constructor(options) {
335
432
  const { url, project, token, operations, connections = 1, connectionEvents } = options;
336
433
  this._url = url;
337
434
  this._project = project;
338
435
  this._token = token;
436
+ this._agent = createHttpAgent(options.http);
339
437
  const websocketUrl = `${url}/graphql/projects/${project}`.replace(/^http/i, "ws");
340
438
  let state = "disconnected";
341
439
  let connectedCount = 0;
@@ -406,6 +504,7 @@ var ContelloClient = class {
406
504
  }
407
505
  async destroy() {
408
506
  await this._pool.disconnect();
507
+ await this._agent.close();
409
508
  }
410
509
  async ping() {
411
510
  return ping((query) => firstValueFrom2(this.subscribe(query)));
@@ -417,7 +516,10 @@ var ContelloClient = class {
417
516
  );
418
517
  }
419
518
  download(fileId) {
420
- return wrap("@contello/client:download", () => downloadFile(this._url, this._token, fileId));
519
+ return wrap("@contello/client:download", () => downloadFile(this._agent, this._url, this._token, fileId));
520
+ }
521
+ proxyHls(path, signal) {
522
+ return wrap("@contello/client:proxyHls", () => proxyHls(this._agent, this._url, this._token, path, signal));
421
523
  }
422
524
  upload(data, meta, options) {
423
525
  return wrap(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contello/client",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "description": "GraphQL client for Contello CMS with WebSocket transport, connection pooling, and built-in codegen",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -11,8 +11,9 @@
11
11
  "directory": "packages/client"
12
12
  },
13
13
  "dependencies": {
14
- "graphql": "^16.13.1",
15
- "graphql-ws": "^6.0.7"
14
+ "graphql": "^16.13.2",
15
+ "graphql-ws": "^6.0.8",
16
+ "undici": "^8.1.0"
16
17
  },
17
18
  "peerDependencies": {
18
19
  "rxjs": "^7.0.0"