@aduptive/strapi-blockscene 2.0.0-alpha.1 → 2.0.0-alpha.10

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 (5) hide show
  1. package/README.md +917 -48
  2. package/dist/admin.cjs +8769 -1067
  3. package/dist/admin.mjs +8835 -1073
  4. package/dist/server.cjs +1678 -39
  5. package/package.json +3 -5
package/dist/server.cjs CHANGED
@@ -106,7 +106,41 @@ var require_groups = __commonJS({
106
106
  const [, end] = groupRange(rows, start, g);
107
107
  return [...rows.slice(0, start), ...rows.slice(end + 1)];
108
108
  }
109
- module2.exports = { safeGroups: safeGroups2, validateGroups: validateGroups2, groupRange, groupRows, topLevelRanges, moveGroup, removeGroup, blockKey, isOpener, isClose };
109
+ var MAX_COLUMNS = 12;
110
+ var parseColumns = (value) => {
111
+ const n = typeof value === "number" ? value : typeof value === "string" && /^\s*\d{1,3}\s*$/.test(value) ? Number(value) : NaN;
112
+ return Number.isInteger(n) && n >= 1 ? n : null;
113
+ };
114
+ var columnsAttribute = (attr) => Boolean(attr) && typeof attr === "object" && !attr.private && (["integer", "biginteger", "float", "decimal", "string"].includes(attr.type) || attr.type === "enumeration" && Array.isArray(attr.enum) && attr.enum.length > 0 && attr.enum.every((value) => parseColumns(value) !== null));
115
+ var layoutFields2 = (schema) => Object.entries(schema?.attributes || {}).filter(([, attr]) => columnsAttribute(attr)).map(([name]) => name);
116
+ function validLayout(value, attributes) {
117
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
118
+ if (!Object.keys(value).every((key) => ["columnsField", "mobileColumnsField", "maxColumns"].includes(key))) return false;
119
+ const field = (name) => typeof name === "string" && /^[A-Za-z_][\w-]{0,63}$/.test(name) && (!attributes || columnsAttribute(attributes[name]));
120
+ return field(value.columnsField) && (value.mobileColumnsField === void 0 || field(value.mobileColumnsField)) && (value.maxColumns === void 0 || Number.isInteger(value.maxColumns) && value.maxColumns >= 1 && value.maxColumns <= MAX_COLUMNS);
121
+ }
122
+ function layoutColumns(row, layout, schema) {
123
+ const max = layout.maxColumns || MAX_COLUMNS;
124
+ const read = (name) => Math.min(max, parseColumns(row?.[name]) ?? parseColumns(schema?.attributes?.[name]?.default) ?? 1);
125
+ return { desktop: read(layout.columnsField), mobile: layout.mobileColumnsField ? read(layout.mobileColumnsField) : null };
126
+ }
127
+ module2.exports = {
128
+ safeGroups: safeGroups2,
129
+ validateGroups: validateGroups2,
130
+ groupRange,
131
+ groupRows,
132
+ topLevelRanges,
133
+ moveGroup,
134
+ removeGroup,
135
+ blockKey,
136
+ isOpener,
137
+ isClose,
138
+ MAX_COLUMNS,
139
+ parseColumns,
140
+ layoutFields: layoutFields2,
141
+ validLayout,
142
+ layoutColumns
143
+ };
110
144
  }
111
145
  });
112
146
 
@@ -118,6 +152,7 @@ var require_settings = __commonJS({
118
152
  var TEMPLATES2 = ["generic", "banner", "cards", "imageText", "faq", "none"];
119
153
  var INITIAL_STATES = ["closed", "open", "remember"];
120
154
  var PREVIEW_MODES = ["form", "split", "preview"];
155
+ var HIDDEN_MODES = ["strip", "flag", "off"];
121
156
  var DEFAULTS2 = {
122
157
  palette: { background: "#F6F6F9", surface: "#DCDCE4", text: "#32324D", accent: "#4945FF" },
123
158
  components: {},
@@ -125,13 +160,118 @@ var require_settings = __commonJS({
125
160
  // blockPreviewInForm: compact read-only preview above a block's fields in form
126
161
  // mode. Only installations that ship the accordion integration (server config
127
162
  // `blockPreview: true`) show and honour it; the page preview is the editor.
128
- editor: { enabled: true, showOpenAll: true, showCloseAll: true, initialState: "closed", previewMode: "form", previewUrl: "", blockPreviewInForm: false }
163
+ editor: {
164
+ enabled: true,
165
+ showOpenAll: true,
166
+ showCloseAll: true,
167
+ showRowThumbnails: true,
168
+ initialState: "closed",
169
+ previewMode: "form",
170
+ previewUrl: "",
171
+ blockPreviewUrl: "",
172
+ blockPreviewInForm: false,
173
+ // Strapi 5: rich-text custom fields render a read-only preview until clicked (see admin/LazyInput.tsx).
174
+ lazyEditors: true,
175
+ lazyFields: ["plugin::ckeditor5.CKEditor"],
176
+ // Row actions in each block header (see README "Row actions"). hiddenBlocks: what the content API does with rows
177
+ // hidden on the site: 'strip' removes them, 'flag' sends them with the attribute, 'off' hides the eye icon.
178
+ confirmDelete: true,
179
+ hiddenBlocks: "strip",
180
+ duplicate: true,
181
+ clipboard: true,
182
+ // Edit view labels that are still the raw attribute name read as "Mobile columns count" (see README "Field labels").
183
+ friendlyLabels: true,
184
+ // Page preview pane (Strapi 5): which toolbar controls show, in order, and the width menu's entries.
185
+ previewToolbar: ["modes", "history", "devices", "status", "actions"],
186
+ previewDevices: ["fit", "mobile", "tablet", "desktop"]
187
+ },
188
+ // Per content type (only the ones with a Dynamic Zone): { enabled: false } turns the plugin off there;
189
+ // previewMode overrides editor.previewMode as the mode the edit view opens in. Absent means the global behaviour.
190
+ contentTypes: {},
191
+ // Version history (Strapi 5, see README "Version history"): off until turned on. contentTypes: 'all' (every api:: type)
192
+ // or a list of uids. Snapshots are kept retentionDays and at most maxSnapshots per document; events eventDays; deleted
193
+ // documents stay in the trash trashDays (fixed per document when it is deleted).
194
+ history: { enabled: false, contentTypes: "all", retentionDays: 90, maxSnapshots: 100, eventDays: 365, trashDays: 90 }
195
+ };
196
+ var ICONS = ["text", "tag", "seo", "settings", "image", "link", "palette", "list", "globe", "info"];
197
+ var SIDEBAR_POSITIONS = ["left", "right", "bottom"];
198
+ var OPENS = ["modal", "drawer"];
199
+ var LABEL = /^[^<>]{1,40}$/;
200
+ var TOOLBAR = ["modes", "history", "devices", "status", "actions"];
201
+ var DEVICE_NAMES = ["fit", "mobile", "tablet", "desktop"];
202
+ var previewToolbar = (value) => Array.isArray(value) && value.every((id) => TOOLBAR.includes(id)) && new Set(value).size === value.length;
203
+ var DEVICE_LABEL = /^[^<>]{1,24}$/;
204
+ var customDevice = (item) => item && typeof item === "object" && !Array.isArray(item) && Object.keys(item).every((key) => ["label", "width"].includes(key)) && typeof item.label === "string" && DEVICE_LABEL.test(item.label.trim()) && Number.isInteger(item.width) && item.width >= 240 && item.width <= 3840;
205
+ var previewDevices = (value) => Array.isArray(value) && value.length >= 1 && value.length <= 8 && value.every((item) => DEVICE_NAMES.includes(item) || customDevice(item)) && new Set(value.map((item) => typeof item === "string" ? item : item.width)).size === value.length;
206
+ var cleanDevices = (value) => value.map((item) => typeof item === "string" ? item : { label: item.label.trim(), width: item.width });
207
+ var sidebarItem = (item, attributes) => item && typeof item === "object" && !Array.isArray(item) && Object.keys(item).every((key) => ["label", "icon", "open", "fields"].includes(key)) && typeof item.label === "string" && LABEL.test(item.label.trim()) && (item.icon === void 0 || item.icon === "" || ICONS.includes(item.icon)) && OPENS.includes(item.open) && Array.isArray(item.fields) && item.fields.length > 0 && item.fields.length <= 30 && item.fields.every((field) => typeof field === "string" && (!attributes || attributes.includes(field)));
208
+ var TYPE_KEYS = {
209
+ enabled: (value) => typeof value === "boolean",
210
+ previewMode: (value) => PREVIEW_MODES.includes(value),
211
+ sidebarPosition: (value) => SIDEBAR_POSITIONS.includes(value),
212
+ previewToolbar,
213
+ previewDevices,
214
+ sidebar: (value, attributes) => Array.isArray(value) && value.length <= 12 && value.every((item) => sidebarItem(item, attributes))
129
215
  };
216
+ var typeMap = (types) => Array.isArray(types) ? Object.fromEntries(types.map((uid) => [uid, null])) : types || {};
130
217
  var PREVIEW_URL = /^https?:\/\/[^\s"'<>]{1,500}$/;
218
+ var blockPreviewUrl = (value) => typeof value === "string" && (value === "" || PREVIEW_URL.test(value) && !/[{}]/.test(value.replace(/\{(uid|name|category|variant|locale)\}/g, "")) && URL.canParse?.(value.replace(/[{}]/g, "")) !== false);
131
219
  var COLOR = /^#[0-9A-Fa-f]{6}$/;
220
+ var FIELD_UID = /^(plugin|global)::[\w.-]+$/;
221
+ var lazyFields = (value) => Array.isArray(value) && value.length <= 20 && value.every((uid) => typeof uid === "string" && FIELD_UID.test(uid));
132
222
  var UID = /^[a-z0-9-]+\.[a-z0-9-]+$/;
223
+ var API_UID = /^api::[\w-]+\.[\w-]+$/;
224
+ var days = (value) => Number.isInteger(value) && value >= 1 && value <= 3650;
225
+ var HISTORY_KEYS = {
226
+ enabled: (value) => typeof value === "boolean",
227
+ contentTypes: (value, uids) => value === "all" || Array.isArray(value) && value.length <= 500 && value.every((uid) => typeof uid === "string" && API_UID.test(uid) && (!uids || uids.includes(uid))),
228
+ retentionDays: days,
229
+ maxSnapshots: (value) => Number.isInteger(value) && value >= 1 && value <= 1e3,
230
+ eventDays: days,
231
+ trashDays: days
232
+ };
233
+ var TYPOLOGIES2 = ["hero", "text", "media", "listing", "cards", "cta", "form", "layout"];
234
+ var TAG = /^[^<>\n]{1,24}$/;
235
+ var cleanTags = (value) => Array.isArray(value) ? [...new Set(value.filter((tag) => typeof tag === "string" && TAG.test(tag.trim())).map((tag) => tag.trim()))].slice(0, 10) : [];
236
+ var validTags = (value) => Array.isArray(value) && value.length <= 10 && value.every((tag) => typeof tag === "string" && TAG.test(tag.trim()));
237
+ var GUESSES = [
238
+ ["hero", /hero|banner|cover/],
239
+ ["text", /text|rich|quote|title/],
240
+ ["media", /image|media|video|gallery|carousel/],
241
+ ["listing", /list|query|archive|related|posts|projects/],
242
+ ["cards", /card/],
243
+ ["cta", /cta|button|link/],
244
+ ["form", /form|contact/],
245
+ ["layout", /wrapper|column|grid|divider|divisor|spacer|section/]
246
+ ];
247
+ function guessTypology(uid, displayName = "") {
248
+ const name = `${uid.split(".").pop()} ${displayName}`.toLowerCase();
249
+ return GUESSES.find(([, pattern]) => pattern.test(name))?.[0] || "text";
250
+ }
251
+ function facetsOf(uid, schema, schemas = {}) {
252
+ const facets = /* @__PURE__ */ new Set();
253
+ const read = (attributes, nested) => {
254
+ for (const attr of Object.values(attributes || {})) {
255
+ if (attr?.type === "media") {
256
+ const allowed = attr.allowedTypes;
257
+ if (!allowed || allowed.includes("images")) facets.add("image");
258
+ if (!allowed || allowed.includes("videos")) facets.add("video");
259
+ if (attr.multiple) facets.add("gallery");
260
+ } else if (["richtext", "blocks"].includes(attr?.type) || attr?.type === "customField" && /ckeditor/i.test(String(attr.customField))) facets.add("richtext");
261
+ else if (attr?.type === "relation") facets.add("dynamic");
262
+ else if (attr?.type === "component") {
263
+ if (attr.repeatable) facets.add("list");
264
+ if (!nested) read(schemas[attr.component]?.attributes, true);
265
+ }
266
+ }
267
+ };
268
+ read(schema?.attributes, false);
269
+ if (/query|archive|related/i.test(uid)) facets.add("dynamic");
270
+ if (/form|contact/i.test(`${uid} ${schema?.info?.displayName || ""}`)) facets.add("form");
271
+ return [...facets];
272
+ }
133
273
  var safeUrl2 = (value) => typeof value === "string" && (/^\/(?!\/)/.test(value) || /^https?:\/\//.test(value)) ? value : void 0;
134
- var { safeGroups: safeGroups2 } = require_groups();
274
+ var { safeGroups: safeGroups2, validLayout } = require_groups();
135
275
  var safeVersion = (value) => typeof value === "string" && /^[\w.-]{1,32}$/.test(value) ? value : void 0;
136
276
  var fail2 = (message, details) => {
137
277
  let ValidationError;
@@ -156,6 +296,16 @@ var require_settings = __commonJS({
156
296
  ["label", "description", "category", "keywords"].filter((key) => typeof entry[key] === "string").map((key) => [key, entry[key]])
157
297
  );
158
298
  entries[uid].image = safeUrl2(entry.image);
299
+ if (TYPOLOGIES2.includes(entry.typology)) entries[uid].typology = entry.typology;
300
+ const tags = cleanTags(entry.tags);
301
+ if (tags.length || entries[uid].category) entries[uid].tags = tags.length ? tags : cleanTags([entries[uid].category]);
302
+ }
303
+ for (const [uid, schema] of Object.entries(config.schemas || {})) {
304
+ const entry = entries[uid] ||= {};
305
+ for (const [key, value] of Object.entries(config.blocks?.[uid] || {})) if (entry[key] === void 0) entry[key] = value;
306
+ entry.facets = facetsOf(uid, schema, config.schemas);
307
+ entry.typology ||= guessTypology(uid, schema?.info?.displayName);
308
+ entry.tags ||= [];
159
309
  }
160
310
  return {
161
311
  components: entries,
@@ -167,7 +317,8 @@ var require_settings = __commonJS({
167
317
  groups: safeGroups2(config.groups, config.componentUids)
168
318
  };
169
319
  }
170
- function validateSettings2(input, componentUids2) {
320
+ function validateSettings2(input, componentUids2, contentTypeUids2 = [], historyTypes = null, schemas = null) {
321
+ const types = typeMap(contentTypeUids2);
171
322
  if (!input || typeof input !== "object" || Array.isArray(input)) fail2("Settings must be an object");
172
323
  if (JSON.stringify(input).length > 64 * 1024) fail2("Settings payload too large");
173
324
  const out = structuredClone(DEFAULTS2);
@@ -179,9 +330,9 @@ var require_settings = __commonJS({
179
330
  }
180
331
  for (const [key, value] of Object.entries(input.editor || {})) {
181
332
  if (!(key in DEFAULTS2.editor)) fail2(`Unknown editor option "${key}"`);
182
- const valid = key === "initialState" ? INITIAL_STATES.includes(value) : key === "previewMode" ? PREVIEW_MODES.includes(value) : key === "previewUrl" ? value === "" || typeof value === "string" && PREVIEW_URL.test(value) : typeof value === "boolean";
333
+ const valid = key === "initialState" ? INITIAL_STATES.includes(value) : key === "previewMode" ? PREVIEW_MODES.includes(value) : key === "hiddenBlocks" ? HIDDEN_MODES.includes(value) : key === "previewUrl" ? value === "" || typeof value === "string" && PREVIEW_URL.test(value) : key === "blockPreviewUrl" ? blockPreviewUrl(value) : key === "lazyFields" ? lazyFields(value) : key === "previewToolbar" ? previewToolbar(value) : key === "previewDevices" ? previewDevices(value) : typeof value === "boolean";
183
334
  if (!valid) fail2(`Invalid value for editor option "${key}"`);
184
- out.editor[key] = key === "previewUrl" && value ? String(new URL(value).href).replace(/\/$/, "") : value;
335
+ out.editor[key] = key === "previewUrl" && value ? String(new URL(value).href).replace(/\/$/, "") : key === "lazyFields" ? [...new Set(value)] : key === "previewDevices" ? cleanDevices(value) : value;
185
336
  }
186
337
  const components = input.components || {};
187
338
  if (typeof components !== "object" || Array.isArray(components)) fail2("components must be an object");
@@ -193,16 +344,45 @@ var require_settings = __commonJS({
193
344
  if (key === "template") {
194
345
  if (!TEMPLATES2.includes(entry.template)) fail2(`Unknown template for "${uid}"`);
195
346
  clean.template = entry.template;
347
+ } else if (key === "typology") {
348
+ if (!TYPOLOGIES2.includes(entry.typology)) fail2(`Unknown typology for "${uid}"`);
349
+ clean.typology = entry.typology;
350
+ } else if (key === "tags") {
351
+ if (!validTags(entry.tags)) fail2(`Invalid tags for "${uid}": up to 10, each 1 to 24 characters`);
352
+ clean.tags = cleanTags(entry.tags);
196
353
  } else if (key === "mediaId") {
197
354
  if (!Number.isInteger(entry.mediaId) || entry.mediaId <= 0) fail2(`Invalid media for "${uid}"`);
198
355
  clean.mediaId = entry.mediaId;
356
+ } else if (key === "layout") {
357
+ if (!validLayout(entry.layout, schemas && (schemas[uid]?.attributes || {}))) fail2(`Invalid layout for "${uid}": columnsField (and mobileColumnsField) must name a number, string or numeric enumeration attribute of the component; maxColumns 1 to 12`);
358
+ clean.layout = structuredClone(entry.layout);
199
359
  } else fail2(`Unknown component setting "${key}"`);
200
360
  }
201
361
  if (Object.keys(clean).length) out.components[uid] = clean;
202
362
  }
363
+ const perType = input.contentTypes || {};
364
+ if (typeof perType !== "object" || Array.isArray(perType)) fail2("contentTypes must be an object");
365
+ for (const [uid, entry] of Object.entries(perType)) {
366
+ if (!(uid in types)) fail2(`Unknown content type "${uid}"`);
367
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) fail2(`Invalid entry for "${uid}"`);
368
+ for (const [key, value] of Object.entries(entry)) {
369
+ if (!(key in TYPE_KEYS)) fail2(`Unknown content type setting "${key}"`);
370
+ if (!TYPE_KEYS[key](value, types[uid])) fail2(`Invalid value for "${key}" of "${uid}"`);
371
+ }
372
+ if (Object.keys(entry).length) out.contentTypes[uid] = { ...structuredClone(entry), ...entry.previewDevices && { previewDevices: cleanDevices(entry.previewDevices) } };
373
+ }
374
+ const history = input.history || {};
375
+ if (typeof history !== "object" || Array.isArray(history)) fail2("history must be an object");
376
+ for (const [key, value] of Object.entries(history)) {
377
+ if (!(key in HISTORY_KEYS)) fail2(`Unknown history option "${key}"`);
378
+ if (!HISTORY_KEYS[key](value, historyTypes)) fail2(`Invalid value for history option "${key}"`);
379
+ out.history[key] = Array.isArray(value) ? [...new Set(value)] : value;
380
+ }
381
+ if (out.history.eventDays < out.history.retentionDays) fail2("history.eventDays must be at least history.retentionDays");
203
382
  return out;
204
383
  }
205
- function mergeSaved2(saved, componentUids2) {
384
+ function mergeSaved2(saved, componentUids2, contentTypeUids2 = [], historyTypes = null, schemas = null) {
385
+ const types = typeMap(contentTypeUids2);
206
386
  const out = structuredClone(DEFAULTS2);
207
387
  if (!saved || typeof saved !== "object") return out;
208
388
  for (const key of Object.keys(DEFAULTS2.palette)) if (COLOR.test(String(saved.palette?.[key]))) out.palette[key] = saved.palette[key];
@@ -211,19 +391,1307 @@ var require_settings = __commonJS({
211
391
  if (value === void 0 || typeof value !== typeof DEFAULTS2.editor[key]) continue;
212
392
  if (key === "initialState" && !INITIAL_STATES.includes(value)) continue;
213
393
  if (key === "previewMode" && !PREVIEW_MODES.includes(value)) continue;
394
+ if (key === "hiddenBlocks" && !HIDDEN_MODES.includes(value)) continue;
214
395
  if (key === "previewUrl" && value && !PREVIEW_URL.test(value)) continue;
396
+ if (key === "blockPreviewUrl" && !blockPreviewUrl(value)) continue;
397
+ if (key === "previewToolbar" && !previewToolbar(value)) continue;
398
+ if (key === "previewDevices" && !previewDevices(value)) continue;
399
+ if (key === "lazyFields") {
400
+ if (!Array.isArray(value)) continue;
401
+ out.editor[key] = [...new Set(value.filter((uid) => lazyFields([uid])))].slice(0, 20);
402
+ continue;
403
+ }
215
404
  out.editor[key] = value;
216
405
  }
217
- for (const [uid, entry] of Object.entries(saved.components || {})) if (componentUids2.includes(uid) && entry && typeof entry === "object") out.components[uid] = { ...entry };
406
+ for (const [uid, entry] of Object.entries(saved.components || {})) {
407
+ if (!componentUids2.includes(uid) || !entry || typeof entry !== "object") continue;
408
+ const clean = { ...entry };
409
+ if ("typology" in clean && !TYPOLOGIES2.includes(clean.typology)) delete clean.typology;
410
+ if ("tags" in clean) {
411
+ clean.tags = cleanTags(clean.tags);
412
+ if (!clean.tags.length) delete clean.tags;
413
+ }
414
+ if ("layout" in clean && !validLayout(clean.layout, schemas && (schemas[uid]?.attributes || {}))) delete clean.layout;
415
+ if (Object.keys(clean).length) out.components[uid] = clean;
416
+ }
417
+ for (const [uid, entry] of Object.entries(saved.contentTypes || {})) {
418
+ if (!(uid in types) || !entry || typeof entry !== "object") continue;
419
+ const fix = (key, value) => key === "sidebar" && Array.isArray(value) ? value.filter((item) => sidebarItem(item, types[uid])) : value;
420
+ const clean = Object.fromEntries(Object.entries(entry).map(([key, value]) => [key, fix(key, value)]).filter(([key, value]) => TYPE_KEYS[key]?.(value, types[uid])));
421
+ if (Object.keys(clean).length) out.contentTypes[uid] = clean;
422
+ }
423
+ for (const key of Object.keys(HISTORY_KEYS)) {
424
+ let value = saved.history?.[key];
425
+ if (key === "contentTypes" && Array.isArray(value)) value = value.filter((uid) => HISTORY_KEYS.contentTypes([uid], historyTypes));
426
+ if (value !== void 0 && HISTORY_KEYS[key](value, historyTypes)) out.history[key] = value;
427
+ }
428
+ out.history.eventDays = Math.max(out.history.eventDays, out.history.retentionDays);
429
+ return out;
430
+ }
431
+ var ENTRY_KEYS = ["components", "contentTypes"];
432
+ var UNSET_WHEN_EMPTY = ["previewUrl", "blockPreviewUrl"];
433
+ var withoutEmpty = (editor) => Object.fromEntries(Object.entries(editor).filter(([key, value]) => !(UNSET_WHEN_EMPTY.includes(key) && value === "")));
434
+ function layer2(base, saved) {
435
+ if (!base) return saved;
436
+ const doc = saved && typeof saved === "object" ? saved : {};
437
+ const own = (key) => doc[key] && typeof doc[key] === "object" ? key === "editor" ? withoutEmpty(doc[key]) : doc[key] : {};
438
+ return Object.fromEntries(Object.keys(DEFAULTS2).map((key) => [key, { ...base[key], ...own(key) }]));
439
+ }
440
+ function overrides2(next, base) {
441
+ if (!base) return next;
442
+ return Object.fromEntries(Object.keys(DEFAULTS2).map((key) => {
443
+ const entries = Object.entries(next[key] || {}).filter(([name, value]) => JSON.stringify(value) !== JSON.stringify(base[key]?.[name]) && !(key === "editor" && UNSET_WHEN_EMPTY.includes(name) && value === ""));
444
+ if (ENTRY_KEYS.includes(key)) {
445
+ for (const uid of Object.keys(base[key] || {})) if (!(uid in (next[key] || {}))) entries.push([uid, {}]);
446
+ }
447
+ return [key, Object.fromEntries(entries)];
448
+ }));
449
+ }
450
+ var FIELD_TEXT = { label: 80, description: 300, placeholder: 120, help: 500 };
451
+ var LOCALE = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
452
+ var plain = (value) => value && typeof value === "object" && !Array.isArray(value);
453
+ var fieldText = (value, max) => typeof value === "string" ? value.trim() !== "" && value.length <= max : plain(value) && Object.keys(value).length > 0 && Object.keys(value).length <= 30 && Object.entries(value).every(([locale, text2]) => LOCALE.test(locale) && fieldText(text2, max));
454
+ function validateFields2(input, schemas = {}, stale = []) {
455
+ if (input === null || input === void 0) return {};
456
+ if (!plain(input)) fail2("fields must be an object");
457
+ if (JSON.stringify(input).length > 256 * 1024) fail2("fields config too large");
458
+ const out = {};
459
+ for (const [uid, entries] of Object.entries(input)) {
460
+ if (!plain(entries)) fail2(`Invalid entry for "${uid}"`);
461
+ for (const [name, entry] of Object.entries(entries)) {
462
+ if (!plain(entry)) fail2(`Invalid entry for "${uid}.${name}"`);
463
+ for (const [key, value] of Object.entries(entry)) {
464
+ if (!(key in FIELD_TEXT)) fail2(`Unknown field setting "${key}" of "${uid}.${name}"`);
465
+ if (!fieldText(value, FIELD_TEXT[key])) fail2(`Invalid ${key} of "${uid}.${name}": a string of 1 to ${FIELD_TEXT[key]} characters, or { "<locale>": string }`);
466
+ }
467
+ if (!schemas[uid]?.includes(name)) {
468
+ stale.push(`${uid}.${name}`);
469
+ continue;
470
+ }
471
+ ;
472
+ (out[uid] ||= {})[name] = structuredClone(entry);
473
+ }
474
+ }
475
+ return out;
476
+ }
477
+ var str = (max) => (value) => typeof value === "string" && value.trim() !== "" && value.length <= max;
478
+ var BLOCK_META = { label: str(80), typology: (value) => TYPOLOGIES2.includes(value), tags: validTags, keywords: str(500), image: (value) => safeUrl2(value) !== void 0 };
479
+ var localize = (holder, key, source, locale, text2) => {
480
+ holder[key] = { ...plain(holder[key]) ? holder[key] : { en: holder[key] ?? source }, [locale]: text2 };
481
+ };
482
+ function schemaMetadata2(schemas = {}, translations = null, notes = []) {
483
+ const blocks = {}, fields = {};
484
+ const own = (holder, where) => {
485
+ const value = holder?.pluginOptions?.blockscene;
486
+ if (value === void 0 || plain(value)) return value || {};
487
+ notes.push(`${where}: pluginOptions.blockscene must be an object`);
488
+ return {};
489
+ };
490
+ for (const [uid, schema] of Object.entries(schemas)) {
491
+ if (!uid.includes("::")) {
492
+ const block = {};
493
+ for (const [key, value] of Object.entries(own(schema, uid))) {
494
+ if (!Object.hasOwn(BLOCK_META, key)) notes.push(`${uid}: unknown key "${key}"`);
495
+ else if (!BLOCK_META[key](value)) notes.push(`${uid}: invalid ${key}`);
496
+ else block[key] = key === "tags" ? cleanTags(value) : value;
497
+ }
498
+ if (typeof schema?.info?.description === "string" && schema.info.description.trim()) block.description = schema.info.description;
499
+ if (Object.keys(block).length) blocks[uid] = block;
500
+ }
501
+ for (const [name, attr] of Object.entries(schema?.attributes || {})) {
502
+ const texts = {};
503
+ for (const [key, value] of Object.entries(own(attr, `${uid}.${name}`))) {
504
+ if (!Object.hasOwn(FIELD_TEXT, key)) notes.push(`${uid}.${name}: unknown key "${key}"`);
505
+ else if (!str(FIELD_TEXT[key])(value)) notes.push(`${uid}.${name}: ${key} must be a string of 1 to ${FIELD_TEXT[key]} characters`);
506
+ else texts[key] = value;
507
+ }
508
+ if (Object.keys(texts).length) (fields[uid] ||= {})[name] = texts;
509
+ }
510
+ }
511
+ if (translations != null && !plain(translations)) {
512
+ notes.push('translations must be { "<locale>": { "<key>": text } }');
513
+ translations = null;
514
+ }
515
+ const stale = [];
516
+ for (const [locale, entries] of Object.entries(translations || {})) {
517
+ if (!LOCALE.test(locale) || !plain(entries) || JSON.stringify(entries).length > 256 * 1024) {
518
+ notes.push(`translations "${locale}" ignored: expected a locale code with a flat { "<key>": text } map under 256 KB`);
519
+ continue;
520
+ }
521
+ for (const [key, text2] of Object.entries(entries)) {
522
+ const uid = Object.keys(schemas).find((uid2) => key === uid2 || key.startsWith(`${uid2}.`));
523
+ const [name, part = "label", extra] = uid ? key.slice(uid.length + 1).split(".") : [];
524
+ const block = uid && !uid.includes("::");
525
+ const target = block && key === uid ? [blocks[uid] ||= {}, "label", schemas[uid]?.info?.displayName || uid, 80] : block && key === `${uid}.description` ? [blocks[uid] ||= {}, "description", null, 300] : uid && Object.hasOwn(schemas[uid]?.attributes || {}, name) && Object.hasOwn(FIELD_TEXT, part) && extra === void 0 ? [null, part, null, FIELD_TEXT[part]] : null;
526
+ if (!target) {
527
+ stale.push(`${locale} "${key}"`);
528
+ continue;
529
+ }
530
+ const [holder, field, source, max] = target;
531
+ if (!str(max)(text2)) {
532
+ notes.push(`translations ${locale} "${key}": a string of 1 to ${max} characters`);
533
+ continue;
534
+ }
535
+ localize(holder || ((fields[uid] ||= {})[name] ||= {}), field, source, locale, text2);
536
+ }
537
+ }
538
+ if (stale.length) notes.push(`translation keys naming no block or field were skipped: ${stale.slice(0, 20).join(", ")}${stale.length > 20 ? ` and ${stale.length - 20} more` : ""}`);
539
+ return { blocks, fields };
540
+ }
541
+ var VARIANT = { id: /^[a-z0-9][a-z0-9_-]{0,39}$/, perComponent: 12, bytes: 16 * 1024, total: 256 * 1024, items: 100 };
542
+ var text = (value) => typeof value === "string";
543
+ var finite = (value) => typeof value === "number" && Number.isFinite(value);
544
+ var SCALARS = {
545
+ string: text,
546
+ text,
547
+ richtext: text,
548
+ email: text,
549
+ uid: text,
550
+ date: text,
551
+ datetime: text,
552
+ time: text,
553
+ timestamp: text,
554
+ integer: Number.isInteger,
555
+ biginteger: (value) => Number.isInteger(value) || text(value) && /^-?\d{1,19}$/.test(value),
556
+ float: finite,
557
+ decimal: finite,
558
+ boolean: (value) => typeof value === "boolean",
559
+ json: () => true,
560
+ customField: () => true,
561
+ blocks: Array.isArray,
562
+ enumeration: (value, attr) => (attr.enum || []).includes(value)
563
+ };
564
+ function variantValues(values, schema, schemas, path, skipped) {
565
+ if (!plain(values)) throw new Error(`${path} must be an object`);
566
+ const out = {};
567
+ for (const [name, value] of Object.entries(values)) {
568
+ if (name === "id" || name === "__component") continue;
569
+ const attr = schema.attributes?.[name], at = `${path}.${name}`;
570
+ if (!attr) throw new Error(`${at} is not an attribute of the component`);
571
+ if (attr.type === "media" || attr.type === "relation") {
572
+ skipped.push(at);
573
+ continue;
574
+ }
575
+ if (attr.type === "component") {
576
+ const nested = schemas[attr.component], max = Math.min(attr.max ?? Infinity, VARIANT.items);
577
+ if (!nested) throw new Error(`${at}: unknown component "${attr.component}"`);
578
+ if (!attr.repeatable) out[name] = value === null ? null : variantValues(value, nested, schemas, at, skipped);
579
+ else if (!Array.isArray(value) || value.length > max) throw new Error(`${at} must be a list of at most ${max} items`);
580
+ else out[name] = value.map((item, index) => variantValues(item, nested, schemas, `${at}[${index}]`, skipped));
581
+ } else if (value === null || SCALARS[attr.type]?.(value, attr)) out[name] = structuredClone(value);
582
+ else throw new Error(`${at}: ${SCALARS[attr.type] ? `not a valid ${attr.type}` : `${attr.type} values are not supported`}`);
583
+ }
584
+ return out;
585
+ }
586
+ function validateVariants2(config, schemas = {}, notes = []) {
587
+ const out = {};
588
+ let total = 0;
589
+ for (const [uid, entry] of Object.entries(plain(config) ? config : {})) {
590
+ if (!plain(entry) || entry.variants === void 0) continue;
591
+ if (!schemas[uid]) {
592
+ notes.push(`${uid}: unknown component`);
593
+ continue;
594
+ }
595
+ if (!Array.isArray(entry.variants) || entry.variants.length > VARIANT.perComponent) {
596
+ notes.push(`${uid}: variants must be a list of at most ${VARIANT.perComponent}`);
597
+ continue;
598
+ }
599
+ const ids = /* @__PURE__ */ new Set();
600
+ entry.variants.forEach((variant, index) => {
601
+ const name = `${uid} variant "${variant?.id ?? index}"`;
602
+ try {
603
+ if (!plain(variant) || Object.keys(variant).some((key) => !["id", "label", "values"].includes(key))) throw new Error("expected { id, label, values }");
604
+ if (!text(variant.id) || !VARIANT.id.test(variant.id) || ids.has(variant.id)) throw new Error('id must be 1 to 40 lowercase letters, digits, "-" or "_", unique per component');
605
+ if (!fieldText(variant.label, 60)) throw new Error('label must be a string of 1 to 60 characters, or { "<locale>": string }');
606
+ const skipped = [];
607
+ const values = variantValues(variant.values ?? {}, schemas[uid], schemas, "values", skipped);
608
+ const size = JSON.stringify(values).length;
609
+ if (size > VARIANT.bytes) throw new Error(`values over ${VARIANT.bytes / 1024} KB`);
610
+ if (total + size > VARIANT.total) throw new Error(`all variants together over ${VARIANT.total / 1024} KB`);
611
+ if (skipped.length) notes.push(`${name}: media and relation values are not inserted (${skipped.slice(0, 5).join(", ")}${skipped.length > 5 ? ", ..." : ""})`);
612
+ ids.add(variant.id);
613
+ total += size;
614
+ (out[uid] ||= []).push({ id: variant.id, label: structuredClone(variant.label), values });
615
+ } catch (error) {
616
+ notes.push(`${name} ignored: ${error.message}`);
617
+ }
618
+ });
619
+ }
620
+ return out;
621
+ }
622
+ var PREFS = { starred: 200, recent: 20 };
623
+ function validatePrefs2(input, componentUids2) {
624
+ if (!input || typeof input !== "object" || Array.isArray(input)) fail2("Preferences must be an object");
625
+ const out = { starred: [], recent: [] };
626
+ for (const [key, value] of Object.entries(input)) {
627
+ if (!(key in PREFS)) fail2(`Unknown preference "${key}"`);
628
+ if (!Array.isArray(value) || value.length > PREFS[key] || !value.every((uid) => typeof uid === "string" && componentUids2.includes(uid))) fail2(`Invalid value for "${key}"`);
629
+ out[key] = [...new Set(value)];
630
+ }
631
+ return out;
632
+ }
633
+ var mergePrefs2 = (saved, componentUids2) => Object.fromEntries(Object.entries(PREFS).map(([key, max]) => [key, Array.isArray(saved?.[key]) ? [...new Set(saved[key].filter((uid) => componentUids2.includes(uid)))].slice(0, max) : []]));
634
+ module2.exports = { PLUGIN: PLUGIN2, HIDDEN_MODES, TEMPLATES: TEMPLATES2, TYPOLOGIES: TYPOLOGIES2, guessTypology, facetsOf, validatePrefs: validatePrefs2, mergePrefs: mergePrefs2, ICONS, DEFAULTS: DEFAULTS2, catalog: catalog2, validateSettings: validateSettings2, validateFields: validateFields2, validateVariants: validateVariants2, schemaMetadata: schemaMetadata2, mergeSaved: mergeSaved2, layer: layer2, overrides: overrides2, safeUrl: safeUrl2, fail: fail2 };
635
+ }
636
+ });
637
+
638
+ // server/hidden.js
639
+ var require_hidden = __commonJS({
640
+ "server/hidden.js"(exports2, module2) {
641
+ "use strict";
642
+ var NAME = /^[a-zA-Z][a-zA-Z0-9_]{0,39}$/;
643
+ var DEFAULT_NAME = "bsHidden";
644
+ var hiddenName2 = (value) => value === void 0 ? DEFAULT_NAME : value === false ? false : typeof value === "string" && NAME.test(value) ? value : null;
645
+ var zoneComponents = (contentTypes) => [...new Set(Object.values(contentTypes || {}).flatMap((schema) => Object.values(schema?.attributes || {}).filter((attr) => attr?.type === "dynamiczone").flatMap((attr) => attr.components || [])))];
646
+ function injectHidden2(components, contentTypes, name) {
647
+ const added = [], skipped = [];
648
+ for (const uid of zoneComponents(contentTypes)) {
649
+ const schema = components?.[uid];
650
+ if (!schema) continue;
651
+ schema.attributes ||= {};
652
+ const current = schema.attributes[name];
653
+ if (current && current.type !== "boolean") {
654
+ skipped.push(uid);
655
+ continue;
656
+ }
657
+ if (!current) schema.attributes[name] = { type: "boolean", default: false, configurable: false };
658
+ added.push(uid);
659
+ }
660
+ return { added, skipped };
661
+ }
662
+ function hideFromBuilder2(services, uids, name) {
663
+ const has = new Set(uids);
664
+ const drop = (attributes) => Array.isArray(attributes) ? attributes.filter((attr) => attr?.name !== name) : attributes && typeof attributes === "object" ? Object.fromEntries(Object.entries(attributes).filter(([key]) => key !== name)) : attributes;
665
+ const extend = (uid, wrap) => {
666
+ if (services?.get?.(uid)) services.extend(uid, wrap);
667
+ };
668
+ extend("plugin::content-type-builder.components", (service) => ({ ...service, formatComponent(component, ...rest) {
669
+ const out = service.formatComponent(component, ...rest);
670
+ return has.has(component?.uid) && out?.schema ? { ...out, schema: { ...out.schema, attributes: drop(out.schema.attributes) } } : out;
671
+ } }));
672
+ extend("plugin::content-type-builder.schema", (service) => ({ ...service, async getSchema(...args) {
673
+ const out = await service.getSchema(...args);
674
+ for (const uid of has) if (out?.components?.[uid]) out.components[uid] = { ...out.components[uid], attributes: drop(out.components[uid].attributes) };
675
+ return out;
676
+ } }));
677
+ }
678
+ function stripHidden(data, schema, schemaOf, name, depth = 0) {
679
+ if (!data || typeof data !== "object" || !schema || depth > 20) return data;
680
+ if (Array.isArray(data)) {
681
+ data.forEach((item) => stripHidden(item, schema, schemaOf, name, depth));
682
+ return data;
683
+ }
684
+ const walk = (value, target) => Array.isArray(value) ? value.forEach((item) => stripHidden(item, target, schemaOf, name, depth + 1)) : stripHidden(value, target, schemaOf, name, depth + 1);
685
+ for (const [key, attr] of Object.entries(schema.attributes || {})) {
686
+ const value = data[key];
687
+ if (value == null || typeof value !== "object") continue;
688
+ if (attr?.type === "dynamiczone" && Array.isArray(value)) {
689
+ data[key] = value.filter((row) => !(row && row[name] === true));
690
+ for (const row of data[key]) stripHidden(row, schemaOf(row?.__component), schemaOf, name, depth + 1);
691
+ } else if (attr?.type === "component") walk(value, schemaOf(attr.component));
692
+ else if (attr?.type === "relation" && attr.target) walk(value, schemaOf(attr.target));
693
+ }
694
+ return data;
695
+ }
696
+ var contentApi = (strapi) => {
697
+ try {
698
+ return strapi.requestContext?.get?.()?.state?.route?.info?.type === "content-api";
699
+ } catch {
700
+ return false;
701
+ }
702
+ };
703
+ var READS = ["findMany", "findOne", "findFirst"];
704
+ function registerHiddenStrip2(strapi, name, plugin) {
705
+ if (!name) return;
706
+ const schemaOf = (uid) => uid && (strapi.getModel?.(uid) || strapi.components?.[uid] || strapi.contentTypes?.[uid]);
707
+ const stripping = async () => {
708
+ try {
709
+ return (await plugin.service("settings").get()).editor.hiddenBlocks === "strip";
710
+ } catch {
711
+ return true;
712
+ }
713
+ };
714
+ const apply = async (uid, result) => result && contentApi(strapi) && await stripping() ? stripHidden(result, schemaOf(uid), schemaOf, name) : result;
715
+ if (strapi.documents?.use) {
716
+ strapi.documents.use(async (ctx, next) => {
717
+ const result = await next();
718
+ return READS.includes(ctx.action) ? apply(ctx.uid, result) : result;
719
+ });
720
+ return;
721
+ }
722
+ strapi.entityService?.decorate?.((service) => ({
723
+ async findMany(uid, params) {
724
+ return apply(uid, await service.findMany(uid, params));
725
+ },
726
+ async findOne(uid, id, params) {
727
+ return apply(uid, await service.findOne(uid, id, params));
728
+ },
729
+ async findPage(uid, params) {
730
+ const page = await service.findPage(uid, params);
731
+ if (page?.results) await apply(uid, page.results);
732
+ return page;
733
+ }
734
+ }));
735
+ }
736
+ module2.exports = { DEFAULT_NAME, hiddenName: hiddenName2, zoneComponents, injectHidden: injectHidden2, hideFromBuilder: hideFromBuilder2, stripHidden, registerHiddenStrip: registerHiddenStrip2 };
737
+ }
738
+ });
739
+
740
+ // server/diff.js
741
+ var require_diff = __commonJS({
742
+ "server/diff.js"(exports2, module2) {
743
+ "use strict";
744
+ var IGNORED = ["id", "documentId", "locale", "localizations", "createdAt", "updatedAt", "publishedAt", "firstPublishedAt", "createdBy", "updatedBy", "strapi_stage", "strapi_assignee", "__temp_key__", "__pivot"];
745
+ var morph = (attr) => String(attr?.relation || "").toLowerCase().includes("morph");
746
+ var kept = (name, attr) => attr && !IGNORED.includes(name) && attr.type !== "password" && !(attr.type === "relation" && (morph(attr) || attr.visible === false));
747
+ var empty = (value) => value === null || value === void 0 || value === "";
748
+ function snapshotPopulate(uid, schemaOf, stack = []) {
749
+ const schema = schemaOf(uid);
750
+ if (!schema || stack.includes(uid)) return {};
751
+ const scalars = (component) => Object.entries(schemaOf(component)?.attributes || {}).filter(([name, attr]) => kept(name, attr) && !["relation", "media", "component", "dynamiczone"].includes(attr.type)).map(([name]) => name);
752
+ const nested = (component) => ({ select: scalars(component).length ? scalars(component) : ["id"], populate: snapshotPopulate(component, schemaOf, [...stack, uid]) });
753
+ const out = {};
754
+ for (const [name, attr] of Object.entries(schema.attributes || {})) {
755
+ if (!kept(name, attr)) continue;
756
+ if (attr.type === "relation") out[name] = { select: ["documentId", "locale"] };
757
+ else if (attr.type === "media") out[name] = { select: ["id"] };
758
+ else if (attr.type === "component") out[name] = nested(attr.component);
759
+ else if (attr.type === "dynamiczone") out[name] = { on: Object.fromEntries((attr.components || []).map((component) => [component, nested(component)])) };
760
+ }
761
+ return out;
762
+ }
763
+ function canonical(data, schema, schemaOf, { relations = true } = {}, depth = 0) {
764
+ const out = {};
765
+ if (!data || typeof data !== "object" || depth > 20) return out;
766
+ const idOf = (file) => file && typeof file === "object" ? file.id : file;
767
+ const ref = (item) => item && typeof item === "object" && item.documentId ? { documentId: item.documentId, ...item.locale && { locale: item.locale } } : null;
768
+ for (const [name, attr] of Object.entries(schema?.attributes || {})) {
769
+ const value = data[name];
770
+ if (!kept(name, attr) || empty(value)) continue;
771
+ if (attr.type === "relation") {
772
+ if (!relations) continue;
773
+ const refs = (Array.isArray(value) ? value : [value]).map(ref).filter(Boolean);
774
+ if (refs.length) out[name] = Array.isArray(value) ? refs : refs[0];
775
+ } else if (attr.type === "media") {
776
+ const ids = (Array.isArray(value) ? value : [value]).map(idOf).filter((id) => !empty(id));
777
+ if (ids.length) out[name] = attr.multiple ? ids : ids[0];
778
+ } else if (attr.type === "component") {
779
+ const child = schemaOf(attr.component);
780
+ if (attr.repeatable) {
781
+ if (Array.isArray(value) && value.length) out[name] = value.map((item) => canonical(item, child, schemaOf, { relations }, depth + 1));
782
+ } else out[name] = canonical(value, child, schemaOf, { relations }, depth + 1);
783
+ } else if (attr.type === "dynamiczone") {
784
+ if (Array.isArray(value) && value.length) out[name] = value.filter((row) => row && typeof row.__component === "string").map((row) => ({ __component: row.__component, ...canonical(row, schemaOf(row.__component), schemaOf, { relations }, depth + 1) }));
785
+ } else out[name] = value;
786
+ }
787
+ return out;
788
+ }
789
+ var stable = (value) => JSON.stringify(value, (_, v) => v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v);
790
+ var same = (a, b) => stable(a ?? null) === stable(b ?? null);
791
+ function diffRows(before = [], after = []) {
792
+ const a = before.map(stable), b = after.map(stable);
793
+ const n = a.length, m = b.length;
794
+ if (n * m > 25e4) return after.map((row, to) => ({ op: a[to] === b[to] ? "same" : "changed", from: to < n ? to : void 0, to, uid: row.__component }));
795
+ const lcs = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
796
+ for (let i2 = n - 1; i2 >= 0; i2--) for (let j2 = m - 1; j2 >= 0; j2--) lcs[i2][j2] = a[i2] === b[j2] ? lcs[i2 + 1][j2 + 1] + 1 : Math.max(lcs[i2 + 1][j2], lcs[i2][j2 + 1]);
797
+ const out = [];
798
+ const gap = (fromRows2, toRows2) => {
799
+ const removed = [...fromRows2];
800
+ for (const to of toRows2) {
801
+ const k = removed.findIndex((from) => before[from].__component === after[to].__component);
802
+ if (k === -1) out.push({ op: "added", to, uid: after[to].__component });
803
+ else out.push({ op: "changed", from: removed.splice(k, 1)[0], to, uid: after[to].__component });
804
+ }
805
+ for (const from of removed) out.push({ op: "removed", from, uid: before[from].__component });
806
+ };
807
+ let i = 0, j = 0, fromRows = [], toRows = [];
808
+ while (i < n || j < m) {
809
+ if (i < n && j < m && a[i] === b[j]) {
810
+ gap(fromRows, toRows);
811
+ fromRows = [];
812
+ toRows = [];
813
+ out.push({ op: "same", from: i, to: j, uid: after[j].__component });
814
+ i++;
815
+ j++;
816
+ } else if (j < m && (i >= n || lcs[i][j + 1] >= lcs[i + 1][j])) toRows.push(j++);
817
+ else fromRows.push(i++);
818
+ }
819
+ gap(fromRows, toRows);
218
820
  return out;
219
821
  }
220
- module2.exports = { PLUGIN: PLUGIN2, TEMPLATES: TEMPLATES2, DEFAULTS: DEFAULTS2, catalog: catalog2, validateSettings: validateSettings2, mergeSaved: mergeSaved2, safeUrl: safeUrl2, fail: fail2 };
822
+ function summarize(before, after, schema) {
823
+ const zones = Object.entries(schema?.attributes || {}).filter(([, attr]) => attr?.type === "dynamiczone").map(([name]) => name);
824
+ const blocks = { added: 0, removed: 0, changed: 0 };
825
+ if (!before) return { initial: true, fields: [], blocks };
826
+ const names = [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after || {})])];
827
+ const fields = names.filter((name) => !zones.includes(name) && !same(before[name], after?.[name])).sort();
828
+ for (const name of zones) for (const { op } of diffRows(before[name], after?.[name])) if (op !== "same") blocks[op]++;
829
+ return { fields, blocks };
830
+ }
831
+ module2.exports = { IGNORED, kept, snapshotPopulate, canonical, stable, same, diffRows, summarize };
832
+ }
833
+ });
834
+
835
+ // server/trash.js
836
+ var require_trash = __commonJS({
837
+ "server/trash.js"(exports2, module2) {
838
+ "use strict";
839
+ var { AsyncLocalStorage } = require("node:async_hooks");
840
+ var { PLUGIN: PLUGIN2 } = require_settings();
841
+ var { kept, canonical, stable } = require_diff();
842
+ var history = () => require_history();
843
+ var TRASH_UID = `plugin::${PLUGIN2}.trash`;
844
+ var STATUSES = ["trashed", "restored"];
845
+ var DAY = 24 * 60 * 60 * 1e3;
846
+ var BATCH = 500;
847
+ var restoring = new AsyncLocalStorage();
848
+ var trashContentType2 = { schema: {
849
+ kind: "collectionType",
850
+ collectionName: "blockscene_trash",
851
+ info: { singularName: "trash", pluralName: "trashes", displayName: "Blockscene trash" },
852
+ options: { draftAndPublish: false },
853
+ pluginOptions: { "content-manager": { visible: false }, "content-type-builder": { visible: false }, i18n: { localized: false } },
854
+ attributes: {
855
+ contentType: { type: "string", required: true },
856
+ relatedDocumentId: { type: "string", required: true },
857
+ // The document's main field (Content Manager setting) at delete time, for the list and the search.
858
+ title: { type: "string" },
859
+ // The locales the delete removed ([null] for a type without i18n).
860
+ locales: { type: "json" },
861
+ // [{ locale, status: 'draft' | 'published' | null (no Draft & Publish), snapshot }]: canonical snapshots (server/diff.js).
862
+ entries: { type: "json" },
863
+ // Links other documents' and blocks' unidirectional relations had to the deleted rows (see `incomingRows`).
864
+ incoming: { type: "json" },
865
+ actor: { type: "string", required: true },
866
+ actorName: { type: "string" },
867
+ deletedAt: { type: "datetime", required: true },
868
+ // deletedAt + trash retention at delete time; the nightly purge deletes the row after it.
869
+ expiresAt: { type: "datetime", required: true },
870
+ status: { type: "enumeration", enum: STATUSES, required: true, default: "trashed" },
871
+ restoredAs: { type: "string" },
872
+ restoredAt: { type: "datetime" },
873
+ size: { type: "integer" }
874
+ },
875
+ indexes: [{ name: "blockscene_trash_list", columns: ["status", "content_type", "deleted_at"] }, { name: "blockscene_trash_expiry", columns: ["expires_at"] }]
876
+ } };
877
+ var expiresAt = (deletedAt, days) => new Date(new Date(deletedAt).getTime() + days * DAY);
878
+ var isObject = (value) => value && typeof value === "object" && !Array.isArray(value);
879
+ var blank = (value) => value === null || value === void 0 || value === "" || Array.isArray(value) && !value.length;
880
+ var toMany = (attr) => /ToMany$|^manyWay$/.test(String(attr?.relation || ""));
881
+ var toOne = (attr) => ["oneToOne", "manyToOne"].includes(attr?.relation);
882
+ var uniqueFields = (schema) => Object.entries(schema?.attributes || {}).filter(([name, attr]) => kept(name, attr) && (attr.unique === true || attr.type === "uid")).map(([name]) => name);
883
+ function chooseEntries(entries) {
884
+ const chosen = /* @__PURE__ */ new Map();
885
+ for (const entry of Array.isArray(entries) ? entries : []) {
886
+ const locale = entry?.locale ?? null, current = chosen.get(locale);
887
+ if (!current || current.status === "published" && entry.status !== "published") chosen.set(locale, entry);
888
+ }
889
+ return chosen;
890
+ }
891
+ function restorePayload(snapshot, schema, schemaOf, { media = /* @__PURE__ */ new Set(), relation = () => false } = {}) {
892
+ const report = { removed: [], media: 0, relations: 0, blocks: 0 };
893
+ const ref = (item) => ({ documentId: item.documentId, ...item.locale && { locale: item.locale } });
894
+ const build = (data, schema2, top, depth) => {
895
+ const out = {};
896
+ if (!isObject(data) || depth > 20) return out;
897
+ for (const [name, value] of Object.entries(data)) {
898
+ if (name === "__component") continue;
899
+ const attr = schema2?.attributes?.[name];
900
+ const drop = () => {
901
+ if (top) report.removed.push(name);
902
+ };
903
+ if (!kept(name, attr)) {
904
+ drop();
905
+ continue;
906
+ }
907
+ const list = Array.isArray(value) ? value : value == null ? [] : [value];
908
+ if (attr.type === "relation") {
909
+ const refs = list.filter((item) => isObject(item) && typeof item.documentId === "string");
910
+ const found = refs.filter((item) => relation(attr.target, item));
911
+ report.relations += refs.length - found.length;
912
+ out[name] = toMany(attr) ? found.map(ref) : found[0] ? ref(found[0]) : null;
913
+ } else if (attr.type === "media") {
914
+ const ids = list.filter(Number.isInteger), found = ids.filter((id) => media.has(id));
915
+ report.media += ids.length - found.length;
916
+ out[name] = attr.multiple ? found : found[0] ?? null;
917
+ } else if (attr.type === "component") {
918
+ const child = schemaOf(attr.component);
919
+ if (!child) {
920
+ drop();
921
+ continue;
922
+ }
923
+ out[name] = attr.repeatable ? list.filter(isObject).map((item) => build(item, child, false, depth + 1)) : isObject(value) ? build(value, child, false, depth + 1) : null;
924
+ } else if (attr.type === "dynamiczone") {
925
+ const rows = list.filter((row) => isObject(row) && typeof row.__component === "string");
926
+ const allowed = rows.filter((row) => (attr.components || []).includes(row.__component) && schemaOf(row.__component));
927
+ report.blocks += rows.length - allowed.length;
928
+ out[name] = allowed.map((row) => ({ __component: row.__component, ...build(row, schemaOf(row.__component), false, depth + 1) }));
929
+ } else if (attr.type === "enumeration" && !(attr.enum || []).includes(value)) drop();
930
+ else out[name] = value;
931
+ }
932
+ return out;
933
+ };
934
+ return { data: build(snapshot, schema, true, 0), report };
935
+ }
936
+ function planRestore(entries, { schema, schemaOf, locales = null, defaultLocale = null, existing = null, singleTaken = false, taken = () => false, media, relation }) {
937
+ const blocking = [], warnings = [], steps = [];
938
+ const published = (Array.isArray(entries) ? entries : []).filter((entry) => entry?.status === "published").map((entry) => entry.locale ?? null);
939
+ if (published.length) warnings.push({ code: "published", locales: published });
940
+ if (singleTaken && !existing) blocking.push({ code: "singleExists" });
941
+ for (const [locale, entry] of chooseEntries(entries)) {
942
+ if (locales && !locales.includes(locale)) {
943
+ warnings.push({ code: "localeRemoved", locale });
944
+ continue;
945
+ }
946
+ if (existing?.includes(locale)) {
947
+ blocking.push({ code: "localeExists", locale });
948
+ continue;
949
+ }
950
+ const { data, report } = restorePayload(entry.snapshot, schema, schemaOf, { media, relation });
951
+ for (const field of uniqueFields(schema)) if (!blank(data[field]) && taken(field, locale, data[field])) blocking.push({ code: "unique", locale, field, value: String(data[field]).slice(0, 100) });
952
+ const required = Object.entries(schema?.attributes || {}).filter(([name, attr]) => attr?.required && kept(name, attr) && blank(data[name])).map(([name]) => name);
953
+ if (required.length) warnings.push({ code: "required", locale, fields: required });
954
+ if (report.removed.length) warnings.push({ code: "fieldsRemoved", locale, fields: report.removed });
955
+ for (const code of ["media", "relations", "blocks"]) if (report[code]) warnings.push({ code, locale, count: report[code] });
956
+ steps.push({ locale, data });
957
+ }
958
+ if (!steps.length && !blocking.length) blocking.push({ code: "nothing" });
959
+ steps.sort((a, b) => (b.locale === defaultLocale) - (a.locale === defaultLocale));
960
+ return { blocking, warnings, steps };
961
+ }
962
+ var incomingSources = (uid, models) => models.flatMap((model) => Object.entries(model.attributes || {}).filter(([, attr]) => attr?.type === "relation" && attr.target === uid && !attr.inversedBy && !attr.mappedBy && attr.joinTable).map(([field, attr]) => ({ owner: model.uid, kind: model.kind, field, joinTable: attr.joinTable, single: toOne(attr) })));
963
+ function incomingRows(source, links, deleted, owners = /* @__PURE__ */ new Map()) {
964
+ const { joinColumn, inverseJoinColumn, orderColumnName } = source.joinTable;
965
+ return links.filter((link) => deleted.has(link[inverseJoinColumn.name]) && !(source.kind === "contentType" && source.owner === source.target && deleted.has(link[joinColumn.name]))).map((link) => {
966
+ const target = deleted.get(link[inverseJoinColumn.name]), owner = owners.get(link[joinColumn.name]);
967
+ return {
968
+ owner: source.owner,
969
+ kind: source.kind,
970
+ field: source.field,
971
+ ownerId: link[joinColumn.name],
972
+ ...source.kind === "contentType" && { ownerDocumentId: owner?.documentId ?? null, ownerLocale: owner?.locale ?? null },
973
+ locale: target.locale ?? null,
974
+ published: Boolean(target.published),
975
+ order: orderColumnName ? link[orderColumnName] ?? null : null
976
+ };
977
+ });
978
+ }
979
+ function previewOf(snapshot, schema, schemaOf) {
980
+ const fields = [], blocks = [];
981
+ const text = (value) => {
982
+ const s = typeof value === "string" ? value : stable(value);
983
+ return s.length > 200 ? `${s.slice(0, 199)}\u2026` : s;
984
+ };
985
+ for (const [name, value] of Object.entries(isObject(snapshot) ? snapshot : {})) {
986
+ const attr = schema?.attributes?.[name];
987
+ if (attr?.type === "dynamiczone") {
988
+ for (const row of Array.isArray(value) ? value : []) blocks.push({ zone: name, uid: row?.__component, name: schemaOf(row?.__component)?.info?.displayName || row?.__component });
989
+ continue;
990
+ }
991
+ const count = Array.isArray(value) ? value.length : 1;
992
+ fields.push({ name, type: attr?.type || "removed", ...["relation", "media", "component"].includes(attr?.type) ? { count } : { value: text(value) } });
993
+ }
994
+ return { fields, blocks };
995
+ }
996
+ function trashService2({ strapi }) {
997
+ const events = () => strapi.plugin(PLUGIN2).service("history");
998
+ const rows = () => strapi.db.query(TRASH_UID);
999
+ const schemaOf = (uid) => uid && (strapi.getModel?.(uid) || strapi.components?.[uid] || strapi.contentTypes?.[uid]);
1000
+ const localized = (uid) => Boolean(schemaOf(uid)?.pluginOptions?.i18n?.localized);
1001
+ const draftAndPublish = (uid) => schemaOf(uid)?.options?.draftAndPublish === true;
1002
+ const models = () => [...Object.values(strapi.contentTypes || {}).map((model) => ({ uid: model.uid, kind: "contentType" })), ...Object.values(strapi.components || {}).map((model) => ({ uid: model.uid, kind: "component" }))].map((model) => ({ ...model, attributes: strapi.db.metadata.get(model.uid)?.attributes })).filter((model) => model.attributes);
1003
+ const table = (trx, name) => strapi.db.getConnection(name).transacting(trx);
1004
+ const lookups = async (uid, snapshots) => {
1005
+ const ids = /* @__PURE__ */ new Set(), refs = [];
1006
+ for (const snapshot of snapshots) {
1007
+ const found = history().refsOf(snapshot, schemaOf(uid), schemaOf);
1008
+ found.media.forEach((id) => ids.add(id));
1009
+ refs.push(...found.relations);
1010
+ }
1011
+ const files = ids.size ? await strapi.db.query("plugin::upload.file").findMany({ select: ["id"], where: { id: { $in: [...ids] } } }) : [];
1012
+ const present = /* @__PURE__ */ new Set();
1013
+ for (const target of [...new Set(refs.map((ref) => ref.target))]) {
1014
+ if (!strapi.contentTypes?.[target]) continue;
1015
+ const found = await strapi.db.query(target).findMany({ select: ["documentId", "locale"], where: {
1016
+ documentId: { $in: [...new Set(refs.filter((ref) => ref.target === target).map((ref) => ref.documentId))] },
1017
+ ...draftAndPublish(target) && { publishedAt: { $null: true } }
1018
+ } });
1019
+ for (const row of found) {
1020
+ present.add(`${target}|${row.documentId}|${row.locale || ""}`);
1021
+ present.add(`${target}|${row.documentId}|*`);
1022
+ }
1023
+ }
1024
+ return { media: new Set(files.map((file) => file.id)), relation: (target, ref) => present.has(`${target}|${ref.documentId}|${localized(target) && ref.locale ? ref.locale : "*"}`) };
1025
+ };
1026
+ const resolveIncoming = async (uid, incoming, locales, trx) => {
1027
+ const out = { links: [], gone: 0, published: 0, replaced: 0 };
1028
+ for (const link of Array.isArray(incoming) ? incoming : []) {
1029
+ if (!locales.includes(link.locale)) continue;
1030
+ if (link.published) {
1031
+ out.published++;
1032
+ continue;
1033
+ }
1034
+ const attr = strapi.db.metadata.get(link.owner)?.attributes?.[link.field];
1035
+ if (!attr?.joinTable || attr.target !== uid) {
1036
+ out.gone++;
1037
+ continue;
1038
+ }
1039
+ let ownerId = null;
1040
+ if (link.kind === "component") ownerId = (await strapi.db.query(link.owner).findOne({ select: ["id"], where: { id: link.ownerId } }))?.id ?? null;
1041
+ else if (strapi.contentTypes?.[link.owner] && link.ownerDocumentId) ownerId = (await strapi.db.query(link.owner).findOne({ select: ["id"], where: {
1042
+ documentId: link.ownerDocumentId,
1043
+ ...localized(link.owner) && { locale: link.ownerLocale },
1044
+ ...draftAndPublish(link.owner) && { publishedAt: { $null: true } }
1045
+ } }))?.id ?? null;
1046
+ if (!ownerId) {
1047
+ out.gone++;
1048
+ continue;
1049
+ }
1050
+ const { joinTable } = attr;
1051
+ if (toOne(attr) && await table(trx, joinTable.name).where(joinTable.joinColumn.name, ownerId).first()) {
1052
+ out.replaced++;
1053
+ continue;
1054
+ }
1055
+ out.links.push({ ...link, ownerRowId: ownerId, joinTable });
1056
+ }
1057
+ return out;
1058
+ };
1059
+ const self = {
1060
+ TRASH_UID,
1061
+ // Before the delete, in its transaction: the links other documents and blocks have to the rows about to be deleted.
1062
+ async incoming(uid, deleted) {
1063
+ if (!deleted.size) return [];
1064
+ return strapi.db.transaction(async ({ trx }) => {
1065
+ const out = [];
1066
+ for (const source of incomingSources(uid, models())) {
1067
+ const links = await table(trx, source.joinTable.name).select("*").whereIn(source.joinTable.inverseJoinColumn.name, [...deleted.keys()]);
1068
+ if (!links.length) continue;
1069
+ const owners = source.kind === "contentType" && strapi.contentTypes?.[source.owner] ? new Map((await strapi.db.query(source.owner).findMany({
1070
+ select: ["id", "documentId", "locale"],
1071
+ where: { id: { $in: [...new Set(links.map((link) => link[source.joinTable.joinColumn.name]))] } }
1072
+ })).map((row) => [row.id, row])) : /* @__PURE__ */ new Map();
1073
+ out.push(...incomingRows({ ...source, target: uid }, links, deleted, owners));
1074
+ }
1075
+ return out;
1076
+ });
1077
+ },
1078
+ // After the delete, in its transaction: the trash row. drafts/published: the stored rows read before the delete.
1079
+ async record({ uid, documentId, locales, drafts, published, incoming, actor, days }) {
1080
+ const dp = draftAndPublish(uid);
1081
+ const entries = [...drafts.map((row) => [row, dp ? "draft" : null]), ...published.map((row) => [row, "published"])].map(([row, status]) => ({ locale: row.locale ?? null, status, snapshot: canonical(row, schemaOf(uid), schemaOf) }));
1082
+ const main = await events().mainField(uid);
1083
+ const first = chooseEntries(entries);
1084
+ const source = first.get(await events().scope(uid).then((list) => list?.[0] ?? null).catch(() => null)) || [...first.values()][0];
1085
+ const title = main && source?.snapshot?.[main] != null ? String(source.snapshot[main]).slice(0, 255) : null;
1086
+ const deletedAt = /* @__PURE__ */ new Date();
1087
+ return rows().create({ data: {
1088
+ contentType: uid,
1089
+ relatedDocumentId: documentId,
1090
+ title,
1091
+ locales: locales || [...new Set(entries.map((entry) => entry.locale))],
1092
+ entries,
1093
+ incoming,
1094
+ ...actor,
1095
+ deletedAt,
1096
+ expiresAt: expiresAt(deletedAt, days),
1097
+ status: "trashed",
1098
+ size: Buffer.byteLength(stable({ entries, incoming }))
1099
+ } });
1100
+ },
1101
+ // One page of trash rows, without their snapshots. `types`: the content types the user may read.
1102
+ async list({ contentType, status = "trashed", page = 1, pageSize = 20, types }) {
1103
+ const where = { status, contentType: contentType ? contentType : { $in: types } };
1104
+ if (contentType && !types.includes(contentType)) return { results: [], pagination: { page, pageSize, total: 0, pageCount: 0 } };
1105
+ const [results, total] = await Promise.all([
1106
+ rows().findMany({
1107
+ select: ["id", "contentType", "relatedDocumentId", "title", "locales", "actor", "actorName", "deletedAt", "expiresAt", "status", "restoredAs", "restoredAt"],
1108
+ where,
1109
+ orderBy: [{ deletedAt: "desc" }, { id: "desc" }],
1110
+ offset: (page - 1) * pageSize,
1111
+ limit: pageSize
1112
+ }),
1113
+ rows().count({ where })
1114
+ ]);
1115
+ return { results, pagination: { page, pageSize, total, pageCount: Math.ceil(total / pageSize) } };
1116
+ },
1117
+ async find(id) {
1118
+ return rows().findOne({ where: { id } });
1119
+ },
1120
+ // One row for the preview: fields and blocks of each entry, and how many links it held.
1121
+ preview(row) {
1122
+ const schema = schemaOf(row.contentType);
1123
+ const { entries, incoming, ...meta } = row;
1124
+ return {
1125
+ ...meta,
1126
+ incoming: (incoming || []).length,
1127
+ entries: (entries || []).map((entry) => ({ locale: entry.locale ?? null, status: entry.status ?? null, ...previewOf(entry.snapshot, schema, schemaOf) }))
1128
+ };
1129
+ },
1130
+ // The pre-check: every lookup a restore needs, then planRestore. Read-only; the restore runs it again in its transaction.
1131
+ async plan(row) {
1132
+ const uid = row.contentType, schema = schemaOf(uid);
1133
+ if (!schema || !strapi.contentTypes?.[uid]) return { blocking: [{ code: "typeGone" }], warnings: [], steps: [], incoming: { links: [], gone: 0, published: 0, replaced: 0 } };
1134
+ const i18n = localized(uid);
1135
+ const locales = i18n ? (await strapi.plugin("i18n").service("locales").find()).map((locale) => locale.code) : null;
1136
+ const defaultLocale = i18n ? await strapi.plugin("i18n").service("locales").getDefaultLocale() : null;
1137
+ const current = await strapi.db.query(uid).findMany({ select: ["locale"], where: { documentId: row.relatedDocumentId } });
1138
+ const existing = current.length ? [...new Set(current.map((entry) => i18n ? entry.locale : null))] : null;
1139
+ const singleTaken = schema.kind === "singleType" && !existing && Boolean(await strapi.db.query(uid).findOne({ select: ["id"] }));
1140
+ const chosen = [...chooseEntries(row.entries).values()];
1141
+ const { media, relation } = await lookups(uid, chosen.map((entry) => entry.snapshot));
1142
+ const taken = /* @__PURE__ */ new Set();
1143
+ for (const entry of chosen) for (const field of uniqueFields(schema)) {
1144
+ const value = entry.snapshot?.[field];
1145
+ if (blank(value) || typeof value === "object") continue;
1146
+ const other = await strapi.db.query(uid).findOne({ select: ["id"], where: { [field]: value, ...i18n && { locale: entry.locale }, ...existing && { documentId: { $ne: row.relatedDocumentId } } } });
1147
+ if (other) taken.add(stable([field, entry.locale ?? null, value]));
1148
+ }
1149
+ const plan = planRestore(row.entries, { schema, schemaOf, locales, defaultLocale, existing, singleTaken, media, relation, taken: (field, locale, value) => taken.has(stable([field, locale ?? null, value])) });
1150
+ const incoming = await strapi.db.transaction(({ trx }) => resolveIncoming(uid, row.incoming, plan.steps.map((step) => step.locale), trx));
1151
+ return { ...plan, documentId: existing ? row.relatedDocumentId : null, incoming };
1152
+ },
1153
+ // What the pre-check endpoint returns: the plan without the data it would write.
1154
+ async check(row) {
1155
+ if (row.status !== "trashed") return { status: row.status, restoredAs: row.restoredAs, blocking: [{ code: "restored" }], warnings: [] };
1156
+ const { steps, incoming: { links, ...incoming }, ...plan } = await self.plan(row);
1157
+ return { ...plan, locales: steps.map((step) => step.locale), incoming: { ...incoming, reconnect: links.length } };
1158
+ },
1159
+ // Restore as a draft, in one transaction: claim the row (a second restore of the same row, concurrent or later, gets
1160
+ // `already` with the first one's document), check again, recreate (default locale first, the others under the same
1161
+ // documentId), put the links back, record `restore` events. A blocking problem throws `conflict` and nothing is written.
1162
+ async restore(id, { actor, userId }) {
1163
+ return restoring.run(true, () => strapi.db.transaction(async ({ trx }) => {
1164
+ const claimed = await rows().updateMany({ where: { id, status: "trashed" }, data: { status: "restored", restoredAt: /* @__PURE__ */ new Date() } });
1165
+ const row = await rows().findOne({ where: { id } });
1166
+ if (!row) return null;
1167
+ if (!claimed?.count) return { already: true, documentId: row.restoredAs || null };
1168
+ const plan = await self.plan(row);
1169
+ if (plan.blocking.length) {
1170
+ const error = new Error("conflict");
1171
+ error.conflict = { blocking: plan.blocking, warnings: plan.warnings };
1172
+ throw error;
1173
+ }
1174
+ const uid = row.contentType, documents = strapi.documents(uid);
1175
+ const creator = userId ? { createdBy: userId, updatedBy: userId } : {};
1176
+ let documentId = plan.documentId;
1177
+ for (const { locale, data } of plan.steps) {
1178
+ const params = { ...locale && { locale }, data: { ...data, ...creator } };
1179
+ if (documentId) await documents.update({ documentId, ...params });
1180
+ else documentId = (await documents.create(params)).documentId;
1181
+ }
1182
+ const restored = await events().rows(uid, documentId, localized(uid) ? plan.steps.map((step) => step.locale) : null);
1183
+ const rowOf = new Map(restored.map((entry) => [entry.locale ?? null, entry]));
1184
+ for (const link of plan.incoming.links) {
1185
+ const target = rowOf.get(link.locale);
1186
+ if (!target) continue;
1187
+ const { joinColumn, inverseJoinColumn, orderColumnName } = link.joinTable;
1188
+ await table(trx, link.joinTable.name).insert({ [joinColumn.name]: link.ownerRowId, [inverseJoinColumn.name]: target.id, ...orderColumnName && link.order != null && { [orderColumnName]: link.order } });
1189
+ }
1190
+ for (const entry of restored) await events().record({ uid, documentId, locale: entry.locale ?? null, action: "restore", entry, actor, extra: { restoredFrom: row.relatedDocumentId, trash: row.id } });
1191
+ await rows().update({ where: { id }, data: { restoredAs: documentId } });
1192
+ const { links, ...incoming } = plan.incoming;
1193
+ return { documentId, locales: plan.steps.map((step) => step.locale), warnings: plan.warnings, incoming: { ...incoming, reconnected: links.length } };
1194
+ }));
1195
+ },
1196
+ // Delete forever (one row), recorded as a `purge` event. Never touches media files.
1197
+ async remove(row, actor) {
1198
+ return strapi.db.transaction(async () => {
1199
+ const { count } = await rows().deleteMany({ where: { id: row.id } });
1200
+ if (count) await events().record({ uid: row.contentType, documentId: row.relatedDocumentId, action: "purge", actor, extra: { trash: row.id, title: row.title } });
1201
+ return count;
1202
+ });
1203
+ },
1204
+ // Nightly, in batches, idempotent: rows past expiresAt are deleted (restored ones too). Never touches media files.
1205
+ async purge(now = Date.now()) {
1206
+ let count = 0;
1207
+ for (; ; ) {
1208
+ const ids = (await rows().findMany({ select: ["id"], where: { expiresAt: { $lt: new Date(now) } }, orderBy: { id: "asc" }, limit: BATCH })).map((row) => row.id);
1209
+ if (ids.length) await rows().deleteMany({ where: { id: { $in: ids } } });
1210
+ count += ids.length;
1211
+ if (ids.length < BATCH) return count;
1212
+ }
1213
+ }
1214
+ };
1215
+ return self;
1216
+ }
1217
+ var ID = /^[1-9]\d{0,15}$/;
1218
+ var API_UID = /^api::[\w-]+\.[\w-]+$/;
1219
+ var int = (value, fallback, max) => {
1220
+ if (value === void 0 || value === "") return fallback;
1221
+ const n = Number(value);
1222
+ return Number.isInteger(n) && n >= 1 && n <= max ? n : NaN;
1223
+ };
1224
+ var trashController2 = ({ strapi }) => {
1225
+ const service = () => strapi.plugin(PLUGIN2).service("trash");
1226
+ const { can, readableTypes, actorOf } = history();
1227
+ const load = async (ctx, action = "read") => {
1228
+ if (!ID.test(String(ctx.params?.id || ""))) {
1229
+ ctx.badRequest("Invalid trash entry");
1230
+ return null;
1231
+ }
1232
+ const row = await service().find(Number(ctx.params.id));
1233
+ if (!row || !can(strapi, ctx, row.contentType, "read") || action !== "read" && !can(strapi, ctx, row.contentType, action)) {
1234
+ ctx.notFound();
1235
+ return null;
1236
+ }
1237
+ return row;
1238
+ };
1239
+ return {
1240
+ async list(ctx) {
1241
+ const { contentType = "", status = "trashed" } = ctx.query || {};
1242
+ const page = int(ctx.query?.page, 1, 1e4), pageSize = int(ctx.query?.pageSize, 20, 100);
1243
+ if (typeof contentType !== "string" || contentType && !API_UID.test(contentType) || !STATUSES.includes(status) || Number.isNaN(page) || Number.isNaN(pageSize)) return ctx.badRequest("Invalid filters");
1244
+ const types = readableTypes(strapi, ctx);
1245
+ ctx.body = {
1246
+ ...await service().list({ contentType, status, page, pageSize, types }),
1247
+ types: types.map((uid) => ({ uid, displayName: strapi.contentTypes[uid].info?.displayName || uid, kind: strapi.contentTypes[uid].kind, localized: Boolean(strapi.contentTypes[uid].pluginOptions?.i18n?.localized) }))
1248
+ };
1249
+ },
1250
+ async find(ctx) {
1251
+ const row = await load(ctx);
1252
+ if (row) ctx.body = service().preview(row);
1253
+ },
1254
+ async check(ctx) {
1255
+ const row = await load(ctx, "create");
1256
+ if (row) ctx.body = await service().check(row);
1257
+ },
1258
+ async restore(ctx) {
1259
+ const row = await load(ctx, "create");
1260
+ if (!row) return;
1261
+ try {
1262
+ const result = await service().restore(row.id, { actor: actorOf(strapi), userId: ctx.state?.user?.id });
1263
+ if (!result) return ctx.notFound();
1264
+ ctx.body = result;
1265
+ } catch (error) {
1266
+ if (!error?.conflict) throw error;
1267
+ ctx.status = 409;
1268
+ ctx.body = { data: null, error: { status: 409, name: "ConflictError", message: "The document cannot be restored as it is: nothing was written.", details: error.conflict } };
1269
+ }
1270
+ },
1271
+ async remove(ctx) {
1272
+ const row = await load(ctx, "delete");
1273
+ if (!row) return;
1274
+ ctx.body = { deleted: await service().remove(row, actorOf(strapi)) };
1275
+ }
1276
+ };
1277
+ };
1278
+ module2.exports = { TRASH_UID, STATUSES, restoring, trashContentType: trashContentType2, expiresAt, uniqueFields, chooseEntries, restorePayload, planRestore, incomingSources, incomingRows, previewOf, trashService: trashService2, trashController: trashController2 };
1279
+ }
1280
+ });
1281
+
1282
+ // server/history.js
1283
+ var require_history = __commonJS({
1284
+ "server/history.js"(exports2, module2) {
1285
+ "use strict";
1286
+ var { createHash } = require("node:crypto");
1287
+ var { PLUGIN: PLUGIN2 } = require_settings();
1288
+ var { snapshotPopulate, canonical, stable, summarize } = require_diff();
1289
+ var { TRASH_UID, restoring } = require_trash();
1290
+ var EVENT_UID = `plugin::${PLUGIN2}.event`;
1291
+ var ACTIONS = ["create", "update", "publish", "unpublish", "discard", "delete", "restore", "purge"];
1292
+ var CAPTURED = { create: "create", clone: "create", update: "update", publish: "publish", unpublish: "unpublish", discardDraft: "discard", delete: "delete" };
1293
+ var CRON2 = "blocksceneHistoryPurge";
1294
+ var BATCH = 500;
1295
+ var DAY = 24 * 60 * 60 * 1e3;
1296
+ var LIST_LIMIT = 100;
1297
+ var ACTORS_LIMIT = 500;
1298
+ var SEARCH_LIMIT = 200;
1299
+ var eventContentType2 = { schema: {
1300
+ kind: "collectionType",
1301
+ collectionName: "blockscene_events",
1302
+ info: { singularName: "event", pluralName: "events", displayName: "Blockscene event" },
1303
+ options: { draftAndPublish: false },
1304
+ pluginOptions: { "content-manager": { visible: false }, "content-type-builder": { visible: false }, i18n: { localized: false } },
1305
+ attributes: {
1306
+ contentType: { type: "string", required: true },
1307
+ relatedDocumentId: { type: "string", required: true },
1308
+ locale: { type: "string" },
1309
+ action: { type: "enumeration", enum: ACTIONS, required: true },
1310
+ // 'admin:<id>', 'token:<id>', 'user:<id>' (Users & Permissions) or 'system'; the name as it was at that moment.
1311
+ actor: { type: "string", required: true },
1312
+ actorName: { type: "string" },
1313
+ at: { type: "datetime", required: true },
1314
+ // { fields: [names], blocks: { added, removed, changed }, initial? } vs the previous snapshot; { missing: true } when the capture failed;
1315
+ // restore: + { restoredFrom, trash }; purge: { trash, title }.
1316
+ summary: { type: "json" },
1317
+ // Null when identical to the previous snapshot of the same locale (same hash) or purged.
1318
+ snapshot: { type: "json" },
1319
+ hash: { type: "string" },
1320
+ size: { type: "integer" }
1321
+ },
1322
+ indexes: [{ name: "blockscene_events_lookup", columns: ["content_type", "related_document_id", "locale", "at"] }]
1323
+ } };
1324
+ var fail2 = (message, Kind = "ApplicationError") => {
1325
+ let E;
1326
+ try {
1327
+ E = require("@strapi/utils").errors[Kind];
1328
+ } catch {
1329
+ E = class extends Error {
1330
+ constructor(m) {
1331
+ super(m);
1332
+ this.name = Kind;
1333
+ }
1334
+ };
1335
+ }
1336
+ throw new E(message);
1337
+ };
1338
+ var hashOf = (text) => createHash("sha256").update(text).digest("hex");
1339
+ var covers2 = (history, uid) => Boolean(history?.enabled) && uid.startsWith("api::") && (history.contentTypes === "all" || Array.isArray(history.contentTypes) && history.contentTypes.includes(uid));
1340
+ var retention = ({ retentionDays, eventDays }, now = Date.now()) => ({ snapshotsBefore: new Date(now - retentionDays * DAY), eventsBefore: new Date(now - eventDays * DAY) });
1341
+ function actorOf(strapi) {
1342
+ let ctx;
1343
+ try {
1344
+ ctx = strapi.requestContext?.get?.();
1345
+ } catch {
1346
+ ctx = null;
1347
+ }
1348
+ const strategy = ctx?.state?.auth?.strategy?.name, user = ctx?.state?.user, token = ctx?.state?.auth?.credentials;
1349
+ const name = (value) => String(value || "").slice(0, 255);
1350
+ if (strategy === "admin" && user?.id) return { actor: `admin:${user.id}`, actorName: name([user.firstname, user.lastname].filter(Boolean).join(" ") || user.username || user.email) };
1351
+ if (strategy === "api-token" && token?.id) return { actor: `token:${token.id}`, actorName: name(token.name) };
1352
+ if (user?.id) return { actor: `user:${user.id}`, actorName: name(user.username || user.email) };
1353
+ return { actor: "system", actorName: "" };
1354
+ }
1355
+ function refsOf(snapshot, schema, schemaOf) {
1356
+ const media = /* @__PURE__ */ new Set(), relations = [];
1357
+ const walk = (data, schema2, depth) => {
1358
+ if (!data || typeof data !== "object" || depth > 20) return;
1359
+ for (const [name, attr] of Object.entries(schema2?.attributes || {})) {
1360
+ const value = data[name];
1361
+ if (value == null) continue;
1362
+ const list = Array.isArray(value) ? value : [value];
1363
+ if (attr.type === "media") list.forEach((id) => Number.isInteger(id) && media.add(id));
1364
+ else if (attr.type === "relation" && attr.target) list.forEach((ref) => ref?.documentId && relations.push({ target: attr.target, ...ref }));
1365
+ else if (attr.type === "component") list.forEach((item) => walk(item, schemaOf(attr.component), depth + 1));
1366
+ else if (attr.type === "dynamiczone") list.forEach((row) => walk(row, schemaOf(row?.__component), depth + 1));
1367
+ }
1368
+ };
1369
+ walk(snapshot, schema, 0);
1370
+ return { media: [...media], relations };
1371
+ }
1372
+ function historyService2({ strapi }) {
1373
+ const plugin = () => strapi.plugin(PLUGIN2);
1374
+ const schemaOf = (uid) => uid && (strapi.getModel?.(uid) || strapi.components?.[uid] || strapi.contentTypes?.[uid]);
1375
+ const localized = (uid) => Boolean(schemaOf(uid)?.pluginOptions?.i18n?.localized);
1376
+ const draftAndPublish = (uid) => schemaOf(uid)?.options?.draftAndPublish === true;
1377
+ const events = () => strapi.db.query(EVENT_UID);
1378
+ const actors = async () => {
1379
+ const meta = strapi.db.metadata.get(EVENT_UID);
1380
+ const column = (name) => meta.attributes[name].columnName || name;
1381
+ return strapi.db.connection(meta.tableName).select({ actor: column("actor") }).max({ actorName: column("actorName") }).groupBy(column("actor")).orderBy(column("actor")).limit(ACTORS_LIMIT);
1382
+ };
1383
+ const scope = async (uid, locale) => {
1384
+ if (!localized(uid)) return [null];
1385
+ if (locale === "*") return null;
1386
+ if (Array.isArray(locale) && locale.length) return locale;
1387
+ if (typeof locale === "string" && locale) return [locale];
1388
+ return [await strapi.plugin("i18n").service("locales").getDefaultLocale()];
1389
+ };
1390
+ const rows = async (uid, documentId, locales, published = false) => !documentId ? [] : strapi.db.query(uid).findMany({
1391
+ where: {
1392
+ documentId,
1393
+ ...locales && localized(uid) && { locale: { $in: locales } },
1394
+ ...draftAndPublish(uid) && { publishedAt: published ? { $notNull: true } : { $null: true } }
1395
+ },
1396
+ populate: snapshotPopulate(uid, schemaOf)
1397
+ });
1398
+ const self = {
1399
+ EVENT_UID,
1400
+ async config() {
1401
+ return (await plugin().service("settings").get()).history;
1402
+ },
1403
+ covers: covers2,
1404
+ // One event. The snapshot is stored unless identical to the latest stored one of the same document and locale.
1405
+ async record({ uid, documentId, locale = null, action, entry, actor, missing = false, extra = null }) {
1406
+ let summary = missing ? { missing: true } : null, snapshot = null, hash = null, size = 0;
1407
+ if (entry) {
1408
+ const content = canonical(entry, schemaOf(uid), schemaOf);
1409
+ const text = stable(content);
1410
+ hash = hashOf(text);
1411
+ const previous = await events().findOne({ select: ["hash", "snapshot"], where: { contentType: uid, relatedDocumentId: documentId, locale, size: { $gt: 0 } }, orderBy: [{ at: "desc" }, { id: "desc" }] });
1412
+ summary = summarize(previous?.snapshot || null, content, schemaOf(uid));
1413
+ if (previous?.hash !== hash) {
1414
+ snapshot = content;
1415
+ size = Buffer.byteLength(text);
1416
+ }
1417
+ }
1418
+ if (extra) summary = { ...summary, ...extra };
1419
+ return events().create({ data: { contentType: uid, relatedDocumentId: documentId, locale, action, ...actor, at: /* @__PURE__ */ new Date(), summary, snapshot, hash, size } });
1420
+ },
1421
+ // After a save or publish: one event per affected entry (drafts, or the published versions after a publish).
1422
+ async captureSave({ uid, action, documentId, locales, published, actor }) {
1423
+ if (!documentId) return;
1424
+ for (const entry of await rows(uid, documentId, locales, published)) await self.record({ uid, documentId, locale: entry.locale ?? null, action, entry, actor });
1425
+ },
1426
+ scope,
1427
+ rows,
1428
+ // The Content Manager's main field of a content type when it is a plain value (what list views show), else null.
1429
+ async mainField(uid) {
1430
+ let name = null;
1431
+ try {
1432
+ name = (await strapi.plugin("content-manager").service("content-types").findConfiguration(strapi.contentTypes[uid]))?.settings?.mainField;
1433
+ } catch {
1434
+ name = null;
1435
+ }
1436
+ return name && name !== "id" && schemaOf(uid)?.attributes?.[name] && !["relation", "media", "component", "dynamiczone", "password", "json", "blocks"].includes(schemaOf(uid).attributes[name].type) ? name : null;
1437
+ },
1438
+ // Latest events of one document and locale, newest first; `stored`: its snapshot (or an identical one) can be loaded.
1439
+ async list({ uid, documentId, locale }) {
1440
+ const where = { contentType: uid, relatedDocumentId: documentId, locale: locale || null };
1441
+ const [list, kept] = await Promise.all([
1442
+ events().findMany({ select: ["id", "action", "actor", "actorName", "at", "summary", "hash", "size"], where, orderBy: [{ at: "desc" }, { id: "desc" }], limit: LIST_LIMIT }),
1443
+ events().findMany({ select: ["hash"], where: { ...where, size: { $gt: 0 } } })
1444
+ ]);
1445
+ const hashes = new Set(kept.map((row) => row.hash));
1446
+ return list.map(({ hash, size, ...event }) => ({ ...event, stored: Boolean(hash && hashes.has(hash)) }));
1447
+ },
1448
+ // One event with its snapshot (from an identical event when this one was deduplicated) and what loading it needs:
1449
+ // the media files and relation targets that still exist (relation labels from the Content Manager's main field).
1450
+ async find(id) {
1451
+ const event = await events().findOne({ where: { id } });
1452
+ if (!event) return null;
1453
+ const { snapshot: own, ...meta } = event;
1454
+ const snapshot = own || event.hash && (await events().findOne({ select: ["snapshot"], where: { contentType: event.contentType, relatedDocumentId: event.relatedDocumentId, locale: event.locale, hash: event.hash, size: { $gt: 0 } } }))?.snapshot || null;
1455
+ if (!snapshot) return { event: meta, snapshot: null, media: {}, relations: {} };
1456
+ const refs = refsOf(snapshot, schemaOf(event.contentType), schemaOf);
1457
+ const files = refs.media.length ? await strapi.db.query("plugin::upload.file").findMany({ where: { id: { $in: refs.media } } }) : [];
1458
+ const relations = {};
1459
+ for (const target of [...new Set(refs.relations.map((ref) => ref.target))]) {
1460
+ if (!strapi.contentTypes?.[target]) continue;
1461
+ const mainField = await self.mainField(target), scalar = Boolean(mainField);
1462
+ const found = await strapi.db.query(target).findMany({
1463
+ select: ["id", "documentId", "locale", ...scalar ? [mainField] : []],
1464
+ where: { documentId: { $in: [...new Set(refs.relations.filter((ref) => ref.target === target).map((ref) => ref.documentId))] }, ...draftAndPublish(target) && { publishedAt: { $null: true } } }
1465
+ });
1466
+ relations[target] = found.map((row) => ({ id: row.id, documentId: row.documentId, locale: row.locale || null, label: scalar && row[mainField] != null ? String(row[mainField]) : void 0, mainField: scalar ? mainField : void 0 }));
1467
+ }
1468
+ return { event: meta, snapshot, media: Object.fromEntries(files.map((file) => [file.id, file])), relations };
1469
+ },
1470
+ // Content activity: one page of events (no snapshots), newest first, with each document's title and whether it still
1471
+ // exists (the list links to it). `types`: the content types the user may read. `q`: documents whose main field
1472
+ // contains it now, or whose trash entry's title does (at most SEARCH_LIMIT per content type).
1473
+ async activity({ actor, contentType, action, from, to, q, page, pageSize, types }) {
1474
+ const empty = { results: [], pagination: { page, pageSize, total: 0, pageCount: 0 }, actors: [] };
1475
+ if (contentType && !types.includes(contentType)) return empty;
1476
+ const where = {
1477
+ contentType: contentType || { $in: types },
1478
+ ...actor && { actor },
1479
+ ...action && { action },
1480
+ ...(from || to) && { at: { ...from && { $gte: from }, ...to && { $lte: to } } }
1481
+ };
1482
+ if (q) {
1483
+ const matches = [];
1484
+ for (const uid of contentType ? [contentType] : types) {
1485
+ const main = await self.mainField(uid);
1486
+ const found = new Set(main ? (await strapi.db.query(uid).findMany({ select: ["documentId"], where: { [main]: { $containsi: q } }, limit: SEARCH_LIMIT })).map((row) => row.documentId) : []);
1487
+ for (const row of await strapi.db.query(TRASH_UID).findMany({ select: ["relatedDocumentId"], where: { contentType: uid, title: { $containsi: q } }, limit: SEARCH_LIMIT })) found.add(row.relatedDocumentId);
1488
+ if (found.size) matches.push({ contentType: uid, relatedDocumentId: { $in: [...found] } });
1489
+ }
1490
+ if (!matches.length) return { ...empty, actors: await actors() };
1491
+ where.$or = matches;
1492
+ }
1493
+ const [list, total] = await Promise.all([
1494
+ events().findMany({ select: ["id", "contentType", "relatedDocumentId", "locale", "action", "actor", "actorName", "at", "summary"], where, orderBy: [{ at: "desc" }, { id: "desc" }], offset: (page - 1) * pageSize, limit: pageSize }),
1495
+ events().count({ where })
1496
+ ]);
1497
+ const docs = /* @__PURE__ */ new Map();
1498
+ for (const uid of [...new Set(list.map((event) => event.contentType))]) {
1499
+ const ids = [...new Set(list.filter((event) => event.contentType === uid).map((event) => event.relatedDocumentId))];
1500
+ const main = strapi.contentTypes?.[uid] ? await self.mainField(uid) : null;
1501
+ const found = strapi.contentTypes?.[uid] ? await strapi.db.query(uid).findMany({ select: ["documentId", "locale", ...main ? [main] : []], where: { documentId: { $in: ids } } }) : [];
1502
+ for (const row of found) {
1503
+ const key = `${uid}|${row.documentId}`;
1504
+ docs.set(key, [...docs.get(key) || [], { locale: row.locale ?? null, title: main && row[main] != null ? String(row[main]) : null }]);
1505
+ }
1506
+ const gone = ids.filter((id) => !docs.has(`${uid}|${id}`));
1507
+ if (gone.length) {
1508
+ for (const row of await strapi.db.query(TRASH_UID).findMany({ select: ["relatedDocumentId", "title"], where: { contentType: uid, relatedDocumentId: { $in: gone } }, orderBy: { id: "desc" } }))
1509
+ if (!docs.has(`trash|${uid}|${row.relatedDocumentId}`)) docs.set(`trash|${uid}|${row.relatedDocumentId}`, row.title);
1510
+ }
1511
+ }
1512
+ const results = list.map((event) => {
1513
+ const rows2 = docs.get(`${event.contentType}|${event.relatedDocumentId}`) || [];
1514
+ const own = rows2.find((row) => row.locale === (event.locale ?? null));
1515
+ if (event.action === "purge") return { ...event, exists: false, title: event.summary?.title ?? null };
1516
+ return { ...event, exists: Boolean(own), title: (own || rows2[0])?.title ?? docs.get(`trash|${event.contentType}|${event.relatedDocumentId}`) ?? null };
1517
+ });
1518
+ return { results, pagination: { page, pageSize, total, pageCount: Math.ceil(total / pageSize) }, actors: await actors() };
1519
+ },
1520
+ // Nightly, in batches, idempotent (two instances running it is harmless): events past eventDays are deleted;
1521
+ // snapshots past retentionDays, or beyond maxSnapshots per document (newest kept), are emptied. Never touches media.
1522
+ async purge(now = Date.now()) {
1523
+ const history = await self.config();
1524
+ const { snapshotsBefore, eventsBefore } = retention(history, now);
1525
+ const counts = { events: 0, expired: 0, excess: 0 };
1526
+ const batches = async (key, query, apply) => {
1527
+ for (; ; ) {
1528
+ const ids = (await events().findMany({ select: ["id"], limit: BATCH, ...query })).map((row) => row.id);
1529
+ if (ids.length) await apply({ id: { $in: ids } });
1530
+ counts[key] += ids.length;
1531
+ if (ids.length < BATCH) return;
1532
+ }
1533
+ };
1534
+ const empty = (where) => events().updateMany({ where, data: { snapshot: null, size: 0 } });
1535
+ await batches("events", { where: { at: { $lt: eventsBefore } }, orderBy: { id: "asc" } }, (where) => events().deleteMany({ where }));
1536
+ await batches("expired", { where: { at: { $lt: snapshotsBefore }, size: { $gt: 0 } }, orderBy: { id: "asc" } }, empty);
1537
+ const meta = strapi.db.metadata.get(EVENT_UID);
1538
+ const column = (name) => meta.attributes[name].columnName || name;
1539
+ const crowded = await strapi.db.connection(meta.tableName).select({ uid: column("contentType"), documentId: column("relatedDocumentId") }).where(column("size"), ">", 0).groupBy(column("contentType"), column("relatedDocumentId")).havingRaw("count(*) > ?", [history.maxSnapshots]);
1540
+ for (const { uid, documentId } of crowded) await batches("excess", {
1541
+ where: { contentType: uid, relatedDocumentId: documentId, size: { $gt: 0 } },
1542
+ orderBy: [{ at: "desc" }, { id: "desc" }],
1543
+ offset: history.maxSnapshots
1544
+ }, empty);
1545
+ return counts;
1546
+ }
1547
+ };
1548
+ return self;
1549
+ }
1550
+ function registerHistory2(strapi) {
1551
+ if (!strapi.documents?.use) return;
1552
+ const service = () => strapi.plugin(PLUGIN2).service("history");
1553
+ const warn = (message, error) => strapi.log.error(`[${PLUGIN2}] ${message}: ${error?.message || error}`);
1554
+ strapi.documents.use(async (ctx, next) => {
1555
+ const action = CAPTURED[ctx.action];
1556
+ if (!action || !String(ctx.uid || "").startsWith("api::") || strapi.plugin(PLUGIN2).config("disabled") === true || restoring.getStore()) return next();
1557
+ const history = service();
1558
+ const params = ctx.params || {};
1559
+ if (action === "delete") {
1560
+ const config = params.documentId ? await history.config() : null;
1561
+ if (!config || !history.covers(config, ctx.uid)) return next();
1562
+ return strapi.db.transaction(async () => {
1563
+ const actor2 = actorOf(strapi), trash = strapi.plugin(PLUGIN2).service("trash");
1564
+ const published = strapi.getModel(ctx.uid)?.options?.draftAndPublish === true;
1565
+ let locales2, entries, live, incoming;
1566
+ try {
1567
+ locales2 = await history.scope(ctx.uid, params.locale);
1568
+ entries = await history.rows(ctx.uid, params.documentId, locales2);
1569
+ live = published ? await history.rows(ctx.uid, params.documentId, locales2, true) : [];
1570
+ incoming = await trash.incoming(ctx.uid, new Map([...entries.map((row) => [row.id, { locale: row.locale, published: false }]), ...live.map((row) => [row.id, { locale: row.locale, published: true }])]));
1571
+ } catch (error) {
1572
+ warn("reading the document before a delete failed", error);
1573
+ fail2(`The version history could not record this delete, so nothing was deleted (${error.message}).`);
1574
+ }
1575
+ const result2 = await next();
1576
+ try {
1577
+ for (const entry of entries) await history.record({ uid: ctx.uid, documentId: params.documentId, locale: entry.locale ?? null, action, entry, actor: actor2 });
1578
+ if (entries.length || live.length) await trash.record({ uid: ctx.uid, documentId: params.documentId, locales: locales2, drafts: entries, published: live, incoming, actor: actor2, days: config.trashDays });
1579
+ } catch (error) {
1580
+ warn("recording a delete failed, the delete was rolled back", error);
1581
+ fail2(`The version history could not record this delete, so nothing was deleted (${error.message}).`);
1582
+ }
1583
+ return result2;
1584
+ });
1585
+ }
1586
+ let covered = false;
1587
+ try {
1588
+ covered = history.covers(await history.config(), ctx.uid);
1589
+ } catch (error) {
1590
+ warn("reading the history settings failed, this change is not recorded", error);
1591
+ }
1592
+ if (!covered) return next();
1593
+ const actor = actorOf(strapi);
1594
+ const result = await next();
1595
+ const documentId = ["create", "update"].includes(action) ? result?.documentId || params.documentId : params.documentId;
1596
+ const locales = ["publish", "unpublish", "discard"].includes(action) ? [...new Set((result?.entries || []).map((entry) => entry?.locale ?? null))] : ctx.action === "clone" ? null : await history.scope(ctx.uid, params.locale).catch(() => [result?.locale ?? null]);
1597
+ const steps = [[action, action === "publish"]];
1598
+ if (["create", "update"].includes(ctx.action) && params.status === "published" && strapi.getModel(ctx.uid)?.options?.draftAndPublish) steps.push(["publish", true]);
1599
+ for (const [step, published] of steps) {
1600
+ if (locales && !locales.length) continue;
1601
+ try {
1602
+ await history.captureSave({ uid: ctx.uid, action: step, documentId, locales, published, actor });
1603
+ } catch (error) {
1604
+ warn(`recording "${step}" of ${ctx.uid} ${documentId} failed, the change was saved without a version`, error);
1605
+ try {
1606
+ if (documentId) for (const locale of locales || [null]) await history.record({ uid: ctx.uid, documentId, locale, action: step, actor, missing: true });
1607
+ } catch (again) {
1608
+ warn("marking the missing version failed too", again);
1609
+ }
1610
+ }
1611
+ }
1612
+ return result;
1613
+ });
1614
+ }
1615
+ function registerPurge2(strapi) {
1616
+ if (!strapi.documents?.use || !strapi.cron?.add) return;
1617
+ strapi.cron.add({ [CRON2]: { options: "0 3 * * *", task: async () => {
1618
+ try {
1619
+ const counts = await strapi.plugin(PLUGIN2).service("history").purge();
1620
+ if (counts.events || counts.expired || counts.excess) strapi.log.info(`[${PLUGIN2}] history purge: ${counts.events} events deleted, ${counts.expired + counts.excess} snapshots emptied`);
1621
+ } catch (error) {
1622
+ strapi.log.error(`[${PLUGIN2}] history purge failed: ${error?.message || error}`);
1623
+ }
1624
+ try {
1625
+ const count = await strapi.plugin(PLUGIN2).service("trash").purge();
1626
+ if (count) strapi.log.info(`[${PLUGIN2}] trash purge: ${count} expired entries deleted`);
1627
+ } catch (error) {
1628
+ strapi.log.error(`[${PLUGIN2}] trash purge failed: ${error?.message || error}`);
1629
+ }
1630
+ } } });
1631
+ }
1632
+ var DOCUMENT_ID = /^[A-Za-z0-9_-]{1,64}$/;
1633
+ var LOCALE = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
1634
+ var can = (strapi, ctx, uid, action = "read") => {
1635
+ try {
1636
+ return !strapi.plugin("content-manager").service("permission-checker").create({ userAbility: ctx.state.userAbility, model: uid }).cannot[action]();
1637
+ } catch {
1638
+ return false;
1639
+ }
1640
+ };
1641
+ var canRead = (strapi, ctx, uid) => can(strapi, ctx, uid);
1642
+ var readableTypes = (strapi, ctx) => Object.keys(strapi.contentTypes || {}).filter((uid) => uid.startsWith("api::") && canRead(strapi, ctx, uid));
1643
+ var ACTOR = /^(system|(admin|token|user):\d{1,15})$/;
1644
+ var int = (value, fallback, max) => {
1645
+ if (value === void 0 || value === "") return fallback;
1646
+ const n = Number(value);
1647
+ return Number.isInteger(n) && n >= 1 && n <= max ? n : NaN;
1648
+ };
1649
+ var date = (value) => {
1650
+ if (!value) return null;
1651
+ const time = Date.parse(value);
1652
+ return typeof value === "string" && value.length <= 40 && Number.isFinite(time) ? new Date(time) : NaN;
1653
+ };
1654
+ var historyController2 = ({ strapi }) => ({
1655
+ async list(ctx) {
1656
+ const { uid, documentId } = ctx.params || {};
1657
+ const locale = ctx.query?.locale || "";
1658
+ if (!String(uid).startsWith("api::") || !strapi.contentTypes?.[uid] || !DOCUMENT_ID.test(documentId || "") || locale && !LOCALE.test(locale)) return ctx.badRequest("Invalid content type, document or locale");
1659
+ if (!canRead(strapi, ctx, uid)) return ctx.forbidden();
1660
+ const history = strapi.plugin(PLUGIN2).service("history");
1661
+ ctx.body = { results: await history.list({ uid, documentId, locale: (await history.scope(uid, locale || void 0))[0] }) };
1662
+ },
1663
+ async find(ctx) {
1664
+ const id = Number(ctx.params?.id);
1665
+ if (!Number.isInteger(id) || id <= 0) return ctx.badRequest("Invalid event");
1666
+ const found = await strapi.plugin(PLUGIN2).service("history").find(id);
1667
+ if (!found || !canRead(strapi, ctx, found.event.contentType)) return ctx.notFound();
1668
+ ctx.body = found;
1669
+ },
1670
+ async activity(ctx) {
1671
+ const { actor = "", contentType = "", action = "", q = "" } = ctx.query || {};
1672
+ const page = int(ctx.query?.page, 1, 1e4), pageSize = int(ctx.query?.pageSize, 25, 100), from = date(ctx.query?.from), to = date(ctx.query?.to);
1673
+ if ([actor, contentType, action, q].some((value) => typeof value !== "string") || actor && !ACTOR.test(actor) || contentType && !/^api::[\w-]+\.[\w-]+$/.test(contentType) || action && !ACTIONS.includes(action) || q.length > 100 || [page, pageSize, from, to].some((value) => Number.isNaN(value))) return ctx.badRequest("Invalid filters");
1674
+ const history = strapi.plugin(PLUGIN2).service("history");
1675
+ const types = readableTypes(strapi, ctx);
1676
+ ctx.body = {
1677
+ ...await history.activity({ actor, contentType, action, from, to, q: q.trim(), page, pageSize, types }),
1678
+ enabled: Boolean((await history.config()).enabled) && strapi.plugin(PLUGIN2).config("disabled") !== true,
1679
+ types: types.map((uid) => ({ uid, displayName: strapi.contentTypes[uid].info?.displayName || uid, kind: strapi.contentTypes[uid].kind, localized: Boolean(strapi.contentTypes[uid].pluginOptions?.i18n?.localized) }))
1680
+ };
1681
+ }
1682
+ });
1683
+ module2.exports = { EVENT_UID, ACTIONS, CAPTURED, CRON: CRON2, BATCH, eventContentType: eventContentType2, covers: covers2, retention, actorOf, refsOf, can, readableTypes, historyService: historyService2, registerHistory: registerHistory2, registerPurge: registerPurge2, historyController: historyController2 };
221
1684
  }
222
1685
  });
223
1686
 
224
1687
  // server/index.js
225
- var { PLUGIN, TEMPLATES, DEFAULTS, catalog, validateSettings, mergeSaved, safeUrl, fail } = require_settings();
226
- var { safeGroups, validateGroups } = require_groups();
1688
+ var { PLUGIN, TEMPLATES, TYPOLOGIES, DEFAULTS, catalog, validateSettings, validateFields, validateVariants, schemaMetadata, mergeSaved, layer, overrides, validatePrefs, mergePrefs, safeUrl, fail } = require_settings();
1689
+ var { safeGroups, validateGroups, layoutFields } = require_groups();
1690
+ var { hiddenName, injectHidden, hideFromBuilder, registerHiddenStrip } = require_hidden();
1691
+ var { CRON, covers, eventContentType, historyService, historyController, registerHistory, registerPurge } = require_history();
1692
+ var { trashContentType, trashService, trashController } = require_trash();
1693
+ var STRAPI5 = true;
1694
+ var withHidden = [];
227
1695
  var store = (strapi) => strapi.store({ type: "plugin", name: PLUGIN });
228
1696
  var LEGACY_PLUGIN = "block-picker";
229
1697
  async function readSettings(strapi) {
@@ -247,6 +1715,8 @@ async function resolveMedia(strapi, settings) {
247
1715
  }
248
1716
  return resolved;
249
1717
  }
1718
+ var contentTypeUids = (strapi) => Object.fromEntries(Object.entries(strapi.contentTypes || {}).filter(([uid, schema]) => uid.startsWith("api::") && zonesOf(schema).length).map(([uid, schema]) => [uid, Object.keys(schema.attributes || {})]));
1719
+ var apiUids = (strapi) => Object.keys(strapi.contentTypes || {}).filter((uid) => uid.startsWith("api::"));
250
1720
  var zonesOf = (schema) => Object.entries(schema?.attributes || {}).filter(([, attr]) => attr?.type === "dynamiczone").map(([name]) => name);
251
1721
  var label = (error) => `row ${error.index + 1}: ${error.code === "closeBeforeOpen" ? `close marker ${error.uid} has no open marker before it` : error.code === "mismatch" ? `close marker ${error.uid} does not match the open group ${error.open} (expected ${error.expected})` : `group ${error.uid} is not closed (expected ${error.expected})`}`;
252
1722
  function checkZones(strapi, uid, entry, groups) {
@@ -263,6 +1733,11 @@ function registerPublishGuard(strapi) {
263
1733
  const groups = safeGroups(plugin.config("groups"), componentUids(strapi));
264
1734
  if (plugin.config("groups") && !groups) strapi.log.warn(`[${PLUGIN}] "groups" config ignored: expected { "<open component uid>": "<close component uid>" } with existing components; every block is treated as ordinary.`);
265
1735
  if (!groups) return;
1736
+ const active = async (uid) => {
1737
+ if (plugin.config("disabled") === true) return false;
1738
+ const settings = await plugin.service("settings").get();
1739
+ return settings.editor.enabled && settings.contentTypes?.[uid]?.enabled !== false;
1740
+ };
266
1741
  if (strapi.documents?.use) {
267
1742
  const defaultLocale = async () => {
268
1743
  try {
@@ -277,7 +1752,7 @@ function registerPublishGuard(strapi) {
277
1752
  if (!publishing || !ctx.uid) return next();
278
1753
  const model = strapi.getModel(ctx.uid);
279
1754
  const zones = zonesOf(model);
280
- if (!zones.length) return next();
1755
+ if (!zones.length || !await active(ctx.uid)) return next();
281
1756
  if (action === "create") {
282
1757
  checkZones(strapi, ctx.uid, params.data || {}, groups);
283
1758
  return next();
@@ -303,19 +1778,19 @@ function registerPublishGuard(strapi) {
303
1778
  const published = (data) => Boolean(data && data.publishedAt);
304
1779
  strapi.db.lifecycles.subscribe({
305
1780
  async beforeCreate(event) {
306
- if (published(event.params?.data)) checkZones(strapi, event.model.uid, event.params.data, groups);
1781
+ if (published(event.params?.data) && await active(event.model.uid)) checkZones(strapi, event.model.uid, event.params.data, groups);
307
1782
  },
308
1783
  async beforeUpdate(event) {
309
1784
  const { data, where } = event.params || {};
310
1785
  const zones = zonesOf(strapi.getModel(event.model.uid));
311
- if (!published(data) || !zones.length) return;
1786
+ if (!published(data) || !zones.length || !await active(event.model.uid)) return;
312
1787
  const entry = zones.every((name) => Array.isArray(data[name])) ? data : { ...await strapi.entityService.findOne(event.model.uid, where?.id, { populate: zones }), ...data };
313
1788
  checkZones(strapi, event.model.uid, entry, groups);
314
1789
  },
315
1790
  async beforeUpdateMany(event) {
316
1791
  const { data, where } = event.params || {};
317
1792
  const zones = zonesOf(strapi.getModel(event.model.uid));
318
- if (!published(data) || !zones.length) return;
1793
+ if (!published(data) || !zones.length || !await active(event.model.uid)) return;
319
1794
  for (const entry of await strapi.entityService.findMany(event.model.uid, { filters: where, populate: zones })) checkZones(strapi, event.model.uid, entry, groups);
320
1795
  }
321
1796
  });
@@ -332,30 +1807,126 @@ module.exports = {
332
1807
  blockPreview: false,
333
1808
  // Optional layout groups: OPEN component uid -> its CLOSE uid, e.g. { 'wrappers.join': 'wrappers.close' }.
334
1809
  // Empty/absent: every Dynamic Zone component is an ordinary block. See README "Layout groups".
335
- groups: null
1810
+ groups: null,
1811
+ // Project defaults from code: same shape as the stored settings, e.g. require('./blockscene.json'). See README "Settings page".
1812
+ settings: null,
1813
+ // Edit view field texts from code (never stored): { uid: { attribute: { label, description, placeholder } } }. See README "Field labels".
1814
+ fields: null,
1815
+ // Other languages for the schema metadata (pluginOptions.blockscene, info.description), one flat map per locale:
1816
+ // { 'pt-BR': require('./blockscene/pt-BR.json') }. See README "Describing blocks and fields in the schema".
1817
+ translations: null,
1818
+ // "Hide on the site": boolean attribute added to every Dynamic Zone component (a DB column); false adds nothing.
1819
+ hiddenAttribute: "bsHidden"
336
1820
  },
337
1821
  validator: catalog
338
1822
  },
1823
+ // Before the database schema sync, so the column exists. A name the host already uses with another type is skipped.
1824
+ register({ strapi }) {
1825
+ const plugin = strapi.plugin(PLUGIN);
1826
+ const name = hiddenName(plugin.config("hiddenAttribute"));
1827
+ withHidden = [];
1828
+ if (name === null) strapi.log.warn(`[${PLUGIN}] "hiddenAttribute" config ignored: expected a name like "bsHidden" or false. Hiding blocks is off.`);
1829
+ if (!name) return;
1830
+ const { added, skipped } = injectHidden(strapi.components, strapi.contentTypes, name);
1831
+ withHidden = added;
1832
+ if (skipped.length) strapi.log.warn(`[${PLUGIN}] "${name}" already exists with another type on ${skipped.join(", ")}; those blocks cannot be hidden.`);
1833
+ },
339
1834
  async bootstrap({ strapi }) {
340
1835
  await strapi.admin.services.permission.actionProvider.registerMany([
341
1836
  { section: "plugins", displayName: "Read gallery settings", uid: "settings.read", pluginName: PLUGIN },
342
- { section: "plugins", displayName: "Change gallery settings", uid: "settings.update", pluginName: PLUGIN }
1837
+ { section: "plugins", displayName: "Change gallery settings", uid: "settings.update", pluginName: PLUGIN },
1838
+ ...STRAPI5 ? [
1839
+ ["history.read", "Read version history"],
1840
+ ["activity.read", "Read content activity"],
1841
+ ["trash.read", "Read the trash"],
1842
+ ["trash.restore", "Restore from the trash"],
1843
+ ["trash.purge", "Delete from the trash forever"]
1844
+ ].map(([uid, displayName]) => ({ section: "plugins", displayName, uid, pluginName: PLUGIN })) : []
343
1845
  ]);
1846
+ strapi.plugin(PLUGIN).service("settings").projectDefaults();
1847
+ strapi.plugin(PLUGIN).service("settings").fields();
1848
+ strapi.plugin(PLUGIN).service("settings").variants();
344
1849
  registerPublishGuard(strapi);
1850
+ registerHiddenStrip(strapi, hiddenName(strapi.plugin(PLUGIN).config("hiddenAttribute")), strapi.plugin(PLUGIN));
1851
+ if (withHidden.length) hideFromBuilder(typeof strapi.get === "function" ? strapi.get("services") : strapi.container.get("services"), withHidden, hiddenName(strapi.plugin(PLUGIN).config("hiddenAttribute")));
1852
+ if (STRAPI5) {
1853
+ registerHistory(strapi);
1854
+ registerPurge(strapi);
1855
+ }
345
1856
  },
346
- services: { settings: ({ strapi }) => ({
347
- async get() {
348
- return mergeSaved(await readSettings(strapi), componentUids(strapi));
349
- },
350
- async set(value) {
351
- const next = validateSettings(value, componentUids(strapi));
352
- for (const [uid, entry] of Object.entries(next.components)) {
353
- if (entry.mediaId && !await findMedia(strapi, entry.mediaId).catch(() => null)) fail(`Media for "${uid}" does not exist`);
1857
+ destroy({ strapi }) {
1858
+ if (STRAPI5) strapi.cron?.remove?.(CRON);
1859
+ },
1860
+ // Version history events and the trash (Strapi 5): hidden from the Content Manager and the Content-Type Builder.
1861
+ contentTypes: STRAPI5 ? { event: eventContentType, trash: trashContentType } : {},
1862
+ services: { settings: ({ strapi }) => {
1863
+ let project;
1864
+ const projectDefaults = () => {
1865
+ if (project !== void 0) return project;
1866
+ const code = strapi.plugin(PLUGIN).config("settings");
1867
+ project = null;
1868
+ if (code) try {
1869
+ project = validateSettings(code, componentUids(strapi), contentTypeUids(strapi), apiUids(strapi), strapi.components);
1870
+ } catch (error) {
1871
+ strapi.log?.warn(`[${PLUGIN}] "settings" config ignored: ${error.message}. Using the built-in defaults under the saved settings.`);
354
1872
  }
355
- await store(strapi).set({ key: "settings", value: next });
356
- return next;
357
- }
358
- }) },
1873
+ return project;
1874
+ };
1875
+ let meta;
1876
+ const schemaMeta = () => {
1877
+ if (meta !== void 0) return meta;
1878
+ const notes = [];
1879
+ meta = schemaMetadata({ ...strapi.contentTypes, ...strapi.components }, strapi.plugin(PLUGIN).config("translations"), notes);
1880
+ if (notes.length) strapi.log?.warn(`[${PLUGIN}] schema metadata left out: ${notes.slice(0, 20).join("; ")}${notes.length > 20 ? `; and ${notes.length - 20} more` : ""}.`);
1881
+ return meta;
1882
+ };
1883
+ let fields;
1884
+ const fieldTexts = () => {
1885
+ if (fields !== void 0) return fields;
1886
+ const schemas = Object.fromEntries(Object.entries({ ...strapi.contentTypes, ...strapi.components }).map(([uid, schema]) => [uid, Object.keys(schema?.attributes || {})]));
1887
+ const stale = [];
1888
+ let code = {};
1889
+ try {
1890
+ code = validateFields(strapi.plugin(PLUGIN).config("fields"), schemas, stale);
1891
+ } catch (error) {
1892
+ strapi.log?.warn(`[${PLUGIN}] "fields" config ignored: ${error.message}. Field labels fall back to the schema metadata and the Content Manager's own.`);
1893
+ }
1894
+ if (stale.length) strapi.log?.warn(`[${PLUGIN}] "fields" entries for fields the schema no longer has were skipped: ${stale.slice(0, 20).join(", ")}${stale.length > 20 ? ` and ${stale.length - 20} more` : ""}.`);
1895
+ fields = structuredClone(schemaMeta().fields);
1896
+ for (const [uid, entries] of Object.entries(code)) for (const [name, entry] of Object.entries(entries)) (fields[uid] ||= {})[name] = { ...fields[uid][name], ...entry };
1897
+ return fields;
1898
+ };
1899
+ let variants;
1900
+ const insertVariants = () => {
1901
+ if (variants !== void 0) return variants;
1902
+ const notes = [];
1903
+ variants = validateVariants(strapi.plugin(PLUGIN).config("components"), strapi.components || {}, notes);
1904
+ for (const note of notes) strapi.log?.warn(`[${PLUGIN}] components variants: ${note}.`);
1905
+ return variants;
1906
+ };
1907
+ const get = async () => mergeSaved(layer(projectDefaults(), await readSettings(strapi)), componentUids(strapi), contentTypeUids(strapi), apiUids(strapi), strapi.components);
1908
+ return {
1909
+ projectDefaults,
1910
+ get,
1911
+ fields: fieldTexts,
1912
+ schema: schemaMeta,
1913
+ variants: insertVariants,
1914
+ async set(value) {
1915
+ const next = validateSettings(value, componentUids(strapi), contentTypeUids(strapi), apiUids(strapi), strapi.components);
1916
+ for (const [uid, entry] of Object.entries(next.components)) {
1917
+ if (entry.mediaId && !await findMedia(strapi, entry.mediaId).catch(() => null)) fail(`Media for "${uid}" does not exist`);
1918
+ }
1919
+ await store(strapi).set({ key: "settings", value: overrides(next, projectDefaults()) });
1920
+ return next;
1921
+ },
1922
+ // Back to the project defaults (or the built-in ones); the legacy copy goes too, or it would be migrated again.
1923
+ async reset() {
1924
+ await store(strapi).delete({ key: "settings" });
1925
+ await strapi.store({ type: "plugin", name: LEGACY_PLUGIN }).delete({ key: "settings" });
1926
+ return get();
1927
+ }
1928
+ };
1929
+ }, ...STRAPI5 && { history: historyService, trash: trashService } },
359
1930
  controllers: {
360
1931
  catalog: ({ strapi }) => ({
361
1932
  async find(ctx) {
@@ -367,53 +1938,121 @@ module.exports = {
367
1938
  disabled: plugin.config("disabled"),
368
1939
  blockPreview: plugin.config("blockPreview"),
369
1940
  groups: plugin.config("groups"),
370
- componentUids: componentUids(strapi)
1941
+ componentUids: componentUids(strapi),
1942
+ schemas: strapi.components,
1943
+ blocks: plugin.service("settings").schema().blocks
371
1944
  });
372
1945
  const settings = await plugin.service("settings").get();
373
1946
  const media = await resolveMedia(strapi, settings);
1947
+ for (const [uid, list] of Object.entries(plugin.service("settings").variants())) base.components[uid] = { ...base.components[uid], variants: list };
374
1948
  for (const [uid, entry] of Object.entries(settings.components)) {
375
- base.components[uid] = { ...base.components[uid], ...media[uid], template: entry.template };
1949
+ base.components[uid] = {
1950
+ ...base.components[uid],
1951
+ ...media[uid],
1952
+ template: entry.template,
1953
+ ...entry.typology && { typology: entry.typology },
1954
+ ...entry.tags && { tags: entry.tags }
1955
+ };
376
1956
  }
1957
+ const hidden = hiddenName(plugin.config("hiddenAttribute")) || null;
1958
+ const types = Object.fromEntries(Object.entries(strapi.contentTypes || {}).filter(([uid]) => !uid.startsWith("admin::")).map(([uid, schema]) => [uid, [schema.info?.displayName || "", ...Object.keys(schema.attributes || {})]]));
1959
+ const history = STRAPI5 && strapi.documents?.use && !base.disabled && settings.history.enabled ? { contentTypes: apiUids(strapi).filter((uid) => covers(settings.history, uid)) } : null;
1960
+ const layouts = Object.fromEntries(Object.entries(settings.components).filter(([uid, entry]) => entry.layout && base.groups?.[uid]).map(([uid, entry]) => [uid, entry.layout]));
377
1961
  ctx.body = {
378
1962
  ...base,
1963
+ layouts,
379
1964
  palette: settings.palette,
380
- editor: { ...settings.editor, enabled: settings.editor.enabled && !base.disabled }
1965
+ contentTypes: settings.contentTypes,
1966
+ hiddenAttribute: hidden,
1967
+ fields: plugin.service("settings").fields(),
1968
+ types,
1969
+ history,
1970
+ editor: { ...settings.editor, enabled: settings.editor.enabled && !base.disabled, ...!hidden && { hiddenBlocks: "off" } }
381
1971
  };
382
1972
  }
383
1973
  }),
384
1974
  settings: ({ strapi }) => ({
385
1975
  async find(ctx) {
386
1976
  const settings = await strapi.plugin(PLUGIN).service("settings").get();
1977
+ const auto = catalog({ components: strapi.plugin(PLUGIN).config("components"), schemas: strapi.components, blocks: strapi.plugin(PLUGIN).service("settings").schema().blocks }).components;
387
1978
  const components = Object.entries(strapi.components || {}).map(([uid, schema]) => ({
388
1979
  uid,
389
1980
  displayName: schema.info?.displayName || uid,
390
- category: schema.category || uid.split(".")[0]
1981
+ category: schema.category || uid.split(".")[0],
1982
+ typology: auto[uid]?.typology,
1983
+ layoutFields: layoutFields(schema)
1984
+ }));
1985
+ const contentTypes = Object.keys(contentTypeUids(strapi)).map((uid) => ({
1986
+ uid,
1987
+ displayName: strapi.contentTypes[uid].info?.displayName || uid,
1988
+ kind: strapi.contentTypes[uid].kind,
1989
+ attributes: Object.entries(strapi.contentTypes[uid].attributes || {}).filter(([, attr]) => attr?.type !== "dynamiczone" && !attr?.private).map(([name, attr]) => ({ name, type: attr.type }))
391
1990
  }));
392
1991
  ctx.body = {
393
1992
  settings,
394
1993
  components,
1994
+ contentTypes,
395
1995
  media: await resolveMedia(strapi, settings),
396
1996
  templates: TEMPLATES,
1997
+ typologies: TYPOLOGIES,
397
1998
  disabled: strapi.plugin(PLUGIN).config("disabled") === true,
1999
+ hiddenAttribute: hiddenName(strapi.plugin(PLUGIN).config("hiddenAttribute")) || null,
398
2000
  blockPreviewAvailable: strapi.plugin(PLUGIN).config("blockPreview") === true,
399
- defaults: DEFAULTS
2001
+ defaults: DEFAULTS,
2002
+ projectDefaults: strapi.plugin(PLUGIN).service("settings").projectDefaults(),
2003
+ // Version history (Strapi 5 only): the content types it can cover.
2004
+ historyTypes: STRAPI5 && strapi.documents?.use ? apiUids(strapi).map((uid) => ({ uid, displayName: strapi.contentTypes[uid].info?.displayName || uid })) : null
400
2005
  };
401
2006
  },
402
2007
  async update(ctx) {
403
2008
  ctx.body = await strapi.plugin(PLUGIN).service("settings").set(ctx.request?.body);
2009
+ },
2010
+ async reset(ctx) {
2011
+ ctx.body = await strapi.plugin(PLUGIN).service("settings").reset();
404
2012
  }
405
- })
2013
+ }),
2014
+ prefs: ({ strapi }) => ({
2015
+ async find(ctx) {
2016
+ const id = ctx.state?.user?.id;
2017
+ if (!id) return ctx.unauthorized();
2018
+ ctx.body = mergePrefs(await store(strapi).get({ key: `prefs:${id}` }), componentUids(strapi));
2019
+ },
2020
+ async update(ctx) {
2021
+ const id = ctx.state?.user?.id;
2022
+ if (!id) return ctx.unauthorized();
2023
+ const value = validatePrefs(ctx.request?.body, componentUids(strapi));
2024
+ await store(strapi).set({ key: `prefs:${id}`, value });
2025
+ ctx.body = value;
2026
+ }
2027
+ }),
2028
+ ...STRAPI5 && { history: historyController, trash: trashController }
406
2029
  },
407
2030
  routes: { admin: { type: "admin", routes: [
408
2031
  { method: "GET", path: "/catalog", handler: "catalog.find", config: { policies: ["admin::isAuthenticatedAdmin"] } },
409
- ...["find", "update"].map((handler, index) => ({
410
- method: index ? "PUT" : "GET",
2032
+ ...["GET", "PUT"].map((method) => ({ method, path: "/me/prefs", handler: `prefs.${method === "GET" ? "find" : "update"}`, config: { policies: ["admin::isAuthenticatedAdmin"] } })),
2033
+ ...[["GET", "find", "read"], ["PUT", "update", "update"], ["DELETE", "reset", "update"]].map(([method, handler, action]) => ({
2034
+ method,
411
2035
  path: "/settings",
412
2036
  handler: `settings.${handler}`,
413
2037
  config: { policies: ["admin::isAuthenticatedAdmin", {
414
2038
  name: "admin::hasPermissions",
415
- config: { actions: [`plugin::${PLUGIN}.settings.${index ? "update" : "read"}`] }
2039
+ config: { actions: [`plugin::${PLUGIN}.settings.${action}`] }
416
2040
  }] }
417
- }))
2041
+ })),
2042
+ ...STRAPI5 ? [
2043
+ ["GET", "/history/:uid/:documentId", "history.list", "history.read"],
2044
+ ["GET", "/history-events/:id", "history.find", "history.read"],
2045
+ ["GET", "/activity", "history.activity", "activity.read"],
2046
+ ["GET", "/trash", "trash.list", "trash.read"],
2047
+ ["GET", "/trash/:id", "trash.find", "trash.read"],
2048
+ ["GET", "/trash/:id/check", "trash.check", "trash.restore"],
2049
+ ["POST", "/trash/:id/restore", "trash.restore", "trash.restore"],
2050
+ ["DELETE", "/trash/:id", "trash.remove", "trash.purge"]
2051
+ ].map(([method, path, handler, action]) => ({
2052
+ method,
2053
+ path,
2054
+ handler,
2055
+ config: { policies: ["admin::isAuthenticatedAdmin", { name: "admin::hasPermissions", config: { actions: [`plugin::${PLUGIN}.${action}`] } }] }
2056
+ })) : []
418
2057
  ] } }
419
2058
  };