@pothos/selection-mapper 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.
Files changed (86) hide show
  1. package/.swcrc +10 -0
  2. package/LICENSE +6 -0
  3. package/README.md +92 -0
  4. package/dts/adapter.d.ts +74 -0
  5. package/dts/adapter.d.ts.map +1 -0
  6. package/dts/deep-equal.d.ts +7 -0
  7. package/dts/deep-equal.d.ts.map +1 -0
  8. package/dts/index.d.ts +13 -0
  9. package/dts/index.d.ts.map +1 -0
  10. package/dts/loader-map.d.ts +63 -0
  11. package/dts/loader-map.d.ts.map +1 -0
  12. package/dts/matches.d.ts +113 -0
  13. package/dts/matches.d.ts.map +1 -0
  14. package/dts/node.d.ts +85 -0
  15. package/dts/node.d.ts.map +1 -0
  16. package/dts/plan.d.ts +176 -0
  17. package/dts/plan.d.ts.map +1 -0
  18. package/dts/types.d.ts +97 -0
  19. package/dts/types.d.ts.map +1 -0
  20. package/dts/walk.d.ts +24 -0
  21. package/dts/walk.d.ts.map +1 -0
  22. package/esm/adapter.d.ts +74 -0
  23. package/esm/adapter.d.ts.map +1 -0
  24. package/esm/adapter.js +47 -0
  25. package/esm/adapter.js.map +1 -0
  26. package/esm/deep-equal.d.ts +7 -0
  27. package/esm/deep-equal.d.ts.map +1 -0
  28. package/esm/deep-equal.js +50 -0
  29. package/esm/deep-equal.js.map +1 -0
  30. package/esm/index.d.ts +13 -0
  31. package/esm/index.d.ts.map +1 -0
  32. package/esm/index.js +12 -0
  33. package/esm/index.js.map +1 -0
  34. package/esm/loader-map.d.ts +63 -0
  35. package/esm/loader-map.d.ts.map +1 -0
  36. package/esm/loader-map.js +197 -0
  37. package/esm/loader-map.js.map +1 -0
  38. package/esm/matches.d.ts +113 -0
  39. package/esm/matches.d.ts.map +1 -0
  40. package/esm/matches.js +419 -0
  41. package/esm/matches.js.map +1 -0
  42. package/esm/node.d.ts +85 -0
  43. package/esm/node.d.ts.map +1 -0
  44. package/esm/node.js +232 -0
  45. package/esm/node.js.map +1 -0
  46. package/esm/package.json +3 -0
  47. package/esm/plan.d.ts +176 -0
  48. package/esm/plan.d.ts.map +1 -0
  49. package/esm/plan.js +339 -0
  50. package/esm/plan.js.map +1 -0
  51. package/esm/types.d.ts +97 -0
  52. package/esm/types.d.ts.map +1 -0
  53. package/esm/types.js +10 -0
  54. package/esm/types.js.map +1 -0
  55. package/esm/walk.d.ts +24 -0
  56. package/esm/walk.d.ts.map +1 -0
  57. package/esm/walk.js +442 -0
  58. package/esm/walk.js.map +1 -0
  59. package/lib/adapter.js +43 -0
  60. package/lib/adapter.js.map +1 -0
  61. package/lib/deep-equal.js +60 -0
  62. package/lib/deep-equal.js.map +1 -0
  63. package/lib/index.js +57 -0
  64. package/lib/index.js.map +1 -0
  65. package/lib/loader-map.js +209 -0
  66. package/lib/loader-map.js.map +1 -0
  67. package/lib/matches.js +427 -0
  68. package/lib/matches.js.map +1 -0
  69. package/lib/node.js +245 -0
  70. package/lib/node.js.map +1 -0
  71. package/lib/plan.js +349 -0
  72. package/lib/plan.js.map +1 -0
  73. package/lib/types.js +9 -0
  74. package/lib/types.js.map +1 -0
  75. package/lib/walk.js +455 -0
  76. package/lib/walk.js.map +1 -0
  77. package/package.json +55 -0
  78. package/src/adapter.ts +96 -0
  79. package/src/deep-equal.ts +67 -0
  80. package/src/index.ts +32 -0
  81. package/src/loader-map.ts +287 -0
  82. package/src/matches.ts +681 -0
  83. package/src/node.ts +327 -0
  84. package/src/plan.ts +454 -0
  85. package/src/types.ts +123 -0
  86. package/src/walk.ts +696 -0
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Structural equality for query arguments (`where`, `orderBy`, `take`, ...). Keys holding
3
+ * `undefined` are treated as absent, so `{ where: cond ? filter : undefined }` compares equal to
4
+ * `{}` when the condition is false.
5
+ */
6
+ export function deepEqual(left: unknown, right: unknown): boolean {
7
+ if (left === right) {
8
+ return true;
9
+ }
10
+
11
+ if (left && right && typeof left === 'object' && typeof right === 'object') {
12
+ if (Array.isArray(left) || Array.isArray(right)) {
13
+ if (!Array.isArray(left) || !Array.isArray(right)) {
14
+ return false;
15
+ }
16
+
17
+ const { length } = left;
18
+
19
+ if (right.length !== length) {
20
+ return false;
21
+ }
22
+
23
+ for (let i = 0; i < length; i += 1) {
24
+ if (!deepEqual(left[i], right[i])) {
25
+ return false;
26
+ }
27
+ }
28
+
29
+ return true;
30
+ }
31
+
32
+ const lValue = left.valueOf?.();
33
+ const rValue = right.valueOf?.();
34
+
35
+ // A boxed value (a Date, a boxed primitive) compares by its primitive, whichever side it is
36
+ // on: a plain object's `valueOf` returns the object itself, and a null-prototype object has
37
+ // none at all, so neither is mistaken for one.
38
+ if (
39
+ (lValue != null && typeof lValue !== 'object') ||
40
+ (rValue != null && typeof rValue !== 'object')
41
+ ) {
42
+ return lValue === rValue;
43
+ }
44
+
45
+ const keys = comparedKeys(left as Record<string, unknown>);
46
+
47
+ if (keys.length !== comparedKeys(right as Record<string, unknown>).length) {
48
+ return false;
49
+ }
50
+
51
+ for (const key of keys) {
52
+ if (
53
+ !deepEqual((left as Record<string, unknown>)[key], (right as Record<string, unknown>)[key])
54
+ ) {
55
+ return false;
56
+ }
57
+ }
58
+
59
+ return true;
60
+ }
61
+
62
+ return false;
63
+ }
64
+
65
+ function comparedKeys(value: Record<string, unknown>) {
66
+ return Object.keys(value).filter((key) => value[key] !== undefined);
67
+ }
package/src/index.ts ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * What the ORM plugins use: the `Plan` class with the two entry points on it, the `Adapter`
3
+ * classes their own adapters extend, and the loader-map, usage and equality helpers their
4
+ * adapters and loaders call. Everything else is module-private; see the README.
5
+ */
6
+ export { Adapter } from './adapter.js';
7
+ export { deepEqual } from './deep-equal.js';
8
+ export {
9
+ cacheKey,
10
+ getLoaderMapping,
11
+ type Mappings,
12
+ setFieldMapping,
13
+ setLoaderMappings,
14
+ setRowFieldMapping,
15
+ setRowMappings,
16
+ } from './loader-map.js';
17
+ export {
18
+ type IndirectInclude,
19
+ type IndirectPathSegment,
20
+ type PathSegment,
21
+ selectedFieldNames,
22
+ } from './matches.js';
23
+ export { type Node, NodeAdapter, type QueryVisitor } from './node.js';
24
+ export { Plan, type PlayedPlan } from './plan.js';
25
+ export type {
26
+ MergeOptions,
27
+ NestedSelection,
28
+ Position,
29
+ SelectedFieldNode,
30
+ SelectFn,
31
+ WalkedType,
32
+ } from './types.js';
@@ -0,0 +1,287 @@
1
+ import { createContextCache } from '@pothos/core';
2
+ import type { GraphQLResolveInfo } from 'graphql';
3
+ import type { Position } from './types.js';
4
+
5
+ /**
6
+ * What a plan records for one field whose selection was merged: the mappings of the fields walked
7
+ * beneath it, and, for a field a select function planned, the position it was planned at, so a
8
+ * resolver can ask the same question of it that the select path asked. A static selection records
9
+ * the shared empty mapping and has no position: it ran no callback that could have read one.
10
+ */
11
+ export interface Mapping {
12
+ nested: Mappings;
13
+ position?: Position;
14
+ }
15
+
16
+ /**
17
+ * Mappings keyed by `${Type}@${relative.path}`, where the relative path is the aliased field path
18
+ * from the walked field to the mapped field (`Post@edges.node.author`). A resolver beneath the
19
+ * walked field finds a mapping iff the plan that would have loaded its data was merged.
20
+ */
21
+ export type Mappings = Record<string, Mapping>;
22
+
23
+ /** The mapping of a static selection: nothing can ever be recorded beneath one. */
24
+ export const EMPTY_MAPPING: Mapping = Object.freeze({ nested: Object.freeze({}) as Mappings });
25
+
26
+ /**
27
+ * Adopts the first mapping recorded for a key; a later one deep-unions into a copy, so a recorded
28
+ * mapping is never changed after the fact (two plays may accept a different subset of the fields).
29
+ */
30
+ export function unionMappings(into: Mapping | undefined, from: Mapping): Mapping {
31
+ if (!into || into === EMPTY_MAPPING) {
32
+ return from;
33
+ }
34
+
35
+ const nested: Mappings = { ...into.nested };
36
+
37
+ for (const key of Object.keys(from.nested)) {
38
+ nested[key] = unionMappings(nested[key], from.nested[key]);
39
+ }
40
+
41
+ return into.position === undefined ? { nested } : { nested, position: into.position };
42
+ }
43
+
44
+ /**
45
+ * Per request context: the mappings recorded so far, and the keys they were recorded under, by
46
+ * the path prefix that rehomed them. `responsePath` drops list indices, so every row of a list
47
+ * rebuilds the same key strings; a prefix builds them once.
48
+ *
49
+ * `mappings` holds what a plan recorded for a whole field: every row of that field was loaded by
50
+ * it, so one mapping per path answers for all of them. `rows` holds a mapping that answers for
51
+ * one row only — because two plans disagreed about a key, or because the plan loaded that row
52
+ * alone. A mapping carries the position a connection pages with, so a row answering from another
53
+ * row's mapping would page with arguments its own data was never fetched with. `rowScoped` stays
54
+ * false while nothing has been recorded there, so a request whose rows were all loaded the same
55
+ * way pays nothing for the row tier.
56
+ */
57
+ const cache = createContextCache(() => ({
58
+ mappings: new Map<string, Mapping>(),
59
+ rehomed: new Map<string, Map<string, string>>(),
60
+ rows: new WeakMap<object, WeakMap<object, Map<string, Mapping>>>(),
61
+ rowScoped: false,
62
+ scopes: new WeakMap<object, Mappings>(),
63
+ }));
64
+
65
+ type Cache = ReturnType<typeof cache>;
66
+
67
+ /**
68
+ * Memoised per path link, which is created once per field per row and never mutated. graphql-js
69
+ * shares the links above a list between every row of it, so the prefix of a field resolved for
70
+ * each of N rows is built once rather than N times. Weak, so the links go with the request.
71
+ */
72
+ const pathKeys = new WeakMap<object, string>();
73
+
74
+ /** The string keys of a response path joined by `.`; list indices are dropped. */
75
+ export function responsePath(path: GraphQLResolveInfo['path'] | undefined): string {
76
+ if (!path) {
77
+ return '';
78
+ }
79
+
80
+ let key = pathKeys.get(path);
81
+
82
+ if (key === undefined) {
83
+ const prefix = responsePath(path.prev);
84
+
85
+ // A list index contributes nothing, so the link's key is its prefix's.
86
+ key = typeof path.key === 'string' ? (prefix ? `${prefix}.${path.key}` : path.key) : prefix;
87
+ pathKeys.set(path, key);
88
+ }
89
+
90
+ return key;
91
+ }
92
+
93
+ export function cacheKey(type: string, path: GraphQLResolveInfo['path']) {
94
+ return `${type}@${responsePath(path)}`;
95
+ }
96
+
97
+ /**
98
+ * The keys `mappings` is recorded under when it is rehomed beneath `prefix`. Built once per
99
+ * prefix and shared by both tiers: the strings depend on the path and the plan's own keys, never
100
+ * on which row is being recorded for.
101
+ */
102
+ function rehomedKeys(cached: Cache, prefix: string) {
103
+ let keys = cached.rehomed.get(prefix);
104
+
105
+ if (!keys) {
106
+ keys = new Map();
107
+ cached.rehomed.set(prefix, keys);
108
+ }
109
+
110
+ return keys;
111
+ }
112
+
113
+ /** `key`, a plan's own `Type@relative.path`, moved beneath `prefix`. Built once per prefix. */
114
+ function rehome(keys: Map<string, string>, key: string, prefix: string) {
115
+ let under = keys.get(key);
116
+
117
+ if (under === undefined) {
118
+ const at = key.indexOf('@');
119
+
120
+ under = `${key.slice(0, at)}@${prefix}.${key.slice(at + 1)}`;
121
+ keys.set(key, under);
122
+ }
123
+
124
+ return under;
125
+ }
126
+
127
+ /** `row` if a mapping can be hung off it. A root field resolves with no parent value at all. */
128
+ function ownerOf(row: unknown): object | null {
129
+ return typeof row === 'object' && row !== null ? row : null;
130
+ }
131
+
132
+ /**
133
+ * Records `mapping` at `key` for `row`. An unclaimed key takes it, and a key already holding this
134
+ * very mapping needs no write, so the rows after the first write nothing. Only a key two plans
135
+ * disagree about gives the row a mapping of its own — or, with no row to hang it off, nothing, so
136
+ * the resolvers beneath fall back and load their own data.
137
+ */
138
+ function claim(
139
+ cached: Cache,
140
+ key: string,
141
+ mapping: Mapping,
142
+ row: object | null,
143
+ path: GraphQLResolveInfo['path'],
144
+ ) {
145
+ const held = cached.mappings.get(key);
146
+
147
+ if (held === undefined) {
148
+ cached.mappings.set(key, mapping);
149
+ } else if (held !== mapping && row) {
150
+ claimForRow(cached, key.slice(0, key.indexOf('@')), mapping, row, path);
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Records `mapping` for this field execution against `row` alone, never in the shared tier. The caller loaded
156
+ * `row` by itself, so an unclaimed key is not the caller's to take: the shared tier answers for
157
+ * every row of a field, and a sibling that was never loaded would read the entry as proof that
158
+ * it had been. With no row to hang it off there is nothing to record, and the resolvers beneath
159
+ * fall back and load their own data.
160
+ */
161
+ function claimForRow(
162
+ cached: Cache,
163
+ type: string,
164
+ mapping: Mapping,
165
+ row: object,
166
+ path: GraphQLResolveInfo['path'],
167
+ ) {
168
+ let byPath = cached.rows.get(row);
169
+ if (!byPath) {
170
+ byPath = new WeakMap();
171
+ cached.rows.set(row, byPath);
172
+ cached.rowScoped = true;
173
+ }
174
+ let own = byPath.get(path);
175
+ if (!own) {
176
+ own = new Map();
177
+ byPath.set(path, own);
178
+ }
179
+ own.set(type, mapping);
180
+ }
181
+
182
+ /**
183
+ * Records the mappings of a plan rooted at the field `info` resolves, under that field's path.
184
+ * The plan loaded the whole field, so its mappings answer for every row of it: they go to the
185
+ * shared tier. Multiple plans can contribute to one field (Relay nodes of different model
186
+ * types share the list's path), so later contributions replace matching keys and retain others.
187
+ */
188
+ export function setLoaderMappings(ctx: object, info: GraphQLResolveInfo, mappings: Mappings) {
189
+ const cached = cache(ctx);
190
+ const prefix = responsePath(info.path);
191
+ const keys = rehomedKeys(cached, prefix);
192
+ const previous = cached.scopes.get(info.path);
193
+ cached.scopes.set(info.path, previous ? { ...previous, ...mappings } : mappings);
194
+
195
+ for (const key of Object.keys(mappings)) {
196
+ cached.mappings.set(rehome(keys, key, prefix), mappings[key]);
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Records a row's mappings and scopes its descendants to this concrete field execution. A
202
+ * descendant's parent is a different object, so row identity alone cannot carry its plan through
203
+ * a relation, connection wrapper, or list. The execution path retains indices to isolate siblings.
204
+ */
205
+ export function setRowMappings(ctx: object, info: GraphQLResolveInfo, mappings: Mappings) {
206
+ cache(ctx).scopes.set(info.path, mappings);
207
+ }
208
+
209
+ /**
210
+ * Records the mapping of the field `info` resolves (under its own parent type) along with the
211
+ * mappings beneath it, so both the field's resolver and the resolvers below it can look
212
+ * themselves up. `row` is the value the field is about to resolve with: the parent row when it
213
+ * was loaded by the planned query, and the reloaded row when the fallback loader fetched it.
214
+ */
215
+ export function setFieldMapping(
216
+ ctx: object,
217
+ info: GraphQLResolveInfo,
218
+ mapping: Mapping,
219
+ row: unknown,
220
+ ) {
221
+ const cached = cache(ctx);
222
+ const owner = ownerOf(row);
223
+
224
+ claim(cached, cacheKey(info.parentType.name, info.path), mapping, owner, info.path);
225
+ cached.scopes.set(info.path, mapping.nested);
226
+ }
227
+
228
+ /**
229
+ * `setFieldMapping` for a plan that loaded `row` alone: the field's own mapping is recorded
230
+ * against `row` rather than claimed for the whole field, so a sibling row the plan never loaded
231
+ * keeps falling back instead of reading the entry and resolving against data it does not carry.
232
+ *
233
+ * Descendants inherit the mapping through this field's execution scope, even when their parent
234
+ * is a child object or a connection wrapper rather than the row that was reloaded.
235
+ */
236
+ export function setRowFieldMapping(
237
+ ctx: object,
238
+ info: GraphQLResolveInfo,
239
+ mapping: Mapping,
240
+ row: unknown,
241
+ ) {
242
+ const cached = cache(ctx);
243
+ const owner = ownerOf(row);
244
+
245
+ if (owner) {
246
+ claimForRow(cached, info.parentType.name, mapping, owner, info.path);
247
+ }
248
+
249
+ cached.scopes.set(info.path, mapping.nested);
250
+ }
251
+
252
+ /**
253
+ * The mapping recorded for the field at `path` on `row`, preferring one recorded for that row
254
+ * over the plan's. `row` is the value whose data the mapping describes — the resolver's parent.
255
+ */
256
+ export function getLoaderMapping(
257
+ ctx: object,
258
+ path: GraphQLResolveInfo['path'],
259
+ type: string,
260
+ row?: unknown,
261
+ ): Mapping | null {
262
+ const cached = cache(ctx);
263
+ const key = cacheKey(type, path);
264
+
265
+ if (cached.rowScoped) {
266
+ const owner = ownerOf(row);
267
+ const own = owner && cached.rows.get(owner)?.get(path)?.get(type);
268
+
269
+ if (own) {
270
+ return own;
271
+ }
272
+ }
273
+
274
+ for (let ancestor = path.prev; ancestor; ancestor = ancestor.prev) {
275
+ const scope = cached.scopes.get(ancestor);
276
+
277
+ if (scope) {
278
+ // A different plan may have omitted this field. Do not treat a sibling's shared mapping
279
+ // as proof that this execution loaded it.
280
+ return (
281
+ scope[`${type}@${responsePath(path).slice(responsePath(ancestor).length + 1)}`] ?? null
282
+ );
283
+ }
284
+ }
285
+
286
+ return cached.mappings.get(key) ?? null;
287
+ }