buildgql 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +375 -0
- package/dist/adapters/apollo.cjs +23 -0
- package/dist/adapters/apollo.d.cts +28 -0
- package/dist/adapters/apollo.d.ts +28 -0
- package/dist/adapters/apollo.js +23 -0
- package/dist/adapters/urql.cjs +16 -0
- package/dist/adapters/urql.d.cts +26 -0
- package/dist/adapters/urql.d.ts +26 -0
- package/dist/adapters/urql.js +16 -0
- package/dist/chunk-2Z2AKLA3.cjs +267 -0
- package/dist/chunk-BM7L4MCF.cjs +27 -0
- package/dist/chunk-RSDTCILU.js +267 -0
- package/dist/chunk-SNFCCROD.js +27 -0
- package/dist/cli/bin.js +842 -0
- package/dist/cli/config.cjs +272 -0
- package/dist/cli/config.d.cts +73 -0
- package/dist/cli/config.d.ts +73 -0
- package/dist/cli/config.js +245 -0
- package/dist/client/index.cjs +16 -0
- package/dist/client/index.d.cts +93 -0
- package/dist/client/index.d.ts +93 -0
- package/dist/client/index.js +16 -0
- package/dist/document-BZ9RdxXB.d.cts +16 -0
- package/dist/document-BZ9RdxXB.d.ts +16 -0
- package/dist/index.cjs +313 -0
- package/dist/index.d.cts +85 -0
- package/dist/index.d.ts +85 -0
- package/dist/index.js +313 -0
- package/dist/operation-DxbEION8.d.cts +200 -0
- package/dist/operation-DxbEION8.d.ts +200 -0
- package/package.json +148 -0
package/dist/cli/bin.js
ADDED
|
@@ -0,0 +1,842 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli/main.ts
|
|
4
|
+
import { readFile as readFile2 } from "fs/promises";
|
|
5
|
+
import { resolve as resolve4 } from "path";
|
|
6
|
+
|
|
7
|
+
// src/cli/config.ts
|
|
8
|
+
import { access } from "fs/promises";
|
|
9
|
+
import { pathToFileURL } from "url";
|
|
10
|
+
import { isAbsolute, join, resolve } from "path";
|
|
11
|
+
|
|
12
|
+
// src/codegen/clients.ts
|
|
13
|
+
var CLIENT_KINDS = ["buildgql", "apollo", "urql", "none"];
|
|
14
|
+
var CLIENT_EMITS = {
|
|
15
|
+
buildgql: { module: "buildgql", names: ["createClient"] },
|
|
16
|
+
apollo: {
|
|
17
|
+
module: "buildgql/adapters/apollo",
|
|
18
|
+
names: ["apolloDocument", "toApolloMutation", "toApolloQuery"]
|
|
19
|
+
},
|
|
20
|
+
urql: { module: "buildgql/adapters/urql", names: ["toUrqlArgs", "urqlDocument"] },
|
|
21
|
+
none: { names: [] }
|
|
22
|
+
};
|
|
23
|
+
function isClientKind(value) {
|
|
24
|
+
return typeof value === "string" && CLIENT_KINDS.includes(value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// src/cli/assert-scalars.ts
|
|
28
|
+
var SCALAR_KEYS = [
|
|
29
|
+
"name",
|
|
30
|
+
"from",
|
|
31
|
+
"declare",
|
|
32
|
+
"input",
|
|
33
|
+
"output"
|
|
34
|
+
];
|
|
35
|
+
var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
36
|
+
var RESERVED_NAMES = /* @__PURE__ */ new Set([
|
|
37
|
+
"break",
|
|
38
|
+
"case",
|
|
39
|
+
"catch",
|
|
40
|
+
"class",
|
|
41
|
+
"const",
|
|
42
|
+
"continue",
|
|
43
|
+
"debugger",
|
|
44
|
+
"default",
|
|
45
|
+
"delete",
|
|
46
|
+
"do",
|
|
47
|
+
"else",
|
|
48
|
+
"enum",
|
|
49
|
+
"export",
|
|
50
|
+
"extends",
|
|
51
|
+
"false",
|
|
52
|
+
"finally",
|
|
53
|
+
"for",
|
|
54
|
+
"function",
|
|
55
|
+
"if",
|
|
56
|
+
"import",
|
|
57
|
+
"in",
|
|
58
|
+
"instanceof",
|
|
59
|
+
"new",
|
|
60
|
+
"null",
|
|
61
|
+
"return",
|
|
62
|
+
"super",
|
|
63
|
+
"switch",
|
|
64
|
+
"this",
|
|
65
|
+
"throw",
|
|
66
|
+
"true",
|
|
67
|
+
"try",
|
|
68
|
+
"typeof",
|
|
69
|
+
"var",
|
|
70
|
+
"void",
|
|
71
|
+
"while",
|
|
72
|
+
"with",
|
|
73
|
+
"await",
|
|
74
|
+
"implements",
|
|
75
|
+
"interface",
|
|
76
|
+
"let",
|
|
77
|
+
"package",
|
|
78
|
+
"private",
|
|
79
|
+
"protected",
|
|
80
|
+
"public",
|
|
81
|
+
"static",
|
|
82
|
+
"yield",
|
|
83
|
+
"any",
|
|
84
|
+
"bigint",
|
|
85
|
+
"boolean",
|
|
86
|
+
"never",
|
|
87
|
+
"number",
|
|
88
|
+
"object",
|
|
89
|
+
"string",
|
|
90
|
+
"symbol",
|
|
91
|
+
"undefined",
|
|
92
|
+
"unknown",
|
|
93
|
+
"as"
|
|
94
|
+
]);
|
|
95
|
+
var UNSAFE_IN_QUOTED_SPECIFIER = /['"\n\r\\]/;
|
|
96
|
+
function isPlainRecord(value) {
|
|
97
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
98
|
+
}
|
|
99
|
+
function assertNonEmptyString(configName, scalar, key, value) {
|
|
100
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
101
|
+
throw new Error(`buildgql: ${configName}'s "scalars.${scalar}.${key}" must be a non-empty string`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function assertScalarsConfig(configName, value) {
|
|
105
|
+
if (!isPlainRecord(value)) {
|
|
106
|
+
throw new Error(`buildgql: ${configName}'s "scalars" must be a record keyed by GraphQL scalar name`);
|
|
107
|
+
}
|
|
108
|
+
for (const [scalar, entry] of Object.entries(value)) {
|
|
109
|
+
if (typeof entry === "string") {
|
|
110
|
+
if (entry.length === 0) {
|
|
111
|
+
throw new Error(`buildgql: ${configName}'s "scalars.${scalar}" must not be an empty string`);
|
|
112
|
+
}
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (!isPlainRecord(entry)) {
|
|
116
|
+
throw new Error(
|
|
117
|
+
`buildgql: ${configName}'s "scalars.${scalar}" must be a TypeScript type string, or an object with "input"/"output", "name" + "from", or "name" + "declare"`
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
for (const key of Object.keys(entry)) {
|
|
121
|
+
if (!SCALAR_KEYS.includes(key)) {
|
|
122
|
+
throw new Error(
|
|
123
|
+
`buildgql: ${configName}'s "scalars.${scalar}" has an unknown key "${key}" \u2014 expected one of ` + SCALAR_KEYS.map((k) => `"${k}"`).join(", ")
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const { name, from, declare, input, output } = entry;
|
|
128
|
+
if (from !== void 0 && declare !== void 0) {
|
|
129
|
+
throw new Error(
|
|
130
|
+
`buildgql: ${configName}'s "scalars.${scalar}" sets both "from" and "declare" \u2014 a type is either imported or declared, not both`
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
if (from !== void 0) {
|
|
134
|
+
assertNonEmptyString(configName, scalar, "from", from);
|
|
135
|
+
if (UNSAFE_IN_QUOTED_SPECIFIER.test(from)) {
|
|
136
|
+
throw new Error(
|
|
137
|
+
`buildgql: ${configName}'s "scalars.${scalar}.from" ("${from}") contains a character ("'", '"', a backslash, or a newline) that cannot appear there \u2014 "from" is emitted inside a quoted module specifier. Use forward slashes even for a Windows-style path.`
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (declare !== void 0) assertNonEmptyString(configName, scalar, "declare", declare);
|
|
142
|
+
if (input !== void 0) assertNonEmptyString(configName, scalar, "input", input);
|
|
143
|
+
if (output !== void 0) assertNonEmptyString(configName, scalar, "output", output);
|
|
144
|
+
if (name !== void 0) {
|
|
145
|
+
assertNonEmptyString(configName, scalar, "name", name);
|
|
146
|
+
if (!IDENTIFIER.test(name)) {
|
|
147
|
+
throw new Error(
|
|
148
|
+
`buildgql: ${configName}'s "scalars.${scalar}.name" ("${name}") is not a valid TypeScript identifier`
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
if (RESERVED_NAMES.has(name)) {
|
|
152
|
+
throw new Error(
|
|
153
|
+
`buildgql: ${configName}'s "scalars.${scalar}.name" ("${name}") is a reserved word and cannot be spliced into "import type { ${name} }" or "export type ${name} = ..." \u2014 choose a different name`
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
if (from === void 0 && declare === void 0) {
|
|
157
|
+
throw new Error(
|
|
158
|
+
`buildgql: ${configName}'s "scalars.${scalar}" sets "name" but neither "from" nor "declare" \u2014 nothing in the generated module would declare that type`
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
} else if (from !== void 0 || declare !== void 0) {
|
|
162
|
+
throw new Error(
|
|
163
|
+
`buildgql: ${configName}'s "scalars.${scalar}" sets "${from !== void 0 ? "from" : "declare"}" but not "name" \u2014 "name" is what the generated module refers to the type by`
|
|
164
|
+
);
|
|
165
|
+
} else if (input === void 0 && output === void 0) {
|
|
166
|
+
throw new Error(
|
|
167
|
+
`buildgql: ${configName}'s "scalars.${scalar}" is empty \u2014 set "input"/"output", or "name" together with "from" or "declare"`
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// src/cli/config.ts
|
|
174
|
+
var CANDIDATES = ["buildgql.config.ts", "buildgql.config.mts", "buildgql.config.mjs", "buildgql.config.js"];
|
|
175
|
+
async function exists(p) {
|
|
176
|
+
try {
|
|
177
|
+
await access(p);
|
|
178
|
+
return true;
|
|
179
|
+
} catch {
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
function isRecord(value) {
|
|
184
|
+
return typeof value === "object" && value !== null;
|
|
185
|
+
}
|
|
186
|
+
function isStringRecord(value) {
|
|
187
|
+
return isRecord(value) && Object.values(value).every((v) => typeof v === "string");
|
|
188
|
+
}
|
|
189
|
+
function errorMessage(err) {
|
|
190
|
+
return err instanceof Error ? err.message : String(err);
|
|
191
|
+
}
|
|
192
|
+
function isMissingTypeStrippingSupport(err) {
|
|
193
|
+
return isRecord(err) && (err.code === "ERR_UNKNOWN_FILE_EXTENSION" || err.code === "ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX");
|
|
194
|
+
}
|
|
195
|
+
function assertBuildGQLConfig(name, value) {
|
|
196
|
+
if (typeof value.schema !== "string" || value.schema.length === 0) {
|
|
197
|
+
throw new Error(`buildgql: ${name} is missing "schema" \u2014 set it to a URL, a .json, or a .graphql file`);
|
|
198
|
+
}
|
|
199
|
+
if (value.output !== void 0 && typeof value.output !== "string") {
|
|
200
|
+
throw new Error(`buildgql: ${name}'s "output" must be a string path`);
|
|
201
|
+
}
|
|
202
|
+
if (value.headers !== void 0 && !isStringRecord(value.headers)) {
|
|
203
|
+
throw new Error(`buildgql: ${name}'s "headers" must be a record of string values`);
|
|
204
|
+
}
|
|
205
|
+
if (value.scalars !== void 0) assertScalarsConfig(name, value.scalars);
|
|
206
|
+
if (value.client !== void 0 && !isClientKind(value.client)) {
|
|
207
|
+
throw new Error(
|
|
208
|
+
`buildgql: ${name}'s "client" must be one of ${CLIENT_KINDS.map((k) => `"${k}"`).join(", ")}`
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
var defaultImporter = (url) => import(url);
|
|
213
|
+
async function loadConfig(cwd = process.cwd(), importModule = defaultImporter) {
|
|
214
|
+
let missingTypeStrippingMessage;
|
|
215
|
+
for (const name of CANDIDATES) {
|
|
216
|
+
const path = join(cwd, name);
|
|
217
|
+
if (!await exists(path)) continue;
|
|
218
|
+
let mod;
|
|
219
|
+
try {
|
|
220
|
+
mod = await importModule(pathToFileURL(path).href);
|
|
221
|
+
} catch (err) {
|
|
222
|
+
if ((name.endsWith(".ts") || name.endsWith(".mts")) && isMissingTypeStrippingSupport(err)) {
|
|
223
|
+
missingTypeStrippingMessage = `buildgql: could not load ${name}. Node must be able to run TypeScript directly (Node >= 22.6 with --experimental-strip-types, or Node >= 23.6). Otherwise rename it to buildgql.config.mjs. Original error: ${errorMessage(err)}`;
|
|
224
|
+
process.stderr.write(
|
|
225
|
+
`buildgql: skipping ${name} \u2014 this Node cannot run TypeScript directly. ${errorMessage(err)}
|
|
226
|
+
`
|
|
227
|
+
);
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
throw new Error(`buildgql: failed to load ${name}: ${errorMessage(err)}`);
|
|
231
|
+
}
|
|
232
|
+
if (!isRecord(mod) || !("default" in mod)) {
|
|
233
|
+
throw new Error(`buildgql: ${name} must have a default export`);
|
|
234
|
+
}
|
|
235
|
+
const config = mod.default;
|
|
236
|
+
if (!isRecord(config)) {
|
|
237
|
+
throw new Error(`buildgql: ${name}'s default export must be an object (use defineConfig({...}))`);
|
|
238
|
+
}
|
|
239
|
+
assertBuildGQLConfig(name, config);
|
|
240
|
+
return { config, path };
|
|
241
|
+
}
|
|
242
|
+
if (missingTypeStrippingMessage) {
|
|
243
|
+
throw new Error(missingTypeStrippingMessage);
|
|
244
|
+
}
|
|
245
|
+
throw new Error(
|
|
246
|
+
`buildgql: no config found in ${cwd}. Create a buildgql.config.ts (or .js) exporting defineConfig({ schema: 'https://...' | './schema.graphql' }).`
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
function resolveOutputDir(config, cwd) {
|
|
250
|
+
const out = config.output ?? "./src/gql";
|
|
251
|
+
return isAbsolute(out) ? out : resolve(cwd, out);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// src/cli/generate.ts
|
|
255
|
+
import { mkdir, writeFile } from "fs/promises";
|
|
256
|
+
import { isAbsolute as isAbsolute3, join as join3, resolve as resolve3 } from "path";
|
|
257
|
+
|
|
258
|
+
// src/codegen/scalars.ts
|
|
259
|
+
var DEFAULT_SCALARS = {
|
|
260
|
+
ID: "string",
|
|
261
|
+
String: "string",
|
|
262
|
+
Int: "number",
|
|
263
|
+
Float: "number",
|
|
264
|
+
Boolean: "boolean"
|
|
265
|
+
};
|
|
266
|
+
var UNKNOWN_SCALAR = "unknown";
|
|
267
|
+
function toMapping(entry) {
|
|
268
|
+
if (typeof entry === "string") return { input: entry, output: entry };
|
|
269
|
+
const fallback = entry.name ?? entry.input ?? entry.output ?? UNKNOWN_SCALAR;
|
|
270
|
+
return { input: entry.input ?? fallback, output: entry.output ?? fallback };
|
|
271
|
+
}
|
|
272
|
+
var DEFAULT_SCALAR_MAPPINGS = Object.fromEntries(
|
|
273
|
+
Object.entries(DEFAULT_SCALARS).map(([name, ts]) => [name, toMapping(ts)])
|
|
274
|
+
);
|
|
275
|
+
function resolveScalars(overrides = {}, rewriteFrom = (from) => from) {
|
|
276
|
+
const scalars = { ...DEFAULT_SCALAR_MAPPINGS };
|
|
277
|
+
const sourceOf = /* @__PURE__ */ new Map();
|
|
278
|
+
const imports = [];
|
|
279
|
+
const declarations = [];
|
|
280
|
+
for (const gqlName of Object.keys(overrides).sort()) {
|
|
281
|
+
const entry = overrides[gqlName];
|
|
282
|
+
scalars[gqlName] = toMapping(entry);
|
|
283
|
+
if (typeof entry === "string" || entry.name === void 0) continue;
|
|
284
|
+
if (entry.from === void 0 && entry.declare === void 0) continue;
|
|
285
|
+
const source = entry.from === void 0 ? `declare "${entry.declare}"` : `import from "${entry.from}"`;
|
|
286
|
+
const seen = sourceOf.get(entry.name);
|
|
287
|
+
if (seen !== void 0) {
|
|
288
|
+
if (seen !== source) {
|
|
289
|
+
throw new Error(
|
|
290
|
+
`buildgql: two scalars both map to a TypeScript type named "${entry.name}", from different sources (${seen} and ${source}). Give one of them a different "name".`
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
sourceOf.set(entry.name, source);
|
|
296
|
+
if (entry.from !== void 0) imports.push({ name: entry.name, from: rewriteFrom(entry.from) });
|
|
297
|
+
else if (entry.declare !== void 0) declarations.push({ name: entry.name, body: entry.declare });
|
|
298
|
+
}
|
|
299
|
+
return { scalars, prelude: { imports, declarations } };
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// src/codegen/ts-types.ts
|
|
303
|
+
function scalarTsType(ir, name) {
|
|
304
|
+
return Object.hasOwn(ir.scalars, name) ? ir.scalars[name] : void 0;
|
|
305
|
+
}
|
|
306
|
+
function leafTsType(ref, ir) {
|
|
307
|
+
if (ref.kind === "enum") return ref.name;
|
|
308
|
+
return scalarTsType(ir, ref.name)?.output ?? UNKNOWN_SCALAR;
|
|
309
|
+
}
|
|
310
|
+
function isAtomicTypeExpression(type) {
|
|
311
|
+
let depth = 0;
|
|
312
|
+
for (let i = 0; i < type.length; i++) {
|
|
313
|
+
const ch = type[i];
|
|
314
|
+
if (ch === "(" || ch === "[" || ch === "{" || ch === "<") {
|
|
315
|
+
depth++;
|
|
316
|
+
} else if (ch === ")" || ch === "]" || ch === "}" || ch === ">" && type[i - 1] !== "=") {
|
|
317
|
+
depth--;
|
|
318
|
+
if (depth < 0) return false;
|
|
319
|
+
} else if (depth === 0 && (ch === "|" || ch === "&" || ch === "=" && type[i + 1] === ">")) {
|
|
320
|
+
return false;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return true;
|
|
324
|
+
}
|
|
325
|
+
function inputTsType(ref, ir) {
|
|
326
|
+
const base = ref.kind === "input" || ref.kind === "enum" ? ref.name : scalarTsType(ir, ref.name)?.input ?? UNKNOWN_SCALAR;
|
|
327
|
+
let out = isAtomicTypeExpression(base) ? base : `(${base})`;
|
|
328
|
+
const toks = [...ref.wrap].reverse();
|
|
329
|
+
let nonNull = false;
|
|
330
|
+
for (const tok of toks) {
|
|
331
|
+
if (tok === "!") {
|
|
332
|
+
nonNull = true;
|
|
333
|
+
} else {
|
|
334
|
+
out = nonNull ? `${out}[]` : `(${out} | null)[]`;
|
|
335
|
+
nonNull = false;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return nonNull ? out : `${out} | null`;
|
|
339
|
+
}
|
|
340
|
+
function argTsType(field, ir) {
|
|
341
|
+
const entries = field.args.map((a) => `${a.name}${a.optional ? "?" : ""}: ${inputTsType(a.type, ir)}`).join("; ");
|
|
342
|
+
return `{ ${entries} }`;
|
|
343
|
+
}
|
|
344
|
+
function typenameTsType(t) {
|
|
345
|
+
if (t.kind === "union" || t.kind === "interface") {
|
|
346
|
+
if (t.possibleTypes.length === 0) return "string";
|
|
347
|
+
return t.possibleTypes.map((p) => `'${p}'`).join(" | ");
|
|
348
|
+
}
|
|
349
|
+
return `'${t.name}'`;
|
|
350
|
+
}
|
|
351
|
+
function unmappedScalars(ir) {
|
|
352
|
+
const names = /* @__PURE__ */ new Set();
|
|
353
|
+
for (const t of ir.types) {
|
|
354
|
+
if (t.kind === "scalar" && !Object.hasOwn(ir.scalars, t.name)) names.add(t.name);
|
|
355
|
+
}
|
|
356
|
+
return [...names].sort();
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// src/codegen/emit.ts
|
|
360
|
+
var HEADER = `/* eslint-disable */
|
|
361
|
+
// AUTO-GENERATED BY buildgql. DO NOT EDIT.
|
|
362
|
+
// Re-run \`npx buildgql generate\` after changing the schema.
|
|
363
|
+
`;
|
|
364
|
+
var CORE_IMPORTS = [
|
|
365
|
+
"argSpec",
|
|
366
|
+
"include",
|
|
367
|
+
"leafField",
|
|
368
|
+
"leafFieldArgs",
|
|
369
|
+
"makeFragment",
|
|
370
|
+
"makeMutation",
|
|
371
|
+
"makeQuery",
|
|
372
|
+
"makeSubscription",
|
|
373
|
+
"objectField",
|
|
374
|
+
"objectFieldArgs",
|
|
375
|
+
"on",
|
|
376
|
+
"skip",
|
|
377
|
+
"spread"
|
|
378
|
+
];
|
|
379
|
+
function importBlock(client) {
|
|
380
|
+
const { module, names } = CLIENT_EMITS[client];
|
|
381
|
+
const fromRoot = module === "buildgql" ? [...CORE_IMPORTS, ...names].sort() : [...CORE_IMPORTS].sort();
|
|
382
|
+
const root = `import {
|
|
383
|
+
${fromRoot.map((n) => ` ${n},`).join("\n")}
|
|
384
|
+
$,
|
|
385
|
+
v,
|
|
386
|
+
} from 'buildgql';
|
|
387
|
+
`;
|
|
388
|
+
if (!module || module === "buildgql") return root;
|
|
389
|
+
return `${root}import { ${names.join(", ")} } from '${module}';
|
|
390
|
+
`;
|
|
391
|
+
}
|
|
392
|
+
function reexportBlock(client) {
|
|
393
|
+
const list = ["$", "v", "on", "spread", "include", "skip", ...CLIENT_EMITS[client].names];
|
|
394
|
+
return `export { ${list.join(", ")} };
|
|
395
|
+
export type { Operation } from 'buildgql';
|
|
396
|
+
`;
|
|
397
|
+
}
|
|
398
|
+
function scalarPreludeBlock(prelude) {
|
|
399
|
+
const byModule = /* @__PURE__ */ new Map();
|
|
400
|
+
for (const { name, from } of prelude.imports) {
|
|
401
|
+
const names = byModule.get(from) ?? /* @__PURE__ */ new Set();
|
|
402
|
+
names.add(name);
|
|
403
|
+
byModule.set(from, names);
|
|
404
|
+
}
|
|
405
|
+
const lines = [...byModule.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(
|
|
406
|
+
([from, names]) => `import type { ${[...names].sort((a, b) => a < b ? -1 : a > b ? 1 : 0).join(", ")} } from '${from}';`
|
|
407
|
+
);
|
|
408
|
+
const decls = [...prelude.declarations].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map((d) => `export type ${d.name} = ${d.body};`);
|
|
409
|
+
if (lines.length === 0 && decls.length === 0) return "";
|
|
410
|
+
return `${[...lines, ...decls].join("\n")}
|
|
411
|
+
`;
|
|
412
|
+
}
|
|
413
|
+
function reservedNames(ir, client) {
|
|
414
|
+
const names = /* @__PURE__ */ new Set([
|
|
415
|
+
...CORE_IMPORTS,
|
|
416
|
+
...CLIENT_EMITS[client].names,
|
|
417
|
+
"$",
|
|
418
|
+
"v",
|
|
419
|
+
"Operation",
|
|
420
|
+
"query"
|
|
421
|
+
]);
|
|
422
|
+
if (ir.mutationType) names.add("mutation");
|
|
423
|
+
if (ir.subscriptionType) names.add("subscription");
|
|
424
|
+
for (const t of ir.types) {
|
|
425
|
+
if (t.kind === "scalar") continue;
|
|
426
|
+
names.add(t.name);
|
|
427
|
+
if (t.kind === "enum") names.add(`${t.name}Values`);
|
|
428
|
+
if (t.kind === "object" || t.kind === "interface" || t.kind === "union") {
|
|
429
|
+
names.add(`${lowerFirst(t.name)}Fragment`);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return names;
|
|
433
|
+
}
|
|
434
|
+
function assertNoScalarNameCollisions(ir, client) {
|
|
435
|
+
const reserved = reservedNames(ir, client);
|
|
436
|
+
const declared = [
|
|
437
|
+
...ir.scalarPrelude.imports.map((i) => i.name),
|
|
438
|
+
...ir.scalarPrelude.declarations.map((d) => d.name)
|
|
439
|
+
];
|
|
440
|
+
for (const name of declared) {
|
|
441
|
+
if (reserved.has(name)) {
|
|
442
|
+
throw new Error(
|
|
443
|
+
`buildgql: a "scalars" entry maps to a TypeScript type named "${name}", which the generated module already binds. Give it a different "name" in your buildgql.config.*.`
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
function lowerFirst(s) {
|
|
449
|
+
return s.charAt(0).toLowerCase() + s.slice(1);
|
|
450
|
+
}
|
|
451
|
+
function wrapLiteral(wrap) {
|
|
452
|
+
return `[${wrap.map((w) => `'${w}'`).join(", ")}]`;
|
|
453
|
+
}
|
|
454
|
+
function argSpec(field, ir) {
|
|
455
|
+
const gqlEntries = field.args.map((a) => `${a.name}: '${a.gqlType}'`).join(", ");
|
|
456
|
+
const enumKeys = field.args.filter((a) => a.type.kind === "enum").map((a) => `'${a.name}'`);
|
|
457
|
+
const enumArg = enumKeys.length > 0 ? `, [${enumKeys.join(", ")}]` : "";
|
|
458
|
+
return `argSpec<${argTsType(field, ir)}>({ ${gqlEntries} }${enumArg})`;
|
|
459
|
+
}
|
|
460
|
+
function emitField(field, ir) {
|
|
461
|
+
const wrap = wrapLiteral(field.type.wrap);
|
|
462
|
+
const isComposite = field.type.kind === "object" || field.type.kind === "interface" || field.type.kind === "union";
|
|
463
|
+
if (!isComposite) {
|
|
464
|
+
const ts = leafTsType(field.type, ir);
|
|
465
|
+
if (field.args.length === 0) {
|
|
466
|
+
return ` ${field.name}: leafField<'${field.name}', ${wrap}, ${ts}>('${field.name}', ${wrap}),`;
|
|
467
|
+
}
|
|
468
|
+
return ` ${field.name}: leafFieldArgs<'${field.name}', ${wrap}, ${ts}, ${argTsType(field, ir)}>('${field.name}', ${wrap}, ${argSpec(field, ir)}),`;
|
|
469
|
+
}
|
|
470
|
+
if (field.args.length === 0) {
|
|
471
|
+
return ` get ${field.name}() { return objectField('${field.name}', ${wrap}, ${field.type.name}) },`;
|
|
472
|
+
}
|
|
473
|
+
return ` get ${field.name}() { return objectFieldArgs('${field.name}', ${wrap}, ${field.type.name}, ${argSpec(field, ir)}) },`;
|
|
474
|
+
}
|
|
475
|
+
function emitEnum(t) {
|
|
476
|
+
const members = t.enumValues.map((v) => ` ${v}: '${v}',`).join("\n");
|
|
477
|
+
const union = t.enumValues.map((v) => `'${v}'`).join(" | ") || "never";
|
|
478
|
+
return `export const ${t.name}Values = {
|
|
479
|
+
${members}
|
|
480
|
+
} as const;
|
|
481
|
+
export type ${t.name} = ${union};
|
|
482
|
+
`;
|
|
483
|
+
}
|
|
484
|
+
function emitInput(t, ir) {
|
|
485
|
+
const fields = t.inputFields.map((f) => ` ${f.name}${f.optional ? "?" : ""}: ${inputTsType(f.type, ir)};`).join("\n");
|
|
486
|
+
return `export interface ${t.name} {
|
|
487
|
+
${fields}
|
|
488
|
+
}
|
|
489
|
+
`;
|
|
490
|
+
}
|
|
491
|
+
function emitTypeMap(t, ir) {
|
|
492
|
+
const body = t.fields.map((f) => emitField(f, ir)).join("\n");
|
|
493
|
+
const typename = ` __typename: leafField<'__typename', ['!'], ${typenameTsType(t)}>('__typename', ['!']),`;
|
|
494
|
+
return `export const ${t.name} = {
|
|
495
|
+
${typename}
|
|
496
|
+
${body}
|
|
497
|
+
};
|
|
498
|
+
`;
|
|
499
|
+
}
|
|
500
|
+
function emit(ir, client = "buildgql") {
|
|
501
|
+
assertNoScalarNameCollisions(ir, client);
|
|
502
|
+
const parts = [HEADER, importBlock(client)];
|
|
503
|
+
const prelude = scalarPreludeBlock(ir.scalarPrelude);
|
|
504
|
+
if (prelude.length > 0) parts.push(prelude);
|
|
505
|
+
for (const t of ir.types.filter((t2) => t2.kind === "enum")) parts.push(emitEnum(t));
|
|
506
|
+
for (const t of ir.types.filter((t2) => t2.kind === "input")) parts.push(emitInput(t, ir));
|
|
507
|
+
const composite = ir.types.filter(
|
|
508
|
+
(t) => t.kind === "object" || t.kind === "interface" || t.kind === "union"
|
|
509
|
+
);
|
|
510
|
+
for (const t of composite) parts.push(emitTypeMap(t, ir));
|
|
511
|
+
parts.push(`export const query = makeQuery(${ir.queryType});`);
|
|
512
|
+
if (ir.mutationType) parts.push(`export const mutation = makeMutation(${ir.mutationType});`);
|
|
513
|
+
if (ir.subscriptionType)
|
|
514
|
+
parts.push(`export const subscription = makeSubscription(${ir.subscriptionType});`);
|
|
515
|
+
for (const t of composite) {
|
|
516
|
+
parts.push(`export const ${lowerFirst(t.name)}Fragment = makeFragment('${t.name}', ${t.name});`);
|
|
517
|
+
}
|
|
518
|
+
parts.push(reexportBlock(client));
|
|
519
|
+
return parts.join("\n");
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// src/codegen/ir.ts
|
|
523
|
+
function irKind(kind) {
|
|
524
|
+
switch (kind) {
|
|
525
|
+
case "SCALAR":
|
|
526
|
+
return "scalar";
|
|
527
|
+
case "ENUM":
|
|
528
|
+
return "enum";
|
|
529
|
+
case "INTERFACE":
|
|
530
|
+
return "interface";
|
|
531
|
+
case "UNION":
|
|
532
|
+
return "union";
|
|
533
|
+
case "INPUT_OBJECT":
|
|
534
|
+
return "input";
|
|
535
|
+
default:
|
|
536
|
+
return "object";
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
function flatten(ref, kinds) {
|
|
540
|
+
const wrap = [];
|
|
541
|
+
let cur = ref;
|
|
542
|
+
while (cur) {
|
|
543
|
+
if (cur.kind === "NON_NULL") {
|
|
544
|
+
wrap.push("!");
|
|
545
|
+
cur = cur.ofType;
|
|
546
|
+
} else if (cur.kind === "LIST") {
|
|
547
|
+
wrap.push("l");
|
|
548
|
+
cur = cur.ofType;
|
|
549
|
+
} else {
|
|
550
|
+
const name = cur.name ?? "Unknown";
|
|
551
|
+
return { wrap, name, kind: kinds.get(name) ?? irKind(cur.kind) };
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
throw new Error("buildgql: malformed type reference in introspection result");
|
|
555
|
+
}
|
|
556
|
+
function printGqlType(ref) {
|
|
557
|
+
if (ref.kind === "NON_NULL") return `${printGqlType(ref.ofType)}!`;
|
|
558
|
+
if (ref.kind === "LIST") return `[${printGqlType(ref.ofType)}]`;
|
|
559
|
+
return ref.name ?? "Unknown";
|
|
560
|
+
}
|
|
561
|
+
function toArg(iv, kinds) {
|
|
562
|
+
const nullable = iv.type.kind !== "NON_NULL";
|
|
563
|
+
return {
|
|
564
|
+
name: iv.name,
|
|
565
|
+
type: flatten(iv.type, kinds),
|
|
566
|
+
gqlType: printGqlType(iv.type),
|
|
567
|
+
optional: nullable || iv.defaultValue !== null
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
function buildIR(schema, scalars = resolveScalars()) {
|
|
571
|
+
const relevant = schema.__schema.types.filter((t) => !t.name.startsWith("__"));
|
|
572
|
+
const kinds = new Map(relevant.map((t) => [t.name, irKind(t.kind)]));
|
|
573
|
+
const types = relevant.map((t) => ({
|
|
574
|
+
name: t.name,
|
|
575
|
+
kind: irKind(t.kind),
|
|
576
|
+
description: t.description,
|
|
577
|
+
fields: (t.fields ?? []).map((f) => ({
|
|
578
|
+
name: f.name,
|
|
579
|
+
type: flatten(f.type, kinds),
|
|
580
|
+
gqlType: printGqlType(f.type),
|
|
581
|
+
args: f.args.map((a) => toArg(a, kinds)),
|
|
582
|
+
description: f.description,
|
|
583
|
+
deprecated: f.isDeprecated ? f.deprecationReason ?? "deprecated" : null
|
|
584
|
+
})),
|
|
585
|
+
inputFields: (t.inputFields ?? []).map((a) => toArg(a, kinds)),
|
|
586
|
+
enumValues: (t.enumValues ?? []).map((e) => e.name),
|
|
587
|
+
possibleTypes: (t.possibleTypes ?? []).map((p) => p.name ?? ""),
|
|
588
|
+
interfaces: (t.interfaces ?? []).map((i) => i.name ?? "")
|
|
589
|
+
}));
|
|
590
|
+
return {
|
|
591
|
+
queryType: schema.__schema.queryType.name,
|
|
592
|
+
mutationType: schema.__schema.mutationType?.name ?? null,
|
|
593
|
+
subscriptionType: schema.__schema.subscriptionType?.name ?? null,
|
|
594
|
+
types,
|
|
595
|
+
// A null-prototype target means a scalar legitimately named `toString`, `valueOf`,
|
|
596
|
+
// or `constructor` cannot resolve to an inherited `Object.prototype` member on
|
|
597
|
+
// either an `in`/`Object.hasOwn` membership check or a plain bracket read — there
|
|
598
|
+
// is no prototype chain left to walk. `resolveScalars` has already merged the
|
|
599
|
+
// built-in five underneath the user's overrides.
|
|
600
|
+
scalars: Object.assign(/* @__PURE__ */ Object.create(null), scalars.scalars),
|
|
601
|
+
scalarPrelude: scalars.prelude
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// src/codegen/introspect.ts
|
|
606
|
+
import { readFile } from "fs/promises";
|
|
607
|
+
import { createRequire } from "module";
|
|
608
|
+
import { join as join2 } from "path";
|
|
609
|
+
function isIntrospectionResult(value) {
|
|
610
|
+
return typeof value === "object" && value !== null && "__schema" in value;
|
|
611
|
+
}
|
|
612
|
+
var TYPE_REF = `
|
|
613
|
+
kind name
|
|
614
|
+
ofType { kind name
|
|
615
|
+
ofType { kind name
|
|
616
|
+
ofType { kind name
|
|
617
|
+
ofType { kind name
|
|
618
|
+
ofType { kind name
|
|
619
|
+
ofType { kind name } } } } } }
|
|
620
|
+
`;
|
|
621
|
+
var INTROSPECTION_QUERY = `query IntrospectionQuery {
|
|
622
|
+
__schema {
|
|
623
|
+
queryType { name }
|
|
624
|
+
mutationType { name }
|
|
625
|
+
subscriptionType { name }
|
|
626
|
+
types {
|
|
627
|
+
kind
|
|
628
|
+
name
|
|
629
|
+
description
|
|
630
|
+
fields(includeDeprecated: true) {
|
|
631
|
+
name
|
|
632
|
+
description
|
|
633
|
+
args { name type { ${TYPE_REF} } defaultValue }
|
|
634
|
+
type { ${TYPE_REF} }
|
|
635
|
+
isDeprecated
|
|
636
|
+
deprecationReason
|
|
637
|
+
}
|
|
638
|
+
inputFields { name type { ${TYPE_REF} } defaultValue }
|
|
639
|
+
interfaces { ${TYPE_REF} }
|
|
640
|
+
enumValues(includeDeprecated: true) { name description }
|
|
641
|
+
possibleTypes { ${TYPE_REF} }
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
}`.replace(/\s+/g, " ");
|
|
645
|
+
async function introspectUrl(url, opts) {
|
|
646
|
+
const doFetch = opts.fetch ?? globalThis.fetch;
|
|
647
|
+
const res = await doFetch(url, {
|
|
648
|
+
method: "POST",
|
|
649
|
+
headers: { "content-type": "application/json", accept: "application/json", ...opts.headers ?? {} },
|
|
650
|
+
body: JSON.stringify({ query: INTROSPECTION_QUERY, operationName: "IntrospectionQuery" })
|
|
651
|
+
});
|
|
652
|
+
if (!res.ok) {
|
|
653
|
+
throw new Error(`buildgql: introspection of ${url} failed with HTTP ${res.status}`);
|
|
654
|
+
}
|
|
655
|
+
const raw = await res.text();
|
|
656
|
+
let payload;
|
|
657
|
+
try {
|
|
658
|
+
payload = JSON.parse(raw);
|
|
659
|
+
} catch {
|
|
660
|
+
throw new Error(`buildgql: introspection of ${url} did not return valid JSON: ${raw.slice(0, 200)}`);
|
|
661
|
+
}
|
|
662
|
+
if (payload.errors && payload.errors.length > 0) {
|
|
663
|
+
throw new Error(
|
|
664
|
+
`buildgql: introspection of ${url} failed: ${payload.errors.map((e) => e.message).join("; ")}`
|
|
665
|
+
);
|
|
666
|
+
}
|
|
667
|
+
if (!payload.data?.__schema) {
|
|
668
|
+
throw new Error(`buildgql: introspection of ${url} returned no __schema`);
|
|
669
|
+
}
|
|
670
|
+
return payload.data;
|
|
671
|
+
}
|
|
672
|
+
function isGraphqlModule(value) {
|
|
673
|
+
if (typeof value !== "object" || value === null) return false;
|
|
674
|
+
const mod = value;
|
|
675
|
+
return ["buildSchema", "parse", "executeSync"].every((name) => typeof mod[name] === "function");
|
|
676
|
+
}
|
|
677
|
+
async function importGraphql(cwd) {
|
|
678
|
+
try {
|
|
679
|
+
return await import("graphql");
|
|
680
|
+
} catch {
|
|
681
|
+
}
|
|
682
|
+
if (cwd === void 0) return void 0;
|
|
683
|
+
try {
|
|
684
|
+
const gql = createRequire(join2(cwd, "buildgql-graphql-resolution.cjs"))("graphql");
|
|
685
|
+
return isGraphqlModule(gql) ? gql : void 0;
|
|
686
|
+
} catch {
|
|
687
|
+
return void 0;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
async function introspectSdl(source, opts) {
|
|
691
|
+
const gql = await importGraphql(opts.cwd);
|
|
692
|
+
if (!gql) {
|
|
693
|
+
throw new Error(
|
|
694
|
+
`buildgql: reading "${source}" as SDL needs the optional peer dependency "graphql", which could not be resolved from buildgql${opts.cwd === void 0 ? "" : ` or from ${opts.cwd}`}. Install it (\`npm install --save-dev graphql\`), or point \`schema\` at an introspection .json file or a URL instead. Running buildgql through \`npx\`/\`dlx\` resolves "graphql" from your project directory, so install it there rather than alongside buildgql.`
|
|
695
|
+
);
|
|
696
|
+
}
|
|
697
|
+
const sdl = await readFile(source, "utf8");
|
|
698
|
+
const schema = gql.buildSchema(sdl, { assumeValidSDL: true });
|
|
699
|
+
const result = gql.executeSync({ schema, document: gql.parse(INTROSPECTION_QUERY) }).data;
|
|
700
|
+
if (!isIntrospectionResult(result)) {
|
|
701
|
+
throw new Error(`buildgql: introspection of "${source}" returned no __schema`);
|
|
702
|
+
}
|
|
703
|
+
return result;
|
|
704
|
+
}
|
|
705
|
+
async function introspectJson(source) {
|
|
706
|
+
const raw = JSON.parse(await readFile(source, "utf8"));
|
|
707
|
+
const schema = "__schema" in raw ? raw : raw.data;
|
|
708
|
+
if (!schema?.__schema) {
|
|
709
|
+
throw new Error(`buildgql: "${source}" does not contain an introspection result (no __schema key)`);
|
|
710
|
+
}
|
|
711
|
+
return schema;
|
|
712
|
+
}
|
|
713
|
+
function loadSchema(source, opts = {}) {
|
|
714
|
+
if (/^https?:\/\//.test(source)) return introspectUrl(source, opts);
|
|
715
|
+
if (source.endsWith(".json")) return introspectJson(source);
|
|
716
|
+
return introspectSdl(source, opts);
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// src/codegen/scalar-imports.ts
|
|
720
|
+
import { isAbsolute as isAbsolute2, relative, resolve as resolve2, sep } from "path";
|
|
721
|
+
var defaultPathModule = {
|
|
722
|
+
isAbsolute: isAbsolute2,
|
|
723
|
+
relative,
|
|
724
|
+
resolve: resolve2,
|
|
725
|
+
sep
|
|
726
|
+
};
|
|
727
|
+
function isBareSpecifier(spec, pathModule = defaultPathModule) {
|
|
728
|
+
return !spec.startsWith(".") && !pathModule.isAbsolute(spec);
|
|
729
|
+
}
|
|
730
|
+
function toOutputRelativeSpecifier(spec, configDir, outputDir, pathModule = defaultPathModule) {
|
|
731
|
+
if (isBareSpecifier(spec, pathModule)) return spec;
|
|
732
|
+
const target = pathModule.resolve(configDir, spec);
|
|
733
|
+
const rel = pathModule.relative(outputDir, target).split(pathModule.sep).join("/");
|
|
734
|
+
if (pathModule.isAbsolute(rel)) {
|
|
735
|
+
throw new Error(
|
|
736
|
+
`buildgql: cannot rewrite ${spec} for output: configDir (${configDir}) and outputDir (${outputDir}) have no shared base path (on Windows, they may be on different drives). Use a bare package specifier (e.g. '@myorg/types') or the "declare" config key (e.g. { name: 'Money', declare: '...' }) instead.`
|
|
737
|
+
);
|
|
738
|
+
}
|
|
739
|
+
if (rel.length === 0) return ".";
|
|
740
|
+
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// src/cli/reporter.ts
|
|
744
|
+
var consoleReporter = {
|
|
745
|
+
info(message) {
|
|
746
|
+
process.stdout.write(`${message}
|
|
747
|
+
`);
|
|
748
|
+
},
|
|
749
|
+
warn(message) {
|
|
750
|
+
process.stderr.write(`${message}
|
|
751
|
+
`);
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
|
|
755
|
+
// src/cli/generate.ts
|
|
756
|
+
function resolveSchemaSource(schema, cwd) {
|
|
757
|
+
if (/^https?:\/\//.test(schema)) return schema;
|
|
758
|
+
return isAbsolute3(schema) ? schema : resolve3(cwd, schema);
|
|
759
|
+
}
|
|
760
|
+
async function generate(config, cwd, reporter = consoleReporter) {
|
|
761
|
+
const schema = await loadSchema(resolveSchemaSource(config.schema, cwd), {
|
|
762
|
+
headers: config.headers,
|
|
763
|
+
cwd
|
|
764
|
+
});
|
|
765
|
+
const dir = resolveOutputDir(config, cwd);
|
|
766
|
+
const scalars = resolveScalars(config.scalars, (from) => toOutputRelativeSpecifier(from, cwd, dir));
|
|
767
|
+
const ir = buildIR(schema, scalars);
|
|
768
|
+
const unmapped = unmappedScalars(ir);
|
|
769
|
+
if (unmapped.length > 0) {
|
|
770
|
+
reporter.warn(
|
|
771
|
+
`buildgql: unmapped custom scalar${unmapped.length > 1 ? "s" : ""}: ${unmapped.join(", ")} \u2014 generated as \`unknown\`. Add ${unmapped.length > 1 ? "them" : "it"} to "scalars" in your buildgql.config.* for real types.`
|
|
772
|
+
);
|
|
773
|
+
}
|
|
774
|
+
if (scalars.prelude.imports.length > 0) {
|
|
775
|
+
const modules = [...new Set(scalars.prelude.imports.map((i) => i.from))].sort();
|
|
776
|
+
reporter.info(
|
|
777
|
+
`buildgql: the generated module imports scalar types from ${modules.join(", ")} (relative specifiers are resolved against your config file, then rewritten against "output")`
|
|
778
|
+
);
|
|
779
|
+
}
|
|
780
|
+
const client = config.client ?? "buildgql";
|
|
781
|
+
const { module, names } = CLIENT_EMITS[client];
|
|
782
|
+
if (module && module !== "buildgql") {
|
|
783
|
+
reporter.info(
|
|
784
|
+
`buildgql: client "${client}" \u2014 the generated module re-exports ${names.join(", ")} from ${module} (requires the "graphql" package)`
|
|
785
|
+
);
|
|
786
|
+
}
|
|
787
|
+
const src = emit(ir, client);
|
|
788
|
+
await mkdir(dir, { recursive: true });
|
|
789
|
+
const file = join3(dir, "index.ts");
|
|
790
|
+
await writeFile(file, src, "utf8");
|
|
791
|
+
return file;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
// src/cli/main.ts
|
|
795
|
+
var USAGE = `buildgql \u2014 type-safe GraphQL query builder codegen
|
|
796
|
+
|
|
797
|
+
Usage:
|
|
798
|
+
buildgql generate [--config <dir>] Generate the SDK from buildgql.config.*
|
|
799
|
+
buildgql --help Show this message
|
|
800
|
+
buildgql --version Print the version
|
|
801
|
+
`;
|
|
802
|
+
async function version() {
|
|
803
|
+
const manifest = new URL("../../package.json", import.meta.url);
|
|
804
|
+
const { version: v } = JSON.parse(await readFile2(manifest, "utf8"));
|
|
805
|
+
return v ?? "unknown";
|
|
806
|
+
}
|
|
807
|
+
async function main(argv, reporter = consoleReporter) {
|
|
808
|
+
const cmd = argv[0];
|
|
809
|
+
if (!cmd || cmd === "--help" || cmd === "-h") {
|
|
810
|
+
process.stdout.write(USAGE);
|
|
811
|
+
return cmd ? 0 : 1;
|
|
812
|
+
}
|
|
813
|
+
if (cmd === "--version" || cmd === "-v") {
|
|
814
|
+
process.stdout.write(`${await version()}
|
|
815
|
+
`);
|
|
816
|
+
return 0;
|
|
817
|
+
}
|
|
818
|
+
if (cmd !== "generate") {
|
|
819
|
+
process.stderr.write(`buildgql: unknown command "${cmd}"
|
|
820
|
+
|
|
821
|
+
${USAGE}`);
|
|
822
|
+
return 1;
|
|
823
|
+
}
|
|
824
|
+
const flagIndex = argv.indexOf("--config");
|
|
825
|
+
const cwd = flagIndex !== -1 && argv[flagIndex + 1] ? resolve4(argv[flagIndex + 1]) : process.cwd();
|
|
826
|
+
try {
|
|
827
|
+
const { config, path } = await loadConfig(cwd);
|
|
828
|
+
reporter.info(`buildgql: using ${path}`);
|
|
829
|
+
const out = await generate(config, cwd, reporter);
|
|
830
|
+
reporter.info(`buildgql: wrote ${out}`);
|
|
831
|
+
return 0;
|
|
832
|
+
} catch (err) {
|
|
833
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
834
|
+
reporter.warn(message.startsWith("buildgql: ") ? message : `buildgql: ${message}`);
|
|
835
|
+
return 1;
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// src/cli/bin.ts
|
|
840
|
+
void main(process.argv.slice(2)).then((code) => {
|
|
841
|
+
process.exitCode = code;
|
|
842
|
+
});
|