@ozguraltan/strapi-content-input 1.0.21 → 1.0.22
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 +33 -7
- package/dist/admin/{AnalyticsHubPage-0p0Mx4AU.js → AnalyticsHubPage-B1_chQkG.js} +2 -2
- package/dist/admin/{AnalyticsHubPage-DsrcGI_Y.mjs → AnalyticsHubPage-DUj3D2kA.mjs} +2 -2
- package/dist/admin/{ContentInputField-CHXrzvE-.mjs → ContentInputField-BrtpTCDd.mjs} +365 -173
- package/dist/admin/{ContentInputField-7rWLSx_7.js → ContentInputField-CQFQxxgm.js} +365 -173
- package/dist/admin/{SurveyWidgetEditor-BmgYQaQS.js → SurveyWidgetEditor-C5Uvyf_h.js} +81 -31
- package/dist/admin/{SurveyWidgetEditor-BVN6X_3G.mjs → SurveyWidgetEditor-DGSwgTzR.mjs} +81 -31
- package/dist/admin/{index-hFIuYqu5.mjs → index-Dc7AFLOj.mjs} +2 -2
- package/dist/admin/{index-CZAwXCFH.js → index-i0NfSYto.js} +2 -2
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +1 -1
- package/dist/admin/src/components/common/CIImageSettingsControl.d.ts +17 -0
- package/dist/admin/src/components/widgets/CustomCardWidgetEditor.d.ts +1 -0
- package/dist/admin/src/components/widgets/HeroSliderStage.d.ts +3 -0
- package/dist/admin/src/core/canvasClasses.d.ts +1 -0
- package/dist/admin/src/core/types.d.ts +12 -0
- package/dist/server/index.js +1176 -184
- package/dist/server/index.mjs +1176 -184
- package/dist/server/src/config/index.d.ts +4 -0
- package/dist/server/src/controllers/ci-image.d.ts +11 -2
- package/dist/server/src/controllers/index.d.ts +1 -0
- package/dist/server/src/index.d.ts +5 -0
- package/dist/server/src/utils/image-variants.d.ts +74 -0
- package/package.json +1 -1
package/dist/server/index.js
CHANGED
|
@@ -36,6 +36,878 @@ const register = ({ strapi }) => {
|
|
|
36
36
|
});
|
|
37
37
|
}
|
|
38
38
|
};
|
|
39
|
+
const inFlightVariants = /* @__PURE__ */ new Map();
|
|
40
|
+
function getSharp() {
|
|
41
|
+
const req = typeof require !== "undefined" ? require : module$1.createRequire(path__default.default.join(process.cwd(), "package.json"));
|
|
42
|
+
return req("sharp");
|
|
43
|
+
}
|
|
44
|
+
function getVariantConfig(strapi) {
|
|
45
|
+
const pluginCfg = strapi?.config?.get?.("plugin::content-input") || {};
|
|
46
|
+
const envFolder = process.env.CI_IMAGE_VARIANT_FOLDER;
|
|
47
|
+
const rawFolder = envFolder !== void 0 && String(envFolder).trim() !== "" ? String(envFolder).trim() : pluginCfg.imageVariantFolder !== void 0 ? pluginCfg.imageVariantFolder : "ci-optimized";
|
|
48
|
+
let folder = "ci-optimized";
|
|
49
|
+
if (rawFolder === null || rawFolder === false || String(rawFolder).trim().toLowerCase() === "none" || String(rawFolder).trim() === "/") {
|
|
50
|
+
folder = null;
|
|
51
|
+
} else {
|
|
52
|
+
const cleaned = String(rawFolder).trim().replace(/^\/+|\/+$/g, "");
|
|
53
|
+
folder = cleaned || "ci-optimized";
|
|
54
|
+
}
|
|
55
|
+
const rawFmt = String(
|
|
56
|
+
process.env.CI_IMAGE_VARIANT_FORMAT || pluginCfg.imageVariantFormat || "webp"
|
|
57
|
+
).trim().toLowerCase();
|
|
58
|
+
const defaultFormat = rawFmt === "auto" ? "auto" : "webp";
|
|
59
|
+
const envRedirect = process.env.CI_IMAGE_REDIRECT_CDN;
|
|
60
|
+
const redirectProxyToCdn = envRedirect !== void 0 ? envRedirect !== "0" && envRedirect.toLowerCase() !== "false" : pluginCfg.redirectProxyToCdn !== false;
|
|
61
|
+
const defaultQuality = Math.min(
|
|
62
|
+
100,
|
|
63
|
+
Math.max(40, Number(pluginCfg.imageVariantQuality) || 85)
|
|
64
|
+
);
|
|
65
|
+
return {
|
|
66
|
+
folder,
|
|
67
|
+
defaultFormat,
|
|
68
|
+
redirectProxyToCdn,
|
|
69
|
+
defaultQuality
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
function isAbsoluteHttpUrl(url) {
|
|
73
|
+
return Boolean(url && /^https?:\/\//i.test(String(url).trim()));
|
|
74
|
+
}
|
|
75
|
+
function isOptimizableRasterImage(mime, urlOrName) {
|
|
76
|
+
const m = String(mime || "").trim().toLowerCase();
|
|
77
|
+
const u = String(urlOrName || "").split("?")[0].split("#")[0].trim().toLowerCase();
|
|
78
|
+
if (u.startsWith("data:") || u.startsWith("blob:")) return false;
|
|
79
|
+
if (m.includes("svg") || m.includes("gif") || m.startsWith("video/") || m.startsWith("audio/") || m.startsWith("application/") || m.startsWith("text/")) {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
if (/\.(svg|gif|mp4|webm|mov|m4v|mp3|wav|ogg|pdf|docx?|xlsx?|pptx?|zip|rar)$/i.test(u)) {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
if (m === "image/jpeg" || m === "image/jpg" || m === "image/png" || m === "image/webp" || m === "image/avif" || m === "image/tiff" || m === "image/bmp") {
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
if (/\.(jpe?g|png|webp|avif|tiff?|bmp)$/i.test(u)) {
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
if (m.startsWith("image/")) {
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
async function loadSourceBuffer(strapi, src) {
|
|
97
|
+
const publicDir = strapi?.dirs?.static?.public || path__default.default.join(process.cwd(), "public");
|
|
98
|
+
if (src.startsWith("/")) {
|
|
99
|
+
const cleanRel = decodeURIComponent(src.split("?")[0]).replace(/^\/+/, "");
|
|
100
|
+
const fullPath = path__default.default.resolve(publicDir, cleanRel);
|
|
101
|
+
const resolvedPublic = path__default.default.resolve(publicDir);
|
|
102
|
+
if (!fullPath.startsWith(resolvedPublic)) {
|
|
103
|
+
throw new Error("Invalid local file path");
|
|
104
|
+
}
|
|
105
|
+
if (!fs__default.default.existsSync(fullPath)) {
|
|
106
|
+
throw new Error(`File not found: ${src}`);
|
|
107
|
+
}
|
|
108
|
+
const buffer = await fs__default.default.promises.readFile(fullPath);
|
|
109
|
+
const ext = path__default.default.extname(fullPath).toLowerCase();
|
|
110
|
+
const mime = ext === ".png" ? "image/png" : ext === ".webp" ? "image/webp" : ext === ".avif" ? "image/avif" : ext === ".gif" ? "image/gif" : "image/jpeg";
|
|
111
|
+
return { buffer, mime };
|
|
112
|
+
}
|
|
113
|
+
if (/^https?:\/\//i.test(src)) {
|
|
114
|
+
const parsed = new URL(src);
|
|
115
|
+
if ((parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1") && parsed.pathname.startsWith("/uploads/")) {
|
|
116
|
+
const cleanRel = decodeURIComponent(parsed.pathname).replace(/^\/+/, "");
|
|
117
|
+
const fullPath = path__default.default.resolve(publicDir, cleanRel);
|
|
118
|
+
if (fs__default.default.existsSync(fullPath)) {
|
|
119
|
+
const buffer = await fs__default.default.promises.readFile(fullPath);
|
|
120
|
+
const ext = path__default.default.extname(fullPath).toLowerCase();
|
|
121
|
+
const mime = ext === ".png" ? "image/png" : ext === ".webp" ? "image/webp" : "image/jpeg";
|
|
122
|
+
return { buffer, mime };
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const res = await fetch(src);
|
|
126
|
+
if (!res.ok) {
|
|
127
|
+
throw new Error(`Failed to fetch remote image (${res.status})`);
|
|
128
|
+
}
|
|
129
|
+
const contentType = res.headers.get("content-type") || "image/jpeg";
|
|
130
|
+
const arr = await res.arrayBuffer();
|
|
131
|
+
return { buffer: Buffer.from(arr), mime: contentType };
|
|
132
|
+
}
|
|
133
|
+
throw new Error("Unsupported image source URL");
|
|
134
|
+
}
|
|
135
|
+
function normalizeImageProcessSpec(imageSettings, defaultAutoMaxW = 1920) {
|
|
136
|
+
const safeMaxW = Math.min(3840, Math.max(64, Math.round(Number(defaultAutoMaxW) || 1920)));
|
|
137
|
+
const rawProc = String(imageSettings?.process ?? "").trim().toLowerCase();
|
|
138
|
+
const rotate = parseInt(String(imageSettings?.rotate || "0"), 10) || 0;
|
|
139
|
+
const q = Math.min(100, Math.max(30, parseInt(String(imageSettings?.quality || "85"), 10) || 85));
|
|
140
|
+
if (rawProc === "none" || rawProc === "no-process" || rawProc === "original") {
|
|
141
|
+
return {
|
|
142
|
+
processMode: "none",
|
|
143
|
+
w: 0,
|
|
144
|
+
h: 0,
|
|
145
|
+
maxW: safeMaxW,
|
|
146
|
+
q,
|
|
147
|
+
rotate: 0
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
if (rawProc === "fit") {
|
|
151
|
+
const w = Math.min(3840, Math.max(0, Math.round(Number(imageSettings?.cWidth) || 0)));
|
|
152
|
+
const h = Math.min(3840, Math.max(0, Math.round(Number(imageSettings?.cHeight) || 0)));
|
|
153
|
+
if (w > 0 && h > 0) {
|
|
154
|
+
return { processMode: "fit", w, h, maxW: safeMaxW, q, rotate };
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (rawProc === "widen") {
|
|
158
|
+
const w = Math.min(3840, Math.max(0, Math.round(Number(imageSettings?.cWidth) || 0)));
|
|
159
|
+
if (w > 0) {
|
|
160
|
+
return { processMode: "widen", w, h: 0, maxW: safeMaxW, q, rotate };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const customAutoW = Number(imageSettings?.maxWidth || imageSettings?.cWidth);
|
|
164
|
+
const autoW = rawProc === "auto" && customAutoW > 0 ? Math.min(3840, Math.max(64, Math.round(customAutoW))) : safeMaxW;
|
|
165
|
+
return {
|
|
166
|
+
processMode: "auto",
|
|
167
|
+
w: autoW,
|
|
168
|
+
h: 0,
|
|
169
|
+
maxW: autoW,
|
|
170
|
+
q,
|
|
171
|
+
rotate
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
function computeCiFormatKey(processMode, w, h, rotate = 0) {
|
|
175
|
+
const effH = processMode === "fit" ? h : 0;
|
|
176
|
+
const effW = w;
|
|
177
|
+
return `ci_${processMode}_${effW}x${effH}${rotate ? `_r${rotate}` : ""}`;
|
|
178
|
+
}
|
|
179
|
+
function compactAssetFormats(formats) {
|
|
180
|
+
if (!formats || typeof formats !== "object") return void 0;
|
|
181
|
+
const out = {};
|
|
182
|
+
const keepStandard = /* @__PURE__ */ new Set(["thumbnail", "small", "medium", "large"]);
|
|
183
|
+
for (const [key, val] of Object.entries(formats)) {
|
|
184
|
+
if (!val || typeof val !== "object" || typeof val.url !== "string" || !val.url) continue;
|
|
185
|
+
if (!keepStandard.has(key) && !key.startsWith("ci_")) continue;
|
|
186
|
+
out[key] = {
|
|
187
|
+
url: val.url,
|
|
188
|
+
...val.width ? { width: Number(val.width) } : {},
|
|
189
|
+
...val.height ? { height: Number(val.height) } : {},
|
|
190
|
+
...val.mime ? { mime: String(val.mime) } : {},
|
|
191
|
+
...val.size ? { size: Number(val.size) } : {}
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
195
|
+
}
|
|
196
|
+
function stripVariantPrefixFromHash(baseNameNoExt) {
|
|
197
|
+
return baseNameNoExt.replace(/^ci_(?:fit|widen|auto)_\d+x\d+(?:_r-?\d+)?_/, "");
|
|
198
|
+
}
|
|
199
|
+
async function findUploadFileForAsset(strapi, assetOrUrl, cache) {
|
|
200
|
+
if (!assetOrUrl) return null;
|
|
201
|
+
const fileQuery = strapi.db.query("plugin::upload.file");
|
|
202
|
+
const isObj = typeof assetOrUrl === "object";
|
|
203
|
+
const rawId = isObj ? assetOrUrl.id : void 0;
|
|
204
|
+
const rawHash = isObj ? assetOrUrl.hash : void 0;
|
|
205
|
+
const rawUrl = isObj ? assetOrUrl.original_url || assetOrUrl.url || assetOrUrl.target_url || assetOrUrl.src || "" : String(assetOrUrl || "");
|
|
206
|
+
const cleanUrl = String(rawUrl || "").split("?")[0].split("#")[0].trim();
|
|
207
|
+
const cacheKey = rawId ? `id:${rawId}` : rawHash ? `hash:${rawHash}` : cleanUrl ? `url:${cleanUrl}` : "";
|
|
208
|
+
if (cache && cacheKey && cache.has(cacheKey)) {
|
|
209
|
+
return cache.get(cacheKey);
|
|
210
|
+
}
|
|
211
|
+
let found = null;
|
|
212
|
+
const remember = (record) => {
|
|
213
|
+
if (cache) {
|
|
214
|
+
if (cacheKey) cache.set(cacheKey, record);
|
|
215
|
+
if (record?.id) cache.set(`id:${record.id}`, record);
|
|
216
|
+
if (record?.hash) cache.set(`hash:${record.hash}`, record);
|
|
217
|
+
if (record?.url) cache.set(`url:${String(record.url).split("?")[0]}`, record);
|
|
218
|
+
}
|
|
219
|
+
return record;
|
|
220
|
+
};
|
|
221
|
+
if (rawId !== void 0 && rawId !== null && rawId !== "") {
|
|
222
|
+
const numId = Number(rawId);
|
|
223
|
+
if (!Number.isNaN(numId) && numId > 0) {
|
|
224
|
+
found = await fileQuery.findOne({ where: { id: numId } });
|
|
225
|
+
if (found) return remember(found);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
if (rawHash && typeof rawHash === "string") {
|
|
229
|
+
const parentHash = stripVariantPrefixFromHash(rawHash.trim());
|
|
230
|
+
found = await fileQuery.findOne({ where: { hash: parentHash } });
|
|
231
|
+
if (found) return remember(found);
|
|
232
|
+
}
|
|
233
|
+
if (!cleanUrl) return remember(null);
|
|
234
|
+
found = await fileQuery.findOne({ where: { url: cleanUrl } });
|
|
235
|
+
if (found) return remember(found);
|
|
236
|
+
let pathnameStr = cleanUrl;
|
|
237
|
+
if (/^https?:\/\//i.test(cleanUrl)) {
|
|
238
|
+
try {
|
|
239
|
+
pathnameStr = decodeURIComponent(new URL(cleanUrl).pathname);
|
|
240
|
+
} catch {
|
|
241
|
+
pathnameStr = cleanUrl;
|
|
242
|
+
}
|
|
243
|
+
if (pathnameStr && pathnameStr !== cleanUrl) {
|
|
244
|
+
found = await fileQuery.findOne({ where: { url: pathnameStr } });
|
|
245
|
+
if (found) return remember(found);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
const baseName = path__default.default.posix.basename(pathnameStr);
|
|
249
|
+
const ext = path__default.default.posix.extname(baseName);
|
|
250
|
+
const baseNoExt = ext ? baseName.slice(0, -ext.length) : baseName;
|
|
251
|
+
if (baseNoExt) {
|
|
252
|
+
const candidateHash = stripVariantPrefixFromHash(baseNoExt);
|
|
253
|
+
if (candidateHash) {
|
|
254
|
+
found = await fileQuery.findOne({ where: { hash: candidateHash } });
|
|
255
|
+
if (found) return remember(found);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return remember(null);
|
|
259
|
+
}
|
|
260
|
+
async function renderSharpVariantBuffer(sourceBuffer, sourceMime, opts) {
|
|
261
|
+
const sharp = getSharp();
|
|
262
|
+
let pipeline = sharp(sourceBuffer, { failOn: "none" }).rotate();
|
|
263
|
+
const rotate = opts.rotate || 0;
|
|
264
|
+
if (rotate && [90, 180, 270, -90].includes(rotate)) {
|
|
265
|
+
pipeline = pipeline.rotate(rotate);
|
|
266
|
+
}
|
|
267
|
+
const cw = opts.cw || 0;
|
|
268
|
+
const ch = opts.ch || 0;
|
|
269
|
+
if (cw > 0 && ch > 0) {
|
|
270
|
+
pipeline = pipeline.extract({
|
|
271
|
+
left: Math.max(0, opts.cx || 0),
|
|
272
|
+
top: Math.max(0, opts.cy || 0),
|
|
273
|
+
width: cw,
|
|
274
|
+
height: ch
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
const { processMode, w, h, q } = opts;
|
|
278
|
+
if (processMode === "fit" && w > 0 && h > 0) {
|
|
279
|
+
pipeline = pipeline.resize(w, h, {
|
|
280
|
+
fit: "cover",
|
|
281
|
+
position: "centre",
|
|
282
|
+
withoutEnlargement: false
|
|
283
|
+
});
|
|
284
|
+
} else if (processMode === "widen" && w > 0) {
|
|
285
|
+
pipeline = pipeline.resize(w, null, {
|
|
286
|
+
fit: "inside",
|
|
287
|
+
withoutEnlargement: false
|
|
288
|
+
});
|
|
289
|
+
} else if (processMode === "auto" && w > 0) {
|
|
290
|
+
pipeline = pipeline.resize(w, null, {
|
|
291
|
+
fit: "inside",
|
|
292
|
+
withoutEnlargement: true
|
|
293
|
+
});
|
|
294
|
+
} else if (w > 0 || h > 0) {
|
|
295
|
+
pipeline = pipeline.resize(w || null, h || null, {
|
|
296
|
+
fit: "inside",
|
|
297
|
+
withoutEnlargement: true
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
const reqFmt = String(opts.requestedFormat || "").trim().toLowerCase();
|
|
301
|
+
const preferWebp = reqFmt === "webp" || !reqFmt && (opts.defaultFormat || "webp") === "webp";
|
|
302
|
+
let contentType = sourceMime || "image/webp";
|
|
303
|
+
let ext = ".webp";
|
|
304
|
+
if (reqFmt === "avif") {
|
|
305
|
+
pipeline = pipeline.avif({ quality: q });
|
|
306
|
+
contentType = "image/avif";
|
|
307
|
+
ext = ".avif";
|
|
308
|
+
} else if (reqFmt === "png") {
|
|
309
|
+
pipeline = pipeline.png({ quality: q });
|
|
310
|
+
contentType = "image/png";
|
|
311
|
+
ext = ".png";
|
|
312
|
+
} else if (reqFmt === "jpg" || reqFmt === "jpeg") {
|
|
313
|
+
pipeline = pipeline.jpeg({ quality: q, mozjpeg: true });
|
|
314
|
+
contentType = "image/jpeg";
|
|
315
|
+
ext = ".jpg";
|
|
316
|
+
} else if (preferWebp || sourceMime === "image/webp") {
|
|
317
|
+
pipeline = pipeline.webp({ quality: q, alphaQuality: 100, effort: 4 });
|
|
318
|
+
contentType = "image/webp";
|
|
319
|
+
ext = ".webp";
|
|
320
|
+
} else if (sourceMime === "image/avif") {
|
|
321
|
+
pipeline = pipeline.avif({ quality: q });
|
|
322
|
+
contentType = "image/avif";
|
|
323
|
+
ext = ".avif";
|
|
324
|
+
} else if (sourceMime === "image/png") {
|
|
325
|
+
pipeline = pipeline.png({ quality: q });
|
|
326
|
+
contentType = "image/png";
|
|
327
|
+
ext = ".png";
|
|
328
|
+
} else {
|
|
329
|
+
pipeline = pipeline.jpeg({ quality: q, mozjpeg: true });
|
|
330
|
+
contentType = "image/jpeg";
|
|
331
|
+
ext = ".jpg";
|
|
332
|
+
}
|
|
333
|
+
const outputBuffer = await pipeline.toBuffer();
|
|
334
|
+
const outMeta = await sharp(outputBuffer).metadata();
|
|
335
|
+
return {
|
|
336
|
+
buffer: outputBuffer,
|
|
337
|
+
contentType,
|
|
338
|
+
ext,
|
|
339
|
+
width: outMeta.width || w || void 0,
|
|
340
|
+
height: outMeta.height || h || void 0
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
async function ensureMediaVariant(strapi, existingFile, spec) {
|
|
344
|
+
const formatKey = computeCiFormatKey(
|
|
345
|
+
spec.processMode,
|
|
346
|
+
spec.w,
|
|
347
|
+
spec.h,
|
|
348
|
+
spec.rotate || 0
|
|
349
|
+
);
|
|
350
|
+
if (!existingFile?.id || !existingFile?.url) {
|
|
351
|
+
return { formatKey, formatEntry: null, updatedFile: existingFile };
|
|
352
|
+
}
|
|
353
|
+
if (!isOptimizableRasterImage(existingFile.mime, existingFile.ext || existingFile.url)) {
|
|
354
|
+
return { formatKey, formatEntry: null, updatedFile: existingFile };
|
|
355
|
+
}
|
|
356
|
+
const already = existingFile.formats?.[formatKey];
|
|
357
|
+
if (already?.url) {
|
|
358
|
+
return { formatKey, formatEntry: already, updatedFile: existingFile };
|
|
359
|
+
}
|
|
360
|
+
const lockKey = `${existingFile.id}:${formatKey}`;
|
|
361
|
+
const activePromise = inFlightVariants.get(lockKey);
|
|
362
|
+
if (activePromise) {
|
|
363
|
+
return activePromise;
|
|
364
|
+
}
|
|
365
|
+
const task = (async () => {
|
|
366
|
+
const cfg = getVariantConfig(strapi);
|
|
367
|
+
const freshCheck = await strapi.db.query("plugin::upload.file").findOne({
|
|
368
|
+
where: { id: existingFile.id }
|
|
369
|
+
});
|
|
370
|
+
const baseRecord = freshCheck || existingFile;
|
|
371
|
+
if (baseRecord.formats?.[formatKey]?.url) {
|
|
372
|
+
return {
|
|
373
|
+
formatKey,
|
|
374
|
+
formatEntry: baseRecord.formats[formatKey],
|
|
375
|
+
updatedFile: baseRecord
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
const { buffer: sourceBuffer, mime: sourceMime } = await loadSourceBuffer(
|
|
379
|
+
strapi,
|
|
380
|
+
baseRecord.url
|
|
381
|
+
);
|
|
382
|
+
const rendered = await renderSharpVariantBuffer(
|
|
383
|
+
sourceBuffer,
|
|
384
|
+
baseRecord.mime || sourceMime,
|
|
385
|
+
{
|
|
386
|
+
processMode: spec.processMode,
|
|
387
|
+
w: spec.w,
|
|
388
|
+
h: spec.h,
|
|
389
|
+
q: spec.q || cfg.defaultQuality,
|
|
390
|
+
rotate: spec.rotate || 0,
|
|
391
|
+
requestedFormat: spec.requestedFormat,
|
|
392
|
+
defaultFormat: cfg.defaultFormat
|
|
393
|
+
}
|
|
394
|
+
);
|
|
395
|
+
const fallbackShortHash = crypto__default.default.createHash("sha1").update(String(baseRecord.url)).digest("hex").slice(0, 10);
|
|
396
|
+
const cleanBaseName = path__default.default.basename(
|
|
397
|
+
baseRecord.name || "image",
|
|
398
|
+
path__default.default.extname(baseRecord.name || "")
|
|
399
|
+
);
|
|
400
|
+
const variantHash = `${formatKey}_${baseRecord.hash || fallbackShortHash}`;
|
|
401
|
+
const variantName = `${formatKey}_${cleanBaseName}${rendered.ext}`;
|
|
402
|
+
const tmpVariantPath = path__default.default.join(
|
|
403
|
+
os__default.default.tmpdir(),
|
|
404
|
+
`${variantHash}_${Date.now()}_${Math.random().toString(36).slice(2, 6)}${rendered.ext}`
|
|
405
|
+
);
|
|
406
|
+
await fs__default.default.promises.writeFile(tmpVariantPath, rendered.buffer);
|
|
407
|
+
try {
|
|
408
|
+
const variantFile = {
|
|
409
|
+
name: variantName,
|
|
410
|
+
hash: variantHash,
|
|
411
|
+
ext: rendered.ext,
|
|
412
|
+
mime: rendered.contentType,
|
|
413
|
+
filepath: tmpVariantPath,
|
|
414
|
+
path: cfg.folder !== null ? cfg.folder : baseRecord.path || null,
|
|
415
|
+
getStream: () => fs__default.default.createReadStream(tmpVariantPath),
|
|
416
|
+
width: rendered.width,
|
|
417
|
+
height: rendered.height,
|
|
418
|
+
size: Math.round(rendered.buffer.length / 1e3 * 100) / 100,
|
|
419
|
+
sizeInBytes: rendered.buffer.length
|
|
420
|
+
};
|
|
421
|
+
const providerService = strapi.plugin("upload").service("provider");
|
|
422
|
+
if (!providerService || typeof providerService.upload !== "function") {
|
|
423
|
+
return { formatKey, formatEntry: null, updatedFile: baseRecord };
|
|
424
|
+
}
|
|
425
|
+
await providerService.upload(variantFile);
|
|
426
|
+
const { filepath: _fp, getStream: _gs, ...serializableFormat } = variantFile;
|
|
427
|
+
const latestRecord = await strapi.db.query("plugin::upload.file").findOne({
|
|
428
|
+
where: { id: baseRecord.id }
|
|
429
|
+
}) || baseRecord;
|
|
430
|
+
const nextFormats = {
|
|
431
|
+
...latestRecord.formats || {},
|
|
432
|
+
[formatKey]: serializableFormat
|
|
433
|
+
};
|
|
434
|
+
const updatedFile = await strapi.db.query("plugin::upload.file").update({
|
|
435
|
+
where: { id: baseRecord.id },
|
|
436
|
+
data: { formats: nextFormats }
|
|
437
|
+
});
|
|
438
|
+
existingFile.formats = nextFormats;
|
|
439
|
+
return {
|
|
440
|
+
formatKey,
|
|
441
|
+
formatEntry: serializableFormat,
|
|
442
|
+
updatedFile: updatedFile || { ...latestRecord, formats: nextFormats }
|
|
443
|
+
};
|
|
444
|
+
} finally {
|
|
445
|
+
await fs__default.default.promises.rm(tmpVariantPath, { force: true }).catch(() => void 0);
|
|
446
|
+
}
|
|
447
|
+
})();
|
|
448
|
+
inFlightVariants.set(lockKey, task);
|
|
449
|
+
try {
|
|
450
|
+
return await task;
|
|
451
|
+
} finally {
|
|
452
|
+
inFlightVariants.delete(lockKey);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
async function clearGeneratedCiVariantsForFile(strapi, fileRecord) {
|
|
456
|
+
if (!fileRecord?.id || !fileRecord?.formats || typeof fileRecord.formats !== "object") {
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
const providerService = strapi.plugin("upload")?.service?.("provider");
|
|
460
|
+
const nextFormats = {};
|
|
461
|
+
const removedFormats = [];
|
|
462
|
+
for (const [k, fmt] of Object.entries(fileRecord.formats)) {
|
|
463
|
+
if (k.startsWith("ci_")) {
|
|
464
|
+
removedFormats.push(fmt);
|
|
465
|
+
} else {
|
|
466
|
+
nextFormats[k] = fmt;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
if (removedFormats.length === 0) return;
|
|
470
|
+
if (providerService && typeof providerService.delete === "function") {
|
|
471
|
+
for (const fmt of removedFormats) {
|
|
472
|
+
try {
|
|
473
|
+
await providerService.delete(fmt);
|
|
474
|
+
} catch {
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
await strapi.db.query("plugin::upload.file").update({
|
|
479
|
+
where: { id: fileRecord.id },
|
|
480
|
+
data: { formats: nextFormats }
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
async function enrichMediaAssetNode(strapi, asset, opts = {}) {
|
|
484
|
+
if (!asset) return asset;
|
|
485
|
+
const isStringInput = typeof asset === "string";
|
|
486
|
+
const rawUrl = isStringInput ? asset : asset.original_url || asset.url || asset.target_url || asset.src || "";
|
|
487
|
+
if (!rawUrl || typeof rawUrl !== "string") return asset;
|
|
488
|
+
const fileRecord = await findUploadFileForAsset(strapi, asset, opts.fileCache);
|
|
489
|
+
if (!fileRecord) {
|
|
490
|
+
return asset;
|
|
491
|
+
}
|
|
492
|
+
const canonicalMasterUrl = fileRecord.url || rawUrl;
|
|
493
|
+
if (!isOptimizableRasterImage(fileRecord.mime, fileRecord.ext || canonicalMasterUrl)) {
|
|
494
|
+
if (isStringInput) return canonicalMasterUrl;
|
|
495
|
+
return {
|
|
496
|
+
...asset,
|
|
497
|
+
id: fileRecord.id,
|
|
498
|
+
hash: fileRecord.hash,
|
|
499
|
+
original_url: canonicalMasterUrl,
|
|
500
|
+
url: canonicalMasterUrl,
|
|
501
|
+
target_url: canonicalMasterUrl
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
const spec = normalizeImageProcessSpec(
|
|
505
|
+
opts.imageSettings,
|
|
506
|
+
opts.defaultAutoMaxW || 1920
|
|
507
|
+
);
|
|
508
|
+
let latestFile = fileRecord;
|
|
509
|
+
let activeVariantUrl;
|
|
510
|
+
if (spec.processMode !== "none") {
|
|
511
|
+
try {
|
|
512
|
+
const primary = await ensureMediaVariant(strapi, latestFile, {
|
|
513
|
+
processMode: spec.processMode,
|
|
514
|
+
w: spec.w,
|
|
515
|
+
h: spec.h,
|
|
516
|
+
q: spec.q,
|
|
517
|
+
rotate: spec.rotate
|
|
518
|
+
});
|
|
519
|
+
latestFile = primary.updatedFile || latestFile;
|
|
520
|
+
if (primary.formatEntry?.url) {
|
|
521
|
+
activeVariantUrl = primary.formatEntry.url;
|
|
522
|
+
}
|
|
523
|
+
} catch (err) {
|
|
524
|
+
strapi.log?.warn?.(
|
|
525
|
+
`[content-input] Image variant generation skipped for "${canonicalMasterUrl}": ${err?.message || err}`
|
|
526
|
+
);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
if (opts.alsoEnsureAutoMaxW && opts.alsoEnsureAutoMaxW > 0 && spec.processMode !== "none" && !(spec.processMode === "auto" && spec.w === opts.alsoEnsureAutoMaxW)) {
|
|
530
|
+
try {
|
|
531
|
+
const secondary = await ensureMediaVariant(strapi, latestFile, {
|
|
532
|
+
processMode: "auto",
|
|
533
|
+
w: opts.alsoEnsureAutoMaxW,
|
|
534
|
+
h: 0,
|
|
535
|
+
q: spec.q
|
|
536
|
+
});
|
|
537
|
+
latestFile = secondary.updatedFile || latestFile;
|
|
538
|
+
} catch {
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
if (opts.fileCache && latestFile?.id) {
|
|
542
|
+
opts.fileCache.set(`id:${latestFile.id}`, latestFile);
|
|
543
|
+
if (latestFile.hash) opts.fileCache.set(`hash:${latestFile.hash}`, latestFile);
|
|
544
|
+
if (latestFile.url) opts.fileCache.set(`url:${String(latestFile.url).split("?")[0]}`, latestFile);
|
|
545
|
+
}
|
|
546
|
+
const compactFormats = compactAssetFormats(latestFile.formats);
|
|
547
|
+
if (isStringInput) {
|
|
548
|
+
return activeVariantUrl || canonicalMasterUrl;
|
|
549
|
+
}
|
|
550
|
+
const nextAsset = {
|
|
551
|
+
...asset,
|
|
552
|
+
id: latestFile.id,
|
|
553
|
+
hash: latestFile.hash,
|
|
554
|
+
original_url: canonicalMasterUrl,
|
|
555
|
+
url: canonicalMasterUrl,
|
|
556
|
+
target_url: canonicalMasterUrl,
|
|
557
|
+
filename: asset.filename || asset.name || latestFile.name || "image",
|
|
558
|
+
mime_type: asset.mime_type || latestFile.mime || "image/webp",
|
|
559
|
+
width: asset.width || latestFile.width || void 0,
|
|
560
|
+
height: asset.height || latestFile.height || void 0
|
|
561
|
+
};
|
|
562
|
+
if (spec.processMode === "none") {
|
|
563
|
+
delete nextAsset.optimized_url;
|
|
564
|
+
} else if (activeVariantUrl) {
|
|
565
|
+
nextAsset.optimized_url = activeVariantUrl;
|
|
566
|
+
}
|
|
567
|
+
if (compactFormats) {
|
|
568
|
+
nextAsset.formats = compactFormats;
|
|
569
|
+
}
|
|
570
|
+
return nextAsset;
|
|
571
|
+
}
|
|
572
|
+
async function runWithConcurrency(tasks, concurrency = 3) {
|
|
573
|
+
const results = new Array(tasks.length);
|
|
574
|
+
let cursor = 0;
|
|
575
|
+
async function worker() {
|
|
576
|
+
while (cursor < tasks.length) {
|
|
577
|
+
const idx = cursor++;
|
|
578
|
+
results[idx] = await tasks[idx]();
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
const poolSize = Math.min(Math.max(1, concurrency), tasks.length);
|
|
582
|
+
await Promise.all(Array.from({ length: poolSize }, () => worker()));
|
|
583
|
+
return results;
|
|
584
|
+
}
|
|
585
|
+
async function optimizeHtmlImgSources(strapi, html, fileCache) {
|
|
586
|
+
if (!html || typeof html !== "string" || !html.includes("<img")) return html;
|
|
587
|
+
const imgRegex = /(<img\b[^>]*?\bsrc=(["']))([^"']+)(\2[^>]*>)/gi;
|
|
588
|
+
const matches = Array.from(html.matchAll(imgRegex));
|
|
589
|
+
if (matches.length === 0) return html;
|
|
590
|
+
const replacements = /* @__PURE__ */ new Map();
|
|
591
|
+
const uniqueSrcs = Array.from(new Set(matches.map((m) => m[3]).filter(Boolean)));
|
|
592
|
+
await runWithConcurrency(
|
|
593
|
+
uniqueSrcs.map((srcUrl) => async () => {
|
|
594
|
+
if (!isOptimizableRasterImage(void 0, srcUrl)) return;
|
|
595
|
+
const fileRecord = await findUploadFileForAsset(strapi, srcUrl, fileCache);
|
|
596
|
+
if (!fileRecord) return;
|
|
597
|
+
if (!isOptimizableRasterImage(fileRecord.mime, fileRecord.ext || fileRecord.url)) return;
|
|
598
|
+
try {
|
|
599
|
+
const res = await ensureMediaVariant(strapi, fileRecord, {
|
|
600
|
+
processMode: "auto",
|
|
601
|
+
w: 1600,
|
|
602
|
+
h: 0
|
|
603
|
+
});
|
|
604
|
+
if (res.formatEntry?.url) {
|
|
605
|
+
replacements.set(srcUrl, res.formatEntry.url);
|
|
606
|
+
}
|
|
607
|
+
} catch {
|
|
608
|
+
}
|
|
609
|
+
}),
|
|
610
|
+
3
|
|
611
|
+
);
|
|
612
|
+
if (replacements.size === 0) return html;
|
|
613
|
+
return html.replace(imgRegex, (full, prefix, _quote, srcVal, suffix) => {
|
|
614
|
+
const nextUrl = replacements.get(srcVal);
|
|
615
|
+
return nextUrl ? `${prefix}${nextUrl}${suffix}` : full;
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
async function syncContentInputTreeMedia(strapi, rawValue) {
|
|
619
|
+
if (!rawValue) return rawValue;
|
|
620
|
+
const wasString = typeof rawValue === "string";
|
|
621
|
+
let parsed = rawValue;
|
|
622
|
+
if (wasString) {
|
|
623
|
+
const trimmed = rawValue.trim();
|
|
624
|
+
if (!trimmed) return rawValue;
|
|
625
|
+
try {
|
|
626
|
+
parsed = JSON.parse(trimmed);
|
|
627
|
+
} catch {
|
|
628
|
+
return rawValue;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
if (!Array.isArray(parsed)) {
|
|
632
|
+
return rawValue;
|
|
633
|
+
}
|
|
634
|
+
const rows = JSON.parse(JSON.stringify(parsed));
|
|
635
|
+
const fileCache = /* @__PURE__ */ new Map();
|
|
636
|
+
const jobs = [];
|
|
637
|
+
const scheduleAsset = (holder, key, opts) => {
|
|
638
|
+
const current = holder?.[key];
|
|
639
|
+
if (!current) return;
|
|
640
|
+
jobs.push(async () => {
|
|
641
|
+
holder[key] = await enrichMediaAssetNode(strapi, current, {
|
|
642
|
+
...opts,
|
|
643
|
+
fileCache
|
|
644
|
+
});
|
|
645
|
+
});
|
|
646
|
+
};
|
|
647
|
+
const scheduleHtml = (holder, key) => {
|
|
648
|
+
const val = holder?.[key];
|
|
649
|
+
if (typeof val !== "string" || !val.includes("<img")) return;
|
|
650
|
+
jobs.push(async () => {
|
|
651
|
+
holder[key] = await optimizeHtmlImgSources(strapi, val, fileCache);
|
|
652
|
+
});
|
|
653
|
+
};
|
|
654
|
+
const walkRows = (rowList) => {
|
|
655
|
+
if (!Array.isArray(rowList)) return;
|
|
656
|
+
for (const row of rowList) {
|
|
657
|
+
if (!row || typeof row !== "object") continue;
|
|
658
|
+
if (row.bgImage) {
|
|
659
|
+
scheduleAsset(row, "bgImage", {
|
|
660
|
+
imageSettings: row.bgOptions?.imageSettings,
|
|
661
|
+
defaultAutoMaxW: 1920
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
const blocks = Array.isArray(row.blocks) ? row.blocks : [];
|
|
665
|
+
for (const block of blocks) {
|
|
666
|
+
if (!block || typeof block !== "object") continue;
|
|
667
|
+
if (block.bgImage) {
|
|
668
|
+
scheduleAsset(block, "bgImage", {
|
|
669
|
+
imageSettings: block.bgOptions?.imageSettings,
|
|
670
|
+
defaultAutoMaxW: 1920
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
const widgets = Array.isArray(block.widgets) ? block.widgets : [];
|
|
674
|
+
for (const widget of widgets) {
|
|
675
|
+
if (!widget || typeof widget !== "object") continue;
|
|
676
|
+
const wId = widget.id;
|
|
677
|
+
const wOpts = widget.options || {};
|
|
678
|
+
const wData = widget.data;
|
|
679
|
+
if (wId === "gallery") {
|
|
680
|
+
const list = Array.isArray(wData) ? wData : Array.isArray(wData?.images) ? wData.images : null;
|
|
681
|
+
if (list) {
|
|
682
|
+
const popupEnabled = wOpts.popup !== false;
|
|
683
|
+
for (let i = 0; i < list.length; i++) {
|
|
684
|
+
scheduleAsset(list, i, {
|
|
685
|
+
imageSettings: wOpts.imageSettings,
|
|
686
|
+
defaultAutoMaxW: 1600,
|
|
687
|
+
alsoEnsureAutoMaxW: popupEnabled ? 1920 : 0
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
} else if (wId === "singleImage" && wData && typeof wData === "object") {
|
|
692
|
+
if (wData.image) {
|
|
693
|
+
scheduleAsset(wData, "image", {
|
|
694
|
+
imageSettings: wOpts.imageSettings || wData.imageSettings,
|
|
695
|
+
defaultAutoMaxW: 1920
|
|
696
|
+
});
|
|
697
|
+
} else if (wData.url || wData.target_url) {
|
|
698
|
+
scheduleAsset(widget, "data", {
|
|
699
|
+
imageSettings: wOpts.imageSettings,
|
|
700
|
+
defaultAutoMaxW: 1920
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
} else if (wId === "banner" && wData && typeof wData === "object") {
|
|
704
|
+
if (wData.image) {
|
|
705
|
+
scheduleAsset(wData, "image", {
|
|
706
|
+
imageSettings: wOpts.imageSettings || wData.imageSettings,
|
|
707
|
+
defaultAutoMaxW: 1920
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
} else if (wId === "youtubeVideo") {
|
|
711
|
+
if (wOpts.thumbnailImage) {
|
|
712
|
+
scheduleAsset(wOpts, "thumbnailImage", {
|
|
713
|
+
imageSettings: wOpts.imageSettings,
|
|
714
|
+
defaultAutoMaxW: 1280
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
if (Array.isArray(wData)) {
|
|
718
|
+
for (const vid of wData) {
|
|
719
|
+
if (vid && typeof vid === "object" && vid.customThumbnail) {
|
|
720
|
+
scheduleAsset(vid, "customThumbnail", {
|
|
721
|
+
imageSettings: wOpts.imageSettings,
|
|
722
|
+
defaultAutoMaxW: 1280
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
} else if (wData && typeof wData === "object" && wData.customThumbnail) {
|
|
727
|
+
scheduleAsset(wData, "customThumbnail", {
|
|
728
|
+
imageSettings: wOpts.imageSettings,
|
|
729
|
+
defaultAutoMaxW: 1280
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
} else if (wId === "heroSlider" && wData && typeof wData === "object") {
|
|
733
|
+
const globalHeroImgSettings = wData.settings?.imageSettings || wOpts.imageSettings;
|
|
734
|
+
const slides = Array.isArray(wData.slides) ? wData.slides : [];
|
|
735
|
+
for (const slide of slides) {
|
|
736
|
+
if (!slide || typeof slide !== "object") continue;
|
|
737
|
+
if (slide.bgImage) {
|
|
738
|
+
scheduleAsset(slide, "bgImage", {
|
|
739
|
+
imageSettings: slide.imageSettings || globalHeroImgSettings,
|
|
740
|
+
defaultAutoMaxW: 1920
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
if (slide.mobileBgImage) {
|
|
744
|
+
scheduleAsset(slide, "mobileBgImage", {
|
|
745
|
+
imageSettings: slide.mobileImageSettings,
|
|
746
|
+
defaultAutoMaxW: 1080
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
const layers = Array.isArray(slide.layers) ? slide.layers : [];
|
|
750
|
+
for (const layer of layers) {
|
|
751
|
+
if (layer && typeof layer === "object" && layer.image) {
|
|
752
|
+
scheduleAsset(layer, "image", {
|
|
753
|
+
imageSettings: layer.imageSettings,
|
|
754
|
+
defaultAutoMaxW: 1200
|
|
755
|
+
});
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
} else if (wId === "customCard" && wData && typeof wData === "object") {
|
|
760
|
+
const cardImgSettings = wData.design?.imageSettings || wOpts.imageSettings;
|
|
761
|
+
const cards = Array.isArray(wData.cards) ? wData.cards : [];
|
|
762
|
+
for (const card of cards) {
|
|
763
|
+
if (!card || typeof card !== "object") continue;
|
|
764
|
+
if (card.image) {
|
|
765
|
+
scheduleAsset(card, "image", {
|
|
766
|
+
imageSettings: cardImgSettings,
|
|
767
|
+
defaultAutoMaxW: 960
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
if (card.authorAvatar) {
|
|
771
|
+
scheduleAsset(card, "authorAvatar", {
|
|
772
|
+
imageSettings: { process: "fit", cWidth: 240, cHeight: 240 },
|
|
773
|
+
defaultAutoMaxW: 240
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
} else if (wId === "entityCard" && wData && typeof wData === "object") {
|
|
778
|
+
const ecImgSettings = wOpts.imageSettings || wOpts.cardProps?.imageSettings;
|
|
779
|
+
if (wData.overrides?.image) {
|
|
780
|
+
scheduleAsset(wData.overrides, "image", {
|
|
781
|
+
imageSettings: ecImgSettings,
|
|
782
|
+
defaultAutoMaxW: 960
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
if (wData.entity?.image) {
|
|
786
|
+
scheduleAsset(wData.entity, "image", {
|
|
787
|
+
imageSettings: ecImgSettings,
|
|
788
|
+
defaultAutoMaxW: 960
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
if (Array.isArray(wData.items)) {
|
|
792
|
+
for (const item of wData.items) {
|
|
793
|
+
if (!item || typeof item !== "object") continue;
|
|
794
|
+
if (item.overrides?.image) {
|
|
795
|
+
scheduleAsset(item.overrides, "image", {
|
|
796
|
+
imageSettings: ecImgSettings,
|
|
797
|
+
defaultAutoMaxW: 960
|
|
798
|
+
});
|
|
799
|
+
}
|
|
800
|
+
if (item.entity?.image) {
|
|
801
|
+
scheduleAsset(item.entity, "image", {
|
|
802
|
+
imageSettings: ecImgSettings,
|
|
803
|
+
defaultAutoMaxW: 960
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
} else if (wId === "HtmlEditor") {
|
|
809
|
+
if (typeof wData === "string") {
|
|
810
|
+
scheduleHtml(widget, "data");
|
|
811
|
+
} else if (wData && typeof wData === "object" && typeof wData.content === "string") {
|
|
812
|
+
scheduleHtml(wData, "content");
|
|
813
|
+
}
|
|
814
|
+
} else if (wId === "tab" || wId === "accordion") {
|
|
815
|
+
const nodes = Array.isArray(wData) ? wData : Array.isArray(wData?.nodes) ? wData.nodes : Array.isArray(wData?.tabs) ? wData.tabs : [];
|
|
816
|
+
for (const node of nodes) {
|
|
817
|
+
if (!node || typeof node !== "object") continue;
|
|
818
|
+
if (Array.isArray(node.rows)) walkRows(node.rows);
|
|
819
|
+
if (Array.isArray(node.content)) walkRows(node.content);
|
|
820
|
+
if (Array.isArray(node.content?.data)) walkRows(node.content.data);
|
|
821
|
+
if (typeof node.html === "string") scheduleHtml(node, "html");
|
|
822
|
+
if (typeof node.content === "string") scheduleHtml(node, "content");
|
|
823
|
+
if (typeof node.content?.html === "string") scheduleHtml(node.content, "html");
|
|
824
|
+
}
|
|
825
|
+
} else if (wId === "survey" && wData && typeof wData === "object") {
|
|
826
|
+
const qLists = [wData.questions, wData.survey?.questions].filter(Array.isArray);
|
|
827
|
+
for (const qList of qLists) {
|
|
828
|
+
for (const q of qList) {
|
|
829
|
+
if (!q || typeof q !== "object" || !Array.isArray(q.options)) continue;
|
|
830
|
+
for (const opt of q.options) {
|
|
831
|
+
if (opt && typeof opt === "object" && opt.image) {
|
|
832
|
+
scheduleAsset(opt, "image", {
|
|
833
|
+
defaultAutoMaxW: 800
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
} else if (wId === "dataTable" && wData && typeof wData === "object") {
|
|
840
|
+
const cols = Array.isArray(wData.columns) ? wData.columns : [];
|
|
841
|
+
const imageColKeys = cols.filter((c) => c && c.type === "image" && c.key).map((c) => String(c.key));
|
|
842
|
+
const dtRows = Array.isArray(wData.rows) ? wData.rows : [];
|
|
843
|
+
if (imageColKeys.length > 0 && dtRows.length > 0) {
|
|
844
|
+
for (const dtRow of dtRows) {
|
|
845
|
+
if (!dtRow || typeof dtRow !== "object") continue;
|
|
846
|
+
for (const key of imageColKeys) {
|
|
847
|
+
if (dtRow[key]) {
|
|
848
|
+
scheduleAsset(dtRow, key, {
|
|
849
|
+
defaultAutoMaxW: 800
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
walkRows(rows);
|
|
861
|
+
if (jobs.length > 0) {
|
|
862
|
+
await runWithConcurrency(jobs, 3);
|
|
863
|
+
}
|
|
864
|
+
return wasString ? JSON.stringify(rows) : rows;
|
|
865
|
+
}
|
|
866
|
+
async function syncSurveyQuestionsMedia(strapi, questions) {
|
|
867
|
+
if (!Array.isArray(questions) || questions.length === 0) return questions;
|
|
868
|
+
const cloned = JSON.parse(JSON.stringify(questions));
|
|
869
|
+
const fileCache = /* @__PURE__ */ new Map();
|
|
870
|
+
const jobs = [];
|
|
871
|
+
for (const q of cloned) {
|
|
872
|
+
if (!q || typeof q !== "object" || !Array.isArray(q.options)) continue;
|
|
873
|
+
for (const opt of q.options) {
|
|
874
|
+
if (opt && typeof opt === "object" && opt.image) {
|
|
875
|
+
jobs.push(async () => {
|
|
876
|
+
opt.image = await enrichMediaAssetNode(strapi, opt.image, {
|
|
877
|
+
defaultAutoMaxW: 800,
|
|
878
|
+
fileCache
|
|
879
|
+
});
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
if (jobs.length > 0) {
|
|
885
|
+
await runWithConcurrency(jobs, 3);
|
|
886
|
+
}
|
|
887
|
+
return cloned;
|
|
888
|
+
}
|
|
889
|
+
function collectContentInputModelFields(strapi) {
|
|
890
|
+
const map = /* @__PURE__ */ new Map();
|
|
891
|
+
const inspectSchemas = (schemas) => {
|
|
892
|
+
if (!schemas || typeof schemas !== "object") return;
|
|
893
|
+
for (const [uid, schema] of Object.entries(schemas)) {
|
|
894
|
+
const attrs = schema?.attributes;
|
|
895
|
+
if (!attrs || typeof attrs !== "object") continue;
|
|
896
|
+
const matchingFields = [];
|
|
897
|
+
for (const [fieldName, attrDef] of Object.entries(attrs)) {
|
|
898
|
+
if (attrDef?.customField === "plugin::content-input.content-input") {
|
|
899
|
+
matchingFields.push(fieldName);
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
if (matchingFields.length > 0) {
|
|
903
|
+
map.set(uid, matchingFields);
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
inspectSchemas(strapi.contentTypes);
|
|
908
|
+
inspectSchemas(strapi.components);
|
|
909
|
+
return map;
|
|
910
|
+
}
|
|
39
911
|
const bootstrap = async ({ strapi }) => {
|
|
40
912
|
try {
|
|
41
913
|
await strapi.plugin("content-input").service("ci-color").ensureSeeded();
|
|
@@ -44,12 +916,66 @@ const bootstrap = async ({ strapi }) => {
|
|
|
44
916
|
} catch (err) {
|
|
45
917
|
strapi.log.warn(`[content-input] Bootstrap seed skipped: ${err?.message || err}`);
|
|
46
918
|
}
|
|
919
|
+
try {
|
|
920
|
+
const modelFieldMap = collectContentInputModelFields(strapi);
|
|
921
|
+
const surveyUid = "plugin::content-input.ci-survey";
|
|
922
|
+
const subscribedModels = Array.from(/* @__PURE__ */ new Set([...modelFieldMap.keys(), surveyUid]));
|
|
923
|
+
if (subscribedModels.length > 0 && strapi.db?.lifecycles?.subscribe) {
|
|
924
|
+
const processEventData = async (event) => {
|
|
925
|
+
const uid = event?.model?.uid;
|
|
926
|
+
const data = event?.params?.data;
|
|
927
|
+
if (!uid || !data || typeof data !== "object") return;
|
|
928
|
+
if (uid === surveyUid) {
|
|
929
|
+
if (Array.isArray(data.questions) && data.questions.length > 0) {
|
|
930
|
+
try {
|
|
931
|
+
data.questions = await syncSurveyQuestionsMedia(strapi, data.questions);
|
|
932
|
+
} catch (err) {
|
|
933
|
+
strapi.log.warn(
|
|
934
|
+
`[content-input] Survey media optimization warning: ${err?.message || err}`
|
|
935
|
+
);
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
return;
|
|
939
|
+
}
|
|
940
|
+
const fields = modelFieldMap.get(uid);
|
|
941
|
+
if (!fields || fields.length === 0) return;
|
|
942
|
+
for (const fieldName of fields) {
|
|
943
|
+
if (data[fieldName] !== void 0 && data[fieldName] !== null) {
|
|
944
|
+
try {
|
|
945
|
+
data[fieldName] = await syncContentInputTreeMedia(strapi, data[fieldName]);
|
|
946
|
+
} catch (err) {
|
|
947
|
+
strapi.log.warn(
|
|
948
|
+
`[content-input] Media sync warning on ${uid}.${fieldName}: ${err?.message || err}`
|
|
949
|
+
);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
};
|
|
954
|
+
strapi.db.lifecycles.subscribe({
|
|
955
|
+
models: subscribedModels,
|
|
956
|
+
async beforeCreate(event) {
|
|
957
|
+
await processEventData(event);
|
|
958
|
+
},
|
|
959
|
+
async beforeUpdate(event) {
|
|
960
|
+
await processEventData(event);
|
|
961
|
+
}
|
|
962
|
+
});
|
|
963
|
+
}
|
|
964
|
+
} catch (err) {
|
|
965
|
+
strapi.log.warn(
|
|
966
|
+
`[content-input] Lifecycle registration skipped: ${err?.message || err}`
|
|
967
|
+
);
|
|
968
|
+
}
|
|
47
969
|
};
|
|
48
970
|
const destroy = ({ strapi }) => {
|
|
49
971
|
};
|
|
50
972
|
const config = {
|
|
51
973
|
default: {
|
|
52
|
-
previewUrl: "/ci-preview"
|
|
974
|
+
previewUrl: "/ci-preview",
|
|
975
|
+
imageVariantFolder: process.env.CI_IMAGE_VARIANT_FOLDER || "ci-optimized",
|
|
976
|
+
imageVariantFormat: process.env.CI_IMAGE_VARIANT_FORMAT || "webp",
|
|
977
|
+
imageVariantQuality: 85,
|
|
978
|
+
redirectProxyToCdn: true
|
|
53
979
|
},
|
|
54
980
|
validator() {
|
|
55
981
|
}
|
|
@@ -300,10 +1226,6 @@ const ciMenuController = ({ strapi }) => ({
|
|
|
300
1226
|
}
|
|
301
1227
|
}
|
|
302
1228
|
});
|
|
303
|
-
function getSharp() {
|
|
304
|
-
const req = typeof require !== "undefined" ? require : module$1.createRequire(path__default.default.join(process.cwd(), "package.json"));
|
|
305
|
-
return req("sharp");
|
|
306
|
-
}
|
|
307
1229
|
function getCacheDir(strapi) {
|
|
308
1230
|
const rootDir = strapi?.dirs?.app?.root || process.cwd();
|
|
309
1231
|
const dir = path__default.default.join(rootDir, ".cache", "content-input-images");
|
|
@@ -312,47 +1234,12 @@ function getCacheDir(strapi) {
|
|
|
312
1234
|
}
|
|
313
1235
|
return dir;
|
|
314
1236
|
}
|
|
315
|
-
async function loadSourceBuffer(strapi, src) {
|
|
316
|
-
const publicDir = strapi?.dirs?.static?.public || path__default.default.join(process.cwd(), "public");
|
|
317
|
-
if (src.startsWith("/")) {
|
|
318
|
-
const cleanRel = decodeURIComponent(src.split("?")[0]).replace(/^\/+/, "");
|
|
319
|
-
const fullPath = path__default.default.resolve(publicDir, cleanRel);
|
|
320
|
-
const resolvedPublic = path__default.default.resolve(publicDir);
|
|
321
|
-
if (!fullPath.startsWith(resolvedPublic)) {
|
|
322
|
-
throw new Error("Invalid local file path");
|
|
323
|
-
}
|
|
324
|
-
if (!fs__default.default.existsSync(fullPath)) {
|
|
325
|
-
throw new Error(`File not found: ${src}`);
|
|
326
|
-
}
|
|
327
|
-
const buffer = await fs__default.default.promises.readFile(fullPath);
|
|
328
|
-
const ext = path__default.default.extname(fullPath).toLowerCase();
|
|
329
|
-
const mime = ext === ".png" ? "image/png" : ext === ".webp" ? "image/webp" : ext === ".avif" ? "image/avif" : ext === ".gif" ? "image/gif" : "image/jpeg";
|
|
330
|
-
return { buffer, mime };
|
|
331
|
-
}
|
|
332
|
-
if (/^https?:\/\//i.test(src)) {
|
|
333
|
-
const parsed = new URL(src);
|
|
334
|
-
if ((parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1") && parsed.pathname.startsWith("/uploads/")) {
|
|
335
|
-
const cleanRel = decodeURIComponent(parsed.pathname).replace(/^\/+/, "");
|
|
336
|
-
const fullPath = path__default.default.resolve(publicDir, cleanRel);
|
|
337
|
-
if (fs__default.default.existsSync(fullPath)) {
|
|
338
|
-
const buffer = await fs__default.default.promises.readFile(fullPath);
|
|
339
|
-
return { buffer, mime: "image/jpeg" };
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
const res = await fetch(src);
|
|
343
|
-
if (!res.ok) {
|
|
344
|
-
throw new Error(`Failed to fetch remote image (${res.status})`);
|
|
345
|
-
}
|
|
346
|
-
const contentType = res.headers.get("content-type") || "image/jpeg";
|
|
347
|
-
const arr = await res.arrayBuffer();
|
|
348
|
-
return { buffer: Buffer.from(arr), mime: contentType };
|
|
349
|
-
}
|
|
350
|
-
throw new Error("Unsupported image source URL");
|
|
351
|
-
}
|
|
352
1237
|
const ciImageController = ({ strapi }) => ({
|
|
353
1238
|
/**
|
|
354
1239
|
* GET /api/content-input/image & GET /content-input/image
|
|
355
|
-
*
|
|
1240
|
+
* Generates `ci-optimized` WebP variants via sharp, uploads to Strapi's Upload Provider (CDN),
|
|
1241
|
+
* persists in `plugin::upload.file.formats`, and issues a 302 redirect when a remote CDN URL is available
|
|
1242
|
+
* (with local byte-stream fallback in local-only environments).
|
|
356
1243
|
*/
|
|
357
1244
|
async processImage(ctx) {
|
|
358
1245
|
try {
|
|
@@ -361,16 +1248,96 @@ const ciImageController = ({ strapi }) => ({
|
|
|
361
1248
|
if (!src) {
|
|
362
1249
|
return ctx.badRequest("Missing src parameter");
|
|
363
1250
|
}
|
|
364
|
-
const
|
|
365
|
-
const
|
|
366
|
-
const
|
|
1251
|
+
const rawProc = String(query.process || "auto").trim().toLowerCase();
|
|
1252
|
+
const processMode = rawProc === "fit" ? "fit" : rawProc === "widen" ? "widen" : "auto";
|
|
1253
|
+
const w = Math.min(
|
|
1254
|
+
3840,
|
|
1255
|
+
Math.max(0, parseInt(String(query.w || query.cWidth || "0"), 10) || 0)
|
|
1256
|
+
);
|
|
1257
|
+
const h = Math.min(
|
|
1258
|
+
3840,
|
|
1259
|
+
Math.max(0, parseInt(String(query.h || query.cHeight || "0"), 10) || 0)
|
|
1260
|
+
);
|
|
367
1261
|
const q = Math.min(100, Math.max(20, parseInt(String(query.q || "85"), 10) || 85));
|
|
368
1262
|
const rotate = parseInt(String(query.rotate || "0"), 10) || 0;
|
|
369
1263
|
const cx = parseInt(String(query.x || "0"), 10) || 0;
|
|
370
1264
|
const cy = parseInt(String(query.y || "0"), 10) || 0;
|
|
371
1265
|
const cw = parseInt(String(query.cw || "0"), 10) || 0;
|
|
372
1266
|
const ch = parseInt(String(query.ch || "0"), 10) || 0;
|
|
373
|
-
const requestedFormat = String(query.format || "").toLowerCase();
|
|
1267
|
+
const requestedFormat = String(query.format || "").trim().toLowerCase();
|
|
1268
|
+
const acceptHeader = String(ctx.req?.headers?.accept || "");
|
|
1269
|
+
const wantsJson = query.json === "1" || query.json === "true" || acceptHeader.includes("application/json");
|
|
1270
|
+
const forceNoRedirect = query.redirect === "0" || query.redirect === "false" || query.proxy === "1" || query.proxy === "true";
|
|
1271
|
+
const forceRedirect = query.redirect === "1" || query.redirect === "true";
|
|
1272
|
+
const cfg = getVariantConfig(strapi);
|
|
1273
|
+
if (cw <= 0 && ch <= 0) {
|
|
1274
|
+
const existingFile = await findUploadFileForAsset(strapi, src);
|
|
1275
|
+
if (existingFile && existingFile.id) {
|
|
1276
|
+
if (!isOptimizableRasterImage(existingFile.mime, existingFile.ext || existingFile.url)) {
|
|
1277
|
+
const directUrl = existingFile.url;
|
|
1278
|
+
if (wantsJson) {
|
|
1279
|
+
ctx.body = { url: directUrl, formatKey: null };
|
|
1280
|
+
return;
|
|
1281
|
+
}
|
|
1282
|
+
if (!forceNoRedirect && directUrl && (cfg.redirectProxyToCdn && isAbsoluteHttpUrl(directUrl) || forceRedirect)) {
|
|
1283
|
+
ctx.set("Cache-Control", "public, max-age=86400");
|
|
1284
|
+
ctx.set("Access-Control-Allow-Origin", "*");
|
|
1285
|
+
ctx.status = 302;
|
|
1286
|
+
ctx.redirect(directUrl);
|
|
1287
|
+
return;
|
|
1288
|
+
}
|
|
1289
|
+
} else {
|
|
1290
|
+
const effW2 = w > 0 ? w : processMode === "auto" ? 1920 : 0;
|
|
1291
|
+
const effH2 = processMode === "fit" ? h : 0;
|
|
1292
|
+
if (effW2 > 0 || effH2 > 0) {
|
|
1293
|
+
const variantRes = await ensureMediaVariant(strapi, existingFile, {
|
|
1294
|
+
processMode,
|
|
1295
|
+
w: effW2,
|
|
1296
|
+
h: effH2,
|
|
1297
|
+
q,
|
|
1298
|
+
rotate,
|
|
1299
|
+
requestedFormat: requestedFormat || void 0
|
|
1300
|
+
});
|
|
1301
|
+
const providerUrl = variantRes.formatEntry?.url;
|
|
1302
|
+
if (providerUrl) {
|
|
1303
|
+
if (wantsJson) {
|
|
1304
|
+
ctx.body = {
|
|
1305
|
+
url: providerUrl,
|
|
1306
|
+
formatKey: variantRes.formatKey
|
|
1307
|
+
};
|
|
1308
|
+
return;
|
|
1309
|
+
}
|
|
1310
|
+
if (!forceNoRedirect && (cfg.redirectProxyToCdn && isAbsoluteHttpUrl(providerUrl) || forceRedirect)) {
|
|
1311
|
+
ctx.set("Cache-Control", "public, max-age=86400");
|
|
1312
|
+
ctx.set("Access-Control-Allow-Origin", "*");
|
|
1313
|
+
ctx.set("X-Content-Input-CDN-Url", providerUrl);
|
|
1314
|
+
ctx.status = 302;
|
|
1315
|
+
ctx.redirect(providerUrl);
|
|
1316
|
+
return;
|
|
1317
|
+
}
|
|
1318
|
+
try {
|
|
1319
|
+
const localVariant = await loadSourceBuffer(strapi, providerUrl);
|
|
1320
|
+
const etagLocal = `"ci-${variantRes.formatKey}-${existingFile.hash || existingFile.id}"`;
|
|
1321
|
+
if (ctx.req?.headers?.["if-none-match"] === etagLocal) {
|
|
1322
|
+
ctx.status = 304;
|
|
1323
|
+
return;
|
|
1324
|
+
}
|
|
1325
|
+
const resolvedMime = variantRes.formatEntry?.mime || localVariant.mime || "image/webp";
|
|
1326
|
+
ctx.body = localVariant.buffer;
|
|
1327
|
+
ctx.type = resolvedMime;
|
|
1328
|
+
ctx.set("Content-Type", resolvedMime);
|
|
1329
|
+
ctx.set("Cache-Control", "public, max-age=31536000, immutable");
|
|
1330
|
+
ctx.set("ETag", etagLocal);
|
|
1331
|
+
ctx.set("Access-Control-Allow-Origin", "*");
|
|
1332
|
+
ctx.set("X-Content-Input-CDN-Url", providerUrl);
|
|
1333
|
+
return;
|
|
1334
|
+
} catch {
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
374
1341
|
const cacheKeyRaw = JSON.stringify({
|
|
375
1342
|
src,
|
|
376
1343
|
processMode,
|
|
@@ -382,11 +1349,11 @@ const ciImageController = ({ strapi }) => ({
|
|
|
382
1349
|
cy,
|
|
383
1350
|
cw,
|
|
384
1351
|
ch,
|
|
385
|
-
requestedFormat
|
|
1352
|
+
requestedFormat: requestedFormat || cfg.defaultFormat
|
|
386
1353
|
});
|
|
387
1354
|
const hash = crypto__default.default.createHash("sha1").update(cacheKeyRaw).digest("hex");
|
|
388
1355
|
const etag = `"ci-${hash}"`;
|
|
389
|
-
if (ctx.req
|
|
1356
|
+
if (!wantsJson && ctx.req?.headers?.["if-none-match"] === etag) {
|
|
390
1357
|
ctx.status = 304;
|
|
391
1358
|
return;
|
|
392
1359
|
}
|
|
@@ -395,138 +1362,112 @@ const ciImageController = ({ strapi }) => ({
|
|
|
395
1362
|
const binPath = path__default.default.join(cacheDir, `${hash}.bin`);
|
|
396
1363
|
if (fs__default.default.existsSync(metaPath) && fs__default.default.existsSync(binPath)) {
|
|
397
1364
|
const meta = JSON.parse(await fs__default.default.promises.readFile(metaPath, "utf8"));
|
|
1365
|
+
if (meta.providerUrl) {
|
|
1366
|
+
if (wantsJson) {
|
|
1367
|
+
ctx.body = { url: meta.providerUrl, formatKey: meta.formatKey || null };
|
|
1368
|
+
return;
|
|
1369
|
+
}
|
|
1370
|
+
if (!forceNoRedirect && (cfg.redirectProxyToCdn && isAbsoluteHttpUrl(meta.providerUrl) || forceRedirect)) {
|
|
1371
|
+
ctx.set("Cache-Control", "public, max-age=86400");
|
|
1372
|
+
ctx.set("Access-Control-Allow-Origin", "*");
|
|
1373
|
+
ctx.set("X-Content-Input-CDN-Url", meta.providerUrl);
|
|
1374
|
+
ctx.status = 302;
|
|
1375
|
+
ctx.redirect(meta.providerUrl);
|
|
1376
|
+
return;
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
398
1379
|
const cachedBuffer = await fs__default.default.promises.readFile(binPath);
|
|
399
|
-
|
|
1380
|
+
const cachedMime = meta.contentType || "image/webp";
|
|
1381
|
+
ctx.body = cachedBuffer;
|
|
1382
|
+
ctx.type = cachedMime;
|
|
1383
|
+
ctx.set("Content-Type", cachedMime);
|
|
400
1384
|
ctx.set("Cache-Control", "public, max-age=31536000, immutable");
|
|
401
1385
|
ctx.set("ETag", etag);
|
|
402
1386
|
ctx.set("Access-Control-Allow-Origin", "*");
|
|
403
|
-
ctx.body = cachedBuffer;
|
|
404
1387
|
return;
|
|
405
1388
|
}
|
|
406
1389
|
const { buffer: sourceBuffer, mime: sourceMime } = await loadSourceBuffer(strapi, src);
|
|
407
|
-
const
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
position: "centre",
|
|
424
|
-
withoutEnlargement: false
|
|
425
|
-
});
|
|
426
|
-
} else if (processMode === "widen" && w > 0) {
|
|
427
|
-
pipeline = pipeline.resize(w, null, {
|
|
428
|
-
fit: "inside",
|
|
429
|
-
withoutEnlargement: false
|
|
430
|
-
});
|
|
431
|
-
} else if (w > 0 || h > 0) {
|
|
432
|
-
pipeline = pipeline.resize(w || null, h || null, {
|
|
433
|
-
fit: "inside",
|
|
434
|
-
withoutEnlargement: true
|
|
435
|
-
});
|
|
436
|
-
}
|
|
437
|
-
let outContentType = sourceMime;
|
|
438
|
-
if (requestedFormat === "webp" || sourceMime === "image/webp") {
|
|
439
|
-
pipeline = pipeline.webp({ quality: q });
|
|
440
|
-
outContentType = "image/webp";
|
|
441
|
-
} else if (requestedFormat === "avif" || sourceMime === "image/avif") {
|
|
442
|
-
pipeline = pipeline.avif({ quality: q });
|
|
443
|
-
outContentType = "image/avif";
|
|
444
|
-
} else if (requestedFormat === "png" || sourceMime === "image/png") {
|
|
445
|
-
pipeline = pipeline.png({ quality: q });
|
|
446
|
-
outContentType = "image/png";
|
|
447
|
-
} else {
|
|
448
|
-
pipeline = pipeline.jpeg({ quality: q, mozjpeg: true });
|
|
449
|
-
outContentType = "image/jpeg";
|
|
450
|
-
}
|
|
451
|
-
const outputBuffer = await pipeline.toBuffer();
|
|
452
|
-
let providerUrl;
|
|
453
|
-
try {
|
|
454
|
-
const cleanSrc = src.split("?")[0];
|
|
455
|
-
const existingFile = await strapi.db.query("plugin::upload.file").findOne({
|
|
456
|
-
where: { url: cleanSrc }
|
|
457
|
-
});
|
|
458
|
-
if (existingFile && existingFile.id) {
|
|
459
|
-
const formatKey = `ci_${processMode}_${w}x${h}${rotate ? `_r${rotate}` : ""}`;
|
|
460
|
-
const existingFormat = existingFile.formats?.[formatKey];
|
|
461
|
-
if (existingFormat?.url) {
|
|
462
|
-
providerUrl = existingFormat.url;
|
|
463
|
-
} else {
|
|
464
|
-
const outMeta = await sharp(outputBuffer).metadata();
|
|
465
|
-
const ext = outContentType === "image/png" ? ".png" : outContentType === "image/webp" ? ".webp" : outContentType === "image/avif" ? ".avif" : ".jpg";
|
|
466
|
-
const variantHash = `${formatKey}_${existingFile.hash || hash.slice(0, 10)}`;
|
|
467
|
-
const variantName = `${formatKey}_${existingFile.name || "image"}`;
|
|
468
|
-
const tmpVariantPath = path__default.default.join(os__default.default.tmpdir(), `${variantHash}${ext}`);
|
|
469
|
-
await fs__default.default.promises.writeFile(tmpVariantPath, outputBuffer);
|
|
470
|
-
try {
|
|
471
|
-
const variantFile = {
|
|
472
|
-
name: variantName,
|
|
473
|
-
hash: variantHash,
|
|
474
|
-
ext,
|
|
475
|
-
mime: outContentType,
|
|
476
|
-
filepath: tmpVariantPath,
|
|
477
|
-
path: existingFile.path || null,
|
|
478
|
-
getStream: () => fs__default.default.createReadStream(tmpVariantPath),
|
|
479
|
-
width: outMeta.width || w || void 0,
|
|
480
|
-
height: outMeta.height || h || void 0,
|
|
481
|
-
size: Math.round(outputBuffer.length / 1e3 * 100) / 100,
|
|
482
|
-
sizeInBytes: outputBuffer.length
|
|
483
|
-
};
|
|
484
|
-
const providerService = strapi.plugin("upload").service("provider");
|
|
485
|
-
if (providerService && typeof providerService.upload === "function") {
|
|
486
|
-
await providerService.upload(variantFile);
|
|
487
|
-
providerUrl = variantFile.url;
|
|
488
|
-
const { filepath: _fp, getStream: _gs, ...serializableFormat } = variantFile;
|
|
489
|
-
const nextFormats = {
|
|
490
|
-
...existingFile.formats || {},
|
|
491
|
-
[formatKey]: serializableFormat
|
|
492
|
-
};
|
|
493
|
-
await strapi.db.query("plugin::upload.file").update({
|
|
494
|
-
where: { id: existingFile.id },
|
|
495
|
-
data: { formats: nextFormats }
|
|
496
|
-
});
|
|
497
|
-
}
|
|
498
|
-
} finally {
|
|
499
|
-
await fs__default.default.promises.rm(tmpVariantPath, { force: true }).catch(() => void 0);
|
|
500
|
-
}
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
} catch {
|
|
504
|
-
}
|
|
505
|
-
await fs__default.default.promises.writeFile(binPath, outputBuffer);
|
|
1390
|
+
const effW = w > 0 ? w : processMode === "auto" ? 1920 : 0;
|
|
1391
|
+
const effH = processMode === "fit" ? h : 0;
|
|
1392
|
+
const rendered = await renderSharpVariantBuffer(sourceBuffer, sourceMime, {
|
|
1393
|
+
processMode,
|
|
1394
|
+
w: effW,
|
|
1395
|
+
h: effH,
|
|
1396
|
+
q,
|
|
1397
|
+
rotate,
|
|
1398
|
+
cx,
|
|
1399
|
+
cy,
|
|
1400
|
+
cw,
|
|
1401
|
+
ch,
|
|
1402
|
+
requestedFormat: requestedFormat || void 0,
|
|
1403
|
+
defaultFormat: cfg.defaultFormat
|
|
1404
|
+
});
|
|
1405
|
+
await fs__default.default.promises.writeFile(binPath, rendered.buffer);
|
|
506
1406
|
await fs__default.default.promises.writeFile(
|
|
507
1407
|
metaPath,
|
|
508
1408
|
JSON.stringify({
|
|
509
|
-
contentType:
|
|
510
|
-
size:
|
|
511
|
-
providerUrl
|
|
1409
|
+
contentType: rendered.contentType,
|
|
1410
|
+
size: rendered.buffer.length
|
|
512
1411
|
})
|
|
513
1412
|
);
|
|
514
|
-
|
|
1413
|
+
if (wantsJson) {
|
|
1414
|
+
ctx.body = { url: src, formatKey: null };
|
|
1415
|
+
return;
|
|
1416
|
+
}
|
|
1417
|
+
ctx.body = rendered.buffer;
|
|
1418
|
+
ctx.type = rendered.contentType;
|
|
1419
|
+
ctx.set("Content-Type", rendered.contentType);
|
|
515
1420
|
ctx.set("Cache-Control", "public, max-age=31536000, immutable");
|
|
516
1421
|
ctx.set("ETag", etag);
|
|
517
1422
|
ctx.set("Access-Control-Allow-Origin", "*");
|
|
518
|
-
if (providerUrl) {
|
|
519
|
-
ctx.set("X-Content-Input-CDN-Url", providerUrl);
|
|
520
|
-
}
|
|
521
|
-
ctx.body = outputBuffer;
|
|
522
1423
|
} catch (err) {
|
|
523
1424
|
ctx.throw(400, err?.message || "Image processing error");
|
|
524
1425
|
}
|
|
525
1426
|
},
|
|
1427
|
+
/**
|
|
1428
|
+
* POST /content-input/media/optimize
|
|
1429
|
+
* Eagerly optimizes one or multiple selected/uploaded Media Library assets into `ci-optimized/*.webp`
|
|
1430
|
+
* on the configured Upload Provider (CDN) and returns enriched CIMediaAsset object(s) with `formats` & `optimized_url`.
|
|
1431
|
+
*/
|
|
1432
|
+
async optimizeMedia(ctx) {
|
|
1433
|
+
try {
|
|
1434
|
+
const body = ctx.request.body || {};
|
|
1435
|
+
const imageSettings = body.imageSettings || null;
|
|
1436
|
+
const defaultAutoMaxW = Number(body.defaultAutoMaxW) || 1920;
|
|
1437
|
+
const fileCache = /* @__PURE__ */ new Map();
|
|
1438
|
+
if (Array.isArray(body.assets)) {
|
|
1439
|
+
const enrichedList = [];
|
|
1440
|
+
for (const item of body.assets) {
|
|
1441
|
+
enrichedList.push(
|
|
1442
|
+
await enrichMediaAssetNode(strapi, item, {
|
|
1443
|
+
imageSettings,
|
|
1444
|
+
defaultAutoMaxW,
|
|
1445
|
+
fileCache
|
|
1446
|
+
})
|
|
1447
|
+
);
|
|
1448
|
+
}
|
|
1449
|
+
ctx.body = { data: enrichedList };
|
|
1450
|
+
return;
|
|
1451
|
+
}
|
|
1452
|
+
if (body.asset) {
|
|
1453
|
+
const enriched = await enrichMediaAssetNode(strapi, body.asset, {
|
|
1454
|
+
imageSettings,
|
|
1455
|
+
defaultAutoMaxW,
|
|
1456
|
+
fileCache
|
|
1457
|
+
});
|
|
1458
|
+
ctx.body = { data: enriched };
|
|
1459
|
+
return;
|
|
1460
|
+
}
|
|
1461
|
+
return ctx.badRequest("asset or assets is required");
|
|
1462
|
+
} catch (err) {
|
|
1463
|
+
ctx.throw(500, err?.message || "Failed to optimize media asset");
|
|
1464
|
+
}
|
|
1465
|
+
},
|
|
526
1466
|
/**
|
|
527
1467
|
* POST /content-input/media/crop
|
|
528
1468
|
* Interactive crop & rotate using sharp on the backend (works seamlessly with local disk AND remote CDNs).
|
|
529
|
-
* Supports mode: 'replace' (crops original asset in Media Library
|
|
1469
|
+
* Supports mode: 'replace' (crops original asset in Media Library & refreshes ci-optimized variants)
|
|
1470
|
+
* or 'duplicate' (saves as new asset).
|
|
530
1471
|
*/
|
|
531
1472
|
async cropMedia(ctx) {
|
|
532
1473
|
const tmpDir = await fs__default.default.promises.mkdtemp(path__default.default.join(os__default.default.tmpdir(), "ci-crop-"));
|
|
@@ -582,7 +1523,7 @@ const ciImageController = ({ strapi }) => ({
|
|
|
582
1523
|
if (ext === ".png" || mime === "image/png") {
|
|
583
1524
|
pipeline = pipeline.png({ quality: 92 });
|
|
584
1525
|
} else if (ext === ".webp" || mime === "image/webp") {
|
|
585
|
-
pipeline = pipeline.webp({ quality: 90 });
|
|
1526
|
+
pipeline = pipeline.webp({ quality: 90, alphaQuality: 100 });
|
|
586
1527
|
} else {
|
|
587
1528
|
pipeline = pipeline.jpeg({ quality: 90, mozjpeg: true });
|
|
588
1529
|
}
|
|
@@ -591,6 +1532,9 @@ const ciImageController = ({ strapi }) => ({
|
|
|
591
1532
|
const targetFileName = mode === "duplicate" ? `${body.name || `${baseName}-cropped`}${ext.startsWith(".") ? ext : `.${ext}`}` : existingFile.name || `${baseName}${ext}`;
|
|
592
1533
|
const tmpFilePath = path__default.default.join(tmpDir, targetFileName);
|
|
593
1534
|
await fs__default.default.promises.writeFile(tmpFilePath, croppedBuffer);
|
|
1535
|
+
if (mode === "replace") {
|
|
1536
|
+
await clearGeneratedCiVariantsForFile(strapi, existingFile);
|
|
1537
|
+
}
|
|
594
1538
|
const uploadService = strapi.plugin("upload").service("upload");
|
|
595
1539
|
const fileInfo = {
|
|
596
1540
|
name: targetFileName,
|
|
@@ -626,6 +1570,17 @@ const ciImageController = ({ strapi }) => ({
|
|
|
626
1570
|
);
|
|
627
1571
|
resultFile = Array.isArray(uploaded) ? uploaded[0] : uploaded;
|
|
628
1572
|
}
|
|
1573
|
+
if (resultFile?.id) {
|
|
1574
|
+
try {
|
|
1575
|
+
const freshRes = await ensureMediaVariant(strapi, resultFile, {
|
|
1576
|
+
processMode: "auto",
|
|
1577
|
+
w: 1920,
|
|
1578
|
+
h: 0
|
|
1579
|
+
});
|
|
1580
|
+
resultFile = freshRes.updatedFile || resultFile;
|
|
1581
|
+
} catch {
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
629
1584
|
ctx.body = { data: resultFile };
|
|
630
1585
|
} catch (err) {
|
|
631
1586
|
ctx.throw(500, err?.message || "Failed to crop media asset");
|
|
@@ -1352,6 +2307,14 @@ const routes = {
|
|
|
1352
2307
|
policies: []
|
|
1353
2308
|
}
|
|
1354
2309
|
},
|
|
2310
|
+
{
|
|
2311
|
+
method: "POST",
|
|
2312
|
+
path: "/media/optimize",
|
|
2313
|
+
handler: "ci-image.optimizeMedia",
|
|
2314
|
+
config: {
|
|
2315
|
+
policies: []
|
|
2316
|
+
}
|
|
2317
|
+
},
|
|
1355
2318
|
{
|
|
1356
2319
|
method: "POST",
|
|
1357
2320
|
path: "/media/crop",
|
|
@@ -4273,6 +5236,14 @@ const ciFormService = ({ strapi }) => ({
|
|
|
4273
5236
|
}
|
|
4274
5237
|
}
|
|
4275
5238
|
}
|
|
5239
|
+
if (imageObj) {
|
|
5240
|
+
try {
|
|
5241
|
+
imageObj = await enrichMediaAssetNode(strapi, imageObj, {
|
|
5242
|
+
defaultAutoMaxW: 960
|
|
5243
|
+
});
|
|
5244
|
+
} catch {
|
|
5245
|
+
}
|
|
5246
|
+
}
|
|
4276
5247
|
const pluralName = ct.info?.pluralName || "items";
|
|
4277
5248
|
const slugField = ["slug", "path", "url", "permalink"].find(
|
|
4278
5249
|
(k) => typeof entry[k] === "string" && entry[k].trim()
|
|
@@ -5272,6 +6243,12 @@ const ciSurveyService = ({ strapi }) => ({
|
|
|
5272
6243
|
settings: payload.settings ?? existing?.settings ?? {},
|
|
5273
6244
|
version: existing ? Number(existing.version || 1) + 1 : 1
|
|
5274
6245
|
};
|
|
6246
|
+
if (Array.isArray(recordData.questions) && recordData.questions.length > 0) {
|
|
6247
|
+
try {
|
|
6248
|
+
recordData.questions = await syncSurveyQuestionsMedia(strapi, recordData.questions);
|
|
6249
|
+
} catch {
|
|
6250
|
+
}
|
|
6251
|
+
}
|
|
5275
6252
|
if (existing) {
|
|
5276
6253
|
const updated = await strapi.db.query(SURVEY_UID).update({
|
|
5277
6254
|
where: { id: existing.id },
|
|
@@ -6075,33 +7052,48 @@ const ciColorService = ({ strapi }) => ({
|
|
|
6075
7052
|
entries = [];
|
|
6076
7053
|
}
|
|
6077
7054
|
const collectionLabelText = ct.info?.displayName || uid;
|
|
6078
|
-
const
|
|
6079
|
-
|
|
6080
|
-
|
|
6081
|
-
|
|
6082
|
-
|
|
6083
|
-
|
|
6084
|
-
|
|
6085
|
-
|
|
6086
|
-
|
|
6087
|
-
|
|
6088
|
-
|
|
6089
|
-
|
|
6090
|
-
|
|
6091
|
-
|
|
6092
|
-
|
|
6093
|
-
|
|
6094
|
-
|
|
6095
|
-
|
|
7055
|
+
const fileCache = /* @__PURE__ */ new Map();
|
|
7056
|
+
const sanitizedRows = await Promise.all(
|
|
7057
|
+
(entries || []).map(async (entry) => {
|
|
7058
|
+
const row = {};
|
|
7059
|
+
for (const f of allowedFields) {
|
|
7060
|
+
if (f.key === "collectionLabel" && entry.collectionLabel === void 0) {
|
|
7061
|
+
row.collectionLabel = collectionLabelText;
|
|
7062
|
+
continue;
|
|
7063
|
+
}
|
|
7064
|
+
if (f.key === "url" && entry.url === void 0) {
|
|
7065
|
+
const slugStr = entry.slug ? String(entry.slug).trim() : "";
|
|
7066
|
+
row.url = slugStr ? slugStr === "home" ? "/" : `/${slugStr.replace(/^\/+/, "")}` : "";
|
|
7067
|
+
continue;
|
|
7068
|
+
}
|
|
7069
|
+
const val = entry[f.key];
|
|
7070
|
+
if (val !== null && val !== void 0 && typeof val === "object") {
|
|
7071
|
+
if (Array.isArray(val)) {
|
|
7072
|
+
if (val[0]?.url) {
|
|
7073
|
+
const enriched = await enrichMediaAssetNode(strapi, val[0], {
|
|
7074
|
+
defaultAutoMaxW: 800,
|
|
7075
|
+
fileCache
|
|
7076
|
+
});
|
|
7077
|
+
row[f.key] = enriched?.optimized_url || enriched?.url || val[0].url;
|
|
7078
|
+
} else {
|
|
7079
|
+
row[f.key] = `${val.length} item`;
|
|
7080
|
+
}
|
|
7081
|
+
} else if (val.url) {
|
|
7082
|
+
const enriched = await enrichMediaAssetNode(strapi, val, {
|
|
7083
|
+
defaultAutoMaxW: 800,
|
|
7084
|
+
fileCache
|
|
7085
|
+
});
|
|
7086
|
+
row[f.key] = enriched?.optimized_url || enriched?.url || val.url;
|
|
7087
|
+
} else {
|
|
7088
|
+
row[f.key] = "";
|
|
7089
|
+
}
|
|
6096
7090
|
} else {
|
|
6097
|
-
row[f.key] = "";
|
|
7091
|
+
row[f.key] = val ?? "";
|
|
6098
7092
|
}
|
|
6099
|
-
} else {
|
|
6100
|
-
row[f.key] = val ?? "";
|
|
6101
7093
|
}
|
|
6102
|
-
|
|
6103
|
-
|
|
6104
|
-
|
|
7094
|
+
return row;
|
|
7095
|
+
})
|
|
7096
|
+
);
|
|
6105
7097
|
return {
|
|
6106
7098
|
uid,
|
|
6107
7099
|
displayName: ct.info?.displayName || uid,
|