@contello/client 3.3.0 → 3.4.1
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.cjs +72 -0
- package/dist/index.d.cts +42 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts +42 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +72 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -3,6 +3,7 @@ let _contello_opentelemetry = require("@contello/opentelemetry");
|
|
|
3
3
|
let _entwico_dash_async = require("@entwico/dash/async");
|
|
4
4
|
let graphql_ws = require("graphql-ws");
|
|
5
5
|
let undici = require("undici");
|
|
6
|
+
let node_crypto = require("node:crypto");
|
|
6
7
|
//#region src/http.ts
|
|
7
8
|
const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
|
|
8
9
|
const FORWARDED_PROXY_HEADERS = /* @__PURE__ */ new Set([
|
|
@@ -159,6 +160,67 @@ function toWebStream(body, signal) {
|
|
|
159
160
|
});
|
|
160
161
|
}
|
|
161
162
|
//#endregion
|
|
163
|
+
//#region src/introspection.ts
|
|
164
|
+
const INTROSPECT_QUERY = `query ContelloIntrospectToken($token: String!) {
|
|
165
|
+
contelloIntrospectToken(token: $token) {
|
|
166
|
+
active audience expiresAt user { id username firstName lastName email } permissions { resourceType scope actions }
|
|
167
|
+
}
|
|
168
|
+
}`;
|
|
169
|
+
async function introspectToken(execute, token) {
|
|
170
|
+
const { contelloIntrospectToken: result } = await execute(INTROSPECT_QUERY, { token });
|
|
171
|
+
if (!result.active || !result.audience || !result.expiresAt || !result.user) return { active: false };
|
|
172
|
+
return {
|
|
173
|
+
active: true,
|
|
174
|
+
audience: result.audience,
|
|
175
|
+
expiresAt: new Date(result.expiresAt),
|
|
176
|
+
user: result.user,
|
|
177
|
+
permissions: result.permissions ?? []
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
const DEFAULT_MAX_AGE_MS = 6e4;
|
|
181
|
+
const DEFAULT_MAX_ENTRIES = 1e4;
|
|
182
|
+
function createTokenIntrospector(introspect, options) {
|
|
183
|
+
const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
|
|
184
|
+
const maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES;
|
|
185
|
+
const audiences = new Set(options.audiences);
|
|
186
|
+
const cache = /* @__PURE__ */ new Map();
|
|
187
|
+
const pending = /* @__PURE__ */ new Map();
|
|
188
|
+
const evict = (now) => {
|
|
189
|
+
for (const [key, entry] of cache) if (entry.until <= now) cache.delete(key);
|
|
190
|
+
for (const key of cache.keys()) {
|
|
191
|
+
if (cache.size < maxEntries) break;
|
|
192
|
+
cache.delete(key);
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
const lookup = async (token, key) => {
|
|
196
|
+
try {
|
|
197
|
+
let result = await introspect(token);
|
|
198
|
+
if (result.active && !audiences.has(result.audience)) result = { active: false };
|
|
199
|
+
const now = Date.now();
|
|
200
|
+
const until = result.active ? Math.min(result.expiresAt.getTime(), now + maxAgeMs) : now + maxAgeMs;
|
|
201
|
+
if (cache.size >= maxEntries) evict(now);
|
|
202
|
+
cache.set(key, {
|
|
203
|
+
result,
|
|
204
|
+
until
|
|
205
|
+
});
|
|
206
|
+
return result;
|
|
207
|
+
} finally {
|
|
208
|
+
pending.delete(key);
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
return { introspect: (token) => {
|
|
212
|
+
const key = (0, node_crypto.createHash)("sha256").update(token).digest("base64url");
|
|
213
|
+
const cached = cache.get(key);
|
|
214
|
+
if (cached && cached.until > Date.now()) return cached.result;
|
|
215
|
+
let running = pending.get(key);
|
|
216
|
+
if (!running) {
|
|
217
|
+
running = lookup(token, key);
|
|
218
|
+
pending.set(key, running);
|
|
219
|
+
}
|
|
220
|
+
return running;
|
|
221
|
+
} };
|
|
222
|
+
}
|
|
223
|
+
//#endregion
|
|
162
224
|
//#region src/ping.ts
|
|
163
225
|
const PING_QUERY = `query ContelloPing { contelloPing { response } }`;
|
|
164
226
|
async function ping(execute) {
|
|
@@ -743,6 +805,15 @@ var ContelloClient = class {
|
|
|
743
805
|
return ping((query) => (0, _entwico_dash_async.firstAsync)(this.subscribe(query)));
|
|
744
806
|
}
|
|
745
807
|
/**
|
|
808
|
+
* What a temporary token the Contello ui handed to an extension page stands for in the project of
|
|
809
|
+
* this client: the user and the user's effective permissions, or inactive. The client's
|
|
810
|
+
* application needs read access to the project. See `createTokenIntrospector` for the caching
|
|
811
|
+
* wrapper a backend puts in front of its requests.
|
|
812
|
+
*/
|
|
813
|
+
introspectToken(token) {
|
|
814
|
+
return wrap("@contello/client:introspectToken", () => introspectToken((query, variables) => (0, _entwico_dash_async.firstAsync)(this.subscribe(query, variables)), token));
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
746
817
|
* Open a subscription on the websocket. Each `[Symbol.asyncIterator]()` call (the implicit one
|
|
747
818
|
* from `for await`, or via `rxjs.from(this)`) starts a fresh server subscription and tears it
|
|
748
819
|
* down when the iterator is returned (`break`, error, or explicit stop).
|
|
@@ -913,4 +984,5 @@ exports.createContelloClient = createContelloClient;
|
|
|
913
984
|
exports.createSourceMutation = createSourceMutation;
|
|
914
985
|
exports.createSourceMutationVariables = createSourceMutationVariables;
|
|
915
986
|
exports.createSourceSubscription = createSourceSubscription;
|
|
987
|
+
exports.createTokenIntrospector = createTokenIntrospector;
|
|
916
988
|
exports.readSourceMutationId = readSourceMutationId;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import "undici";
|
|
2
|
+
import { MaybePromise } from "@entwico/dash";
|
|
2
3
|
import { ReadableStream as ReadableStream$1 } from "node:stream/web";
|
|
3
4
|
//#region src/http.d.ts
|
|
4
5
|
type HttpAgentOptions = {
|
|
@@ -29,6 +30,39 @@ type SitemapProxyOptions = {
|
|
|
29
30
|
ifNoneMatch?: string | undefined;
|
|
30
31
|
};
|
|
31
32
|
//#endregion
|
|
33
|
+
//#region src/introspection.d.ts
|
|
34
|
+
type ResourceAction = 'READ' | 'CREATE' | 'UPDATE' | 'DELETE';
|
|
35
|
+
type ResourcePermissions = {
|
|
36
|
+
resourceType: 'ENTITY' | 'ASSET' | 'ROUTE' | 'I18N_MESSAGE_COLLECTION' | 'MODELLING' | 'EXTENSION' | (string & {});
|
|
37
|
+
scope: string | null;
|
|
38
|
+
actions: ResourceAction[];
|
|
39
|
+
};
|
|
40
|
+
type IntrospectedUser = {
|
|
41
|
+
id: string;
|
|
42
|
+
username: string;
|
|
43
|
+
firstName: string;
|
|
44
|
+
lastName: string;
|
|
45
|
+
email: string;
|
|
46
|
+
};
|
|
47
|
+
type TokenIntrospection = {
|
|
48
|
+
active: false;
|
|
49
|
+
} | {
|
|
50
|
+
active: true;
|
|
51
|
+
audience: string;
|
|
52
|
+
expiresAt: Date;
|
|
53
|
+
user: IntrospectedUser;
|
|
54
|
+
permissions: ResourcePermissions[];
|
|
55
|
+
};
|
|
56
|
+
type TokenIntrospectorOptions = {
|
|
57
|
+
audiences: string[];
|
|
58
|
+
maxAgeMs?: number | undefined;
|
|
59
|
+
maxEntries?: number | undefined;
|
|
60
|
+
};
|
|
61
|
+
type TokenIntrospector = {
|
|
62
|
+
introspect: (token: string) => MaybePromise<TokenIntrospection>;
|
|
63
|
+
};
|
|
64
|
+
export declare function createTokenIntrospector(introspect: (token: string) => Promise<TokenIntrospection>, options: TokenIntrospectorOptions): TokenIntrospector;
|
|
65
|
+
//#endregion
|
|
32
66
|
//#region src/types.d.ts
|
|
33
67
|
type OperationKind = 'query' | 'mutation' | 'subscription';
|
|
34
68
|
type OperationDef<TResult = unknown, TVariables = Record<string, unknown>, TKind extends OperationKind = OperationKind> = {
|
|
@@ -230,6 +264,13 @@ export declare class ContelloClient<TSchema extends Schema | undefined = undefin
|
|
|
230
264
|
init(): Promise<void>;
|
|
231
265
|
destroy(): Promise<void>;
|
|
232
266
|
ping(): Promise<void>;
|
|
267
|
+
/**
|
|
268
|
+
* What a temporary token the Contello ui handed to an extension page stands for in the project of
|
|
269
|
+
* this client: the user and the user's effective permissions, or inactive. The client's
|
|
270
|
+
* application needs read access to the project. See `createTokenIntrospector` for the caching
|
|
271
|
+
* wrapper a backend puts in front of its requests.
|
|
272
|
+
*/
|
|
273
|
+
introspectToken(token: string): Promise<TokenIntrospection>;
|
|
233
274
|
/**
|
|
234
275
|
* Open a subscription on the websocket. Each `[Symbol.asyncIterator]()` call (the implicit one
|
|
235
276
|
* from `for await`, or via `rxjs.from(this)`) starts a fresh server subscription and tears it
|
|
@@ -296,5 +337,5 @@ export declare function readSourceMutationId(binding: SourceMutationBinding, res
|
|
|
296
337
|
*/
|
|
297
338
|
export declare const BUILT_IN_MUTATIONS: Partial<Record<SourceCardinality, SourceMutations>>;
|
|
298
339
|
//#endregion
|
|
299
|
-
export type { ConnectionContext, ConnectionEvents, ContelloClientOptions, DownloadResult, HttpAgentOptions, LocalDate, LocalDateTime, OperationDef, OperationKind, OperationMap, ProxyResult, Rpc, Schema, SitemapProxyOptions, SourceAccessors, SourceCardinality, SourceDef, SourceMap, SourceMutationArgument, SourceMutationBinding, SourceMutationKind, SourceMutationResult, SourceMutationValues, SourceMutations, SourceWrites, UploadData, UploadMetadata, UploadOptions };
|
|
340
|
+
export type { ConnectionContext, ConnectionEvents, ContelloClientOptions, DownloadResult, HttpAgentOptions, IntrospectedUser, LocalDate, LocalDateTime, OperationDef, OperationKind, OperationMap, ProxyResult, ResourceAction, ResourcePermissions, Rpc, Schema, SitemapProxyOptions, SourceAccessors, SourceCardinality, SourceDef, SourceMap, SourceMutationArgument, SourceMutationBinding, SourceMutationKind, SourceMutationResult, SourceMutationValues, SourceMutations, SourceWrites, TokenIntrospection, TokenIntrospector, TokenIntrospectorOptions, UploadData, UploadMetadata, UploadOptions };
|
|
300
341
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":["NodeReadableStream"],"sources":["../src/http.ts","../src/types.ts","../src/upload.ts","../src/client.ts","../src/scalars.ts","../src/source-subscription.ts","../src/source-mutation.ts","../src/built-in-mutations.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":["NodeReadableStream"],"sources":["../src/http.ts","../src/introspection.ts","../src/types.ts","../src/upload.ts","../src/client.ts","../src/scalars.ts","../src/source-subscription.ts","../src/source-mutation.ts","../src/built-in-mutations.ts"],"mappings":";;;;KAkCY;EACV;EACA;EACA;EACA;;KAcU;EACV;EACA;EACA,SAAS,QAAQ;EACjB,UAAU,eAAe;;KAiCf;EACV;EACA,SAAS;EACT,UAAU,eAAe;;KAqBf;;EAEV;;EAEA;;EAEA;;EAEA;;;;KC/GU;KAKA;EACV;EACA;EACA,SAAS;;KAGC;EACV;EACA;EACA;EACA;EACA;;KAKU;EACN;;EAEF;EAEA;EACA,WAAW;EACX,MAAM;EACN,aAAa;;KAgCL;EAGV;EAGA;EAEA;;KAGU;EAEV,aAAa,kBAAkB,aAAa;;wBAU9B,wBACd,aAAa,kBAAkB,QAAQ,qBACvC,SAAS,2BACR;;;KCjGS;KAEA,aACV,mBACA,aAAa,yBACb,cAAc,gBAAgB;EAE9B;EACA,MAAM;;EAEN,WAAW;;EAEX,cAAc;;KAGJ,eAAe,eAAe;KAE9B,YAAY,UAAU,gBAAgB,YAAY;KAClD,eAAe,UAAU,gBAAgB,YAAY;KAErD,UAAU,UAAU,gBAAgB,mCAC5C,eAAe,WAAW,8BAClB,cAAc,YAAY,OAC/B,WAAW,eAAe,OAAO,cAAc,YAAY,MAC9D,eAAe,WAAW,8BAClB,QAAQ,YAAY,OACzB,WAAW,eAAe,OAAO,QAAQ,YAAY;KAEhD,IAAI,UAAU,mBACvB,WAAW,IAAI,UAAU,EAAE;;;;;;;;;KAWlB;;;;;;KAOA;;EAEV;;EAEA;;EAEA;;;;;EAKA;;;;;;;;KASU;;;;;KAM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AS;EACtB,YAAY,SAAS,mBAAmB;;KAG9B,sBAAsB,gBAAgB;EAChD;EACA;EACA;EACA,SAAS;EACT;EACA,OAAO;EACP;EACA;EACA,YAAY;EACZ,mBAAmB;;qBAKR,eAAe,gBAAgB;UAClC;UACA;UACA;UACA;UACA;UACA;UACA;EAEI,YAAA,SAAS,sBAAsB;MAuFvC,OAAO,gBAAgB,aAAa,kBAAkB,IAAI;MAQ1D,WAAW,gBAAgB,kBAAkB,iBAAiB,gBAAgB;EAQ5E,QAAQ;EAIR,WAAW;EAKX,QAAQ;;;;;;;EAWd,gBAAgB,gBAAgB,QAAQ;;;;;;EAaxC,UAAU,OAAO,eAAe,YAAY,sCAAsC,cAAc;EA2FhG,SAAS,iBAAiB,QAAQ;EAIlC,SAAS,cAAc,SAAS,0BAA0B,QAAQ;EAIlE,aACE,mBACA,SAAS,qBACT,SAAS,0BACR,QAAQ;EAOX,OAAO,MAAM,YAAY,MAAM,gBAAgB,UAAU,4BAA4B;EAOrF,QAAQ,OAAO,eAAe,YAAY,sCAAsC,QAAQ;;wBAS1E,qBAAqB,gBAAgB,gCACnD,SAAS,sBAAsB,WAC9B,eAAe;;;KCrUN;EACV;EACA;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;EACA;;;;wBCcc,yBAAyB,QAAQ;;;KCvBrC,2BAA2B;;KAG3B;EACV;EACA;;;wBAwBc,qBAAqB,QAAQ,WAAW,MAAM;;;;;;;wBA+B9C,8BACd,SAAS,uBACT,QAAQ,uBACP;;wBAYa,qBAAqB,SAAS,uBAAuB;;;;;;;;;;;;;;;qBChExD,oBAAoB,QAAQ,OAAO,mBAAmB"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Agent } from "undici";
|
|
2
|
+
import { MaybePromise } from "@entwico/dash";
|
|
2
3
|
import { ReadableStream as ReadableStream$1 } from "node:stream/web";
|
|
3
4
|
//#region src/http.d.ts
|
|
4
5
|
type HttpAgentOptions = {
|
|
@@ -29,6 +30,39 @@ type SitemapProxyOptions = {
|
|
|
29
30
|
ifNoneMatch?: string | undefined;
|
|
30
31
|
};
|
|
31
32
|
//#endregion
|
|
33
|
+
//#region src/introspection.d.ts
|
|
34
|
+
type ResourceAction = 'READ' | 'CREATE' | 'UPDATE' | 'DELETE';
|
|
35
|
+
type ResourcePermissions = {
|
|
36
|
+
resourceType: 'ENTITY' | 'ASSET' | 'ROUTE' | 'I18N_MESSAGE_COLLECTION' | 'MODELLING' | 'EXTENSION' | (string & {});
|
|
37
|
+
scope: string | null;
|
|
38
|
+
actions: ResourceAction[];
|
|
39
|
+
};
|
|
40
|
+
type IntrospectedUser = {
|
|
41
|
+
id: string;
|
|
42
|
+
username: string;
|
|
43
|
+
firstName: string;
|
|
44
|
+
lastName: string;
|
|
45
|
+
email: string;
|
|
46
|
+
};
|
|
47
|
+
type TokenIntrospection = {
|
|
48
|
+
active: false;
|
|
49
|
+
} | {
|
|
50
|
+
active: true;
|
|
51
|
+
audience: string;
|
|
52
|
+
expiresAt: Date;
|
|
53
|
+
user: IntrospectedUser;
|
|
54
|
+
permissions: ResourcePermissions[];
|
|
55
|
+
};
|
|
56
|
+
type TokenIntrospectorOptions = {
|
|
57
|
+
audiences: string[];
|
|
58
|
+
maxAgeMs?: number | undefined;
|
|
59
|
+
maxEntries?: number | undefined;
|
|
60
|
+
};
|
|
61
|
+
type TokenIntrospector = {
|
|
62
|
+
introspect: (token: string) => MaybePromise<TokenIntrospection>;
|
|
63
|
+
};
|
|
64
|
+
export declare function createTokenIntrospector(introspect: (token: string) => Promise<TokenIntrospection>, options: TokenIntrospectorOptions): TokenIntrospector;
|
|
65
|
+
//#endregion
|
|
32
66
|
//#region src/types.d.ts
|
|
33
67
|
type OperationKind = 'query' | 'mutation' | 'subscription';
|
|
34
68
|
type OperationDef<TResult = unknown, TVariables = Record<string, unknown>, TKind extends OperationKind = OperationKind> = {
|
|
@@ -230,6 +264,13 @@ export declare class ContelloClient<TSchema extends Schema | undefined = undefin
|
|
|
230
264
|
init(): Promise<void>;
|
|
231
265
|
destroy(): Promise<void>;
|
|
232
266
|
ping(): Promise<void>;
|
|
267
|
+
/**
|
|
268
|
+
* What a temporary token the Contello ui handed to an extension page stands for in the project of
|
|
269
|
+
* this client: the user and the user's effective permissions, or inactive. The client's
|
|
270
|
+
* application needs read access to the project. See `createTokenIntrospector` for the caching
|
|
271
|
+
* wrapper a backend puts in front of its requests.
|
|
272
|
+
*/
|
|
273
|
+
introspectToken(token: string): Promise<TokenIntrospection>;
|
|
233
274
|
/**
|
|
234
275
|
* Open a subscription on the websocket. Each `[Symbol.asyncIterator]()` call (the implicit one
|
|
235
276
|
* from `for await`, or via `rxjs.from(this)`) starts a fresh server subscription and tears it
|
|
@@ -296,5 +337,5 @@ export declare function readSourceMutationId(binding: SourceMutationBinding, res
|
|
|
296
337
|
*/
|
|
297
338
|
export declare const BUILT_IN_MUTATIONS: Partial<Record<SourceCardinality, SourceMutations>>;
|
|
298
339
|
//#endregion
|
|
299
|
-
export type { ConnectionContext, ConnectionEvents, ContelloClientOptions, DownloadResult, HttpAgentOptions, LocalDate, LocalDateTime, OperationDef, OperationKind, OperationMap, ProxyResult, Rpc, Schema, SitemapProxyOptions, SourceAccessors, SourceCardinality, SourceDef, SourceMap, SourceMutationArgument, SourceMutationBinding, SourceMutationKind, SourceMutationResult, SourceMutationValues, SourceMutations, SourceWrites, UploadData, UploadMetadata, UploadOptions };
|
|
340
|
+
export type { ConnectionContext, ConnectionEvents, ContelloClientOptions, DownloadResult, HttpAgentOptions, IntrospectedUser, LocalDate, LocalDateTime, OperationDef, OperationKind, OperationMap, ProxyResult, ResourceAction, ResourcePermissions, Rpc, Schema, SitemapProxyOptions, SourceAccessors, SourceCardinality, SourceDef, SourceMap, SourceMutationArgument, SourceMutationBinding, SourceMutationKind, SourceMutationResult, SourceMutationValues, SourceMutations, SourceWrites, TokenIntrospection, TokenIntrospector, TokenIntrospectorOptions, UploadData, UploadMetadata, UploadOptions };
|
|
300
341
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["NodeReadableStream"],"sources":["../src/http.ts","../src/types.ts","../src/upload.ts","../src/client.ts","../src/scalars.ts","../src/source-subscription.ts","../src/source-mutation.ts","../src/built-in-mutations.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["NodeReadableStream"],"sources":["../src/http.ts","../src/introspection.ts","../src/types.ts","../src/upload.ts","../src/client.ts","../src/scalars.ts","../src/source-subscription.ts","../src/source-mutation.ts","../src/built-in-mutations.ts"],"mappings":";;;;KAkCY;EACV;EACA;EACA;EACA;;KAcU;EACV;EACA;EACA,SAAS,QAAQ;EACjB,UAAU,eAAe;;KAiCf;EACV;EACA,SAAS;EACT,UAAU,eAAe;;KAqBf;;EAEV;;EAEA;;EAEA;;EAEA;;;;KC/GU;KAKA;EACV;EACA;EACA,SAAS;;KAGC;EACV;EACA;EACA;EACA;EACA;;KAKU;EACN;;EAEF;EAEA;EACA,WAAW;EACX,MAAM;EACN,aAAa;;KAgCL;EAGV;EAGA;EAEA;;KAGU;EAEV,aAAa,kBAAkB,aAAa;;wBAU9B,wBACd,aAAa,kBAAkB,QAAQ,qBACvC,SAAS,2BACR;;;KCjGS;KAEA,aACV,mBACA,aAAa,yBACb,cAAc,gBAAgB;EAE9B;EACA,MAAM;;EAEN,WAAW;;EAEX,cAAc;;KAGJ,eAAe,eAAe;KAE9B,YAAY,UAAU,gBAAgB,YAAY;KAClD,eAAe,UAAU,gBAAgB,YAAY;KAErD,UAAU,UAAU,gBAAgB,mCAC5C,eAAe,WAAW,8BAClB,cAAc,YAAY,OAC/B,WAAW,eAAe,OAAO,cAAc,YAAY,MAC9D,eAAe,WAAW,8BAClB,QAAQ,YAAY,OACzB,WAAW,eAAe,OAAO,QAAQ,YAAY;KAEhD,IAAI,UAAU,mBACvB,WAAW,IAAI,UAAU,EA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AQ;;;;KCGE;EACV;EACA;;KAGU;EACV,gBAAgB,SAAS;EACzB,iBAAiB,SAAS;EAC1B,aAAa,SAAS;EACtB,YAAY,SAAS,mBAAmB;;KAG9B,sBAAsB,gBAAgB;EAChD;EACA;EACA;EACA,SAAS;EACT;EACA,OAAO;EACP;EACA;EACA,YAAY;EACZ,mBAAmB;;qBAKR,eAAe,gBAAgB;UAClC;UACA;UACA;UACA;UACA;UACA;UACA;EAEI,YAAA,SAAS,sBAAsB;MAuFvC,OAAO,gBAAgB,aAAa,kBAAkB,IAAI;MAQ1D,WAAW,gBAAgB,kBAAkB,iBAAiB,gBAAgB;EAQ5E,QAAQ;EAIR,WAAW;EAKX,QAAQ;;;;;;;EAWd,gBAAgB,gBAAgB,QAAQ;;;;;;EAaxC,UAAU,OAAO,eAAe,YAAY,sCAAsC,cAAc;EA2FhG,SAAS,iBAAiB,QAAQ;EAIlC,SAAS,cAAc,SAAS,0BAA0B,QAAQ;EAIlE,aACE,mBACA,SAAS,qBACT,SAAS,0BACR,QAAQ;EAOX,OAAO,MAAM,YAAY,MAAM,gBAAgB,UAAU,4BAA4B;EAOrF,QAAQ,OAAO,eAAe,YAAY,sCAAsC,QAAQ;;wBAS1E,qBAAqB,gBAAgB,gCACnD,SAAS,sBAAsB,WAC9B,eAAe;;;KCrUN;EACV;EACA;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;EACA;;;;wBCcc,yBAAyB,QAAQ;;;KCvBrC,2BAA2B;;KAG3B;EACV;EACA;;;wBAwBc,qBAAqB,QAAQ,WAAW,MAAM;;;;;;;wBA+B9C,8BACd,SAAS,uBACT,QAAQ,uBACP;;wBAYa,qBAAqB,SAAS,uBAAuB;;;;;;;;;;;;;;;qBChExD,oBAAoB,QAAQ,OAAO,mBAAmB"}
|
package/dist/index.js
CHANGED
|
@@ -2,6 +2,7 @@ import { createOperationTelemetry, graphqlOperationAttributes, injectTraceContex
|
|
|
2
2
|
import { concatAsync, exponentialBackoff, firstAsync, mapAsync } from "@entwico/dash/async";
|
|
3
3
|
import { createClient } from "graphql-ws";
|
|
4
4
|
import { Agent, request } from "undici";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
5
6
|
//#region src/http.ts
|
|
6
7
|
const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
|
|
7
8
|
const FORWARDED_PROXY_HEADERS = /* @__PURE__ */ new Set([
|
|
@@ -158,6 +159,67 @@ function toWebStream(body, signal) {
|
|
|
158
159
|
});
|
|
159
160
|
}
|
|
160
161
|
//#endregion
|
|
162
|
+
//#region src/introspection.ts
|
|
163
|
+
const INTROSPECT_QUERY = `query ContelloIntrospectToken($token: String!) {
|
|
164
|
+
contelloIntrospectToken(token: $token) {
|
|
165
|
+
active audience expiresAt user { id username firstName lastName email } permissions { resourceType scope actions }
|
|
166
|
+
}
|
|
167
|
+
}`;
|
|
168
|
+
async function introspectToken(execute, token) {
|
|
169
|
+
const { contelloIntrospectToken: result } = await execute(INTROSPECT_QUERY, { token });
|
|
170
|
+
if (!result.active || !result.audience || !result.expiresAt || !result.user) return { active: false };
|
|
171
|
+
return {
|
|
172
|
+
active: true,
|
|
173
|
+
audience: result.audience,
|
|
174
|
+
expiresAt: new Date(result.expiresAt),
|
|
175
|
+
user: result.user,
|
|
176
|
+
permissions: result.permissions ?? []
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
const DEFAULT_MAX_AGE_MS = 6e4;
|
|
180
|
+
const DEFAULT_MAX_ENTRIES = 1e4;
|
|
181
|
+
function createTokenIntrospector(introspect, options) {
|
|
182
|
+
const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
|
|
183
|
+
const maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES;
|
|
184
|
+
const audiences = new Set(options.audiences);
|
|
185
|
+
const cache = /* @__PURE__ */ new Map();
|
|
186
|
+
const pending = /* @__PURE__ */ new Map();
|
|
187
|
+
const evict = (now) => {
|
|
188
|
+
for (const [key, entry] of cache) if (entry.until <= now) cache.delete(key);
|
|
189
|
+
for (const key of cache.keys()) {
|
|
190
|
+
if (cache.size < maxEntries) break;
|
|
191
|
+
cache.delete(key);
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
const lookup = async (token, key) => {
|
|
195
|
+
try {
|
|
196
|
+
let result = await introspect(token);
|
|
197
|
+
if (result.active && !audiences.has(result.audience)) result = { active: false };
|
|
198
|
+
const now = Date.now();
|
|
199
|
+
const until = result.active ? Math.min(result.expiresAt.getTime(), now + maxAgeMs) : now + maxAgeMs;
|
|
200
|
+
if (cache.size >= maxEntries) evict(now);
|
|
201
|
+
cache.set(key, {
|
|
202
|
+
result,
|
|
203
|
+
until
|
|
204
|
+
});
|
|
205
|
+
return result;
|
|
206
|
+
} finally {
|
|
207
|
+
pending.delete(key);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
return { introspect: (token) => {
|
|
211
|
+
const key = createHash("sha256").update(token).digest("base64url");
|
|
212
|
+
const cached = cache.get(key);
|
|
213
|
+
if (cached && cached.until > Date.now()) return cached.result;
|
|
214
|
+
let running = pending.get(key);
|
|
215
|
+
if (!running) {
|
|
216
|
+
running = lookup(token, key);
|
|
217
|
+
pending.set(key, running);
|
|
218
|
+
}
|
|
219
|
+
return running;
|
|
220
|
+
} };
|
|
221
|
+
}
|
|
222
|
+
//#endregion
|
|
161
223
|
//#region src/ping.ts
|
|
162
224
|
const PING_QUERY = `query ContelloPing { contelloPing { response } }`;
|
|
163
225
|
async function ping(execute) {
|
|
@@ -742,6 +804,15 @@ var ContelloClient = class {
|
|
|
742
804
|
return ping((query) => firstAsync(this.subscribe(query)));
|
|
743
805
|
}
|
|
744
806
|
/**
|
|
807
|
+
* What a temporary token the Contello ui handed to an extension page stands for in the project of
|
|
808
|
+
* this client: the user and the user's effective permissions, or inactive. The client's
|
|
809
|
+
* application needs read access to the project. See `createTokenIntrospector` for the caching
|
|
810
|
+
* wrapper a backend puts in front of its requests.
|
|
811
|
+
*/
|
|
812
|
+
introspectToken(token) {
|
|
813
|
+
return wrap("@contello/client:introspectToken", () => introspectToken((query, variables) => firstAsync(this.subscribe(query, variables)), token));
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
745
816
|
* Open a subscription on the websocket. Each `[Symbol.asyncIterator]()` call (the implicit one
|
|
746
817
|
* from `for await`, or via `rxjs.from(this)`) starts a fresh server subscription and tears it
|
|
747
818
|
* down when the iterator is returned (`break`, error, or explicit stop).
|
|
@@ -906,6 +977,6 @@ const BUILT_IN_MUTATIONS = {
|
|
|
906
977
|
}
|
|
907
978
|
};
|
|
908
979
|
//#endregion
|
|
909
|
-
export { BUILT_IN_MUTATIONS, ContelloClient, createContelloClient, createSourceMutation, createSourceMutationVariables, createSourceSubscription, readSourceMutationId };
|
|
980
|
+
export { BUILT_IN_MUTATIONS, ContelloClient, createContelloClient, createSourceMutation, createSourceMutationVariables, createSourceSubscription, createTokenIntrospector, readSourceMutationId };
|
|
910
981
|
|
|
911
982
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["undiciRequest","cache","createSelection","uploadAsset"],"sources":["../src/http.ts","../src/ping.ts","../src/pool.ts","../src/telemetry.ts","../src/scalars.ts","../src/transform-variables.ts","../src/rpc.ts","../src/source-mutation.ts","../src/source-subscription.ts","../src/sources.ts","../src/transform-response.ts","../src/upload.ts","../src/client.ts","../src/built-in-mutations.ts"],"sourcesContent":["import { Agent, type Dispatcher, request as undiciRequest } from 'undici';\n\nconst SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;\n\nconst FORWARDED_PROXY_HEADERS = new Set([\n 'content-type',\n 'content-length',\n 'content-range',\n 'content-encoding',\n 'accept-ranges',\n 'cache-control',\n 'etag',\n 'last-modified',\n 'expires',\n 'age',\n 'vary',\n]);\n\nfunction assertSafeSegment(segment: string, kind: string): void {\n if (segment === '.' || segment === '..' || !SAFE_SEGMENT.test(segment)) {\n throw new Error(`invalid ${kind}`);\n }\n}\n\nfunction assertSafeAssetPath(path: string, kind: string): void {\n if (path === '') {\n throw new Error(`invalid ${kind}`);\n }\n\n for (const segment of path.split('/')) {\n assertSafeSegment(segment, kind);\n }\n}\n\nexport type HttpAgentOptions = {\n pipelining?: number | undefined;\n allowH2?: boolean | undefined;\n maxConcurrentStreams?: number | undefined;\n keepAliveTimeout?: number | undefined;\n};\n\nexport function createHttpAgent(options?: HttpAgentOptions | undefined): Agent {\n return new Agent({\n pipelining: options?.pipelining ?? 10,\n allowH2: options?.allowH2 ?? true,\n maxConcurrentStreams: options?.maxConcurrentStreams ?? 128,\n keepAliveTimeout: options?.keepAliveTimeout ?? 60_000,\n autoSelectFamily: true,\n autoSelectFamilyAttemptTimeout: 25,\n });\n}\n\nexport type DownloadResult = {\n mimeType: string;\n size: number;\n bytes(): Promise<Uint8Array>;\n stream(): ReadableStream<Uint8Array>;\n};\n\nexport async function downloadFile(\n agent: Dispatcher,\n url: string,\n token: string,\n fileId: string,\n): Promise<DownloadResult> {\n assertSafeSegment(fileId, 'file id');\n\n const response = await undiciRequest(`${url}/api/v1/assets/files/${fileId}`, {\n headers: { token },\n dispatcher: agent,\n });\n\n if (response.statusCode < 200 || response.statusCode >= 300) {\n safeDestroyBody(response.body);\n\n throw new Error(`download failed: ${response.statusCode}`);\n }\n\n const mimeType = firstHeader(response.headers, 'content-type') ?? 'application/octet-stream';\n const size = Number(firstHeader(response.headers, 'content-length') ?? 0);\n\n return {\n mimeType,\n size,\n bytes: async () => new Uint8Array(await response.body.arrayBuffer()),\n stream: () => toWebStream(response.body),\n };\n}\n\nexport type ProxyResult = {\n status: number;\n headers: Headers;\n stream(): ReadableStream<Uint8Array>;\n};\n\nexport async function proxyHls(\n agent: Dispatcher,\n url: string,\n token: string,\n path: string,\n signal?: AbortSignal | undefined,\n): Promise<ProxyResult> {\n assertSafeAssetPath(path, 'hls path');\n\n const response = await undiciRequest(`${url}/api/v1/assets/video/hls/${path}`, {\n headers: { token },\n dispatcher: agent,\n signal: signal ?? null,\n });\n\n return buildProxyResult(response, signal);\n}\n\nexport type SitemapProxyOptions = {\n /** chunk source as received from the query string; core decides whether the source/page pair is valid */\n source?: string | undefined;\n /** chunk page as received from the query string */\n page?: string | undefined;\n /** the incoming request's Accept-Encoding, so stored gzip bytes pass through untouched */\n acceptEncoding?: string | undefined;\n /** the incoming request's If-None-Match, so core can answer 304 */\n ifNoneMatch?: string | undefined;\n};\n\nexport async function proxySitemap(\n agent: Dispatcher,\n url: string,\n token: string,\n projectRef: string,\n sitemapId: string,\n options: SitemapProxyOptions,\n signal?: AbortSignal | undefined,\n): Promise<ProxyResult> {\n assertSafeSegment(projectRef, 'project ref');\n assertSafeSegment(sitemapId, 'sitemap id');\n\n const search = new URLSearchParams();\n\n if (options.source !== undefined) {\n search.set('source', options.source);\n }\n\n if (options.page !== undefined) {\n search.set('page', options.page);\n }\n\n const query = search.size > 0 ? `?${search}` : '';\n const headers: Record<string, string> = { token };\n\n if (options.acceptEncoding) {\n headers['accept-encoding'] = options.acceptEncoding;\n }\n\n if (options.ifNoneMatch) {\n headers['if-none-match'] = options.ifNoneMatch;\n }\n\n const response = await undiciRequest(`${url}/api/v1/projects/${projectRef}/sitemaps/${sitemapId}${query}`, {\n headers,\n dispatcher: agent,\n signal: signal ?? null,\n });\n\n const result = buildProxyResult(response, signal);\n\n if (response.statusCode === 304) {\n safeDestroyBody(response.body);\n\n return { ...result, stream: emptyStream };\n }\n\n return result;\n}\n\nfunction emptyStream(): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n start(controller) {\n controller.close();\n },\n });\n}\n\nfunction buildProxyResult(response: Dispatcher.ResponseData, signal: AbortSignal | undefined): ProxyResult {\n const headers = new Headers();\n\n for (const [key, value] of Object.entries(response.headers)) {\n if (!FORWARDED_PROXY_HEADERS.has(key.toLowerCase())) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else if (value !== null && value !== undefined) {\n headers.set(key, value);\n }\n }\n\n return {\n status: response.statusCode,\n headers,\n stream: () => toWebStream(response.body, signal),\n };\n}\n\nfunction firstHeader(headers: Record<string, string | string[] | undefined>, key: string): string | undefined {\n const v = headers[key];\n\n return Array.isArray(v) ? v[0] : v;\n}\n\nfunction safeDestroyBody(body: Dispatcher.ResponseData['body']): void {\n try {\n body.on('error', () => {});\n body.destroy();\n } catch {\n // already destroyed\n }\n}\n\nfunction toWebStream(\n body: Dispatcher.ResponseData['body'],\n signal?: AbortSignal | undefined,\n): ReadableStream<Uint8Array> {\n let closed = false;\n\n const cleanup = () => {\n if (closed) {\n return;\n }\n\n closed = true;\n signal?.removeEventListener('abort', cleanup);\n safeDestroyBody(body);\n };\n\n return new ReadableStream<Uint8Array>({\n start(controller) {\n signal?.addEventListener('abort', cleanup);\n\n body.on('data', (chunk: Uint8Array) => {\n if (closed || signal?.aborted) {\n return;\n }\n\n try {\n controller.enqueue(chunk);\n } catch {\n cleanup();\n }\n });\n\n body.on('end', () => {\n if (closed || signal?.aborted) {\n return;\n }\n\n closed = true;\n signal?.removeEventListener('abort', cleanup);\n\n try {\n controller.close();\n } catch {\n // already closed\n }\n });\n\n body.on('error', (err: Error) => {\n cleanup();\n\n if (err.name === 'AbortError') {\n try {\n controller.close();\n } catch {\n // already closed\n }\n\n return;\n }\n\n try {\n controller.error(err);\n } catch {\n // already closed\n }\n });\n },\n cancel() {\n cleanup();\n },\n });\n}\n","const PING_QUERY = `query ContelloPing { contelloPing { response } }`;\n\ntype PingResult = { contelloPing: { response: string } };\n\nexport async function ping(execute: <T>(query: string) => Promise<T>): Promise<void> {\n const data = await execute<PingResult>(PING_QUERY);\n\n if (data.contelloPing.response !== 'pong') {\n throw new Error(`unexpected ping response: ${data.contelloPing.response}`);\n }\n}\n","import type { Client } from 'graphql-ws';\n\n// how long connect() waits for an individual client's first `connected` event\n// before resolving optimistically. without this a single unreachable endpoint\n// (graphql-ws retries forever) would make init() hang indefinitely; the client\n// keeps retrying in the background and get() routes around it via failover.\nconst DEFAULT_CONNECT_TIMEOUT = 10_000;\n\nexport class ConnectionPool {\n private _clients: Client[] = [];\n private _connected: boolean[] = [];\n private _currentIndex = 0;\n\n constructor(\n private _createClient: (id: string) => Client,\n private _poolSize: number,\n private _connectTimeout = DEFAULT_CONNECT_TIMEOUT,\n ) {}\n\n async connect() {\n const ready: Promise<void>[] = [];\n\n for (let i = 0; i < this._poolSize; i++) {\n const index = i;\n const client = this._createClient(String(i + 1));\n\n this._clients.push(client);\n this._connected.push(false);\n\n client.on('connected', () => {\n this._connected[index] = true;\n });\n client.on('closed', () => {\n this._connected[index] = false;\n });\n\n ready.push(\n new Promise<void>((resolve) => {\n let settled = false;\n\n const done = () => {\n if (settled) {\n return;\n }\n\n settled = true;\n offConnected();\n clearTimeout(timer);\n resolve();\n };\n\n const offConnected = client.on('connected', done);\n const timer = setTimeout(done, this._connectTimeout);\n\n timer.unref?.();\n }),\n );\n }\n\n await Promise.all(ready);\n }\n\n get() {\n if (this._clients.length === 0) {\n throw new Error('@contello/client: connection pool is empty — call client.init() first');\n }\n\n // prefer a currently-connected client, scanning round-robin from the cursor\n for (let i = 0; i < this._clients.length; i++) {\n const index = (this._currentIndex + i) % this._clients.length;\n\n if (this._connected[index] === true) {\n this._currentIndex = (index + 1) % this._clients.length;\n\n return this._clients[index]!;\n }\n }\n\n // none known-connected — fall back to plain round-robin; graphql-ws buffers\n // the operation until the chosen socket reconnects\n const client = this._clients[this._currentIndex]!;\n\n this._currentIndex = (this._currentIndex + 1) % this._clients.length;\n\n return client;\n }\n\n async disconnect() {\n const closed = this._clients.map(\n (client) =>\n new Promise<void>((resolve) => {\n const unsubscribe = client.on('closed', () => {\n unsubscribe();\n resolve();\n });\n\n client.dispose();\n }),\n );\n\n this._clients = [];\n this._connected = [];\n this._currentIndex = 0;\n\n await Promise.all(closed);\n }\n}\n","import { createOperationTelemetry } from '@contello/opentelemetry';\n\nexport const { wrap } = createOperationTelemetry('@contello/client');\n","export type LocalDateTime = {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n};\n\nexport type LocalDate = {\n year: number;\n month: number;\n day: number;\n};\n\nconst LOCAL_DATE_TIME_KEYS = ['year', 'month', 'day', 'hour', 'minute', 'second'] as const;\nconst LOCAL_DATE_KEYS = ['year', 'month', 'day'] as const;\n\nconst DATE_TIME_REGEX = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})/;\nconst DATE_REGEX = /^(\\d{4})-(\\d{2})-(\\d{2})/;\n\nfunction pad2(n: number): string {\n return n.toString().padStart(2, '0');\n}\n\nfunction pad4(n: number): string {\n return n.toString().padStart(4, '0');\n}\n\nfunction hasExactKeys(value: object, keys: readonly string[]): boolean {\n const ownKeys = Object.keys(value);\n\n if (ownKeys.length !== keys.length) {\n return false;\n }\n\n for (const key of keys) {\n if (!Object.prototype.hasOwnProperty.call(value, key)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction allNumbers(value: Record<string, unknown>, keys: readonly string[]): boolean {\n for (const key of keys) {\n if (typeof value[key] !== 'number') {\n return false;\n }\n }\n\n return true;\n}\n\nexport function isLocalDateTime(value: unknown): value is LocalDateTime {\n return (\n !!value &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n hasExactKeys(value, LOCAL_DATE_TIME_KEYS) &&\n allNumbers(value as Record<string, unknown>, LOCAL_DATE_TIME_KEYS)\n );\n}\n\nexport function isLocalDate(value: unknown): value is LocalDate {\n return (\n !!value &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n hasExactKeys(value, LOCAL_DATE_KEYS) &&\n allNumbers(value as Record<string, unknown>, LOCAL_DATE_KEYS)\n );\n}\n\nexport function decodeLocalDateTime(value: string): LocalDateTime {\n const match = DATE_TIME_REGEX.exec(value);\n\n if (!match) {\n throw new Error(`@contello/client: cannot decode LocalDateTime from \"${value}\"`);\n }\n\n return {\n year: Number(match[1]),\n month: Number(match[2]),\n day: Number(match[3]),\n hour: Number(match[4]),\n minute: Number(match[5]),\n second: Number(match[6]),\n };\n}\n\nexport function decodeLocalDate(value: string): LocalDate {\n const match = DATE_REGEX.exec(value);\n\n if (!match) {\n throw new Error(`@contello/client: cannot decode LocalDate from \"${value}\"`);\n }\n\n return {\n year: Number(match[1]),\n month: Number(match[2]),\n day: Number(match[3]),\n };\n}\n\nexport function encodeLocalDateTime(value: LocalDateTime): string {\n return (\n `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}` +\n `T${pad2(value.hour)}:${pad2(value.minute)}:${pad2(value.second)}Z`\n );\n}\n\nexport function encodeLocalDate(value: LocalDate): string {\n return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T00:00:00Z`;\n}\n","import { encodeLocalDate, encodeLocalDateTime, isLocalDate, isLocalDateTime } from './scalars';\n\n/**\n * encodes outgoing variables: LocalDateTime / LocalDate POJOs become wire strings.\n * detection is by shape — generated input types use the struct types, so consumers\n * pass structs in the right places, and stray objects with the same shape would be\n * an extremely unusual coincidence.\n */\nexport function transformVariables<T>(value: T): T {\n if (value === null || value === undefined) {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => transformVariables(item)) as unknown as T;\n }\n\n if (typeof value !== 'object') {\n return value;\n }\n\n if (isLocalDateTime(value)) {\n return encodeLocalDateTime(value) as unknown as T;\n }\n\n if (isLocalDate(value)) {\n return encodeLocalDate(value) as unknown as T;\n }\n\n const obj = value as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n\n for (const [key, val] of Object.entries(obj)) {\n out[key] = transformVariables(val);\n }\n\n return out as unknown as T;\n}\n","import { graphqlOperationAttributes } from '@contello/opentelemetry';\nimport { firstAsync } from '@entwico/dash/async';\nimport { wrap } from './telemetry';\nimport { transformVariables } from './transform-variables';\nimport type { OperationMap, Rpc } from './types';\n\ntype Subscribe = <TData>(query: string, variables?: Record<string, unknown> | undefined) => AsyncIterable<TData>;\n\nexport function buildRpc<T extends OperationMap>(operations: T, subscribe: Subscribe): Rpc<T> {\n const rpc = {} as Record<string, (...args: any[]) => any>;\n\n for (const [name, def] of Object.entries(operations)) {\n rpc[name] = def.kind === 'subscription' ? (variables?: Record<string, unknown>) =>\n subscribe<unknown>(def.document, transformVariables(variables)) : (variables?: Record<string, unknown>) => {\n const vars = transformVariables(variables);\n\n return wrap(\n `rpc:${name}`,\n () => firstAsync(subscribe<unknown>(def.document, vars)),\n graphqlOperationAttributes(def.document, vars),\n );\n };\n }\n\n return rpc as Rpc<T>;\n}\n","import { transformVariables } from './transform-variables';\nimport type { SourceDef, SourceMutationBinding, SourceMutations } from './types';\n\nexport type SourceMutationKind = keyof SourceMutations;\n\n/** What a write takes: the caller's input, and the id for a delete. */\nexport type SourceMutationValues = {\n input?: unknown;\n id?: string | undefined;\n};\n\nconst cache = new WeakMap<SourceDef, Partial<Record<SourceMutationKind, string>>>();\n\n/**\n * A create/update answers with the entity itself, so it selects the source's own fragment — the\n * write comes back in the same shape a read does and needs no follow-up fetch. A delete answers\n * with an id, either wrapped in a response object or, for routes, as a bare scalar.\n */\nfunction createSelection(source: SourceDef, binding: SourceMutationBinding): string {\n const declarations = binding.arguments.map((argument) => `$${argument.name}: ${argument.type}`).join(', ');\n const args = binding.arguments.map((argument) => `${argument.name}: $${argument.name}`).join(', ');\n const selection = { entity: ` { ...${source.fragment} }`, idObject: ' { id }', idScalar: '' }[binding.result];\n const operation = `mutation(${declarations}) { result: ${binding.field}(${args})${selection} }`;\n\n return binding.result === 'entity' ? `${source.document}\\n${operation}` : operation;\n}\n\nexport function getSourceMutation(source: SourceDef, kind: SourceMutationKind): SourceMutationBinding | undefined {\n return source.mutations?.[kind];\n}\n\n/** The mutation document for one write operation of a source. Cached per source + kind. */\nexport function createSourceMutation(source: SourceDef, kind: SourceMutationKind): string {\n const binding = getSourceMutation(source, kind);\n\n if (!binding) {\n throw new Error(\n `@contello/client: source \"${source.__model}\" has no ${kind} mutation — ` +\n `the schema exposes none for this model`,\n );\n }\n\n const cached = cache.get(source);\n\n if (cached?.[kind] !== undefined) {\n return cached[kind];\n }\n\n const doc = createSelection(source, binding);\n const entry = cached ?? {};\n\n entry[kind] = doc;\n cache.set(source, entry);\n\n return doc;\n}\n\n/**\n * Variables for a write: one per bound argument, the input nested under the envelope field when\n * the argument is a one-field wrapper, and everything encoded on the way out (LocalDate /\n * LocalDateTime structs become wire strings) — every caller goes through here, so no write path\n * can skip the encoding.\n */\nexport function createSourceMutationVariables(\n binding: SourceMutationBinding,\n values: SourceMutationValues,\n): Record<string, unknown> {\n const variables: Record<string, unknown> = {};\n\n for (const argument of binding.arguments) {\n variables[argument.name] =\n argument.from === 'id' ? values.id : (argument.envelope ? { [argument.envelope]: values.input } : values.input);\n }\n\n return transformVariables(variables);\n}\n\n/** Pulls the id out of whatever shape the mutation answered with. */\nexport function readSourceMutationId(binding: SourceMutationBinding, result: unknown): string {\n return binding.result === 'idScalar' ? (result as string) : (result as { id: string }).id;\n}\n","import type { SourceDef } from './types';\n\nconst cache = new WeakMap<SourceDef, string>();\n\nfunction createSelection(source: SourceDef): string {\n const spread = `{ ...${source.fragment} }`;\n\n switch (source.__cardinality) {\n case 'singleton': {\n return `subscription { source: ${source.subscription} ${spread} }`;\n }\n case 'entity': {\n return `subscription($ids: [ID!]) { source: ${source.subscription}(request: { filter: { ids: $ids } }) ${spread} }`;\n }\n case 'route': {\n return `subscription($ids: [ID!], $paths: [String!]) { source: ${source.subscription}(request: { ids: $ids, paths: $paths }) ${spread} }`;\n }\n case 'asset': {\n return `subscription($ids: [ID!]) { source: ${source.subscription}(filter: { ids: $ids }) ${spread} }`;\n }\n case 'i18nMessage': {\n return `subscription($collection: String!, $ids: [ID!]) { source: ${source.subscription}(collectionReferenceName: $collection, ids: $ids) ${spread} }`;\n }\n }\n}\n\nexport function createSourceSubscription(source: SourceDef): string {\n const cached = cache.get(source);\n\n if (cached !== undefined) {\n return cached;\n }\n\n const doc = `${source.document}\\n${createSelection(source)}`;\n\n cache.set(source, doc);\n\n return doc;\n}\n","import { graphqlOperationAttributes } from '@contello/opentelemetry';\nimport { concatAsync, firstAsync, mapAsync } from '@entwico/dash/async';\nimport {\n type SourceMutationKind,\n createSourceMutation,\n createSourceMutationVariables,\n readSourceMutationId,\n} from './source-mutation';\nimport { createSourceSubscription } from './source-subscription';\nimport { wrap } from './telemetry';\nimport { transformVariables } from './transform-variables';\nimport type { SourceAccessors, SourceDef, SourceMap } from './types';\n\ntype Subscribe = <TData>(query: string, variables?: Record<string, unknown> | undefined) => AsyncIterable<TData>;\n\nconst WRITE_KINDS: SourceMutationKind[] = ['create', 'update', 'delete'];\n\nexport function createSources<TSources extends SourceMap>(\n sources: TSources,\n subscribe: Subscribe,\n): SourceAccessors<TSources> {\n const out = {} as Record<string, Record<string, (...args: any[]) => Promise<unknown>>>;\n\n for (const [name, source] of Object.entries(sources)) {\n const def = source as SourceDef;\n const doc = createSourceSubscription(def);\n const accessor = createSourceAccessor(name, def, doc, subscribe);\n\n if (accessor) {\n out[name] = { ...accessor, ...createSourceWriters(name, def, subscribe) };\n }\n }\n\n return out as SourceAccessors<TSources>;\n}\n\n/**\n * Write accessors for the mutations the generator bound to this source. A create/update answers\n * with the entity in the source's fragment shape, a delete with the id it removed. Nothing is\n * cached here — `@contello/store` collections take the same payload into their cache.\n */\nfunction createSourceWriters(\n name: string,\n def: SourceDef,\n subscribe: Subscribe,\n): Record<string, (input: unknown) => Promise<unknown>> {\n const out: Record<string, (input: unknown) => Promise<unknown>> = {};\n\n for (const kind of WRITE_KINDS) {\n const binding = def.mutations?.[kind];\n\n if (!binding) {\n continue;\n }\n\n const doc = createSourceMutation(def, kind);\n\n out[kind] = (input: unknown) => {\n // a delete is addressed by id: bindings that take a bare `id:` argument read it off the input\n const variables = createSourceMutationVariables(\n binding,\n kind === 'delete' ? { input, id: (input as { id: string }).id } : { input },\n );\n\n return wrap(\n `source:${name}:${kind}`,\n async () => {\n const response = await firstAsync(subscribe<{ result: unknown }>(doc, variables));\n\n if (response?.result === undefined || response.result === null) {\n throw new Error(`@contello/client: ${kind} on source \"${name}\" returned no entity`);\n }\n\n return kind === 'delete' ? readSourceMutationId(binding, response.result) : response.result;\n },\n graphqlOperationAttributes(doc, variables),\n );\n };\n }\n\n return out;\n}\n\nfunction createSourceAccessor(\n name: string,\n def: SourceDef,\n doc: string,\n subscribe: Subscribe,\n): { fetch: (...args: any[]) => Promise<unknown> } | undefined {\n switch (def.__cardinality) {\n case 'singleton': {\n return {\n fetch: () =>\n wrap(\n `source:${name}`,\n () => firstAsync(mapAsync(subscribe<{ source: unknown }>(doc), (r) => r.source)),\n graphqlOperationAttributes(doc),\n ),\n };\n }\n case 'entity': {\n return {\n fetch: (vars?: { ids?: string[] }) => {\n const variables = transformVariables({ ids: vars?.ids });\n\n return wrap(\n `source:${name}`,\n () => concatAsync(mapAsync(subscribe<{ source: unknown[] }>(doc, variables), (r) => r.source)),\n graphqlOperationAttributes(doc, variables),\n );\n },\n };\n }\n case 'route': {\n return {\n fetch: (vars?: { ids?: string[] | undefined; paths?: string[] | undefined } | undefined) => {\n const variables = transformVariables({ ids: vars?.ids, paths: vars?.paths });\n\n return wrap(\n `source:${name}`,\n () => concatAsync(mapAsync(subscribe<{ source: unknown[] }>(doc, variables), (r) => r.source)),\n graphqlOperationAttributes(doc, variables),\n );\n },\n };\n }\n case 'asset': {\n return {\n fetch: (vars?: { ids?: string[] | undefined } | undefined) => {\n const variables = transformVariables({ ids: vars?.ids });\n\n return wrap(\n `source:${name}`,\n () => concatAsync(mapAsync(subscribe<{ source: unknown[] }>(doc, variables), (r) => r.source)),\n graphqlOperationAttributes(doc, variables),\n );\n },\n };\n }\n case 'i18nMessage': {\n return {\n fetch: (vars: { collection: string; ids?: string[] | undefined }) => {\n const variables = transformVariables({ collection: vars.collection, ids: vars.ids });\n\n return wrap(\n `source:${name}`,\n () => concatAsync(mapAsync(subscribe<{ source: unknown[] }>(doc, variables), (r) => r.source)),\n graphqlOperationAttributes(doc, variables),\n );\n },\n };\n }\n }\n}\n","import { decodeLocalDate, decodeLocalDateTime } from './scalars';\n\nconst FLAT_PREFIX = '_flat_';\nconst LDT_PREFIX = '_ldt_';\nconst LD_PREFIX = '_ld_';\n\nconst MODEL_SUFFIXES = ['Entity', 'Component'];\n\nfunction decodeValue(value: unknown, decoder: (s: string) => unknown): unknown {\n if (value === null || value === undefined) {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => decodeValue(item, decoder));\n }\n\n if (typeof value === 'string') {\n return decoder(value);\n }\n\n return value;\n}\n\ntype FlatRef = { _flatId?: string | undefined };\ntype FlatComponent = FlatRef & { __typename?: string | undefined };\n\nfunction deriveModel(typename: string): string | undefined {\n for (const suffix of MODEL_SUFFIXES) {\n if (typename.endsWith(suffix)) {\n const stripped = typename.slice(0, -suffix.length);\n\n return stripped.charAt(0).toLowerCase() + stripped.slice(1);\n }\n }\n\n return undefined;\n}\n\n/**\n * transforms a GraphQL response in a single depth-first pass:\n * - resolves `_flat_{field}` companions into nested component arrays (refs are\n * matched against the companion map by `_flatId`, at any nesting depth — the\n * companion lists the whole subtree, so one map serves every ref below it)\n * - injects `__model` on objects with entity/component `__typename`\n * - decodes managed scalar aliases (`_ldt_` / `_ld_`) into structured values\n *\n * a `seen` set guards against shared or cyclic references so every object is\n * visited exactly once.\n */\nexport function transformResponse<T>(data: T): T {\n transformNode(data, undefined, new WeakSet());\n\n return data;\n}\n\nfunction transformNode(\n value: unknown,\n flatMap: Map<string, FlatComponent> | undefined,\n seen: WeakSet<object>,\n): void {\n if (!value || typeof value !== 'object') {\n return;\n }\n\n if (seen.has(value)) {\n return;\n }\n\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) {\n transformNode(item, flatMap, seen);\n }\n\n return;\n }\n\n const obj = value as Record<string, unknown>;\n\n // inject __model from __typename\n const typename = obj['__typename'];\n\n if (typeof typename === 'string') {\n const model = deriveModel(typename);\n\n if (model) {\n obj['__model'] = model;\n }\n }\n\n // collect `_flat_*` companions into this scope's resolution map, extending any\n // map inherited from an ancestor so refs nested below resolve against the same\n // companion set\n let ownMap: Map<string, FlatComponent> | undefined;\n\n for (const key of Object.keys(obj)) {\n if (!key.startsWith(FLAT_PREFIX)) {\n continue;\n }\n\n const flatArray = obj[key] as FlatComponent[] | undefined;\n\n delete obj[key];\n\n if (!flatArray) {\n continue;\n }\n\n if (!ownMap) {\n ownMap = flatMap ? new Map(flatMap) : new Map();\n }\n\n for (const component of flatArray) {\n if (component._flatId) {\n ownMap.set(component._flatId, component);\n }\n }\n }\n\n // decode scalar aliases, resolve ref arrays, and recurse — one pass over keys.\n // refs resolve against this object's own companion map if it had `_flat_*`\n // siblings, otherwise against the inherited ancestor map\n const resolveMap = ownMap ?? flatMap;\n\n for (const key of Object.keys(obj)) {\n if (key.startsWith(LDT_PREFIX)) {\n obj[key.slice(LDT_PREFIX.length)] = decodeValue(obj[key], decodeLocalDateTime);\n delete obj[key];\n\n continue;\n }\n\n if (key.startsWith(LD_PREFIX)) {\n obj[key.slice(LD_PREFIX.length)] = decodeValue(obj[key], decodeLocalDate);\n delete obj[key];\n\n continue;\n }\n\n const inner = obj[key];\n\n if (\n resolveMap &&\n Array.isArray(inner) &&\n inner.length > 0 &&\n (inner[0] as FlatRef | undefined)?._flatId !== undefined\n ) {\n obj[key] = resolveRefs(inner as FlatRef[], resolveMap);\n }\n\n transformNode(obj[key], resolveMap, seen);\n }\n}\n\nfunction resolveRefs(refs: readonly FlatRef[], flatMap: Map<string, FlatComponent>): FlatComponent[] {\n const resolved: FlatComponent[] = [];\n\n for (const ref of refs) {\n if (!ref._flatId) {\n continue;\n }\n\n const component = flatMap.get(ref._flatId);\n\n if (component) {\n resolved.push(component);\n }\n }\n\n return resolved;\n}\n","import type { ReadableStream as NodeReadableStream } from 'node:stream/web';\n\nexport type UploadMetadata = {\n name: string;\n mimeType?: string | undefined;\n size?: number | undefined;\n annotations?: { key: string; value: string }[] | undefined;\n collectionRefs?: string[] | undefined;\n /**\n * `deleteIfNotUsed` lets the server delete the asset once nothing references it.\n * @default 'retain'\n */\n retentionPolicy?: 'retain' | 'deleteIfNotUsed' | undefined;\n};\n\nexport type UploadData = Uint8Array | NodeReadableStream<Uint8Array> | ReadableStream<Uint8Array>;\n\ntype InitFrame = { type: 'init'; metadata: UploadMetadata & { projectRef: string }; token: string };\ntype ServerMessage = { type: 'ack' } | { type: 'progress'; bytesReceived: number } | { type: 'done'; id: string };\n\nexport type UploadOptions = {\n chunkSize?: number | undefined;\n abort?: AbortSignal | undefined;\n};\n\nconst DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024;\n\nfunction isUint8Array(data: UploadData): data is Uint8Array {\n return data instanceof Uint8Array;\n}\n\nexport function upload(\n url: string,\n project: string,\n token: string,\n data: UploadData,\n meta: UploadMetadata,\n options?: UploadOptions | undefined,\n): Promise<string> {\n const chunkSize = options?.chunkSize ?? DEFAULT_CHUNK_SIZE;\n const wsUrl = `${url.replace(/^http/i, 'ws')}/api/v1/assets/ws`;\n\n const size = isUint8Array(data) ? data.length : meta.size;\n\n return new Promise<string>((resolve, reject) => {\n const ws = new WebSocket(wsUrl, 'contello-file-upload-v1');\n\n let done = false;\n\n const cleanup = () => {\n options?.abort?.removeEventListener('abort', abortHandler);\n };\n\n const abortHandler = () => {\n if (done) {\n return;\n }\n\n ws.close();\n reject(new Error('upload aborted'));\n };\n\n options?.abort?.addEventListener('abort', abortHandler);\n\n function sendBuffer(buf: Uint8Array) {\n let offset = 0;\n\n while (offset < buf.length) {\n const chunk = buf.subarray(offset, offset + chunkSize);\n\n ws.send(chunk);\n offset += chunk.length;\n }\n\n ws.send(JSON.stringify({ type: 'done' }));\n }\n\n const MAX_BUFFER_SIZE = 8 * 1024 * 1024;\n\n function waitForBufferedDrain(): Promise<void> {\n return new Promise((resolveDrain, rejectDrain) => {\n const check = () => {\n if (options?.abort?.aborted) {\n rejectDrain(new Error('upload aborted'));\n\n return;\n }\n\n if (ws.bufferedAmount <= MAX_BUFFER_SIZE) {\n resolveDrain();\n\n return;\n }\n\n setTimeout(check, 50);\n };\n\n check();\n });\n }\n\n async function sendStream(stream: UploadData) {\n const reader = (stream as ReadableStream<Uint8Array>).getReader();\n\n try {\n while (true) {\n const { done: streamDone, value } = await reader.read();\n\n if (streamDone) break;\n\n await waitForBufferedDrain();\n ws.send(value);\n }\n\n ws.send(JSON.stringify({ type: 'done' }));\n } catch (error) {\n reject(error);\n ws.close();\n }\n }\n\n ws.addEventListener('open', () => {\n const initFrame: InitFrame = {\n type: 'init',\n metadata: { ...meta, ...(size !== undefined && { size }), projectRef: project },\n token,\n };\n\n ws.send(JSON.stringify(initFrame));\n });\n\n ws.addEventListener('message', (event) => {\n const message: ServerMessage = JSON.parse(String(event.data));\n\n if (message.type === 'ack') {\n if (isUint8Array(data)) {\n sendBuffer(data);\n } else {\n sendStream(data);\n }\n\n return;\n }\n\n if (message.type !== 'done') {\n return;\n }\n\n done = true;\n cleanup();\n ws.close();\n resolve(message.id);\n });\n\n ws.addEventListener('error', () => {\n cleanup();\n reject(new Error('upload websocket error'));\n });\n\n ws.addEventListener('close', () => {\n cleanup();\n\n if (!done) {\n reject(new Error('connection closed before upload completed'));\n }\n });\n });\n}\n","import { graphqlOperationAttributes, injectTraceContext } from '@contello/opentelemetry';\nimport { exponentialBackoff, firstAsync } from '@entwico/dash/async';\nimport { createClient } from 'graphql-ws';\nimport type { Agent } from 'undici';\n\nimport {\n type DownloadResult,\n type HttpAgentOptions,\n type ProxyResult,\n type SitemapProxyOptions,\n createHttpAgent,\n downloadFile,\n proxyHls,\n proxySitemap,\n} from './http';\nimport { ping } from './ping';\nimport { ConnectionPool } from './pool';\nimport { buildRpc } from './rpc';\nimport { createSources } from './sources';\nimport { wrap } from './telemetry';\nimport { transformResponse } from './transform-response';\nimport type { Rpc, Schema, SourceAccessors } from './types';\nimport { type UploadData, type UploadMetadata, type UploadOptions, upload as uploadAsset } from './upload';\n\nexport type ConnectionContext = {\n connectionId: string;\n websocketUrl: string;\n};\n\nexport type ConnectionEvents = {\n onConnected?: ((context: ConnectionContext) => void) | undefined;\n onConnecting?: ((context: ConnectionContext) => void) | undefined;\n onClosed?: ((context: ConnectionContext) => void) | undefined;\n onError?: ((context: ConnectionContext, error: unknown) => void) | undefined;\n};\n\nexport type ContelloClientOptions<TSchema extends Schema | undefined = undefined> = {\n url: string;\n project: string;\n token: string;\n schema?: TSchema | undefined;\n connections?: number | undefined;\n http?: HttpAgentOptions | undefined;\n onConnected?: (() => void) | undefined;\n onReconnecting?: (() => void) | undefined;\n onError?: ((error: unknown) => void) | undefined;\n connectionEvents?: ConnectionEvents | undefined;\n};\n\ntype PoolState = 'disconnected' | 'connected' | 'reconnecting';\n\nexport class ContelloClient<TSchema extends Schema | undefined = undefined> {\n private _pool: ConnectionPool;\n private _rpc: TSchema extends Schema<infer TOps, any, any> ? Rpc<TOps> : undefined;\n private _sources: TSchema extends Schema<any, infer TSources, any> ? SourceAccessors<TSources> : undefined;\n private _url: string;\n private _project: string;\n private _token: string;\n private _agent: Agent;\n\n constructor(options: ContelloClientOptions<TSchema>) {\n const { url, project, token, schema, connections = 1, connectionEvents } = options;\n\n this._url = url;\n this._project = project;\n this._token = token;\n this._agent = createHttpAgent(options.http);\n\n const websocketUrl = `${url}/graphql/projects/${project}`.replace(/^http/i, 'ws');\n\n let state: PoolState = 'disconnected';\n let connectedCount = 0;\n\n const onConnectionUp = () => {\n connectedCount++;\n\n if (connectedCount !== connections || state === 'connected') {\n return;\n }\n\n state = 'connected';\n options.onConnected?.();\n };\n\n const onConnectionDown = () => {\n if (connectedCount > 0) {\n connectedCount--;\n }\n\n if (state !== 'connected') {\n return;\n }\n\n state = 'reconnecting';\n options.onReconnecting?.();\n };\n\n this._pool = new ConnectionPool((id: string) => {\n const context: ConnectionContext = Object.freeze({ connectionId: id, websocketUrl });\n\n return createClient({\n url: websocketUrl,\n connectionParams: { token },\n lazy: false,\n keepAlive: 30_000,\n retryAttempts: Infinity,\n retryWait: exponentialBackoff,\n shouldRetry: () => true,\n jsonMessageReplacer: (key, value) => {\n if (!key) {\n return injectTraceContext(value);\n }\n\n return value;\n },\n ...(options.onError && { onNonLazyError: (e) => options.onError!(e) }),\n on: {\n connected: () => {\n onConnectionUp();\n connectionEvents?.onConnected?.(context);\n },\n connecting: () => {\n connectionEvents?.onConnecting?.(context);\n },\n closed: () => {\n onConnectionDown();\n connectionEvents?.onClosed?.(context);\n },\n ...((options.onError || connectionEvents?.onError) && {\n error: (e) => {\n options.onError?.(e);\n connectionEvents?.onError?.(context, e);\n },\n }),\n },\n });\n }, connections);\n\n this._rpc = (\n schema?.operations ? buildRpc(schema.operations, (q, v) => this.subscribe(q, v)) : undefined\n ) as typeof this._rpc;\n\n this._sources = (\n schema?.sources ? createSources(schema.sources, (q, v) => this.subscribe(q, v)) : undefined\n ) as typeof this._sources;\n }\n\n get rpc(): TSchema extends Schema<infer TOps, any, any> ? Rpc<TOps> : never {\n if (!this._rpc) {\n throw new Error('@contello/client: .rpc accessed without a schema containing operations');\n }\n\n return this._rpc as any;\n }\n\n get sources(): TSchema extends Schema<any, infer TSources, any> ? SourceAccessors<TSources> : never {\n if (!this._sources) {\n throw new Error('@contello/client: .sources accessed without a schema containing sources');\n }\n\n return this._sources as any;\n }\n\n async init(): Promise<void> {\n await this._pool.connect();\n }\n\n async destroy(): Promise<void> {\n await this._pool.disconnect();\n await this._agent.close();\n }\n\n async ping(): Promise<void> {\n // excluded from telemetry to avoid noise\n return ping((query) => firstAsync(this.subscribe(query)));\n }\n\n /**\n * Open a subscription on the websocket. Each `[Symbol.asyncIterator]()` call (the implicit one\n * from `for await`, or via `rxjs.from(this)`) starts a fresh server subscription and tears it\n * down when the iterator is returned (`break`, error, or explicit stop).\n */\n subscribe<TData>(query: string, variables?: Record<string, unknown> | undefined): AsyncIterable<TData> {\n const pool = this._pool;\n\n return {\n [Symbol.asyncIterator](): AsyncIterator<TData> {\n const wsClient = pool.get();\n const queue: TData[] = [];\n let pending: { resolve: (r: IteratorResult<TData>) => void; reject: (e: unknown) => void } | undefined;\n let done = false;\n let error: unknown;\n\n const unsubscribe = wsClient.subscribe<TData>(\n { query, variables },\n {\n next(msg) {\n const value = transformResponse(msg.data);\n\n if (value === undefined || value === null) {\n return;\n }\n\n if (pending) {\n const p = pending;\n\n pending = undefined;\n p.resolve({ value: value as TData, done: false });\n } else {\n queue.push(value as TData);\n }\n },\n error(err) {\n done = true;\n error = err;\n\n if (!pending) {\n return;\n }\n\n const p = pending;\n\n pending = undefined;\n p.reject(err);\n },\n complete() {\n done = true;\n\n if (!pending) {\n return;\n }\n\n const p = pending;\n\n pending = undefined;\n p.resolve({ value: undefined as unknown as TData, done: true });\n },\n },\n );\n\n return {\n next(): Promise<IteratorResult<TData>> {\n if (queue.length > 0) {\n return Promise.resolve({ value: queue.shift()!, done: false });\n }\n\n if (error !== undefined) {\n return Promise.reject(error);\n }\n\n if (done) {\n return Promise.resolve({ value: undefined as unknown as TData, done: true });\n }\n\n return new Promise<IteratorResult<TData>>((resolve, reject) => {\n pending = { resolve, reject };\n });\n },\n return(): Promise<IteratorResult<TData>> {\n unsubscribe();\n\n return Promise.resolve({ value: undefined as unknown as TData, done: true });\n },\n throw(err): Promise<IteratorResult<TData>> {\n unsubscribe();\n\n return Promise.reject(err);\n },\n };\n },\n };\n }\n\n download(fileId: string): Promise<DownloadResult> {\n return wrap('@contello/client:download', () => downloadFile(this._agent, this._url, this._token, fileId));\n }\n\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult> {\n return wrap('@contello/client:proxyHls', () => proxyHls(this._agent, this._url, this._token, path, signal));\n }\n\n proxySitemap(\n sitemapId: string,\n options: SitemapProxyOptions,\n signal?: AbortSignal | undefined,\n ): Promise<ProxyResult> {\n return wrap(\n '@contello/client:proxySitemap',\n () => proxySitemap(this._agent, this._url, this._token, this._project, sitemapId, options, signal),\n );\n }\n\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string> {\n return wrap(\n '@contello/client:upload',\n () => uploadAsset(this._url, this._project, this._token, data, meta, options),\n );\n }\n\n execute<TData>(query: string, variables?: Record<string, unknown> | undefined): Promise<TData> {\n return wrap(\n '@contello/client:execute',\n () => firstAsync(this.subscribe<TData>(query, variables)),\n graphqlOperationAttributes(query, variables),\n );\n }\n}\n\nexport function createContelloClient<TSchema extends Schema | undefined = undefined>(\n options: ContelloClientOptions<TSchema>,\n): ContelloClient<TSchema> {\n return new ContelloClient(options);\n}\n","import type { SourceCardinality, SourceMutations } from './types';\n\n/**\n * Write bindings for the built-in sources. Unlike entity mutations these are not derived — their\n * field and argument names are fixed parts of every Contello schema — but the generator still\n * checks each one against the introspected schema before emitting it, so a server without them\n * (or with a different shape) simply yields a read-only source.\n *\n * Routes are the odd ones: `updateContelloRoute` is keyed by the `path` inside its input rather\n * than by an id, and it replaces the route rather than patching it. `deleteContelloRoute` takes a\n * bare `id` and answers with a bare id string.\n *\n * Assets have no `create` — an asset comes into being through `client.upload()`, not a mutation.\n */\nexport const BUILT_IN_MUTATIONS: Partial<Record<SourceCardinality, SourceMutations>> = {\n route: {\n create: {\n field: 'createContelloRoute',\n arguments: [{ name: 'route', type: 'ContelloRouteInput!', from: 'input' }],\n result: 'entity',\n },\n update: {\n field: 'updateContelloRoute',\n arguments: [{ name: 'route', type: 'ContelloRouteInput!', from: 'input' }],\n result: 'entity',\n },\n delete: {\n field: 'deleteContelloRoute',\n arguments: [{ name: 'id', type: 'String', from: 'id' }],\n result: 'idScalar',\n },\n },\n asset: {\n update: {\n field: 'updateContelloAsset',\n arguments: [{ name: 'request', type: 'ContelloAssetUpdateInput!', from: 'input' }],\n result: 'entity',\n },\n delete: {\n field: 'deleteContelloAsset',\n arguments: [{ name: 'id', type: 'String!', from: 'id' }],\n result: 'idObject',\n },\n },\n};\n"],"mappings":";;;;;AAEA,MAAM,eAAe;AAErB,MAAM,0CAA0B,IAAI,IAAI;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAS,kBAAkB,SAAiB,M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;GAAQ,CAAC;GACjF,QAAQ;EACV;EACA,QAAQ;GACN,OAAO;GACP,WAAW,CAAC;IAAE,MAAM;IAAM,MAAM;IAAW,MAAM;GAAK,CAAC;GACvD,QAAQ;EACV;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["undiciRequest","cache","createSelection","uploadAsset"],"sources":["../src/http.ts","../src/introspection.ts","../src/ping.ts","../src/pool.ts","../src/telemetry.ts","../src/scalars.ts","../src/transform-variables.ts","../src/rpc.ts","../src/source-mutation.ts","../src/source-subscription.ts","../src/sources.ts","../src/transform-response.ts","../src/upload.ts","../src/client.ts","../src/built-in-mutations.ts"],"sourcesContent":["import { Agent, type Dispatcher, request as undiciRequest } from 'undici';\n\nconst SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;\n\nconst FORWARDED_PROXY_HEADERS = new Set([\n 'content-type',\n 'content-length',\n 'content-range',\n 'content-encoding',\n 'accept-ranges',\n 'cache-control',\n 'etag',\n 'last-modified',\n 'expires',\n 'age',\n 'vary',\n]);\n\nfunction assertSafeSegment(segment: string, kind: string): void {\n if (segment === '.' || segment === '..' || !SAFE_SEGMENT.test(segment)) {\n throw new Error(`invalid ${kind}`);\n }\n}\n\nfunction assertSafeAssetPath(path: string, kind: string): void {\n if (path === '') {\n throw new Error(`invalid ${kind}`);\n }\n\n for (const segment of path.split('/')) {\n assertSafeSegment(segment, kind);\n }\n}\n\nexport type HttpAgentOptions = {\n pipelining?: number | undefined;\n allowH2?: boolean | undefined;\n maxConcurrentStreams?: number | undefined;\n keepAliveTimeout?: number | undefined;\n};\n\nexport function createHttpAgent(options?: HttpAgentOptions | undefined): Agent {\n return new Agent({\n pipelining: options?.pipelining ?? 10,\n allowH2: options?.allowH2 ?? true,\n maxConcurrentStreams: options?.maxConcurrentStreams ?? 128,\n keepAliveTimeout: options?.keepAliveTimeout ?? 60_000,\n autoSelectFamily: true,\n autoSelectFamilyAttemptTimeout: 25,\n });\n}\n\nexport type DownloadResult = {\n mimeType: string;\n size: number;\n bytes(): Promise<Uint8Array>;\n stream(): ReadableStream<Uint8Array>;\n};\n\nexport async function downloadFile(\n agent: Dispatcher,\n url: string,\n token: string,\n fileId: string,\n): Promise<DownloadResult> {\n assertSafeSegment(fileId, 'file id');\n\n const response = await undiciRequest(`${url}/api/v1/assets/files/${fileId}`, {\n headers: { token },\n dispatcher: agent,\n });\n\n if (response.statusCode < 200 || response.statusCode >= 300) {\n safeDestroyBody(response.body);\n\n throw new Error(`download failed: ${response.statusCode}`);\n }\n\n const mimeType = firstHeader(response.headers, 'content-type') ?? 'application/octet-stream';\n const size = Number(firstHeader(response.headers, 'content-length') ?? 0);\n\n return {\n mimeType,\n size,\n bytes: async () => new Uint8Array(await response.body.arrayBuffer()),\n stream: () => toWebStream(response.body),\n };\n}\n\nexport type ProxyResult = {\n status: number;\n headers: Headers;\n stream(): ReadableStream<Uint8Array>;\n};\n\nexport async function proxyHls(\n agent: Dispatcher,\n url: string,\n token: string,\n path: string,\n signal?: AbortSignal | undefined,\n): Promise<ProxyResult> {\n assertSafeAssetPath(path, 'hls path');\n\n const response = await undiciRequest(`${url}/api/v1/assets/video/hls/${path}`, {\n headers: { token },\n dispatcher: agent,\n signal: signal ?? null,\n });\n\n return buildProxyResult(response, signal);\n}\n\nexport type SitemapProxyOptions = {\n /** chunk source as received from the query string; core decides whether the source/page pair is valid */\n source?: string | undefined;\n /** chunk page as received from the query string */\n page?: string | undefined;\n /** the incoming request's Accept-Encoding, so stored gzip bytes pass through untouched */\n acceptEncoding?: string | undefined;\n /** the incoming request's If-None-Match, so core can answer 304 */\n ifNoneMatch?: string | undefined;\n};\n\nexport async function proxySitemap(\n agent: Dispatcher,\n url: string,\n token: string,\n projectRef: string,\n sitemapId: string,\n options: SitemapProxyOptions,\n signal?: AbortSignal | undefined,\n): Promise<ProxyResult> {\n assertSafeSegment(projectRef, 'project ref');\n assertSafeSegment(sitemapId, 'sitemap id');\n\n const search = new URLSearchParams();\n\n if (options.source !== undefined) {\n search.set('source', options.source);\n }\n\n if (options.page !== undefined) {\n search.set('page', options.page);\n }\n\n const query = search.size > 0 ? `?${search}` : '';\n const headers: Record<string, string> = { token };\n\n if (options.acceptEncoding) {\n headers['accept-encoding'] = options.acceptEncoding;\n }\n\n if (options.ifNoneMatch) {\n headers['if-none-match'] = options.ifNoneMatch;\n }\n\n const response = await undiciRequest(`${url}/api/v1/projects/${projectRef}/sitemaps/${sitemapId}${query}`, {\n headers,\n dispatcher: agent,\n signal: signal ?? null,\n });\n\n const result = buildProxyResult(response, signal);\n\n if (response.statusCode === 304) {\n safeDestroyBody(response.body);\n\n return { ...result, stream: emptyStream };\n }\n\n return result;\n}\n\nfunction emptyStream(): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n start(controller) {\n controller.close();\n },\n });\n}\n\nfunction buildProxyResult(response: Dispatcher.ResponseData, signal: AbortSignal | undefined): ProxyResult {\n const headers = new Headers();\n\n for (const [key, value] of Object.entries(response.headers)) {\n if (!FORWARDED_PROXY_HEADERS.has(key.toLowerCase())) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else if (value !== null && value !== undefined) {\n headers.set(key, value);\n }\n }\n\n return {\n status: response.statusCode,\n headers,\n stream: () => toWebStream(response.body, signal),\n };\n}\n\nfunction firstHeader(headers: Record<string, string | string[] | undefined>, key: string): string | undefined {\n const v = headers[key];\n\n return Array.isArray(v) ? v[0] : v;\n}\n\nfunction safeDestroyBody(body: Dispatcher.ResponseData['body']): void {\n try {\n body.on('error', () => {});\n body.destroy();\n } catch {\n // already destroyed\n }\n}\n\nfunction toWebStream(\n body: Dispatcher.ResponseData['body'],\n signal?: AbortSignal | undefined,\n): ReadableStream<Uint8Array> {\n let closed = false;\n\n const cleanup = () => {\n if (closed) {\n return;\n }\n\n closed = true;\n signal?.removeEventListener('abort', cleanup);\n safeDestroyBody(body);\n };\n\n return new ReadableStream<Uint8Array>({\n start(controller) {\n signal?.addEventListener('abort', cleanup);\n\n body.on('data', (chunk: Uint8Array) => {\n if (closed || signal?.aborted) {\n return;\n }\n\n try {\n controller.enqueue(chunk);\n } catch {\n cleanup();\n }\n });\n\n body.on('end', () => {\n if (closed || signal?.aborted) {\n return;\n }\n\n closed = true;\n signal?.removeEventListener('abort', cleanup);\n\n try {\n controller.close();\n } catch {\n // already closed\n }\n });\n\n body.on('error', (err: Error) => {\n cleanup();\n\n if (err.name === 'AbortError') {\n try {\n controller.close();\n } catch {\n // already closed\n }\n\n return;\n }\n\n try {\n controller.error(err);\n } catch {\n // already closed\n }\n });\n },\n cancel() {\n cleanup();\n },\n });\n}\n","import { createHash } from 'node:crypto';\n\nimport type { MaybePromise } from '@entwico/dash';\n\nconst INTROSPECT_QUERY = `query ContelloIntrospectToken($token: String!) {\n contelloIntrospectToken(token: $token) {\n active audience expiresAt user { id username firstName lastName email } permissions { resourceType scope actions }\n }\n}`;\n\nexport type ResourceAction = 'READ' | 'CREATE' | 'UPDATE' | 'DELETE';\n\n// the actions the user may take on one resource of the project: the type with what identifies the\n// resource (an entity model id, an i18n message collection id, an extension id, a route path\n// pattern), no scope for the types without one\nexport type ResourcePermissions = {\n resourceType: 'ENTITY' | 'ASSET' | 'ROUTE' | 'I18N_MESSAGE_COLLECTION' | 'MODELLING' | 'EXTENSION' | (string & {});\n scope: string | null;\n actions: ResourceAction[];\n};\n\nexport type IntrospectedUser = {\n id: string;\n username: string;\n firstName: string;\n lastName: string;\n email: string;\n};\n\n// what a temporary token stands for in the project of the client; an inactive answer carries\n// nothing else\nexport type TokenIntrospection =\n | { active: false }\n | {\n active: true;\n // who the token was minted for: the origin of the extension\n audience: string;\n expiresAt: Date;\n user: IntrospectedUser;\n permissions: ResourcePermissions[];\n };\n\ntype IntrospectionResult = {\n contelloIntrospectToken: {\n active: boolean;\n audience: string | null;\n expiresAt: string | null;\n user: IntrospectedUser | null;\n permissions: ResourcePermissions[] | null;\n };\n};\n\nexport async function introspectToken(\n execute: <T>(query: string, variables: Record<string, unknown>) => Promise<T>,\n token: string,\n): Promise<TokenIntrospection> {\n const { contelloIntrospectToken: result } = await execute<IntrospectionResult>(INTROSPECT_QUERY, { token });\n\n if (!result.active || !result.audience || !result.expiresAt || !result.user) {\n return { active: false };\n }\n\n return {\n active: true,\n audience: result.audience,\n expiresAt: new Date(result.expiresAt),\n user: result.user,\n permissions: result.permissions ?? [],\n };\n}\n\nexport type TokenIntrospectorOptions = {\n // the audiences this backend serves, the origins of its extension pages: a token minted for any\n // other audience is inactive here\n audiences: string[];\n // how long an answer is reused before core is asked again, so a disabled user or an expired\n // token takes effect within this time; default one minute\n maxAgeMs?: number | undefined;\n // how many answers are kept at most; default 10000\n maxEntries?: number | undefined;\n};\n\nexport type TokenIntrospector = {\n // a cached answer comes back synchronously\n introspect: (token: string) => MaybePromise<TokenIntrospection>;\n};\n\nconst DEFAULT_MAX_AGE_MS = 60_000;\nconst DEFAULT_MAX_ENTRIES = 10_000;\n\ntype CacheEntry = { result: TokenIntrospection; until: number };\n\n// the introspection a backend runs on every request of an extension page: the answer of core is\n// kept until its expiry or maxAgeMs, whichever comes first, keyed by a hash of the token\nexport function createTokenIntrospector(\n introspect: (token: string) => Promise<TokenIntrospection>,\n options: TokenIntrospectorOptions,\n): TokenIntrospector {\n const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;\n const maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES;\n const audiences = new Set(options.audiences);\n const cache = new Map<string, CacheEntry>();\n const pending = new Map<string, Promise<TokenIntrospection>>();\n\n // entries expire within maxAgeMs of their insertion, so insertion order is close to expiry order\n // and the oldest entries are the ones to drop when the expired ones are not enough\n const evict = (now: number) => {\n for (const [key, entry] of cache) {\n if (entry.until <= now) {\n cache.delete(key);\n }\n }\n\n for (const key of cache.keys()) {\n if (cache.size < maxEntries) {\n break;\n }\n\n cache.delete(key);\n }\n };\n\n const lookup = async (token: string, key: string): Promise<TokenIntrospection> => {\n try {\n let result = await introspect(token);\n\n if (result.active && !audiences.has(result.audience)) {\n result = { active: false };\n }\n\n const now = Date.now();\n const until = result.active ? Math.min(result.expiresAt.getTime(), now + maxAgeMs) : now + maxAgeMs;\n\n if (cache.size >= maxEntries) {\n evict(now);\n }\n\n cache.set(key, { result, until });\n\n return result;\n } finally {\n pending.delete(key);\n }\n };\n\n return {\n introspect: (token) => {\n const key = createHash('sha256').update(token).digest('base64url');\n const cached = cache.get(key);\n\n if (cached && cached.until > Date.now()) {\n return cached.result;\n }\n\n let running = pending.get(key);\n\n if (!running) {\n running = lookup(token, key);\n pending.set(key, running);\n }\n\n return running;\n },\n };\n}\n","const PING_QUERY = `query ContelloPing { contelloPing { response } }`;\n\ntype PingResult = { contelloPing: { response: string } };\n\nexport async function ping(execute: <T>(query: string) => Promise<T>): Promise<void> {\n const data = await execute<PingResult>(PING_QUERY);\n\n if (data.contelloPing.response !== 'pong') {\n throw new Error(`unexpected ping response: ${data.contelloPing.response}`);\n }\n}\n","import type { Client } from 'graphql-ws';\n\n// how long connect() waits for an individual client's first `connected` event\n// before resolving optimistically. without this a single unreachable endpoint\n// (graphql-ws retries forever) would make init() hang indefinitely; the client\n// keeps retrying in the background and get() routes around it via failover.\nconst DEFAULT_CONNECT_TIMEOUT = 10_000;\n\nexport class ConnectionPool {\n private _clients: Client[] = [];\n private _connected: boolean[] = [];\n private _currentIndex = 0;\n\n constructor(\n private _createClient: (id: string) => Client,\n private _poolSize: number,\n private _connectTimeout = DEFAULT_CONNECT_TIMEOUT,\n ) {}\n\n async connect() {\n const ready: Promise<void>[] = [];\n\n for (let i = 0; i < this._poolSize; i++) {\n const index = i;\n const client = this._createClient(String(i + 1));\n\n this._clients.push(client);\n this._connected.push(false);\n\n client.on('connected', () => {\n this._connected[index] = true;\n });\n client.on('closed', () => {\n this._connected[index] = false;\n });\n\n ready.push(\n new Promise<void>((resolve) => {\n let settled = false;\n\n const done = () => {\n if (settled) {\n return;\n }\n\n settled = true;\n offConnected();\n clearTimeout(timer);\n resolve();\n };\n\n const offConnected = client.on('connected', done);\n const timer = setTimeout(done, this._connectTimeout);\n\n timer.unref?.();\n }),\n );\n }\n\n await Promise.all(ready);\n }\n\n get() {\n if (this._clients.length === 0) {\n throw new Error('@contello/client: connection pool is empty — call client.init() first');\n }\n\n // prefer a currently-connected client, scanning round-robin from the cursor\n for (let i = 0; i < this._clients.length; i++) {\n const index = (this._currentIndex + i) % this._clients.length;\n\n if (this._connected[index] === true) {\n this._currentIndex = (index + 1) % this._clients.length;\n\n return this._clients[index]!;\n }\n }\n\n // none known-connected — fall back to plain round-robin; graphql-ws buffers\n // the operation until the chosen socket reconnects\n const client = this._clients[this._currentIndex]!;\n\n this._currentIndex = (this._currentIndex + 1) % this._clients.length;\n\n return client;\n }\n\n async disconnect() {\n const closed = this._clients.map(\n (client) =>\n new Promise<void>((resolve) => {\n const unsubscribe = client.on('closed', () => {\n unsubscribe();\n resolve();\n });\n\n client.dispose();\n }),\n );\n\n this._clients = [];\n this._connected = [];\n this._currentIndex = 0;\n\n await Promise.all(closed);\n }\n}\n","import { createOperationTelemetry } from '@contello/opentelemetry';\n\nexport const { wrap } = createOperationTelemetry('@contello/client');\n","export type LocalDateTime = {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n};\n\nexport type LocalDate = {\n year: number;\n month: number;\n day: number;\n};\n\nconst LOCAL_DATE_TIME_KEYS = ['year', 'month', 'day', 'hour', 'minute', 'second'] as const;\nconst LOCAL_DATE_KEYS = ['year', 'month', 'day'] as const;\n\nconst DATE_TIME_REGEX = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})/;\nconst DATE_REGEX = /^(\\d{4})-(\\d{2})-(\\d{2})/;\n\nfunction pad2(n: number): string {\n return n.toString().padStart(2, '0');\n}\n\nfunction pad4(n: number): string {\n return n.toString().padStart(4, '0');\n}\n\nfunction hasExactKeys(value: object, keys: readonly string[]): boolean {\n const ownKeys = Object.keys(value);\n\n if (ownKeys.length !== keys.length) {\n return false;\n }\n\n for (const key of keys) {\n if (!Object.prototype.hasOwnProperty.call(value, key)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction allNumbers(value: Record<string, unknown>, keys: readonly string[]): boolean {\n for (const key of keys) {\n if (typeof value[key] !== 'number') {\n return false;\n }\n }\n\n return true;\n}\n\nexport function isLocalDateTime(value: unknown): value is LocalDateTime {\n return (\n !!value &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n hasExactKeys(value, LOCAL_DATE_TIME_KEYS) &&\n allNumbers(value as Record<string, unknown>, LOCAL_DATE_TIME_KEYS)\n );\n}\n\nexport function isLocalDate(value: unknown): value is LocalDate {\n return (\n !!value &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n hasExactKeys(value, LOCAL_DATE_KEYS) &&\n allNumbers(value as Record<string, unknown>, LOCAL_DATE_KEYS)\n );\n}\n\nexport function decodeLocalDateTime(value: string): LocalDateTime {\n const match = DATE_TIME_REGEX.exec(value);\n\n if (!match) {\n throw new Error(`@contello/client: cannot decode LocalDateTime from \"${value}\"`);\n }\n\n return {\n year: Number(match[1]),\n month: Number(match[2]),\n day: Number(match[3]),\n hour: Number(match[4]),\n minute: Number(match[5]),\n second: Number(match[6]),\n };\n}\n\nexport function decodeLocalDate(value: string): LocalDate {\n const match = DATE_REGEX.exec(value);\n\n if (!match) {\n throw new Error(`@contello/client: cannot decode LocalDate from \"${value}\"`);\n }\n\n return {\n year: Number(match[1]),\n month: Number(match[2]),\n day: Number(match[3]),\n };\n}\n\nexport function encodeLocalDateTime(value: LocalDateTime): string {\n return (\n `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}` +\n `T${pad2(value.hour)}:${pad2(value.minute)}:${pad2(value.second)}Z`\n );\n}\n\nexport function encodeLocalDate(value: LocalDate): string {\n return `${pad4(value.year)}-${pad2(value.month)}-${pad2(value.day)}T00:00:00Z`;\n}\n","import { encodeLocalDate, encodeLocalDateTime, isLocalDate, isLocalDateTime } from './scalars';\n\n/**\n * encodes outgoing variables: LocalDateTime / LocalDate POJOs become wire strings.\n * detection is by shape — generated input types use the struct types, so consumers\n * pass structs in the right places, and stray objects with the same shape would be\n * an extremely unusual coincidence.\n */\nexport function transformVariables<T>(value: T): T {\n if (value === null || value === undefined) {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => transformVariables(item)) as unknown as T;\n }\n\n if (typeof value !== 'object') {\n return value;\n }\n\n if (isLocalDateTime(value)) {\n return encodeLocalDateTime(value) as unknown as T;\n }\n\n if (isLocalDate(value)) {\n return encodeLocalDate(value) as unknown as T;\n }\n\n const obj = value as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n\n for (const [key, val] of Object.entries(obj)) {\n out[key] = transformVariables(val);\n }\n\n return out as unknown as T;\n}\n","import { graphqlOperationAttributes } from '@contello/opentelemetry';\nimport { firstAsync } from '@entwico/dash/async';\nimport { wrap } from './telemetry';\nimport { transformVariables } from './transform-variables';\nimport type { OperationMap, Rpc } from './types';\n\ntype Subscribe = <TData>(query: string, variables?: Record<string, unknown> | undefined) => AsyncIterable<TData>;\n\nexport function buildRpc<T extends OperationMap>(operations: T, subscribe: Subscribe): Rpc<T> {\n const rpc = {} as Record<string, (...args: any[]) => any>;\n\n for (const [name, def] of Object.entries(operations)) {\n rpc[name] = def.kind === 'subscription' ? (variables?: Record<string, unknown>) =>\n subscribe<unknown>(def.document, transformVariables(variables)) : (variables?: Record<string, unknown>) => {\n const vars = transformVariables(variables);\n\n return wrap(\n `rpc:${name}`,\n () => firstAsync(subscribe<unknown>(def.document, vars)),\n graphqlOperationAttributes(def.document, vars),\n );\n };\n }\n\n return rpc as Rpc<T>;\n}\n","import { transformVariables } from './transform-variables';\nimport type { SourceDef, SourceMutationBinding, SourceMutations } from './types';\n\nexport type SourceMutationKind = keyof SourceMutations;\n\n/** What a write takes: the caller's input, and the id for a delete. */\nexport type SourceMutationValues = {\n input?: unknown;\n id?: string | undefined;\n};\n\nconst cache = new WeakMap<SourceDef, Partial<Record<SourceMutationKind, string>>>();\n\n/**\n * A create/update answers with the entity itself, so it selects the source's own fragment — the\n * write comes back in the same shape a read does and needs no follow-up fetch. A delete answers\n * with an id, either wrapped in a response object or, for routes, as a bare scalar.\n */\nfunction createSelection(source: SourceDef, binding: SourceMutationBinding): string {\n const declarations = binding.arguments.map((argument) => `$${argument.name}: ${argument.type}`).join(', ');\n const args = binding.arguments.map((argument) => `${argument.name}: $${argument.name}`).join(', ');\n const selection = { entity: ` { ...${source.fragment} }`, idObject: ' { id }', idScalar: '' }[binding.result];\n const operation = `mutation(${declarations}) { result: ${binding.field}(${args})${selection} }`;\n\n return binding.result === 'entity' ? `${source.document}\\n${operation}` : operation;\n}\n\nexport function getSourceMutation(source: SourceDef, kind: SourceMutationKind): SourceMutationBinding | undefined {\n return source.mutations?.[kind];\n}\n\n/** The mutation document for one write operation of a source. Cached per source + kind. */\nexport function createSourceMutation(source: SourceDef, kind: SourceMutationKind): string {\n const binding = getSourceMutation(source, kind);\n\n if (!binding) {\n throw new Error(\n `@contello/client: source \"${source.__model}\" has no ${kind} mutation — ` +\n `the schema exposes none for this model`,\n );\n }\n\n const cached = cache.get(source);\n\n if (cached?.[kind] !== undefined) {\n return cached[kind];\n }\n\n const doc = createSelection(source, binding);\n const entry = cached ?? {};\n\n entry[kind] = doc;\n cache.set(source, entry);\n\n return doc;\n}\n\n/**\n * Variables for a write: one per bound argument, the input nested under the envelope field when\n * the argument is a one-field wrapper, and everything encoded on the way out (LocalDate /\n * LocalDateTime structs become wire strings) — every caller goes through here, so no write path\n * can skip the encoding.\n */\nexport function createSourceMutationVariables(\n binding: SourceMutationBinding,\n values: SourceMutationValues,\n): Record<string, unknown> {\n const variables: Record<string, unknown> = {};\n\n for (const argument of binding.arguments) {\n variables[argument.name] =\n argument.from === 'id' ? values.id : (argument.envelope ? { [argument.envelope]: values.input } : values.input);\n }\n\n return transformVariables(variables);\n}\n\n/** Pulls the id out of whatever shape the mutation answered with. */\nexport function readSourceMutationId(binding: SourceMutationBinding, result: unknown): string {\n return binding.result === 'idScalar' ? (result as string) : (result as { id: string }).id;\n}\n","import type { SourceDef } from './types';\n\nconst cache = new WeakMap<SourceDef, string>();\n\nfunction createSelection(source: SourceDef): string {\n const spread = `{ ...${source.fragment} }`;\n\n switch (source.__cardinality) {\n case 'singleton': {\n return `subscription { source: ${source.subscription} ${spread} }`;\n }\n case 'entity': {\n return `subscription($ids: [ID!]) { source: ${source.subscription}(request: { filter: { ids: $ids } }) ${spread} }`;\n }\n case 'route': {\n return `subscription($ids: [ID!], $paths: [String!]) { source: ${source.subscription}(request: { ids: $ids, paths: $paths }) ${spread} }`;\n }\n case 'asset': {\n return `subscription($ids: [ID!]) { source: ${source.subscription}(filter: { ids: $ids }) ${spread} }`;\n }\n case 'i18nMessage': {\n return `subscription($collection: String!, $ids: [ID!]) { source: ${source.subscription}(collectionReferenceName: $collection, ids: $ids) ${spread} }`;\n }\n }\n}\n\nexport function createSourceSubscription(source: SourceDef): string {\n const cached = cache.get(source);\n\n if (cached !== undefined) {\n return cached;\n }\n\n const doc = `${source.document}\\n${createSelection(source)}`;\n\n cache.set(source, doc);\n\n return doc;\n}\n","import { graphqlOperationAttributes } from '@contello/opentelemetry';\nimport { concatAsync, firstAsync, mapAsync } from '@entwico/dash/async';\nimport {\n type SourceMutationKind,\n createSourceMutation,\n createSourceMutationVariables,\n readSourceMutationId,\n} from './source-mutation';\nimport { createSourceSubscription } from './source-subscription';\nimport { wrap } from './telemetry';\nimport { transformVariables } from './transform-variables';\nimport type { SourceAccessors, SourceDef, SourceMap } from './types';\n\ntype Subscribe = <TData>(query: string, variables?: Record<string, unknown> | undefined) => AsyncIterable<TData>;\n\nconst WRITE_KINDS: SourceMutationKind[] = ['create', 'update', 'delete'];\n\nexport function createSources<TSources extends SourceMap>(\n sources: TSources,\n subscribe: Subscribe,\n): SourceAccessors<TSources> {\n const out = {} as Record<string, Record<string, (...args: any[]) => Promise<unknown>>>;\n\n for (const [name, source] of Object.entries(sources)) {\n const def = source as SourceDef;\n const doc = createSourceSubscription(def);\n const accessor = createSourceAccessor(name, def, doc, subscribe);\n\n if (accessor) {\n out[name] = { ...accessor, ...createSourceWriters(name, def, subscribe) };\n }\n }\n\n return out as SourceAccessors<TSources>;\n}\n\n/**\n * Write accessors for the mutations the generator bound to this source. A create/update answers\n * with the entity in the source's fragment shape, a delete with the id it removed. Nothing is\n * cached here — `@contello/store` collections take the same payload into their cache.\n */\nfunction createSourceWriters(\n name: string,\n def: SourceDef,\n subscribe: Subscribe,\n): Record<string, (input: unknown) => Promise<unknown>> {\n const out: Record<string, (input: unknown) => Promise<unknown>> = {};\n\n for (const kind of WRITE_KINDS) {\n const binding = def.mutations?.[kind];\n\n if (!binding) {\n continue;\n }\n\n const doc = createSourceMutation(def, kind);\n\n out[kind] = (input: unknown) => {\n // a delete is addressed by id: bindings that take a bare `id:` argument read it off the input\n const variables = createSourceMutationVariables(\n binding,\n kind === 'delete' ? { input, id: (input as { id: string }).id } : { input },\n );\n\n return wrap(\n `source:${name}:${kind}`,\n async () => {\n const response = await firstAsync(subscribe<{ result: unknown }>(doc, variables));\n\n if (response?.result === undefined || response.result === null) {\n throw new Error(`@contello/client: ${kind} on source \"${name}\" returned no entity`);\n }\n\n return kind === 'delete' ? readSourceMutationId(binding, response.result) : response.result;\n },\n graphqlOperationAttributes(doc, variables),\n );\n };\n }\n\n return out;\n}\n\nfunction createSourceAccessor(\n name: string,\n def: SourceDef,\n doc: string,\n subscribe: Subscribe,\n): { fetch: (...args: any[]) => Promise<unknown> } | undefined {\n switch (def.__cardinality) {\n case 'singleton': {\n return {\n fetch: () =>\n wrap(\n `source:${name}`,\n () => firstAsync(mapAsync(subscribe<{ source: unknown }>(doc), (r) => r.source)),\n graphqlOperationAttributes(doc),\n ),\n };\n }\n case 'entity': {\n return {\n fetch: (vars?: { ids?: string[] }) => {\n const variables = transformVariables({ ids: vars?.ids });\n\n return wrap(\n `source:${name}`,\n () => concatAsync(mapAsync(subscribe<{ source: unknown[] }>(doc, variables), (r) => r.source)),\n graphqlOperationAttributes(doc, variables),\n );\n },\n };\n }\n case 'route': {\n return {\n fetch: (vars?: { ids?: string[] | undefined; paths?: string[] | undefined } | undefined) => {\n const variables = transformVariables({ ids: vars?.ids, paths: vars?.paths });\n\n return wrap(\n `source:${name}`,\n () => concatAsync(mapAsync(subscribe<{ source: unknown[] }>(doc, variables), (r) => r.source)),\n graphqlOperationAttributes(doc, variables),\n );\n },\n };\n }\n case 'asset': {\n return {\n fetch: (vars?: { ids?: string[] | undefined } | undefined) => {\n const variables = transformVariables({ ids: vars?.ids });\n\n return wrap(\n `source:${name}`,\n () => concatAsync(mapAsync(subscribe<{ source: unknown[] }>(doc, variables), (r) => r.source)),\n graphqlOperationAttributes(doc, variables),\n );\n },\n };\n }\n case 'i18nMessage': {\n return {\n fetch: (vars: { collection: string; ids?: string[] | undefined }) => {\n const variables = transformVariables({ collection: vars.collection, ids: vars.ids });\n\n return wrap(\n `source:${name}`,\n () => concatAsync(mapAsync(subscribe<{ source: unknown[] }>(doc, variables), (r) => r.source)),\n graphqlOperationAttributes(doc, variables),\n );\n },\n };\n }\n }\n}\n","import { decodeLocalDate, decodeLocalDateTime } from './scalars';\n\nconst FLAT_PREFIX = '_flat_';\nconst LDT_PREFIX = '_ldt_';\nconst LD_PREFIX = '_ld_';\n\nconst MODEL_SUFFIXES = ['Entity', 'Component'];\n\nfunction decodeValue(value: unknown, decoder: (s: string) => unknown): unknown {\n if (value === null || value === undefined) {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => decodeValue(item, decoder));\n }\n\n if (typeof value === 'string') {\n return decoder(value);\n }\n\n return value;\n}\n\ntype FlatRef = { _flatId?: string | undefined };\ntype FlatComponent = FlatRef & { __typename?: string | undefined };\n\nfunction deriveModel(typename: string): string | undefined {\n for (const suffix of MODEL_SUFFIXES) {\n if (typename.endsWith(suffix)) {\n const stripped = typename.slice(0, -suffix.length);\n\n return stripped.charAt(0).toLowerCase() + stripped.slice(1);\n }\n }\n\n return undefined;\n}\n\n/**\n * transforms a GraphQL response in a single depth-first pass:\n * - resolves `_flat_{field}` companions into nested component arrays (refs are\n * matched against the companion map by `_flatId`, at any nesting depth — the\n * companion lists the whole subtree, so one map serves every ref below it)\n * - injects `__model` on objects with entity/component `__typename`\n * - decodes managed scalar aliases (`_ldt_` / `_ld_`) into structured values\n *\n * a `seen` set guards against shared or cyclic references so every object is\n * visited exactly once.\n */\nexport function transformResponse<T>(data: T): T {\n transformNode(data, undefined, new WeakSet());\n\n return data;\n}\n\nfunction transformNode(\n value: unknown,\n flatMap: Map<string, FlatComponent> | undefined,\n seen: WeakSet<object>,\n): void {\n if (!value || typeof value !== 'object') {\n return;\n }\n\n if (seen.has(value)) {\n return;\n }\n\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) {\n transformNode(item, flatMap, seen);\n }\n\n return;\n }\n\n const obj = value as Record<string, unknown>;\n\n // inject __model from __typename\n const typename = obj['__typename'];\n\n if (typeof typename === 'string') {\n const model = deriveModel(typename);\n\n if (model) {\n obj['__model'] = model;\n }\n }\n\n // collect `_flat_*` companions into this scope's resolution map, extending any\n // map inherited from an ancestor so refs nested below resolve against the same\n // companion set\n let ownMap: Map<string, FlatComponent> | undefined;\n\n for (const key of Object.keys(obj)) {\n if (!key.startsWith(FLAT_PREFIX)) {\n continue;\n }\n\n const flatArray = obj[key] as FlatComponent[] | undefined;\n\n delete obj[key];\n\n if (!flatArray) {\n continue;\n }\n\n if (!ownMap) {\n ownMap = flatMap ? new Map(flatMap) : new Map();\n }\n\n for (const component of flatArray) {\n if (component._flatId) {\n ownMap.set(component._flatId, component);\n }\n }\n }\n\n // decode scalar aliases, resolve ref arrays, and recurse — one pass over keys.\n // refs resolve against this object's own companion map if it had `_flat_*`\n // siblings, otherwise against the inherited ancestor map\n const resolveMap = ownMap ?? flatMap;\n\n for (const key of Object.keys(obj)) {\n if (key.startsWith(LDT_PREFIX)) {\n obj[key.slice(LDT_PREFIX.length)] = decodeValue(obj[key], decodeLocalDateTime);\n delete obj[key];\n\n continue;\n }\n\n if (key.startsWith(LD_PREFIX)) {\n obj[key.slice(LD_PREFIX.length)] = decodeValue(obj[key], decodeLocalDate);\n delete obj[key];\n\n continue;\n }\n\n const inner = obj[key];\n\n if (\n resolveMap &&\n Array.isArray(inner) &&\n inner.length > 0 &&\n (inner[0] as FlatRef | undefined)?._flatId !== undefined\n ) {\n obj[key] = resolveRefs(inner as FlatRef[], resolveMap);\n }\n\n transformNode(obj[key], resolveMap, seen);\n }\n}\n\nfunction resolveRefs(refs: readonly FlatRef[], flatMap: Map<string, FlatComponent>): FlatComponent[] {\n const resolved: FlatComponent[] = [];\n\n for (const ref of refs) {\n if (!ref._flatId) {\n continue;\n }\n\n const component = flatMap.get(ref._flatId);\n\n if (component) {\n resolved.push(component);\n }\n }\n\n return resolved;\n}\n","import type { ReadableStream as NodeReadableStream } from 'node:stream/web';\n\nexport type UploadMetadata = {\n name: string;\n mimeType?: string | undefined;\n size?: number | undefined;\n annotations?: { key: string; value: string }[] | undefined;\n collectionRefs?: string[] | undefined;\n /**\n * `deleteIfNotUsed` lets the server delete the asset once nothing references it.\n * @default 'retain'\n */\n retentionPolicy?: 'retain' | 'deleteIfNotUsed' | undefined;\n};\n\nexport type UploadData = Uint8Array | NodeReadableStream<Uint8Array> | ReadableStream<Uint8Array>;\n\ntype InitFrame = { type: 'init'; metadata: UploadMetadata & { projectRef: string }; token: string };\ntype ServerMessage = { type: 'ack' } | { type: 'progress'; bytesReceived: number } | { type: 'done'; id: string };\n\nexport type UploadOptions = {\n chunkSize?: number | undefined;\n abort?: AbortSignal | undefined;\n};\n\nconst DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024;\n\nfunction isUint8Array(data: UploadData): data is Uint8Array {\n return data instanceof Uint8Array;\n}\n\nexport function upload(\n url: string,\n project: string,\n token: string,\n data: UploadData,\n meta: UploadMetadata,\n options?: UploadOptions | undefined,\n): Promise<string> {\n const chunkSize = options?.chunkSize ?? DEFAULT_CHUNK_SIZE;\n const wsUrl = `${url.replace(/^http/i, 'ws')}/api/v1/assets/ws`;\n\n const size = isUint8Array(data) ? data.length : meta.size;\n\n return new Promise<string>((resolve, reject) => {\n const ws = new WebSocket(wsUrl, 'contello-file-upload-v1');\n\n let done = false;\n\n const cleanup = () => {\n options?.abort?.removeEventListener('abort', abortHandler);\n };\n\n const abortHandler = () => {\n if (done) {\n return;\n }\n\n ws.close();\n reject(new Error('upload aborted'));\n };\n\n options?.abort?.addEventListener('abort', abortHandler);\n\n function sendBuffer(buf: Uint8Array) {\n let offset = 0;\n\n while (offset < buf.length) {\n const chunk = buf.subarray(offset, offset + chunkSize);\n\n ws.send(chunk);\n offset += chunk.length;\n }\n\n ws.send(JSON.stringify({ type: 'done' }));\n }\n\n const MAX_BUFFER_SIZE = 8 * 1024 * 1024;\n\n function waitForBufferedDrain(): Promise<void> {\n return new Promise((resolveDrain, rejectDrain) => {\n const check = () => {\n if (options?.abort?.aborted) {\n rejectDrain(new Error('upload aborted'));\n\n return;\n }\n\n if (ws.bufferedAmount <= MAX_BUFFER_SIZE) {\n resolveDrain();\n\n return;\n }\n\n setTimeout(check, 50);\n };\n\n check();\n });\n }\n\n async function sendStream(stream: UploadData) {\n const reader = (stream as ReadableStream<Uint8Array>).getReader();\n\n try {\n while (true) {\n const { done: streamDone, value } = await reader.read();\n\n if (streamDone) break;\n\n await waitForBufferedDrain();\n ws.send(value);\n }\n\n ws.send(JSON.stringify({ type: 'done' }));\n } catch (error) {\n reject(error);\n ws.close();\n }\n }\n\n ws.addEventListener('open', () => {\n const initFrame: InitFrame = {\n type: 'init',\n metadata: { ...meta, ...(size !== undefined && { size }), projectRef: project },\n token,\n };\n\n ws.send(JSON.stringify(initFrame));\n });\n\n ws.addEventListener('message', (event) => {\n const message: ServerMessage = JSON.parse(String(event.data));\n\n if (message.type === 'ack') {\n if (isUint8Array(data)) {\n sendBuffer(data);\n } else {\n sendStream(data);\n }\n\n return;\n }\n\n if (message.type !== 'done') {\n return;\n }\n\n done = true;\n cleanup();\n ws.close();\n resolve(message.id);\n });\n\n ws.addEventListener('error', () => {\n cleanup();\n reject(new Error('upload websocket error'));\n });\n\n ws.addEventListener('close', () => {\n cleanup();\n\n if (!done) {\n reject(new Error('connection closed before upload completed'));\n }\n });\n });\n}\n","import { graphqlOperationAttributes, injectTraceContext } from '@contello/opentelemetry';\nimport { exponentialBackoff, firstAsync } from '@entwico/dash/async';\nimport { createClient } from 'graphql-ws';\nimport type { Agent } from 'undici';\n\nimport {\n type DownloadResult,\n type HttpAgentOptions,\n type ProxyResult,\n type SitemapProxyOptions,\n createHttpAgent,\n downloadFile,\n proxyHls,\n proxySitemap,\n} from './http';\nimport { type TokenIntrospection, introspectToken } from './introspection';\nimport { ping } from './ping';\nimport { ConnectionPool } from './pool';\nimport { buildRpc } from './rpc';\nimport { createSources } from './sources';\nimport { wrap } from './telemetry';\nimport { transformResponse } from './transform-response';\nimport type { Rpc, Schema, SourceAccessors } from './types';\nimport { type UploadData, type UploadMetadata, type UploadOptions, upload as uploadAsset } from './upload';\n\nexport type ConnectionContext = {\n connectionId: string;\n websocketUrl: string;\n};\n\nexport type ConnectionEvents = {\n onConnected?: ((context: ConnectionContext) => void) | undefined;\n onConnecting?: ((context: ConnectionContext) => void) | undefined;\n onClosed?: ((context: ConnectionContext) => void) | undefined;\n onError?: ((context: ConnectionContext, error: unknown) => void) | undefined;\n};\n\nexport type ContelloClientOptions<TSchema extends Schema | undefined = undefined> = {\n url: string;\n project: string;\n token: string;\n schema?: TSchema | undefined;\n connections?: number | undefined;\n http?: HttpAgentOptions | undefined;\n onConnected?: (() => void) | undefined;\n onReconnecting?: (() => void) | undefined;\n onError?: ((error: unknown) => void) | undefined;\n connectionEvents?: ConnectionEvents | undefined;\n};\n\ntype PoolState = 'disconnected' | 'connected' | 'reconnecting';\n\nexport class ContelloClient<TSchema extends Schema | undefined = undefined> {\n private _pool: ConnectionPool;\n private _rpc: TSchema extends Schema<infer TOps, any, any> ? Rpc<TOps> : undefined;\n private _sources: TSchema extends Schema<any, infer TSources, any> ? SourceAccessors<TSources> : undefined;\n private _url: string;\n private _project: string;\n private _token: string;\n private _agent: Agent;\n\n constructor(options: ContelloClientOptions<TSchema>) {\n const { url, project, token, schema, connections = 1, connectionEvents } = options;\n\n this._url = url;\n this._project = project;\n this._token = token;\n this._agent = createHttpAgent(options.http);\n\n const websocketUrl = `${url}/graphql/projects/${project}`.replace(/^http/i, 'ws');\n\n let state: PoolState = 'disconnected';\n let connectedCount = 0;\n\n const onConnectionUp = () => {\n connectedCount++;\n\n if (connectedCount !== connections || state === 'connected') {\n return;\n }\n\n state = 'connected';\n options.onConnected?.();\n };\n\n const onConnectionDown = () => {\n if (connectedCount > 0) {\n connectedCount--;\n }\n\n if (state !== 'connected') {\n return;\n }\n\n state = 'reconnecting';\n options.onReconnecting?.();\n };\n\n this._pool = new ConnectionPool((id: string) => {\n const context: ConnectionContext = Object.freeze({ connectionId: id, websocketUrl });\n\n return createClient({\n url: websocketUrl,\n connectionParams: { token },\n lazy: false,\n keepAlive: 30_000,\n retryAttempts: Infinity,\n retryWait: exponentialBackoff,\n shouldRetry: () => true,\n jsonMessageReplacer: (key, value) => {\n if (!key) {\n return injectTraceContext(value);\n }\n\n return value;\n },\n ...(options.onError && { onNonLazyError: (e) => options.onError!(e) }),\n on: {\n connected: () => {\n onConnectionUp();\n connectionEvents?.onConnected?.(context);\n },\n connecting: () => {\n connectionEvents?.onConnecting?.(context);\n },\n closed: () => {\n onConnectionDown();\n connectionEvents?.onClosed?.(context);\n },\n ...((options.onError || connectionEvents?.onError) && {\n error: (e) => {\n options.onError?.(e);\n connectionEvents?.onError?.(context, e);\n },\n }),\n },\n });\n }, connections);\n\n this._rpc = (\n schema?.operations ? buildRpc(schema.operations, (q, v) => this.subscribe(q, v)) : undefined\n ) as typeof this._rpc;\n\n this._sources = (\n schema?.sources ? createSources(schema.sources, (q, v) => this.subscribe(q, v)) : undefined\n ) as typeof this._sources;\n }\n\n get rpc(): TSchema extends Schema<infer TOps, any, any> ? Rpc<TOps> : never {\n if (!this._rpc) {\n throw new Error('@contello/client: .rpc accessed without a schema containing operations');\n }\n\n return this._rpc as any;\n }\n\n get sources(): TSchema extends Schema<any, infer TSources, any> ? SourceAccessors<TSources> : never {\n if (!this._sources) {\n throw new Error('@contello/client: .sources accessed without a schema containing sources');\n }\n\n return this._sources as any;\n }\n\n async init(): Promise<void> {\n await this._pool.connect();\n }\n\n async destroy(): Promise<void> {\n await this._pool.disconnect();\n await this._agent.close();\n }\n\n async ping(): Promise<void> {\n // excluded from telemetry to avoid noise\n return ping((query) => firstAsync(this.subscribe(query)));\n }\n\n /**\n * What a temporary token the Contello ui handed to an extension page stands for in the project of\n * this client: the user and the user's effective permissions, or inactive. The client's\n * application needs read access to the project. See `createTokenIntrospector` for the caching\n * wrapper a backend puts in front of its requests.\n */\n introspectToken(token: string): Promise<TokenIntrospection> {\n // not execute(): its span records the variables, and the token must not end up in telemetry\n return wrap(\n '@contello/client:introspectToken',\n () => introspectToken((query, variables) => firstAsync(this.subscribe(query, variables)), token),\n );\n }\n\n /**\n * Open a subscription on the websocket. Each `[Symbol.asyncIterator]()` call (the implicit one\n * from `for await`, or via `rxjs.from(this)`) starts a fresh server subscription and tears it\n * down when the iterator is returned (`break`, error, or explicit stop).\n */\n subscribe<TData>(query: string, variables?: Record<string, unknown> | undefined): AsyncIterable<TData> {\n const pool = this._pool;\n\n return {\n [Symbol.asyncIterator](): AsyncIterator<TData> {\n const wsClient = pool.get();\n const queue: TData[] = [];\n let pending: { resolve: (r: IteratorResult<TData>) => void; reject: (e: unknown) => void } | undefined;\n let done = false;\n let error: unknown;\n\n const unsubscribe = wsClient.subscribe<TData>(\n { query, variables },\n {\n next(msg) {\n const value = transformResponse(msg.data);\n\n if (value === undefined || value === null) {\n return;\n }\n\n if (pending) {\n const p = pending;\n\n pending = undefined;\n p.resolve({ value: value as TData, done: false });\n } else {\n queue.push(value as TData);\n }\n },\n error(err) {\n done = true;\n error = err;\n\n if (!pending) {\n return;\n }\n\n const p = pending;\n\n pending = undefined;\n p.reject(err);\n },\n complete() {\n done = true;\n\n if (!pending) {\n return;\n }\n\n const p = pending;\n\n pending = undefined;\n p.resolve({ value: undefined as unknown as TData, done: true });\n },\n },\n );\n\n return {\n next(): Promise<IteratorResult<TData>> {\n if (queue.length > 0) {\n return Promise.resolve({ value: queue.shift()!, done: false });\n }\n\n if (error !== undefined) {\n return Promise.reject(error);\n }\n\n if (done) {\n return Promise.resolve({ value: undefined as unknown as TData, done: true });\n }\n\n return new Promise<IteratorResult<TData>>((resolve, reject) => {\n pending = { resolve, reject };\n });\n },\n return(): Promise<IteratorResult<TData>> {\n unsubscribe();\n\n return Promise.resolve({ value: undefined as unknown as TData, done: true });\n },\n throw(err): Promise<IteratorResult<TData>> {\n unsubscribe();\n\n return Promise.reject(err);\n },\n };\n },\n };\n }\n\n download(fileId: string): Promise<DownloadResult> {\n return wrap('@contello/client:download', () => downloadFile(this._agent, this._url, this._token, fileId));\n }\n\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult> {\n return wrap('@contello/client:proxyHls', () => proxyHls(this._agent, this._url, this._token, path, signal));\n }\n\n proxySitemap(\n sitemapId: string,\n options: SitemapProxyOptions,\n signal?: AbortSignal | undefined,\n ): Promise<ProxyResult> {\n return wrap(\n '@contello/client:proxySitemap',\n () => proxySitemap(this._agent, this._url, this._token, this._project, sitemapId, options, signal),\n );\n }\n\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string> {\n return wrap(\n '@contello/client:upload',\n () => uploadAsset(this._url, this._project, this._token, data, meta, options),\n );\n }\n\n execute<TData>(query: string, variables?: Record<string, unknown> | undefined): Promise<TData> {\n return wrap(\n '@contello/client:execute',\n () => firstAsync(this.subscribe<TData>(query, variables)),\n graphqlOperationAttributes(query, variables),\n );\n }\n}\n\nexport function createContelloClient<TSchema extends Schema | undefined = undefined>(\n options: ContelloClientOptions<TSchema>,\n): ContelloClient<TSchema> {\n return new ContelloClient(options);\n}\n","import type { SourceCardinality, SourceMutations } from './types';\n\n/**\n * Write bindings for the built-in sources. Unlike entity mutations these are not derived — their\n * field and argument names are fixed parts of every Contello schema — but the generator still\n * checks each one against the introspected schema before emitting it, so a server without them\n * (or with a different shape) simply yields a read-only source.\n *\n * Routes are the odd ones: `updateContelloRoute` is keyed by the `path` inside its input rather\n * than by an id, and it replaces the route rather than patching it. `deleteContelloRoute` takes a\n * bare `id` and answers with a bare id string.\n *\n * Assets have no `create` — an asset comes into being through `client.upload()`, not a mutation.\n */\nexport const BUILT_IN_MUTATIONS: Partial<Record<SourceCardinality, SourceMutations>> = {\n route: {\n create: {\n field: 'createContelloRoute',\n arguments: [{ name: 'route', type: 'ContelloRouteInput!', from: 'input' }],\n result: 'entity',\n },\n update: {\n field: 'updateContelloRoute',\n arguments: [{ name: 'route', type: 'ContelloRouteInput!', from: 'input' }],\n result: 'entity',\n },\n delete: {\n field: 'deleteContelloRoute',\n arguments: [{ name: 'id', type: 'String', from: 'id' }],\n result: 'idScalar',\n },\n },\n asset: {\n update: {\n field: 'updateContelloAsset',\n arguments: [{ name: 'request', type: 'ContelloAssetUpdateInput!', from: 'input' }],\n result: 'entity',\n },\n delete: {\n field: 'deleteContelloAsset',\n arguments: [{ name: 'id', type: 'String!', from: 'id' }],\n result: 'idObject',\n },\n },\n};\n"],"mappings":";;;;;;AAEA,MAAM,eAAe;AAErB,MAAM,0CAA0B,IAAI,IAAI;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAS,kBAAkB,SAAiB,MAAoB;CAC9D,IAAI,YAAY,OAAO,YAAY,QAAQ,CAAC,aAAa,KAAK,OAAO,GACnE,MAAM,IAAI,MAAM,WAAW,MAAM;AAErC;AAEA,SAAS,oBAAoB,MAAc,MAAoB;CAC7D,IAAI,SAAS,IACX,MAAM,IAAI,MAAM,WAAW,MAAM;CAG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