@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/api.ts
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
import { http, HttpResponse } from 'msw';
|
|
2
|
+
|
|
3
|
+
import { settings } from './config.ts';
|
|
4
|
+
import { definitionOf, factoryOf, nextId, payload } from './factories.ts';
|
|
5
|
+
import type { Attrs, BuiltRecord } from './formats.ts';
|
|
6
|
+
import {
|
|
7
|
+
finishRequest,
|
|
8
|
+
isBypassed,
|
|
9
|
+
nearMisses,
|
|
10
|
+
reportFailure,
|
|
11
|
+
useHandler,
|
|
12
|
+
} from './network.ts';
|
|
13
|
+
import { sourceOf } from './store.ts';
|
|
14
|
+
|
|
15
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
16
|
+
export type Json = any;
|
|
17
|
+
|
|
18
|
+
export interface Call {
|
|
19
|
+
method: string;
|
|
20
|
+
url: string;
|
|
21
|
+
params: Record<string, string | readonly string[] | undefined>;
|
|
22
|
+
query: Json;
|
|
23
|
+
body: Json;
|
|
24
|
+
headers: Headers;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
type Responder = (call: Call) => unknown;
|
|
28
|
+
type ResponseValue = Responder | Response | object | null | undefined;
|
|
29
|
+
type HeaderValue = string | number | null | ((value: string | null) => unknown);
|
|
30
|
+
type Arg = ResponseValue | string | number;
|
|
31
|
+
type Method = 'get' | 'post' | 'put' | 'patch' | 'delete';
|
|
32
|
+
|
|
33
|
+
interface Guard {
|
|
34
|
+
body?: unknown;
|
|
35
|
+
query?: unknown;
|
|
36
|
+
partialQuery?: unknown;
|
|
37
|
+
headers?: Record<string, HeaderValue>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const requests: Call[] = [];
|
|
41
|
+
|
|
42
|
+
export interface Handle {
|
|
43
|
+
readonly calls: Call[];
|
|
44
|
+
readonly timesCalled: number;
|
|
45
|
+
readonly lastCall: Call;
|
|
46
|
+
returns(...args: Arg[]): Handle;
|
|
47
|
+
fails(status?: number, body?: unknown): Handle;
|
|
48
|
+
match(body: object | ((body: Json) => unknown)): Handle;
|
|
49
|
+
withQuery(query: Attrs, options?: { partial?: boolean }): Handle;
|
|
50
|
+
withHeaders(headers: Record<string, HeaderValue>): Handle;
|
|
51
|
+
remove(): void;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function parseEntries(entries: Iterable<[string, unknown]>): Attrs {
|
|
55
|
+
const result: Attrs = {};
|
|
56
|
+
for (const [path, value] of entries) {
|
|
57
|
+
const keys = path.replace(/\]/g, '').split('[');
|
|
58
|
+
let node: Attrs = result;
|
|
59
|
+
keys.forEach((key, index) => {
|
|
60
|
+
const next = keys[index + 1];
|
|
61
|
+
const slot =
|
|
62
|
+
Array.isArray(node) && key === '' ? String(node.length) : key;
|
|
63
|
+
const current = Object.hasOwn(node, slot) ? node[slot] : undefined;
|
|
64
|
+
const item =
|
|
65
|
+
next === undefined
|
|
66
|
+
? current === undefined
|
|
67
|
+
? value
|
|
68
|
+
: [current, value].flat()
|
|
69
|
+
: isObject(current)
|
|
70
|
+
? current
|
|
71
|
+
: /^\d*$/.test(next)
|
|
72
|
+
? []
|
|
73
|
+
: {};
|
|
74
|
+
Object.defineProperty(node, slot, {
|
|
75
|
+
value: item,
|
|
76
|
+
enumerable: true,
|
|
77
|
+
writable: true,
|
|
78
|
+
configurable: true,
|
|
79
|
+
});
|
|
80
|
+
node = item as Attrs;
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
return result;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function parseBody(request: Request): Promise<unknown> {
|
|
87
|
+
const contentType = request.headers.get('content-type') ?? '';
|
|
88
|
+
if (!request.body) {
|
|
89
|
+
return undefined;
|
|
90
|
+
} else if (contentType.includes('json')) {
|
|
91
|
+
return request.clone().json();
|
|
92
|
+
} else if (
|
|
93
|
+
contentType.includes('form-data') ||
|
|
94
|
+
contentType.includes('x-www-form-urlencoded')
|
|
95
|
+
) {
|
|
96
|
+
return parseEntries(await request.clone().formData());
|
|
97
|
+
}
|
|
98
|
+
return request.clone().text();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function plain(value: unknown): unknown {
|
|
102
|
+
return value !== null &&
|
|
103
|
+
typeof value === 'object' &&
|
|
104
|
+
typeof (value as { toJSON?: unknown }).toJSON === 'function'
|
|
105
|
+
? (value as { toJSON(): unknown }).toJSON()
|
|
106
|
+
: value;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function text(value: unknown): string {
|
|
110
|
+
return typeof value === 'string' ? value : (JSON.stringify(value) ?? '');
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function isObject(value: unknown): value is Attrs {
|
|
114
|
+
return value !== null && typeof value === 'object';
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function isSubset(expected: unknown, actual: unknown, exact = false): boolean {
|
|
118
|
+
expected = plain(expected);
|
|
119
|
+
if (typeof expected === 'function') {
|
|
120
|
+
return Boolean((expected as (value: unknown) => unknown)(actual));
|
|
121
|
+
} else if (Array.isArray(expected)) {
|
|
122
|
+
return (
|
|
123
|
+
Array.isArray(actual) &&
|
|
124
|
+
actual.length === expected.length &&
|
|
125
|
+
expected.every((value, index) => isSubset(value, actual[index], exact))
|
|
126
|
+
);
|
|
127
|
+
} else if (isObject(expected)) {
|
|
128
|
+
const entries = Object.entries(expected);
|
|
129
|
+
const required = entries.filter(([, value]) => value !== undefined);
|
|
130
|
+
return (
|
|
131
|
+
isObject(actual) &&
|
|
132
|
+
!Array.isArray(actual) &&
|
|
133
|
+
(!exact || required.length === Object.keys(actual).length) &&
|
|
134
|
+
entries.every(
|
|
135
|
+
([key, value]) =>
|
|
136
|
+
(Object.hasOwn(actual, key) ||
|
|
137
|
+
value === undefined ||
|
|
138
|
+
typeof value === 'function') &&
|
|
139
|
+
isSubset(value, actual[key], exact),
|
|
140
|
+
)
|
|
141
|
+
);
|
|
142
|
+
} else if (expected === null || expected === undefined) {
|
|
143
|
+
return actual === expected;
|
|
144
|
+
} else if (isObject(actual)) {
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
return text(expected) === text(actual);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function hasHeaders(
|
|
151
|
+
expected: Record<string, HeaderValue>,
|
|
152
|
+
headers: Headers,
|
|
153
|
+
): boolean {
|
|
154
|
+
return Object.entries(expected).every(([name, value]) => {
|
|
155
|
+
const actual = headers.get(name);
|
|
156
|
+
if (typeof value === 'function') {
|
|
157
|
+
return Boolean(value(actual));
|
|
158
|
+
}
|
|
159
|
+
return value == null ? actual === null : actual === text(value);
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function matches(
|
|
164
|
+
{ body, query, partialQuery, headers }: Guard,
|
|
165
|
+
call: Call,
|
|
166
|
+
): boolean {
|
|
167
|
+
return (
|
|
168
|
+
(body === undefined || isSubset(body, call.body)) &&
|
|
169
|
+
(query === undefined || isSubset(query, call.query, true)) &&
|
|
170
|
+
(partialQuery === undefined || isSubset(partialQuery, call.query)) &&
|
|
171
|
+
(headers === undefined || hasHeaders(headers, call.headers))
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function unwrapRecords(body: unknown): unknown {
|
|
176
|
+
if (!isObject(body) || Object.getPrototypeOf(body) !== Object.prototype) {
|
|
177
|
+
return body;
|
|
178
|
+
}
|
|
179
|
+
return Object.fromEntries(
|
|
180
|
+
Object.entries(body).map(([key, value]) => [
|
|
181
|
+
key,
|
|
182
|
+
Array.isArray(value) ? value.map(sourceOf) : sourceOf(value),
|
|
183
|
+
]),
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function toResponse(
|
|
188
|
+
response: ResponseValue,
|
|
189
|
+
call: Call,
|
|
190
|
+
): Promise<Response> {
|
|
191
|
+
const resolved =
|
|
192
|
+
typeof response === 'function'
|
|
193
|
+
? await (response as Responder)(call)
|
|
194
|
+
: response;
|
|
195
|
+
if (resolved instanceof Response) {
|
|
196
|
+
return resolved.clone();
|
|
197
|
+
} else if (resolved == null) {
|
|
198
|
+
return new HttpResponse(null, { status: 204 });
|
|
199
|
+
}
|
|
200
|
+
return HttpResponse.json(unwrapRecords(resolved) as Attrs);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export function absoluteUrl(path: string): string {
|
|
204
|
+
if (/^https?:/.test(path)) {
|
|
205
|
+
return path;
|
|
206
|
+
} else if (path.startsWith('//')) {
|
|
207
|
+
return `${window.location.protocol}${path}`;
|
|
208
|
+
} else if (!path.startsWith('/')) {
|
|
209
|
+
throw new Error(
|
|
210
|
+
`api paths start with "/" or are absolute URLs, got "${path}"`,
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
return `${settings().apiBase}${path}`;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function register(
|
|
217
|
+
method: Method,
|
|
218
|
+
path: string,
|
|
219
|
+
initial: ResponseValue,
|
|
220
|
+
toPayload?: (...args: unknown[]) => ResponseValue,
|
|
221
|
+
): Handle {
|
|
222
|
+
const url = absoluteUrl(path);
|
|
223
|
+
const calls: Call[] = [];
|
|
224
|
+
let response = initial;
|
|
225
|
+
let removed = false;
|
|
226
|
+
let where: Guard = {};
|
|
227
|
+
|
|
228
|
+
const handle: Handle = {
|
|
229
|
+
calls,
|
|
230
|
+
get timesCalled() {
|
|
231
|
+
return calls.length;
|
|
232
|
+
},
|
|
233
|
+
get lastCall() {
|
|
234
|
+
return calls.at(-1) as Call;
|
|
235
|
+
},
|
|
236
|
+
returns(...args) {
|
|
237
|
+
const [value] = args;
|
|
238
|
+
const isRaw =
|
|
239
|
+
value === null ||
|
|
240
|
+
value instanceof Response ||
|
|
241
|
+
typeof value === 'function';
|
|
242
|
+
response =
|
|
243
|
+
toPayload && !isRaw ? toPayload(...args) : (value as ResponseValue);
|
|
244
|
+
return handle;
|
|
245
|
+
},
|
|
246
|
+
fails(status = 500, body = {}) {
|
|
247
|
+
response = reply(status, body);
|
|
248
|
+
return handle;
|
|
249
|
+
},
|
|
250
|
+
match(body) {
|
|
251
|
+
where = { ...where, body };
|
|
252
|
+
return handle;
|
|
253
|
+
},
|
|
254
|
+
withQuery(query, { partial = false } = {}) {
|
|
255
|
+
const { query: _query, partialQuery: _partial, ...rest } = where;
|
|
256
|
+
where = { ...rest, [partial ? 'partialQuery' : 'query']: query };
|
|
257
|
+
return handle;
|
|
258
|
+
},
|
|
259
|
+
withHeaders(headers) {
|
|
260
|
+
where = {
|
|
261
|
+
...where,
|
|
262
|
+
headers: {
|
|
263
|
+
...where.headers,
|
|
264
|
+
...Object.fromEntries(
|
|
265
|
+
Object.entries(headers).map(([name, value]) => [
|
|
266
|
+
name.toLowerCase(),
|
|
267
|
+
value,
|
|
268
|
+
]),
|
|
269
|
+
),
|
|
270
|
+
},
|
|
271
|
+
};
|
|
272
|
+
return handle;
|
|
273
|
+
},
|
|
274
|
+
remove() {
|
|
275
|
+
removed = true;
|
|
276
|
+
},
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
const respond = async ({
|
|
280
|
+
request,
|
|
281
|
+
params,
|
|
282
|
+
requestId,
|
|
283
|
+
}: {
|
|
284
|
+
request: Request;
|
|
285
|
+
params: Call['params'];
|
|
286
|
+
requestId: string;
|
|
287
|
+
}) => {
|
|
288
|
+
if (removed || isBypassed(request.url)) {
|
|
289
|
+
return undefined;
|
|
290
|
+
}
|
|
291
|
+
const call: Call = {
|
|
292
|
+
method: request.method,
|
|
293
|
+
url: request.url,
|
|
294
|
+
params,
|
|
295
|
+
query: parseEntries(new URL(request.url).searchParams),
|
|
296
|
+
body: await parseBody(request),
|
|
297
|
+
headers: request.headers,
|
|
298
|
+
};
|
|
299
|
+
if (!matches(where, call)) {
|
|
300
|
+
nearMisses.set(requestId, [
|
|
301
|
+
...(nearMisses.get(requestId) ?? []),
|
|
302
|
+
{
|
|
303
|
+
expected: where as Attrs,
|
|
304
|
+
received: { ...call, headers: Object.fromEntries(call.headers) },
|
|
305
|
+
},
|
|
306
|
+
]);
|
|
307
|
+
return undefined;
|
|
308
|
+
}
|
|
309
|
+
calls.push(call);
|
|
310
|
+
requests.push(call);
|
|
311
|
+
return toResponse(response, call);
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
useHandler(
|
|
315
|
+
http[method](url, async (info) => {
|
|
316
|
+
try {
|
|
317
|
+
return await respond(info);
|
|
318
|
+
} catch (failure) {
|
|
319
|
+
finishRequest(info.requestId);
|
|
320
|
+
reportFailure(failure);
|
|
321
|
+
throw failure;
|
|
322
|
+
}
|
|
323
|
+
}),
|
|
324
|
+
);
|
|
325
|
+
|
|
326
|
+
return handle;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function collectionUrl(type: string): string {
|
|
330
|
+
const { url, format } = definitionOf(type);
|
|
331
|
+
return url ?? `${settings().namespace}${format.path(type)}`;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function memberUrl(type: string, id?: unknown): string {
|
|
335
|
+
return `${collectionUrl(type)}/${id == null ? ':id' : text(id)}`;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
interface Target {
|
|
339
|
+
type: string;
|
|
340
|
+
record?: BuiltRecord;
|
|
341
|
+
id?: unknown;
|
|
342
|
+
rest: unknown[];
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function resolve(typeOrRecord: unknown, ...args: unknown[]): Target {
|
|
346
|
+
if (typeof typeOrRecord === 'string') {
|
|
347
|
+
const [recordOrId, ...rest] = args;
|
|
348
|
+
if (
|
|
349
|
+
typeof recordOrId === 'function' ||
|
|
350
|
+
recordOrId instanceof Response ||
|
|
351
|
+
(isObject(recordOrId) && !('id' in recordOrId))
|
|
352
|
+
) {
|
|
353
|
+
return { type: typeOrRecord, rest: args };
|
|
354
|
+
}
|
|
355
|
+
const isRecord = isObject(recordOrId);
|
|
356
|
+
return {
|
|
357
|
+
type: typeOrRecord,
|
|
358
|
+
record: isRecord ? (recordOrId as BuiltRecord) : undefined,
|
|
359
|
+
id: isRecord ? (recordOrId as BuiltRecord).id : recordOrId,
|
|
360
|
+
rest,
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
const record = typeOrRecord as BuiltRecord & {
|
|
364
|
+
constructor: { modelName?: string };
|
|
365
|
+
};
|
|
366
|
+
const type = record.constructor.modelName ?? factoryOf(record);
|
|
367
|
+
if (!type) {
|
|
368
|
+
throw new Error(
|
|
369
|
+
'api shortcuts need a type name, a record from build() or a seeded model',
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
return { type, record, id: record.id, rest: args };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
export function reply(status: number, body?: unknown): Response {
|
|
376
|
+
return body === undefined
|
|
377
|
+
? new HttpResponse(null, { status })
|
|
378
|
+
: HttpResponse.json(body as Attrs, { status });
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
export function clearRequests(): void {
|
|
382
|
+
requests.length = 0;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
export const api = {
|
|
386
|
+
get requests(): Call[] {
|
|
387
|
+
return requests;
|
|
388
|
+
},
|
|
389
|
+
|
|
390
|
+
lastRequest(method: string, path: string): Call | undefined {
|
|
391
|
+
const { pathname } = new URL(absoluteUrl(path));
|
|
392
|
+
return requests.findLast(
|
|
393
|
+
(call) =>
|
|
394
|
+
call.method === method.toUpperCase() &&
|
|
395
|
+
new URL(call.url).pathname === pathname,
|
|
396
|
+
);
|
|
397
|
+
},
|
|
398
|
+
|
|
399
|
+
get: (path: string, response?: ResponseValue) =>
|
|
400
|
+
register('get', path, response),
|
|
401
|
+
post: (path: string, response?: ResponseValue) =>
|
|
402
|
+
register('post', path, response),
|
|
403
|
+
put: (path: string, response?: ResponseValue) =>
|
|
404
|
+
register('put', path, response),
|
|
405
|
+
patch: (path: string, response?: ResponseValue) =>
|
|
406
|
+
register('patch', path, response),
|
|
407
|
+
delete: (path: string, response?: ResponseValue) =>
|
|
408
|
+
register('delete', path, response),
|
|
409
|
+
|
|
410
|
+
find(typeOrRecord: string | object, ...args: Arg[]): Handle {
|
|
411
|
+
const { type, record, id, rest } = resolve(typeOrRecord, ...args);
|
|
412
|
+
const [last] = rest;
|
|
413
|
+
const raw =
|
|
414
|
+
typeof last === 'function' || last instanceof Response ? last : undefined;
|
|
415
|
+
const extra = raw === undefined && isObject(last) ? last : undefined;
|
|
416
|
+
const one = (value: unknown, more?: Attrs) => () =>
|
|
417
|
+
payload(type, sourceOf(value) as BuiltRecord, more);
|
|
418
|
+
const any =
|
|
419
|
+
(more?: Attrs) =>
|
|
420
|
+
({ params }: Call) =>
|
|
421
|
+
payload(type, { id: id ?? params.id }, more);
|
|
422
|
+
|
|
423
|
+
return register(
|
|
424
|
+
'get',
|
|
425
|
+
memberUrl(type, id),
|
|
426
|
+
raw ?? (record ? one(record, extra) : any(extra)),
|
|
427
|
+
one as (...args: unknown[]) => ResponseValue,
|
|
428
|
+
);
|
|
429
|
+
},
|
|
430
|
+
|
|
431
|
+
query(type: string, records: unknown[] = [], extra: Attrs = {}): Handle {
|
|
432
|
+
const many =
|
|
433
|
+
(list: unknown[] = [], more: Attrs = {}) =>
|
|
434
|
+
() =>
|
|
435
|
+
payload(type, list.map(sourceOf), more);
|
|
436
|
+
|
|
437
|
+
return register(
|
|
438
|
+
'get',
|
|
439
|
+
collectionUrl(type),
|
|
440
|
+
many(records, extra),
|
|
441
|
+
many as (...args: unknown[]) => ResponseValue,
|
|
442
|
+
);
|
|
443
|
+
},
|
|
444
|
+
|
|
445
|
+
create(type: string, attrs: Attrs | Responder = {}): Handle {
|
|
446
|
+
const { format } = definitionOf(type);
|
|
447
|
+
const created = (values: Attrs | Responder) =>
|
|
448
|
+
typeof values === 'function'
|
|
449
|
+
? values
|
|
450
|
+
: ({ body }: Call) =>
|
|
451
|
+
payload(type, {
|
|
452
|
+
id: format.idFromBody(type, body) ?? nextId(type),
|
|
453
|
+
...values,
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
return register(
|
|
457
|
+
'post',
|
|
458
|
+
collectionUrl(type),
|
|
459
|
+
created(attrs),
|
|
460
|
+
created as (...args: unknown[]) => ResponseValue,
|
|
461
|
+
);
|
|
462
|
+
},
|
|
463
|
+
|
|
464
|
+
update(typeOrRecord: string | object, ...args: Arg[]): Handle {
|
|
465
|
+
const { type, id, rest } = resolve(typeOrRecord, ...args);
|
|
466
|
+
const attrs = (rest[0] ?? {}) as Attrs | Responder;
|
|
467
|
+
const updated = (values: Attrs | Responder) =>
|
|
468
|
+
typeof values === 'function'
|
|
469
|
+
? values
|
|
470
|
+
: ({ params }: Call) =>
|
|
471
|
+
payload(type, { id: id ?? params.id, ...values });
|
|
472
|
+
|
|
473
|
+
return register(
|
|
474
|
+
definitionOf(type).format.updateMethod,
|
|
475
|
+
memberUrl(type, id),
|
|
476
|
+
updated(attrs),
|
|
477
|
+
updated as (...args: unknown[]) => ResponseValue,
|
|
478
|
+
);
|
|
479
|
+
},
|
|
480
|
+
|
|
481
|
+
destroy(typeOrRecord: string | object, ...args: Arg[]): Handle {
|
|
482
|
+
const { type, id, rest } = resolve(typeOrRecord, ...args);
|
|
483
|
+
return register('delete', memberUrl(type, id), rest[0] ?? null);
|
|
484
|
+
},
|
|
485
|
+
};
|
package/src/beacon.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
let installed = false;
|
|
2
|
+
|
|
3
|
+
export function installBeaconShim(): void {
|
|
4
|
+
if (installed || typeof navigator.sendBeacon !== 'function') {
|
|
5
|
+
return;
|
|
6
|
+
}
|
|
7
|
+
installed = true;
|
|
8
|
+
Object.defineProperty(navigator, 'sendBeacon', {
|
|
9
|
+
configurable: true,
|
|
10
|
+
writable: true,
|
|
11
|
+
value(url: string | URL, data?: BodyInit | null) {
|
|
12
|
+
fetch(url, { method: 'POST', body: data ?? null, keepalive: true }).catch(
|
|
13
|
+
() => undefined,
|
|
14
|
+
);
|
|
15
|
+
return true;
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function removeBeaconShim(): void {
|
|
21
|
+
if (installed) {
|
|
22
|
+
delete (navigator as { sendBeacon?: unknown }).sendBeacon;
|
|
23
|
+
installed = false;
|
|
24
|
+
}
|
|
25
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { jsonApi, type Format } from './formats.ts';
|
|
2
|
+
|
|
3
|
+
export interface Options {
|
|
4
|
+
apiHost?: string;
|
|
5
|
+
namespace?: string;
|
|
6
|
+
origins?: string[];
|
|
7
|
+
format?: Format;
|
|
8
|
+
beacons?: boolean;
|
|
9
|
+
bypass?: string[];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface Settings {
|
|
13
|
+
apiBase: string;
|
|
14
|
+
namespace: string;
|
|
15
|
+
appOrigins: string[];
|
|
16
|
+
format: Format;
|
|
17
|
+
beacons: boolean;
|
|
18
|
+
bypass: string[];
|
|
19
|
+
bypassPercy: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let options: Options = {};
|
|
23
|
+
let resolved: Settings | undefined;
|
|
24
|
+
|
|
25
|
+
export function configure(next: Options): void {
|
|
26
|
+
options = { ...options, ...next };
|
|
27
|
+
resolved = undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function resetConfiguration(): void {
|
|
31
|
+
options = {};
|
|
32
|
+
resolved = undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const PERCY_DEFAULT = 'http://localhost:5338';
|
|
36
|
+
|
|
37
|
+
export function percyOrigin(): string {
|
|
38
|
+
const scope = globalThis as {
|
|
39
|
+
PercySDKUtils?: { percy?: { address?: unknown } };
|
|
40
|
+
process?: { env?: Record<string, string | undefined> };
|
|
41
|
+
};
|
|
42
|
+
const runtime = scope.PercySDKUtils?.percy?.address;
|
|
43
|
+
const address =
|
|
44
|
+
typeof runtime === 'string'
|
|
45
|
+
? runtime
|
|
46
|
+
: (scope.process?.env?.PERCY_SERVER_ADDRESS ?? PERCY_DEFAULT);
|
|
47
|
+
return new URL(URL.canParse(address) ? address : PERCY_DEFAULT).origin;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function toUrl(host: string): URL {
|
|
51
|
+
return new URL(host, window.location.href);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function settings(): Settings {
|
|
55
|
+
if (resolved) {
|
|
56
|
+
return resolved;
|
|
57
|
+
}
|
|
58
|
+
const api = toUrl(options.apiHost ?? window.location.origin);
|
|
59
|
+
resolved = {
|
|
60
|
+
apiBase: `${api.origin}${api.pathname}`.replace(/\/$/, ''),
|
|
61
|
+
namespace: (options.namespace ?? '')
|
|
62
|
+
.replace(/^\/*/, '/')
|
|
63
|
+
.replace(/\/+$/, ''),
|
|
64
|
+
appOrigins: [
|
|
65
|
+
...new Set([
|
|
66
|
+
window.location.origin,
|
|
67
|
+
api.origin,
|
|
68
|
+
...(options.origins ?? []).map((origin) => toUrl(origin).origin),
|
|
69
|
+
]),
|
|
70
|
+
],
|
|
71
|
+
format: options.format ?? jsonApi(),
|
|
72
|
+
beacons: options.beacons ?? false,
|
|
73
|
+
bypass: (options.bypass ?? []).map((origin) => toUrl(origin).origin),
|
|
74
|
+
bypassPercy: options.bypass === undefined,
|
|
75
|
+
};
|
|
76
|
+
return resolved;
|
|
77
|
+
}
|