twenty-client-sdk 2.16.0 → 2.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-DWNI8pZO.js +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.mjs +11 -5
- package/dist/generate.cjs +46 -46
- package/dist/generate.mjs +146 -149
- package/dist/metadata/generated/schema.d.ts +524 -452
- package/dist/metadata/generated/types.d.ts +344 -305
- package/dist/metadata.cjs +3 -3
- package/dist/metadata.mjs +1589 -1537
- package/package.json +2 -3
- package/dist/chunk-Dqa2HsxW.mjs +0 -20
- package/dist/chunk-mLOUI7ql.js +0 -1
package/dist/generate.mjs
CHANGED
|
@@ -1,63 +1,62 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n } from "
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { assertValidSchema as te, buildSchema as ne, getNamedType as h, isEnumType as g, isInputObjectType as _, isInterfaceType as v, isListType as re, isNamedType as ie, isNonNullType as ae, isObjectType as y, isScalarType as b, isUnionType as x, lexicographicSortSchema as oe, printSchema as se } from "graphql";
|
|
1
|
+
import { n as e } from "./application-CbP6KYwU.mjs";
|
|
2
|
+
import { appendFile as t, copyFile as n, cp as r, mkdir as i, readdir as a, rename as o, rm as s, writeFile as c } from "node:fs/promises";
|
|
3
|
+
import { dirname as l, join as u, parse as ee, relative as d, resolve as f } from "node:path";
|
|
4
|
+
import { build as p } from "esbuild";
|
|
5
|
+
import { assertValidSchema as te, buildSchema as ne, getNamedType as m, isEnumType as h, isInputObjectType as g, isInterfaceType as _, isListType as re, isNamedType as ie, isNonNullType as ae, isObjectType as v, isScalarType as y, isUnionType as b, lexicographicSortSchema as oe, printSchema as se } from "graphql";
|
|
7
6
|
import ce from "lodash/camelCase.js";
|
|
8
|
-
import { promises as
|
|
7
|
+
import { promises as x, readFileSync as le } from "node:fs";
|
|
9
8
|
import { homedir as ue } from "node:os";
|
|
10
9
|
import de from "prettier/standalone";
|
|
11
10
|
import * as fe from "prettier/plugins/graphql";
|
|
12
11
|
import * as pe from "prettier/plugins/typescript";
|
|
13
|
-
import * as
|
|
14
|
-
import
|
|
12
|
+
import * as S from "prettier/plugins/estree";
|
|
13
|
+
import C from "lodash/uniq.js";
|
|
15
14
|
import { fileURLToPath as me } from "node:url";
|
|
16
15
|
//#region src/generate/client-wrapper.ts
|
|
17
|
-
var he = "// __STRIPPED_DURING_INJECTION_START__", ge = "// __STRIPPED_DURING_INJECTION_END__",
|
|
16
|
+
var he = "// __STRIPPED_DURING_INJECTION_START__", ge = "// __STRIPPED_DURING_INJECTION_END__", w = "// __UPLOAD_FILE_START__", T = "// __UPLOAD_FILE_END__", E = (e) => e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), D = (e, t) => {
|
|
18
17
|
let n = e;
|
|
19
|
-
return n = n.replace(RegExp(`${
|
|
20
|
-
},
|
|
18
|
+
return n = n.replace(RegExp(`${E(he)}[\\s\\S]*?${E(ge)}\\n?`), ""), n = n.replace("'__TWENTY_DEFAULT_URL__'", t.defaultUrl), n = n.replace(/TwentyGeneratedClient/g, t.apiClientName), t.includeUploadFile ? (n = n.replace(RegExp(`\\s*${E(w)}\\n`), "\n"), n = n.replace(RegExp(`\\s*${E(T)}\\n`), "\n")) : n = n.replace(RegExp(`\\s*${E(w)}[\\s\\S]*?${E(T)}\\n?`), "\n"), `\n// ${t.apiClientName} (auto-injected by twenty-client-sdk)\n${n}`;
|
|
19
|
+
}, O = (e) => i(e, { recursive: !0 }), k = async (e) => {
|
|
21
20
|
let t;
|
|
22
21
|
try {
|
|
23
|
-
t = await
|
|
22
|
+
t = await a(e);
|
|
24
23
|
} catch (t) {
|
|
25
24
|
if (t instanceof Error && "code" in t && t.code === "ENOENT") {
|
|
26
|
-
await
|
|
25
|
+
await i(e, { recursive: !0 });
|
|
27
26
|
return;
|
|
28
27
|
}
|
|
29
28
|
throw t;
|
|
30
29
|
}
|
|
31
|
-
await Promise.all(t.map((t) =>
|
|
30
|
+
await Promise.all(t.map((t) => s(u(e, t), {
|
|
32
31
|
recursive: !0,
|
|
33
32
|
force: !0
|
|
34
33
|
})));
|
|
35
34
|
}, _e = async (e, t) => {
|
|
36
35
|
try {
|
|
37
|
-
await
|
|
36
|
+
await o(e, t);
|
|
38
37
|
} catch (n) {
|
|
39
|
-
if (n instanceof Error && "code" in n && n.code === "EXDEV") await
|
|
38
|
+
if (n instanceof Error && "code" in n && n.code === "EXDEV") await r(e, t, { recursive: !0 }), await s(e, {
|
|
40
39
|
recursive: !0,
|
|
41
40
|
force: !0
|
|
42
41
|
});
|
|
43
42
|
else throw n;
|
|
44
43
|
}
|
|
45
|
-
},
|
|
44
|
+
}, A = (e) => s(e, {
|
|
46
45
|
recursive: !0,
|
|
47
46
|
force: !0
|
|
48
47
|
}), ve = (e) => {
|
|
49
|
-
let { root: t } =
|
|
48
|
+
let { root: t } = ee(e), n = e.slice(t.length).split(/[\\/]/).filter(Boolean).length, r = f(ue()), i = e === r || r.startsWith(`${e}/`);
|
|
50
49
|
if (e === t || n < 2 || i) throw Error(`Refusing to recursively clear unsafe path: ${e}`);
|
|
51
|
-
},
|
|
52
|
-
let n =
|
|
53
|
-
t && (ve(n), await
|
|
50
|
+
}, j = async (e, t = !1) => {
|
|
51
|
+
let n = f(...e);
|
|
52
|
+
t && (ve(n), await x.rm(n, {
|
|
54
53
|
recursive: !0,
|
|
55
54
|
force: !0
|
|
56
|
-
})), await
|
|
57
|
-
},
|
|
58
|
-
let n =
|
|
59
|
-
await
|
|
60
|
-
},
|
|
55
|
+
})), await x.mkdir(n, { recursive: !0 });
|
|
56
|
+
}, M = async (e, t) => {
|
|
57
|
+
let n = f(...e, "..");
|
|
58
|
+
await x.mkdir(n, { recursive: !0 }), await x.writeFile(f(...e), t);
|
|
59
|
+
}, N = "./runtime", P = (e) => e ? `${e.name}GenqlSelection` : "", F = (e) => {
|
|
61
60
|
let t = e.config?.endpoint ? `"${e.config.endpoint}"` : "undefined", n = e.config?.fetchImport;
|
|
62
61
|
return `
|
|
63
62
|
function(options${t ? "?" : ""}: ClientOptions): Client {
|
|
@@ -70,11 +69,11 @@ function(options${t ? "?" : ""}: ClientOptions): Client {
|
|
|
70
69
|
subscriptionRoot: typeMap.Subscription!,
|
|
71
70
|
}) as any
|
|
72
71
|
}`;
|
|
73
|
-
},
|
|
72
|
+
}, ye = (e, t) => {
|
|
74
73
|
let n = e.getQueryType(), r = e.getMutationType(), i = e.getSubscriptionType(), a = t.config?.fetchImport || "";
|
|
75
74
|
t.addCodeBlock(`
|
|
76
75
|
${a}
|
|
77
|
-
${
|
|
76
|
+
${be({
|
|
78
77
|
mutationType: r,
|
|
79
78
|
queryType: n,
|
|
80
79
|
subscriptionType: i
|
|
@@ -84,54 +83,54 @@ ${xe({
|
|
|
84
83
|
createClient as createClientOriginal,
|
|
85
84
|
generateGraphqlOperation,
|
|
86
85
|
type FieldsSelection, type GraphqlOperation, type ClientOptions, GenqlError
|
|
87
|
-
} from '${
|
|
88
|
-
export type { FieldsSelection } from '${
|
|
86
|
+
} from '${N}'
|
|
87
|
+
export type { FieldsSelection } from '${N}'
|
|
89
88
|
export { GenqlError }
|
|
90
89
|
|
|
91
90
|
import types from './types'
|
|
92
91
|
export * from './schema'
|
|
93
92
|
const typeMap = linkTypeMap(types as any)
|
|
94
93
|
|
|
95
|
-
${
|
|
94
|
+
${xe({
|
|
96
95
|
mutationType: r,
|
|
97
96
|
queryType: n,
|
|
98
97
|
subscriptionType: i
|
|
99
98
|
})}
|
|
100
99
|
|
|
101
|
-
export const createClient = ${
|
|
100
|
+
export const createClient = ${F(t)}
|
|
102
101
|
|
|
103
102
|
export const everything = {
|
|
104
103
|
__scalar: true
|
|
105
104
|
}
|
|
106
105
|
`), n && t.addCodeBlock(`
|
|
107
|
-
export type QueryResult<fields extends ${
|
|
108
|
-
export const generateQueryOp: (fields: ${
|
|
106
|
+
export type QueryResult<fields extends ${P(n)}> = FieldsSelection<${n.name}, fields>
|
|
107
|
+
export const generateQueryOp: (fields: ${P(n)} & { __name?: string }) => GraphqlOperation = function(fields) {
|
|
109
108
|
return generateGraphqlOperation('query', typeMap.Query!, fields as any)
|
|
110
109
|
}
|
|
111
110
|
`), r && t.addCodeBlock(`
|
|
112
|
-
export type MutationResult<fields extends ${
|
|
113
|
-
export const generateMutationOp: (fields: ${
|
|
111
|
+
export type MutationResult<fields extends ${P(r)}> = FieldsSelection<${r.name}, fields>
|
|
112
|
+
export const generateMutationOp: (fields: ${P(r)} & { __name?: string }) => GraphqlOperation = function(fields) {
|
|
114
113
|
return generateGraphqlOperation('mutation', typeMap.Mutation!, fields as any)
|
|
115
114
|
}
|
|
116
115
|
`), i && t.addCodeBlock(`
|
|
117
|
-
export type SubscriptionResult<fields extends ${
|
|
118
|
-
export const generateSubscriptionOp: (fields: ${
|
|
116
|
+
export type SubscriptionResult<fields extends ${P(i)}> = FieldsSelection<${i.name}, fields>
|
|
117
|
+
export const generateSubscriptionOp: (fields: ${P(i)} & { __name?: string }) => GraphqlOperation = function(fields) {
|
|
119
118
|
return generateGraphqlOperation('subscription', typeMap.Subscription!, fields as any)
|
|
120
119
|
}
|
|
121
120
|
`);
|
|
122
121
|
};
|
|
123
|
-
function
|
|
122
|
+
function be({ queryType: e, mutationType: t, subscriptionType: n }) {
|
|
124
123
|
let r = [];
|
|
125
|
-
return e && r.push(
|
|
124
|
+
return e && r.push(P(e), e.name), t && r.push(P(t), t.name), n && r.push(P(n), n.name), r.length > 0 ? `import type {${r.join(",")}} from './schema'` : "";
|
|
126
125
|
}
|
|
127
|
-
function
|
|
126
|
+
function xe({ queryType: e, mutationType: t, subscriptionType: n }) {
|
|
128
127
|
let r = "";
|
|
129
128
|
return e && (r += `
|
|
130
|
-
query<R extends ${
|
|
129
|
+
query<R extends ${P(e)}>(
|
|
131
130
|
request: R & { __name?: string },
|
|
132
131
|
): Promise<FieldsSelection<${e.name}, R>>
|
|
133
132
|
`), t && (r += `
|
|
134
|
-
mutation<R extends ${
|
|
133
|
+
mutation<R extends ${P(t)}>(
|
|
135
134
|
request: R & { __name?: string },
|
|
136
135
|
): Promise<FieldsSelection<${t.name}, R>>
|
|
137
136
|
`), `
|
|
@@ -151,14 +150,14 @@ var I = [
|
|
|
151
150
|
"__EnumValue",
|
|
152
151
|
"__Directive",
|
|
153
152
|
"__DirectiveLocation"
|
|
154
|
-
],
|
|
153
|
+
], Se = async (e, t) => {
|
|
155
154
|
try {
|
|
156
155
|
return await de.format(e, {
|
|
157
156
|
parser: t,
|
|
158
157
|
plugins: [
|
|
159
158
|
fe,
|
|
160
159
|
pe,
|
|
161
|
-
|
|
160
|
+
S
|
|
162
161
|
],
|
|
163
162
|
semi: !1,
|
|
164
163
|
singleQuote: !0,
|
|
@@ -168,10 +167,8 @@ var I = [
|
|
|
168
167
|
} catch {
|
|
169
168
|
return e;
|
|
170
169
|
}
|
|
171
|
-
},
|
|
172
|
-
|
|
173
|
-
})))()), Te = (e, t) => {
|
|
174
|
-
let n = we.default.relative(e, t);
|
|
170
|
+
}, Ce = (e, t) => {
|
|
171
|
+
let n = d(e, t);
|
|
175
172
|
return n[0] === "." ? n : `./${n}`;
|
|
176
173
|
}, L = class {
|
|
177
174
|
constructor(e, t) {
|
|
@@ -181,7 +178,7 @@ var I = [
|
|
|
181
178
|
e && this.codeBlocks.push(e);
|
|
182
179
|
}
|
|
183
180
|
addImport(e, t, n, r, i) {
|
|
184
|
-
this.config && this.config.output && (e = r ? e :
|
|
181
|
+
this.config && this.config.output && (e = r ? e : Ce(this.config.output, e)), this.imports[e] || (this.imports[e] = []);
|
|
185
182
|
let a = this.imports[e], o = a.find((e) => t && e.isDefault || !t && e.module === n);
|
|
186
183
|
if (o) return o.alias;
|
|
187
184
|
this.importAliasCounter++;
|
|
@@ -205,7 +202,7 @@ var I = [
|
|
|
205
202
|
let e = this.getImportBlock();
|
|
206
203
|
e && n.unshift(e);
|
|
207
204
|
}
|
|
208
|
-
return e && t ?
|
|
205
|
+
return e && t ? Se(n.join("\n\n"), e) : e ? n.join("\n\n") : n.join("");
|
|
209
206
|
}
|
|
210
207
|
}, R = (e) => {
|
|
211
208
|
let t = [];
|
|
@@ -223,7 +220,7 @@ var I = [
|
|
|
223
220
|
} else return `: ${H(e, !1, !1, r, i, a)}`;
|
|
224
221
|
if (ie(e)) {
|
|
225
222
|
let n = e.name;
|
|
226
|
-
|
|
223
|
+
y(e) && (n = `Scalars['${n}']`);
|
|
227
224
|
let i = a(n);
|
|
228
225
|
return r ? t ? i : `(${i} | undefined)` : t ? i : `(${i} | null)`;
|
|
229
226
|
}
|
|
@@ -244,7 +241,7 @@ function W(e) {
|
|
|
244
241
|
}
|
|
245
242
|
//#endregion
|
|
246
243
|
//#region src/generate/genql/render/requestTypes/inputObjectType.ts
|
|
247
|
-
var
|
|
244
|
+
var we = (e, t) => {
|
|
248
245
|
let n = e.getFields();
|
|
249
246
|
t.config?.sortProperties && (n = W(n));
|
|
250
247
|
let r = Object.keys(n).map((e) => {
|
|
@@ -252,30 +249,30 @@ var Ee = (e, t) => {
|
|
|
252
249
|
return `${V(t)}${t.name}${U(t.type, !1, !0)}`;
|
|
253
250
|
});
|
|
254
251
|
t.addCodeBlock(`${z(e)}export interface ${e.name} {${r.join(",")}}`);
|
|
255
|
-
},
|
|
252
|
+
}, Te = " ", Ee = (e, t) => {
|
|
256
253
|
let n = e.getFields();
|
|
257
254
|
t.config?.sortProperties && (n = W(n));
|
|
258
255
|
let r = Object.keys(n).map((e) => {
|
|
259
|
-
let t = n[e], r = [], i =
|
|
260
|
-
return o && (a ? r.push(`(${
|
|
256
|
+
let t = n[e], r = [], i = m(t.type), a = !(h(i) || y(i)), o = t.args.length > 0, s = De(t), c = !s.match(/[^?]:/);
|
|
257
|
+
return o && (a ? r.push(`(${P(i)} & { __args${c ? "?" : ""}: ${s} })`) : r.push(`{ __args: ${s} }`)), c && !a && r.push("boolean | number"), !o && a && r.push(P(i)), `${B(t)}${t.name}?: ${r.join(" | ")}`;
|
|
261
258
|
});
|
|
262
|
-
if (
|
|
263
|
-
let n = t.schema.getPossibleTypes(e).map((e) => `on_${e.name}?: ${
|
|
259
|
+
if (_(e) && t.schema) {
|
|
260
|
+
let n = t.schema.getPossibleTypes(e).map((e) => `on_${e.name}?: ${P(e)}`);
|
|
264
261
|
t.config?.sortProperties && (n = n.sort()), r = r.concat(n);
|
|
265
262
|
}
|
|
266
|
-
r.push("__typename?: boolean | number"), r.push("__scalar?: boolean | number"), r = r.map((e) => e.split("\n").filter(Boolean).map((e) =>
|
|
267
|
-
},
|
|
263
|
+
r.push("__typename?: boolean | number"), r.push("__scalar?: boolean | number"), r = r.map((e) => e.split("\n").filter(Boolean).map((e) => Te + e).join("\n")), t.addCodeBlock(`${z(e)}export interface ${P(e)}{\n${r.join("\n")}\n}`);
|
|
264
|
+
}, De = (e) => `{${e.args.map((e) => `${V(e)}${e.name}${U(e.type, !1, !0)}`).join(", ")}}`, Oe = (e, t) => {
|
|
268
265
|
let n = [...e.getTypes()];
|
|
269
266
|
t.config?.sortProperties && (n = n.sort());
|
|
270
|
-
let r = n.map((e) => `on_${e.name}?:${
|
|
271
|
-
r.push(...i.map((e) => `on_${e.name}?: ${
|
|
272
|
-
},
|
|
267
|
+
let r = n.map((e) => `on_${e.name}?:${P(e)}`), i = C(n.map((e) => e.getInterfaces()).flat());
|
|
268
|
+
r.push(...i.map((e) => `on_${e.name}?: ${P(e)}`)), r.push("__typename?: boolean | number"), t.addCodeBlock(`${z(e)}export interface ${P(e)}{\n${r.map((e) => " " + e).join(",\n")}\n}`);
|
|
269
|
+
}, ke = (e, t) => {
|
|
273
270
|
let n = e.getTypeMap();
|
|
274
271
|
t.config?.sortProperties && (n = W(n));
|
|
275
272
|
for (let e in n) {
|
|
276
273
|
if (I.includes(e)) continue;
|
|
277
274
|
let r = n[e];
|
|
278
|
-
(
|
|
275
|
+
(v(r) || _(r)) && Ee(r, t), g(r) && we(r, t), b(r) && Oe(r, t);
|
|
279
276
|
}
|
|
280
277
|
let r = [
|
|
281
278
|
{
|
|
@@ -290,58 +287,58 @@ var Ee = (e, t) => {
|
|
|
290
287
|
type: e.getSubscriptionType(),
|
|
291
288
|
name: "SubscriptionGenqlSelection"
|
|
292
289
|
}
|
|
293
|
-
].map(
|
|
290
|
+
].map(Ae).filter(Boolean).join("\n");
|
|
294
291
|
t.addCodeBlock(r);
|
|
295
292
|
};
|
|
296
|
-
function
|
|
297
|
-
return e &&
|
|
293
|
+
function Ae({ type: e, name: t }) {
|
|
294
|
+
return e && P(e) !== t ? `export type ${t} = ${P(e)}` : "";
|
|
298
295
|
}
|
|
299
296
|
//#endregion
|
|
300
297
|
//#region src/generate/genql/render/responseTypes/enumType.ts
|
|
301
|
-
var
|
|
298
|
+
var je = (e, t) => {
|
|
302
299
|
let n = e.getValues().map((e) => `'${e.name}'`);
|
|
303
300
|
t.addCodeBlock(`${z(e)}export type ${e.name} = ${n.join(" | ")}`);
|
|
304
|
-
},
|
|
301
|
+
}, Me = " ", G = (e, t) => {
|
|
305
302
|
let n = e.getFields();
|
|
306
303
|
t.config?.sortProperties && (n = W(n));
|
|
307
304
|
let r = Object.keys(n).map((e) => n[e]);
|
|
308
305
|
if (!t.schema) throw Error("no schema provided");
|
|
309
|
-
let i =
|
|
310
|
-
a = a.map((e) => e.split("\n").filter(Boolean).map((e) =>
|
|
311
|
-
},
|
|
306
|
+
let i = v(e) ? [e.name] : t.schema.getPossibleTypes(e).map((e) => e.name), a = r.map((e) => `${B(e)}${e.name}${U(e.type, !0, !0)}`).concat([`__typename: ${i.length > 0 ? i.map((e) => `'${e}'`).join("|") : "string"}`]);
|
|
307
|
+
a = a.map((e) => e.split("\n").filter(Boolean).map((e) => Me + e).join("\n")), t.addCodeBlock(`${z(e)}export interface ${e.name} {\n${a.join("\n")}\n}`);
|
|
308
|
+
}, Ne = {
|
|
312
309
|
Int: "number",
|
|
313
310
|
Float: "number",
|
|
314
311
|
String: "string",
|
|
315
312
|
Boolean: "boolean",
|
|
316
313
|
ID: "string"
|
|
317
|
-
},
|
|
318
|
-
...
|
|
314
|
+
}, K = (e, t) => ({
|
|
315
|
+
...Ne,
|
|
319
316
|
...t?.config?.scalarTypes || {}
|
|
320
317
|
})[e.name] || "any";
|
|
321
318
|
//#endregion
|
|
322
319
|
//#region src/generate/genql/render/responseTypes/scalarType.ts
|
|
323
|
-
function
|
|
320
|
+
function Pe(e, t) {
|
|
324
321
|
let n = "";
|
|
325
322
|
return t.forEach((t) => {
|
|
326
|
-
n += ` ${t.name}: ${
|
|
323
|
+
n += ` ${t.name}: ${K(t, e)},\n`;
|
|
327
324
|
}), `export type Scalars = {\n${n}}`;
|
|
328
325
|
}
|
|
329
326
|
//#endregion
|
|
330
327
|
//#region src/generate/genql/render/responseTypes/unionType.ts
|
|
331
|
-
var
|
|
328
|
+
var Fe = (e, t) => {
|
|
332
329
|
let n = e.getTypes().map((e) => e.name);
|
|
333
330
|
t.config?.sortProperties && (n = n.sort()), t.addCodeBlock(`${z(e)}export type ${e.name} = (${n.join(" | ")}) & { __isUnion?: true }`);
|
|
334
|
-
},
|
|
331
|
+
}, Ie = (e, t) => {
|
|
335
332
|
if (!t.schema) throw Error("schema is required to render unionType");
|
|
336
333
|
let n = t.schema.getPossibleTypes(e).map((e) => e.name);
|
|
337
334
|
n.length ? t.addCodeBlock(`${z(e)}export type ${e.name} = (${n.join(" | ")}) & { __isUnion?: true }`) : G(e, t);
|
|
338
|
-
},
|
|
335
|
+
}, Le = (e, t) => {
|
|
339
336
|
let n = e.getTypeMap();
|
|
340
|
-
t.config?.sortProperties && (n = W(n)), t.addCodeBlock(
|
|
337
|
+
t.config?.sortProperties && (n = W(n)), t.addCodeBlock(Pe(t, Object.values(n).filter((e) => y(e))));
|
|
341
338
|
for (let e in n) {
|
|
342
339
|
if (I.includes(e)) continue;
|
|
343
340
|
let r = n[e];
|
|
344
|
-
|
|
341
|
+
h(r) && je(r, t), b(r) && Fe(r, t), v(r) && G(r, t), _(r) && Ie(r, t);
|
|
345
342
|
}
|
|
346
343
|
let r = [
|
|
347
344
|
{
|
|
@@ -356,15 +353,15 @@ var Le = (e, t) => {
|
|
|
356
353
|
type: e.getSubscriptionType(),
|
|
357
354
|
name: "Subscription"
|
|
358
355
|
}
|
|
359
|
-
].map(
|
|
356
|
+
].map(Re).filter(Boolean).join("\n");
|
|
360
357
|
t.addCodeBlock(r);
|
|
361
358
|
};
|
|
362
|
-
function
|
|
359
|
+
function Re({ type: e, name: t }) {
|
|
363
360
|
return e && e.name !== t ? `export type ${t} = ${e.name}` : "";
|
|
364
361
|
}
|
|
365
362
|
//#endregion
|
|
366
363
|
//#region src/generate/genql/render/schema/renderSchema.ts
|
|
367
|
-
var
|
|
364
|
+
var ze = (e, t) => {
|
|
368
365
|
t.addCodeBlock(se(e));
|
|
369
366
|
}, q = (e, t) => `
|
|
370
367
|
const ${e}_possibleTypes: string[] = [${t.map((e) => `'${e}'`).join(",")}]
|
|
@@ -372,18 +369,18 @@ var Ve = (e, t) => {
|
|
|
372
369
|
if (!obj?.__typename) throw new Error('__typename is missing in "is${e}"')
|
|
373
370
|
return ${e}_possibleTypes.includes(obj.__typename)
|
|
374
371
|
}
|
|
375
|
-
`,
|
|
372
|
+
`, Be = (e, t) => {
|
|
376
373
|
let n = e.getTypeMap();
|
|
377
374
|
for (let r in n) {
|
|
378
375
|
if (I.includes(r)) continue;
|
|
379
376
|
let i = n[r];
|
|
380
|
-
if (
|
|
377
|
+
if (b(i)) {
|
|
381
378
|
let e = i.getTypes().map((e) => e.name);
|
|
382
379
|
t.addCodeBlock(q(i.name, e));
|
|
383
|
-
} else if (
|
|
380
|
+
} else if (_(i)) {
|
|
384
381
|
let n = e.getPossibleTypes(i).map((e) => e.name);
|
|
385
382
|
t.addCodeBlock(q(i.name, n));
|
|
386
|
-
} else
|
|
383
|
+
} else v(i) && t.addCodeBlock(q(i.name, [i.name]));
|
|
387
384
|
}
|
|
388
385
|
};
|
|
389
386
|
//#endregion
|
|
@@ -395,38 +392,38 @@ function J(e) {
|
|
|
395
392
|
//#region src/generate/genql/render/typeMap/objectType.ts
|
|
396
393
|
var Y = (e, t) => {
|
|
397
394
|
let n = Object.keys(e.getFields()).reduce((t, n) => {
|
|
398
|
-
let r = e.getFields()[n], i = { type:
|
|
395
|
+
let r = e.getFields()[n], i = { type: m(r.type).name };
|
|
399
396
|
t[n] = i;
|
|
400
397
|
let a = r.args || [];
|
|
401
398
|
return a.length > 0 && (i.args = a.reduce((e, t) => {
|
|
402
|
-
let n = t.type.toString(), r =
|
|
399
|
+
let n = t.type.toString(), r = m(t.type).name;
|
|
403
400
|
return e[t.name] = [r], r !== n && e[t.name]?.push(n), e;
|
|
404
401
|
}, {})), t;
|
|
405
402
|
}, {});
|
|
406
|
-
return
|
|
403
|
+
return _(e) && t.schema && t.schema.getPossibleTypes(e).map((e) => {
|
|
407
404
|
J(n) || (n[`on_${e.name}`] = { type: e.name });
|
|
408
405
|
}), J(n) || (n.__typename = { type: "String" }), n;
|
|
409
|
-
},
|
|
406
|
+
}, Ve = (e, t) => {
|
|
410
407
|
let n = e.getTypes(), r = n.reduce((e, t) => (e[`on_${t.name}`] = { type: t.name }, e), {});
|
|
411
|
-
return
|
|
408
|
+
return C(n.map((e) => e.getInterfaces()).flat()).forEach((e) => {
|
|
412
409
|
r[`on_${e.name}`] = { type: e.name };
|
|
413
410
|
}), r.__typename = { type: "String" }, r;
|
|
414
|
-
},
|
|
411
|
+
}, He = (e, t) => {
|
|
415
412
|
let n = {
|
|
416
413
|
scalars: [],
|
|
417
414
|
types: {}
|
|
418
415
|
};
|
|
419
416
|
Object.keys(e.getTypeMap()).filter((e) => !I.includes(e)).map((t) => e.getTypeMap()[t]).map((e) => {
|
|
420
|
-
|
|
417
|
+
v(e) || _(e) || g(e) ? n.types[e.name] = Y(e, t) : b(e) ? n.types[e.name] = Ve(e, t) : (y(e) || h(e)) && (n.scalars.push(e.name), n.types[e.name] = {});
|
|
421
418
|
});
|
|
422
419
|
let r = e.getQueryType();
|
|
423
420
|
r?.name && r?.name !== "Query" && (delete n.types[r.name], n.types.Query = Y(r, t));
|
|
424
421
|
let i = e.getMutationType();
|
|
425
422
|
i?.name && i.name !== "Mutation" && (delete n.types[i.name], n.types.Mutation = Y(i, t));
|
|
426
423
|
let a = e.getSubscriptionType();
|
|
427
|
-
a?.name && a.name !== "Subscription" && (delete n.types[a.name], n.types.Subscription = Y(a, t)), t.addCodeBlock(JSON.stringify(
|
|
424
|
+
a?.name && a.name !== "Subscription" && (delete n.types[a.name], n.types.Subscription = Y(a, t)), t.addCodeBlock(JSON.stringify(Ue(n), null, 4));
|
|
428
425
|
};
|
|
429
|
-
function
|
|
426
|
+
function Ue(e) {
|
|
430
427
|
let t = Object.assign({}, ...Object.keys(e.types).map((e, t) => ({ [e]: t })));
|
|
431
428
|
return {
|
|
432
429
|
scalars: e.scalars.map((e) => t[e]),
|
|
@@ -447,110 +444,110 @@ function Ge(e) {
|
|
|
447
444
|
}
|
|
448
445
|
//#endregion
|
|
449
446
|
//#region src/generate/genql/runtime/batcher.ts?raw
|
|
450
|
-
var Ke = "import type { GraphqlOperation } from './generateGraphqlOperation'\nimport { GenqlError } from './error'\n\ntype Variables = Record<string, any>\n\ntype QueryError = Error & {\n message: string\n\n locations?: Array<{\n line: number\n column: number\n }>\n path?: any\n rid: string\n details?: Record<string, any>\n}\ntype Result = {\n data: Record<string, any>\n errors: Array<QueryError>\n}\ntype Fetcher = (\n batchedQuery: GraphqlOperation | Array<GraphqlOperation>,\n) => Promise<Array<Result>>\ntype Options = {\n batchInterval?: number\n shouldBatch?: boolean\n maxBatchSize?: number\n}\ntype Queue = Array<{\n request: GraphqlOperation\n resolve: (...args: Array<any>) => any\n reject: (...args: Array<any>) => any\n}>\n\n/**\n * takes a list of requests (queue) and batches them into a single server request.\n * It will then resolve each individual requests promise with the appropriate data.\n * @private\n * @param {QueryBatcher} client - the client to use\n * @param {Queue} queue - the list of requests to batch\n */\nfunction dispatchQueueBatch(client: QueryBatcher, queue: Queue): void {\n let batchedQuery: any = queue.map((item) => item.request)\n\n if (batchedQuery.length === 1) {\n batchedQuery = batchedQuery[0]\n }\n\n client.fetcher(batchedQuery).then((responses: any) => {\n if (queue.length === 1 && !Array.isArray(responses)) {\n if (responses.errors && responses.errors.length) {\n queue[0].reject(\n new GenqlError(responses.errors, responses.data),\n )\n return\n }\n\n queue[0].resolve(responses)\n return\n } else if (responses.length !== queue.length) {\n throw new Error('response length did not match query length')\n }\n\n for (let i = 0; i < queue.length; i++) {\n if (responses[i].errors && responses[i].errors.length) {\n queue[i].reject(\n new GenqlError(responses[i].errors, responses[i].data),\n )\n } else {\n queue[i].resolve(responses[i])\n }\n }\n }).catch((error: any) => {\n // Reject every queued request if the batched fetch fails (e.g. network\n // error), otherwise callers hang forever and the rejection is unhandled.\n for (const item of queue) {\n item.reject(error)\n }\n })\n}\n\n/**\n * creates a list of requests to batch according to max batch size.\n * @private\n * @param {QueryBatcher} client - the client to create list of requests from from\n * @param {Options} options - the options for the batch\n */\nfunction dispatchQueue(client: QueryBatcher, options: Options): void {\n const queue = client._queue\n const maxBatchSize = options.maxBatchSize || 0\n client._queue = []\n\n if (maxBatchSize > 0 && maxBatchSize < queue.length) {\n for (let i = 0; i < queue.length / maxBatchSize; i++) {\n dispatchQueueBatch(\n client,\n queue.slice(i * maxBatchSize, (i + 1) * maxBatchSize),\n )\n }\n } else {\n dispatchQueueBatch(client, queue)\n }\n}\n/**\n * Create a batcher client.\n * @param {Fetcher} fetcher - A function that can handle the network requests to graphql endpoint\n * @param {Options} options - the options to be used by client\n * @param {boolean} options.shouldBatch - should the client batch requests. (default true)\n * @param {integer} options.batchInterval - duration (in MS) of each batch window. (default 6)\n * @param {integer} options.maxBatchSize - max number of requests in a batch. (default 0)\n * @param {boolean} options.defaultHeaders - default headers to include with every request\n *\n * @example\n * const fetcher = batchedQuery => fetch('path/to/graphql', {\n * method: 'post',\n * headers: {\n * Accept: 'application/json',\n * 'Content-Type': 'application/json',\n * },\n * body: JSON.stringify(batchedQuery),\n * credentials: 'include',\n * })\n * .then(response => response.json())\n *\n * const client = new QueryBatcher(fetcher, { maxBatchSize: 10 })\n */\n\nexport class QueryBatcher {\n fetcher: Fetcher\n _options: Options\n _queue: Queue\n\n constructor(\n fetcher: Fetcher,\n {\n batchInterval = 6,\n shouldBatch = true,\n maxBatchSize = 0,\n }: Options = {},\n ) {\n this.fetcher = fetcher\n this._options = {\n batchInterval,\n shouldBatch,\n maxBatchSize,\n }\n this._queue = []\n }\n\n /**\n * Fetch will send a graphql request and return the parsed json.\n * @param {string} query - the graphql query.\n * @param {Variables} variables - any variables you wish to inject as key/value pairs.\n * @param {[string]} operationName - the graphql operationName.\n * @param {Options} overrides - the client options overrides.\n *\n * @return {promise} resolves to parsed json of server response\n *\n * @example\n * client.fetch(`\n * query getHuman($id: ID!) {\n * human(id: $id) {\n * name\n * height\n * }\n * }\n * `, { id: \"1001\" }, 'getHuman')\n * .then(human => {\n * // do something with human\n * console.log(human);\n * });\n */\n fetch(\n query: string,\n variables?: Variables,\n operationName?: string,\n overrides: Options = {},\n ): Promise<Result> {\n const request: GraphqlOperation = {\n query,\n }\n const options = Object.assign({}, this._options, overrides)\n\n if (variables) {\n request.variables = variables\n }\n\n if (operationName) {\n request.operationName = operationName\n }\n\n const promise = new Promise<Result>((resolve, reject) => {\n this._queue.push({\n request,\n resolve,\n reject,\n })\n\n if (this._queue.length === 1) {\n if (options.shouldBatch) {\n setTimeout(\n () => dispatchQueue(this, options),\n options.batchInterval,\n )\n } else {\n dispatchQueue(this, options)\n }\n }\n })\n return promise\n }\n\n /**\n * Fetch will send a graphql request and return the parsed json.\n * @param {string} query - the graphql query.\n * @param {Variables} variables - any variables you wish to inject as key/value pairs.\n * @param {[string]} operationName - the graphql operationName.\n * @param {Options} overrides - the client options overrides.\n *\n * @return {Promise<Array<Result>>} resolves to parsed json of server response\n *\n * @example\n * client.forceFetch(`\n * query getHuman($id: ID!) {\n * human(id: $id) {\n * name\n * height\n * }\n * }\n * `, { id: \"1001\" }, 'getHuman')\n * .then(human => {\n * // do something with human\n * console.log(human);\n * });\n */\n forceFetch(\n query: string,\n variables?: Variables,\n operationName?: string,\n overrides: Options = {},\n ): Promise<Result> {\n const request: GraphqlOperation = {\n query,\n }\n const options = Object.assign({}, this._options, overrides, {\n shouldBatch: false,\n })\n\n if (variables) {\n request.variables = variables\n }\n\n if (operationName) {\n request.operationName = operationName\n }\n\n const promise = new Promise<Result>((resolve, reject) => {\n const client = new QueryBatcher(this.fetcher, this._options)\n client._queue = [\n {\n request,\n resolve,\n reject,\n },\n ]\n dispatchQueue(client, options)\n })\n return promise\n }\n}\n", qe = "\nimport { type BatchOptions, createFetcher } from './fetcher'\nimport type { ExecutionResult, LinkedType } from './types'\nimport {\n generateGraphqlOperation,\n type GraphqlOperation,\n} from './generateGraphqlOperation'\n\nexport type Headers =\n | HeadersInit\n | (() => HeadersInit)\n | (() => Promise<HeadersInit>)\n\nexport type BaseFetcher = (\n operation: GraphqlOperation | GraphqlOperation[],\n) => Promise<ExecutionResult | ExecutionResult[]>\n\nexport type ClientOptions = Omit<RequestInit, 'body' | 'headers'> & {\n url?: string\n batch?: BatchOptions | boolean\n fetcher?: BaseFetcher\n fetch?: Function\n headers?: Headers\n}\n\nexport const createClient = ({\n queryRoot,\n mutationRoot,\n subscriptionRoot,\n ...options\n}: ClientOptions & {\n queryRoot?: LinkedType\n mutationRoot?: LinkedType\n subscriptionRoot?: LinkedType\n}) => {\n const fetcher = createFetcher(options)\n const client: {\n query?: Function\n mutation?: Function\n } = {}\n\n if (queryRoot) {\n client.query = (request: any) => {\n if (!queryRoot) throw new Error('queryRoot argument is missing')\n\n const resultPromise = fetcher(\n generateGraphqlOperation('query', queryRoot, request),\n )\n\n return resultPromise\n }\n }\n if (mutationRoot) {\n client.mutation = (request: any) => {\n if (!mutationRoot)\n throw new Error('mutationRoot argument is missing')\n\n const resultPromise = fetcher(\n generateGraphqlOperation('mutation', mutationRoot, request),\n )\n\n return resultPromise\n }\n }\n\n return client as any\n}\n", Je = "export class GenqlError extends Error {\n errors: Array<GraphqlError> = []\n /**\n * Partial data returned by the server\n */\n data?: any\n constructor(errors: any[], data: any) {\n let message = Array.isArray(errors)\n ? errors.map((x) => x?.message || '').join('\\n')\n : ''\n if (!message) {\n message = 'GraphQL error'\n }\n super(message)\n this.errors = errors\n this.data = data\n }\n}\n\ninterface GraphqlError {\n message: string\n locations?: Array<{\n line: number\n column: number\n }>\n path?: string[]\n extensions?: Record<string, any>\n}\n", Ye = "import { QueryBatcher } from './batcher'\n\nimport type { ClientOptions } from './createClient'\nimport type { GraphqlOperation } from './generateGraphqlOperation'\nimport { GenqlError } from './error'\n\nexport interface Fetcher {\n (gql: GraphqlOperation): Promise<any>\n}\n\nexport type BatchOptions = {\n batchInterval?: number // ms\n maxBatchSize?: number\n}\n\nconst DEFAULT_BATCH_OPTIONS = {\n maxBatchSize: 10,\n batchInterval: 40,\n}\n\nexport const createFetcher = ({\n url,\n headers = {},\n fetcher,\n fetch: _fetch,\n batch = false,\n ...rest\n}: ClientOptions): Fetcher => {\n if (!url && !fetcher) {\n throw new Error('url or fetcher is required')\n }\n if (!fetcher) {\n fetcher = async (body) => {\n let headersObject =\n typeof headers == 'function' ? await headers() : headers\n headersObject = headersObject || {}\n if (typeof fetch === 'undefined' && !_fetch) {\n throw new Error(\n 'Global `fetch` function is not available, pass a fetch polyfill to Genql `createClient`',\n )\n }\n let fetchImpl = _fetch || fetch\n const res = await fetchImpl(url!, {\n headers: {\n 'Content-Type': 'application/json',\n ...headersObject,\n },\n method: 'POST',\n body: JSON.stringify(body),\n ...rest,\n })\n if (!res.ok) {\n throw new Error(`${res.statusText}: ${await res.text()}`)\n }\n const json = await res.json()\n return json\n }\n }\n\n if (!batch) {\n return async (body) => {\n const json = await fetcher!(body)\n if (Array.isArray(json)) {\n return json.map((json) => {\n if (json?.errors?.length) {\n throw new GenqlError(json.errors || [], json.data)\n }\n return json.data\n })\n } else {\n if (json?.errors?.length) {\n throw new GenqlError(json.errors || [], json.data)\n }\n return json.data\n }\n }\n }\n\n const batcher = new QueryBatcher(\n async (batchedQuery) => {\n // console.log(batchedQuery) // [{ query: 'query{user{age}}', variables: {} }, ...]\n const json = await fetcher!(batchedQuery)\n return json as any\n },\n batch === true ? DEFAULT_BATCH_OPTIONS : batch,\n )\n\n return async ({ query, variables }) => {\n const json = await batcher.fetch(query, variables)\n if (json?.data) {\n return json.data\n }\n throw new Error(\n 'Genql batch fetcher returned unexpected result ' + JSON.stringify(json),\n )\n }\n}\n", Xe = "import type { LinkedField, LinkedType } from './types'\n\nexport interface Args {\n [arg: string]: any | undefined\n}\n\nexport interface Fields {\n [field: string]: Request\n}\n\nexport type Request = boolean | number | Fields\n\nexport interface Variables {\n [name: string]: {\n value: any\n typing: [LinkedType, string]\n }\n}\n\nexport interface Context {\n root: LinkedType\n varCounter: number\n variables: Variables\n fragmentCounter: number\n fragments: string[]\n}\n\nexport interface GraphqlOperation {\n query: string\n variables?: { [name: string]: any }\n operationName?: string\n}\n\nconst parseRequest = (\n request: Request | undefined,\n ctx: Context,\n path: string[],\n): string => {\n if (typeof request === 'object' && '__args' in request) {\n const args: any = request.__args\n let fields: Request | undefined = { ...request }\n delete fields.__args\n const argNames = Object.keys(args)\n\n if (argNames.length === 0) {\n return parseRequest(fields, ctx, path)\n }\n\n const field = getFieldFromPath(ctx.root, path)\n\n const argStrings = argNames.map((argName) => {\n ctx.varCounter++\n const varName = `v${ctx.varCounter}`\n\n const typing = field.args && field.args[argName] // typeMap used here, .args\n\n if (!typing) {\n throw new Error(\n `no typing defined for argument \\`${argName}\\` in path \\`${path.join(\n '.',\n )}\\``,\n )\n }\n\n ctx.variables[varName] = {\n value: args[argName],\n typing,\n }\n\n return `${argName}:$${varName}`\n })\n return `(${argStrings})${parseRequest(fields, ctx, path)}`\n } else if (typeof request === 'object' && Object.keys(request).length > 0) {\n const fields = request\n const fieldNames = Object.keys(fields).filter((k) => Boolean(fields[k]))\n\n if (fieldNames.length === 0) {\n throw new Error(\n `field selection should not be empty: ${path.join('.')}`,\n )\n }\n\n const type =\n path.length > 0 ? getFieldFromPath(ctx.root, path).type : ctx.root\n const scalarFields = type.scalar\n\n let scalarFieldsFragment: string | undefined\n\n if (fieldNames.includes('__scalar')) {\n const falsyFieldNames = new Set(\n Object.keys(fields).filter((k) => !Boolean(fields[k])),\n )\n if (scalarFields?.length) {\n ctx.fragmentCounter++\n scalarFieldsFragment = `f${ctx.fragmentCounter}`\n\n ctx.fragments.push(\n `fragment ${scalarFieldsFragment} on ${\n type.name\n }{${scalarFields\n .filter((f) => !falsyFieldNames.has(f))\n .join(',')}}`,\n )\n }\n }\n\n const fieldsSelection = fieldNames\n .filter((f) => !['__scalar', '__name'].includes(f))\n .map((f) => {\n const parsed = parseRequest(fields[f], ctx, [...path, f])\n\n if (f.startsWith('on_')) {\n ctx.fragmentCounter++\n const implementationFragment = `f${ctx.fragmentCounter}`\n\n const typeMatch = f.match(/^on_(.+)/)\n\n if (!typeMatch || !typeMatch[1])\n throw new Error('match failed')\n\n ctx.fragments.push(\n `fragment ${implementationFragment} on ${typeMatch[1]}${parsed}`,\n )\n\n return `...${implementationFragment}`\n } else {\n return `${f}${parsed}`\n }\n })\n .concat(scalarFieldsFragment ? [`...${scalarFieldsFragment}`] : [])\n .join(',')\n\n return `{${fieldsSelection}}`\n } else {\n return ''\n }\n}\n\nexport const generateGraphqlOperation = (\n operation: 'query' | 'mutation' | 'subscription',\n root: LinkedType,\n fields?: Fields,\n): GraphqlOperation => {\n const ctx: Context = {\n root: root,\n varCounter: 0,\n variables: {},\n fragmentCounter: 0,\n fragments: [],\n }\n const result = parseRequest(fields, ctx, [])\n\n const varNames = Object.keys(ctx.variables)\n\n const varsString =\n varNames.length > 0\n ? `(${varNames.map((v) => {\n const variableType = ctx.variables[v].typing[1]\n return `$${v}:${variableType}`\n })})`\n : ''\n\n const operationName = fields?.__name || ''\n\n return {\n query: [\n `${operation} ${operationName}${varsString}${result}`,\n ...ctx.fragments,\n ].join(','),\n variables: Object.keys(ctx.variables).reduce<{ [name: string]: any }>(\n (r, v) => {\n r[v] = ctx.variables[v].value\n return r\n },\n {},\n ),\n ...(operationName ? { operationName: operationName.toString() } : {}),\n }\n}\n\nexport const getFieldFromPath = (\n root: LinkedType | undefined,\n path: string[],\n) => {\n let current: LinkedField | undefined\n\n if (!root) throw new Error('root type is not provided')\n\n if (path.length === 0) throw new Error(`path is empty`)\n\n path.forEach((f) => {\n const type = current ? current.type : root\n\n if (!type.fields)\n throw new Error(`type \\`${type.name}\\` does not have fields`)\n\n const possibleTypes = Object.keys(type.fields)\n .filter((i) => i.startsWith('on_'))\n .reduce(\n (types, fieldName) => {\n const field = type.fields && type.fields[fieldName]\n if (field) types.push(field.type)\n return types\n },\n [type],\n )\n\n let field: LinkedField | null = null\n\n possibleTypes.forEach((type) => {\n const found = type.fields && type.fields[f]\n if (found) field = found\n })\n\n if (!field)\n throw new Error(\n `type \\`${type.name}\\` does not have a field \\`${f}\\``,\n )\n\n current = field\n })\n\n return current as LinkedField\n}\n", Ze = "export { createClient } from './createClient'\nexport type { ClientOptions } from './createClient'\nexport type { FieldsSelection } from './typeSelection'\nexport { generateGraphqlOperation } from './generateGraphqlOperation'\nexport type { GraphqlOperation } from './generateGraphqlOperation'\nexport { linkTypeMap } from './linkTypeMap'\n// export { Observable } from 'zen-observable-ts'\nexport { createFetcher } from './fetcher'\nexport { GenqlError } from './error'\nexport const everything = {\n __scalar: true,\n}\n", Qe = "import type {\n CompressedType,\n CompressedTypeMap,\n LinkedArgMap,\n LinkedField,\n LinkedType,\n LinkedTypeMap,\n} from './types'\n\nexport interface PartialLinkedFieldMap {\n [field: string]: {\n type: string\n args?: LinkedArgMap\n }\n}\n\nexport const linkTypeMap = (\n typeMap: CompressedTypeMap<number>,\n): LinkedTypeMap => {\n const indexToName: Record<number, string> = Object.assign(\n {},\n ...Object.keys(typeMap.types).map((k, i) => ({ [i]: k })),\n )\n\n let intermediaryTypeMap = Object.assign(\n {},\n ...Object.keys(typeMap.types || {}).map(\n (k): Record<string, LinkedType> => {\n const type: CompressedType = typeMap.types[k]!\n const fields = type || {}\n return {\n [k]: {\n name: k,\n // type scalar properties\n scalar: Object.keys(fields).filter((f) => {\n const [type] = fields[f] || []\n return type && typeMap.scalars.includes(type)\n }),\n // fields with corresponding `type` and `args`\n fields: Object.assign(\n {},\n ...Object.keys(fields).map(\n (f): PartialLinkedFieldMap => {\n const [typeIndex, args] = fields[f] || []\n if (typeIndex == null) {\n return {}\n }\n return {\n [f]: {\n // replace index with type name\n type: indexToName[typeIndex],\n args: Object.assign(\n {},\n ...Object.keys(args || {}).map(\n (k) => {\n // if argTypeString == argTypeName, argTypeString is missing, need to readd it\n if (!args || !args[k]) {\n return\n }\n const [\n argTypeName,\n argTypeString,\n ] = args[k] as any\n return {\n [k]: [\n indexToName[\n argTypeName\n ],\n argTypeString ||\n indexToName[\n argTypeName\n ],\n ],\n }\n },\n ),\n ),\n },\n }\n },\n ),\n ),\n },\n }\n },\n ),\n )\n const res = resolveConcreteTypes(intermediaryTypeMap)\n return res\n}\n\n// replace typename with concrete type\nexport const resolveConcreteTypes = (linkedTypeMap: LinkedTypeMap) => {\n Object.keys(linkedTypeMap).forEach((typeNameFromKey) => {\n const type: LinkedType = linkedTypeMap[typeNameFromKey]!\n // type.name = typeNameFromKey\n if (!type.fields) {\n return\n }\n\n const fields = type.fields\n\n Object.keys(fields).forEach((f) => {\n const field: LinkedField = fields[f]!\n\n if (field.args) {\n const args = field.args\n Object.keys(args).forEach((key) => {\n const arg = args[key]\n\n if (arg) {\n const [typeName] = arg\n\n if (typeof typeName === 'string') {\n if (!linkedTypeMap[typeName]) {\n linkedTypeMap[typeName] = { name: typeName }\n }\n\n arg[0] = linkedTypeMap[typeName]!\n }\n }\n })\n }\n\n const typeName = field.type as LinkedType | string\n\n if (typeof typeName === 'string') {\n if (!linkedTypeMap[typeName]) {\n linkedTypeMap[typeName] = { name: typeName }\n }\n\n field.type = linkedTypeMap[typeName]!\n }\n })\n })\n\n return linkedTypeMap\n}\n", $e = "//////////////////////////////////////////////////\n\n// SOME THINGS TO KNOW BEFORE DIVING IN\n/*\n0. DST is the request type, SRC is the response type\n\n1. FieldsSelection uses an object because currently is impossible to make recursive types\n\n2. FieldsSelection is a recursive type that makes a type based on request type and fields\n\n3. HandleObject handles object types\n\n4. Handle__scalar adds all scalar properties excluding non scalar props\n*/\n\nexport type FieldsSelection<SRC extends Anify<DST> | undefined, DST> = {\n scalar: SRC\n union: Handle__isUnion<SRC, DST>\n object: HandleObject<SRC, DST>\n array: SRC extends Nil\n ? never\n : SRC extends (infer T)[]\n ? Array<FieldsSelection<T, DST>>\n : never\n __scalar: Handle__scalar<SRC, DST>\n never: never\n}[DST extends Nil\n ? 'never'\n : SRC extends Nil\n ? 'never'\n : DST extends false | 0\n ? 'never'\n : SRC extends Scalar\n ? 'scalar'\n : SRC extends any[]\n ? 'array'\n : SRC extends { __isUnion?: any }\n ? 'union'\n : DST extends { __scalar?: any }\n ? '__scalar'\n : DST extends {}\n ? 'object'\n : 'never']\n\ntype HandleObject<SRC extends Anify<DST>, DST> = SRC extends Nil\n ? never\n : Pick<\n {\n // using keyof SRC to maintain ?: relations of SRC type\n [Key in keyof SRC]: Key extends keyof DST\n ? FieldsSelection<\n NonNullable<SRC[Key]>,\n NonNullable<DST[Key]>\n >\n : SRC[Key]\n },\n Exclude<keyof DST, FieldsToRemove>\n // {\n // // remove falsy values\n // [Key in keyof DST]: DST[Key] extends false | 0 ? never : Key\n // }[keyof DST]\n >\n\ntype Handle__scalar<SRC extends Anify<DST>, DST> = SRC extends Nil\n ? never\n : Pick<\n // continue processing fields that are in DST, directly pass SRC type if not in DST\n {\n [Key in keyof SRC]: Key extends keyof DST\n ? FieldsSelection<SRC[Key], DST[Key]>\n : SRC[Key]\n },\n // remove fields that are not scalars or are not in DST\n {\n [Key in keyof SRC]: SRC[Key] extends Nil\n ? never\n : Key extends FieldsToRemove\n ? never\n : SRC[Key] extends Scalar\n ? Key\n : Key extends keyof DST\n ? Key\n : never\n }[keyof SRC]\n >\n\ntype Handle__isUnion<SRC extends Anify<DST>, DST> = SRC extends Nil\n ? never\n : Omit<SRC, FieldsToRemove> // just return the union type\n\ntype Scalar = string | number | Date | boolean | null | undefined\n\ntype Anify<T> = { [P in keyof T]?: any }\n\ntype FieldsToRemove = '__isUnion' | '__scalar' | '__name' | '__args'\n\ntype Nil = undefined | null\n", et = "\nexport interface ExecutionResult<TData = { [key: string]: any }> {\n errors?: Array<Error>\n data?: TData | null\n}\n\nexport interface ArgMap<keyType = number> {\n [arg: string]: [keyType, string] | [keyType] | undefined\n}\n\nexport type CompressedField<keyType = number> = [\n type: keyType,\n args?: ArgMap<keyType>,\n]\n\nexport interface CompressedFieldMap<keyType = number> {\n [field: string]: CompressedField<keyType> | undefined\n}\n\nexport type CompressedType<keyType = number> = CompressedFieldMap<keyType>\n\nexport interface CompressedTypeMap<keyType = number> {\n scalars: Array<keyType>\n types: {\n [type: string]: CompressedType<keyType> | undefined\n }\n}\n\n// normal types\nexport type Field<keyType = number> = {\n type: keyType\n args?: ArgMap<keyType>\n}\n\nexport interface FieldMap<keyType = number> {\n [field: string]: Field<keyType> | undefined\n}\n\nexport type Type<keyType = number> = FieldMap<keyType>\n\nexport interface TypeMap<keyType = number> {\n scalars: Array<keyType>\n types: {\n [type: string]: Type<keyType> | undefined\n }\n}\n\nexport interface LinkedArgMap {\n [arg: string]: [LinkedType, string] | undefined\n}\nexport interface LinkedField {\n type: LinkedType\n args?: LinkedArgMap\n}\n\nexport interface LinkedFieldMap {\n [field: string]: LinkedField | undefined\n}\n\nexport interface LinkedType {\n name: string\n fields?: LinkedFieldMap\n scalar?: string[]\n}\n\nexport interface LinkedTypeMap {\n [type: string]: LinkedType | undefined\n}\n", X = (e, t) => e === void 0 ? le(d(d(u(me(import.meta.url)), "runtime"), t), "utf-8") : e, tt = [
|
|
447
|
+
var We = "import type { GraphqlOperation } from './generateGraphqlOperation'\nimport { GenqlError } from './error'\n\ntype Variables = Record<string, any>\n\ntype QueryError = Error & {\n message: string\n\n locations?: Array<{\n line: number\n column: number\n }>\n path?: any\n rid: string\n details?: Record<string, any>\n}\ntype Result = {\n data: Record<string, any>\n errors: Array<QueryError>\n}\ntype Fetcher = (\n batchedQuery: GraphqlOperation | Array<GraphqlOperation>,\n) => Promise<Array<Result>>\ntype Options = {\n batchInterval?: number\n shouldBatch?: boolean\n maxBatchSize?: number\n}\ntype Queue = Array<{\n request: GraphqlOperation\n resolve: (...args: Array<any>) => any\n reject: (...args: Array<any>) => any\n}>\n\n/**\n * takes a list of requests (queue) and batches them into a single server request.\n * It will then resolve each individual requests promise with the appropriate data.\n * @private\n * @param {QueryBatcher} client - the client to use\n * @param {Queue} queue - the list of requests to batch\n */\nfunction dispatchQueueBatch(client: QueryBatcher, queue: Queue): void {\n let batchedQuery: any = queue.map((item) => item.request)\n\n if (batchedQuery.length === 1) {\n batchedQuery = batchedQuery[0]\n }\n\n client.fetcher(batchedQuery).then((responses: any) => {\n if (queue.length === 1 && !Array.isArray(responses)) {\n if (responses.errors && responses.errors.length) {\n queue[0].reject(\n new GenqlError(responses.errors, responses.data),\n )\n return\n }\n\n queue[0].resolve(responses)\n return\n } else if (responses.length !== queue.length) {\n throw new Error('response length did not match query length')\n }\n\n for (let i = 0; i < queue.length; i++) {\n if (responses[i].errors && responses[i].errors.length) {\n queue[i].reject(\n new GenqlError(responses[i].errors, responses[i].data),\n )\n } else {\n queue[i].resolve(responses[i])\n }\n }\n }).catch((error: any) => {\n // Reject every queued request if the batched fetch fails (e.g. network\n // error), otherwise callers hang forever and the rejection is unhandled.\n for (const item of queue) {\n item.reject(error)\n }\n })\n}\n\n/**\n * creates a list of requests to batch according to max batch size.\n * @private\n * @param {QueryBatcher} client - the client to create list of requests from from\n * @param {Options} options - the options for the batch\n */\nfunction dispatchQueue(client: QueryBatcher, options: Options): void {\n const queue = client._queue\n const maxBatchSize = options.maxBatchSize || 0\n client._queue = []\n\n if (maxBatchSize > 0 && maxBatchSize < queue.length) {\n for (let i = 0; i < queue.length / maxBatchSize; i++) {\n dispatchQueueBatch(\n client,\n queue.slice(i * maxBatchSize, (i + 1) * maxBatchSize),\n )\n }\n } else {\n dispatchQueueBatch(client, queue)\n }\n}\n/**\n * Create a batcher client.\n * @param {Fetcher} fetcher - A function that can handle the network requests to graphql endpoint\n * @param {Options} options - the options to be used by client\n * @param {boolean} options.shouldBatch - should the client batch requests. (default true)\n * @param {integer} options.batchInterval - duration (in MS) of each batch window. (default 6)\n * @param {integer} options.maxBatchSize - max number of requests in a batch. (default 0)\n * @param {boolean} options.defaultHeaders - default headers to include with every request\n *\n * @example\n * const fetcher = batchedQuery => fetch('path/to/graphql', {\n * method: 'post',\n * headers: {\n * Accept: 'application/json',\n * 'Content-Type': 'application/json',\n * },\n * body: JSON.stringify(batchedQuery),\n * credentials: 'include',\n * })\n * .then(response => response.json())\n *\n * const client = new QueryBatcher(fetcher, { maxBatchSize: 10 })\n */\n\nexport class QueryBatcher {\n fetcher: Fetcher\n _options: Options\n _queue: Queue\n\n constructor(\n fetcher: Fetcher,\n {\n batchInterval = 6,\n shouldBatch = true,\n maxBatchSize = 0,\n }: Options = {},\n ) {\n this.fetcher = fetcher\n this._options = {\n batchInterval,\n shouldBatch,\n maxBatchSize,\n }\n this._queue = []\n }\n\n /**\n * Fetch will send a graphql request and return the parsed json.\n * @param {string} query - the graphql query.\n * @param {Variables} variables - any variables you wish to inject as key/value pairs.\n * @param {[string]} operationName - the graphql operationName.\n * @param {Options} overrides - the client options overrides.\n *\n * @return {promise} resolves to parsed json of server response\n *\n * @example\n * client.fetch(`\n * query getHuman($id: ID!) {\n * human(id: $id) {\n * name\n * height\n * }\n * }\n * `, { id: \"1001\" }, 'getHuman')\n * .then(human => {\n * // do something with human\n * console.log(human);\n * });\n */\n fetch(\n query: string,\n variables?: Variables,\n operationName?: string,\n overrides: Options = {},\n ): Promise<Result> {\n const request: GraphqlOperation = {\n query,\n }\n const options = Object.assign({}, this._options, overrides)\n\n if (variables) {\n request.variables = variables\n }\n\n if (operationName) {\n request.operationName = operationName\n }\n\n const promise = new Promise<Result>((resolve, reject) => {\n this._queue.push({\n request,\n resolve,\n reject,\n })\n\n if (this._queue.length === 1) {\n if (options.shouldBatch) {\n setTimeout(\n () => dispatchQueue(this, options),\n options.batchInterval,\n )\n } else {\n dispatchQueue(this, options)\n }\n }\n })\n return promise\n }\n\n /**\n * Fetch will send a graphql request and return the parsed json.\n * @param {string} query - the graphql query.\n * @param {Variables} variables - any variables you wish to inject as key/value pairs.\n * @param {[string]} operationName - the graphql operationName.\n * @param {Options} overrides - the client options overrides.\n *\n * @return {Promise<Array<Result>>} resolves to parsed json of server response\n *\n * @example\n * client.forceFetch(`\n * query getHuman($id: ID!) {\n * human(id: $id) {\n * name\n * height\n * }\n * }\n * `, { id: \"1001\" }, 'getHuman')\n * .then(human => {\n * // do something with human\n * console.log(human);\n * });\n */\n forceFetch(\n query: string,\n variables?: Variables,\n operationName?: string,\n overrides: Options = {},\n ): Promise<Result> {\n const request: GraphqlOperation = {\n query,\n }\n const options = Object.assign({}, this._options, overrides, {\n shouldBatch: false,\n })\n\n if (variables) {\n request.variables = variables\n }\n\n if (operationName) {\n request.operationName = operationName\n }\n\n const promise = new Promise<Result>((resolve, reject) => {\n const client = new QueryBatcher(this.fetcher, this._options)\n client._queue = [\n {\n request,\n resolve,\n reject,\n },\n ]\n dispatchQueue(client, options)\n })\n return promise\n }\n}\n", Ge = "\nimport { type BatchOptions, createFetcher } from './fetcher'\nimport type { ExecutionResult, LinkedType } from './types'\nimport {\n generateGraphqlOperation,\n type GraphqlOperation,\n} from './generateGraphqlOperation'\n\nexport type Headers =\n | HeadersInit\n | (() => HeadersInit)\n | (() => Promise<HeadersInit>)\n\nexport type BaseFetcher = (\n operation: GraphqlOperation | GraphqlOperation[],\n) => Promise<ExecutionResult | ExecutionResult[]>\n\nexport type ClientOptions = Omit<RequestInit, 'body' | 'headers'> & {\n url?: string\n batch?: BatchOptions | boolean\n fetcher?: BaseFetcher\n fetch?: Function\n headers?: Headers\n}\n\nexport const createClient = ({\n queryRoot,\n mutationRoot,\n subscriptionRoot,\n ...options\n}: ClientOptions & {\n queryRoot?: LinkedType\n mutationRoot?: LinkedType\n subscriptionRoot?: LinkedType\n}) => {\n const fetcher = createFetcher(options)\n const client: {\n query?: Function\n mutation?: Function\n } = {}\n\n if (queryRoot) {\n client.query = (request: any) => {\n if (!queryRoot) throw new Error('queryRoot argument is missing')\n\n const resultPromise = fetcher(\n generateGraphqlOperation('query', queryRoot, request),\n )\n\n return resultPromise\n }\n }\n if (mutationRoot) {\n client.mutation = (request: any) => {\n if (!mutationRoot)\n throw new Error('mutationRoot argument is missing')\n\n const resultPromise = fetcher(\n generateGraphqlOperation('mutation', mutationRoot, request),\n )\n\n return resultPromise\n }\n }\n\n return client as any\n}\n", Ke = "export class GenqlError extends Error {\n errors: Array<GraphqlError> = []\n /**\n * Partial data returned by the server\n */\n data?: any\n constructor(errors: any[], data: any) {\n let message = Array.isArray(errors)\n ? errors.map((x) => x?.message || '').join('\\n')\n : ''\n if (!message) {\n message = 'GraphQL error'\n }\n super(message)\n this.errors = errors\n this.data = data\n }\n}\n\ninterface GraphqlError {\n message: string\n locations?: Array<{\n line: number\n column: number\n }>\n path?: string[]\n extensions?: Record<string, any>\n}\n", qe = "import { QueryBatcher } from './batcher'\n\nimport type { ClientOptions } from './createClient'\nimport type { GraphqlOperation } from './generateGraphqlOperation'\nimport { GenqlError } from './error'\n\nexport interface Fetcher {\n (gql: GraphqlOperation): Promise<any>\n}\n\nexport type BatchOptions = {\n batchInterval?: number // ms\n maxBatchSize?: number\n}\n\nconst DEFAULT_BATCH_OPTIONS = {\n maxBatchSize: 10,\n batchInterval: 40,\n}\n\nexport const createFetcher = ({\n url,\n headers = {},\n fetcher,\n fetch: _fetch,\n batch = false,\n ...rest\n}: ClientOptions): Fetcher => {\n if (!url && !fetcher) {\n throw new Error('url or fetcher is required')\n }\n if (!fetcher) {\n fetcher = async (body) => {\n let headersObject =\n typeof headers == 'function' ? await headers() : headers\n headersObject = headersObject || {}\n if (typeof fetch === 'undefined' && !_fetch) {\n throw new Error(\n 'Global `fetch` function is not available, pass a fetch polyfill to Genql `createClient`',\n )\n }\n let fetchImpl = _fetch || fetch\n const res = await fetchImpl(url!, {\n headers: {\n 'Content-Type': 'application/json',\n ...headersObject,\n },\n method: 'POST',\n body: JSON.stringify(body),\n ...rest,\n })\n if (!res.ok) {\n throw new Error(`${res.statusText}: ${await res.text()}`)\n }\n const json = await res.json()\n return json\n }\n }\n\n if (!batch) {\n return async (body) => {\n const json = await fetcher!(body)\n if (Array.isArray(json)) {\n return json.map((json) => {\n if (json?.errors?.length) {\n throw new GenqlError(json.errors || [], json.data)\n }\n return json.data\n })\n } else {\n if (json?.errors?.length) {\n throw new GenqlError(json.errors || [], json.data)\n }\n return json.data\n }\n }\n }\n\n const batcher = new QueryBatcher(\n async (batchedQuery) => {\n // console.log(batchedQuery) // [{ query: 'query{user{age}}', variables: {} }, ...]\n const json = await fetcher!(batchedQuery)\n return json as any\n },\n batch === true ? DEFAULT_BATCH_OPTIONS : batch,\n )\n\n return async ({ query, variables }) => {\n const json = await batcher.fetch(query, variables)\n if (json?.data) {\n return json.data\n }\n throw new Error(\n 'Genql batch fetcher returned unexpected result ' + JSON.stringify(json),\n )\n }\n}\n", Je = "import type { LinkedField, LinkedType } from './types'\n\nexport interface Args {\n [arg: string]: any | undefined\n}\n\nexport interface Fields {\n [field: string]: Request\n}\n\nexport type Request = boolean | number | Fields\n\nexport interface Variables {\n [name: string]: {\n value: any\n typing: [LinkedType, string]\n }\n}\n\nexport interface Context {\n root: LinkedType\n varCounter: number\n variables: Variables\n fragmentCounter: number\n fragments: string[]\n}\n\nexport interface GraphqlOperation {\n query: string\n variables?: { [name: string]: any }\n operationName?: string\n}\n\nconst parseRequest = (\n request: Request | undefined,\n ctx: Context,\n path: string[],\n): string => {\n if (typeof request === 'object' && '__args' in request) {\n const args: any = request.__args\n let fields: Request | undefined = { ...request }\n delete fields.__args\n const argNames = Object.keys(args)\n\n if (argNames.length === 0) {\n return parseRequest(fields, ctx, path)\n }\n\n const field = getFieldFromPath(ctx.root, path)\n\n const argStrings = argNames.map((argName) => {\n ctx.varCounter++\n const varName = `v${ctx.varCounter}`\n\n const typing = field.args && field.args[argName] // typeMap used here, .args\n\n if (!typing) {\n throw new Error(\n `no typing defined for argument \\`${argName}\\` in path \\`${path.join(\n '.',\n )}\\``,\n )\n }\n\n ctx.variables[varName] = {\n value: args[argName],\n typing,\n }\n\n return `${argName}:$${varName}`\n })\n return `(${argStrings})${parseRequest(fields, ctx, path)}`\n } else if (typeof request === 'object' && Object.keys(request).length > 0) {\n const fields = request\n const fieldNames = Object.keys(fields).filter((k) => Boolean(fields[k]))\n\n if (fieldNames.length === 0) {\n throw new Error(\n `field selection should not be empty: ${path.join('.')}`,\n )\n }\n\n const type =\n path.length > 0 ? getFieldFromPath(ctx.root, path).type : ctx.root\n const scalarFields = type.scalar\n\n let scalarFieldsFragment: string | undefined\n\n if (fieldNames.includes('__scalar')) {\n const falsyFieldNames = new Set(\n Object.keys(fields).filter((k) => !Boolean(fields[k])),\n )\n if (scalarFields?.length) {\n ctx.fragmentCounter++\n scalarFieldsFragment = `f${ctx.fragmentCounter}`\n\n ctx.fragments.push(\n `fragment ${scalarFieldsFragment} on ${\n type.name\n }{${scalarFields\n .filter((f) => !falsyFieldNames.has(f))\n .join(',')}}`,\n )\n }\n }\n\n const fieldsSelection = fieldNames\n .filter((f) => !['__scalar', '__name'].includes(f))\n .map((f) => {\n const parsed = parseRequest(fields[f], ctx, [...path, f])\n\n if (f.startsWith('on_')) {\n ctx.fragmentCounter++\n const implementationFragment = `f${ctx.fragmentCounter}`\n\n const typeMatch = f.match(/^on_(.+)/)\n\n if (!typeMatch || !typeMatch[1])\n throw new Error('match failed')\n\n ctx.fragments.push(\n `fragment ${implementationFragment} on ${typeMatch[1]}${parsed}`,\n )\n\n return `...${implementationFragment}`\n } else {\n return `${f}${parsed}`\n }\n })\n .concat(scalarFieldsFragment ? [`...${scalarFieldsFragment}`] : [])\n .join(',')\n\n return `{${fieldsSelection}}`\n } else {\n return ''\n }\n}\n\nexport const generateGraphqlOperation = (\n operation: 'query' | 'mutation' | 'subscription',\n root: LinkedType,\n fields?: Fields,\n): GraphqlOperation => {\n const ctx: Context = {\n root: root,\n varCounter: 0,\n variables: {},\n fragmentCounter: 0,\n fragments: [],\n }\n const result = parseRequest(fields, ctx, [])\n\n const varNames = Object.keys(ctx.variables)\n\n const varsString =\n varNames.length > 0\n ? `(${varNames.map((v) => {\n const variableType = ctx.variables[v].typing[1]\n return `$${v}:${variableType}`\n })})`\n : ''\n\n const operationName = fields?.__name || ''\n\n return {\n query: [\n `${operation} ${operationName}${varsString}${result}`,\n ...ctx.fragments,\n ].join(','),\n variables: Object.keys(ctx.variables).reduce<{ [name: string]: any }>(\n (r, v) => {\n r[v] = ctx.variables[v].value\n return r\n },\n {},\n ),\n ...(operationName ? { operationName: operationName.toString() } : {}),\n }\n}\n\nexport const getFieldFromPath = (\n root: LinkedType | undefined,\n path: string[],\n) => {\n let current: LinkedField | undefined\n\n if (!root) throw new Error('root type is not provided')\n\n if (path.length === 0) throw new Error(`path is empty`)\n\n path.forEach((f) => {\n const type = current ? current.type : root\n\n if (!type.fields)\n throw new Error(`type \\`${type.name}\\` does not have fields`)\n\n const possibleTypes = Object.keys(type.fields)\n .filter((i) => i.startsWith('on_'))\n .reduce(\n (types, fieldName) => {\n const field = type.fields && type.fields[fieldName]\n if (field) types.push(field.type)\n return types\n },\n [type],\n )\n\n let field: LinkedField | null = null\n\n possibleTypes.forEach((type) => {\n const found = type.fields && type.fields[f]\n if (found) field = found\n })\n\n if (!field)\n throw new Error(\n `type \\`${type.name}\\` does not have a field \\`${f}\\``,\n )\n\n current = field\n })\n\n return current as LinkedField\n}\n", Ye = "export { createClient } from './createClient'\nexport type { ClientOptions } from './createClient'\nexport type { FieldsSelection } from './typeSelection'\nexport { generateGraphqlOperation } from './generateGraphqlOperation'\nexport type { GraphqlOperation } from './generateGraphqlOperation'\nexport { linkTypeMap } from './linkTypeMap'\n// export { Observable } from 'zen-observable-ts'\nexport { createFetcher } from './fetcher'\nexport { GenqlError } from './error'\nexport const everything = {\n __scalar: true,\n}\n", Xe = "import type {\n CompressedType,\n CompressedTypeMap,\n LinkedArgMap,\n LinkedField,\n LinkedType,\n LinkedTypeMap,\n} from './types'\n\nexport interface PartialLinkedFieldMap {\n [field: string]: {\n type: string\n args?: LinkedArgMap\n }\n}\n\nexport const linkTypeMap = (\n typeMap: CompressedTypeMap<number>,\n): LinkedTypeMap => {\n const indexToName: Record<number, string> = Object.assign(\n {},\n ...Object.keys(typeMap.types).map((k, i) => ({ [i]: k })),\n )\n\n let intermediaryTypeMap = Object.assign(\n {},\n ...Object.keys(typeMap.types || {}).map(\n (k): Record<string, LinkedType> => {\n const type: CompressedType = typeMap.types[k]!\n const fields = type || {}\n return {\n [k]: {\n name: k,\n // type scalar properties\n scalar: Object.keys(fields).filter((f) => {\n const [type] = fields[f] || []\n return type && typeMap.scalars.includes(type)\n }),\n // fields with corresponding `type` and `args`\n fields: Object.assign(\n {},\n ...Object.keys(fields).map(\n (f): PartialLinkedFieldMap => {\n const [typeIndex, args] = fields[f] || []\n if (typeIndex == null) {\n return {}\n }\n return {\n [f]: {\n // replace index with type name\n type: indexToName[typeIndex],\n args: Object.assign(\n {},\n ...Object.keys(args || {}).map(\n (k) => {\n // if argTypeString == argTypeName, argTypeString is missing, need to readd it\n if (!args || !args[k]) {\n return\n }\n const [\n argTypeName,\n argTypeString,\n ] = args[k] as any\n return {\n [k]: [\n indexToName[\n argTypeName\n ],\n argTypeString ||\n indexToName[\n argTypeName\n ],\n ],\n }\n },\n ),\n ),\n },\n }\n },\n ),\n ),\n },\n }\n },\n ),\n )\n const res = resolveConcreteTypes(intermediaryTypeMap)\n return res\n}\n\n// replace typename with concrete type\nexport const resolveConcreteTypes = (linkedTypeMap: LinkedTypeMap) => {\n Object.keys(linkedTypeMap).forEach((typeNameFromKey) => {\n const type: LinkedType = linkedTypeMap[typeNameFromKey]!\n // type.name = typeNameFromKey\n if (!type.fields) {\n return\n }\n\n const fields = type.fields\n\n Object.keys(fields).forEach((f) => {\n const field: LinkedField = fields[f]!\n\n if (field.args) {\n const args = field.args\n Object.keys(args).forEach((key) => {\n const arg = args[key]\n\n if (arg) {\n const [typeName] = arg\n\n if (typeof typeName === 'string') {\n if (!linkedTypeMap[typeName]) {\n linkedTypeMap[typeName] = { name: typeName }\n }\n\n arg[0] = linkedTypeMap[typeName]!\n }\n }\n })\n }\n\n const typeName = field.type as LinkedType | string\n\n if (typeof typeName === 'string') {\n if (!linkedTypeMap[typeName]) {\n linkedTypeMap[typeName] = { name: typeName }\n }\n\n field.type = linkedTypeMap[typeName]!\n }\n })\n })\n\n return linkedTypeMap\n}\n", Ze = "//////////////////////////////////////////////////\n\n// SOME THINGS TO KNOW BEFORE DIVING IN\n/*\n0. DST is the request type, SRC is the response type\n\n1. FieldsSelection uses an object because currently is impossible to make recursive types\n\n2. FieldsSelection is a recursive type that makes a type based on request type and fields\n\n3. HandleObject handles object types\n\n4. Handle__scalar adds all scalar properties excluding non scalar props\n*/\n\nexport type FieldsSelection<SRC extends Anify<DST> | undefined, DST> = {\n scalar: SRC\n union: Handle__isUnion<SRC, DST>\n object: HandleObject<SRC, DST>\n array: SRC extends Nil\n ? never\n : SRC extends (infer T)[]\n ? Array<FieldsSelection<T, DST>>\n : never\n __scalar: Handle__scalar<SRC, DST>\n never: never\n}[DST extends Nil\n ? 'never'\n : SRC extends Nil\n ? 'never'\n : DST extends false | 0\n ? 'never'\n : SRC extends Scalar\n ? 'scalar'\n : SRC extends any[]\n ? 'array'\n : SRC extends { __isUnion?: any }\n ? 'union'\n : DST extends { __scalar?: any }\n ? '__scalar'\n : DST extends {}\n ? 'object'\n : 'never']\n\ntype HandleObject<SRC extends Anify<DST>, DST> = SRC extends Nil\n ? never\n : Pick<\n {\n // using keyof SRC to maintain ?: relations of SRC type\n [Key in keyof SRC]: Key extends keyof DST\n ? FieldsSelection<\n NonNullable<SRC[Key]>,\n NonNullable<DST[Key]>\n >\n : SRC[Key]\n },\n Exclude<keyof DST, FieldsToRemove>\n // {\n // // remove falsy values\n // [Key in keyof DST]: DST[Key] extends false | 0 ? never : Key\n // }[keyof DST]\n >\n\ntype Handle__scalar<SRC extends Anify<DST>, DST> = SRC extends Nil\n ? never\n : Pick<\n // continue processing fields that are in DST, directly pass SRC type if not in DST\n {\n [Key in keyof SRC]: Key extends keyof DST\n ? FieldsSelection<SRC[Key], DST[Key]>\n : SRC[Key]\n },\n // remove fields that are not scalars or are not in DST\n {\n [Key in keyof SRC]: SRC[Key] extends Nil\n ? never\n : Key extends FieldsToRemove\n ? never\n : SRC[Key] extends Scalar\n ? Key\n : Key extends keyof DST\n ? Key\n : never\n }[keyof SRC]\n >\n\ntype Handle__isUnion<SRC extends Anify<DST>, DST> = SRC extends Nil\n ? never\n : Omit<SRC, FieldsToRemove> // just return the union type\n\ntype Scalar = string | number | Date | boolean | null | undefined\n\ntype Anify<T> = { [P in keyof T]?: any }\n\ntype FieldsToRemove = '__isUnion' | '__scalar' | '__name' | '__args'\n\ntype Nil = undefined | null\n", Qe = "\nexport interface ExecutionResult<TData = { [key: string]: any }> {\n errors?: Array<Error>\n data?: TData | null\n}\n\nexport interface ArgMap<keyType = number> {\n [arg: string]: [keyType, string] | [keyType] | undefined\n}\n\nexport type CompressedField<keyType = number> = [\n type: keyType,\n args?: ArgMap<keyType>,\n]\n\nexport interface CompressedFieldMap<keyType = number> {\n [field: string]: CompressedField<keyType> | undefined\n}\n\nexport type CompressedType<keyType = number> = CompressedFieldMap<keyType>\n\nexport interface CompressedTypeMap<keyType = number> {\n scalars: Array<keyType>\n types: {\n [type: string]: CompressedType<keyType> | undefined\n }\n}\n\n// normal types\nexport type Field<keyType = number> = {\n type: keyType\n args?: ArgMap<keyType>\n}\n\nexport interface FieldMap<keyType = number> {\n [field: string]: Field<keyType> | undefined\n}\n\nexport type Type<keyType = number> = FieldMap<keyType>\n\nexport interface TypeMap<keyType = number> {\n scalars: Array<keyType>\n types: {\n [type: string]: Type<keyType> | undefined\n }\n}\n\nexport interface LinkedArgMap {\n [arg: string]: [LinkedType, string] | undefined\n}\nexport interface LinkedField {\n type: LinkedType\n args?: LinkedArgMap\n}\n\nexport interface LinkedFieldMap {\n [field: string]: LinkedField | undefined\n}\n\nexport interface LinkedType {\n name: string\n fields?: LinkedFieldMap\n scalar?: string[]\n}\n\nexport interface LinkedTypeMap {\n [type: string]: LinkedType | undefined\n}\n", X = (e, t) => e === void 0 ? le(u(u(l(me(import.meta.url)), "runtime"), t), "utf-8") : e, $e = [
|
|
451
448
|
{
|
|
452
449
|
name: "batcher.ts",
|
|
453
|
-
content: X(
|
|
450
|
+
content: X(We, "batcher.ts")
|
|
454
451
|
},
|
|
455
452
|
{
|
|
456
453
|
name: "createClient.ts",
|
|
457
|
-
content: X(
|
|
454
|
+
content: X(Ge, "createClient.ts")
|
|
458
455
|
},
|
|
459
456
|
{
|
|
460
457
|
name: "error.ts",
|
|
461
|
-
content: X(
|
|
458
|
+
content: X(Ke, "error.ts")
|
|
462
459
|
},
|
|
463
460
|
{
|
|
464
461
|
name: "fetcher.ts",
|
|
465
|
-
content: X(
|
|
462
|
+
content: X(qe, "fetcher.ts")
|
|
466
463
|
},
|
|
467
464
|
{
|
|
468
465
|
name: "generateGraphqlOperation.ts",
|
|
469
|
-
content: X(
|
|
466
|
+
content: X(Je, "generateGraphqlOperation.ts")
|
|
470
467
|
},
|
|
471
468
|
{
|
|
472
469
|
name: "index.ts",
|
|
473
|
-
content: X(
|
|
470
|
+
content: X(Ye, "index.ts")
|
|
474
471
|
},
|
|
475
472
|
{
|
|
476
473
|
name: "linkTypeMap.ts",
|
|
477
|
-
content: X(
|
|
474
|
+
content: X(Xe, "linkTypeMap.ts")
|
|
478
475
|
},
|
|
479
476
|
{
|
|
480
477
|
name: "typeSelection.ts",
|
|
481
|
-
content: X(
|
|
478
|
+
content: X(Ze, "typeSelection.ts")
|
|
482
479
|
},
|
|
483
480
|
{
|
|
484
481
|
name: "types.ts",
|
|
485
|
-
content: X(
|
|
482
|
+
content: X(Qe, "types.ts")
|
|
486
483
|
}
|
|
487
|
-
],
|
|
484
|
+
], et = "schema.ts", tt = "schema.graphql", nt = "types.ts", rt = "index.ts", it = async (e, t) => {
|
|
488
485
|
if (!e.output) throw Error("`output` must be defined in the config");
|
|
489
486
|
let n = e.output;
|
|
490
|
-
await
|
|
487
|
+
await j([n], !0);
|
|
491
488
|
let r = new L(t, e);
|
|
492
|
-
|
|
493
|
-
for (let { name: e, content: t } of
|
|
489
|
+
ze(t, r), await M([n, tt], await r.toCode("graphql")), await j([n, "runtime"]);
|
|
490
|
+
for (let { name: e, content: t } of $e) await M([
|
|
494
491
|
n,
|
|
495
492
|
"runtime",
|
|
496
493
|
e
|
|
497
494
|
], "// @ts-nocheck\n" + t);
|
|
498
495
|
let i = new L(t, e);
|
|
499
|
-
|
|
496
|
+
Le(t, i), ke(t, i), Be(t, i), at(t, i), await M([n, et], "// @ts-nocheck\n" + await i.toCode("typescript"));
|
|
500
497
|
let a = new L(t, e);
|
|
501
|
-
|
|
498
|
+
He(t, a), await M([n, nt], `export default ${await a.toCode()}`);
|
|
502
499
|
let o = new L(t, e);
|
|
503
|
-
|
|
500
|
+
ye(t, o), await M([n, rt], "// @ts-nocheck\n" + await o.toCode("typescript", !0));
|
|
504
501
|
};
|
|
505
|
-
function
|
|
502
|
+
function at(e, t) {
|
|
506
503
|
let n = e.getTypeMap(), r = [];
|
|
507
504
|
for (let e in n) {
|
|
508
505
|
if (I.includes(e)) continue;
|
|
509
506
|
let t = n[e];
|
|
510
|
-
|
|
507
|
+
h(t) && r.push(t);
|
|
511
508
|
}
|
|
512
509
|
r.length !== 0 && t.addCodeBlock(r.map((e) => `export const ${ce("enum" + e.name)} = {\n` + e.getValues().map((e) => e?.name ? ` ${e.name}: '${e.name}' as const` : "").join(",\n") + "\n}\n").join("\n"));
|
|
513
510
|
}
|
|
514
511
|
//#endregion
|
|
515
512
|
//#region src/generate/genql/tasks/schemaTask.ts
|
|
516
|
-
var
|
|
513
|
+
var ot = async (e) => {
|
|
517
514
|
if (!e.schema) throw Error("`schema` must be defined in the config");
|
|
518
515
|
let t = ne(e.schema, { assumeValidSDL: !0 }), n = e.sortProperties ? oe(t) : t;
|
|
519
516
|
return n.getQueryType() && te(n), n;
|
|
520
517
|
}, Z = async (e) => {
|
|
521
518
|
if (!e.output) throw Error("`output` must be defined in the config");
|
|
522
|
-
await
|
|
523
|
-
},
|
|
519
|
+
await it(e, await ot(e));
|
|
520
|
+
}, st = {
|
|
524
521
|
DateTime: "string",
|
|
525
522
|
JSON: "Record<string, unknown>",
|
|
526
523
|
UUID: "string"
|
|
527
|
-
}, Q = "core/generated", $ = async ({ schema:
|
|
528
|
-
let a = i ?? "// Ambient type stubs for the genql-generated code this template gets\n// injected into. They enable full typecheck/lint on this file.\n// __STRIPPED_DURING_INJECTION_START__\ntype QueryGenqlSelection = Record<string, unknown>;\ntype MutationGenqlSelection = Record<string, unknown>;\ntype GraphqlOperation = Record<string, unknown>;\n\ntype ClientOptions = {\n url?: string;\n headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);\n fetcher?: (\n operation: GraphqlOperation | GraphqlOperation[],\n ) => Promise<unknown>;\n fetch?: typeof globalThis.fetch;\n batch?: unknown;\n};\n\ntype Client = {\n query: (\n request: QueryGenqlSelection & { __name?: string },\n ) => Promise<unknown>;\n mutation: (\n request: MutationGenqlSelection & { __name?: string },\n ) => Promise<unknown>;\n};\n\ndeclare function createClient(options: ClientOptions): Client;\n\ndeclare class GenqlError extends Error {\n constructor(errors: unknown, data: unknown);\n}\n// __STRIPPED_DURING_INJECTION_END__\n\nconst APP_ACCESS_TOKEN_ENV_KEY = 'TWENTY_APP_ACCESS_TOKEN';\nconst API_KEY_ENV_KEY = 'TWENTY_API_KEY';\n\ntype TwentyGeneratedClientOptions = ClientOptions;\n\ntype ProcessEnvironment = Record<string, string | undefined>;\n\ntype GraphqlErrorPayloadEntry = {\n message?: string;\n extensions?: { code?: string };\n};\n\ntype GraphqlResponsePayload = {\n data?: Record<string, unknown>;\n errors?: GraphqlErrorPayloadEntry[];\n};\n\ntype GraphqlResponse = {\n status: number;\n statusText: string;\n payload: GraphqlResponsePayload | null;\n rawBody: string;\n};\n\nconst getProcessEnvironment = (): ProcessEnvironment => {\n const processObject = (\n globalThis as { process?: { env?: ProcessEnvironment } }\n ).process;\n\n return processObject?.env ?? {};\n};\n\nconst getTokenFromAuthorizationHeader = (\n authorizationHeader: string | undefined,\n): string | null => {\n if (typeof authorizationHeader !== 'string') {\n return null;\n }\n\n const trimmedAuthorizationHeader = authorizationHeader.trim();\n\n if (trimmedAuthorizationHeader.length === 0) {\n return null;\n }\n\n if (trimmedAuthorizationHeader === 'Bearer') {\n return null;\n }\n\n if (trimmedAuthorizationHeader.startsWith('Bearer ')) {\n return trimmedAuthorizationHeader.slice('Bearer '.length).trim();\n }\n\n return trimmedAuthorizationHeader;\n};\n\nconst getTokenFromHeaders = (\n headers: HeadersInit | undefined,\n): string | null => {\n if (!headers) {\n return null;\n }\n\n if (headers instanceof Headers) {\n return getTokenFromAuthorizationHeader(\n headers.get('Authorization') ?? undefined,\n );\n }\n\n if (Array.isArray(headers)) {\n const matchedAuthorizationHeader = headers.find(\n ([headerName]) => headerName.toLowerCase() === 'authorization',\n );\n\n return getTokenFromAuthorizationHeader(matchedAuthorizationHeader?.[1]);\n }\n\n const headersRecord = headers as Record<string, string | undefined>;\n\n return getTokenFromAuthorizationHeader(\n headersRecord.Authorization ?? headersRecord.authorization,\n );\n};\n\nconst hasAuthenticationErrorInGraphqlPayload = (\n payload: GraphqlResponsePayload | null,\n): boolean => {\n if (!payload?.errors) {\n return false;\n }\n\n return payload.errors.some((graphqlError) => {\n return (\n graphqlError.extensions?.code === 'UNAUTHENTICATED' ||\n graphqlError.message?.toLowerCase() === 'unauthorized'\n );\n });\n};\n\nconst defaultOptions: TwentyGeneratedClientOptions = {\n url: '__TWENTY_DEFAULT_URL__',\n headers: {\n 'Content-Type': 'application/json',\n },\n};\n\nexport class TwentyGeneratedClient {\n private client: Client;\n private url: string;\n private requestOptions: RequestInit;\n private headers: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);\n private fetchImplementation: typeof globalThis.fetch | null;\n private authorizationToken: string | null;\n private refreshAccessTokenPromise: Promise<string | null> | null = null;\n\n constructor(options?: TwentyGeneratedClientOptions) {\n const merged: TwentyGeneratedClientOptions = {\n ...defaultOptions,\n ...options,\n };\n\n const {\n url,\n headers,\n fetch: customFetchImplementation,\n fetcher: _fetcher,\n batch: _batch,\n ...requestOptions\n } = merged;\n\n this.url = url ?? '';\n this.requestOptions = requestOptions;\n this.headers = headers ?? {};\n this.fetchImplementation =\n customFetchImplementation ?? globalThis.fetch ?? null;\n\n const processEnvironment = getProcessEnvironment();\n const tokenFromHeaders = getTokenFromHeaders(\n typeof headers === 'function' ? undefined : headers,\n );\n\n // Priority: explicit header > app access token > api key (legacy).\n this.authorizationToken =\n tokenFromHeaders ??\n processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] ??\n processEnvironment[API_KEY_ENV_KEY] ??\n null;\n\n this.client = createClient({\n ...merged,\n headers: undefined,\n fetcher: async (operation) =>\n this.executeGraphqlRequestWithOptionalRefresh({\n operation,\n }),\n });\n }\n\n query<R extends QueryGenqlSelection>(request: R & { __name?: string }) {\n return this.client.query(request);\n }\n\n mutation<R extends MutationGenqlSelection>(request: R & { __name?: string }) {\n return this.client.mutation(request);\n }\n\n // __UPLOAD_FILE_START__\n async uploadFile(\n fileBuffer: Buffer,\n filename: string,\n contentType: string = 'application/octet-stream',\n fieldMetadataUniversalIdentifier: string,\n ): Promise<{\n id: string;\n path: string;\n size: number;\n createdAt: string;\n url: string;\n }> {\n const form = new FormData();\n\n form.append(\n 'operations',\n JSON.stringify({\n query: `mutation UploadFilesFieldFileByUniversalIdentifier($file: Upload!, $fieldMetadataUniversalIdentifier: String!) {\n uploadFilesFieldFileByUniversalIdentifier(file: $file, fieldMetadataUniversalIdentifier: $fieldMetadataUniversalIdentifier) { id path size createdAt url }\n }`,\n variables: {\n file: null,\n fieldMetadataUniversalIdentifier,\n },\n }),\n );\n form.append('map', JSON.stringify({ '0': ['variables.file'] }));\n form.append(\n '0',\n new Blob([fileBuffer as BlobPart], { type: contentType }),\n filename,\n );\n\n const result = await this.executeGraphqlRequestWithOptionalRefresh({\n operation: form,\n headers: {},\n requestInit: {\n method: 'POST',\n },\n });\n\n if (result.errors) {\n throw new GenqlError(result.errors, result.data);\n }\n\n const data = result.data as Record<string, unknown>;\n\n return data.uploadFilesFieldFileByUniversalIdentifier as {\n id: string;\n path: string;\n size: number;\n createdAt: string;\n url: string;\n };\n }\n // __UPLOAD_FILE_END__\n\n private async executeGraphqlRequestWithOptionalRefresh({\n operation,\n headers,\n requestInit,\n }: {\n operation: GraphqlOperation | GraphqlOperation[] | FormData;\n headers?: HeadersInit;\n requestInit?: RequestInit;\n }) {\n const firstResponse = await this.executeGraphqlRequest({\n operation,\n headers,\n requestInit,\n token: this.authorizationToken,\n });\n\n if (this.shouldRefreshToken(firstResponse)) {\n const refreshedAccessToken = await this.requestRefreshedAccessToken();\n\n if (refreshedAccessToken) {\n const retryResponse = await this.executeGraphqlRequest({\n operation,\n headers,\n requestInit,\n token: refreshedAccessToken,\n });\n\n return this.assertResponseIsSuccessful(retryResponse);\n }\n }\n\n return this.assertResponseIsSuccessful(firstResponse);\n }\n\n private async executeGraphqlRequest({\n operation,\n headers,\n requestInit,\n token,\n }: {\n operation: GraphqlOperation | GraphqlOperation[] | FormData;\n headers?: HeadersInit;\n requestInit?: RequestInit;\n token: string | null;\n }): Promise<GraphqlResponse> {\n if (!this.fetchImplementation) {\n throw new Error(\n 'Global `fetch` function is not available, ' +\n 'pass a fetch implementation to the Twenty client',\n );\n }\n\n const resolvedHeaders = await this.resolveHeaders();\n const requestHeaders = new Headers(resolvedHeaders);\n\n if (headers) {\n new Headers(headers).forEach((value, key) =>\n requestHeaders.set(key, value),\n );\n }\n\n if (operation instanceof FormData) {\n requestHeaders.delete('Content-Type');\n } else {\n requestHeaders.set('Content-Type', 'application/json');\n }\n\n if (token) {\n requestHeaders.set('Authorization', `Bearer ${token}`);\n } else {\n requestHeaders.delete('Authorization');\n }\n\n const response = await this.fetchImplementation.call(globalThis, this.url, {\n ...this.requestOptions,\n ...requestInit,\n method: requestInit?.method ?? 'POST',\n headers: requestHeaders,\n body:\n operation instanceof FormData ? operation : JSON.stringify(operation),\n });\n\n const rawBody = await response.text();\n let payload: GraphqlResponsePayload | null = null;\n\n if (rawBody.trim().length > 0) {\n try {\n payload = JSON.parse(rawBody) as GraphqlResponsePayload;\n } catch {\n payload = null;\n }\n }\n\n return {\n status: response.status,\n statusText: response.statusText,\n payload,\n rawBody,\n };\n }\n\n private async resolveHeaders(): Promise<HeadersInit> {\n if (typeof this.headers === 'function') {\n return (await this.headers()) ?? {};\n }\n\n return this.headers ?? {};\n }\n\n private shouldRefreshToken(response: GraphqlResponse): boolean {\n if (response.status === 401) {\n return true;\n }\n\n return hasAuthenticationErrorInGraphqlPayload(response.payload);\n }\n\n private assertResponseIsSuccessful(response: GraphqlResponse) {\n if (response.status < 200 || response.status >= 300) {\n throw new Error(`${response.statusText}: ${response.rawBody}`);\n }\n\n if (response.payload === null) {\n throw new Error('Invalid JSON response');\n }\n\n return response.payload;\n }\n\n private async requestRefreshedAccessToken(): Promise<string | null> {\n const refreshAccessTokenFunction = (\n globalThis as {\n frontComponentHostCommunicationApi?: {\n requestAccessTokenRefresh?: () => Promise<string>;\n };\n }\n ).frontComponentHostCommunicationApi?.requestAccessTokenRefresh;\n\n if (typeof refreshAccessTokenFunction !== 'function') {\n return null;\n }\n\n if (!this.refreshAccessTokenPromise) {\n this.refreshAccessTokenPromise = refreshAccessTokenFunction()\n .then((refreshedAccessToken) => {\n if (\n typeof refreshedAccessToken !== 'string' ||\n refreshedAccessToken.length === 0\n ) {\n return null;\n }\n\n this.setAuthorizationToken(refreshedAccessToken);\n\n return refreshedAccessToken;\n })\n .catch((refreshError: unknown) => {\n console.error('Twenty client: token refresh failed', refreshError);\n\n return null;\n })\n .finally(() => {\n this.refreshAccessTokenPromise = null;\n });\n }\n\n return this.refreshAccessTokenPromise;\n }\n\n private setAuthorizationToken(token: string) {\n this.authorizationToken = token;\n\n const processEnvironment = getProcessEnvironment();\n\n processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] = token;\n }\n}\n", o = `${t}.tmp`;
|
|
529
|
-
await
|
|
524
|
+
}, Q = "core/generated", $ = async ({ schema: n, outputPath: r, clientWrapperTemplateSource: i }) => {
|
|
525
|
+
let a = i ?? "// Ambient type stubs for the genql-generated code this template gets\n// injected into. They enable full typecheck/lint on this file.\n// __STRIPPED_DURING_INJECTION_START__\ntype QueryGenqlSelection = Record<string, unknown>;\ntype MutationGenqlSelection = Record<string, unknown>;\ntype GraphqlOperation = Record<string, unknown>;\n\ntype ClientOptions = {\n url?: string;\n headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);\n fetcher?: (\n operation: GraphqlOperation | GraphqlOperation[],\n ) => Promise<unknown>;\n fetch?: typeof globalThis.fetch;\n batch?: unknown;\n};\n\ntype Client = {\n query: (\n request: QueryGenqlSelection & { __name?: string },\n ) => Promise<unknown>;\n mutation: (\n request: MutationGenqlSelection & { __name?: string },\n ) => Promise<unknown>;\n};\n\ndeclare function createClient(options: ClientOptions): Client;\n\ndeclare class GenqlError extends Error {\n constructor(errors: unknown, data: unknown);\n}\n// __STRIPPED_DURING_INJECTION_END__\n\nconst APP_ACCESS_TOKEN_ENV_KEY = 'TWENTY_APP_ACCESS_TOKEN';\nconst API_KEY_ENV_KEY = 'TWENTY_API_KEY';\n\ntype TwentyGeneratedClientOptions = ClientOptions;\n\ntype ProcessEnvironment = Record<string, string | undefined>;\n\ntype GraphqlErrorPayloadEntry = {\n message?: string;\n extensions?: { code?: string };\n};\n\ntype GraphqlResponsePayload = {\n data?: Record<string, unknown>;\n errors?: GraphqlErrorPayloadEntry[];\n};\n\ntype GraphqlResponse = {\n status: number;\n statusText: string;\n payload: GraphqlResponsePayload | null;\n rawBody: string;\n};\n\nconst getProcessEnvironment = (): ProcessEnvironment => {\n const processObject = (\n globalThis as { process?: { env?: ProcessEnvironment } }\n ).process;\n\n return processObject?.env ?? {};\n};\n\nconst getTokenFromAuthorizationHeader = (\n authorizationHeader: string | undefined,\n): string | null => {\n if (typeof authorizationHeader !== 'string') {\n return null;\n }\n\n const trimmedAuthorizationHeader = authorizationHeader.trim();\n\n if (trimmedAuthorizationHeader.length === 0) {\n return null;\n }\n\n if (trimmedAuthorizationHeader === 'Bearer') {\n return null;\n }\n\n if (trimmedAuthorizationHeader.startsWith('Bearer ')) {\n return trimmedAuthorizationHeader.slice('Bearer '.length).trim();\n }\n\n return trimmedAuthorizationHeader;\n};\n\nconst getTokenFromHeaders = (\n headers: HeadersInit | undefined,\n): string | null => {\n if (!headers) {\n return null;\n }\n\n if (headers instanceof Headers) {\n return getTokenFromAuthorizationHeader(\n headers.get('Authorization') ?? undefined,\n );\n }\n\n if (Array.isArray(headers)) {\n const matchedAuthorizationHeader = headers.find(\n ([headerName]) => headerName.toLowerCase() === 'authorization',\n );\n\n return getTokenFromAuthorizationHeader(matchedAuthorizationHeader?.[1]);\n }\n\n const headersRecord = headers as Record<string, string | undefined>;\n\n return getTokenFromAuthorizationHeader(\n headersRecord.Authorization ?? headersRecord.authorization,\n );\n};\n\nconst hasAuthenticationErrorInGraphqlPayload = (\n payload: GraphqlResponsePayload | null,\n): boolean => {\n if (!payload?.errors) {\n return false;\n }\n\n return payload.errors.some((graphqlError) => {\n return (\n graphqlError.extensions?.code === 'UNAUTHENTICATED' ||\n graphqlError.message?.toLowerCase() === 'unauthorized'\n );\n });\n};\n\nconst defaultOptions: TwentyGeneratedClientOptions = {\n url: '__TWENTY_DEFAULT_URL__',\n headers: {\n 'Content-Type': 'application/json',\n },\n};\n\nexport class TwentyGeneratedClient {\n private client: Client;\n private url: string;\n private requestOptions: RequestInit;\n private headers: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);\n private fetchImplementation: typeof globalThis.fetch | null;\n private authorizationToken: string | null;\n private refreshAccessTokenPromise: Promise<string | null> | null = null;\n\n constructor(options?: TwentyGeneratedClientOptions) {\n const merged: TwentyGeneratedClientOptions = {\n ...defaultOptions,\n ...options,\n };\n\n const {\n url,\n headers,\n fetch: customFetchImplementation,\n fetcher: _fetcher,\n batch: _batch,\n ...requestOptions\n } = merged;\n\n this.url = url ?? '';\n this.requestOptions = requestOptions;\n this.headers = headers ?? {};\n this.fetchImplementation =\n customFetchImplementation ?? globalThis.fetch ?? null;\n\n const processEnvironment = getProcessEnvironment();\n const tokenFromHeaders = getTokenFromHeaders(\n typeof headers === 'function' ? undefined : headers,\n );\n\n // Priority: explicit header > app access token > api key (legacy).\n this.authorizationToken =\n tokenFromHeaders ??\n processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] ??\n processEnvironment[API_KEY_ENV_KEY] ??\n null;\n\n this.client = createClient({\n ...merged,\n headers: undefined,\n fetcher: async (operation) =>\n this.executeGraphqlRequestWithOptionalRefresh({\n operation,\n }),\n });\n }\n\n query<R extends QueryGenqlSelection>(request: R & { __name?: string }) {\n return this.client.query(request);\n }\n\n mutation<R extends MutationGenqlSelection>(request: R & { __name?: string }) {\n return this.client.mutation(request);\n }\n\n // __UPLOAD_FILE_START__\n async uploadFile(\n fileBuffer: Buffer,\n filename: string,\n contentType: string = 'application/octet-stream',\n fieldMetadataUniversalIdentifier: string,\n ): Promise<{\n id: string;\n path: string;\n size: number;\n createdAt: string;\n url: string;\n }> {\n const form = new FormData();\n\n form.append(\n 'operations',\n JSON.stringify({\n query: `mutation UploadFilesFieldFileByUniversalIdentifier($file: Upload!, $fieldMetadataUniversalIdentifier: String!) {\n uploadFilesFieldFileByUniversalIdentifier(file: $file, fieldMetadataUniversalIdentifier: $fieldMetadataUniversalIdentifier) { id path size createdAt url }\n }`,\n variables: {\n file: null,\n fieldMetadataUniversalIdentifier,\n },\n }),\n );\n form.append('map', JSON.stringify({ '0': ['variables.file'] }));\n form.append(\n '0',\n new Blob([fileBuffer as BlobPart], { type: contentType }),\n filename,\n );\n\n const result = await this.executeGraphqlRequestWithOptionalRefresh({\n operation: form,\n headers: {},\n requestInit: {\n method: 'POST',\n },\n });\n\n if (result.errors) {\n throw new GenqlError(result.errors, result.data);\n }\n\n const data = result.data as Record<string, unknown>;\n\n return data.uploadFilesFieldFileByUniversalIdentifier as {\n id: string;\n path: string;\n size: number;\n createdAt: string;\n url: string;\n };\n }\n // __UPLOAD_FILE_END__\n\n private async executeGraphqlRequestWithOptionalRefresh({\n operation,\n headers,\n requestInit,\n }: {\n operation: GraphqlOperation | GraphqlOperation[] | FormData;\n headers?: HeadersInit;\n requestInit?: RequestInit;\n }) {\n const firstResponse = await this.executeGraphqlRequest({\n operation,\n headers,\n requestInit,\n token: this.authorizationToken,\n });\n\n if (this.shouldRefreshToken(firstResponse)) {\n const refreshedAccessToken = await this.requestRefreshedAccessToken();\n\n if (refreshedAccessToken) {\n const retryResponse = await this.executeGraphqlRequest({\n operation,\n headers,\n requestInit,\n token: refreshedAccessToken,\n });\n\n return this.assertResponseIsSuccessful(retryResponse);\n }\n }\n\n return this.assertResponseIsSuccessful(firstResponse);\n }\n\n private async executeGraphqlRequest({\n operation,\n headers,\n requestInit,\n token,\n }: {\n operation: GraphqlOperation | GraphqlOperation[] | FormData;\n headers?: HeadersInit;\n requestInit?: RequestInit;\n token: string | null;\n }): Promise<GraphqlResponse> {\n if (!this.fetchImplementation) {\n throw new Error(\n 'Global `fetch` function is not available, ' +\n 'pass a fetch implementation to the Twenty client',\n );\n }\n\n const resolvedHeaders = await this.resolveHeaders();\n const requestHeaders = new Headers(resolvedHeaders);\n\n if (headers) {\n new Headers(headers).forEach((value, key) =>\n requestHeaders.set(key, value),\n );\n }\n\n if (operation instanceof FormData) {\n requestHeaders.delete('Content-Type');\n } else {\n requestHeaders.set('Content-Type', 'application/json');\n }\n\n if (token) {\n requestHeaders.set('Authorization', `Bearer ${token}`);\n } else {\n requestHeaders.delete('Authorization');\n }\n\n const response = await this.fetchImplementation.call(globalThis, this.url, {\n ...this.requestOptions,\n ...requestInit,\n method: requestInit?.method ?? 'POST',\n headers: requestHeaders,\n body:\n operation instanceof FormData ? operation : JSON.stringify(operation),\n });\n\n const rawBody = await response.text();\n let payload: GraphqlResponsePayload | null = null;\n\n if (rawBody.trim().length > 0) {\n try {\n payload = JSON.parse(rawBody) as GraphqlResponsePayload;\n } catch {\n payload = null;\n }\n }\n\n return {\n status: response.status,\n statusText: response.statusText,\n payload,\n rawBody,\n };\n }\n\n private async resolveHeaders(): Promise<HeadersInit> {\n if (typeof this.headers === 'function') {\n return (await this.headers()) ?? {};\n }\n\n return this.headers ?? {};\n }\n\n private shouldRefreshToken(response: GraphqlResponse): boolean {\n if (response.status === 401) {\n return true;\n }\n\n return hasAuthenticationErrorInGraphqlPayload(response.payload);\n }\n\n private assertResponseIsSuccessful(response: GraphqlResponse) {\n if (response.status < 200 || response.status >= 300) {\n throw new Error(`${response.statusText}: ${response.rawBody}`);\n }\n\n if (response.payload === null) {\n throw new Error('Invalid JSON response');\n }\n\n return response.payload;\n }\n\n private async requestRefreshedAccessToken(): Promise<string | null> {\n const refreshAccessTokenFunction = (\n globalThis as {\n frontComponentHostCommunicationApi?: {\n requestAccessTokenRefresh?: () => Promise<string>;\n };\n }\n ).frontComponentHostCommunicationApi?.requestAccessTokenRefresh;\n\n if (typeof refreshAccessTokenFunction !== 'function') {\n return null;\n }\n\n if (!this.refreshAccessTokenPromise) {\n this.refreshAccessTokenPromise = refreshAccessTokenFunction()\n .then((refreshedAccessToken) => {\n if (\n typeof refreshedAccessToken !== 'string' ||\n refreshedAccessToken.length === 0\n ) {\n return null;\n }\n\n this.setAuthorizationToken(refreshedAccessToken);\n\n return refreshedAccessToken;\n })\n .catch((refreshError: unknown) => {\n console.error('Twenty client: token refresh failed', refreshError);\n\n return null;\n })\n .finally(() => {\n this.refreshAccessTokenPromise = null;\n });\n }\n\n return this.refreshAccessTokenPromise;\n }\n\n private setAuthorizationToken(token: string) {\n this.authorizationToken = token;\n\n const processEnvironment = getProcessEnvironment();\n\n processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] = token;\n }\n}\n", o = `${r}.tmp`;
|
|
526
|
+
await O(o), await k(o);
|
|
530
527
|
try {
|
|
531
528
|
await Z({
|
|
532
|
-
schema:
|
|
529
|
+
schema: n,
|
|
533
530
|
output: o,
|
|
534
|
-
scalarTypes:
|
|
531
|
+
scalarTypes: st
|
|
535
532
|
});
|
|
536
|
-
let i =
|
|
533
|
+
let i = D(a, {
|
|
537
534
|
apiClientName: "CoreApiClient",
|
|
538
|
-
defaultUrl: `\`\${process.env.${
|
|
535
|
+
defaultUrl: `\`\${process.env.${e}}/graphql\``,
|
|
539
536
|
includeUploadFile: !0
|
|
540
537
|
});
|
|
541
|
-
await
|
|
538
|
+
await t(u(o, "index.ts"), i), await A(r), await _e(o, r), await lt(r);
|
|
542
539
|
} catch (e) {
|
|
543
|
-
throw await
|
|
540
|
+
throw await A(o), e;
|
|
544
541
|
}
|
|
545
|
-
},
|
|
546
|
-
let
|
|
542
|
+
}, ct = async ({ packageRoot: e, schema: t }) => {
|
|
543
|
+
let r = u(e, "dist", Q);
|
|
547
544
|
await $({
|
|
548
545
|
schema: t,
|
|
549
|
-
outputPath:
|
|
550
|
-
}), await
|
|
551
|
-
},
|
|
552
|
-
let t =
|
|
553
|
-
await
|
|
546
|
+
outputPath: r
|
|
547
|
+
}), await n(u(r, "index.mjs"), u(e, "dist", "core.mjs")), await n(u(r, "index.cjs"), u(e, "dist", "core.cjs"));
|
|
548
|
+
}, lt = async (e) => {
|
|
549
|
+
let t = u(e, "index.ts"), n = u(e, "index.mjs");
|
|
550
|
+
await p({
|
|
554
551
|
entryPoints: [t],
|
|
555
552
|
outfile: n,
|
|
556
553
|
bundle: !0,
|
|
@@ -559,40 +556,40 @@ var ct = async (e) => {
|
|
|
559
556
|
target: "node18",
|
|
560
557
|
sourcemap: !1,
|
|
561
558
|
minify: !1
|
|
562
|
-
}), await
|
|
559
|
+
}), await p({
|
|
563
560
|
entryPoints: [t],
|
|
564
|
-
outfile:
|
|
561
|
+
outfile: u(e, "index.cjs"),
|
|
565
562
|
bundle: !0,
|
|
566
563
|
format: "cjs",
|
|
567
564
|
platform: "node",
|
|
568
565
|
target: "node18",
|
|
569
566
|
sourcemap: !1,
|
|
570
567
|
minify: !1
|
|
571
|
-
}), await
|
|
568
|
+
}), await c(u(e, "package.json"), JSON.stringify({
|
|
572
569
|
type: "module",
|
|
573
570
|
main: "index.mjs",
|
|
574
571
|
module: "index.mjs"
|
|
575
572
|
}, null, 2));
|
|
576
|
-
},
|
|
573
|
+
}, ut = {
|
|
577
574
|
DateTime: "string",
|
|
578
575
|
JSON: "Record<string, unknown>",
|
|
579
576
|
UUID: "string"
|
|
580
|
-
},
|
|
577
|
+
}, dt = async ({ schema: n, outputPath: r, clientWrapperTemplateSource: i }) => {
|
|
581
578
|
let a = i ?? "// Ambient type stubs for the genql-generated code this template gets\n// injected into. They enable full typecheck/lint on this file.\n// __STRIPPED_DURING_INJECTION_START__\ntype QueryGenqlSelection = Record<string, unknown>;\ntype MutationGenqlSelection = Record<string, unknown>;\ntype GraphqlOperation = Record<string, unknown>;\n\ntype ClientOptions = {\n url?: string;\n headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);\n fetcher?: (\n operation: GraphqlOperation | GraphqlOperation[],\n ) => Promise<unknown>;\n fetch?: typeof globalThis.fetch;\n batch?: unknown;\n};\n\ntype Client = {\n query: (\n request: QueryGenqlSelection & { __name?: string },\n ) => Promise<unknown>;\n mutation: (\n request: MutationGenqlSelection & { __name?: string },\n ) => Promise<unknown>;\n};\n\ndeclare function createClient(options: ClientOptions): Client;\n\ndeclare class GenqlError extends Error {\n constructor(errors: unknown, data: unknown);\n}\n// __STRIPPED_DURING_INJECTION_END__\n\nconst APP_ACCESS_TOKEN_ENV_KEY = 'TWENTY_APP_ACCESS_TOKEN';\nconst API_KEY_ENV_KEY = 'TWENTY_API_KEY';\n\ntype TwentyGeneratedClientOptions = ClientOptions;\n\ntype ProcessEnvironment = Record<string, string | undefined>;\n\ntype GraphqlErrorPayloadEntry = {\n message?: string;\n extensions?: { code?: string };\n};\n\ntype GraphqlResponsePayload = {\n data?: Record<string, unknown>;\n errors?: GraphqlErrorPayloadEntry[];\n};\n\ntype GraphqlResponse = {\n status: number;\n statusText: string;\n payload: GraphqlResponsePayload | null;\n rawBody: string;\n};\n\nconst getProcessEnvironment = (): ProcessEnvironment => {\n const processObject = (\n globalThis as { process?: { env?: ProcessEnvironment } }\n ).process;\n\n return processObject?.env ?? {};\n};\n\nconst getTokenFromAuthorizationHeader = (\n authorizationHeader: string | undefined,\n): string | null => {\n if (typeof authorizationHeader !== 'string') {\n return null;\n }\n\n const trimmedAuthorizationHeader = authorizationHeader.trim();\n\n if (trimmedAuthorizationHeader.length === 0) {\n return null;\n }\n\n if (trimmedAuthorizationHeader === 'Bearer') {\n return null;\n }\n\n if (trimmedAuthorizationHeader.startsWith('Bearer ')) {\n return trimmedAuthorizationHeader.slice('Bearer '.length).trim();\n }\n\n return trimmedAuthorizationHeader;\n};\n\nconst getTokenFromHeaders = (\n headers: HeadersInit | undefined,\n): string | null => {\n if (!headers) {\n return null;\n }\n\n if (headers instanceof Headers) {\n return getTokenFromAuthorizationHeader(\n headers.get('Authorization') ?? undefined,\n );\n }\n\n if (Array.isArray(headers)) {\n const matchedAuthorizationHeader = headers.find(\n ([headerName]) => headerName.toLowerCase() === 'authorization',\n );\n\n return getTokenFromAuthorizationHeader(matchedAuthorizationHeader?.[1]);\n }\n\n const headersRecord = headers as Record<string, string | undefined>;\n\n return getTokenFromAuthorizationHeader(\n headersRecord.Authorization ?? headersRecord.authorization,\n );\n};\n\nconst hasAuthenticationErrorInGraphqlPayload = (\n payload: GraphqlResponsePayload | null,\n): boolean => {\n if (!payload?.errors) {\n return false;\n }\n\n return payload.errors.some((graphqlError) => {\n return (\n graphqlError.extensions?.code === 'UNAUTHENTICATED' ||\n graphqlError.message?.toLowerCase() === 'unauthorized'\n );\n });\n};\n\nconst defaultOptions: TwentyGeneratedClientOptions = {\n url: '__TWENTY_DEFAULT_URL__',\n headers: {\n 'Content-Type': 'application/json',\n },\n};\n\nexport class TwentyGeneratedClient {\n private client: Client;\n private url: string;\n private requestOptions: RequestInit;\n private headers: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);\n private fetchImplementation: typeof globalThis.fetch | null;\n private authorizationToken: string | null;\n private refreshAccessTokenPromise: Promise<string | null> | null = null;\n\n constructor(options?: TwentyGeneratedClientOptions) {\n const merged: TwentyGeneratedClientOptions = {\n ...defaultOptions,\n ...options,\n };\n\n const {\n url,\n headers,\n fetch: customFetchImplementation,\n fetcher: _fetcher,\n batch: _batch,\n ...requestOptions\n } = merged;\n\n this.url = url ?? '';\n this.requestOptions = requestOptions;\n this.headers = headers ?? {};\n this.fetchImplementation =\n customFetchImplementation ?? globalThis.fetch ?? null;\n\n const processEnvironment = getProcessEnvironment();\n const tokenFromHeaders = getTokenFromHeaders(\n typeof headers === 'function' ? undefined : headers,\n );\n\n // Priority: explicit header > app access token > api key (legacy).\n this.authorizationToken =\n tokenFromHeaders ??\n processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] ??\n processEnvironment[API_KEY_ENV_KEY] ??\n null;\n\n this.client = createClient({\n ...merged,\n headers: undefined,\n fetcher: async (operation) =>\n this.executeGraphqlRequestWithOptionalRefresh({\n operation,\n }),\n });\n }\n\n query<R extends QueryGenqlSelection>(request: R & { __name?: string }) {\n return this.client.query(request);\n }\n\n mutation<R extends MutationGenqlSelection>(request: R & { __name?: string }) {\n return this.client.mutation(request);\n }\n\n // __UPLOAD_FILE_START__\n async uploadFile(\n fileBuffer: Buffer,\n filename: string,\n contentType: string = 'application/octet-stream',\n fieldMetadataUniversalIdentifier: string,\n ): Promise<{\n id: string;\n path: string;\n size: number;\n createdAt: string;\n url: string;\n }> {\n const form = new FormData();\n\n form.append(\n 'operations',\n JSON.stringify({\n query: `mutation UploadFilesFieldFileByUniversalIdentifier($file: Upload!, $fieldMetadataUniversalIdentifier: String!) {\n uploadFilesFieldFileByUniversalIdentifier(file: $file, fieldMetadataUniversalIdentifier: $fieldMetadataUniversalIdentifier) { id path size createdAt url }\n }`,\n variables: {\n file: null,\n fieldMetadataUniversalIdentifier,\n },\n }),\n );\n form.append('map', JSON.stringify({ '0': ['variables.file'] }));\n form.append(\n '0',\n new Blob([fileBuffer as BlobPart], { type: contentType }),\n filename,\n );\n\n const result = await this.executeGraphqlRequestWithOptionalRefresh({\n operation: form,\n headers: {},\n requestInit: {\n method: 'POST',\n },\n });\n\n if (result.errors) {\n throw new GenqlError(result.errors, result.data);\n }\n\n const data = result.data as Record<string, unknown>;\n\n return data.uploadFilesFieldFileByUniversalIdentifier as {\n id: string;\n path: string;\n size: number;\n createdAt: string;\n url: string;\n };\n }\n // __UPLOAD_FILE_END__\n\n private async executeGraphqlRequestWithOptionalRefresh({\n operation,\n headers,\n requestInit,\n }: {\n operation: GraphqlOperation | GraphqlOperation[] | FormData;\n headers?: HeadersInit;\n requestInit?: RequestInit;\n }) {\n const firstResponse = await this.executeGraphqlRequest({\n operation,\n headers,\n requestInit,\n token: this.authorizationToken,\n });\n\n if (this.shouldRefreshToken(firstResponse)) {\n const refreshedAccessToken = await this.requestRefreshedAccessToken();\n\n if (refreshedAccessToken) {\n const retryResponse = await this.executeGraphqlRequest({\n operation,\n headers,\n requestInit,\n token: refreshedAccessToken,\n });\n\n return this.assertResponseIsSuccessful(retryResponse);\n }\n }\n\n return this.assertResponseIsSuccessful(firstResponse);\n }\n\n private async executeGraphqlRequest({\n operation,\n headers,\n requestInit,\n token,\n }: {\n operation: GraphqlOperation | GraphqlOperation[] | FormData;\n headers?: HeadersInit;\n requestInit?: RequestInit;\n token: string | null;\n }): Promise<GraphqlResponse> {\n if (!this.fetchImplementation) {\n throw new Error(\n 'Global `fetch` function is not available, ' +\n 'pass a fetch implementation to the Twenty client',\n );\n }\n\n const resolvedHeaders = await this.resolveHeaders();\n const requestHeaders = new Headers(resolvedHeaders);\n\n if (headers) {\n new Headers(headers).forEach((value, key) =>\n requestHeaders.set(key, value),\n );\n }\n\n if (operation instanceof FormData) {\n requestHeaders.delete('Content-Type');\n } else {\n requestHeaders.set('Content-Type', 'application/json');\n }\n\n if (token) {\n requestHeaders.set('Authorization', `Bearer ${token}`);\n } else {\n requestHeaders.delete('Authorization');\n }\n\n const response = await this.fetchImplementation.call(globalThis, this.url, {\n ...this.requestOptions,\n ...requestInit,\n method: requestInit?.method ?? 'POST',\n headers: requestHeaders,\n body:\n operation instanceof FormData ? operation : JSON.stringify(operation),\n });\n\n const rawBody = await response.text();\n let payload: GraphqlResponsePayload | null = null;\n\n if (rawBody.trim().length > 0) {\n try {\n payload = JSON.parse(rawBody) as GraphqlResponsePayload;\n } catch {\n payload = null;\n }\n }\n\n return {\n status: response.status,\n statusText: response.statusText,\n payload,\n rawBody,\n };\n }\n\n private async resolveHeaders(): Promise<HeadersInit> {\n if (typeof this.headers === 'function') {\n return (await this.headers()) ?? {};\n }\n\n return this.headers ?? {};\n }\n\n private shouldRefreshToken(response: GraphqlResponse): boolean {\n if (response.status === 401) {\n return true;\n }\n\n return hasAuthenticationErrorInGraphqlPayload(response.payload);\n }\n\n private assertResponseIsSuccessful(response: GraphqlResponse) {\n if (response.status < 200 || response.status >= 300) {\n throw new Error(`${response.statusText}: ${response.rawBody}`);\n }\n\n if (response.payload === null) {\n throw new Error('Invalid JSON response');\n }\n\n return response.payload;\n }\n\n private async requestRefreshedAccessToken(): Promise<string | null> {\n const refreshAccessTokenFunction = (\n globalThis as {\n frontComponentHostCommunicationApi?: {\n requestAccessTokenRefresh?: () => Promise<string>;\n };\n }\n ).frontComponentHostCommunicationApi?.requestAccessTokenRefresh;\n\n if (typeof refreshAccessTokenFunction !== 'function') {\n return null;\n }\n\n if (!this.refreshAccessTokenPromise) {\n this.refreshAccessTokenPromise = refreshAccessTokenFunction()\n .then((refreshedAccessToken) => {\n if (\n typeof refreshedAccessToken !== 'string' ||\n refreshedAccessToken.length === 0\n ) {\n return null;\n }\n\n this.setAuthorizationToken(refreshedAccessToken);\n\n return refreshedAccessToken;\n })\n .catch((refreshError: unknown) => {\n console.error('Twenty client: token refresh failed', refreshError);\n\n return null;\n })\n .finally(() => {\n this.refreshAccessTokenPromise = null;\n });\n }\n\n return this.refreshAccessTokenPromise;\n }\n\n private setAuthorizationToken(token: string) {\n this.authorizationToken = token;\n\n const processEnvironment = getProcessEnvironment();\n\n processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] = token;\n }\n}\n";
|
|
582
|
-
await
|
|
583
|
-
schema:
|
|
584
|
-
output:
|
|
579
|
+
await O(r), await k(r), await Z({
|
|
580
|
+
schema: n,
|
|
581
|
+
output: r,
|
|
585
582
|
scalarTypes: {
|
|
586
|
-
...
|
|
583
|
+
...ut,
|
|
587
584
|
Upload: "File"
|
|
588
585
|
}
|
|
589
586
|
});
|
|
590
|
-
let o =
|
|
587
|
+
let o = D(a, {
|
|
591
588
|
apiClientName: "MetadataApiClient",
|
|
592
|
-
defaultUrl: `\`\${process.env.${
|
|
589
|
+
defaultUrl: `\`\${process.env.${e}}/metadata\``,
|
|
593
590
|
includeUploadFile: !0
|
|
594
591
|
});
|
|
595
|
-
await
|
|
592
|
+
await t(u(r, "index.ts"), o);
|
|
596
593
|
};
|
|
597
594
|
//#endregion
|
|
598
|
-
export { Q as GENERATED_CORE_DIR, $ as generateCoreClientFromSchema,
|
|
595
|
+
export { Q as GENERATED_CORE_DIR, $ as generateCoreClientFromSchema, dt as generateMetadataClient, ct as replaceCoreClient };
|