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