@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/dist/index.js ADDED
@@ -0,0 +1,1290 @@
1
+ import { http, passthrough, HttpResponse } from 'msw';
2
+ export { HttpResponse, passthrough } from 'msw';
3
+ import { macroCondition, dependencySatisfies, importSync } from '@embroider/macros';
4
+ import { buildWaiter, hasPendingWaiters, getPendingWaiterState } from '@ember/test-waiters';
5
+ import { FetchInterceptor } from '@mswjs/interceptors/fetch';
6
+ import { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest';
7
+ import { defineNetwork, InterceptorSource } from 'msw/experimental';
8
+ import * as QUnit from 'qunit';
9
+ import { getContext } from '@ember/test-helpers';
10
+ import { setupApplicationTest as setupApplicationTest$1, setupRenderingTest as setupRenderingTest$1, setupTest as setupTest$1 } from 'ember-qunit';
11
+
12
+ function appInflector() {
13
+ if (macroCondition(dependencySatisfies('@ember-data/request-utils', '>=5.3.0'))) {
14
+ return importSync('@ember-data/request-utils/string');
15
+ } else if (macroCondition(dependencySatisfies('ember-inflector', '*'))) {
16
+ return importSync('ember-inflector');
17
+ }
18
+ return {
19
+ pluralize: word => `${word}s`,
20
+ singularize: word => word.replace(/s$/, '')
21
+ };
22
+ }
23
+ let detected;
24
+ function pluralize(word) {
25
+ return (detected ??= appInflector()).pluralize(word);
26
+ }
27
+ function singularize(word) {
28
+ return (detected ??= appInflector()).singularize(word);
29
+ }
30
+ function underscore(word) {
31
+ return word.replace(/([a-z\d])([A-Z])/g, '$1_$2').replace(/-/g, '_').toLowerCase();
32
+ }
33
+ function dasherize(word) {
34
+ return underscore(word).replace(/_/g, '-');
35
+ }
36
+ function camelize(word) {
37
+ return word.replace(/[-_\s]+(.)?/g, (_, next) => next ? next.toUpperCase() : '').replace(/^[A-Z]/, first => first.toLowerCase());
38
+ }
39
+
40
+ const KEY_RULES = {
41
+ snake: {
42
+ invalid: /[A-Z-]/,
43
+ description: 'snake_case'
44
+ },
45
+ camel: {
46
+ invalid: /[_-]/,
47
+ description: 'camelCase'
48
+ },
49
+ dash: {
50
+ invalid: /[A-Z_]/,
51
+ description: 'dasherized'
52
+ }
53
+ };
54
+ function keyError(keys, key) {
55
+ const rule = KEY_RULES[keys];
56
+ return rule.invalid.test(key) ? `Overrides use the API's ${rule.description} keys.` : undefined;
57
+ }
58
+ function collect(records, context) {
59
+ const seen = new Set(records);
60
+ const result = [];
61
+ const visit = record => {
62
+ for (const related of context.related(record)) {
63
+ if (!seen.has(related.record)) {
64
+ seen.add(related.record);
65
+ result.push(related);
66
+ visit(related.record);
67
+ }
68
+ }
69
+ };
70
+ records.forEach(visit);
71
+ return result;
72
+ }
73
+ function idUnder(body, key) {
74
+ const root = body !== null && typeof body === 'object' ? body[key] : null;
75
+ return root !== null && typeof root === 'object' ? root.id : undefined;
76
+ }
77
+ function sideloaded(rootKey) {
78
+ return {
79
+ document(type, data, extra, context) {
80
+ const many = Array.isArray(data);
81
+ const records = many ? data : [data];
82
+ const result = {
83
+ [rootKey(type, many)]: many ? [...data] : data
84
+ };
85
+ for (const {
86
+ type: relatedType,
87
+ record
88
+ } of collect(records, context)) {
89
+ const key = rootKey(relatedType, true);
90
+ (result[key] ??= []).push(record);
91
+ }
92
+ return {
93
+ ...result,
94
+ ...extra
95
+ };
96
+ },
97
+ idFromBody: (type, body) => idUnder(body, rootKey(type, false))
98
+ };
99
+ }
100
+ function activeModel() {
101
+ const rootKey = (type, plural) => plural ? pluralize(underscore(type)) : underscore(type);
102
+ return {
103
+ updateMethod: 'put',
104
+ separatesRelationships: false,
105
+ keyError: key => keyError('snake', key),
106
+ relationshipKey: (key, kind) => kind === 'belongsTo' ? `${key}_id` : `${singularize(key)}_ids`,
107
+ path: type => `/${rootKey(type, true)}`,
108
+ ...sideloaded(rootKey)
109
+ };
110
+ }
111
+ function rest(options = {}) {
112
+ const keys = options.keys ?? 'camel';
113
+ const cased = type => keys === 'snake' ? underscore(type) : keys === 'dash' ? dasherize(type) : camelize(type);
114
+ const rootKey = (type, plural) => plural ? pluralize(cased(type)) : cased(type);
115
+ return {
116
+ updateMethod: 'put',
117
+ separatesRelationships: false,
118
+ keyError: key => keyError(keys, key),
119
+ relationshipKey: key => key,
120
+ path: options.path ?? (type => `/${pluralize(camelize(type))}`),
121
+ ...sideloaded(rootKey)
122
+ };
123
+ }
124
+ function jsonApi() {
125
+ const resourceType = type => pluralize(dasherize(type));
126
+ const identifier = (type, value) => {
127
+ if (value !== null && typeof value === 'object' && 'id' in value) {
128
+ const {
129
+ type: explicit,
130
+ id
131
+ } = value;
132
+ return {
133
+ type: resourceType(explicit ?? type),
134
+ id: String(id)
135
+ };
136
+ }
137
+ return {
138
+ type: resourceType(type),
139
+ id: String(value)
140
+ };
141
+ };
142
+ const toLinkage = (relationship, value) => {
143
+ if (relationship.kind === 'hasMany') {
144
+ return (value ?? []).map(item => identifier(relationship.type, item));
145
+ }
146
+ return value == null ? null : identifier(relationship.type, value);
147
+ };
148
+ return {
149
+ updateMethod: 'patch',
150
+ separatesRelationships: true,
151
+ keyError: key => keyError('dash', key),
152
+ relationshipKey: key => key,
153
+ path: type => `/${resourceType(type)}`,
154
+ document(type, data, extra, context) {
155
+ const many = Array.isArray(data);
156
+ const records = many ? data : [data];
157
+ const related = collect(records, context);
158
+ const present = new Set([...records.map(record => ({
159
+ type,
160
+ record
161
+ })), ...related].map(({
162
+ type: t,
163
+ record
164
+ }) => `${resourceType(t)}:${String(record.id)}`));
165
+ const isPresent = linked => linked === null || [linked].flat().every(({
166
+ type: t,
167
+ id
168
+ }) => present.has(`${t}:${id}`));
169
+ const resource = (resourceOf, record) => {
170
+ const {
171
+ id,
172
+ ...rest
173
+ } = record;
174
+ const declared = context.relationships(record);
175
+ const attributes = {};
176
+ const relationships = {};
177
+ for (const [key, value] of Object.entries(rest)) {
178
+ const relationship = declared.get(key);
179
+ if (!relationship) {
180
+ attributes[key] = value;
181
+ continue;
182
+ }
183
+ const linked = toLinkage(relationship, value);
184
+ if (context.seeding || isPresent(linked)) {
185
+ relationships[key] = {
186
+ data: linked
187
+ };
188
+ }
189
+ }
190
+ return {
191
+ id: String(id),
192
+ type: resourceType(resourceOf),
193
+ attributes,
194
+ ...(Object.keys(relationships).length ? {
195
+ relationships
196
+ } : {})
197
+ };
198
+ };
199
+ return {
200
+ data: many ? records.map(record => resource(type, record)) : resource(type, data),
201
+ ...(related.length ? {
202
+ included: related.map(({
203
+ type: t,
204
+ record
205
+ }) => resource(t, record))
206
+ } : {}),
207
+ ...extra
208
+ };
209
+ },
210
+ idFromBody: (_type, body) => idUnder(body, 'data')
211
+ };
212
+ }
213
+
214
+ let options = {};
215
+ let resolved;
216
+ function configure(next) {
217
+ options = {
218
+ ...options,
219
+ ...next
220
+ };
221
+ resolved = undefined;
222
+ }
223
+ const PERCY_DEFAULT = 'http://localhost:5338';
224
+ function percyOrigin() {
225
+ const scope = globalThis;
226
+ const runtime = scope.PercySDKUtils?.percy?.address;
227
+ const address = typeof runtime === 'string' ? runtime : scope.process?.env?.PERCY_SERVER_ADDRESS ?? PERCY_DEFAULT;
228
+ return new URL(URL.canParse(address) ? address : PERCY_DEFAULT).origin;
229
+ }
230
+ function toUrl(host) {
231
+ return new URL(host, window.location.href);
232
+ }
233
+ function settings() {
234
+ if (resolved) {
235
+ return resolved;
236
+ }
237
+ const api = toUrl(options.apiHost ?? window.location.origin);
238
+ resolved = {
239
+ apiBase: `${api.origin}${api.pathname}`.replace(/\/$/, ''),
240
+ namespace: (options.namespace ?? '').replace(/^\/*/, '/').replace(/\/+$/, ''),
241
+ appOrigins: [...new Set([window.location.origin, api.origin, ...(options.origins ?? []).map(origin => toUrl(origin).origin)])],
242
+ format: options.format ?? jsonApi(),
243
+ beacons: options.beacons ?? false,
244
+ bypass: (options.bypass ?? []).map(origin => toUrl(origin).origin),
245
+ bypassPercy: options.bypass === undefined
246
+ };
247
+ return resolved;
248
+ }
249
+
250
+ const definitions = new Map();
251
+ const sequences = new Map();
252
+ const sideloads = new WeakMap();
253
+ const relationshipMaps = new WeakMap();
254
+ const transients = new WeakMap();
255
+ const overrideKeys = new WeakMap();
256
+ const factories = new WeakMap();
257
+ class Sequence {
258
+ constructor(generate) {
259
+ this.generate = generate;
260
+ }
261
+ }
262
+ class Association {
263
+ constructor(kind, type, args) {
264
+ this.kind = kind;
265
+ this.type = type;
266
+ this.args = args;
267
+ }
268
+ }
269
+ function isPlainObject(value) {
270
+ return value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;
271
+ }
272
+ function clone(value) {
273
+ if (Array.isArray(value)) {
274
+ return value.map(clone);
275
+ } else if (isPlainObject(value)) {
276
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clone(item)]));
277
+ }
278
+ return value;
279
+ }
280
+ function nextId(name) {
281
+ const id = (sequences.get(name) ?? 0) + 1;
282
+ sequences.set(name, id);
283
+ return id;
284
+ }
285
+ function resetSequences() {
286
+ sequences.clear();
287
+ }
288
+ function defineFactory(name, definition = {}) {
289
+ definitions.set(name, definition);
290
+ }
291
+ function belongsTo(type, ...args) {
292
+ return new Association('belongsTo', type, args);
293
+ }
294
+ function hasMany(type, ...args) {
295
+ return new Association('hasMany', type, args);
296
+ }
297
+ function fragment(type, ...args) {
298
+ return new Association('fragment', type, args);
299
+ }
300
+ function sequence(generate) {
301
+ return new Sequence(generate);
302
+ }
303
+ function definitionOf(name) {
304
+ const definition = definitions.get(name) ?? {};
305
+ return {
306
+ ...definition,
307
+ format: definition.format ?? settings().format
308
+ };
309
+ }
310
+ function isBuilt(value) {
311
+ return value !== null && typeof value === 'object' && factories.has(value);
312
+ }
313
+ function link({
314
+ kind,
315
+ type
316
+ }, value, related) {
317
+ const items = kind === 'hasMany' ? [value ?? []].flat() : [value];
318
+ for (const item of items.filter(isBuilt)) {
319
+ related.push({
320
+ type: factoryOf(item) ?? type,
321
+ record: item
322
+ });
323
+ }
324
+ const idOf = item => isBuilt(item) ? item.id : item;
325
+ return kind === 'hasMany' ? items.map(idOf) : idOf(value);
326
+ }
327
+ function build(name, ...args) {
328
+ const definition = definitions.get(name);
329
+ if (!definition) {
330
+ throw new Error(`No factory defined for "${name}"`);
331
+ }
332
+ const {
333
+ format
334
+ } = definitionOf(name);
335
+ const last = args.at(-1);
336
+ const overrides = isPlainObject(last) ? args.pop() : {};
337
+ const transientKeys = new Set(Object.keys(definition.transient ?? {}));
338
+ const declared = definition.relationships ?? {};
339
+ const attrs = {
340
+ ...definition.transient,
341
+ ...definition.default
342
+ };
343
+ const mutations = [];
344
+ for (const trait of args) {
345
+ const traitAttrs = definition.traits?.[trait];
346
+ if (!traitAttrs) {
347
+ throw new Error(`Factory "${name}" has no trait "${trait}"`);
348
+ } else if (typeof traitAttrs === 'function') {
349
+ mutations.push(traitAttrs);
350
+ } else {
351
+ Object.assign(attrs, traitAttrs);
352
+ }
353
+ }
354
+ for (const key of Object.keys(overrides)) {
355
+ const error = transientKeys.has(key) || key in declared ? undefined : format.keyError(key);
356
+ if (error) {
357
+ throw new Error(`build('${name}') got "${key}". ${error}`);
358
+ }
359
+ }
360
+ Object.assign(attrs, overrides);
361
+ const {
362
+ id
363
+ } = attrs;
364
+ const record = {
365
+ id: id instanceof Sequence ? id.generate(nextId(name)) : id ?? nextId(name)
366
+ };
367
+ if (Number.isInteger(Number(id)) && id !== '' && id !== null) {
368
+ sequences.set(name, Math.max(sequences.get(name) ?? 0, Number(id)));
369
+ }
370
+ const related = [];
371
+ const relationships = new Map();
372
+ const options = {};
373
+ const deferred = [];
374
+ for (const [key, value] of Object.entries(attrs)) {
375
+ if (key === 'id') {
376
+ continue;
377
+ } else if (transientKeys.has(key)) {
378
+ options[key] = value;
379
+ } else if (value instanceof Sequence) {
380
+ record[key] = value.generate(nextId(`${name}.${key}`));
381
+ } else if (value instanceof Association && value.kind === 'fragment') {
382
+ const {
383
+ id: _id,
384
+ ...nested
385
+ } = build(value.type, ...value.args);
386
+ record[key] = nested;
387
+ } else if (value instanceof Association || declared[key]) {
388
+ const {
389
+ type,
390
+ kind
391
+ } = value instanceof Association ? value : declared[key];
392
+ if (value instanceof Association && kind === 'hasMany' && !value.args.length) {
393
+ throw new Error(`hasMany('${type}') in a default or trait needs a count`);
394
+ }
395
+ const built = value instanceof Association ? kind === 'hasMany' ? buildList(type, ...value.args) : build(type, ...value.args) : value;
396
+ const wireKey = format.relationshipKey(key, kind);
397
+ record[wireKey] = link({
398
+ type,
399
+ kind
400
+ }, built, related);
401
+ relationships.set(wireKey, {
402
+ type,
403
+ kind
404
+ });
405
+ } else if (typeof value === 'function') {
406
+ record[key] = undefined;
407
+ deferred.push([key, value]);
408
+ } else if ([value].flat().some(isBuilt)) {
409
+ throw new Error(`build('${name}') got built records under "${key}". Declare it in the ${name} factory's relationships: { ${key}: belongsTo(...) } or hasMany(...).`);
410
+ } else {
411
+ record[key] = clone(value);
412
+ }
413
+ }
414
+ deferred.forEach(([key, value]) => record[key] = value(record));
415
+ mutations.forEach(mutate => mutate(record));
416
+ sideloads.set(record, related);
417
+ relationshipMaps.set(record, relationships);
418
+ transients.set(record, options);
419
+ factories.set(record, name);
420
+ overrideKeys.set(record, Object.entries(overrides).filter(([key]) => !transientKeys.has(key)).map(([key, value]) => {
421
+ const association = value instanceof Association ? value : declared[key];
422
+ return association && association.kind !== 'fragment' ? {
423
+ key: format.relationshipKey(key, association.kind),
424
+ relationship: true
425
+ } : {
426
+ key,
427
+ relationship: false
428
+ };
429
+ }));
430
+ return record;
431
+ }
432
+ function buildList(name, ...args) {
433
+ if (typeof args[0] === 'number') {
434
+ const [count, ...rest] = args;
435
+ return Array.from({
436
+ length: count
437
+ }, () => build(name, ...rest));
438
+ }
439
+ return args.map(spec => build(name, ...[spec].flat()));
440
+ }
441
+ function factoryOf(record) {
442
+ return isPlainObject(record) ? factories.get(record) : undefined;
443
+ }
444
+ function transientOf(record) {
445
+ return transients.get(record) ?? {};
446
+ }
447
+ function overridesOf(record) {
448
+ return overrideKeys.get(record) ?? [];
449
+ }
450
+ function sideload(record, ...related) {
451
+ const list = sideloads.get(record) ?? [];
452
+ for (const item of related) {
453
+ const type = item && factoryOf(item);
454
+ if (item && type) {
455
+ list.push({
456
+ type,
457
+ record: item
458
+ });
459
+ }
460
+ }
461
+ sideloads.set(record, list);
462
+ return record;
463
+ }
464
+ function declaredRelationships(name, format) {
465
+ return Object.entries(definitions.get(name)?.relationships ?? {}).filter(([, association]) => association.kind !== 'fragment').map(([key, association]) => {
466
+ const kind = association.kind;
467
+ return [key, format.relationshipKey(key, kind), {
468
+ type: association.type,
469
+ kind
470
+ }];
471
+ });
472
+ }
473
+ function prepare(type, record, format, cache) {
474
+ const cached = cache.get(record);
475
+ if (cached) {
476
+ return cached;
477
+ }
478
+ const relationships = new Map(relationshipMaps.get(record) ?? []);
479
+ const related = [...(sideloads.get(record) ?? [])];
480
+ let copy = record;
481
+ for (const [key, wireKey, relationship] of declaredRelationships(factoryOf(record) ?? type, format)) {
482
+ relationships.set(wireKey, relationship);
483
+ const source = key in record && key !== wireKey ? key : wireKey;
484
+ const value = record[source];
485
+ if (source === wireKey && ![value].flat().some(isBuilt)) {
486
+ continue;
487
+ }
488
+ copy = copy === record ? {
489
+ ...record
490
+ } : copy;
491
+ delete copy[source];
492
+ copy[wireKey] = link(relationship, value, related);
493
+ }
494
+ const prepared = {
495
+ record: copy,
496
+ related,
497
+ relationships
498
+ };
499
+ cache.set(record, prepared);
500
+ cache.set(copy, prepared);
501
+ return prepared;
502
+ }
503
+ function documentFor(type, data, extra, seeding) {
504
+ const {
505
+ format
506
+ } = definitionOf(type);
507
+ const cache = new Map();
508
+ const prepared = (record, recordType = type) => prepare(recordType, record, format, cache);
509
+ const records = Array.isArray(data) ? data.map(record => prepared(record).record) : prepared(data).record;
510
+ return format.document(type, records, extra, {
511
+ seeding,
512
+ related: record => prepared(record).related.map(entry => ({
513
+ type: entry.type,
514
+ record: prepared(entry.record, entry.type).record
515
+ })),
516
+ relationships: record => prepared(record).relationships
517
+ });
518
+ }
519
+ function payload(type, data, extra = {}) {
520
+ return documentFor(type, data, extra, false);
521
+ }
522
+ function mergePayloads(...payloads) {
523
+ const result = {};
524
+ for (const [key, value] of payloads.flatMap(Object.entries)) {
525
+ const existing = result[key];
526
+ result[key] = Array.isArray(existing) && Array.isArray(value) ? [...existing, ...value] : value;
527
+ }
528
+ return result;
529
+ }
530
+
531
+ let installed$1 = false;
532
+ function installBeaconShim() {
533
+ if (installed$1 || typeof navigator.sendBeacon !== 'function') {
534
+ return;
535
+ }
536
+ installed$1 = true;
537
+ Object.defineProperty(navigator, 'sendBeacon', {
538
+ configurable: true,
539
+ writable: true,
540
+ value(url, data) {
541
+ fetch(url, {
542
+ method: 'POST',
543
+ body: data ?? null,
544
+ keepalive: true
545
+ }).catch(() => undefined);
546
+ return true;
547
+ }
548
+ });
549
+ }
550
+ function removeBeaconShim() {
551
+ if (installed$1) {
552
+ delete navigator.sendBeacon;
553
+ installed$1 = false;
554
+ }
555
+ }
556
+
557
+ const waiter$1 = buildWaiter('ember-api-mocks:responses');
558
+ const nativeSetTimeout = window.setTimeout.bind(window);
559
+ const READERS = ['json', 'text', 'arrayBuffer', 'blob', 'formData', 'bytes'];
560
+ const open = new Set();
561
+ let installed;
562
+ function afterTwoMacrotasks(callback) {
563
+ nativeSetTimeout(() => nativeSetTimeout(callback, 0), 0);
564
+ }
565
+ function end(pending) {
566
+ if (!pending.ended) {
567
+ pending.ended = true;
568
+ waiter$1.endAsync(pending.token);
569
+ open.delete(pending);
570
+ }
571
+ }
572
+ function endAfterReads(pending) {
573
+ nativeSetTimeout(() => {
574
+ if (pending.reads === 0) {
575
+ end(pending);
576
+ }
577
+ }, 0);
578
+ }
579
+ function instrument(response, pending) {
580
+ const target = response;
581
+ for (const reader of READERS) {
582
+ const original = target[reader];
583
+ if (typeof original !== 'function') {
584
+ continue;
585
+ }
586
+ target[reader] = (...args) => {
587
+ pending.reads += 1;
588
+ pending.readStarted = true;
589
+ return original.apply(response, args).finally(() => {
590
+ pending.reads -= 1;
591
+ endAfterReads(pending);
592
+ });
593
+ };
594
+ }
595
+ const clone = response.clone.bind(response);
596
+ target.clone = () => instrument(clone(), pending);
597
+ return response;
598
+ }
599
+ function urlOf(input) {
600
+ const raw = input instanceof Request ? input.url : String(input);
601
+ return URL.canParse(raw, window.location.href) ? new URL(raw, window.location.href).href : undefined;
602
+ }
603
+ const WRAPPER = Symbol.for('ember-api-mocks.fetch');
604
+ function stateOf(value) {
605
+ return typeof value === 'function' ? value[WRAPPER] : undefined;
606
+ }
607
+ function unwrapStaleFetch() {
608
+ let current = globalThis.fetch;
609
+ for (let state = stateOf(current); state && !state.active; state = stateOf(current)) {
610
+ current = state.original;
611
+ }
612
+ if (current !== globalThis.fetch) {
613
+ globalThis.fetch = current;
614
+ }
615
+ }
616
+ function installFetchWaiter(original, tracks) {
617
+ if (installed) {
618
+ return;
619
+ }
620
+ const inner = globalThis.fetch;
621
+ const state = {
622
+ original,
623
+ active: true
624
+ };
625
+ const wrapper = function (input, init) {
626
+ if (!state.active) {
627
+ const passThrough = state.original;
628
+ return passThrough(input, init);
629
+ }
630
+ const url = urlOf(input);
631
+ if (url === undefined || !tracks(url)) {
632
+ return inner(input, init);
633
+ }
634
+ const pending = {
635
+ token: waiter$1.beginAsync(),
636
+ reads: 0,
637
+ readStarted: false,
638
+ ended: false
639
+ };
640
+ open.add(pending);
641
+ return inner(input, init).then(response => {
642
+ afterTwoMacrotasks(() => {
643
+ if (!pending.readStarted) {
644
+ end(pending);
645
+ }
646
+ });
647
+ return instrument(response, pending);
648
+ }, error => {
649
+ endAfterReads(pending);
650
+ throw error;
651
+ });
652
+ };
653
+ Object.defineProperty(wrapper, WRAPPER, {
654
+ value: state
655
+ });
656
+ installed = {
657
+ wrapper,
658
+ inner,
659
+ state
660
+ };
661
+ globalThis.fetch = wrapper;
662
+ }
663
+ function endOpenResponses() {
664
+ [...open].forEach(end);
665
+ }
666
+ function removeFetchWaiter() {
667
+ if (installed) {
668
+ installed.state.active = false;
669
+ if (globalThis.fetch === installed.wrapper) {
670
+ globalThis.fetch = installed.inner;
671
+ }
672
+ installed = undefined;
673
+ }
674
+ endOpenResponses();
675
+ }
676
+
677
+ const nearMisses = new Map();
678
+ let reporter = failure => QUnit.onUncaughtException(failure);
679
+ function reportFailure(failure) {
680
+ reporter(failure instanceof Error ? failure : new Error(String(failure)));
681
+ }
682
+ function describe(value) {
683
+ return JSON.stringify(value, (_key, item) => typeof item === 'function' ? '[predicate]' : item, 2);
684
+ }
685
+ function describeNearMisses(requestId) {
686
+ return (nearMisses.get(requestId) ?? []).map(({
687
+ expected,
688
+ received
689
+ }) => {
690
+ const actual = Object.fromEntries(Object.keys(expected).map(key => {
691
+ const value = received[key === 'partialQuery' ? 'query' : key];
692
+ return [key, key === 'headers' ? Object.fromEntries(Object.keys(expected.headers).map(name => [name, value[name] ?? null])) : value];
693
+ }));
694
+ return `\nA handler for this URL expected ${describe(expected)}\nbut received ${describe(actual)}`;
695
+ }).join('');
696
+ }
697
+ function isBypassed(url) {
698
+ if (!/^https?:/.test(url)) {
699
+ return true;
700
+ }
701
+ const {
702
+ origin
703
+ } = new URL(url);
704
+ const {
705
+ bypass,
706
+ bypassPercy
707
+ } = settings();
708
+ return bypass.includes(origin) || bypassPercy && origin === percyOrigin();
709
+ }
710
+ const unhandled = http.all('*', ({
711
+ request,
712
+ requestId
713
+ }) => {
714
+ if (isBypassed(request.url)) {
715
+ return passthrough();
716
+ }
717
+ if (settings().appOrigins.includes(new URL(request.url).origin)) {
718
+ reportFailure(new Error(`No handler for ${request.method} ${request.url}${describeNearMisses(requestId)}`));
719
+ }
720
+ return new HttpResponse(null, {
721
+ status: 404
722
+ });
723
+ });
724
+ const nativeNow = performance.now.bind(performance);
725
+ const waiter = buildWaiter('ember-api-mocks:requests');
726
+ const pendingRequests = new Map();
727
+ function startRequest(requestId, request) {
728
+ if (!isBypassed(request.url) && !pendingRequests.has(requestId)) {
729
+ pendingRequests.set(requestId, waiter.beginAsync());
730
+ }
731
+ }
732
+ function endRequest(requestId) {
733
+ if (pendingRequests.has(requestId)) {
734
+ waiter.endAsync(pendingRequests.get(requestId));
735
+ pendingRequests.delete(requestId);
736
+ }
737
+ }
738
+ function finishRequest(requestId) {
739
+ if (pendingRequests.has(requestId)) {
740
+ afterTwoMacrotasks(() => endRequest(requestId));
741
+ }
742
+ }
743
+ function forgetPendingRequests() {
744
+ [...pendingRequests.keys()].forEach(endRequest);
745
+ }
746
+ function createNetwork() {
747
+ const created = defineNetwork({
748
+ sources: [new InterceptorSource({
749
+ interceptors: [new XMLHttpRequestInterceptor(), new FetchInterceptor()]
750
+ })],
751
+ handlers: [unhandled],
752
+ onUnhandledFrame: 'bypass',
753
+ context: {
754
+ quiet: true
755
+ }
756
+ });
757
+ created.events.on('request:start', event => {
758
+ const {
759
+ requestId,
760
+ request
761
+ } = event;
762
+ startRequest(requestId, request);
763
+ });
764
+ created.events.on('request:end', event => finishRequest(event.requestId));
765
+ return created;
766
+ }
767
+ let instance;
768
+ function network() {
769
+ return instance ??= createNetwork();
770
+ }
771
+ function useHandler(handler) {
772
+ network().use(handler);
773
+ }
774
+ function enableNetwork() {
775
+ unwrapStaleFetch();
776
+ const original = globalThis.fetch;
777
+ network().enable();
778
+ installFetchWaiter(original, url => !isBypassed(url));
779
+ if (settings().beacons) {
780
+ installBeaconShim();
781
+ }
782
+ }
783
+ function disableNetwork() {
784
+ removeBeaconShim();
785
+ removeFetchWaiter();
786
+ network().resetHandlers();
787
+ network().disable();
788
+ forgetPendingRequests();
789
+ nearMisses.clear();
790
+ }
791
+ const SETTLE_LIMIT_MS = 1000;
792
+ async function settleRequests() {
793
+ const deadline = nativeNow() + SETTLE_LIMIT_MS;
794
+ let quiet = 0;
795
+ while (quiet < 2 && nativeNow() < deadline) {
796
+ await new Promise(resolve => nativeSetTimeout(resolve, 0));
797
+ quiet = pendingRequests.size === 0 && !hasPendingWaiters() ? quiet + 1 : 0;
798
+ }
799
+ if (quiet < 2) {
800
+ const names = Object.keys(getPendingWaiterState().waiters);
801
+ const others = names.filter(name => !name.startsWith('ember-api-mocks:'));
802
+ reportFailure(new Error(others.length && others.length === names.length ? `Test waiters were still pending when the test ended: ${others.join(', ')}` : 'Requests were still pending when the test ended'));
803
+ }
804
+ forgetPendingRequests();
805
+ endOpenResponses();
806
+ }
807
+
808
+ /* Minimal structural types so the addon works with ember-data 4.12 and 5.x */
809
+
810
+ const sources = new WeakMap();
811
+ function isFragment(modelClass) {
812
+ if (macroCondition(dependencySatisfies('ember-data-model-fragments', '*'))) {
813
+ const {
814
+ default: Fragment
815
+ } = importSync('ember-data-model-fragments/fragment');
816
+ return modelClass.prototype instanceof Fragment;
817
+ }
818
+ return false;
819
+ }
820
+ function attributeKeys(serializer, modelClass) {
821
+ const keys = new Set(['id']);
822
+ const add = attribute => {
823
+ keys.add(attribute);
824
+ keys.add(serializer.keyForAttribute(attribute, 'deserialize'));
825
+ };
826
+ modelClass.eachAttribute(add);
827
+ modelClass.eachComputedProperty?.((name, meta) => {
828
+ if (meta?.isAttribute) {
829
+ add(name);
830
+ }
831
+ });
832
+ return keys;
833
+ }
834
+ function modelKeys(serializer, modelClass) {
835
+ const keys = attributeKeys(serializer, modelClass);
836
+ const relationships = new Set();
837
+ modelClass.eachRelationship((relationship, {
838
+ kind
839
+ }) => {
840
+ const key = serializer.keyForRelationship(relationship, kind, 'deserialize');
841
+ relationships.add(key);
842
+ keys.add(key);
843
+ keys.add(`${key.replace(/_ids?$/, '')}_type`);
844
+ });
845
+ for (const [name, mapping] of Object.entries(serializer.attrs ?? {})) {
846
+ keys.add(serializer.keyForAttribute(name, 'deserialize'));
847
+ const key = typeof mapping === 'string' ? mapping : mapping.key;
848
+ if (key) {
849
+ keys.add(key);
850
+ }
851
+ }
852
+ return {
853
+ keys,
854
+ relationships
855
+ };
856
+ }
857
+ function rejectUnusedOverrides(name, record, {
858
+ keys,
859
+ relationships
860
+ }) {
861
+ const overrides = overridesOf(record);
862
+ const undeclared = overrides.find(({
863
+ key,
864
+ relationship
865
+ }) => !relationship && relationships.has(key));
866
+ if (undeclared && definitionOf(name).format.separatesRelationships) {
867
+ throw new Error(`seed('${name}') got ${undeclared.key}, a relationship the ${name} factory does not declare. Declare it in the factory's relationships: { ${undeclared.key}: belongsTo(...) } or hasMany(...).`);
868
+ }
869
+ const unused = overrides.map(({
870
+ key
871
+ }) => key).filter(key => !keys.has(key));
872
+ if (unused.length) {
873
+ throw new Error(`seed('${name}') got ${unused.join(', ')}, which the ${name} model does not read. Use the keys the API sends.`);
874
+ }
875
+ }
876
+ function currentStore() {
877
+ const context = getContext();
878
+ if (!context?.owner) {
879
+ throw new Error('seed() needs a test set up with setupTest or setupRenderingTest');
880
+ }
881
+ return context.owner.lookup('service:store');
882
+ }
883
+ function pushFragment(store, name, modelClass, record) {
884
+ const serializer = store.serializerFor(name);
885
+ const {
886
+ id: _id,
887
+ ...attrs
888
+ } = record;
889
+ const {
890
+ data
891
+ } = serializer.normalize(modelClass, attrs);
892
+ const fragment = store.createFragment(name, data.attributes);
893
+ const known = attributeKeys(serializer, modelClass);
894
+ for (const [key, value] of Object.entries(attrs)) {
895
+ if (!known.has(key)) {
896
+ fragment[key] = value;
897
+ }
898
+ }
899
+ return fragment;
900
+ }
901
+ function push(name, record) {
902
+ const store = currentStore();
903
+ const modelClass = store.modelFor(name);
904
+ if (isFragment(modelClass)) {
905
+ return pushFragment(store, name, modelClass, record);
906
+ }
907
+ rejectUnusedOverrides(name, record, modelKeys(store.serializerFor(name), modelClass));
908
+ const {
909
+ beforeSeed,
910
+ afterSeed
911
+ } = definitionOf(name);
912
+ beforeSeed?.(record, store);
913
+ store.pushPayload(name, JSON.parse(JSON.stringify(documentFor(name, record, {}, true))));
914
+ const model = store.peekRecord(name, String(record.id));
915
+ sources.set(model, record);
916
+ afterSeed?.(model, transientOf(record));
917
+ return model;
918
+ }
919
+ function seed(name, ...args) {
920
+ return push(name, build(name, ...args));
921
+ }
922
+ function seedList(name, ...args) {
923
+ return buildList(name, ...args).map(record => push(name, record));
924
+ }
925
+ function seedRecord(record) {
926
+ const name = factoryOf(record);
927
+ if (!name) {
928
+ throw new Error('seedRecord() takes a record from build()');
929
+ }
930
+ return push(name, record);
931
+ }
932
+ function sourceOf(value) {
933
+ if (value !== null && typeof value === 'object' && sources.has(value)) {
934
+ return sources.get(value);
935
+ }
936
+ const modelName = value?.constructor?.modelName;
937
+ if (typeof modelName === 'string') {
938
+ throw new Error(`A ${modelName} record that was not created with seed() was used in a mocked response. Pass API JSON instead.`);
939
+ }
940
+ return value;
941
+ }
942
+
943
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
944
+
945
+ const requests = [];
946
+ function parseEntries(entries) {
947
+ const result = {};
948
+ for (const [path, value] of entries) {
949
+ const keys = path.replace(/\]/g, '').split('[');
950
+ let node = result;
951
+ keys.forEach((key, index) => {
952
+ const next = keys[index + 1];
953
+ const slot = Array.isArray(node) && key === '' ? String(node.length) : key;
954
+ const current = Object.hasOwn(node, slot) ? node[slot] : undefined;
955
+ const item = next === undefined ? current === undefined ? value : [current, value].flat() : isObject(current) ? current : /^\d*$/.test(next) ? [] : {};
956
+ Object.defineProperty(node, slot, {
957
+ value: item,
958
+ enumerable: true,
959
+ writable: true,
960
+ configurable: true
961
+ });
962
+ node = item;
963
+ });
964
+ }
965
+ return result;
966
+ }
967
+ async function parseBody(request) {
968
+ const contentType = request.headers.get('content-type') ?? '';
969
+ if (!request.body) {
970
+ return undefined;
971
+ } else if (contentType.includes('json')) {
972
+ return request.clone().json();
973
+ } else if (contentType.includes('form-data') || contentType.includes('x-www-form-urlencoded')) {
974
+ return parseEntries(await request.clone().formData());
975
+ }
976
+ return request.clone().text();
977
+ }
978
+ function plain(value) {
979
+ return value !== null && typeof value === 'object' && typeof value.toJSON === 'function' ? value.toJSON() : value;
980
+ }
981
+ function text(value) {
982
+ return typeof value === 'string' ? value : JSON.stringify(value) ?? '';
983
+ }
984
+ function isObject(value) {
985
+ return value !== null && typeof value === 'object';
986
+ }
987
+ function isSubset(expected, actual, exact = false) {
988
+ expected = plain(expected);
989
+ if (typeof expected === 'function') {
990
+ return Boolean(expected(actual));
991
+ } else if (Array.isArray(expected)) {
992
+ return Array.isArray(actual) && actual.length === expected.length && expected.every((value, index) => isSubset(value, actual[index], exact));
993
+ } else if (isObject(expected)) {
994
+ const entries = Object.entries(expected);
995
+ const required = entries.filter(([, value]) => value !== undefined);
996
+ return isObject(actual) && !Array.isArray(actual) && (!exact || required.length === Object.keys(actual).length) && entries.every(([key, value]) => (Object.hasOwn(actual, key) || value === undefined || typeof value === 'function') && isSubset(value, actual[key], exact));
997
+ } else if (expected === null || expected === undefined) {
998
+ return actual === expected;
999
+ } else if (isObject(actual)) {
1000
+ return false;
1001
+ }
1002
+ return text(expected) === text(actual);
1003
+ }
1004
+ function hasHeaders(expected, headers) {
1005
+ return Object.entries(expected).every(([name, value]) => {
1006
+ const actual = headers.get(name);
1007
+ if (typeof value === 'function') {
1008
+ return Boolean(value(actual));
1009
+ }
1010
+ return value == null ? actual === null : actual === text(value);
1011
+ });
1012
+ }
1013
+ function matches({
1014
+ body,
1015
+ query,
1016
+ partialQuery,
1017
+ headers
1018
+ }, call) {
1019
+ return (body === undefined || isSubset(body, call.body)) && (query === undefined || isSubset(query, call.query, true)) && (partialQuery === undefined || isSubset(partialQuery, call.query)) && (headers === undefined || hasHeaders(headers, call.headers));
1020
+ }
1021
+ function unwrapRecords(body) {
1022
+ if (!isObject(body) || Object.getPrototypeOf(body) !== Object.prototype) {
1023
+ return body;
1024
+ }
1025
+ return Object.fromEntries(Object.entries(body).map(([key, value]) => [key, Array.isArray(value) ? value.map(sourceOf) : sourceOf(value)]));
1026
+ }
1027
+ async function toResponse(response, call) {
1028
+ const resolved = typeof response === 'function' ? await response(call) : response;
1029
+ if (resolved instanceof Response) {
1030
+ return resolved.clone();
1031
+ } else if (resolved == null) {
1032
+ return new HttpResponse(null, {
1033
+ status: 204
1034
+ });
1035
+ }
1036
+ return HttpResponse.json(unwrapRecords(resolved));
1037
+ }
1038
+ function absoluteUrl(path) {
1039
+ if (/^https?:/.test(path)) {
1040
+ return path;
1041
+ } else if (path.startsWith('//')) {
1042
+ return `${window.location.protocol}${path}`;
1043
+ } else if (!path.startsWith('/')) {
1044
+ throw new Error(`api paths start with "/" or are absolute URLs, got "${path}"`);
1045
+ }
1046
+ return `${settings().apiBase}${path}`;
1047
+ }
1048
+ function register(method, path, initial, toPayload) {
1049
+ const url = absoluteUrl(path);
1050
+ const calls = [];
1051
+ let response = initial;
1052
+ let removed = false;
1053
+ let where = {};
1054
+ const handle = {
1055
+ calls,
1056
+ get timesCalled() {
1057
+ return calls.length;
1058
+ },
1059
+ get lastCall() {
1060
+ return calls.at(-1);
1061
+ },
1062
+ returns(...args) {
1063
+ const [value] = args;
1064
+ const isRaw = value === null || value instanceof Response || typeof value === 'function';
1065
+ response = toPayload && !isRaw ? toPayload(...args) : value;
1066
+ return handle;
1067
+ },
1068
+ fails(status = 500, body = {}) {
1069
+ response = reply(status, body);
1070
+ return handle;
1071
+ },
1072
+ match(body) {
1073
+ where = {
1074
+ ...where,
1075
+ body
1076
+ };
1077
+ return handle;
1078
+ },
1079
+ withQuery(query, {
1080
+ partial = false
1081
+ } = {}) {
1082
+ const {
1083
+ query: _query,
1084
+ partialQuery: _partial,
1085
+ ...rest
1086
+ } = where;
1087
+ where = {
1088
+ ...rest,
1089
+ [partial ? 'partialQuery' : 'query']: query
1090
+ };
1091
+ return handle;
1092
+ },
1093
+ withHeaders(headers) {
1094
+ where = {
1095
+ ...where,
1096
+ headers: {
1097
+ ...where.headers,
1098
+ ...Object.fromEntries(Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]))
1099
+ }
1100
+ };
1101
+ return handle;
1102
+ },
1103
+ remove() {
1104
+ removed = true;
1105
+ }
1106
+ };
1107
+ const respond = async ({
1108
+ request,
1109
+ params,
1110
+ requestId
1111
+ }) => {
1112
+ if (removed || isBypassed(request.url)) {
1113
+ return undefined;
1114
+ }
1115
+ const call = {
1116
+ method: request.method,
1117
+ url: request.url,
1118
+ params,
1119
+ query: parseEntries(new URL(request.url).searchParams),
1120
+ body: await parseBody(request),
1121
+ headers: request.headers
1122
+ };
1123
+ if (!matches(where, call)) {
1124
+ nearMisses.set(requestId, [...(nearMisses.get(requestId) ?? []), {
1125
+ expected: where,
1126
+ received: {
1127
+ ...call,
1128
+ headers: Object.fromEntries(call.headers)
1129
+ }
1130
+ }]);
1131
+ return undefined;
1132
+ }
1133
+ calls.push(call);
1134
+ requests.push(call);
1135
+ return toResponse(response, call);
1136
+ };
1137
+ useHandler(http[method](url, async info => {
1138
+ try {
1139
+ return await respond(info);
1140
+ } catch (failure) {
1141
+ finishRequest(info.requestId);
1142
+ reportFailure(failure);
1143
+ throw failure;
1144
+ }
1145
+ }));
1146
+ return handle;
1147
+ }
1148
+ function collectionUrl(type) {
1149
+ const {
1150
+ url,
1151
+ format
1152
+ } = definitionOf(type);
1153
+ return url ?? `${settings().namespace}${format.path(type)}`;
1154
+ }
1155
+ function memberUrl(type, id) {
1156
+ return `${collectionUrl(type)}/${id == null ? ':id' : text(id)}`;
1157
+ }
1158
+ function resolve(typeOrRecord, ...args) {
1159
+ if (typeof typeOrRecord === 'string') {
1160
+ const [recordOrId, ...rest] = args;
1161
+ if (typeof recordOrId === 'function' || recordOrId instanceof Response || isObject(recordOrId) && !('id' in recordOrId)) {
1162
+ return {
1163
+ type: typeOrRecord,
1164
+ rest: args
1165
+ };
1166
+ }
1167
+ const isRecord = isObject(recordOrId);
1168
+ return {
1169
+ type: typeOrRecord,
1170
+ record: isRecord ? recordOrId : undefined,
1171
+ id: isRecord ? recordOrId.id : recordOrId,
1172
+ rest
1173
+ };
1174
+ }
1175
+ const record = typeOrRecord;
1176
+ const type = record.constructor.modelName ?? factoryOf(record);
1177
+ if (!type) {
1178
+ throw new Error('api shortcuts need a type name, a record from build() or a seeded model');
1179
+ }
1180
+ return {
1181
+ type,
1182
+ record,
1183
+ id: record.id,
1184
+ rest: args
1185
+ };
1186
+ }
1187
+ function reply(status, body) {
1188
+ return body === undefined ? new HttpResponse(null, {
1189
+ status
1190
+ }) : HttpResponse.json(body, {
1191
+ status
1192
+ });
1193
+ }
1194
+ function clearRequests() {
1195
+ requests.length = 0;
1196
+ }
1197
+ const api = {
1198
+ get requests() {
1199
+ return requests;
1200
+ },
1201
+ lastRequest(method, path) {
1202
+ const {
1203
+ pathname
1204
+ } = new URL(absoluteUrl(path));
1205
+ return requests.findLast(call => call.method === method.toUpperCase() && new URL(call.url).pathname === pathname);
1206
+ },
1207
+ get: (path, response) => register('get', path, response),
1208
+ post: (path, response) => register('post', path, response),
1209
+ put: (path, response) => register('put', path, response),
1210
+ patch: (path, response) => register('patch', path, response),
1211
+ delete: (path, response) => register('delete', path, response),
1212
+ find(typeOrRecord, ...args) {
1213
+ const {
1214
+ type,
1215
+ record,
1216
+ id,
1217
+ rest
1218
+ } = resolve(typeOrRecord, ...args);
1219
+ const [last] = rest;
1220
+ const raw = typeof last === 'function' || last instanceof Response ? last : undefined;
1221
+ const extra = raw === undefined && isObject(last) ? last : undefined;
1222
+ const one = (value, more) => () => payload(type, sourceOf(value), more);
1223
+ const any = more => ({
1224
+ params
1225
+ }) => payload(type, {
1226
+ id: id ?? params.id
1227
+ }, more);
1228
+ return register('get', memberUrl(type, id), raw ?? (record ? one(record, extra) : any(extra)), one);
1229
+ },
1230
+ query(type, records = [], extra = {}) {
1231
+ const many = (list = [], more = {}) => () => payload(type, list.map(sourceOf), more);
1232
+ return register('get', collectionUrl(type), many(records, extra), many);
1233
+ },
1234
+ create(type, attrs = {}) {
1235
+ const {
1236
+ format
1237
+ } = definitionOf(type);
1238
+ const created = values => typeof values === 'function' ? values : ({
1239
+ body
1240
+ }) => payload(type, {
1241
+ id: format.idFromBody(type, body) ?? nextId(type),
1242
+ ...values
1243
+ });
1244
+ return register('post', collectionUrl(type), created(attrs), created);
1245
+ },
1246
+ update(typeOrRecord, ...args) {
1247
+ const {
1248
+ type,
1249
+ id,
1250
+ rest
1251
+ } = resolve(typeOrRecord, ...args);
1252
+ const attrs = rest[0] ?? {};
1253
+ const updated = values => typeof values === 'function' ? values : ({
1254
+ params
1255
+ }) => payload(type, {
1256
+ id: id ?? params.id,
1257
+ ...values
1258
+ });
1259
+ return register(definitionOf(type).format.updateMethod, memberUrl(type, id), updated(attrs), updated);
1260
+ },
1261
+ destroy(typeOrRecord, ...args) {
1262
+ const {
1263
+ type,
1264
+ id,
1265
+ rest
1266
+ } = resolve(typeOrRecord, ...args);
1267
+ return register('delete', memberUrl(type, id), rest[0] ?? null);
1268
+ }
1269
+ };
1270
+
1271
+ function withApi(setup) {
1272
+ return function (hooks, options) {
1273
+ hooks.beforeEach(function () {
1274
+ resetSequences();
1275
+ enableNetwork();
1276
+ });
1277
+ hooks.afterEach(function () {
1278
+ disableNetwork();
1279
+ clearRequests();
1280
+ });
1281
+ setup(hooks, options);
1282
+ hooks.afterEach(settleRequests);
1283
+ };
1284
+ }
1285
+ const setupApplicationTest = withApi(setupApplicationTest$1);
1286
+ const setupRenderingTest = withApi(setupRenderingTest$1);
1287
+ const setupTest = withApi(setupTest$1);
1288
+
1289
+ export { activeModel, api, belongsTo, build, buildList, configure, defineFactory, factoryOf, fragment, hasMany, jsonApi, mergePayloads, payload, reply, rest, seed, seedList, seedRecord, sequence, setupApplicationTest, setupRenderingTest, setupTest, sideload, sourceOf };
1290
+ //# sourceMappingURL=index.js.map