@panneau/protocol 5.0.0-alpha.3 → 5.0.0-alpha.31

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