@gqloom/core 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1198 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/resolver/silk.ts
8
+ import {
9
+ GraphQLNonNull,
10
+ GraphQLList
11
+ } from "graphql";
12
+
13
+ // src/utils/symbols.ts
14
+ var symbols_exports = {};
15
+ __export(symbols_exports, {
16
+ CONTEXT_MEMORY_MAP_KEY: () => CONTEXT_MEMORY_MAP_KEY,
17
+ GET_GRAPHQL_TYPE: () => GET_GRAPHQL_TYPE,
18
+ PARSE: () => PARSE,
19
+ RESOLVER_OPTIONS_KEY: () => RESOLVER_OPTIONS_KEY,
20
+ WEAVER_CONFIG: () => WEAVER_CONFIG
21
+ });
22
+ var GET_GRAPHQL_TYPE = Symbol.for("gqloom.get_graphql_type");
23
+ var PARSE = Symbol.for("gqloom.parse");
24
+ var WEAVER_CONFIG = Symbol.for("gqloom.weaver_config");
25
+ var RESOLVER_OPTIONS_KEY = Symbol.for("gqloom.resolver-options");
26
+ var CONTEXT_MEMORY_MAP_KEY = Symbol.for("gqloom.context-memory");
27
+
28
+ // src/resolver/silk.ts
29
+ function silk(type, parse) {
30
+ return {
31
+ [GET_GRAPHQL_TYPE]: typeof type === "function" ? type : () => type,
32
+ [PARSE]: parse
33
+ };
34
+ }
35
+ silk.parse = parseSilk;
36
+ silk.getType = getGraphQLType;
37
+ silk.nonNull = nonNullSilk;
38
+ silk.list = listSilk;
39
+ silk.nullable = nullableSilk;
40
+ function nonNullSilk(origin) {
41
+ return {
42
+ [GET_GRAPHQL_TYPE]: () => {
43
+ const originType = getGraphQLType(origin);
44
+ if (originType instanceof GraphQLNonNull) {
45
+ return originType;
46
+ } else {
47
+ return new GraphQLNonNull(originType);
48
+ }
49
+ },
50
+ [PARSE]: (input) => origin[PARSE]?.(input)
51
+ };
52
+ }
53
+ function listSilk(origin) {
54
+ return {
55
+ [GET_GRAPHQL_TYPE]: () => {
56
+ let originType = getGraphQLType(origin);
57
+ if (originType instanceof GraphQLNonNull && originType.ofType instanceof GraphQLList) {
58
+ originType = originType.ofType;
59
+ }
60
+ if (originType instanceof GraphQLList) {
61
+ originType = originType.ofType;
62
+ }
63
+ return new GraphQLNonNull(new GraphQLList(originType));
64
+ }
65
+ };
66
+ }
67
+ function nullableSilk(origin) {
68
+ return {
69
+ [GET_GRAPHQL_TYPE]: () => {
70
+ const originType = getGraphQLType(origin);
71
+ if (originType instanceof GraphQLNonNull) {
72
+ return originType.ofType;
73
+ } else {
74
+ return originType;
75
+ }
76
+ },
77
+ [PARSE]: (input) => origin[PARSE]?.(input)
78
+ };
79
+ }
80
+ function getGraphQLType(silk2) {
81
+ return silk2[GET_GRAPHQL_TYPE]();
82
+ }
83
+ function parseSilk(silk2, input) {
84
+ if (silk2[PARSE] == null) return input;
85
+ return silk2[PARSE](input);
86
+ }
87
+ function isSilk(target) {
88
+ if (typeof target !== "object") return false;
89
+ if (target == null) return false;
90
+ return GET_GRAPHQL_TYPE in target;
91
+ }
92
+
93
+ // src/utils/args.ts
94
+ function getOperationOptions(resolveOrOptions) {
95
+ if (typeof resolveOrOptions === "function") {
96
+ return { resolve: resolveOrOptions };
97
+ }
98
+ return resolveOrOptions;
99
+ }
100
+ function getSubscriptionOptions(subscribeOrOptions) {
101
+ if (typeof subscribeOrOptions === "function") {
102
+ return { subscribe: subscribeOrOptions };
103
+ }
104
+ return subscribeOrOptions;
105
+ }
106
+ function getFieldOptions({
107
+ description,
108
+ deprecationReason,
109
+ extensions
110
+ }) {
111
+ return {
112
+ description,
113
+ deprecationReason,
114
+ extensions
115
+ };
116
+ }
117
+
118
+ // src/utils/middleware.ts
119
+ function applyMiddlewares(middlewares, resolveFunction, payload) {
120
+ const next = (index) => {
121
+ if (index >= middlewares.length) {
122
+ return resolveFunction();
123
+ }
124
+ const middleware = middlewares[index];
125
+ return middleware(() => next(index + 1), payload);
126
+ };
127
+ return next(0);
128
+ }
129
+ function compose(...lists) {
130
+ const list = [];
131
+ for (const item of lists) {
132
+ if (item != null) {
133
+ list.push(...item);
134
+ }
135
+ }
136
+ return list;
137
+ }
138
+
139
+ // src/utils/context.ts
140
+ import { AsyncLocalStorage } from "async_hooks";
141
+ function onlyMemoization() {
142
+ return { memoization: /* @__PURE__ */ new WeakMap(), isMemoization: true };
143
+ }
144
+ function isOnlyMemoryPayload(payload) {
145
+ return payload.isMemoization === true;
146
+ }
147
+ var resolverPayloadStorage = new AsyncLocalStorage();
148
+ function useResolverPayload() {
149
+ const payload = resolverPayloadStorage.getStore();
150
+ if (payload === void 0 || isOnlyMemoryPayload(payload)) return;
151
+ return payload;
152
+ }
153
+ function useContext() {
154
+ return useResolverPayload()?.context;
155
+ }
156
+ function useMemoizationMap() {
157
+ const payload = resolverPayloadStorage.getStore();
158
+ if (payload == null) return;
159
+ if (isOnlyMemoryPayload(payload)) return payload.memoization;
160
+ return ContextMemoization.assignMemoizationMap(payload.context);
161
+ }
162
+ var ContextMemoization = class {
163
+ constructor(getter, options = {}) {
164
+ this.getter = getter;
165
+ this.getter = getter;
166
+ this.getMemoizationMap = options.getMemoizationMap ?? useMemoizationMap;
167
+ this.key = options.key ?? this.getter;
168
+ }
169
+ getMemoizationMap;
170
+ key;
171
+ /**
172
+ * Get the value in memoization or call the getter function
173
+ * @returns the value of the getter function
174
+ */
175
+ get() {
176
+ const map = this.getMemoizationMap();
177
+ if (!map) return this.getter();
178
+ if (!map.has(this.key)) {
179
+ map.set(this.key, this.getter());
180
+ }
181
+ return map.get(this.key);
182
+ }
183
+ /**
184
+ * Clear the memoization
185
+ * @returns true if the memoization is cleared, undefined if the context is not found
186
+ */
187
+ clear() {
188
+ const map = this.getMemoizationMap();
189
+ if (!map) return;
190
+ return map.delete(this.key);
191
+ }
192
+ /**
193
+ * Check if the memoization exists
194
+ * @returns true if the memoization exists, undefined if the context is not found
195
+ */
196
+ exists() {
197
+ const map = this.getMemoizationMap();
198
+ if (!map) return;
199
+ return map.has(this.key);
200
+ }
201
+ /**
202
+ * Set a new value to the memoization
203
+ * @param value the new value to set
204
+ * @returns the memoization map or undefined if the context is not found
205
+ */
206
+ set(value) {
207
+ const map = this.getMemoizationMap();
208
+ if (!map) return;
209
+ return map.set(this.key, value);
210
+ }
211
+ static assignMemoizationMap(target) {
212
+ target[CONTEXT_MEMORY_MAP_KEY] ??= /* @__PURE__ */ new WeakMap();
213
+ return target[CONTEXT_MEMORY_MAP_KEY];
214
+ }
215
+ };
216
+ function createMemoization(...args) {
217
+ const memoization = new ContextMemoization(...args);
218
+ const callable = () => memoization.get();
219
+ return Object.assign(callable, {
220
+ get: () => memoization.get(),
221
+ set: (value) => memoization.set(value),
222
+ clear: () => memoization.clear(),
223
+ exists: () => memoization.exists(),
224
+ getter: memoization.getter
225
+ });
226
+ }
227
+
228
+ // src/utils/object.ts
229
+ function mapValue(record, fn) {
230
+ const result = /* @__PURE__ */ Object.create(null);
231
+ for (const key of Object.keys(record)) {
232
+ const value = fn(record[key], key);
233
+ if (value === SKIP) continue;
234
+ result[key] = value;
235
+ }
236
+ return result;
237
+ }
238
+ var SKIP = Symbol.for("mapValue.skip");
239
+ mapValue.SKIP = SKIP;
240
+ function toObjMap(obj) {
241
+ if (obj == null) {
242
+ return /* @__PURE__ */ Object.create(null);
243
+ }
244
+ if (Object.getPrototypeOf(obj) === null) {
245
+ return obj;
246
+ }
247
+ const map = /* @__PURE__ */ Object.create(null);
248
+ for (const [key, value] of Object.entries(obj)) {
249
+ map[key] = value;
250
+ }
251
+ return map;
252
+ }
253
+ function notNullish(x) {
254
+ return x != null;
255
+ }
256
+ function deepMerge(...objects) {
257
+ const result = {};
258
+ for (const obj of objects) {
259
+ if (obj == null) continue;
260
+ for (const [key, value] of Object.entries(obj)) {
261
+ if (value !== null && typeof value === "object") {
262
+ if (Array.isArray(value)) {
263
+ if (!Array.isArray(result[key])) {
264
+ result[key] = [];
265
+ }
266
+ result[key] = [...result[key], ...value];
267
+ } else {
268
+ result[key] = deepMerge(result[key], value);
269
+ }
270
+ } else {
271
+ result[key] = value;
272
+ }
273
+ }
274
+ }
275
+ return result;
276
+ }
277
+
278
+ // src/utils/error.ts
279
+ function markErrorLocation(error, ...locations) {
280
+ if (error instanceof Error) {
281
+ error.message = markLocation(error.message, ...locations);
282
+ }
283
+ return error;
284
+ }
285
+ function tryIn(func, ...locations) {
286
+ try {
287
+ return func();
288
+ } catch (error) {
289
+ throw markErrorLocation(error, ...locations);
290
+ }
291
+ }
292
+ function markLocation(message, ...locations) {
293
+ if (locations.length === 0) {
294
+ return message;
295
+ }
296
+ const [existingPrefix, newMessage] = (() => {
297
+ const existingPrefixPattern = /^\[(.*?)\]/;
298
+ const match = existingPrefixPattern.exec(message);
299
+ if (match) return [match[1], message.slice(match[0].length).trim()];
300
+ return [void 0, message];
301
+ })();
302
+ const combinedLocation = locations.concat(existingPrefix ? [existingPrefix] : []).join(".");
303
+ return `[${combinedLocation}] ${newMessage}`;
304
+ }
305
+
306
+ // src/resolver/input.ts
307
+ function createInputParser(schema, value) {
308
+ let result;
309
+ const parse = async () => {
310
+ if (result !== void 0) return result;
311
+ result = await parseInputValue(schema, value);
312
+ return result;
313
+ };
314
+ Object.assign(parse, { schema, value });
315
+ Object.defineProperty(parse, "result", {
316
+ get: () => result,
317
+ set: (value2) => result = value2
318
+ });
319
+ return parse;
320
+ }
321
+ function parseInputValue(inputSchema, input) {
322
+ if (inputSchema === void 0) {
323
+ return input;
324
+ }
325
+ if (isSilk(inputSchema)) {
326
+ if (typeof inputSchema[symbols_exports.PARSE] === "function") {
327
+ return inputSchema[symbols_exports.PARSE](input);
328
+ }
329
+ return input;
330
+ }
331
+ return parseInputEntries(inputSchema, input);
332
+ }
333
+ async function parseInputEntries(inputSchema, input = {}) {
334
+ const result = {};
335
+ await Promise.all(
336
+ Object.entries(inputSchema).map(async ([key, value]) => {
337
+ if (typeof value[symbols_exports.PARSE] === "function") {
338
+ result[key] = await value[symbols_exports.PARSE](input[key]);
339
+ } else {
340
+ result[key] = input[key];
341
+ }
342
+ })
343
+ );
344
+ return result;
345
+ }
346
+
347
+ // src/resolver/resolver.ts
348
+ var silkQuery = (output, resolveOrOptions) => {
349
+ const options = getOperationOptions(resolveOrOptions);
350
+ const type = "query";
351
+ return {
352
+ ...getFieldOptions(options),
353
+ input: options.input,
354
+ output,
355
+ resolve: (inputValue, extraOptions) => {
356
+ const parseInput = createInputParser(options.input, inputValue);
357
+ return applyMiddlewares(
358
+ compose(extraOptions?.middlewares, options.middlewares),
359
+ async () => options.resolve(await parseInput()),
360
+ { parseInput, parent: void 0, outputSilk: output, type }
361
+ );
362
+ },
363
+ type
364
+ };
365
+ };
366
+ var silkMutation = (output, resolveOrOptions) => {
367
+ const options = getOperationOptions(resolveOrOptions);
368
+ const type = "mutation";
369
+ return {
370
+ ...getFieldOptions(options),
371
+ input: options.input,
372
+ output,
373
+ resolve: (inputValue, extraOptions) => {
374
+ const parseInput = createInputParser(options.input, inputValue);
375
+ return applyMiddlewares(
376
+ compose(extraOptions?.middlewares, options.middlewares),
377
+ async () => options.resolve(await parseInput()),
378
+ { parseInput, parent: void 0, outputSilk: output, type }
379
+ );
380
+ },
381
+ type
382
+ };
383
+ };
384
+ var silkField = (output, resolveOrOptions) => {
385
+ const options = getOperationOptions(resolveOrOptions);
386
+ const type = "field";
387
+ return {
388
+ ...getFieldOptions(options),
389
+ input: options.input,
390
+ output,
391
+ resolve: (parent, inputValue, extraOptions) => {
392
+ const parseInput = createInputParser(options.input, inputValue);
393
+ return applyMiddlewares(
394
+ compose(extraOptions?.middlewares, options.middlewares),
395
+ async () => options.resolve(parent, await parseInput()),
396
+ { parseInput, parent, outputSilk: output, type }
397
+ );
398
+ },
399
+ type
400
+ };
401
+ };
402
+ var defaultSubscriptionResolve = (source) => source;
403
+ var silkSubscription = (output, subscribeOrOptions) => {
404
+ const options = getSubscriptionOptions(subscribeOrOptions);
405
+ const type = "subscription";
406
+ return {
407
+ ...getFieldOptions(options),
408
+ input: options.input,
409
+ output,
410
+ subscribe: (inputValue, extraOptions) => {
411
+ const parseInput = createInputParser(options.input, inputValue);
412
+ return applyMiddlewares(
413
+ compose(
414
+ extraOptions?.middlewares,
415
+ options.middlewares
416
+ ),
417
+ async () => options.subscribe(await parseInput()),
418
+ { parseInput, parent: void 0, outputSilk: output, type }
419
+ );
420
+ },
421
+ resolve: options.resolve ?? defaultSubscriptionResolve,
422
+ type
423
+ };
424
+ };
425
+ var ResolverOptionsMap = /* @__PURE__ */ new WeakMap();
426
+ function baseResolver(operations, options) {
427
+ const record = {};
428
+ Object.entries(operations).forEach(([name, operation]) => {
429
+ record[name] = extraOperationOptions(operation, options);
430
+ });
431
+ if (options) ResolverOptionsMap.set(record, options);
432
+ return record;
433
+ }
434
+ function extraOperationOptions(operation, options) {
435
+ const composeMiddlewares = (extraOptions) => compose(extraOptions?.middlewares, options?.middlewares);
436
+ switch (operation.type) {
437
+ case "field":
438
+ return {
439
+ ...operation,
440
+ resolve: (parent, input, extraOptions) => operation.resolve(parent, input, {
441
+ ...extraOptions,
442
+ middlewares: composeMiddlewares(extraOptions)
443
+ })
444
+ };
445
+ case "subscription":
446
+ return {
447
+ ...operation,
448
+ subscribe: (input, extraOptions) => operation.subscribe(input, {
449
+ ...extraOptions,
450
+ middlewares: composeMiddlewares(extraOptions)
451
+ })
452
+ };
453
+ default:
454
+ return {
455
+ ...operation,
456
+ resolve: (input, extraOptions) => operation.resolve(input, {
457
+ ...extraOptions,
458
+ middlewares: composeMiddlewares(extraOptions)
459
+ })
460
+ };
461
+ }
462
+ }
463
+ var silkResolver = Object.assign(
464
+ baseResolver,
465
+ {
466
+ of: (parent, operations, options) => baseResolver(
467
+ operations,
468
+ { ...options, parent }
469
+ )
470
+ }
471
+ );
472
+ var loom = {
473
+ query: silkQuery,
474
+ resolver: silkResolver,
475
+ field: silkField,
476
+ subscription: silkSubscription,
477
+ mutation: silkMutation
478
+ };
479
+
480
+ // src/helper/create-loom.ts
481
+ function toSilkInput(schema, toSilk, isSchema) {
482
+ if (schema == null) {
483
+ return schema;
484
+ }
485
+ if (isSchema(schema)) {
486
+ return toSilk(schema);
487
+ }
488
+ const record = {};
489
+ for (const [key, value] of Object.entries(schema)) {
490
+ record[key] = toSilk(value);
491
+ }
492
+ return record;
493
+ }
494
+ function createResolverBobbin(toSilk) {
495
+ return Object.assign(baseResolver, {
496
+ of: (parent, operations, options) => baseResolver(
497
+ operations,
498
+ { ...options, parent: toSilk(parent) }
499
+ )
500
+ });
501
+ }
502
+ function createFieldBobbin(toSilk, isSchema) {
503
+ return (output, resolveOrOptions) => {
504
+ const options = getOperationOptions(
505
+ resolveOrOptions
506
+ );
507
+ return silkField(toSilk(output), {
508
+ ...options,
509
+ input: toSilkInput(options.input, toSilk, isSchema)
510
+ });
511
+ };
512
+ }
513
+ function createQueryBobbin(toSilk, isSchema) {
514
+ return (output, resolveOrOptions) => {
515
+ const options = getOperationOptions(resolveOrOptions);
516
+ return silkQuery(toSilk(output), {
517
+ ...options,
518
+ input: toSilkInput(options.input, toSilk, isSchema)
519
+ });
520
+ };
521
+ }
522
+ function createMutationBobbin(toSilk, isSchema) {
523
+ return (output, resolveOrOptions) => {
524
+ const options = getOperationOptions(resolveOrOptions);
525
+ return silkMutation(toSilk(output), {
526
+ ...options,
527
+ input: toSilkInput(options.input, toSilk, isSchema)
528
+ });
529
+ };
530
+ }
531
+ function createSubscriptionBobbin(toSilk, isSchema) {
532
+ return (output, resolveOrOptions) => {
533
+ const options = getSubscriptionOptions(resolveOrOptions);
534
+ return silkSubscription(toSilk(output), {
535
+ ...options,
536
+ input: toSilkInput(options.input, toSilk, isSchema)
537
+ });
538
+ };
539
+ }
540
+ function createLoom(toSilk, isSchema) {
541
+ return {
542
+ query: createQueryBobbin(toSilk, isSchema),
543
+ mutation: createMutationBobbin(toSilk, isSchema),
544
+ field: createFieldBobbin(toSilk, isSchema),
545
+ resolver: createResolverBobbin(toSilk),
546
+ subscription: createSubscriptionBobbin(toSilk, isSchema)
547
+ };
548
+ }
549
+
550
+ // src/schema/object.ts
551
+ import {
552
+ GraphQLObjectType,
553
+ assertName,
554
+ isObjectType as isObjectType3,
555
+ resolveObjMapThunk,
556
+ isListType as isListType2,
557
+ GraphQLList as GraphQLList3,
558
+ GraphQLNonNull as GraphQLNonNull3,
559
+ isNonNullType as isNonNullType2,
560
+ isUnionType as isUnionType3,
561
+ GraphQLUnionType
562
+ } from "graphql";
563
+
564
+ // src/schema/weaver-context.ts
565
+ import {
566
+ isEnumType,
567
+ isObjectType,
568
+ isUnionType
569
+ } from "graphql";
570
+ var ref;
571
+ var names = /* @__PURE__ */ new WeakMap();
572
+ function initWeaverContext() {
573
+ return {
574
+ loomObjectMap: /* @__PURE__ */ new Map(),
575
+ loomUnionMap: /* @__PURE__ */ new Map(),
576
+ inputMap: /* @__PURE__ */ new Map(),
577
+ interfaceMap: /* @__PURE__ */ new Map(),
578
+ configs: /* @__PURE__ */ new Map(),
579
+ getConfig(key) {
580
+ return this.configs.get(key);
581
+ },
582
+ setConfig(config) {
583
+ const key = config[WEAVER_CONFIG];
584
+ this.configs.set(key, config);
585
+ },
586
+ deleteConfig(key) {
587
+ this.configs.delete(key);
588
+ },
589
+ names,
590
+ namedTypes: /* @__PURE__ */ new Map(),
591
+ memoNamedType(gqlTypeValue) {
592
+ const gqlType = gqlTypeValue;
593
+ if (isObjectType(gqlType) || isUnionType(gqlType) || isEnumType(gqlType)) {
594
+ this.namedTypes.set(gqlType.name, gqlType);
595
+ }
596
+ return gqlTypeValue;
597
+ },
598
+ getNamedType(name) {
599
+ return this.namedTypes.get(name);
600
+ }
601
+ };
602
+ }
603
+ var weaverContext = {
604
+ get loomObjectMap() {
605
+ return ref?.loomObjectMap;
606
+ },
607
+ get loomUnionMap() {
608
+ return ref?.loomUnionMap;
609
+ },
610
+ get inputMap() {
611
+ return ref?.inputMap;
612
+ },
613
+ get interfaceMap() {
614
+ return ref?.interfaceMap;
615
+ },
616
+ get configs() {
617
+ return ref?.configs;
618
+ },
619
+ getConfig(key) {
620
+ return ref?.getConfig(key);
621
+ },
622
+ setConfig(config) {
623
+ ref?.setConfig(config);
624
+ },
625
+ deleteConfig(key) {
626
+ ref?.deleteConfig(key);
627
+ },
628
+ get value() {
629
+ return ref;
630
+ },
631
+ useConfig(config, callback) {
632
+ const context = weaverContext.value ?? initWeaverContext();
633
+ context.setConfig(config);
634
+ const result = provideWeaverContext(callback, context);
635
+ context.deleteConfig(config[WEAVER_CONFIG]);
636
+ return result;
637
+ },
638
+ names,
639
+ getNamedType(name) {
640
+ return ref?.getNamedType(name);
641
+ },
642
+ memoNamedType(gqlType) {
643
+ return ref?.memoNamedType(gqlType) ?? gqlType;
644
+ },
645
+ GraphQLTypes: /* @__PURE__ */ new WeakMap(),
646
+ getGraphQLType(origin) {
647
+ return this.GraphQLTypes.get(origin);
648
+ },
649
+ memoGraphQLType(origin, gqlType) {
650
+ this.GraphQLTypes.set(origin, gqlType);
651
+ return gqlType;
652
+ }
653
+ };
654
+ function provideWeaverContext(func, value) {
655
+ const lastRef = ref;
656
+ ref = value;
657
+ try {
658
+ return func();
659
+ } finally {
660
+ ref = lastRef;
661
+ }
662
+ }
663
+ function collectNames(...namesList) {
664
+ const namesRecord = {};
665
+ for (const namesItem of namesList) {
666
+ for (const [name, schema] of Object.entries(namesItem)) {
667
+ names.set(schema, name);
668
+ namesRecord[name] = schema;
669
+ }
670
+ }
671
+ return namesRecord;
672
+ }
673
+
674
+ // src/schema/input.ts
675
+ import {
676
+ GraphQLInputObjectType,
677
+ GraphQLList as GraphQLList2,
678
+ GraphQLNonNull as GraphQLNonNull2,
679
+ isInterfaceType,
680
+ isListType,
681
+ isNonNullType,
682
+ isObjectType as isObjectType2,
683
+ isUnionType as isUnionType2,
684
+ isInputObjectType
685
+ } from "graphql";
686
+ function inputToArgs(input) {
687
+ if (input === void 0) return void 0;
688
+ if (isSilk(input)) {
689
+ let inputType = getGraphQLType(input);
690
+ if (isNonNullType(inputType)) inputType = inputType.ofType;
691
+ if (isObjectType2(inputType)) {
692
+ return mapValue(
693
+ inputType.toConfig().fields,
694
+ (it) => toInputFieldConfig(it)
695
+ );
696
+ }
697
+ throw new Error(`Cannot convert ${inputType.toString()} to input type`);
698
+ }
699
+ const args = {};
700
+ Object.entries(input).forEach(([name, field]) => {
701
+ tryIn(() => {
702
+ args[name] = {
703
+ ...field,
704
+ type: ensureInputType(field)
705
+ };
706
+ }, name);
707
+ });
708
+ return args;
709
+ }
710
+ function ensureInputType(silkOrType) {
711
+ const gqlType = (() => {
712
+ if (isSilk(silkOrType)) {
713
+ return getGraphQLType(silkOrType);
714
+ }
715
+ return silkOrType;
716
+ })();
717
+ if (isUnionType2(gqlType))
718
+ throw new Error(`Cannot convert union type ${gqlType.name} to input type`);
719
+ if (isNonNullType(gqlType)) {
720
+ return new GraphQLNonNull2(ensureInputType(gqlType.ofType));
721
+ }
722
+ if (isListType(gqlType)) {
723
+ return new GraphQLList2(ensureInputType(gqlType.ofType));
724
+ }
725
+ if (isObjectType2(gqlType) || isInterfaceType(gqlType))
726
+ return ensureInputObjectType(gqlType);
727
+ return gqlType;
728
+ }
729
+ function ensureInputObjectType(object) {
730
+ if (isInputObjectType(object)) return object;
731
+ const existing = weaverContext.inputMap?.get(object);
732
+ if (existing != null) return existing;
733
+ const {
734
+ astNode: _,
735
+ extensionASTNodes: __,
736
+ fields,
737
+ ...config
738
+ } = object.toConfig();
739
+ const getInputObjectName = weaverContext.getConfig("gqloom.core.schema")?.getInputObjectName ?? ((name) => name);
740
+ const input = new GraphQLInputObjectType({
741
+ ...config,
742
+ name: getInputObjectName(object.name),
743
+ fields: mapValue(fields, (it) => toInputFieldConfig(it))
744
+ });
745
+ weaverContext.inputMap?.set(object, input);
746
+ return input;
747
+ }
748
+ function toInputFieldConfig({
749
+ astNode: _,
750
+ resolve: _1,
751
+ ...config
752
+ }) {
753
+ return { ...config, type: ensureInputType(config.type) };
754
+ }
755
+
756
+ // src/schema/object.ts
757
+ var LoomObjectType = class extends GraphQLObjectType {
758
+ extraFields = /* @__PURE__ */ new Map();
759
+ weaverContext;
760
+ resolverOptions;
761
+ constructor(objectOrGetter, options = {}) {
762
+ const origin = typeof objectOrGetter === "function" ? objectOrGetter() : objectOrGetter;
763
+ const config = (() => {
764
+ if (isObjectType3(origin)) {
765
+ return origin.toConfig();
766
+ } else if (typeof origin === "string") {
767
+ return { name: origin, fields: {} };
768
+ } else {
769
+ return origin;
770
+ }
771
+ })();
772
+ super(config);
773
+ this.resolverOptions = options.resolverOptions;
774
+ this.weaverContext = options.weaverContext ?? initWeaverContext();
775
+ }
776
+ addField(name, resolver) {
777
+ const existing = this.extraFields.get(name);
778
+ if (existing && existing !== resolver) {
779
+ throw new Error(`Field ${name} already exists in ${this.name}`);
780
+ }
781
+ this.extraFields.set(name, resolver);
782
+ }
783
+ mergeExtensions(extensions) {
784
+ this.extensions = deepMerge(this.extensions, extensions);
785
+ }
786
+ extraField;
787
+ getFields() {
788
+ const fields = super.getFields();
789
+ Object.values(fields).forEach(
790
+ (field) => field.type = this.getCacheType(field.type)
791
+ );
792
+ const extraField = provideWeaverContext(
793
+ () => defineFieldMap(this.mapToFieldConfig(this.extraFields)),
794
+ this.weaverContext
795
+ );
796
+ if (Object.keys(this.extraField ?? {}).join() !== Object.keys(extraField).join()) {
797
+ this.extraField = extraField;
798
+ }
799
+ return {
800
+ ...fields,
801
+ ...this.extraField
802
+ };
803
+ }
804
+ mapToFieldConfig(map) {
805
+ const record = {};
806
+ for (const [name, field] of map.entries()) {
807
+ record[name] = this.toFieldConfig(field);
808
+ }
809
+ return record;
810
+ }
811
+ toFieldConfig(field) {
812
+ try {
813
+ const outputType = this.getCacheType(getGraphQLType(field.output));
814
+ return {
815
+ ...extract(field),
816
+ type: outputType,
817
+ args: inputToArgs(field.input),
818
+ ...this.provideForResolve(field),
819
+ ...this.provideForSubscribe(field)
820
+ };
821
+ } catch (error) {
822
+ throw markErrorLocation(error);
823
+ }
824
+ }
825
+ provideForResolve(field) {
826
+ if (field?.resolve == null) return;
827
+ if (field.resolve === defaultSubscriptionResolve)
828
+ return { resolve: defaultSubscriptionResolve };
829
+ const resolve = field.type === "field" ? (root, args, context, info) => resolverPayloadStorage.run(
830
+ { root, args, context, info, field },
831
+ () => field.resolve(root, args, this.resolverOptions)
832
+ ) : field.type === "subscription" ? (root, args, context, info) => resolverPayloadStorage.run(
833
+ { root, args, context, info, field },
834
+ () => field.resolve(root, args)
835
+ ) : (root, args, context, info) => resolverPayloadStorage.run(
836
+ { root, args, context, info, field },
837
+ () => field.resolve(args, this.resolverOptions)
838
+ );
839
+ return { resolve };
840
+ }
841
+ provideForSubscribe(field) {
842
+ if (field?.subscribe == null) return;
843
+ return {
844
+ subscribe: (root, args, context, info) => resolverPayloadStorage.run(
845
+ { root, args, context, info, field },
846
+ () => field.subscribe?.(args, this.resolverOptions)
847
+ )
848
+ };
849
+ }
850
+ getCacheType(gqlType) {
851
+ return getCacheType(gqlType, this.options);
852
+ }
853
+ get options() {
854
+ const { resolverOptions, weaverContext: weaverContext2 } = this;
855
+ return { resolverOptions, weaverContext: weaverContext2 };
856
+ }
857
+ };
858
+ function extract({
859
+ deprecationReason,
860
+ description,
861
+ extensions
862
+ }) {
863
+ return {
864
+ description,
865
+ deprecationReason,
866
+ extensions
867
+ };
868
+ }
869
+ function defineFieldMap(fields) {
870
+ const fieldMap = resolveObjMapThunk(fields);
871
+ return mapValue(fieldMap, (fieldConfig, fieldName) => {
872
+ const argsConfig = fieldConfig.args ?? {};
873
+ return {
874
+ name: assertName(fieldName),
875
+ description: fieldConfig.description,
876
+ type: fieldConfig.type,
877
+ args: defineArguments(argsConfig),
878
+ resolve: fieldConfig.resolve,
879
+ subscribe: fieldConfig.subscribe,
880
+ deprecationReason: fieldConfig.deprecationReason,
881
+ extensions: toObjMap(fieldConfig.extensions),
882
+ astNode: fieldConfig.astNode
883
+ };
884
+ });
885
+ }
886
+ function defineArguments(args) {
887
+ return Object.entries(args).map(([argName, argConfig]) => ({
888
+ name: assertName(argName),
889
+ description: argConfig.description,
890
+ type: argConfig.type,
891
+ defaultValue: argConfig.defaultValue,
892
+ deprecationReason: argConfig.deprecationReason,
893
+ extensions: toObjMap(argConfig.extensions),
894
+ astNode: argConfig.astNode
895
+ }));
896
+ }
897
+ function getCacheType(gqlType, options = {}) {
898
+ const context = options.weaverContext ?? weaverContext;
899
+ if (gqlType instanceof LoomObjectType) return gqlType;
900
+ if (isObjectType3(gqlType)) {
901
+ const gqlObject = context.loomObjectMap?.get(gqlType);
902
+ if (gqlObject != null) return gqlObject;
903
+ const loomObject = new LoomObjectType(gqlType, options);
904
+ context.loomObjectMap?.set(gqlType, loomObject);
905
+ return loomObject;
906
+ } else if (isListType2(gqlType)) {
907
+ return new GraphQLList3(getCacheType(gqlType.ofType, options));
908
+ } else if (isNonNullType2(gqlType)) {
909
+ return new GraphQLNonNull3(getCacheType(gqlType.ofType, options));
910
+ } else if (isUnionType3(gqlType)) {
911
+ const existing = context.loomUnionMap?.get(gqlType);
912
+ if (existing != null) return existing;
913
+ const config = gqlType.toConfig();
914
+ const unionType = new GraphQLUnionType({
915
+ ...config,
916
+ types: config.types.map(
917
+ (type) => getCacheType(type, options)
918
+ )
919
+ });
920
+ context.loomUnionMap?.set(gqlType, unionType);
921
+ return unionType;
922
+ }
923
+ return gqlType;
924
+ }
925
+
926
+ // src/schema/schema-weaver.ts
927
+ import {
928
+ GraphQLSchema,
929
+ isObjectType as isObjectType4,
930
+ isNonNullType as isNonNullType3,
931
+ isEnumType as isEnumType2,
932
+ isUnionType as isUnionType4
933
+ } from "graphql";
934
+ var SchemaWeaver = class _SchemaWeaver {
935
+ query;
936
+ mutation;
937
+ subscription;
938
+ types;
939
+ context;
940
+ resolverOptions;
941
+ /**
942
+ * Create a Schema Weaver config object
943
+ * @param config Schema Weaver config options
944
+ * @returns a Schema Weaver config object
945
+ */
946
+ static config(config) {
947
+ return {
948
+ ...config,
949
+ [WEAVER_CONFIG]: "gqloom.core.schema"
950
+ };
951
+ }
952
+ constructor({ query, mutation, subscription, types } = {}, context) {
953
+ if (query != null) this.query = query;
954
+ if (mutation != null) this.mutation = mutation;
955
+ if (subscription != null) this.subscription = subscription;
956
+ if (types != null) this.types = types.slice();
957
+ this.context = context ?? initWeaverContext();
958
+ }
959
+ use(...middlewares) {
960
+ this.resolverOptions ??= {};
961
+ this.resolverOptions.middlewares ??= [];
962
+ this.resolverOptions.middlewares.push(...middlewares);
963
+ return this;
964
+ }
965
+ add(resolver) {
966
+ provideWeaverContext(() => this.addResolver(resolver), this.context);
967
+ return this;
968
+ }
969
+ addType(silk2) {
970
+ const gqlType = provideWeaverContext(() => {
971
+ let gqlType2 = getGraphQLType(silk2);
972
+ if (isNonNullType3(gqlType2)) gqlType2 = gqlType2.ofType;
973
+ if (isObjectType4(gqlType2)) {
974
+ const existing = this.context.loomObjectMap.get(gqlType2);
975
+ if (existing != null) return existing;
976
+ const extraObject = new LoomObjectType(gqlType2, this.fieldOptions);
977
+ this.context.loomObjectMap.set(gqlType2, extraObject);
978
+ return extraObject;
979
+ } else if (isUnionType4(gqlType2) || isEnumType2(gqlType2)) {
980
+ return gqlType2;
981
+ }
982
+ throw new Error(
983
+ `${gqlType2?.name ?? gqlType2.toString()} is not a named type`
984
+ );
985
+ }, this.context);
986
+ this.types ??= [];
987
+ this.types.push(gqlType);
988
+ return this;
989
+ }
990
+ setConfig(config) {
991
+ this.context.setConfig(config);
992
+ return this;
993
+ }
994
+ weaveGraphQLSchema() {
995
+ const { query, mutation, subscription, types } = this;
996
+ const config = this.context.getConfig("gqloom.core.schema");
997
+ const schema = new GraphQLSchema({
998
+ query,
999
+ mutation,
1000
+ subscription,
1001
+ types: [...types ?? [], ...config?.types ?? []],
1002
+ ...config
1003
+ });
1004
+ return schema;
1005
+ }
1006
+ addResolver(resolver) {
1007
+ const resolverOptions = ResolverOptionsMap.get(resolver);
1008
+ const parent = resolverOptions?.parent;
1009
+ const parentObject = (() => {
1010
+ if (parent == null) return void 0;
1011
+ let gqlType = getGraphQLType(parent);
1012
+ if (isNonNullType3(gqlType)) gqlType = gqlType.ofType;
1013
+ if (isObjectType4(gqlType)) {
1014
+ const existing = this.context.loomObjectMap.get(gqlType);
1015
+ if (existing != null) return existing;
1016
+ const extraObject = new LoomObjectType(gqlType, this.fieldOptions);
1017
+ this.context.loomObjectMap.set(gqlType, extraObject);
1018
+ return extraObject;
1019
+ }
1020
+ throw new Error(
1021
+ `${gqlType?.name ?? gqlType.toString()} is not an object type`
1022
+ );
1023
+ })();
1024
+ if (resolverOptions?.extensions && parentObject)
1025
+ parentObject.mergeExtensions(resolverOptions.extensions);
1026
+ Object.entries(resolver).forEach(([name, operation]) => {
1027
+ if (operation.type === "field") {
1028
+ if (parentObject == null) return;
1029
+ parentObject.addField(name, operation);
1030
+ } else {
1031
+ const operationObject = this.getOperationObject(operation.type);
1032
+ operationObject.addField(name, operation);
1033
+ }
1034
+ });
1035
+ return this;
1036
+ }
1037
+ getOperationObject(type) {
1038
+ switch (type) {
1039
+ case "query": {
1040
+ this.query ??= new LoomObjectType(
1041
+ { name: "Query", fields: {} },
1042
+ this.fieldOptions
1043
+ );
1044
+ return this.query;
1045
+ }
1046
+ case "mutation": {
1047
+ this.mutation ??= new LoomObjectType(
1048
+ { name: "Mutation", fields: {} },
1049
+ this.fieldOptions
1050
+ );
1051
+ return this.mutation;
1052
+ }
1053
+ case "subscription": {
1054
+ this.subscription ??= new LoomObjectType(
1055
+ { name: "Subscription", fields: {} },
1056
+ this.fieldOptions
1057
+ );
1058
+ return this.subscription;
1059
+ }
1060
+ }
1061
+ }
1062
+ get fieldOptions() {
1063
+ const { resolverOptions, context } = this;
1064
+ return { resolverOptions, weaverContext: context };
1065
+ }
1066
+ static optionsFrom(...inputs) {
1067
+ const configs = /* @__PURE__ */ new Set();
1068
+ const middlewares = /* @__PURE__ */ new Set();
1069
+ const resolvers = /* @__PURE__ */ new Set();
1070
+ const silks = /* @__PURE__ */ new Set();
1071
+ let context;
1072
+ for (const item of inputs) {
1073
+ if (typeof item === "function") {
1074
+ middlewares.add(item);
1075
+ } else if (WEAVER_CONFIG in item) {
1076
+ configs.add(item);
1077
+ if (item[WEAVER_CONFIG] === "gqloom.core.schema") {
1078
+ context = item.weaverContext;
1079
+ }
1080
+ } else if (isSilk(item)) {
1081
+ silks.add(item);
1082
+ } else {
1083
+ resolvers.add(item);
1084
+ }
1085
+ }
1086
+ return { context, configs, middlewares, resolvers, silks };
1087
+ }
1088
+ /**
1089
+ * Weave a GraphQL Schema from resolvers
1090
+ * @param inputs Resolvers, Global Middlewares or WeaverConfigs
1091
+ * @returns GraphQ LSchema
1092
+ */
1093
+ static weave(...inputs) {
1094
+ const { context, configs, middlewares, resolvers, silks } = _SchemaWeaver.optionsFrom(...inputs);
1095
+ const weaver = new _SchemaWeaver({}, context);
1096
+ configs.forEach((it) => weaver.setConfig(it));
1097
+ middlewares.forEach((it) => weaver.use(it));
1098
+ resolvers.forEach((it) => weaver.add(it));
1099
+ silks.forEach((it) => weaver.addType(it));
1100
+ return weaver.weaveGraphQLSchema();
1101
+ }
1102
+ };
1103
+ var weave = SchemaWeaver.weave;
1104
+
1105
+ // src/schema/interface.ts
1106
+ import {
1107
+ GraphQLInterfaceType,
1108
+ isInterfaceType as isInterfaceType2,
1109
+ isObjectType as isObjectType5
1110
+ } from "graphql";
1111
+ function ensureInterfaceType(gqlType, interfaceConfig) {
1112
+ if (isInterfaceType2(gqlType)) return gqlType;
1113
+ if (!isObjectType5(gqlType))
1114
+ throw new Error(`${gqlType.toString()} is not an object`);
1115
+ const key = gqlType;
1116
+ const existing = weaverContext.interfaceMap?.get(key);
1117
+ if (existing != null) return existing;
1118
+ const {
1119
+ astNode: _,
1120
+ extensionASTNodes: _1,
1121
+ fields,
1122
+ ...config
1123
+ } = gqlType.toConfig();
1124
+ const interfaceType = new GraphQLInterfaceType({
1125
+ ...config,
1126
+ ...interfaceConfig,
1127
+ fields: mapValue(fields, (field) => {
1128
+ return { ...field, type: getCacheType(field.type) };
1129
+ })
1130
+ });
1131
+ weaverContext.interfaceMap?.set(key, interfaceType);
1132
+ return interfaceType;
1133
+ }
1134
+
1135
+ // src/schema/extensions.ts
1136
+ function mergeExtensions(...extensionsList) {
1137
+ return deepMerge(...extensionsList);
1138
+ }
1139
+ export {
1140
+ ContextMemoization,
1141
+ LoomObjectType,
1142
+ ResolverOptionsMap,
1143
+ symbols_exports as SYMBOLS,
1144
+ SchemaWeaver,
1145
+ applyMiddlewares,
1146
+ baseResolver,
1147
+ collectNames,
1148
+ compose,
1149
+ createFieldBobbin,
1150
+ createInputParser,
1151
+ createLoom,
1152
+ createMemoization,
1153
+ createMutationBobbin,
1154
+ createQueryBobbin,
1155
+ createResolverBobbin,
1156
+ createSubscriptionBobbin,
1157
+ deepMerge,
1158
+ defaultSubscriptionResolve,
1159
+ ensureInputObjectType,
1160
+ ensureInputType,
1161
+ ensureInterfaceType,
1162
+ getCacheType,
1163
+ getFieldOptions,
1164
+ getGraphQLType,
1165
+ getOperationOptions,
1166
+ getSubscriptionOptions,
1167
+ initWeaverContext,
1168
+ inputToArgs,
1169
+ isOnlyMemoryPayload,
1170
+ isSilk,
1171
+ listSilk,
1172
+ loom,
1173
+ mapValue,
1174
+ markErrorLocation,
1175
+ markLocation,
1176
+ mergeExtensions,
1177
+ nonNullSilk,
1178
+ notNullish,
1179
+ nullableSilk,
1180
+ onlyMemoization,
1181
+ parseInputValue,
1182
+ parseSilk,
1183
+ provideWeaverContext,
1184
+ resolverPayloadStorage,
1185
+ silk,
1186
+ silkField,
1187
+ silkMutation,
1188
+ silkQuery,
1189
+ silkResolver,
1190
+ silkSubscription,
1191
+ toObjMap,
1192
+ tryIn,
1193
+ useContext,
1194
+ useMemoizationMap,
1195
+ useResolverPayload,
1196
+ weave,
1197
+ weaverContext
1198
+ };