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