@panneau/protocol 5.0.0-alpha.4 → 5.0.0-alpha.41
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/addresses.d.ts +23 -0
- package/dist/addresses.d.ts.map +1 -0
- package/dist/addresses.js +52 -0
- package/dist/addresses.js.map +1 -0
- package/dist/aggregates.d.ts +135 -0
- package/dist/aggregates.d.ts.map +1 -0
- package/dist/aggregates.js +236 -0
- package/dist/aggregates.js.map +1 -0
- package/dist/compound.d.ts +20 -0
- package/dist/compound.d.ts.map +1 -0
- package/dist/compound.js +27 -0
- package/dist/compound.js.map +1 -0
- package/dist/conditions.d.ts +1 -1
- package/dist/conformance/index.d.ts +6 -0
- package/dist/conformance/index.d.ts.map +1 -1
- package/dist/conformance/index.js +970 -11
- package/dist/conformance/index.js.map +1 -1
- package/dist/constants.d.ts +108 -2
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +181 -3
- package/dist/constants.js.map +1 -1
- package/dist/context.d.ts +15 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +34 -0
- package/dist/context.js.map +1 -0
- package/dist/currencies.d.ts +22 -0
- package/dist/currencies.d.ts.map +1 -0
- package/dist/currencies.js +231 -0
- package/dist/currencies.js.map +1 -0
- package/dist/dashboards.d.ts +95 -0
- package/dist/dashboards.d.ts.map +1 -0
- package/dist/dashboards.js +140 -0
- package/dist/dashboards.js.map +1 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +22 -8
- package/dist/libraries.d.ts +33 -0
- package/dist/libraries.d.ts.map +1 -0
- package/dist/libraries.js +59 -0
- package/dist/libraries.js.map +1 -0
- package/dist/links.d.ts +38 -0
- package/dist/links.d.ts.map +1 -0
- package/dist/links.js +65 -0
- package/dist/links.js.map +1 -0
- package/dist/lint.d.ts +4 -4
- package/dist/lint.d.ts.map +1 -1
- package/dist/lint.js +540 -15
- package/dist/lint.js.map +1 -1
- package/dist/mock/auth.d.ts +71 -0
- package/dist/mock/auth.d.ts.map +1 -0
- package/dist/mock/auth.js +346 -0
- package/dist/mock/auth.js.map +1 -0
- package/dist/mock/example.d.ts +1 -1
- package/dist/mock/example.d.ts.map +1 -1
- package/dist/mock/example.js +49 -28
- package/dist/mock/example.js.map +1 -1
- package/dist/mock/index.d.ts +96 -5
- package/dist/mock/index.d.ts.map +1 -1
- package/dist/mock/index.js +505 -44
- package/dist/mock/index.js.map +1 -1
- package/dist/openapi.d.ts.map +1 -1
- package/dist/openapi.js +462 -50
- package/dist/openapi.js.map +1 -1
- package/dist/periods.d.ts +61 -0
- package/dist/periods.d.ts.map +1 -0
- package/dist/periods.js +130 -0
- package/dist/periods.js.map +1 -0
- package/dist/problem.d.ts +1 -1
- package/dist/query.d.ts +18 -0
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +34 -8
- package/dist/query.js.map +1 -1
- package/dist/resourceTypes.d.ts +39 -0
- package/dist/resourceTypes.d.ts.map +1 -0
- package/dist/resourceTypes.js +34 -0
- package/dist/resourceTypes.js.map +1 -0
- package/dist/rules.d.ts +18 -5
- package/dist/rules.d.ts.map +1 -1
- package/dist/rules.js +233 -15
- package/dist/rules.js.map +1 -1
- package/dist/runtime/index.d.ts +23 -10
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/index.js +16 -3
- package/dist/schemas/action.d.ts +119 -10
- package/dist/schemas/action.d.ts.map +1 -1
- package/dist/schemas/action.js +20 -3
- package/dist/schemas/action.js.map +1 -1
- package/dist/schemas/api.d.ts +266 -5
- package/dist/schemas/api.d.ts.map +1 -1
- package/dist/schemas/api.js +134 -16
- package/dist/schemas/api.js.map +1 -1
- package/dist/schemas/boot.d.ts +25 -1
- package/dist/schemas/boot.d.ts.map +1 -1
- package/dist/schemas/boot.js +2 -1
- package/dist/schemas/boot.js.map +1 -1
- package/dist/schemas/common.d.ts +1 -0
- package/dist/schemas/common.d.ts.map +1 -1
- package/dist/schemas/common.js +2 -1
- package/dist/schemas/common.js.map +1 -1
- package/dist/schemas/definition.d.ts +1414 -30
- package/dist/schemas/definition.d.ts.map +1 -1
- package/dist/schemas/definition.js +77 -17
- package/dist/schemas/definition.js.map +1 -1
- package/dist/schemas/field.d.ts +358 -2
- package/dist/schemas/field.d.ts.map +1 -1
- package/dist/schemas/field.js +161 -20
- package/dist/schemas/field.js.map +1 -1
- package/dist/schemas/index.d.ts +5820 -46
- package/dist/schemas/index.d.ts.map +1 -1
- package/dist/schemas/index.js +69 -7
- package/dist/schemas/index.js.map +1 -1
- package/dist/schemas/jsonRules.d.ts +83 -0
- package/dist/schemas/jsonRules.d.ts.map +1 -0
- package/dist/schemas/jsonRules.js +46 -0
- package/dist/schemas/jsonRules.js.map +1 -0
- package/dist/schemas/layout.d.ts +2 -1
- package/dist/schemas/layout.d.ts.map +1 -1
- package/dist/schemas/layout.js +2 -1
- package/dist/schemas/layout.js.map +1 -1
- package/dist/schemas/list.d.ts +34 -2
- package/dist/schemas/list.d.ts.map +1 -1
- package/dist/schemas/list.js +21 -6
- package/dist/schemas/list.js.map +1 -1
- package/dist/schemas/resource.d.ts +826 -17
- package/dist/schemas/resource.d.ts.map +1 -1
- package/dist/schemas/resource.js +26 -4
- package/dist/schemas/resource.js.map +1 -1
- package/dist/schemas/theme.d.ts +6 -2
- package/dist/schemas/theme.d.ts.map +1 -1
- package/dist/schemas/theme.js +1 -0
- package/dist/schemas/theme.js.map +1 -1
- package/dist/schemas/widget.d.ts +4379 -0
- package/dist/schemas/widget.d.ts.map +1 -0
- package/dist/schemas/widget.js +269 -0
- package/dist/schemas/widget.js.map +1 -0
- package/dist/search.d.ts +51 -0
- package/dist/search.d.ts.map +1 -0
- package/dist/search.js +53 -0
- package/dist/search.js.map +1 -0
- package/dist/themes.d.ts +1 -1
- package/dist/transforms.d.ts +17 -0
- package/dist/transforms.d.ts.map +1 -0
- package/dist/transforms.js +34 -0
- package/dist/transforms.js.map +1 -0
- package/dist/validate.d.ts +5 -3
- package/dist/validate.d.ts.map +1 -1
- package/dist/validate.js +36 -2
- package/dist/validate.js.map +1 -1
- package/dist/values.d.ts +5 -1
- package/dist/values.d.ts.map +1 -1
- package/dist/values.js +16 -2
- package/dist/values.js.map +1 -1
- package/dist/widgets.d.ts +232 -0
- package/dist/widgets.d.ts.map +1 -0
- package/dist/widgets.js +630 -0
- package/dist/widgets.js.map +1 -0
- package/package.json +6 -3
- package/schema/boot.schema.json +1461 -104
- package/schema/definition.schema.json +1459 -105
- package/schema/openapi.json +7176 -2000
package/dist/mock/index.js
CHANGED
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
import { PROBLEM_CONTENT_TYPE } from "../version.js";
|
|
2
|
+
import { CONTEXT_HEADER, CONTEXT_PROBLEM_TYPE, ITEM_ACTION_ABILITIES, isBuiltInItemAction } from "../constants.js";
|
|
2
3
|
import { isRecord } from "../values.js";
|
|
3
4
|
import { checkValues } from "../rules.js";
|
|
5
|
+
import { getMediaLibraries } from "../libraries.js";
|
|
6
|
+
import { ITEM_TYPE_KEY, getResourceType, getTypeFields, hasResourceTypes } from "../resourceTypes.js";
|
|
4
7
|
import { fromSearchParams, isFilterRange, matchesFilterRange } from "../query.js";
|
|
8
|
+
import { checkWidgetData, readsResources } from "../widgets.js";
|
|
9
|
+
import { aggregateItems, getFilterRange, readAggregateQuery } from "../aggregates.js";
|
|
10
|
+
import { getDashboardWidgets, getSummaryWidgets, readWidgetDataQuery } from "../dashboards.js";
|
|
11
|
+
import { readSearchQuery } from "../search.js";
|
|
12
|
+
import { contextBefore, parseContextHeader } from "../context.js";
|
|
13
|
+
import { createMockAuth } from "./auth.js";
|
|
5
14
|
import { createExampleDefinition } from "./example.js";
|
|
6
15
|
//#region src/mock/index.ts
|
|
7
16
|
var RESERVED_KEYS = /* @__PURE__ */ new Set([
|
|
@@ -9,6 +18,51 @@ var RESERVED_KEYS = /* @__PURE__ */ new Set([
|
|
|
9
18
|
"version",
|
|
10
19
|
"abilities"
|
|
11
20
|
]);
|
|
21
|
+
function escapeHtml(text) {
|
|
22
|
+
return text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
|
|
23
|
+
}
|
|
24
|
+
/** A plain page with the values of an item, as a `data:` URL, for iframe previews. */
|
|
25
|
+
function defaultPreviewUrl(item) {
|
|
26
|
+
const rows = Object.entries(item).filter(([key]) => !RESERVED_KEYS.has(key)).map(([key, value]) => `<dt>${escapeHtml(key)}</dt><dd>${escapeHtml(typeof value === "string" ? value : JSON.stringify(value))}</dd>`).join("");
|
|
27
|
+
const html = `<!doctype html><meta charset="utf-8"><title>Preview</title><body style="font-family:system-ui;margin:2rem"><h1>Item ${escapeHtml(item.id)}</h1><dl>${rows}</dl></body>`;
|
|
28
|
+
return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
|
|
29
|
+
}
|
|
30
|
+
/** What the mock knows of a URL to embed: a video of YouTube or Vimeo, or a web page. */
|
|
31
|
+
function defaultEmbed(url) {
|
|
32
|
+
if (!URL.canParse(url)) return null;
|
|
33
|
+
const parsed = new URL(url);
|
|
34
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
|
|
35
|
+
const host = parsed.hostname.replace(/^www\./, "");
|
|
36
|
+
const youtube = host === "youtu.be" ? parsed.pathname.slice(1) : host.endsWith("youtube.com") ? parsed.searchParams.get("v") : null;
|
|
37
|
+
if (youtube !== null && youtube !== "") return {
|
|
38
|
+
url,
|
|
39
|
+
type: "video",
|
|
40
|
+
provider: "YouTube",
|
|
41
|
+
title: `YouTube video ${youtube}`,
|
|
42
|
+
thumbnailUrl: `https://i.ytimg.com/vi/${youtube}/hqdefault.jpg`,
|
|
43
|
+
html: `<iframe src="https://www.youtube.com/embed/${youtube}" width="560" height="315" allowfullscreen></iframe>`,
|
|
44
|
+
width: 560,
|
|
45
|
+
height: 315
|
|
46
|
+
};
|
|
47
|
+
if (host === "vimeo.com") {
|
|
48
|
+
const id = parsed.pathname.split("/").filter(Boolean)[0] ?? "";
|
|
49
|
+
return {
|
|
50
|
+
url,
|
|
51
|
+
type: "video",
|
|
52
|
+
provider: "Vimeo",
|
|
53
|
+
title: `Vimeo video ${id}`,
|
|
54
|
+
html: `<iframe src="https://player.vimeo.com/video/${id}" width="640" height="360" allowfullscreen></iframe>`,
|
|
55
|
+
width: 640,
|
|
56
|
+
height: 360
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
url,
|
|
61
|
+
type: "link",
|
|
62
|
+
provider: host,
|
|
63
|
+
title: host
|
|
64
|
+
};
|
|
65
|
+
}
|
|
12
66
|
var DEFAULT_MESSAGES = {
|
|
13
67
|
required: () => "This field is required.",
|
|
14
68
|
min: (failure) => `This value must be at least ${String(failure.value)}.`,
|
|
@@ -16,11 +70,17 @@ var DEFAULT_MESSAGES = {
|
|
|
16
70
|
pattern: () => "This value has an invalid format.",
|
|
17
71
|
email: () => "This value must be an email address.",
|
|
18
72
|
url: () => "This value must be a URL.",
|
|
73
|
+
json: () => "This value must be valid JSON: an object or an array.",
|
|
19
74
|
in: () => "This value is not one of the choices.",
|
|
20
75
|
accept: () => "This file type is not accepted.",
|
|
21
76
|
maxSize: () => "This file is too large.",
|
|
22
77
|
before: () => "This date is too late.",
|
|
23
|
-
after: () => "This date is too early."
|
|
78
|
+
after: () => "This date is too early.",
|
|
79
|
+
providers: (failure) => `This embed must come from ${Array.isArray(failure.value) ? failure.value.join(" or ") : "another provider"}.`,
|
|
80
|
+
crop: (failure) => {
|
|
81
|
+
const ratios = isRecord(failure.value) ? failure.value.ratios : void 0;
|
|
82
|
+
return Array.isArray(ratios) && ratios.length > 0 ? `Crop this image to ${ratios.join(" or ")}.` : "Crop this image.";
|
|
83
|
+
}
|
|
24
84
|
};
|
|
25
85
|
function message(failure) {
|
|
26
86
|
return failure.message ?? DEFAULT_MESSAGES[failure.rule]?.(failure) ?? "This value is invalid.";
|
|
@@ -57,17 +117,30 @@ function searchableText(value) {
|
|
|
57
117
|
if (isRecord(value)) return Object.values(value).map(searchableText).join(" ");
|
|
58
118
|
return "";
|
|
59
119
|
}
|
|
120
|
+
/** What a value sorts by: the start of a `daterange`, the amount of `money`, or its text. */
|
|
121
|
+
function sortValue(value) {
|
|
122
|
+
if (!isRecord(value)) return value;
|
|
123
|
+
if ("start" in value && "end" in value) return value.start ?? value.end;
|
|
124
|
+
if ("currency" in value && typeof value.amount === "number") return value.amount;
|
|
125
|
+
return searchableText(value);
|
|
126
|
+
}
|
|
60
127
|
function compare(a, b) {
|
|
61
|
-
const left =
|
|
62
|
-
const right =
|
|
128
|
+
const left = sortValue(a);
|
|
129
|
+
const right = sortValue(b);
|
|
63
130
|
if (left === right) return 0;
|
|
64
131
|
if (left === void 0 || left === null) return 1;
|
|
65
132
|
if (right === void 0 || right === null) return -1;
|
|
133
|
+
if (typeof left === "number" && typeof right === "number") return left - right;
|
|
66
134
|
return String(left).localeCompare(String(right), void 0, { numeric: true });
|
|
67
135
|
}
|
|
68
136
|
function applyQuery(items, query) {
|
|
69
137
|
let result = items;
|
|
70
138
|
Object.entries(query.filter ?? {}).forEach(([key, expected]) => {
|
|
139
|
+
if (key === "ids") {
|
|
140
|
+
const ids = (Array.isArray(expected) ? expected : [expected]).map(String).slice(0, 100);
|
|
141
|
+
result = result.filter((item) => ids.includes(item.id));
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
71
144
|
if (isFilterRange(expected)) {
|
|
72
145
|
result = result.filter((item) => matchesFilterRange(item[key], expected));
|
|
73
146
|
return;
|
|
@@ -113,37 +186,117 @@ function mediaOf(file) {
|
|
|
113
186
|
};
|
|
114
187
|
}
|
|
115
188
|
/**
|
|
189
|
+
* A media item with its own transform (its `transform` field) in its `media`, where references
|
|
190
|
+
* give it to clients (decision 0031).
|
|
191
|
+
*/
|
|
192
|
+
function withOwnTransform(resource, item) {
|
|
193
|
+
if (resource.kind !== "media" || !isRecord(item.media)) return item;
|
|
194
|
+
const { transform: _previous, ...media } = item.media;
|
|
195
|
+
return {
|
|
196
|
+
...item,
|
|
197
|
+
media: isRecord(item.transform) ? {
|
|
198
|
+
...media,
|
|
199
|
+
transform: item.transform
|
|
200
|
+
} : media
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Whether an item allows an action, as clients read its abilities (decision 0040): a built-in item
|
|
205
|
+
* action needs its ability (`delete`, `duplicate`…), and another action its id.
|
|
206
|
+
*/
|
|
207
|
+
function allows(item, actionId) {
|
|
208
|
+
const ability = isBuiltInItemAction(actionId) ? ITEM_ACTION_ABILITIES[actionId] : actionId;
|
|
209
|
+
return item.abilities[ability] === true && item.abilities[actionId] !== false;
|
|
210
|
+
}
|
|
211
|
+
/** The names of the fields of a resource whose ability is `false` (decision 0046). */
|
|
212
|
+
function fieldsWithout(resource, ability) {
|
|
213
|
+
return new Set(resource.fields.filter((field) => field.abilities?.[ability] === false).map((field) => field.name));
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* The resource as the items of a type see it (decision 0077): with the fields of the type after its
|
|
217
|
+
* own. The resource itself without a type.
|
|
218
|
+
*/
|
|
219
|
+
function withTypeFields(resource, type) {
|
|
220
|
+
return hasResourceTypes(resource) ? {
|
|
221
|
+
...resource,
|
|
222
|
+
fields: getTypeFields(resource, type)
|
|
223
|
+
} : resource;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* A body without the values of the fields the user can't see or update, and of the fields that
|
|
227
|
+
* forms leave out (`notInForm`, decision 0071), which are ignored.
|
|
228
|
+
*/
|
|
229
|
+
function writableValues(resource, body) {
|
|
230
|
+
const ignored = /* @__PURE__ */ new Set([
|
|
231
|
+
...fieldsWithout(resource, "view"),
|
|
232
|
+
...fieldsWithout(resource, "update"),
|
|
233
|
+
...resource.fields.filter((field) => field.notInForm === true).map((field) => field.name)
|
|
234
|
+
]);
|
|
235
|
+
return Object.fromEntries(Object.entries(body).filter(([key]) => !ignored.has(key)));
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
116
238
|
* An in-memory backend that implements the protocol's resource routes: definition, list, show,
|
|
117
|
-
* create, update (with `If-Match`), delete and the built-in `delete` action.
|
|
239
|
+
* create, update (with `If-Match`), delete, duplicate and the built-in `delete` action. A resource
|
|
240
|
+
* that declares its `delete` `undoable` has a trash: the result of `delete` says how to undo it,
|
|
241
|
+
* and the built-in `restore` puts the items back (decision 0063). Its items
|
|
242
|
+
* allow every built-in item action (`view`, `update`, `duplicate`, `delete`), unless an item of
|
|
243
|
+
* `items` gives its own `abilities`. It reads abilities as clients do (decision 0046): a resource
|
|
244
|
+
* without `viewAny` answers `403` on its list, one without `create` on creates, an item without
|
|
245
|
+
* `view`, `update` or `delete` on those requests; items leave out the values of fields with
|
|
246
|
+
* `view: false`, and writes ignore those of fields with `update: false`. A resource with `types`
|
|
247
|
+
* needs the `type` of a new item, among the types it can create, and its items have the fields of
|
|
248
|
+
* their type (decision 0077). A list with `aggregates` answers
|
|
249
|
+
* `GET /resources/{resource}/aggregate` with `aggregateItems()` (decision 0084). Values are checked
|
|
118
250
|
* with the portable rules. Used to test the conformance kit, and to develop frontends without a
|
|
119
251
|
* real backend.
|
|
120
252
|
*/
|
|
121
|
-
function createMockBackend(
|
|
253
|
+
function createMockBackend(options) {
|
|
254
|
+
const { definition, items = {} } = options;
|
|
255
|
+
const auth = options.auth !== void 0 ? createMockAuth(options.auth, definition.auth) : null;
|
|
122
256
|
const store = /* @__PURE__ */ new Map();
|
|
257
|
+
const trash = /* @__PURE__ */ new Map();
|
|
123
258
|
let nextId = 1;
|
|
124
259
|
const abilitiesFor = (resource) => Object.fromEntries([
|
|
260
|
+
["view", true],
|
|
125
261
|
["update", true],
|
|
262
|
+
["duplicate", true],
|
|
126
263
|
["delete", true],
|
|
127
264
|
...(resource.actions ?? []).map((action) => [action.id, true])
|
|
128
265
|
]);
|
|
266
|
+
const freshId = (resource) => {
|
|
267
|
+
const items = store.get(resource.id) ?? [];
|
|
268
|
+
let id = String(nextId++);
|
|
269
|
+
while (items.some((item) => item.id === id)) id = String(nextId++);
|
|
270
|
+
return id;
|
|
271
|
+
};
|
|
129
272
|
const makeItem = (resource, values) => {
|
|
130
|
-
const id = typeof values.id === "string" || typeof values.id === "number" ? String(values.id) :
|
|
273
|
+
const id = typeof values.id === "string" || typeof values.id === "number" ? String(values.id) : freshId(resource);
|
|
274
|
+
const rest = Object.fromEntries(Object.entries(values).filter(([key]) => !RESERVED_KEYS.has(key)));
|
|
275
|
+
const own = isRecord(values.abilities) ? values.abilities : {};
|
|
131
276
|
return {
|
|
132
|
-
...
|
|
277
|
+
...rest,
|
|
133
278
|
id,
|
|
134
279
|
version: "1",
|
|
135
|
-
abilities:
|
|
280
|
+
abilities: {
|
|
281
|
+
...abilitiesFor(resource),
|
|
282
|
+
...own
|
|
283
|
+
}
|
|
136
284
|
};
|
|
137
285
|
};
|
|
286
|
+
const present = (resource, item) => {
|
|
287
|
+
const hidden = fieldsWithout(withTypeFields(resource, item[ITEM_TYPE_KEY]), "view");
|
|
288
|
+
return hidden.size === 0 ? item : Object.fromEntries(Object.entries(item).filter(([key]) => !hidden.has(key)));
|
|
289
|
+
};
|
|
138
290
|
definition.resources.forEach((resource) => {
|
|
139
291
|
store.set(resource.id, (items[resource.id] ?? []).map((values) => makeItem(resource, values)));
|
|
140
292
|
});
|
|
141
293
|
const basePath = new URL(definition.api.baseUrl, "http://panneau.test").pathname.replace(/\/$/, "");
|
|
142
|
-
const validationProblem = (resource, values, mode) => {
|
|
294
|
+
const validationProblem = (resource, values, mode, item) => {
|
|
143
295
|
const failures = checkValues(resource.fields, values, {
|
|
144
296
|
mode,
|
|
145
297
|
partial: mode === "update",
|
|
146
|
-
locales: definition.locales
|
|
298
|
+
locales: definition.locales,
|
|
299
|
+
...item !== void 0 ? { item } : {}
|
|
147
300
|
});
|
|
148
301
|
const paths = Object.keys(failures);
|
|
149
302
|
if (paths.length === 0) return null;
|
|
@@ -226,29 +379,36 @@ function createMockBackend({ definition, items = {} }) {
|
|
|
226
379
|
};
|
|
227
380
|
const missingMedia = (paths) => problem(422, "The given data was invalid.", {
|
|
228
381
|
type: "urn:panneau:problem:validation",
|
|
229
|
-
errors: Object.fromEntries(paths.map((path) => [path, [
|
|
382
|
+
errors: Object.fromEntries(Object.entries(paths).map(([path, message]) => [path, [message]]))
|
|
230
383
|
});
|
|
231
384
|
const missingUploads = (paths) => problem(422, "The given data was invalid.", {
|
|
232
385
|
type: "urn:panneau:problem:validation",
|
|
233
386
|
errors: Object.fromEntries(paths.map((path) => [path, ["This upload does not exist."]]))
|
|
234
387
|
});
|
|
235
388
|
const resolveMedia = (resource, values) => {
|
|
236
|
-
const missing =
|
|
389
|
+
const missing = {};
|
|
237
390
|
const resolved = { ...values };
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
const library = libraries.find((candidate) => field.resource !== void 0 ? candidate.id === field.resource : true);
|
|
391
|
+
resource.fields.filter((field) => (field.type === "media" || field.type === "image") && field.name in values).forEach((field) => {
|
|
392
|
+
const allowed = getMediaLibraries(definition, field);
|
|
241
393
|
const toReference = (value, path) => {
|
|
242
394
|
const id = isRecord(value) ? value.id : value;
|
|
243
395
|
if (typeof id !== "string" && typeof id !== "number") return value;
|
|
396
|
+
const named = isRecord(value) && typeof value.resource === "string" ? value.resource : void 0;
|
|
397
|
+
if (named === void 0 && allowed.length > 1) {
|
|
398
|
+
missing[path] = "This field allows several libraries: name the library.";
|
|
399
|
+
return value;
|
|
400
|
+
}
|
|
401
|
+
const libraryId = named ?? allowed[0];
|
|
402
|
+
const library = definition.resources.find((candidate) => candidate.id === libraryId && allowed.includes(candidate.id));
|
|
244
403
|
const media = (store.get(library?.id ?? "") ?? []).find((candidate) => candidate.id === String(id));
|
|
245
404
|
if (media === void 0 || library === void 0) {
|
|
246
|
-
missing.
|
|
405
|
+
missing[path] = "This media does not exist.";
|
|
247
406
|
return value;
|
|
248
407
|
}
|
|
249
408
|
const title = media[library.itemTitle ?? "name"];
|
|
250
409
|
return {
|
|
251
410
|
id: media.id,
|
|
411
|
+
...allowed.length > 1 ? { resource: library.id } : {},
|
|
252
412
|
...typeof title === "string" ? { label: title } : {},
|
|
253
413
|
...isRecord(media.media) ? { media: media.media } : {},
|
|
254
414
|
...isRecord(value) && isRecord(value.transform) ? { transform: value.transform } : {}
|
|
@@ -271,7 +431,7 @@ function createMockBackend({ definition, items = {} }) {
|
|
|
271
431
|
problem: missingUploads(files.missing)
|
|
272
432
|
};
|
|
273
433
|
const media = resolveMedia(resource, files.values);
|
|
274
|
-
if (media.missing.length > 0) return {
|
|
434
|
+
if (Object.keys(media.missing).length > 0) return {
|
|
275
435
|
values: body,
|
|
276
436
|
problem: missingMedia(media.missing)
|
|
277
437
|
};
|
|
@@ -282,7 +442,109 @@ function createMockBackend({ definition, items = {} }) {
|
|
|
282
442
|
problem: null
|
|
283
443
|
};
|
|
284
444
|
};
|
|
445
|
+
const search = (params, inScope) => {
|
|
446
|
+
const read = readSearchQuery(params, definition);
|
|
447
|
+
if (read.errors !== void 0) return problem(422, "The given data was invalid.", {
|
|
448
|
+
type: "urn:panneau:problem:validation",
|
|
449
|
+
errors: read.errors
|
|
450
|
+
});
|
|
451
|
+
const { q, limit, resources } = read.query;
|
|
452
|
+
let left = 20;
|
|
453
|
+
return json(200, { data: resources.flatMap((id) => {
|
|
454
|
+
if (left === 0) return [];
|
|
455
|
+
const searched = definition.resources.find((candidate) => candidate.id === id);
|
|
456
|
+
if (searched === void 0 || searched.abilities?.viewAny === false) return [];
|
|
457
|
+
const found = applyQuery(inScope(id, store.get(id) ?? []), { q });
|
|
458
|
+
const items = found.slice(0, Math.min(limit, left)).map((item) => present(searched, item));
|
|
459
|
+
left -= items.length;
|
|
460
|
+
return items.length > 0 ? [{
|
|
461
|
+
resource: id,
|
|
462
|
+
items,
|
|
463
|
+
total: found.length
|
|
464
|
+
}] : [];
|
|
465
|
+
}) });
|
|
466
|
+
};
|
|
467
|
+
const params = definition.context?.params ?? [];
|
|
468
|
+
const names = params.map(({ name }) => name);
|
|
469
|
+
const choicesOf = (name, values) => {
|
|
470
|
+
return params.find((candidate) => candidate.name === name)?.options ?? options.context?.options?.(name, contextBefore(values, names, name)) ?? [];
|
|
471
|
+
};
|
|
472
|
+
const refused = (name) => problem(403, "This value of the context can’t be used.", {
|
|
473
|
+
type: CONTEXT_PROBLEM_TYPE,
|
|
474
|
+
param: name
|
|
475
|
+
});
|
|
476
|
+
/**
|
|
477
|
+
* The values of the header that the definition declares, each one checked against its
|
|
478
|
+
* choices, in order: a value that isn't one is a `403` problem with its `param`. A `fixed`
|
|
479
|
+
* param has the value of the definition, as a backend would take it from the request: another
|
|
480
|
+
* value in the header is refused.
|
|
481
|
+
*/
|
|
482
|
+
const readContext = (header) => {
|
|
483
|
+
const sent = parseContextHeader(header);
|
|
484
|
+
const values = {};
|
|
485
|
+
for (const param of params) {
|
|
486
|
+
const { name } = param;
|
|
487
|
+
const value = sent[name];
|
|
488
|
+
if (param.fixed === true && typeof param.value === "string") {
|
|
489
|
+
if (value !== void 0 && value !== param.value) return refused(name);
|
|
490
|
+
values[name] = param.value;
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
if (value === void 0) continue;
|
|
494
|
+
if (!choicesOf(name, values).some((choice) => choice.value === value)) return refused(name);
|
|
495
|
+
values[name] = value;
|
|
496
|
+
}
|
|
497
|
+
return values;
|
|
498
|
+
};
|
|
499
|
+
/** The definition for the values of the context: the `value` and `valueLabel` of each param. */
|
|
500
|
+
const answerWidget = async (id, params, values, inScope) => {
|
|
501
|
+
const read = readWidgetDataQuery(params);
|
|
502
|
+
if (read.errors !== void 0) return problem(422, "The given data was invalid.", {
|
|
503
|
+
type: "urn:panneau:problem:validation",
|
|
504
|
+
errors: read.errors
|
|
505
|
+
});
|
|
506
|
+
const current = definitionFor(values);
|
|
507
|
+
if (read.resource !== void 0) {
|
|
508
|
+
const summarized = current.resources.find((candidate) => candidate.id === read.resource);
|
|
509
|
+
if (summarized?.summary !== void 0 && summarized.abilities?.viewAny === false) return problem(403, "This resource can’t be listed.");
|
|
510
|
+
}
|
|
511
|
+
const widget = (read.resource !== void 0 ? getSummaryWidgets(current, read.resource) : getDashboardWidgets(current, read.page)).find((candidate) => candidate.id === id);
|
|
512
|
+
const data = options.widgets?.[id];
|
|
513
|
+
if (widget === void 0 || readsResources(widget) || data === void 0) return problem(404, "Widget not found.");
|
|
514
|
+
const answer = typeof data === "function" ? await data({
|
|
515
|
+
context: values,
|
|
516
|
+
page: read.page ?? null,
|
|
517
|
+
resource: read.resource ?? null,
|
|
518
|
+
query: read.query ?? {},
|
|
519
|
+
period: read.period,
|
|
520
|
+
items: (resource) => inScope(resource, store.get(resource) ?? [])
|
|
521
|
+
}) : data;
|
|
522
|
+
if (answer instanceof Response) return answer;
|
|
523
|
+
const wrong = checkWidgetData(widget.type, answer);
|
|
524
|
+
return wrong.length === 0 ? json(200, answer) : problem(500, `The data of the widget doesn't have the shape of \`${widget.type}\`.`, { detail: `Wrong keys: ${wrong.map((key) => key === "" ? "(the data)" : key).join(", ")}.` });
|
|
525
|
+
};
|
|
526
|
+
const definitionFor = (values) => definition.context === void 0 ? definition : {
|
|
527
|
+
...definition,
|
|
528
|
+
context: {
|
|
529
|
+
...definition.context,
|
|
530
|
+
params: params.map((param) => {
|
|
531
|
+
if (param.fixed === true) return param;
|
|
532
|
+
const value = values[param.name] ?? null;
|
|
533
|
+
const label = value !== null ? choicesOf(param.name, values).find((choice) => choice.value === value)?.label : void 0;
|
|
534
|
+
return {
|
|
535
|
+
...param,
|
|
536
|
+
value,
|
|
537
|
+
valueLabel: label ?? null
|
|
538
|
+
};
|
|
539
|
+
})
|
|
540
|
+
}
|
|
541
|
+
};
|
|
285
542
|
const handle = async (request) => {
|
|
543
|
+
const response = await answer(request);
|
|
544
|
+
if (definition.context !== void 0) response.headers.set("Vary", CONTEXT_HEADER);
|
|
545
|
+
return response;
|
|
546
|
+
};
|
|
547
|
+
const answer = async (request) => {
|
|
286
548
|
const url = new URL(request.url, "http://panneau.test");
|
|
287
549
|
if (!url.pathname.startsWith(basePath)) return problem(404, "Not found.");
|
|
288
550
|
const segments = url.pathname.slice(basePath.length).split("/").filter((segment) => segment !== "").map(decodeURIComponent);
|
|
@@ -291,24 +553,94 @@ function createMockBackend({ definition, items = {} }) {
|
|
|
291
553
|
const body = await request.json().catch(() => null);
|
|
292
554
|
return isRecord(body) ? body : {};
|
|
293
555
|
};
|
|
294
|
-
if (
|
|
556
|
+
if (auth !== null) {
|
|
557
|
+
if (segments[0] === "auth") return auth.answer(segments.slice(1), method, readBody, url);
|
|
558
|
+
const account = segments[0] === "account" ? auth.account(segments.slice(1), method, readBody) : null;
|
|
559
|
+
if (account !== null) return account;
|
|
560
|
+
const refused = auth.refuse();
|
|
561
|
+
if (refused !== null) return refused;
|
|
562
|
+
}
|
|
563
|
+
const context = readContext(request.headers.get(CONTEXT_HEADER));
|
|
564
|
+
if (context instanceof Response) return context;
|
|
565
|
+
const inScope = (resource, list) => {
|
|
566
|
+
const scope = options.context?.scope;
|
|
567
|
+
return scope !== void 0 ? list.filter((item) => scope(resource, item, context)) : list;
|
|
568
|
+
};
|
|
569
|
+
if (segments.length === 1 && segments[0] === "definition" && method === "GET") {
|
|
570
|
+
const built = definitionFor(context);
|
|
571
|
+
return json(200, auth !== null ? {
|
|
572
|
+
...built,
|
|
573
|
+
user: auth.user()
|
|
574
|
+
} : built);
|
|
575
|
+
}
|
|
576
|
+
if (segments.length === 3 && segments[0] === "context" && segments[2] === "options" && method === "GET") {
|
|
577
|
+
const name = segments[1] ?? "";
|
|
578
|
+
if (!names.includes(name)) return problem(404, "The context has no such param.");
|
|
579
|
+
const q = (url.searchParams.get("q") ?? "").trim().toLocaleLowerCase();
|
|
580
|
+
return json(200, { data: choicesOf(name, context).filter((choice) => choice.label.toLocaleLowerCase().includes(q)).slice(0, 20) });
|
|
581
|
+
}
|
|
582
|
+
if (segments.length === 1 && segments[0] === "embeds" && method === "GET") {
|
|
583
|
+
const url = new URL(request.url, "http://panneau.test").searchParams.get("url") ?? "";
|
|
584
|
+
const embed = url === "" ? null : (options.embed ?? defaultEmbed)(url);
|
|
585
|
+
return embed !== null ? json(200, { data: embed }) : problem(422, "The given data was invalid.", {
|
|
586
|
+
type: "urn:panneau:problem:validation",
|
|
587
|
+
errors: { url: ["This URL can’t be embedded."] }
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
if (segments.length === 3 && segments[0] === "dashboard" && segments[1] === "widgets" && method === "GET") return answerWidget(segments[2] ?? "", url.searchParams, context, inScope);
|
|
591
|
+
if (segments.length === 1 && segments[0] === "search" && method === "GET") return search(url.searchParams, inScope);
|
|
295
592
|
if (segments[0] === "uploads") return handleUploads(segments, method, readBody);
|
|
296
593
|
if (segments[0] !== "resources" || segments[1] === void 0) return problem(404, "Not found.");
|
|
297
594
|
const resource = definition.resources.find((candidate) => candidate.id === segments[1]);
|
|
298
595
|
const list = resource !== void 0 ? store.get(resource.id) : void 0;
|
|
299
596
|
if (resource === void 0 || list === void 0) return problem(404, "Resource not found.");
|
|
597
|
+
const scoped = inScope(resource.id, list);
|
|
598
|
+
if (segments.length === 3 && segments[2] === "aggregate" && method === "GET") {
|
|
599
|
+
if (resource.abilities?.viewAny === false) return problem(403, "This resource can’t be listed.");
|
|
600
|
+
const aggregates = resource.list?.aggregates;
|
|
601
|
+
if (aggregates === void 0) return problem(404, "This resource has no aggregates.");
|
|
602
|
+
const read = readAggregateQuery(url.searchParams, aggregates);
|
|
603
|
+
if (read.errors !== void 0) return problem(422, "The given data was invalid.", {
|
|
604
|
+
type: "urn:panneau:problem:validation",
|
|
605
|
+
errors: read.errors
|
|
606
|
+
});
|
|
607
|
+
const query = fromSearchParams(url.searchParams);
|
|
608
|
+
const group = read.query.group;
|
|
609
|
+
return json(200, aggregateItems(applyQuery(scoped, {
|
|
610
|
+
...query,
|
|
611
|
+
sort: []
|
|
612
|
+
}), read.query, {
|
|
613
|
+
fields: [...resource.fields, ...(resource.types ?? []).flatMap((type) => type.fields)],
|
|
614
|
+
range: group?.type === "period" ? getFilterRange(query, group.field) : void 0
|
|
615
|
+
}));
|
|
616
|
+
}
|
|
300
617
|
if (segments.length === 2) {
|
|
301
618
|
if (method === "GET") {
|
|
619
|
+
if (resource.abilities?.viewAny === false) return problem(403, "This resource can’t be listed.");
|
|
302
620
|
const query = fromSearchParams(url.searchParams);
|
|
303
621
|
const perPage = query.perPage ?? resource.list?.perPage ?? 20;
|
|
304
622
|
const page = query.page ?? 1;
|
|
305
623
|
const sort = query.sort ?? resource.list?.defaultSort?.split(",");
|
|
306
|
-
const matching = applyQuery(
|
|
624
|
+
const matching = applyQuery(scoped, {
|
|
307
625
|
...query,
|
|
308
626
|
...sort !== void 0 ? { sort } : {}
|
|
309
627
|
});
|
|
628
|
+
if (resource.list?.pagination === "cursor") {
|
|
629
|
+
const cursor = query.cursor ?? "o0";
|
|
630
|
+
if (!/^o\d+$/.test(cursor)) return problem(422, "The cursor is invalid.", { errors: { cursor: ["The cursor is invalid."] } });
|
|
631
|
+
const offset = Number(cursor.slice(1));
|
|
632
|
+
const end = offset + perPage;
|
|
633
|
+
return json(200, {
|
|
634
|
+
data: matching.slice(offset, end).map((item) => present(resource, item)),
|
|
635
|
+
meta: {
|
|
636
|
+
perPage,
|
|
637
|
+
nextCursor: end < matching.length ? `o${String(end)}` : null,
|
|
638
|
+
previousCursor: offset - perPage > 0 ? `o${String(offset - perPage)}` : null
|
|
639
|
+
}
|
|
640
|
+
});
|
|
641
|
+
}
|
|
310
642
|
return json(200, {
|
|
311
|
-
data: matching.slice((page - 1) * perPage, page * perPage),
|
|
643
|
+
data: matching.slice((page - 1) * perPage, page * perPage).map((item) => present(resource, item)),
|
|
312
644
|
meta: {
|
|
313
645
|
page,
|
|
314
646
|
perPage,
|
|
@@ -318,29 +650,70 @@ function createMockBackend({ definition, items = {} }) {
|
|
|
318
650
|
});
|
|
319
651
|
}
|
|
320
652
|
if (method === "POST") {
|
|
321
|
-
|
|
322
|
-
const
|
|
653
|
+
if (resource.abilities?.create === false) return problem(403, "Items of this resource can’t be created.");
|
|
654
|
+
const raw = await readBody();
|
|
655
|
+
const typed = hasResourceTypes(resource);
|
|
656
|
+
const type = typed ? getResourceType(resource, raw[ITEM_TYPE_KEY]) : void 0;
|
|
657
|
+
if (typed && type === void 0) return problem(422, "The given data was invalid.", {
|
|
658
|
+
type: "urn:panneau:problem:validation",
|
|
659
|
+
errors: { [ITEM_TYPE_KEY]: ["The type is not a type of this resource."] }
|
|
660
|
+
});
|
|
661
|
+
if (type?.abilities?.create === false) return problem(403, "Items of this type can’t be created.");
|
|
662
|
+
const ofType = withTypeFields(resource, type?.id);
|
|
663
|
+
const body = writableValues(ofType, raw);
|
|
664
|
+
const invalid = validationProblem(ofType, body, "create");
|
|
323
665
|
if (invalid !== null) return invalid;
|
|
324
|
-
const { values, problem: unresolved } = resolveValues(
|
|
666
|
+
const { values, problem: unresolved } = resolveValues(ofType, body);
|
|
325
667
|
if (unresolved !== null) return unresolved;
|
|
326
|
-
const item = makeItem(resource, {
|
|
668
|
+
const item = withOwnTransform(ofType, makeItem(resource, {
|
|
327
669
|
...values,
|
|
328
|
-
id: void 0
|
|
329
|
-
|
|
670
|
+
id: void 0,
|
|
671
|
+
...type !== void 0 ? { [ITEM_TYPE_KEY]: type.id } : {}
|
|
672
|
+
}));
|
|
330
673
|
list.push(item);
|
|
331
|
-
return json(201, { data: item }, etag(item));
|
|
674
|
+
return json(201, { data: present(resource, item) }, etag(item));
|
|
332
675
|
}
|
|
333
676
|
return problem(405, "Method not allowed.");
|
|
334
677
|
}
|
|
678
|
+
if (segments[2] === "fields" && segments[4] === "check" && segments.length === 5) {
|
|
679
|
+
if (method !== "POST") return problem(405, "Method not allowed.");
|
|
680
|
+
const field = [...resource.fields, ...(resource.types ?? []).flatMap((type) => type.fields)].find((candidate) => candidate.name === segments[3] && candidate.check === true);
|
|
681
|
+
if (field === void 0) return problem(404, "Field not found.");
|
|
682
|
+
const body = await readBody();
|
|
683
|
+
if (typeof body.value !== "string") return problem(422, "The given data was invalid.", {
|
|
684
|
+
type: "urn:panneau:problem:validation",
|
|
685
|
+
errors: { value: ["The value is required."] }
|
|
686
|
+
});
|
|
687
|
+
const locale = typeof body.locale === "string" ? body.locale : null;
|
|
688
|
+
const id = typeof body.id === "string" || typeof body.id === "number" ? String(body.id) : null;
|
|
689
|
+
const valueOf = (item) => {
|
|
690
|
+
const value = item[field.name];
|
|
691
|
+
return locale !== null && isRecord(value) ? value[locale] : value;
|
|
692
|
+
};
|
|
693
|
+
const taken = (candidate) => list.some((item) => item.id !== id && valueOf(item) === candidate);
|
|
694
|
+
const available = !taken(body.value);
|
|
695
|
+
let suggestion = null;
|
|
696
|
+
for (let index = 2; !available && suggestion === null; index += 1) {
|
|
697
|
+
const candidate = `${body.value}-${String(index)}`;
|
|
698
|
+
suggestion = taken(candidate) ? null : candidate;
|
|
699
|
+
}
|
|
700
|
+
const prefix = typeof field.settings?.prefix === "string" ? field.settings.prefix : null;
|
|
701
|
+
return json(200, {
|
|
702
|
+
available,
|
|
703
|
+
suggestion,
|
|
704
|
+
prefix,
|
|
705
|
+
url: prefix !== null ? `${prefix}${body.value}` : null
|
|
706
|
+
});
|
|
707
|
+
}
|
|
335
708
|
if (segments[2] === "actions" && segments[3] !== void 0 && segments.length === 4) {
|
|
336
709
|
if (method !== "POST") return problem(405, "Method not allowed.");
|
|
337
710
|
const actionId = segments[3];
|
|
338
711
|
const action = (resource.actions ?? []).find((candidate) => candidate.id === actionId);
|
|
339
712
|
const body = await readBody();
|
|
340
713
|
if (body.dryRun === true) {
|
|
341
|
-
if (action?.dryRun !== true) return problem(400, "This action does not support dry runs.");
|
|
342
|
-
const selected = selectItems(
|
|
343
|
-
const allowed = selected.filter((item) => item
|
|
714
|
+
if (action?.dryRun !== true && actionId !== "delete") return problem(400, "This action does not support dry runs.");
|
|
715
|
+
const selected = selectItems(scoped, body.selection);
|
|
716
|
+
const allowed = selected.filter((item) => allows(item, actionId));
|
|
344
717
|
return json(200, {
|
|
345
718
|
summary: {
|
|
346
719
|
succeeded: allowed.length,
|
|
@@ -354,46 +727,134 @@ function createMockBackend({ definition, items = {} }) {
|
|
|
354
727
|
}))
|
|
355
728
|
});
|
|
356
729
|
}
|
|
730
|
+
const hasTrash = (resource.actions ?? []).some((candidate) => candidate.id === "delete" && candidate.undoable === true);
|
|
731
|
+
if (actionId === "restore" && hasTrash) {
|
|
732
|
+
const selection = body.selection;
|
|
733
|
+
const ids = selection !== void 0 && "ids" in selection && Array.isArray(selection.ids) ? selection.ids.map(String) : null;
|
|
734
|
+
if (ids === null) return problem(422, "The selection needs ids.", {
|
|
735
|
+
type: "urn:panneau:problem:validation",
|
|
736
|
+
errors: { selection: ["The selection needs ids."] }
|
|
737
|
+
});
|
|
738
|
+
const deleted = trash.get(resource.id) ?? [];
|
|
739
|
+
const restored = deleted.filter((item) => ids.includes(item.id));
|
|
740
|
+
const missing = ids.filter((id) => !restored.some((item) => item.id === id));
|
|
741
|
+
if (ids.length === 1 && missing.length === 1) return problem(404, "Item not found.");
|
|
742
|
+
trash.set(resource.id, deleted.filter((item) => !restored.includes(item)));
|
|
743
|
+
store.set(resource.id, [...list, ...restored]);
|
|
744
|
+
return json(200, {
|
|
745
|
+
summary: {
|
|
746
|
+
succeeded: restored.length,
|
|
747
|
+
failed: 0,
|
|
748
|
+
skipped: missing.length
|
|
749
|
+
},
|
|
750
|
+
...missing.length > 0 ? { results: missing.map((id) => ({
|
|
751
|
+
id,
|
|
752
|
+
status: "skipped",
|
|
753
|
+
reason: "not_found"
|
|
754
|
+
})) } : {},
|
|
755
|
+
refresh: "list"
|
|
756
|
+
});
|
|
757
|
+
}
|
|
357
758
|
if (actionId !== "delete") return problem(404, "Action not found.");
|
|
358
|
-
const
|
|
359
|
-
|
|
759
|
+
const selection = body.selection;
|
|
760
|
+
const selected = selectItems(scoped, selection);
|
|
761
|
+
const allowed = selected.filter((item) => allows(item, "delete"));
|
|
762
|
+
const skipped = selected.filter((item) => !allowed.includes(item));
|
|
763
|
+
const inUse = allowed.filter((item) => options.inUse?.({
|
|
764
|
+
resource: resource.id,
|
|
765
|
+
item
|
|
766
|
+
}) === true);
|
|
767
|
+
const deleted = allowed.filter((item) => !inUse.includes(item));
|
|
768
|
+
if ((selection !== void 0 && "ids" in selection && Array.isArray(selection.ids) ? selection.ids : null)?.length === 1 && skipped.length > 0) return problem(403, "This item can’t be deleted.");
|
|
769
|
+
store.set(resource.id, list.filter((item) => !deleted.includes(item)));
|
|
770
|
+
if (hasTrash) trash.set(resource.id, [...trash.get(resource.id) ?? [], ...deleted]);
|
|
360
771
|
return json(200, {
|
|
361
|
-
message: `${
|
|
772
|
+
message: `${deleted.length} deleted.`,
|
|
773
|
+
...hasTrash && deleted.length > 0 && deleted.length <= 100 ? { undo: {
|
|
774
|
+
action: "restore",
|
|
775
|
+
items: deleted.map((item) => item.id)
|
|
776
|
+
} } : {},
|
|
362
777
|
summary: {
|
|
363
|
-
succeeded:
|
|
778
|
+
succeeded: deleted.length,
|
|
364
779
|
failed: 0,
|
|
365
|
-
skipped:
|
|
780
|
+
skipped: skipped.length + inUse.length
|
|
366
781
|
},
|
|
782
|
+
...skipped.length + inUse.length > 0 ? { results: [...skipped.map((item) => ({
|
|
783
|
+
id: item.id,
|
|
784
|
+
status: "skipped",
|
|
785
|
+
reason: "forbidden"
|
|
786
|
+
})), ...inUse.map((item) => ({
|
|
787
|
+
id: item.id,
|
|
788
|
+
status: "skipped",
|
|
789
|
+
reason: "in_use"
|
|
790
|
+
}))].slice(0, 20) } : {},
|
|
367
791
|
refresh: "list"
|
|
368
792
|
});
|
|
369
793
|
}
|
|
794
|
+
if (segments.length === 4 && segments[3] === "duplicate" && segments[2] !== void 0) {
|
|
795
|
+
const current = scoped.find((item) => item.id === segments[2]);
|
|
796
|
+
if (current === void 0) return problem(404, "Item not found.");
|
|
797
|
+
if (method !== "POST") return problem(405, "Method not allowed.");
|
|
798
|
+
if (!allows(current, "duplicate")) return problem(403, "This item can’t be duplicated.");
|
|
799
|
+
const { id: _id, version: _version, abilities: _abilities, ...values } = current;
|
|
800
|
+
const copy = makeItem(resource, {
|
|
801
|
+
...values,
|
|
802
|
+
id: freshId(resource)
|
|
803
|
+
});
|
|
804
|
+
list.push(copy);
|
|
805
|
+
return json(201, { data: present(resource, copy) }, etag(copy));
|
|
806
|
+
}
|
|
807
|
+
if (segments.length === 4 && segments[3] === "preview" && segments[2] !== void 0) {
|
|
808
|
+
const current = scoped.find((item) => item.id === segments[2]);
|
|
809
|
+
if (current === void 0) return problem(404, "Item not found.");
|
|
810
|
+
if (method !== "POST") return problem(405, "Method not allowed.");
|
|
811
|
+
const body = await readBody();
|
|
812
|
+
const item = {
|
|
813
|
+
...current,
|
|
814
|
+
...isRecord(body) ? body : {}
|
|
815
|
+
};
|
|
816
|
+
return json(200, {
|
|
817
|
+
url: options.previewUrl?.({
|
|
818
|
+
resource: resource.id,
|
|
819
|
+
item
|
|
820
|
+
}) ?? defaultPreviewUrl(item),
|
|
821
|
+
expiresAt: new Date(Date.now() + 3e5).toISOString()
|
|
822
|
+
});
|
|
823
|
+
}
|
|
370
824
|
if (segments.length !== 3 || segments[2] === void 0) return problem(404, "Not found.");
|
|
371
825
|
const id = segments[2];
|
|
372
|
-
const index = list.findIndex((item) => item.id === id);
|
|
826
|
+
const index = scoped.some((item) => item.id === id) ? list.findIndex((item) => item.id === id) : -1;
|
|
373
827
|
const current = list[index];
|
|
374
828
|
if (current === void 0) return problem(404, "Item not found.");
|
|
375
|
-
if (method === "GET")
|
|
829
|
+
if (method === "GET") {
|
|
830
|
+
if (current.abilities.view !== true) return problem(403, "This item can’t be viewed.");
|
|
831
|
+
return json(200, { data: present(resource, current) }, etag(current));
|
|
832
|
+
}
|
|
376
833
|
if (method === "PATCH") {
|
|
834
|
+
if (current.abilities.update !== true) return problem(403, "This item can’t be updated.");
|
|
377
835
|
const ifMatch = request.headers.get("If-Match");
|
|
378
836
|
if (ifMatch !== null && current.version !== null && parseEtag(ifMatch) !== current.version) return problem(412, "The item was changed by someone else.", {
|
|
379
837
|
type: "urn:panneau:problem:version-conflict",
|
|
380
|
-
current
|
|
838
|
+
current: present(resource, current)
|
|
381
839
|
});
|
|
382
|
-
const
|
|
383
|
-
const
|
|
840
|
+
const ofType = withTypeFields(resource, current[ITEM_TYPE_KEY]);
|
|
841
|
+
const writable = writableValues(ofType, await readBody());
|
|
842
|
+
const body = hasResourceTypes(resource) ? Object.fromEntries(Object.entries(writable).filter(([key]) => key !== ITEM_TYPE_KEY)) : writable;
|
|
843
|
+
const invalid = validationProblem(ofType, body, "update", current);
|
|
384
844
|
if (invalid !== null) return invalid;
|
|
385
|
-
const { values, problem: unresolved } = resolveValues(
|
|
845
|
+
const { values, problem: unresolved } = resolveValues(ofType, body);
|
|
386
846
|
if (unresolved !== null) return unresolved;
|
|
387
847
|
const updates = Object.fromEntries(Object.entries(values).filter(([key]) => !RESERVED_KEYS.has(key)));
|
|
388
|
-
const updated = {
|
|
848
|
+
const updated = withOwnTransform(ofType, {
|
|
389
849
|
...current,
|
|
390
850
|
...updates,
|
|
391
851
|
version: current.version === null ? null : String(Number(current.version) + 1)
|
|
392
|
-
};
|
|
852
|
+
});
|
|
393
853
|
list[index] = updated;
|
|
394
|
-
return json(200, { data: updated }, etag(updated));
|
|
854
|
+
return json(200, { data: present(resource, updated) }, etag(updated));
|
|
395
855
|
}
|
|
396
856
|
if (method === "DELETE") {
|
|
857
|
+
if (current.abilities.delete !== true) return problem(403, "This item can’t be deleted.");
|
|
397
858
|
list.splice(index, 1);
|
|
398
859
|
return json(204, null);
|
|
399
860
|
}
|