@ozguraltan/strapi-content-input 1.0.21 → 1.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +42 -13
  2. package/dist/admin/{AnalyticsHubPage-DsrcGI_Y.mjs → AnalyticsHubPage-Dvpx3KsP.mjs} +168 -55
  3. package/dist/admin/{AnalyticsHubPage-0p0Mx4AU.js → AnalyticsHubPage-K_trli5i.js} +186 -55
  4. package/dist/admin/{ContentInputField-CHXrzvE-.mjs → ContentInputField-C2kmtUwD.mjs} +328 -366
  5. package/dist/admin/{ContentInputField-7rWLSx_7.js → ContentInputField-CjxYYEps.js} +343 -381
  6. package/dist/admin/{SurveyWidgetEditor-BVN6X_3G.mjs → SurveyWidgetEditor-DMWOkHUt.mjs} +3271 -227
  7. package/dist/admin/{SurveyWidgetEditor-BmgYQaQS.js → SurveyWidgetEditor-DOYxWop9.js} +3247 -203
  8. package/dist/admin/{index-hFIuYqu5.mjs → index-AePRA0IB.mjs} +2 -2
  9. package/dist/admin/{index-CZAwXCFH.js → index-B9C8Qrfd.js} +2 -2
  10. package/dist/admin/index.js +1 -1
  11. package/dist/admin/index.mjs +1 -1
  12. package/dist/admin/src/components/common/CIImageSettingsControl.d.ts +17 -0
  13. package/dist/admin/src/components/widgets/CustomCardWidgetEditor.d.ts +1 -0
  14. package/dist/admin/src/components/widgets/HeroSliderStage.d.ts +3 -0
  15. package/dist/admin/src/components/widgets/SurveyLivePreviewPane.d.ts +9 -0
  16. package/dist/admin/src/components/widgets/SurveyWidgetEditor.d.ts +3 -1
  17. package/dist/admin/src/core/canvasClasses.d.ts +1 -0
  18. package/dist/admin/src/core/types.d.ts +12 -0
  19. package/dist/server/index.js +1359 -196
  20. package/dist/server/index.mjs +1341 -196
  21. package/dist/server/src/config/index.d.ts +4 -0
  22. package/dist/server/src/controllers/ci-image.d.ts +11 -2
  23. package/dist/server/src/controllers/index.d.ts +1 -0
  24. package/dist/server/src/index.d.ts +15 -1
  25. package/dist/server/src/services/ci-survey.d.ts +10 -1
  26. package/dist/server/src/services/index.d.ts +10 -1
  27. package/dist/server/src/utils/image-variants.d.ts +74 -0
  28. package/dist/server/src/utils/surveyEngine.d.ts +5 -0
  29. package/package.json +1 -1
@@ -5,11 +5,30 @@ const fs = require("fs");
5
5
  const module$1 = require("module");
6
6
  const os = require("os");
7
7
  const path = require("path");
8
+ const XLSXNs = require("xlsx");
8
9
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
10
+ function _interopNamespace(e) {
11
+ if (e && e.__esModule) return e;
12
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
13
+ if (e) {
14
+ for (const k in e) {
15
+ if (k !== "default") {
16
+ const d = Object.getOwnPropertyDescriptor(e, k);
17
+ Object.defineProperty(n, k, d.get ? d : {
18
+ enumerable: true,
19
+ get: () => e[k]
20
+ });
21
+ }
22
+ }
23
+ }
24
+ n.default = e;
25
+ return Object.freeze(n);
26
+ }
9
27
  const crypto__default = /* @__PURE__ */ _interopDefault(crypto);
10
28
  const fs__default = /* @__PURE__ */ _interopDefault(fs);
11
29
  const os__default = /* @__PURE__ */ _interopDefault(os);
12
30
  const path__default = /* @__PURE__ */ _interopDefault(path);
31
+ const XLSXNs__namespace = /* @__PURE__ */ _interopNamespace(XLSXNs);
13
32
  const register = ({ strapi }) => {
14
33
  strapi.customFields.register({
15
34
  name: "content-input",
@@ -36,6 +55,878 @@ const register = ({ strapi }) => {
36
55
  });
37
56
  }
38
57
  };
58
+ const inFlightVariants = /* @__PURE__ */ new Map();
59
+ function getSharp() {
60
+ const req = typeof require !== "undefined" ? require : module$1.createRequire(path__default.default.join(process.cwd(), "package.json"));
61
+ return req("sharp");
62
+ }
63
+ function getVariantConfig(strapi) {
64
+ const pluginCfg = strapi?.config?.get?.("plugin::content-input") || {};
65
+ const envFolder = process.env.CI_IMAGE_VARIANT_FOLDER;
66
+ const rawFolder = envFolder !== void 0 && String(envFolder).trim() !== "" ? String(envFolder).trim() : pluginCfg.imageVariantFolder !== void 0 ? pluginCfg.imageVariantFolder : "ci-optimized";
67
+ let folder = "ci-optimized";
68
+ if (rawFolder === null || rawFolder === false || String(rawFolder).trim().toLowerCase() === "none" || String(rawFolder).trim() === "/") {
69
+ folder = null;
70
+ } else {
71
+ const cleaned = String(rawFolder).trim().replace(/^\/+|\/+$/g, "");
72
+ folder = cleaned || "ci-optimized";
73
+ }
74
+ const rawFmt = String(
75
+ process.env.CI_IMAGE_VARIANT_FORMAT || pluginCfg.imageVariantFormat || "webp"
76
+ ).trim().toLowerCase();
77
+ const defaultFormat = rawFmt === "auto" ? "auto" : "webp";
78
+ const envRedirect = process.env.CI_IMAGE_REDIRECT_CDN;
79
+ const redirectProxyToCdn = envRedirect !== void 0 ? envRedirect !== "0" && envRedirect.toLowerCase() !== "false" : pluginCfg.redirectProxyToCdn !== false;
80
+ const defaultQuality = Math.min(
81
+ 100,
82
+ Math.max(40, Number(pluginCfg.imageVariantQuality) || 85)
83
+ );
84
+ return {
85
+ folder,
86
+ defaultFormat,
87
+ redirectProxyToCdn,
88
+ defaultQuality
89
+ };
90
+ }
91
+ function isAbsoluteHttpUrl(url) {
92
+ return Boolean(url && /^https?:\/\//i.test(String(url).trim()));
93
+ }
94
+ function isOptimizableRasterImage(mime, urlOrName) {
95
+ const m = String(mime || "").trim().toLowerCase();
96
+ const u = String(urlOrName || "").split("?")[0].split("#")[0].trim().toLowerCase();
97
+ if (u.startsWith("data:") || u.startsWith("blob:")) return false;
98
+ if (m.includes("svg") || m.includes("gif") || m.startsWith("video/") || m.startsWith("audio/") || m.startsWith("application/") || m.startsWith("text/")) {
99
+ return false;
100
+ }
101
+ if (/\.(svg|gif|mp4|webm|mov|m4v|mp3|wav|ogg|pdf|docx?|xlsx?|pptx?|zip|rar)$/i.test(u)) {
102
+ return false;
103
+ }
104
+ if (m === "image/jpeg" || m === "image/jpg" || m === "image/png" || m === "image/webp" || m === "image/avif" || m === "image/tiff" || m === "image/bmp") {
105
+ return true;
106
+ }
107
+ if (/\.(jpe?g|png|webp|avif|tiff?|bmp)$/i.test(u)) {
108
+ return true;
109
+ }
110
+ if (m.startsWith("image/")) {
111
+ return true;
112
+ }
113
+ return false;
114
+ }
115
+ async function loadSourceBuffer(strapi, src) {
116
+ const publicDir = strapi?.dirs?.static?.public || path__default.default.join(process.cwd(), "public");
117
+ if (src.startsWith("/")) {
118
+ const cleanRel = decodeURIComponent(src.split("?")[0]).replace(/^\/+/, "");
119
+ const fullPath = path__default.default.resolve(publicDir, cleanRel);
120
+ const resolvedPublic = path__default.default.resolve(publicDir);
121
+ if (!fullPath.startsWith(resolvedPublic)) {
122
+ throw new Error("Invalid local file path");
123
+ }
124
+ if (!fs__default.default.existsSync(fullPath)) {
125
+ throw new Error(`File not found: ${src}`);
126
+ }
127
+ const buffer = await fs__default.default.promises.readFile(fullPath);
128
+ const ext = path__default.default.extname(fullPath).toLowerCase();
129
+ const mime = ext === ".png" ? "image/png" : ext === ".webp" ? "image/webp" : ext === ".avif" ? "image/avif" : ext === ".gif" ? "image/gif" : "image/jpeg";
130
+ return { buffer, mime };
131
+ }
132
+ if (/^https?:\/\//i.test(src)) {
133
+ const parsed = new URL(src);
134
+ if ((parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1") && parsed.pathname.startsWith("/uploads/")) {
135
+ const cleanRel = decodeURIComponent(parsed.pathname).replace(/^\/+/, "");
136
+ const fullPath = path__default.default.resolve(publicDir, cleanRel);
137
+ if (fs__default.default.existsSync(fullPath)) {
138
+ const buffer = await fs__default.default.promises.readFile(fullPath);
139
+ const ext = path__default.default.extname(fullPath).toLowerCase();
140
+ const mime = ext === ".png" ? "image/png" : ext === ".webp" ? "image/webp" : "image/jpeg";
141
+ return { buffer, mime };
142
+ }
143
+ }
144
+ const res = await fetch(src);
145
+ if (!res.ok) {
146
+ throw new Error(`Failed to fetch remote image (${res.status})`);
147
+ }
148
+ const contentType = res.headers.get("content-type") || "image/jpeg";
149
+ const arr = await res.arrayBuffer();
150
+ return { buffer: Buffer.from(arr), mime: contentType };
151
+ }
152
+ throw new Error("Unsupported image source URL");
153
+ }
154
+ function normalizeImageProcessSpec(imageSettings, defaultAutoMaxW = 1920) {
155
+ const safeMaxW = Math.min(3840, Math.max(64, Math.round(Number(defaultAutoMaxW) || 1920)));
156
+ const rawProc = String(imageSettings?.process ?? "").trim().toLowerCase();
157
+ const rotate = parseInt(String(imageSettings?.rotate || "0"), 10) || 0;
158
+ const q = Math.min(100, Math.max(30, parseInt(String(imageSettings?.quality || "85"), 10) || 85));
159
+ if (rawProc === "none" || rawProc === "no-process" || rawProc === "original") {
160
+ return {
161
+ processMode: "none",
162
+ w: 0,
163
+ h: 0,
164
+ maxW: safeMaxW,
165
+ q,
166
+ rotate: 0
167
+ };
168
+ }
169
+ if (rawProc === "fit") {
170
+ const w = Math.min(3840, Math.max(0, Math.round(Number(imageSettings?.cWidth) || 0)));
171
+ const h = Math.min(3840, Math.max(0, Math.round(Number(imageSettings?.cHeight) || 0)));
172
+ if (w > 0 && h > 0) {
173
+ return { processMode: "fit", w, h, maxW: safeMaxW, q, rotate };
174
+ }
175
+ }
176
+ if (rawProc === "widen") {
177
+ const w = Math.min(3840, Math.max(0, Math.round(Number(imageSettings?.cWidth) || 0)));
178
+ if (w > 0) {
179
+ return { processMode: "widen", w, h: 0, maxW: safeMaxW, q, rotate };
180
+ }
181
+ }
182
+ const customAutoW = Number(imageSettings?.maxWidth || imageSettings?.cWidth);
183
+ const autoW = rawProc === "auto" && customAutoW > 0 ? Math.min(3840, Math.max(64, Math.round(customAutoW))) : safeMaxW;
184
+ return {
185
+ processMode: "auto",
186
+ w: autoW,
187
+ h: 0,
188
+ maxW: autoW,
189
+ q,
190
+ rotate
191
+ };
192
+ }
193
+ function computeCiFormatKey(processMode, w, h, rotate = 0) {
194
+ const effH = processMode === "fit" ? h : 0;
195
+ const effW = w;
196
+ return `ci_${processMode}_${effW}x${effH}${rotate ? `_r${rotate}` : ""}`;
197
+ }
198
+ function compactAssetFormats(formats) {
199
+ if (!formats || typeof formats !== "object") return void 0;
200
+ const out = {};
201
+ const keepStandard = /* @__PURE__ */ new Set(["thumbnail", "small", "medium", "large"]);
202
+ for (const [key, val] of Object.entries(formats)) {
203
+ if (!val || typeof val !== "object" || typeof val.url !== "string" || !val.url) continue;
204
+ if (!keepStandard.has(key) && !key.startsWith("ci_")) continue;
205
+ out[key] = {
206
+ url: val.url,
207
+ ...val.width ? { width: Number(val.width) } : {},
208
+ ...val.height ? { height: Number(val.height) } : {},
209
+ ...val.mime ? { mime: String(val.mime) } : {},
210
+ ...val.size ? { size: Number(val.size) } : {}
211
+ };
212
+ }
213
+ return Object.keys(out).length > 0 ? out : void 0;
214
+ }
215
+ function stripVariantPrefixFromHash(baseNameNoExt) {
216
+ return baseNameNoExt.replace(/^ci_(?:fit|widen|auto)_\d+x\d+(?:_r-?\d+)?_/, "");
217
+ }
218
+ async function findUploadFileForAsset(strapi, assetOrUrl, cache) {
219
+ if (!assetOrUrl) return null;
220
+ const fileQuery = strapi.db.query("plugin::upload.file");
221
+ const isObj = typeof assetOrUrl === "object";
222
+ const rawId = isObj ? assetOrUrl.id : void 0;
223
+ const rawHash = isObj ? assetOrUrl.hash : void 0;
224
+ const rawUrl = isObj ? assetOrUrl.original_url || assetOrUrl.url || assetOrUrl.target_url || assetOrUrl.src || "" : String(assetOrUrl || "");
225
+ const cleanUrl = String(rawUrl || "").split("?")[0].split("#")[0].trim();
226
+ const cacheKey = rawId ? `id:${rawId}` : rawHash ? `hash:${rawHash}` : cleanUrl ? `url:${cleanUrl}` : "";
227
+ if (cache && cacheKey && cache.has(cacheKey)) {
228
+ return cache.get(cacheKey);
229
+ }
230
+ let found = null;
231
+ const remember = (record) => {
232
+ if (cache) {
233
+ if (cacheKey) cache.set(cacheKey, record);
234
+ if (record?.id) cache.set(`id:${record.id}`, record);
235
+ if (record?.hash) cache.set(`hash:${record.hash}`, record);
236
+ if (record?.url) cache.set(`url:${String(record.url).split("?")[0]}`, record);
237
+ }
238
+ return record;
239
+ };
240
+ if (rawId !== void 0 && rawId !== null && rawId !== "") {
241
+ const numId = Number(rawId);
242
+ if (!Number.isNaN(numId) && numId > 0) {
243
+ found = await fileQuery.findOne({ where: { id: numId } });
244
+ if (found) return remember(found);
245
+ }
246
+ }
247
+ if (rawHash && typeof rawHash === "string") {
248
+ const parentHash = stripVariantPrefixFromHash(rawHash.trim());
249
+ found = await fileQuery.findOne({ where: { hash: parentHash } });
250
+ if (found) return remember(found);
251
+ }
252
+ if (!cleanUrl) return remember(null);
253
+ found = await fileQuery.findOne({ where: { url: cleanUrl } });
254
+ if (found) return remember(found);
255
+ let pathnameStr = cleanUrl;
256
+ if (/^https?:\/\//i.test(cleanUrl)) {
257
+ try {
258
+ pathnameStr = decodeURIComponent(new URL(cleanUrl).pathname);
259
+ } catch {
260
+ pathnameStr = cleanUrl;
261
+ }
262
+ if (pathnameStr && pathnameStr !== cleanUrl) {
263
+ found = await fileQuery.findOne({ where: { url: pathnameStr } });
264
+ if (found) return remember(found);
265
+ }
266
+ }
267
+ const baseName = path__default.default.posix.basename(pathnameStr);
268
+ const ext = path__default.default.posix.extname(baseName);
269
+ const baseNoExt = ext ? baseName.slice(0, -ext.length) : baseName;
270
+ if (baseNoExt) {
271
+ const candidateHash = stripVariantPrefixFromHash(baseNoExt);
272
+ if (candidateHash) {
273
+ found = await fileQuery.findOne({ where: { hash: candidateHash } });
274
+ if (found) return remember(found);
275
+ }
276
+ }
277
+ return remember(null);
278
+ }
279
+ async function renderSharpVariantBuffer(sourceBuffer, sourceMime, opts) {
280
+ const sharp = getSharp();
281
+ let pipeline = sharp(sourceBuffer, { failOn: "none" }).rotate();
282
+ const rotate = opts.rotate || 0;
283
+ if (rotate && [90, 180, 270, -90].includes(rotate)) {
284
+ pipeline = pipeline.rotate(rotate);
285
+ }
286
+ const cw = opts.cw || 0;
287
+ const ch = opts.ch || 0;
288
+ if (cw > 0 && ch > 0) {
289
+ pipeline = pipeline.extract({
290
+ left: Math.max(0, opts.cx || 0),
291
+ top: Math.max(0, opts.cy || 0),
292
+ width: cw,
293
+ height: ch
294
+ });
295
+ }
296
+ const { processMode, w, h, q } = opts;
297
+ if (processMode === "fit" && w > 0 && h > 0) {
298
+ pipeline = pipeline.resize(w, h, {
299
+ fit: "cover",
300
+ position: "centre",
301
+ withoutEnlargement: false
302
+ });
303
+ } else if (processMode === "widen" && w > 0) {
304
+ pipeline = pipeline.resize(w, null, {
305
+ fit: "inside",
306
+ withoutEnlargement: false
307
+ });
308
+ } else if (processMode === "auto" && w > 0) {
309
+ pipeline = pipeline.resize(w, null, {
310
+ fit: "inside",
311
+ withoutEnlargement: true
312
+ });
313
+ } else if (w > 0 || h > 0) {
314
+ pipeline = pipeline.resize(w || null, h || null, {
315
+ fit: "inside",
316
+ withoutEnlargement: true
317
+ });
318
+ }
319
+ const reqFmt = String(opts.requestedFormat || "").trim().toLowerCase();
320
+ const preferWebp = reqFmt === "webp" || !reqFmt && (opts.defaultFormat || "webp") === "webp";
321
+ let contentType = sourceMime || "image/webp";
322
+ let ext = ".webp";
323
+ if (reqFmt === "avif") {
324
+ pipeline = pipeline.avif({ quality: q });
325
+ contentType = "image/avif";
326
+ ext = ".avif";
327
+ } else if (reqFmt === "png") {
328
+ pipeline = pipeline.png({ quality: q });
329
+ contentType = "image/png";
330
+ ext = ".png";
331
+ } else if (reqFmt === "jpg" || reqFmt === "jpeg") {
332
+ pipeline = pipeline.jpeg({ quality: q, mozjpeg: true });
333
+ contentType = "image/jpeg";
334
+ ext = ".jpg";
335
+ } else if (preferWebp || sourceMime === "image/webp") {
336
+ pipeline = pipeline.webp({ quality: q, alphaQuality: 100, effort: 4 });
337
+ contentType = "image/webp";
338
+ ext = ".webp";
339
+ } else if (sourceMime === "image/avif") {
340
+ pipeline = pipeline.avif({ quality: q });
341
+ contentType = "image/avif";
342
+ ext = ".avif";
343
+ } else if (sourceMime === "image/png") {
344
+ pipeline = pipeline.png({ quality: q });
345
+ contentType = "image/png";
346
+ ext = ".png";
347
+ } else {
348
+ pipeline = pipeline.jpeg({ quality: q, mozjpeg: true });
349
+ contentType = "image/jpeg";
350
+ ext = ".jpg";
351
+ }
352
+ const outputBuffer = await pipeline.toBuffer();
353
+ const outMeta = await sharp(outputBuffer).metadata();
354
+ return {
355
+ buffer: outputBuffer,
356
+ contentType,
357
+ ext,
358
+ width: outMeta.width || w || void 0,
359
+ height: outMeta.height || h || void 0
360
+ };
361
+ }
362
+ async function ensureMediaVariant(strapi, existingFile, spec) {
363
+ const formatKey = computeCiFormatKey(
364
+ spec.processMode,
365
+ spec.w,
366
+ spec.h,
367
+ spec.rotate || 0
368
+ );
369
+ if (!existingFile?.id || !existingFile?.url) {
370
+ return { formatKey, formatEntry: null, updatedFile: existingFile };
371
+ }
372
+ if (!isOptimizableRasterImage(existingFile.mime, existingFile.ext || existingFile.url)) {
373
+ return { formatKey, formatEntry: null, updatedFile: existingFile };
374
+ }
375
+ const already = existingFile.formats?.[formatKey];
376
+ if (already?.url) {
377
+ return { formatKey, formatEntry: already, updatedFile: existingFile };
378
+ }
379
+ const lockKey = `${existingFile.id}:${formatKey}`;
380
+ const activePromise = inFlightVariants.get(lockKey);
381
+ if (activePromise) {
382
+ return activePromise;
383
+ }
384
+ const task = (async () => {
385
+ const cfg = getVariantConfig(strapi);
386
+ const freshCheck = await strapi.db.query("plugin::upload.file").findOne({
387
+ where: { id: existingFile.id }
388
+ });
389
+ const baseRecord = freshCheck || existingFile;
390
+ if (baseRecord.formats?.[formatKey]?.url) {
391
+ return {
392
+ formatKey,
393
+ formatEntry: baseRecord.formats[formatKey],
394
+ updatedFile: baseRecord
395
+ };
396
+ }
397
+ const { buffer: sourceBuffer, mime: sourceMime } = await loadSourceBuffer(
398
+ strapi,
399
+ baseRecord.url
400
+ );
401
+ const rendered = await renderSharpVariantBuffer(
402
+ sourceBuffer,
403
+ baseRecord.mime || sourceMime,
404
+ {
405
+ processMode: spec.processMode,
406
+ w: spec.w,
407
+ h: spec.h,
408
+ q: spec.q || cfg.defaultQuality,
409
+ rotate: spec.rotate || 0,
410
+ requestedFormat: spec.requestedFormat,
411
+ defaultFormat: cfg.defaultFormat
412
+ }
413
+ );
414
+ const fallbackShortHash = crypto__default.default.createHash("sha1").update(String(baseRecord.url)).digest("hex").slice(0, 10);
415
+ const cleanBaseName = path__default.default.basename(
416
+ baseRecord.name || "image",
417
+ path__default.default.extname(baseRecord.name || "")
418
+ );
419
+ const variantHash = `${formatKey}_${baseRecord.hash || fallbackShortHash}`;
420
+ const variantName = `${formatKey}_${cleanBaseName}${rendered.ext}`;
421
+ const tmpVariantPath = path__default.default.join(
422
+ os__default.default.tmpdir(),
423
+ `${variantHash}_${Date.now()}_${Math.random().toString(36).slice(2, 6)}${rendered.ext}`
424
+ );
425
+ await fs__default.default.promises.writeFile(tmpVariantPath, rendered.buffer);
426
+ try {
427
+ const variantFile = {
428
+ name: variantName,
429
+ hash: variantHash,
430
+ ext: rendered.ext,
431
+ mime: rendered.contentType,
432
+ filepath: tmpVariantPath,
433
+ path: cfg.folder !== null ? cfg.folder : baseRecord.path || null,
434
+ getStream: () => fs__default.default.createReadStream(tmpVariantPath),
435
+ width: rendered.width,
436
+ height: rendered.height,
437
+ size: Math.round(rendered.buffer.length / 1e3 * 100) / 100,
438
+ sizeInBytes: rendered.buffer.length
439
+ };
440
+ const providerService = strapi.plugin("upload").service("provider");
441
+ if (!providerService || typeof providerService.upload !== "function") {
442
+ return { formatKey, formatEntry: null, updatedFile: baseRecord };
443
+ }
444
+ await providerService.upload(variantFile);
445
+ const { filepath: _fp, getStream: _gs, ...serializableFormat } = variantFile;
446
+ const latestRecord = await strapi.db.query("plugin::upload.file").findOne({
447
+ where: { id: baseRecord.id }
448
+ }) || baseRecord;
449
+ const nextFormats = {
450
+ ...latestRecord.formats || {},
451
+ [formatKey]: serializableFormat
452
+ };
453
+ const updatedFile = await strapi.db.query("plugin::upload.file").update({
454
+ where: { id: baseRecord.id },
455
+ data: { formats: nextFormats }
456
+ });
457
+ existingFile.formats = nextFormats;
458
+ return {
459
+ formatKey,
460
+ formatEntry: serializableFormat,
461
+ updatedFile: updatedFile || { ...latestRecord, formats: nextFormats }
462
+ };
463
+ } finally {
464
+ await fs__default.default.promises.rm(tmpVariantPath, { force: true }).catch(() => void 0);
465
+ }
466
+ })();
467
+ inFlightVariants.set(lockKey, task);
468
+ try {
469
+ return await task;
470
+ } finally {
471
+ inFlightVariants.delete(lockKey);
472
+ }
473
+ }
474
+ async function clearGeneratedCiVariantsForFile(strapi, fileRecord) {
475
+ if (!fileRecord?.id || !fileRecord?.formats || typeof fileRecord.formats !== "object") {
476
+ return;
477
+ }
478
+ const providerService = strapi.plugin("upload")?.service?.("provider");
479
+ const nextFormats = {};
480
+ const removedFormats = [];
481
+ for (const [k, fmt] of Object.entries(fileRecord.formats)) {
482
+ if (k.startsWith("ci_")) {
483
+ removedFormats.push(fmt);
484
+ } else {
485
+ nextFormats[k] = fmt;
486
+ }
487
+ }
488
+ if (removedFormats.length === 0) return;
489
+ if (providerService && typeof providerService.delete === "function") {
490
+ for (const fmt of removedFormats) {
491
+ try {
492
+ await providerService.delete(fmt);
493
+ } catch {
494
+ }
495
+ }
496
+ }
497
+ await strapi.db.query("plugin::upload.file").update({
498
+ where: { id: fileRecord.id },
499
+ data: { formats: nextFormats }
500
+ });
501
+ }
502
+ async function enrichMediaAssetNode(strapi, asset, opts = {}) {
503
+ if (!asset) return asset;
504
+ const isStringInput = typeof asset === "string";
505
+ const rawUrl = isStringInput ? asset : asset.original_url || asset.url || asset.target_url || asset.src || "";
506
+ if (!rawUrl || typeof rawUrl !== "string") return asset;
507
+ const fileRecord = await findUploadFileForAsset(strapi, asset, opts.fileCache);
508
+ if (!fileRecord) {
509
+ return asset;
510
+ }
511
+ const canonicalMasterUrl = fileRecord.url || rawUrl;
512
+ if (!isOptimizableRasterImage(fileRecord.mime, fileRecord.ext || canonicalMasterUrl)) {
513
+ if (isStringInput) return canonicalMasterUrl;
514
+ return {
515
+ ...asset,
516
+ id: fileRecord.id,
517
+ hash: fileRecord.hash,
518
+ original_url: canonicalMasterUrl,
519
+ url: canonicalMasterUrl,
520
+ target_url: canonicalMasterUrl
521
+ };
522
+ }
523
+ const spec = normalizeImageProcessSpec(
524
+ opts.imageSettings,
525
+ opts.defaultAutoMaxW || 1920
526
+ );
527
+ let latestFile = fileRecord;
528
+ let activeVariantUrl;
529
+ if (spec.processMode !== "none") {
530
+ try {
531
+ const primary = await ensureMediaVariant(strapi, latestFile, {
532
+ processMode: spec.processMode,
533
+ w: spec.w,
534
+ h: spec.h,
535
+ q: spec.q,
536
+ rotate: spec.rotate
537
+ });
538
+ latestFile = primary.updatedFile || latestFile;
539
+ if (primary.formatEntry?.url) {
540
+ activeVariantUrl = primary.formatEntry.url;
541
+ }
542
+ } catch (err) {
543
+ strapi.log?.warn?.(
544
+ `[content-input] Image variant generation skipped for "${canonicalMasterUrl}": ${err?.message || err}`
545
+ );
546
+ }
547
+ }
548
+ if (opts.alsoEnsureAutoMaxW && opts.alsoEnsureAutoMaxW > 0 && spec.processMode !== "none" && !(spec.processMode === "auto" && spec.w === opts.alsoEnsureAutoMaxW)) {
549
+ try {
550
+ const secondary = await ensureMediaVariant(strapi, latestFile, {
551
+ processMode: "auto",
552
+ w: opts.alsoEnsureAutoMaxW,
553
+ h: 0,
554
+ q: spec.q
555
+ });
556
+ latestFile = secondary.updatedFile || latestFile;
557
+ } catch {
558
+ }
559
+ }
560
+ if (opts.fileCache && latestFile?.id) {
561
+ opts.fileCache.set(`id:${latestFile.id}`, latestFile);
562
+ if (latestFile.hash) opts.fileCache.set(`hash:${latestFile.hash}`, latestFile);
563
+ if (latestFile.url) opts.fileCache.set(`url:${String(latestFile.url).split("?")[0]}`, latestFile);
564
+ }
565
+ const compactFormats = compactAssetFormats(latestFile.formats);
566
+ if (isStringInput) {
567
+ return activeVariantUrl || canonicalMasterUrl;
568
+ }
569
+ const nextAsset = {
570
+ ...asset,
571
+ id: latestFile.id,
572
+ hash: latestFile.hash,
573
+ original_url: canonicalMasterUrl,
574
+ url: canonicalMasterUrl,
575
+ target_url: canonicalMasterUrl,
576
+ filename: asset.filename || asset.name || latestFile.name || "image",
577
+ mime_type: asset.mime_type || latestFile.mime || "image/webp",
578
+ width: asset.width || latestFile.width || void 0,
579
+ height: asset.height || latestFile.height || void 0
580
+ };
581
+ if (spec.processMode === "none") {
582
+ delete nextAsset.optimized_url;
583
+ } else if (activeVariantUrl) {
584
+ nextAsset.optimized_url = activeVariantUrl;
585
+ }
586
+ if (compactFormats) {
587
+ nextAsset.formats = compactFormats;
588
+ }
589
+ return nextAsset;
590
+ }
591
+ async function runWithConcurrency(tasks, concurrency = 3) {
592
+ const results = new Array(tasks.length);
593
+ let cursor = 0;
594
+ async function worker() {
595
+ while (cursor < tasks.length) {
596
+ const idx = cursor++;
597
+ results[idx] = await tasks[idx]();
598
+ }
599
+ }
600
+ const poolSize = Math.min(Math.max(1, concurrency), tasks.length);
601
+ await Promise.all(Array.from({ length: poolSize }, () => worker()));
602
+ return results;
603
+ }
604
+ async function optimizeHtmlImgSources(strapi, html, fileCache) {
605
+ if (!html || typeof html !== "string" || !html.includes("<img")) return html;
606
+ const imgRegex = /(<img\b[^>]*?\bsrc=(["']))([^"']+)(\2[^>]*>)/gi;
607
+ const matches = Array.from(html.matchAll(imgRegex));
608
+ if (matches.length === 0) return html;
609
+ const replacements = /* @__PURE__ */ new Map();
610
+ const uniqueSrcs = Array.from(new Set(matches.map((m) => m[3]).filter(Boolean)));
611
+ await runWithConcurrency(
612
+ uniqueSrcs.map((srcUrl) => async () => {
613
+ if (!isOptimizableRasterImage(void 0, srcUrl)) return;
614
+ const fileRecord = await findUploadFileForAsset(strapi, srcUrl, fileCache);
615
+ if (!fileRecord) return;
616
+ if (!isOptimizableRasterImage(fileRecord.mime, fileRecord.ext || fileRecord.url)) return;
617
+ try {
618
+ const res = await ensureMediaVariant(strapi, fileRecord, {
619
+ processMode: "auto",
620
+ w: 1600,
621
+ h: 0
622
+ });
623
+ if (res.formatEntry?.url) {
624
+ replacements.set(srcUrl, res.formatEntry.url);
625
+ }
626
+ } catch {
627
+ }
628
+ }),
629
+ 3
630
+ );
631
+ if (replacements.size === 0) return html;
632
+ return html.replace(imgRegex, (full, prefix, _quote, srcVal, suffix) => {
633
+ const nextUrl = replacements.get(srcVal);
634
+ return nextUrl ? `${prefix}${nextUrl}${suffix}` : full;
635
+ });
636
+ }
637
+ async function syncContentInputTreeMedia(strapi, rawValue) {
638
+ if (!rawValue) return rawValue;
639
+ const wasString = typeof rawValue === "string";
640
+ let parsed = rawValue;
641
+ if (wasString) {
642
+ const trimmed = rawValue.trim();
643
+ if (!trimmed) return rawValue;
644
+ try {
645
+ parsed = JSON.parse(trimmed);
646
+ } catch {
647
+ return rawValue;
648
+ }
649
+ }
650
+ if (!Array.isArray(parsed)) {
651
+ return rawValue;
652
+ }
653
+ const rows = JSON.parse(JSON.stringify(parsed));
654
+ const fileCache = /* @__PURE__ */ new Map();
655
+ const jobs = [];
656
+ const scheduleAsset = (holder, key, opts) => {
657
+ const current = holder?.[key];
658
+ if (!current) return;
659
+ jobs.push(async () => {
660
+ holder[key] = await enrichMediaAssetNode(strapi, current, {
661
+ ...opts,
662
+ fileCache
663
+ });
664
+ });
665
+ };
666
+ const scheduleHtml = (holder, key) => {
667
+ const val = holder?.[key];
668
+ if (typeof val !== "string" || !val.includes("<img")) return;
669
+ jobs.push(async () => {
670
+ holder[key] = await optimizeHtmlImgSources(strapi, val, fileCache);
671
+ });
672
+ };
673
+ const walkRows = (rowList) => {
674
+ if (!Array.isArray(rowList)) return;
675
+ for (const row of rowList) {
676
+ if (!row || typeof row !== "object") continue;
677
+ if (row.bgImage) {
678
+ scheduleAsset(row, "bgImage", {
679
+ imageSettings: row.bgOptions?.imageSettings,
680
+ defaultAutoMaxW: 1920
681
+ });
682
+ }
683
+ const blocks = Array.isArray(row.blocks) ? row.blocks : [];
684
+ for (const block of blocks) {
685
+ if (!block || typeof block !== "object") continue;
686
+ if (block.bgImage) {
687
+ scheduleAsset(block, "bgImage", {
688
+ imageSettings: block.bgOptions?.imageSettings,
689
+ defaultAutoMaxW: 1920
690
+ });
691
+ }
692
+ const widgets = Array.isArray(block.widgets) ? block.widgets : [];
693
+ for (const widget of widgets) {
694
+ if (!widget || typeof widget !== "object") continue;
695
+ const wId = widget.id;
696
+ const wOpts = widget.options || {};
697
+ const wData = widget.data;
698
+ if (wId === "gallery") {
699
+ const list = Array.isArray(wData) ? wData : Array.isArray(wData?.images) ? wData.images : null;
700
+ if (list) {
701
+ const popupEnabled = wOpts.popup !== false;
702
+ for (let i = 0; i < list.length; i++) {
703
+ scheduleAsset(list, i, {
704
+ imageSettings: wOpts.imageSettings,
705
+ defaultAutoMaxW: 1600,
706
+ alsoEnsureAutoMaxW: popupEnabled ? 1920 : 0
707
+ });
708
+ }
709
+ }
710
+ } else if (wId === "singleImage" && wData && typeof wData === "object") {
711
+ if (wData.image) {
712
+ scheduleAsset(wData, "image", {
713
+ imageSettings: wOpts.imageSettings || wData.imageSettings,
714
+ defaultAutoMaxW: 1920
715
+ });
716
+ } else if (wData.url || wData.target_url) {
717
+ scheduleAsset(widget, "data", {
718
+ imageSettings: wOpts.imageSettings,
719
+ defaultAutoMaxW: 1920
720
+ });
721
+ }
722
+ } else if (wId === "banner" && wData && typeof wData === "object") {
723
+ if (wData.image) {
724
+ scheduleAsset(wData, "image", {
725
+ imageSettings: wOpts.imageSettings || wData.imageSettings,
726
+ defaultAutoMaxW: 1920
727
+ });
728
+ }
729
+ } else if (wId === "youtubeVideo") {
730
+ if (wOpts.thumbnailImage) {
731
+ scheduleAsset(wOpts, "thumbnailImage", {
732
+ imageSettings: wOpts.imageSettings,
733
+ defaultAutoMaxW: 1280
734
+ });
735
+ }
736
+ if (Array.isArray(wData)) {
737
+ for (const vid of wData) {
738
+ if (vid && typeof vid === "object" && vid.customThumbnail) {
739
+ scheduleAsset(vid, "customThumbnail", {
740
+ imageSettings: wOpts.imageSettings,
741
+ defaultAutoMaxW: 1280
742
+ });
743
+ }
744
+ }
745
+ } else if (wData && typeof wData === "object" && wData.customThumbnail) {
746
+ scheduleAsset(wData, "customThumbnail", {
747
+ imageSettings: wOpts.imageSettings,
748
+ defaultAutoMaxW: 1280
749
+ });
750
+ }
751
+ } else if (wId === "heroSlider" && wData && typeof wData === "object") {
752
+ const globalHeroImgSettings = wData.settings?.imageSettings || wOpts.imageSettings;
753
+ const slides = Array.isArray(wData.slides) ? wData.slides : [];
754
+ for (const slide of slides) {
755
+ if (!slide || typeof slide !== "object") continue;
756
+ if (slide.bgImage) {
757
+ scheduleAsset(slide, "bgImage", {
758
+ imageSettings: slide.imageSettings || globalHeroImgSettings,
759
+ defaultAutoMaxW: 1920
760
+ });
761
+ }
762
+ if (slide.mobileBgImage) {
763
+ scheduleAsset(slide, "mobileBgImage", {
764
+ imageSettings: slide.mobileImageSettings,
765
+ defaultAutoMaxW: 1080
766
+ });
767
+ }
768
+ const layers = Array.isArray(slide.layers) ? slide.layers : [];
769
+ for (const layer of layers) {
770
+ if (layer && typeof layer === "object" && layer.image) {
771
+ scheduleAsset(layer, "image", {
772
+ imageSettings: layer.imageSettings,
773
+ defaultAutoMaxW: 1200
774
+ });
775
+ }
776
+ }
777
+ }
778
+ } else if (wId === "customCard" && wData && typeof wData === "object") {
779
+ const cardImgSettings = wData.design?.imageSettings || wOpts.imageSettings;
780
+ const cards = Array.isArray(wData.cards) ? wData.cards : [];
781
+ for (const card of cards) {
782
+ if (!card || typeof card !== "object") continue;
783
+ if (card.image) {
784
+ scheduleAsset(card, "image", {
785
+ imageSettings: cardImgSettings,
786
+ defaultAutoMaxW: 960
787
+ });
788
+ }
789
+ if (card.authorAvatar) {
790
+ scheduleAsset(card, "authorAvatar", {
791
+ imageSettings: { process: "fit", cWidth: 240, cHeight: 240 },
792
+ defaultAutoMaxW: 240
793
+ });
794
+ }
795
+ }
796
+ } else if (wId === "entityCard" && wData && typeof wData === "object") {
797
+ const ecImgSettings = wOpts.imageSettings || wOpts.cardProps?.imageSettings;
798
+ if (wData.overrides?.image) {
799
+ scheduleAsset(wData.overrides, "image", {
800
+ imageSettings: ecImgSettings,
801
+ defaultAutoMaxW: 960
802
+ });
803
+ }
804
+ if (wData.entity?.image) {
805
+ scheduleAsset(wData.entity, "image", {
806
+ imageSettings: ecImgSettings,
807
+ defaultAutoMaxW: 960
808
+ });
809
+ }
810
+ if (Array.isArray(wData.items)) {
811
+ for (const item of wData.items) {
812
+ if (!item || typeof item !== "object") continue;
813
+ if (item.overrides?.image) {
814
+ scheduleAsset(item.overrides, "image", {
815
+ imageSettings: ecImgSettings,
816
+ defaultAutoMaxW: 960
817
+ });
818
+ }
819
+ if (item.entity?.image) {
820
+ scheduleAsset(item.entity, "image", {
821
+ imageSettings: ecImgSettings,
822
+ defaultAutoMaxW: 960
823
+ });
824
+ }
825
+ }
826
+ }
827
+ } else if (wId === "HtmlEditor") {
828
+ if (typeof wData === "string") {
829
+ scheduleHtml(widget, "data");
830
+ } else if (wData && typeof wData === "object" && typeof wData.content === "string") {
831
+ scheduleHtml(wData, "content");
832
+ }
833
+ } else if (wId === "tab" || wId === "accordion") {
834
+ const nodes = Array.isArray(wData) ? wData : Array.isArray(wData?.nodes) ? wData.nodes : Array.isArray(wData?.tabs) ? wData.tabs : [];
835
+ for (const node of nodes) {
836
+ if (!node || typeof node !== "object") continue;
837
+ if (Array.isArray(node.rows)) walkRows(node.rows);
838
+ if (Array.isArray(node.content)) walkRows(node.content);
839
+ if (Array.isArray(node.content?.data)) walkRows(node.content.data);
840
+ if (typeof node.html === "string") scheduleHtml(node, "html");
841
+ if (typeof node.content === "string") scheduleHtml(node, "content");
842
+ if (typeof node.content?.html === "string") scheduleHtml(node.content, "html");
843
+ }
844
+ } else if (wId === "survey" && wData && typeof wData === "object") {
845
+ const qLists = [wData.questions, wData.survey?.questions].filter(Array.isArray);
846
+ for (const qList of qLists) {
847
+ for (const q of qList) {
848
+ if (!q || typeof q !== "object" || !Array.isArray(q.options)) continue;
849
+ for (const opt of q.options) {
850
+ if (opt && typeof opt === "object" && opt.image) {
851
+ scheduleAsset(opt, "image", {
852
+ defaultAutoMaxW: 800
853
+ });
854
+ }
855
+ }
856
+ }
857
+ }
858
+ } else if (wId === "dataTable" && wData && typeof wData === "object") {
859
+ const cols = Array.isArray(wData.columns) ? wData.columns : [];
860
+ const imageColKeys = cols.filter((c) => c && c.type === "image" && c.key).map((c) => String(c.key));
861
+ const dtRows = Array.isArray(wData.rows) ? wData.rows : [];
862
+ if (imageColKeys.length > 0 && dtRows.length > 0) {
863
+ for (const dtRow of dtRows) {
864
+ if (!dtRow || typeof dtRow !== "object") continue;
865
+ for (const key of imageColKeys) {
866
+ if (dtRow[key]) {
867
+ scheduleAsset(dtRow, key, {
868
+ defaultAutoMaxW: 800
869
+ });
870
+ }
871
+ }
872
+ }
873
+ }
874
+ }
875
+ }
876
+ }
877
+ }
878
+ };
879
+ walkRows(rows);
880
+ if (jobs.length > 0) {
881
+ await runWithConcurrency(jobs, 3);
882
+ }
883
+ return wasString ? JSON.stringify(rows) : rows;
884
+ }
885
+ async function syncSurveyQuestionsMedia(strapi, questions) {
886
+ if (!Array.isArray(questions) || questions.length === 0) return questions;
887
+ const cloned = JSON.parse(JSON.stringify(questions));
888
+ const fileCache = /* @__PURE__ */ new Map();
889
+ const jobs = [];
890
+ for (const q of cloned) {
891
+ if (!q || typeof q !== "object" || !Array.isArray(q.options)) continue;
892
+ for (const opt of q.options) {
893
+ if (opt && typeof opt === "object" && opt.image) {
894
+ jobs.push(async () => {
895
+ opt.image = await enrichMediaAssetNode(strapi, opt.image, {
896
+ defaultAutoMaxW: 800,
897
+ fileCache
898
+ });
899
+ });
900
+ }
901
+ }
902
+ }
903
+ if (jobs.length > 0) {
904
+ await runWithConcurrency(jobs, 3);
905
+ }
906
+ return cloned;
907
+ }
908
+ function collectContentInputModelFields(strapi) {
909
+ const map = /* @__PURE__ */ new Map();
910
+ const inspectSchemas = (schemas) => {
911
+ if (!schemas || typeof schemas !== "object") return;
912
+ for (const [uid, schema] of Object.entries(schemas)) {
913
+ const attrs = schema?.attributes;
914
+ if (!attrs || typeof attrs !== "object") continue;
915
+ const matchingFields = [];
916
+ for (const [fieldName, attrDef] of Object.entries(attrs)) {
917
+ if (attrDef?.customField === "plugin::content-input.content-input") {
918
+ matchingFields.push(fieldName);
919
+ }
920
+ }
921
+ if (matchingFields.length > 0) {
922
+ map.set(uid, matchingFields);
923
+ }
924
+ }
925
+ };
926
+ inspectSchemas(strapi.contentTypes);
927
+ inspectSchemas(strapi.components);
928
+ return map;
929
+ }
39
930
  const bootstrap = async ({ strapi }) => {
40
931
  try {
41
932
  await strapi.plugin("content-input").service("ci-color").ensureSeeded();
@@ -44,12 +935,66 @@ const bootstrap = async ({ strapi }) => {
44
935
  } catch (err) {
45
936
  strapi.log.warn(`[content-input] Bootstrap seed skipped: ${err?.message || err}`);
46
937
  }
938
+ try {
939
+ const modelFieldMap = collectContentInputModelFields(strapi);
940
+ const surveyUid = "plugin::content-input.ci-survey";
941
+ const subscribedModels = Array.from(/* @__PURE__ */ new Set([...modelFieldMap.keys(), surveyUid]));
942
+ if (subscribedModels.length > 0 && strapi.db?.lifecycles?.subscribe) {
943
+ const processEventData = async (event) => {
944
+ const uid = event?.model?.uid;
945
+ const data = event?.params?.data;
946
+ if (!uid || !data || typeof data !== "object") return;
947
+ if (uid === surveyUid) {
948
+ if (Array.isArray(data.questions) && data.questions.length > 0) {
949
+ try {
950
+ data.questions = await syncSurveyQuestionsMedia(strapi, data.questions);
951
+ } catch (err) {
952
+ strapi.log.warn(
953
+ `[content-input] Survey media optimization warning: ${err?.message || err}`
954
+ );
955
+ }
956
+ }
957
+ return;
958
+ }
959
+ const fields = modelFieldMap.get(uid);
960
+ if (!fields || fields.length === 0) return;
961
+ for (const fieldName of fields) {
962
+ if (data[fieldName] !== void 0 && data[fieldName] !== null) {
963
+ try {
964
+ data[fieldName] = await syncContentInputTreeMedia(strapi, data[fieldName]);
965
+ } catch (err) {
966
+ strapi.log.warn(
967
+ `[content-input] Media sync warning on ${uid}.${fieldName}: ${err?.message || err}`
968
+ );
969
+ }
970
+ }
971
+ }
972
+ };
973
+ strapi.db.lifecycles.subscribe({
974
+ models: subscribedModels,
975
+ async beforeCreate(event) {
976
+ await processEventData(event);
977
+ },
978
+ async beforeUpdate(event) {
979
+ await processEventData(event);
980
+ }
981
+ });
982
+ }
983
+ } catch (err) {
984
+ strapi.log.warn(
985
+ `[content-input] Lifecycle registration skipped: ${err?.message || err}`
986
+ );
987
+ }
47
988
  };
48
989
  const destroy = ({ strapi }) => {
49
990
  };
50
991
  const config = {
51
992
  default: {
52
- previewUrl: "/ci-preview"
993
+ previewUrl: "/ci-preview",
994
+ imageVariantFolder: process.env.CI_IMAGE_VARIANT_FOLDER || "ci-optimized",
995
+ imageVariantFormat: process.env.CI_IMAGE_VARIANT_FORMAT || "webp",
996
+ imageVariantQuality: 85,
997
+ redirectProxyToCdn: true
53
998
  },
54
999
  validator() {
55
1000
  }
@@ -300,10 +1245,6 @@ const ciMenuController = ({ strapi }) => ({
300
1245
  }
301
1246
  }
302
1247
  });
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
1248
  function getCacheDir(strapi) {
308
1249
  const rootDir = strapi?.dirs?.app?.root || process.cwd();
309
1250
  const dir = path__default.default.join(rootDir, ".cache", "content-input-images");
@@ -312,47 +1253,12 @@ function getCacheDir(strapi) {
312
1253
  }
313
1254
  return dir;
314
1255
  }
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
1256
  const ciImageController = ({ strapi }) => ({
353
1257
  /**
354
1258
  * GET /api/content-input/image & GET /content-input/image
355
- * On-the-fly image scaling & cropping powered by sharp with disk + CDN HTTP caching.
1259
+ * Generates `ci-optimized` WebP variants via sharp, uploads to Strapi's Upload Provider (CDN),
1260
+ * persists in `plugin::upload.file.formats`, and issues a 302 redirect when a remote CDN URL is available
1261
+ * (with local byte-stream fallback in local-only environments).
356
1262
  */
357
1263
  async processImage(ctx) {
358
1264
  try {
@@ -361,16 +1267,96 @@ const ciImageController = ({ strapi }) => ({
361
1267
  if (!src) {
362
1268
  return ctx.badRequest("Missing src parameter");
363
1269
  }
364
- const processMode = String(query.process || "fit").toLowerCase();
365
- const w = Math.min(3840, Math.max(0, parseInt(String(query.w || query.cWidth || "0"), 10) || 0));
366
- const h = Math.min(3840, Math.max(0, parseInt(String(query.h || query.cHeight || "0"), 10) || 0));
1270
+ const rawProc = String(query.process || "auto").trim().toLowerCase();
1271
+ const processMode = rawProc === "fit" ? "fit" : rawProc === "widen" ? "widen" : "auto";
1272
+ const w = Math.min(
1273
+ 3840,
1274
+ Math.max(0, parseInt(String(query.w || query.cWidth || "0"), 10) || 0)
1275
+ );
1276
+ const h = Math.min(
1277
+ 3840,
1278
+ Math.max(0, parseInt(String(query.h || query.cHeight || "0"), 10) || 0)
1279
+ );
367
1280
  const q = Math.min(100, Math.max(20, parseInt(String(query.q || "85"), 10) || 85));
368
1281
  const rotate = parseInt(String(query.rotate || "0"), 10) || 0;
369
1282
  const cx = parseInt(String(query.x || "0"), 10) || 0;
370
1283
  const cy = parseInt(String(query.y || "0"), 10) || 0;
371
1284
  const cw = parseInt(String(query.cw || "0"), 10) || 0;
372
1285
  const ch = parseInt(String(query.ch || "0"), 10) || 0;
373
- const requestedFormat = String(query.format || "").toLowerCase();
1286
+ const requestedFormat = String(query.format || "").trim().toLowerCase();
1287
+ const acceptHeader = String(ctx.req?.headers?.accept || "");
1288
+ const wantsJson = query.json === "1" || query.json === "true" || acceptHeader.includes("application/json");
1289
+ const forceNoRedirect = query.redirect === "0" || query.redirect === "false" || query.proxy === "1" || query.proxy === "true";
1290
+ const forceRedirect = query.redirect === "1" || query.redirect === "true";
1291
+ const cfg = getVariantConfig(strapi);
1292
+ if (cw <= 0 && ch <= 0) {
1293
+ const existingFile = await findUploadFileForAsset(strapi, src);
1294
+ if (existingFile && existingFile.id) {
1295
+ if (!isOptimizableRasterImage(existingFile.mime, existingFile.ext || existingFile.url)) {
1296
+ const directUrl = existingFile.url;
1297
+ if (wantsJson) {
1298
+ ctx.body = { url: directUrl, formatKey: null };
1299
+ return;
1300
+ }
1301
+ if (!forceNoRedirect && directUrl && (cfg.redirectProxyToCdn && isAbsoluteHttpUrl(directUrl) || forceRedirect)) {
1302
+ ctx.set("Cache-Control", "public, max-age=86400");
1303
+ ctx.set("Access-Control-Allow-Origin", "*");
1304
+ ctx.status = 302;
1305
+ ctx.redirect(directUrl);
1306
+ return;
1307
+ }
1308
+ } else {
1309
+ const effW2 = w > 0 ? w : processMode === "auto" ? 1920 : 0;
1310
+ const effH2 = processMode === "fit" ? h : 0;
1311
+ if (effW2 > 0 || effH2 > 0) {
1312
+ const variantRes = await ensureMediaVariant(strapi, existingFile, {
1313
+ processMode,
1314
+ w: effW2,
1315
+ h: effH2,
1316
+ q,
1317
+ rotate,
1318
+ requestedFormat: requestedFormat || void 0
1319
+ });
1320
+ const providerUrl = variantRes.formatEntry?.url;
1321
+ if (providerUrl) {
1322
+ if (wantsJson) {
1323
+ ctx.body = {
1324
+ url: providerUrl,
1325
+ formatKey: variantRes.formatKey
1326
+ };
1327
+ return;
1328
+ }
1329
+ if (!forceNoRedirect && (cfg.redirectProxyToCdn && isAbsoluteHttpUrl(providerUrl) || forceRedirect)) {
1330
+ ctx.set("Cache-Control", "public, max-age=86400");
1331
+ ctx.set("Access-Control-Allow-Origin", "*");
1332
+ ctx.set("X-Content-Input-CDN-Url", providerUrl);
1333
+ ctx.status = 302;
1334
+ ctx.redirect(providerUrl);
1335
+ return;
1336
+ }
1337
+ try {
1338
+ const localVariant = await loadSourceBuffer(strapi, providerUrl);
1339
+ const etagLocal = `"ci-${variantRes.formatKey}-${existingFile.hash || existingFile.id}"`;
1340
+ if (ctx.req?.headers?.["if-none-match"] === etagLocal) {
1341
+ ctx.status = 304;
1342
+ return;
1343
+ }
1344
+ const resolvedMime = variantRes.formatEntry?.mime || localVariant.mime || "image/webp";
1345
+ ctx.body = localVariant.buffer;
1346
+ ctx.type = resolvedMime;
1347
+ ctx.set("Content-Type", resolvedMime);
1348
+ ctx.set("Cache-Control", "public, max-age=31536000, immutable");
1349
+ ctx.set("ETag", etagLocal);
1350
+ ctx.set("Access-Control-Allow-Origin", "*");
1351
+ ctx.set("X-Content-Input-CDN-Url", providerUrl);
1352
+ return;
1353
+ } catch {
1354
+ }
1355
+ }
1356
+ }
1357
+ }
1358
+ }
1359
+ }
374
1360
  const cacheKeyRaw = JSON.stringify({
375
1361
  src,
376
1362
  processMode,
@@ -382,11 +1368,11 @@ const ciImageController = ({ strapi }) => ({
382
1368
  cy,
383
1369
  cw,
384
1370
  ch,
385
- requestedFormat
1371
+ requestedFormat: requestedFormat || cfg.defaultFormat
386
1372
  });
387
1373
  const hash = crypto__default.default.createHash("sha1").update(cacheKeyRaw).digest("hex");
388
1374
  const etag = `"ci-${hash}"`;
389
- if (ctx.req.headers["if-none-match"] === etag) {
1375
+ if (!wantsJson && ctx.req?.headers?.["if-none-match"] === etag) {
390
1376
  ctx.status = 304;
391
1377
  return;
392
1378
  }
@@ -395,138 +1381,112 @@ const ciImageController = ({ strapi }) => ({
395
1381
  const binPath = path__default.default.join(cacheDir, `${hash}.bin`);
396
1382
  if (fs__default.default.existsSync(metaPath) && fs__default.default.existsSync(binPath)) {
397
1383
  const meta = JSON.parse(await fs__default.default.promises.readFile(metaPath, "utf8"));
1384
+ if (meta.providerUrl) {
1385
+ if (wantsJson) {
1386
+ ctx.body = { url: meta.providerUrl, formatKey: meta.formatKey || null };
1387
+ return;
1388
+ }
1389
+ if (!forceNoRedirect && (cfg.redirectProxyToCdn && isAbsoluteHttpUrl(meta.providerUrl) || forceRedirect)) {
1390
+ ctx.set("Cache-Control", "public, max-age=86400");
1391
+ ctx.set("Access-Control-Allow-Origin", "*");
1392
+ ctx.set("X-Content-Input-CDN-Url", meta.providerUrl);
1393
+ ctx.status = 302;
1394
+ ctx.redirect(meta.providerUrl);
1395
+ return;
1396
+ }
1397
+ }
398
1398
  const cachedBuffer = await fs__default.default.promises.readFile(binPath);
399
- ctx.set("Content-Type", meta.contentType || "image/jpeg");
1399
+ const cachedMime = meta.contentType || "image/webp";
1400
+ ctx.body = cachedBuffer;
1401
+ ctx.type = cachedMime;
1402
+ ctx.set("Content-Type", cachedMime);
400
1403
  ctx.set("Cache-Control", "public, max-age=31536000, immutable");
401
1404
  ctx.set("ETag", etag);
402
1405
  ctx.set("Access-Control-Allow-Origin", "*");
403
- ctx.body = cachedBuffer;
404
1406
  return;
405
1407
  }
406
1408
  const { buffer: sourceBuffer, mime: sourceMime } = await loadSourceBuffer(strapi, src);
407
- const sharp = getSharp();
408
- let pipeline = sharp(sourceBuffer, { failOn: "none" }).rotate();
409
- if (rotate && [90, 180, 270, -90].includes(rotate)) {
410
- pipeline = pipeline.rotate(rotate);
411
- }
412
- if (cw > 0 && ch > 0) {
413
- pipeline = pipeline.extract({
414
- left: Math.max(0, cx),
415
- top: Math.max(0, cy),
416
- width: cw,
417
- height: ch
418
- });
419
- }
420
- if (processMode === "fit" && w > 0 && h > 0) {
421
- pipeline = pipeline.resize(w, h, {
422
- fit: "cover",
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);
1409
+ const effW = w > 0 ? w : processMode === "auto" ? 1920 : 0;
1410
+ const effH = processMode === "fit" ? h : 0;
1411
+ const rendered = await renderSharpVariantBuffer(sourceBuffer, sourceMime, {
1412
+ processMode,
1413
+ w: effW,
1414
+ h: effH,
1415
+ q,
1416
+ rotate,
1417
+ cx,
1418
+ cy,
1419
+ cw,
1420
+ ch,
1421
+ requestedFormat: requestedFormat || void 0,
1422
+ defaultFormat: cfg.defaultFormat
1423
+ });
1424
+ await fs__default.default.promises.writeFile(binPath, rendered.buffer);
506
1425
  await fs__default.default.promises.writeFile(
507
1426
  metaPath,
508
1427
  JSON.stringify({
509
- contentType: outContentType,
510
- size: outputBuffer.length,
511
- providerUrl
1428
+ contentType: rendered.contentType,
1429
+ size: rendered.buffer.length
512
1430
  })
513
1431
  );
514
- ctx.set("Content-Type", outContentType);
1432
+ if (wantsJson) {
1433
+ ctx.body = { url: src, formatKey: null };
1434
+ return;
1435
+ }
1436
+ ctx.body = rendered.buffer;
1437
+ ctx.type = rendered.contentType;
1438
+ ctx.set("Content-Type", rendered.contentType);
515
1439
  ctx.set("Cache-Control", "public, max-age=31536000, immutable");
516
1440
  ctx.set("ETag", etag);
517
1441
  ctx.set("Access-Control-Allow-Origin", "*");
518
- if (providerUrl) {
519
- ctx.set("X-Content-Input-CDN-Url", providerUrl);
520
- }
521
- ctx.body = outputBuffer;
522
1442
  } catch (err) {
523
1443
  ctx.throw(400, err?.message || "Image processing error");
524
1444
  }
525
1445
  },
1446
+ /**
1447
+ * POST /content-input/media/optimize
1448
+ * Eagerly optimizes one or multiple selected/uploaded Media Library assets into `ci-optimized/*.webp`
1449
+ * on the configured Upload Provider (CDN) and returns enriched CIMediaAsset object(s) with `formats` & `optimized_url`.
1450
+ */
1451
+ async optimizeMedia(ctx) {
1452
+ try {
1453
+ const body = ctx.request.body || {};
1454
+ const imageSettings = body.imageSettings || null;
1455
+ const defaultAutoMaxW = Number(body.defaultAutoMaxW) || 1920;
1456
+ const fileCache = /* @__PURE__ */ new Map();
1457
+ if (Array.isArray(body.assets)) {
1458
+ const enrichedList = [];
1459
+ for (const item of body.assets) {
1460
+ enrichedList.push(
1461
+ await enrichMediaAssetNode(strapi, item, {
1462
+ imageSettings,
1463
+ defaultAutoMaxW,
1464
+ fileCache
1465
+ })
1466
+ );
1467
+ }
1468
+ ctx.body = { data: enrichedList };
1469
+ return;
1470
+ }
1471
+ if (body.asset) {
1472
+ const enriched = await enrichMediaAssetNode(strapi, body.asset, {
1473
+ imageSettings,
1474
+ defaultAutoMaxW,
1475
+ fileCache
1476
+ });
1477
+ ctx.body = { data: enriched };
1478
+ return;
1479
+ }
1480
+ return ctx.badRequest("asset or assets is required");
1481
+ } catch (err) {
1482
+ ctx.throw(500, err?.message || "Failed to optimize media asset");
1483
+ }
1484
+ },
526
1485
  /**
527
1486
  * POST /content-input/media/crop
528
1487
  * 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) or 'duplicate' (saves as new asset).
1488
+ * Supports mode: 'replace' (crops original asset in Media Library & refreshes ci-optimized variants)
1489
+ * or 'duplicate' (saves as new asset).
530
1490
  */
531
1491
  async cropMedia(ctx) {
532
1492
  const tmpDir = await fs__default.default.promises.mkdtemp(path__default.default.join(os__default.default.tmpdir(), "ci-crop-"));
@@ -582,7 +1542,7 @@ const ciImageController = ({ strapi }) => ({
582
1542
  if (ext === ".png" || mime === "image/png") {
583
1543
  pipeline = pipeline.png({ quality: 92 });
584
1544
  } else if (ext === ".webp" || mime === "image/webp") {
585
- pipeline = pipeline.webp({ quality: 90 });
1545
+ pipeline = pipeline.webp({ quality: 90, alphaQuality: 100 });
586
1546
  } else {
587
1547
  pipeline = pipeline.jpeg({ quality: 90, mozjpeg: true });
588
1548
  }
@@ -591,6 +1551,9 @@ const ciImageController = ({ strapi }) => ({
591
1551
  const targetFileName = mode === "duplicate" ? `${body.name || `${baseName}-cropped`}${ext.startsWith(".") ? ext : `.${ext}`}` : existingFile.name || `${baseName}${ext}`;
592
1552
  const tmpFilePath = path__default.default.join(tmpDir, targetFileName);
593
1553
  await fs__default.default.promises.writeFile(tmpFilePath, croppedBuffer);
1554
+ if (mode === "replace") {
1555
+ await clearGeneratedCiVariantsForFile(strapi, existingFile);
1556
+ }
594
1557
  const uploadService = strapi.plugin("upload").service("upload");
595
1558
  const fileInfo = {
596
1559
  name: targetFileName,
@@ -626,6 +1589,17 @@ const ciImageController = ({ strapi }) => ({
626
1589
  );
627
1590
  resultFile = Array.isArray(uploaded) ? uploaded[0] : uploaded;
628
1591
  }
1592
+ if (resultFile?.id) {
1593
+ try {
1594
+ const freshRes = await ensureMediaVariant(strapi, resultFile, {
1595
+ processMode: "auto",
1596
+ w: 1920,
1597
+ h: 0
1598
+ });
1599
+ resultFile = freshRes.updatedFile || resultFile;
1600
+ } catch {
1601
+ }
1602
+ }
629
1603
  ctx.body = { data: resultFile };
630
1604
  } catch (err) {
631
1605
  ctx.throw(500, err?.message || "Failed to crop media asset");
@@ -960,18 +1934,31 @@ const ciSurveyController = ({ strapi }) => ({
960
1934
  async exportResponses(ctx) {
961
1935
  try {
962
1936
  const { id } = ctx.params;
963
- const format = String(ctx.query?.format || "csv").toLowerCase() === "json" ? "json" : "csv";
1937
+ const rawFmt = String(ctx.query?.format || "xlsx").toLowerCase();
1938
+ const format = rawFmt === "json" ? "json" : rawFmt === "csv" ? "csv" : "xlsx";
964
1939
  const locale = String(ctx.query?.locale || "en").trim();
965
1940
  const from = ctx.query?.from ? String(ctx.query.from) : void 0;
966
1941
  const to = ctx.query?.to ? String(ctx.query.to) : void 0;
1942
+ const encoding = String(ctx.query?.encoding || "").toLowerCase();
967
1943
  const exported = await strapi.plugin("content-input").service("ci-survey").exportResponses(id, { format, locale, from, to });
968
1944
  if (!exported) {
969
1945
  return ctx.notFound("Survey not found");
970
1946
  }
1947
+ if (encoding === "base64") {
1948
+ const buf = Buffer.isBuffer(exported.body) ? exported.body : Buffer.from(String(exported.body), "utf8");
1949
+ ctx.status = 200;
1950
+ ctx.body = {
1951
+ filename: exported.filename,
1952
+ contentType: exported.contentType,
1953
+ base64: buf.toString("base64")
1954
+ };
1955
+ return;
1956
+ }
1957
+ ctx.body = exported.body;
1958
+ ctx.type = exported.contentType;
971
1959
  ctx.set("Content-Type", exported.contentType);
972
1960
  ctx.set("Content-Disposition", `attachment; filename="${exported.filename}"`);
973
1961
  ctx.status = 200;
974
- ctx.body = exported.body;
975
1962
  } catch (err) {
976
1963
  ctx.throw(500, err);
977
1964
  }
@@ -1352,6 +2339,14 @@ const routes = {
1352
2339
  policies: []
1353
2340
  }
1354
2341
  },
2342
+ {
2343
+ method: "POST",
2344
+ path: "/media/optimize",
2345
+ handler: "ci-image.optimizeMedia",
2346
+ config: {
2347
+ policies: []
2348
+ }
2349
+ },
1355
2350
  {
1356
2351
  method: "POST",
1357
2352
  path: "/media/crop",
@@ -4273,6 +5268,14 @@ const ciFormService = ({ strapi }) => ({
4273
5268
  }
4274
5269
  }
4275
5270
  }
5271
+ if (imageObj) {
5272
+ try {
5273
+ imageObj = await enrichMediaAssetNode(strapi, imageObj, {
5274
+ defaultAutoMaxW: 960
5275
+ });
5276
+ } catch {
5277
+ }
5278
+ }
4276
5279
  const pluralName = ct.info?.pluralName || "items";
4277
5280
  const slugField = ["slug", "path", "url", "permalink"].find(
4278
5281
  (k) => typeof entry[k] === "string" && entry[k].trim()
@@ -4303,6 +5306,7 @@ const ciFormService = ({ strapi }) => ({
4303
5306
  };
4304
5307
  }
4305
5308
  });
5309
+ const XLSX = XLSXNs__namespace?.utils ? XLSXNs__namespace : XLSXNs__namespace?.default || XLSXNs__namespace;
4306
5310
  function evalSingleRule(rule, answers) {
4307
5311
  const targetVal = answers ? answers[rule.questionKey] : void 0;
4308
5312
  const op = rule.operator;
@@ -4679,6 +5683,7 @@ function computeSurveyAnalytics(survey, rawResponses, filter = {}) {
4679
5683
  }
4680
5684
  const distribution = Object.keys(distMap).map(Number).sort((a, b) => a - b).map((value) => ({
4681
5685
  value,
5686
+ labels: q.scaleLabels ? q.scaleLabels[String(value)] : void 0,
4682
5687
  count: distMap[value] || 0,
4683
5688
  percentage: answeredCount > 0 ? Math.round((distMap[value] || 0) / answeredCount * 1e3) / 10 : 0
4684
5689
  }));
@@ -4689,6 +5694,7 @@ function computeSurveyAnalytics(survey, rawResponses, filter = {}) {
4689
5694
  max: maxVal,
4690
5695
  lowLabel: q.lowLabel,
4691
5696
  highLabel: q.highLabel,
5697
+ scaleLabels: q.scaleLabels,
4692
5698
  average: answeredCount > 0 ? Math.round(sum / answeredCount * 100) / 100 : 0,
4693
5699
  distribution,
4694
5700
  npsBreakdown: q.type === "nps" ? {
@@ -4877,6 +5883,7 @@ function computePublicSurveyResults(survey, rawResponses) {
4877
5883
  optionsBreakdown: qs.optionsBreakdown,
4878
5884
  average: qs.average,
4879
5885
  distribution: qs.distribution,
5886
+ scaleLabels: qs.scaleLabels,
4880
5887
  npsBreakdown: qs.npsBreakdown,
4881
5888
  rankingBreakdown: qs.rankingBreakdown
4882
5889
  }))
@@ -4889,9 +5896,17 @@ function escapeCsvCell(val) {
4889
5896
  }
4890
5897
  return str;
4891
5898
  }
4892
- function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
5899
+ function buildSurveyResponseExportAoA(survey, rawResponses, locale = "en") {
5900
+ const tr = String(locale || "").toLowerCase().startsWith("tr");
4893
5901
  const activeQuestions = (survey.questions || []).filter((q) => q && q.type !== "statement");
4894
- const headers = [
5902
+ const headers = tr ? [
5903
+ "Yanıt ID",
5904
+ "Gönderim Tarihi",
5905
+ "Dil",
5906
+ "Süre (sn)",
5907
+ "NPS Puanı",
5908
+ "NPS Kategorisi"
5909
+ ] : [
4895
5910
  "Response ID",
4896
5911
  "Submitted At",
4897
5912
  "Locale",
@@ -4909,18 +5924,18 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
4909
5924
  } else {
4910
5925
  headers.push(`${qTitle} (${q.key})`);
4911
5926
  if (q.allowOther) {
4912
- headers.push(`${qTitle} [Other Text]`);
5927
+ headers.push(`${qTitle} [${tr ? "Diğer Açıklama" : "Other Text"}]`);
4913
5928
  }
4914
5929
  }
4915
5930
  }
4916
- const lines = [headers.map(escapeCsvCell).join(",")];
5931
+ const rows = [];
4917
5932
  for (const r of rawResponses || []) {
4918
5933
  const rowCells = [
4919
5934
  String(r.id || r.documentId || ""),
4920
5935
  String(r.submittedAt || r.createdAt || ""),
4921
5936
  String(r.locale || ""),
4922
- String(r.durationSeconds ?? ""),
4923
- r.npsValue !== null && r.npsValue !== void 0 ? String(r.npsValue) : "",
5937
+ typeof r.durationSeconds === "number" ? r.durationSeconds : String(r.durationSeconds ?? ""),
5938
+ typeof r.npsValue === "number" ? r.npsValue : r.npsValue !== null && r.npsValue !== void 0 && r.npsValue !== "" ? Number(r.npsValue) : "",
4924
5939
  String(r.npsCategory || "")
4925
5940
  ];
4926
5941
  for (const q of activeQuestions) {
@@ -4937,7 +5952,7 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
4937
5952
  } else if (Array.isArray(q.options) && q.options.length > 0) {
4938
5953
  if (Array.isArray(ans)) {
4939
5954
  const mapped = ans.map((optId) => {
4940
- if (optId === "__other__") return locale === "tr" ? "Diğer" : "Other";
5955
+ if (optId === "__other__") return tr ? "Diğer" : "Other";
4941
5956
  const found = q.options.find((o) => o.id === optId);
4942
5957
  return found ? resolveLocalizedText(found.labels, locale, optId) : optId;
4943
5958
  });
@@ -4945,7 +5960,7 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
4945
5960
  } else if (ans !== void 0 && ans !== null && ans !== "") {
4946
5961
  const strAns = String(ans);
4947
5962
  if (strAns === "__other__") {
4948
- rowCells.push(locale === "tr" ? "Diğer" : "Other");
5963
+ rowCells.push(tr ? "Diğer" : "Other");
4949
5964
  } else {
4950
5965
  const found = q.options.find((o) => o.id === strAns);
4951
5966
  rowCells.push(found ? resolveLocalizedText(found.labels, locale, strAns) : strAns);
@@ -4957,16 +5972,131 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
4957
5972
  rowCells.push(String(r.otherTexts?.[q.key] || ""));
4958
5973
  }
4959
5974
  } else {
4960
- rowCells.push(ans === void 0 || ans === null ? "" : String(ans));
5975
+ if (q.type === "likert_scale" && q.scaleLabels && ans !== void 0 && ans !== null && ans !== "") {
5976
+ const ptLbl = resolveLocalizedText(q.scaleLabels[String(ans)], locale, "");
5977
+ rowCells.push(ptLbl ? `${ans} - ${ptLbl}` : Number.isNaN(Number(ans)) ? String(ans) : Number(ans));
5978
+ } else if ((q.type === "nps" || q.type === "star_rating" || q.type === "likert_scale") && ans !== void 0 && ans !== null && ans !== "" && !Number.isNaN(Number(ans))) {
5979
+ rowCells.push(Number(ans));
5980
+ } else {
5981
+ rowCells.push(ans === void 0 || ans === null ? "" : String(ans));
5982
+ }
4961
5983
  if (q.allowOther) {
4962
5984
  rowCells.push(String(r.otherTexts?.[q.key] || ""));
4963
5985
  }
4964
5986
  }
4965
5987
  }
4966
- lines.push(rowCells.map(escapeCsvCell).join(","));
5988
+ rows.push(rowCells);
5989
+ }
5990
+ return { headers, rows };
5991
+ }
5992
+ function computeAutoColWidths(aoa) {
5993
+ const colCount = aoa.reduce((m, r) => Math.max(m, r.length), 0);
5994
+ const widths = [];
5995
+ for (let c = 0; c < colCount; c++) {
5996
+ let maxLen = 12;
5997
+ for (let r = 0; r < Math.min(aoa.length, 300); r++) {
5998
+ const cell = aoa[r]?.[c];
5999
+ const str = cell === null || cell === void 0 ? "" : String(cell);
6000
+ if (str.length > maxLen) maxLen = str.length;
6001
+ }
6002
+ widths.push({ wch: Math.min(54, maxLen + 3) });
6003
+ }
6004
+ return widths;
6005
+ }
6006
+ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
6007
+ const { headers, rows } = buildSurveyResponseExportAoA(survey, rawResponses, locale);
6008
+ const lines = [headers.map(escapeCsvCell).join(",")];
6009
+ for (const r of rows) {
6010
+ lines.push(r.map(escapeCsvCell).join(","));
4967
6011
  }
4968
6012
  return `\uFEFF${lines.join("\r\n")}`;
4969
6013
  }
6014
+ function exportSurveyResponsesToXlsxBuffer(survey, rawResponses, locale = "en") {
6015
+ const tr = String(locale || "").toLowerCase().startsWith("tr");
6016
+ const { headers, rows } = buildSurveyResponseExportAoA(survey, rawResponses, locale);
6017
+ const responsesAoA = [headers, ...rows];
6018
+ const wb = XLSX.utils.book_new();
6019
+ const wsResponses = XLSX.utils.aoa_to_sheet(responsesAoA);
6020
+ wsResponses["!cols"] = computeAutoColWidths(responsesAoA);
6021
+ XLSX.utils.book_append_sheet(wb, wsResponses, tr ? "Yanitlar" : "Responses");
6022
+ const analytics = computeSurveyAnalytics(survey, rawResponses);
6023
+ const s = analytics.summary;
6024
+ const summaryAoA = [
6025
+ [tr ? "Anket Başlığı" : "Survey Title", resolveLocalizedText(survey.titleI18n, locale, survey.title)],
6026
+ ["Survey Slug", survey.slug],
6027
+ [tr ? "Dışa Aktarım Tarihi" : "Exported At", (/* @__PURE__ */ new Date()).toISOString()],
6028
+ [tr ? "Toplam Yanıt" : "Total Responses", s.totalResponses],
6029
+ [tr ? "Ortalama Süre (sn)" : "Average Duration (s)", s.avgDurationSeconds],
6030
+ [tr ? "Medyan Süre (sn)" : "Median Duration (s)", s.medianDurationSeconds]
6031
+ ];
6032
+ if (s.nps?.hasNps) {
6033
+ summaryAoA.push(
6034
+ ["Net Promoter Score (NPS)", s.nps.score ?? 0],
6035
+ [
6036
+ tr ? "NPS Dağılımı" : "NPS Breakdown",
6037
+ `Promoters: ${s.nps.promoters} (${s.nps.promotersPct}%) | Passives: ${s.nps.passives} (${s.nps.passivesPct}%) | Detractors: ${s.nps.detractors} (${s.nps.detractorsPct}%)`
6038
+ ]
6039
+ );
6040
+ }
6041
+ summaryAoA.push(
6042
+ [],
6043
+ tr ? ["Soru Anahtarı", "Soru Başlığı", "Tip", "Seçenek / Kriter", "Adet / Ort.", "Yüzde (%)"] : ["Question Key", "Question Title", "Type", "Option / Metric", "Count / Avg", "Share (%)"]
6044
+ );
6045
+ for (const qs of analytics.questionStats) {
6046
+ const qTitle = resolveLocalizedText(qs.title, locale, qs.key);
6047
+ if (Array.isArray(qs.optionsBreakdown)) {
6048
+ for (const opt of qs.optionsBreakdown) {
6049
+ const optLbl = opt.id === "__other__" ? tr ? "Diğer" : "Other" : resolveLocalizedText(opt.labels, locale, opt.id);
6050
+ summaryAoA.push([qs.key, qTitle, qs.type, optLbl, opt.count, opt.percentage]);
6051
+ }
6052
+ } else if (Array.isArray(qs.distribution)) {
6053
+ summaryAoA.push([
6054
+ qs.key,
6055
+ qTitle,
6056
+ qs.type,
6057
+ tr ? "Ortalama Puan" : "Average Score",
6058
+ qs.average,
6059
+ ""
6060
+ ]);
6061
+ for (const d of qs.distribution) {
6062
+ const ptLbl = d.labels ? resolveLocalizedText(d.labels, locale, "") : "";
6063
+ summaryAoA.push([
6064
+ qs.key,
6065
+ qTitle,
6066
+ qs.type,
6067
+ ptLbl ? `${d.value} - ${ptLbl}` : String(d.value),
6068
+ d.count,
6069
+ d.percentage
6070
+ ]);
6071
+ }
6072
+ } else if (Array.isArray(qs.rankingBreakdown)) {
6073
+ for (const rk of qs.rankingBreakdown) {
6074
+ summaryAoA.push([
6075
+ qs.key,
6076
+ qTitle,
6077
+ qs.type,
6078
+ resolveLocalizedText(rk.labels, locale, rk.id),
6079
+ rk.averageRank,
6080
+ rk.scorePercentage
6081
+ ]);
6082
+ }
6083
+ } else {
6084
+ summaryAoA.push([
6085
+ qs.key,
6086
+ qTitle,
6087
+ qs.type,
6088
+ tr ? "Toplam Yanıt" : "Answered Count",
6089
+ qs.answeredCount || 0,
6090
+ ""
6091
+ ]);
6092
+ }
6093
+ }
6094
+ const wsSummary = XLSX.utils.aoa_to_sheet(summaryAoA);
6095
+ wsSummary["!cols"] = computeAutoColWidths(summaryAoA);
6096
+ XLSX.utils.book_append_sheet(wb, wsSummary, tr ? "Ozet_Istatistik" : "Summary");
6097
+ const out = XLSX.write(wb, { type: "buffer", bookType: "xlsx" });
6098
+ return Buffer.isBuffer(out) ? out : Buffer.from(out);
6099
+ }
4970
6100
  const SURVEY_UID = "plugin::content-input.ci-survey";
4971
6101
  const SURVEY_RESPONSE_UID = "plugin::content-input.ci-survey-response";
4972
6102
  let activeSeedPromise = null;
@@ -5272,6 +6402,12 @@ const ciSurveyService = ({ strapi }) => ({
5272
6402
  settings: payload.settings ?? existing?.settings ?? {},
5273
6403
  version: existing ? Number(existing.version || 1) + 1 : 1
5274
6404
  };
6405
+ if (Array.isArray(recordData.questions) && recordData.questions.length > 0) {
6406
+ try {
6407
+ recordData.questions = await syncSurveyQuestionsMedia(strapi, recordData.questions);
6408
+ } catch {
6409
+ }
6410
+ }
5275
6411
  if (existing) {
5276
6412
  const updated = await strapi.db.query(SURVEY_UID).update({
5277
6413
  where: { id: existing.id },
@@ -5532,6 +6668,18 @@ const ciSurveyService = ({ strapi }) => ({
5532
6668
  return true;
5533
6669
  });
5534
6670
  }
6671
+ if (options2.format === "xlsx") {
6672
+ const xlsxBuf = exportSurveyResponsesToXlsxBuffer(
6673
+ survey,
6674
+ responses,
6675
+ options2.locale || "en"
6676
+ );
6677
+ return {
6678
+ filename: `${survey.slug}-responses.xlsx`,
6679
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
6680
+ body: xlsxBuf
6681
+ };
6682
+ }
5535
6683
  if (options2.format === "json") {
5536
6684
  return {
5537
6685
  filename: `${survey.slug}-responses.json`,
@@ -6075,33 +7223,48 @@ const ciColorService = ({ strapi }) => ({
6075
7223
  entries = [];
6076
7224
  }
6077
7225
  const collectionLabelText = ct.info?.displayName || uid;
6078
- const sanitizedRows = (entries || []).map((entry) => {
6079
- const row = {};
6080
- for (const f of allowedFields) {
6081
- if (f.key === "collectionLabel" && entry.collectionLabel === void 0) {
6082
- row.collectionLabel = collectionLabelText;
6083
- continue;
6084
- }
6085
- if (f.key === "url" && entry.url === void 0) {
6086
- const slugStr = entry.slug ? String(entry.slug).trim() : "";
6087
- row.url = slugStr ? slugStr === "home" ? "/" : `/${slugStr.replace(/^\/+/, "")}` : "";
6088
- continue;
6089
- }
6090
- const val = entry[f.key];
6091
- if (val !== null && val !== void 0 && typeof val === "object") {
6092
- if (Array.isArray(val)) {
6093
- row[f.key] = val[0]?.url || `${val.length} item`;
6094
- } else if (val.url) {
6095
- row[f.key] = val.url;
7226
+ const fileCache = /* @__PURE__ */ new Map();
7227
+ const sanitizedRows = await Promise.all(
7228
+ (entries || []).map(async (entry) => {
7229
+ const row = {};
7230
+ for (const f of allowedFields) {
7231
+ if (f.key === "collectionLabel" && entry.collectionLabel === void 0) {
7232
+ row.collectionLabel = collectionLabelText;
7233
+ continue;
7234
+ }
7235
+ if (f.key === "url" && entry.url === void 0) {
7236
+ const slugStr = entry.slug ? String(entry.slug).trim() : "";
7237
+ row.url = slugStr ? slugStr === "home" ? "/" : `/${slugStr.replace(/^\/+/, "")}` : "";
7238
+ continue;
7239
+ }
7240
+ const val = entry[f.key];
7241
+ if (val !== null && val !== void 0 && typeof val === "object") {
7242
+ if (Array.isArray(val)) {
7243
+ if (val[0]?.url) {
7244
+ const enriched = await enrichMediaAssetNode(strapi, val[0], {
7245
+ defaultAutoMaxW: 800,
7246
+ fileCache
7247
+ });
7248
+ row[f.key] = enriched?.optimized_url || enriched?.url || val[0].url;
7249
+ } else {
7250
+ row[f.key] = `${val.length} item`;
7251
+ }
7252
+ } else if (val.url) {
7253
+ const enriched = await enrichMediaAssetNode(strapi, val, {
7254
+ defaultAutoMaxW: 800,
7255
+ fileCache
7256
+ });
7257
+ row[f.key] = enriched?.optimized_url || enriched?.url || val.url;
7258
+ } else {
7259
+ row[f.key] = "";
7260
+ }
6096
7261
  } else {
6097
- row[f.key] = "";
7262
+ row[f.key] = val ?? "";
6098
7263
  }
6099
- } else {
6100
- row[f.key] = val ?? "";
6101
7264
  }
6102
- }
6103
- return row;
6104
- });
7265
+ return row;
7266
+ })
7267
+ );
6105
7268
  return {
6106
7269
  uid,
6107
7270
  displayName: ct.info?.displayName || uid,