@visiblevc/ember-api-mocks 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +9 -0
- package/README.md +366 -2
- package/addon-main.cjs +4 -0
- package/declarations/api.d.ts +46 -0
- package/declarations/api.d.ts.map +1 -0
- package/declarations/beacon.d.ts +3 -0
- package/declarations/beacon.d.ts.map +1 -0
- package/declarations/config.d.ts +23 -0
- package/declarations/config.d.ts.map +1 -0
- package/declarations/factories.d.ts +53 -0
- package/declarations/factories.d.ts.map +1 -0
- package/declarations/fetch-waiter.d.ts +7 -0
- package/declarations/fetch-waiter.d.ts.map +1 -0
- package/declarations/formats.d.ts +37 -0
- package/declarations/formats.d.ts.map +1 -0
- package/declarations/index.d.ts +8 -0
- package/declarations/index.d.ts.map +1 -0
- package/declarations/inflection.d.ts +6 -0
- package/declarations/inflection.d.ts.map +1 -0
- package/declarations/network.d.ts +15 -0
- package/declarations/network.d.ts.map +1 -0
- package/declarations/setup.d.ts +6 -0
- package/declarations/setup.d.ts.map +1 -0
- package/declarations/store.d.ts +6 -0
- package/declarations/store.d.ts.map +1 -0
- package/dist/index.js +1290 -0
- package/dist/index.js.map +1 -0
- package/package.json +149 -3
- package/src/api.ts +485 -0
- package/src/beacon.ts +25 -0
- package/src/config.ts +77 -0
- package/src/factories.ts +404 -0
- package/src/fetch-waiter.ts +161 -0
- package/src/formats.ts +231 -0
- package/src/index.ts +31 -0
- package/src/inflection.ts +53 -0
- package/src/network.ts +206 -0
- package/src/setup.ts +30 -0
- package/src/store.ts +214 -0
package/src/factories.ts
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
import type { Json } from './api.ts';
|
|
2
|
+
import { settings } from './config.ts';
|
|
3
|
+
import type {
|
|
4
|
+
Attrs,
|
|
5
|
+
BuiltRecord,
|
|
6
|
+
Format,
|
|
7
|
+
Related,
|
|
8
|
+
Relationship,
|
|
9
|
+
RelationshipKind,
|
|
10
|
+
} from './formats.ts';
|
|
11
|
+
|
|
12
|
+
type Value =
|
|
13
|
+
| ((record: Json) => unknown)
|
|
14
|
+
| object
|
|
15
|
+
| string
|
|
16
|
+
| number
|
|
17
|
+
| boolean
|
|
18
|
+
| null
|
|
19
|
+
| undefined;
|
|
20
|
+
type Values = Record<string, Value>;
|
|
21
|
+
type Trait = Values | ((record: Json) => void);
|
|
22
|
+
type Overrides = Attrs;
|
|
23
|
+
type BuildArg = string | Overrides;
|
|
24
|
+
type ListArg = number | BuildArg | BuildArg[];
|
|
25
|
+
|
|
26
|
+
export interface FactoryDefinition {
|
|
27
|
+
default?: Values;
|
|
28
|
+
traits?: Record<string, Trait>;
|
|
29
|
+
transient?: Values;
|
|
30
|
+
relationships?: Record<string, Association>;
|
|
31
|
+
format?: Format;
|
|
32
|
+
url?: string;
|
|
33
|
+
beforeSeed?: (record: Json, store: Json) => void;
|
|
34
|
+
afterSeed?: (model: Json, transient: Json) => void;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const definitions = new Map<string, FactoryDefinition>();
|
|
38
|
+
const sequences = new Map<string, number>();
|
|
39
|
+
const sideloads = new WeakMap<BuiltRecord, Related[]>();
|
|
40
|
+
const relationshipMaps = new WeakMap<BuiltRecord, Map<string, Relationship>>();
|
|
41
|
+
const transients = new WeakMap<BuiltRecord, Attrs>();
|
|
42
|
+
const overrideKeys = new WeakMap<BuiltRecord, Override[]>();
|
|
43
|
+
const factories = new WeakMap<BuiltRecord, string>();
|
|
44
|
+
|
|
45
|
+
interface Override {
|
|
46
|
+
key: string;
|
|
47
|
+
relationship: boolean;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
class Sequence {
|
|
51
|
+
constructor(readonly generate: (n: number) => unknown) {}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export class Association {
|
|
55
|
+
constructor(
|
|
56
|
+
readonly kind: RelationshipKind | 'fragment',
|
|
57
|
+
readonly type: string,
|
|
58
|
+
readonly args: ListArg[],
|
|
59
|
+
) {}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function isPlainObject(value: unknown): value is Attrs {
|
|
63
|
+
return (
|
|
64
|
+
value !== null &&
|
|
65
|
+
typeof value === 'object' &&
|
|
66
|
+
Object.getPrototypeOf(value) === Object.prototype
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function clone<T>(value: T): T {
|
|
71
|
+
if (Array.isArray(value)) {
|
|
72
|
+
return value.map(clone) as T;
|
|
73
|
+
} else if (isPlainObject(value)) {
|
|
74
|
+
return Object.fromEntries(
|
|
75
|
+
Object.entries(value).map(([key, item]) => [key, clone(item)]),
|
|
76
|
+
) as T;
|
|
77
|
+
}
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function nextId(name: string): number {
|
|
82
|
+
const id = (sequences.get(name) ?? 0) + 1;
|
|
83
|
+
sequences.set(name, id);
|
|
84
|
+
return id;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function resetSequences(): void {
|
|
88
|
+
sequences.clear();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function defineFactory(
|
|
92
|
+
name: string,
|
|
93
|
+
definition: FactoryDefinition = {},
|
|
94
|
+
): void {
|
|
95
|
+
definitions.set(name, definition);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function belongsTo(type: string, ...args: BuildArg[]): Association {
|
|
99
|
+
return new Association('belongsTo', type, args);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function hasMany(type: string, ...args: ListArg[]): Association {
|
|
103
|
+
return new Association('hasMany', type, args);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function fragment(type: string, ...args: BuildArg[]): Association {
|
|
107
|
+
return new Association('fragment', type, args);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function sequence(generate: (n: number) => unknown): Sequence {
|
|
111
|
+
return new Sequence(generate);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function definitionOf(
|
|
115
|
+
name: string,
|
|
116
|
+
): FactoryDefinition & { format: Format } {
|
|
117
|
+
const definition = definitions.get(name) ?? {};
|
|
118
|
+
return { ...definition, format: definition.format ?? settings().format };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function isBuilt(value: unknown): value is BuiltRecord {
|
|
122
|
+
return (
|
|
123
|
+
value !== null &&
|
|
124
|
+
typeof value === 'object' &&
|
|
125
|
+
factories.has(value as BuiltRecord)
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function link(
|
|
130
|
+
{ kind, type }: Relationship,
|
|
131
|
+
value: unknown,
|
|
132
|
+
related: Related[],
|
|
133
|
+
): unknown {
|
|
134
|
+
const items = kind === 'hasMany' ? [value ?? []].flat() : [value];
|
|
135
|
+
for (const item of items.filter(isBuilt)) {
|
|
136
|
+
related.push({ type: factoryOf(item) ?? type, record: item });
|
|
137
|
+
}
|
|
138
|
+
const idOf = (item: unknown) => (isBuilt(item) ? item.id : item);
|
|
139
|
+
return kind === 'hasMany' ? items.map(idOf) : idOf(value);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function build<T extends object = BuiltRecord>(
|
|
143
|
+
name: string,
|
|
144
|
+
...args: BuildArg[]
|
|
145
|
+
): T {
|
|
146
|
+
const definition = definitions.get(name);
|
|
147
|
+
if (!definition) {
|
|
148
|
+
throw new Error(`No factory defined for "${name}"`);
|
|
149
|
+
}
|
|
150
|
+
const { format } = definitionOf(name);
|
|
151
|
+
const last = args.at(-1);
|
|
152
|
+
const overrides: Overrides = isPlainObject(last)
|
|
153
|
+
? (args.pop() as Overrides)
|
|
154
|
+
: {};
|
|
155
|
+
const transientKeys = new Set(Object.keys(definition.transient ?? {}));
|
|
156
|
+
const declared = definition.relationships ?? {};
|
|
157
|
+
|
|
158
|
+
const attrs: Attrs = { ...definition.transient, ...definition.default };
|
|
159
|
+
const mutations: Array<(record: BuiltRecord) => void> = [];
|
|
160
|
+
for (const trait of args as string[]) {
|
|
161
|
+
const traitAttrs = definition.traits?.[trait];
|
|
162
|
+
if (!traitAttrs) {
|
|
163
|
+
throw new Error(`Factory "${name}" has no trait "${trait}"`);
|
|
164
|
+
} else if (typeof traitAttrs === 'function') {
|
|
165
|
+
mutations.push(traitAttrs as (record: BuiltRecord) => void);
|
|
166
|
+
} else {
|
|
167
|
+
Object.assign(attrs, traitAttrs);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
for (const key of Object.keys(overrides)) {
|
|
171
|
+
const error =
|
|
172
|
+
transientKeys.has(key) || key in declared
|
|
173
|
+
? undefined
|
|
174
|
+
: format.keyError(key);
|
|
175
|
+
if (error) {
|
|
176
|
+
throw new Error(`build('${name}') got "${key}". ${error}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
Object.assign(attrs, overrides);
|
|
180
|
+
|
|
181
|
+
const { id } = attrs;
|
|
182
|
+
const record: BuiltRecord = {
|
|
183
|
+
id:
|
|
184
|
+
id instanceof Sequence ? id.generate(nextId(name)) : (id ?? nextId(name)),
|
|
185
|
+
};
|
|
186
|
+
if (Number.isInteger(Number(id)) && id !== '' && id !== null) {
|
|
187
|
+
sequences.set(name, Math.max(sequences.get(name) ?? 0, Number(id)));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const related: Related[] = [];
|
|
191
|
+
const relationships = new Map<string, Relationship>();
|
|
192
|
+
const options: Attrs = {};
|
|
193
|
+
const deferred: Array<[string, (record: BuiltRecord) => unknown]> = [];
|
|
194
|
+
for (const [key, value] of Object.entries(attrs)) {
|
|
195
|
+
if (key === 'id') {
|
|
196
|
+
continue;
|
|
197
|
+
} else if (transientKeys.has(key)) {
|
|
198
|
+
options[key] = value;
|
|
199
|
+
} else if (value instanceof Sequence) {
|
|
200
|
+
record[key] = value.generate(nextId(`${name}.${key}`));
|
|
201
|
+
} else if (value instanceof Association && value.kind === 'fragment') {
|
|
202
|
+
const { id: _id, ...nested } = build(
|
|
203
|
+
value.type,
|
|
204
|
+
...(value.args as BuildArg[]),
|
|
205
|
+
);
|
|
206
|
+
record[key] = nested;
|
|
207
|
+
} else if (value instanceof Association || declared[key]) {
|
|
208
|
+
const { type, kind } = (
|
|
209
|
+
value instanceof Association ? value : declared[key]
|
|
210
|
+
) as Relationship;
|
|
211
|
+
if (
|
|
212
|
+
value instanceof Association &&
|
|
213
|
+
kind === 'hasMany' &&
|
|
214
|
+
!value.args.length
|
|
215
|
+
) {
|
|
216
|
+
throw new Error(
|
|
217
|
+
`hasMany('${type}') in a default or trait needs a count`,
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
const built =
|
|
221
|
+
value instanceof Association
|
|
222
|
+
? kind === 'hasMany'
|
|
223
|
+
? buildList(type, ...value.args)
|
|
224
|
+
: build(type, ...(value.args as BuildArg[]))
|
|
225
|
+
: value;
|
|
226
|
+
const wireKey = format.relationshipKey(key, kind);
|
|
227
|
+
record[wireKey] = link({ type, kind }, built, related);
|
|
228
|
+
relationships.set(wireKey, { type, kind });
|
|
229
|
+
} else if (typeof value === 'function') {
|
|
230
|
+
record[key] = undefined;
|
|
231
|
+
deferred.push([key, value as (record: BuiltRecord) => unknown]);
|
|
232
|
+
} else if ([value].flat().some(isBuilt)) {
|
|
233
|
+
throw new Error(
|
|
234
|
+
`build('${name}') got built records under "${key}". Declare it in the ${name} factory's relationships: { ${key}: belongsTo(...) } or hasMany(...).`,
|
|
235
|
+
);
|
|
236
|
+
} else {
|
|
237
|
+
record[key] = clone(value);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
deferred.forEach(([key, value]) => (record[key] = value(record)));
|
|
241
|
+
mutations.forEach((mutate) => mutate(record));
|
|
242
|
+
|
|
243
|
+
sideloads.set(record, related);
|
|
244
|
+
relationshipMaps.set(record, relationships);
|
|
245
|
+
transients.set(record, options);
|
|
246
|
+
factories.set(record, name);
|
|
247
|
+
overrideKeys.set(
|
|
248
|
+
record,
|
|
249
|
+
Object.entries(overrides)
|
|
250
|
+
.filter(([key]) => !transientKeys.has(key))
|
|
251
|
+
.map(([key, value]) => {
|
|
252
|
+
const association =
|
|
253
|
+
value instanceof Association ? value : declared[key];
|
|
254
|
+
return association && association.kind !== 'fragment'
|
|
255
|
+
? {
|
|
256
|
+
key: format.relationshipKey(key, association.kind),
|
|
257
|
+
relationship: true,
|
|
258
|
+
}
|
|
259
|
+
: { key, relationship: false };
|
|
260
|
+
}),
|
|
261
|
+
);
|
|
262
|
+
return record as T;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export function buildList<T extends object = BuiltRecord>(
|
|
266
|
+
name: string,
|
|
267
|
+
...args: unknown[]
|
|
268
|
+
): T[] {
|
|
269
|
+
if (typeof args[0] === 'number') {
|
|
270
|
+
const [count, ...rest] = args as [number, ...BuildArg[]];
|
|
271
|
+
return Array.from({ length: count }, () => build<T>(name, ...rest));
|
|
272
|
+
}
|
|
273
|
+
return (args as Array<BuildArg | BuildArg[]>).map((spec) =>
|
|
274
|
+
build<T>(name, ...[spec].flat()),
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export function factoryOf(record: unknown): string | undefined {
|
|
279
|
+
return isPlainObject(record)
|
|
280
|
+
? factories.get(record as BuiltRecord)
|
|
281
|
+
: undefined;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export function transientOf(record: BuiltRecord): Attrs {
|
|
285
|
+
return transients.get(record) ?? {};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export function overridesOf(record: BuiltRecord): Override[] {
|
|
289
|
+
return overrideKeys.get(record) ?? [];
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export function sideload<T extends object>(
|
|
293
|
+
record: T,
|
|
294
|
+
...related: Array<object | null | undefined>
|
|
295
|
+
): T {
|
|
296
|
+
const list = sideloads.get(record as BuiltRecord) ?? [];
|
|
297
|
+
for (const item of related) {
|
|
298
|
+
const type = item && factoryOf(item);
|
|
299
|
+
if (item && type) {
|
|
300
|
+
list.push({ type, record: item as BuiltRecord });
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
sideloads.set(record as BuiltRecord, list);
|
|
304
|
+
return record;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
interface Prepared {
|
|
308
|
+
record: BuiltRecord;
|
|
309
|
+
related: Related[];
|
|
310
|
+
relationships: Map<string, Relationship>;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function declaredRelationships(
|
|
314
|
+
name: string,
|
|
315
|
+
format: Format,
|
|
316
|
+
): Array<[string, string, Relationship]> {
|
|
317
|
+
return Object.entries(definitions.get(name)?.relationships ?? {})
|
|
318
|
+
.filter(([, association]) => association.kind !== 'fragment')
|
|
319
|
+
.map(([key, association]) => {
|
|
320
|
+
const kind = association.kind as RelationshipKind;
|
|
321
|
+
return [
|
|
322
|
+
key,
|
|
323
|
+
format.relationshipKey(key, kind),
|
|
324
|
+
{ type: association.type, kind },
|
|
325
|
+
];
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function prepare(
|
|
330
|
+
type: string,
|
|
331
|
+
record: BuiltRecord,
|
|
332
|
+
format: Format,
|
|
333
|
+
cache: Map<BuiltRecord, Prepared>,
|
|
334
|
+
): Prepared {
|
|
335
|
+
const cached = cache.get(record);
|
|
336
|
+
if (cached) {
|
|
337
|
+
return cached;
|
|
338
|
+
}
|
|
339
|
+
const relationships = new Map(relationshipMaps.get(record) ?? []);
|
|
340
|
+
const related = [...(sideloads.get(record) ?? [])];
|
|
341
|
+
let copy = record;
|
|
342
|
+
for (const [key, wireKey, relationship] of declaredRelationships(
|
|
343
|
+
factoryOf(record) ?? type,
|
|
344
|
+
format,
|
|
345
|
+
)) {
|
|
346
|
+
relationships.set(wireKey, relationship);
|
|
347
|
+
const source = key in record && key !== wireKey ? key : wireKey;
|
|
348
|
+
const value = record[source];
|
|
349
|
+
if (source === wireKey && ![value].flat().some(isBuilt)) {
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
copy = copy === record ? { ...record } : copy;
|
|
353
|
+
delete copy[source];
|
|
354
|
+
copy[wireKey] = link(relationship, value, related);
|
|
355
|
+
}
|
|
356
|
+
const prepared = { record: copy, related, relationships };
|
|
357
|
+
cache.set(record, prepared);
|
|
358
|
+
cache.set(copy, prepared);
|
|
359
|
+
return prepared;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
export function documentFor(
|
|
363
|
+
type: string,
|
|
364
|
+
data: BuiltRecord | BuiltRecord[],
|
|
365
|
+
extra: Attrs,
|
|
366
|
+
seeding: boolean,
|
|
367
|
+
): Attrs {
|
|
368
|
+
const { format } = definitionOf(type);
|
|
369
|
+
const cache = new Map<BuiltRecord, Prepared>();
|
|
370
|
+
const prepared = (record: BuiltRecord, recordType = type) =>
|
|
371
|
+
prepare(recordType, record, format, cache);
|
|
372
|
+
const records = Array.isArray(data)
|
|
373
|
+
? data.map((record) => prepared(record).record)
|
|
374
|
+
: prepared(data).record;
|
|
375
|
+
return format.document(type, records, extra, {
|
|
376
|
+
seeding,
|
|
377
|
+
related: (record) =>
|
|
378
|
+
prepared(record).related.map((entry) => ({
|
|
379
|
+
type: entry.type,
|
|
380
|
+
record: prepared(entry.record, entry.type).record,
|
|
381
|
+
})),
|
|
382
|
+
relationships: (record) => prepared(record).relationships,
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export function payload(
|
|
387
|
+
type: string,
|
|
388
|
+
data: object | object[],
|
|
389
|
+
extra: Attrs = {},
|
|
390
|
+
): Attrs {
|
|
391
|
+
return documentFor(type, data as BuiltRecord | BuiltRecord[], extra, false);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
export function mergePayloads(...payloads: Attrs[]): Attrs {
|
|
395
|
+
const result: Attrs = {};
|
|
396
|
+
for (const [key, value] of payloads.flatMap(Object.entries)) {
|
|
397
|
+
const existing = result[key];
|
|
398
|
+
result[key] =
|
|
399
|
+
Array.isArray(existing) && Array.isArray(value)
|
|
400
|
+
? [...(existing as unknown[]), ...(value as unknown[])]
|
|
401
|
+
: value;
|
|
402
|
+
}
|
|
403
|
+
return result;
|
|
404
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { buildWaiter } from '@ember/test-waiters';
|
|
2
|
+
|
|
3
|
+
const waiter = buildWaiter('ember-api-mocks:responses');
|
|
4
|
+
export const nativeSetTimeout = window.setTimeout.bind(window);
|
|
5
|
+
const READERS = [
|
|
6
|
+
'json',
|
|
7
|
+
'text',
|
|
8
|
+
'arrayBuffer',
|
|
9
|
+
'blob',
|
|
10
|
+
'formData',
|
|
11
|
+
'bytes',
|
|
12
|
+
] as const;
|
|
13
|
+
|
|
14
|
+
interface Pending {
|
|
15
|
+
token: unknown;
|
|
16
|
+
reads: number;
|
|
17
|
+
readStarted: boolean;
|
|
18
|
+
ended: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const open = new Set<Pending>();
|
|
22
|
+
let installed:
|
|
23
|
+
| { wrapper: typeof fetch; inner: typeof fetch; state: WrapperState }
|
|
24
|
+
| undefined;
|
|
25
|
+
|
|
26
|
+
export function afterTwoMacrotasks(callback: () => void): void {
|
|
27
|
+
nativeSetTimeout(() => nativeSetTimeout(callback, 0), 0);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function end(pending: Pending): void {
|
|
31
|
+
if (!pending.ended) {
|
|
32
|
+
pending.ended = true;
|
|
33
|
+
waiter.endAsync(pending.token);
|
|
34
|
+
open.delete(pending);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function endAfterReads(pending: Pending): void {
|
|
39
|
+
nativeSetTimeout(() => {
|
|
40
|
+
if (pending.reads === 0) {
|
|
41
|
+
end(pending);
|
|
42
|
+
}
|
|
43
|
+
}, 0);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function instrument(response: Response, pending: Pending): Response {
|
|
47
|
+
const target = response as unknown as Record<string, unknown>;
|
|
48
|
+
for (const reader of READERS) {
|
|
49
|
+
const original = target[reader];
|
|
50
|
+
if (typeof original !== 'function') {
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
target[reader] = (...args: unknown[]) => {
|
|
54
|
+
pending.reads += 1;
|
|
55
|
+
pending.readStarted = true;
|
|
56
|
+
return (original as (...a: unknown[]) => Promise<unknown>)
|
|
57
|
+
.apply(response, args)
|
|
58
|
+
.finally(() => {
|
|
59
|
+
pending.reads -= 1;
|
|
60
|
+
endAfterReads(pending);
|
|
61
|
+
});
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const clone = response.clone.bind(response);
|
|
65
|
+
target.clone = () => instrument(clone(), pending);
|
|
66
|
+
return response;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function urlOf(input: RequestInfo | URL): string | undefined {
|
|
70
|
+
const raw = input instanceof Request ? input.url : String(input);
|
|
71
|
+
return URL.canParse(raw, window.location.href)
|
|
72
|
+
? new URL(raw, window.location.href).href
|
|
73
|
+
: undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
interface WrapperState {
|
|
77
|
+
original: typeof fetch;
|
|
78
|
+
active: boolean;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const WRAPPER = Symbol.for('ember-api-mocks.fetch');
|
|
82
|
+
|
|
83
|
+
function stateOf(value: unknown): WrapperState | undefined {
|
|
84
|
+
return typeof value === 'function'
|
|
85
|
+
? (value as { [WRAPPER]?: WrapperState })[WRAPPER]
|
|
86
|
+
: undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function unwrapStaleFetch(): void {
|
|
90
|
+
let current = globalThis.fetch;
|
|
91
|
+
for (
|
|
92
|
+
let state = stateOf(current);
|
|
93
|
+
state && !state.active;
|
|
94
|
+
state = stateOf(current)
|
|
95
|
+
) {
|
|
96
|
+
current = state.original;
|
|
97
|
+
}
|
|
98
|
+
if (current !== globalThis.fetch) {
|
|
99
|
+
globalThis.fetch = current;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function installFetchWaiter(
|
|
104
|
+
original: typeof fetch,
|
|
105
|
+
tracks: (url: string) => boolean,
|
|
106
|
+
): void {
|
|
107
|
+
if (installed) {
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const inner = globalThis.fetch;
|
|
111
|
+
const state: WrapperState = { original, active: true };
|
|
112
|
+
const wrapper = function (input: RequestInfo | URL, init?: RequestInit) {
|
|
113
|
+
if (!state.active) {
|
|
114
|
+
const passThrough = state.original;
|
|
115
|
+
return passThrough(input, init);
|
|
116
|
+
}
|
|
117
|
+
const url = urlOf(input);
|
|
118
|
+
if (url === undefined || !tracks(url)) {
|
|
119
|
+
return inner(input, init);
|
|
120
|
+
}
|
|
121
|
+
const pending: Pending = {
|
|
122
|
+
token: waiter.beginAsync(),
|
|
123
|
+
reads: 0,
|
|
124
|
+
readStarted: false,
|
|
125
|
+
ended: false,
|
|
126
|
+
};
|
|
127
|
+
open.add(pending);
|
|
128
|
+
return inner(input, init).then(
|
|
129
|
+
(response) => {
|
|
130
|
+
afterTwoMacrotasks(() => {
|
|
131
|
+
if (!pending.readStarted) {
|
|
132
|
+
end(pending);
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
return instrument(response, pending);
|
|
136
|
+
},
|
|
137
|
+
(error: unknown) => {
|
|
138
|
+
endAfterReads(pending);
|
|
139
|
+
throw error;
|
|
140
|
+
},
|
|
141
|
+
);
|
|
142
|
+
};
|
|
143
|
+
Object.defineProperty(wrapper, WRAPPER, { value: state });
|
|
144
|
+
installed = { wrapper, inner, state };
|
|
145
|
+
globalThis.fetch = wrapper;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function endOpenResponses(): void {
|
|
149
|
+
[...open].forEach(end);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function removeFetchWaiter(): void {
|
|
153
|
+
if (installed) {
|
|
154
|
+
installed.state.active = false;
|
|
155
|
+
if (globalThis.fetch === installed.wrapper) {
|
|
156
|
+
globalThis.fetch = installed.inner;
|
|
157
|
+
}
|
|
158
|
+
installed = undefined;
|
|
159
|
+
}
|
|
160
|
+
endOpenResponses();
|
|
161
|
+
}
|