@littlebox/strapi-suite 1.0.51 → 1.0.54

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 (49) hide show
  1. package/README.md +29 -0
  2. package/dist/_chunks/{App-C7RgdLC-.js → App-B7_8BaVG.js} +557 -35
  3. package/dist/_chunks/{App-b_1MuDrk.mjs → App-BfGB2pF_.mjs} +550 -28
  4. package/dist/_chunks/{SlugInput-DlOanbzA.mjs → SlugInput-CvgVtZza.mjs} +1 -2
  5. package/dist/_chunks/{SlugInput-DvQWzpBu.js → SlugInput-eCwgqJtH.js} +3 -4
  6. package/dist/_chunks/{en-CGJcJfk1.js → en-D89cXiov.js} +46 -1
  7. package/dist/_chunks/{en-CRSiVe4w.mjs → en-knG97mCH.mjs} +46 -1
  8. package/dist/_chunks/{index-C3MUddO-.mjs → index-97f0S4q6.mjs} +2270 -73
  9. package/dist/_chunks/{index-UZTUyNY3.js → index-DnXsi_Ar.js} +2292 -78
  10. package/dist/admin/index.js +1 -1
  11. package/dist/admin/index.mjs +2 -2
  12. package/dist/admin/src/components/DocumentTranslateBox.d.ts +5 -0
  13. package/dist/admin/src/components/DocumentTranslateModal.d.ts +11 -0
  14. package/dist/admin/src/components/TranslationAiModal.d.ts +8 -0
  15. package/dist/admin/src/components/TranslationSettingsModal.d.ts +6 -0
  16. package/dist/admin/src/contexts/settings.d.ts +1 -0
  17. package/dist/admin/src/core/config.d.ts +1 -0
  18. package/dist/admin/src/core/gateways/aiGateway.d.ts +19 -0
  19. package/dist/admin/src/core/gateways/documentGateway.d.ts +15 -0
  20. package/dist/admin/src/core/gateways/translationGateway.d.ts +13 -0
  21. package/dist/admin/src/core/usecases/translateDocument.d.ts +33 -0
  22. package/dist/admin/src/core/usecases/translateWithAi.d.ts +17 -0
  23. package/dist/admin/src/core/utils/documentFields.d.ts +23 -0
  24. package/dist/admin/src/core/utils/tabs.d.ts +53 -0
  25. package/dist/admin/src/ctb/TabSelect.d.ts +31 -0
  26. package/dist/admin/src/ctb/TabsEditor.d.ts +21 -0
  27. package/dist/admin/src/ctb/registerTabsInContentTypeBuilder.d.ts +1 -0
  28. package/dist/admin/src/ctb/tabBadges.d.ts +14 -0
  29. package/dist/admin/src/editView/TabSection.d.ts +6 -0
  30. package/dist/admin/src/editView/TabsBar.d.ts +10 -0
  31. package/dist/admin/src/editView/mutateEditViewLayout.d.ts +12 -0
  32. package/dist/admin/src/editView/sectionVisibility.d.ts +7 -0
  33. package/dist/admin/src/editView/tabsStore.d.ts +13 -0
  34. package/dist/server/index.js +812 -392
  35. package/dist/server/index.mjs +812 -392
  36. package/dist/server/src/config/index.d.ts +4 -0
  37. package/dist/server/src/controllers/index.d.ts +6 -0
  38. package/dist/server/src/controllers/modules/ai-translation.d.ts +7 -0
  39. package/dist/server/src/controllers/modules/translation.d.ts +1 -0
  40. package/dist/server/src/index.d.ts +22 -1
  41. package/dist/server/src/middlewares/tabs.d.ts +4 -0
  42. package/dist/server/src/services/app/setting.d.ts +3 -1
  43. package/dist/server/src/services/index.d.ts +16 -1
  44. package/dist/server/src/services/modules/ai-translation.d.ts +35 -0
  45. package/dist/server/src/utils/groupByContentTypeTabs.d.ts +7 -0
  46. package/dist/server/src/utils/tabs.d.ts +17 -0
  47. package/package.json +6 -3
  48. package/dist/_chunks/convertToSlug-DmgViUjP.mjs +0 -84
  49. package/dist/_chunks/convertToSlug-DqHa9ej4.js +0 -83
@@ -1,6 +1,10 @@
1
1
  const PLUGIN_ID = "littlebox-strapi-suite";
2
2
  const SLUG_LANGUAGE_STRATEGY = "language";
3
3
  const SLUG_CONTENT_STRATEGY = "content";
4
+ const AI_TRANSLATION_MODULE = "translation";
5
+ const AI_TRANSLATION_DEFAULT_MODEL = "gpt-4o";
6
+ const AI_TRANSLATION_BATCH_SIZE = 40;
7
+ const OPENAI_CHAT_COMPLETIONS_URL = "https://api.openai.com/v1/chat/completions";
4
8
  const config = {
5
9
  default: {
6
10
  pluginId: PLUGIN_ID,
@@ -396,78 +400,104 @@ async function deleteAttributes(event, config2) {
396
400
  }
397
401
  const bootstrap = async ({ strapi: strapi2 }) => {
398
402
  const config2 = strapi2.config.get(`plugin::${PLUGIN_ID}`);
399
- try {
400
- await strapi2.db.query(config2.uuid.app.setting).createMany({
401
- data: [
402
- {
403
- module: "menu",
404
- property: "active",
405
- type: "boolean",
406
- value: "true"
407
- },
408
- {
409
- module: "attribute",
410
- property: "active",
411
- type: "boolean",
412
- value: "true"
413
- },
414
- {
415
- module: "parameter",
416
- property: "active",
417
- type: "boolean",
418
- value: "true"
419
- },
420
- {
421
- module: "translation",
422
- property: "active",
423
- type: "boolean",
424
- value: "true"
425
- },
426
- {
427
- module: "slug",
428
- property: "active",
429
- type: "boolean",
430
- value: "true"
431
- },
432
- {
433
- module: "slug",
434
- property: "showDefaultLanguage",
435
- type: "boolean",
436
- value: "false"
437
- },
438
- {
439
- module: "slug",
440
- property: "homepageContentId",
441
- type: "string",
442
- value: null
443
- },
444
- {
445
- module: "slug",
446
- property: "homepageContentModel",
447
- type: "string",
448
- value: null
449
- },
450
- {
451
- module: "slug",
452
- property: "homepageSlugStrategy",
453
- type: "string",
454
- value: "language"
455
- },
456
- {
457
- module: "template",
458
- property: "active",
459
- type: "boolean",
460
- value: "true"
461
- },
462
- {
463
- module: "locale",
464
- property: "active",
465
- type: "boolean",
466
- value: "true"
403
+ const defaultSettings = [
404
+ {
405
+ module: "menu",
406
+ property: "active",
407
+ type: "boolean",
408
+ value: "true"
409
+ },
410
+ {
411
+ module: "attribute",
412
+ property: "active",
413
+ type: "boolean",
414
+ value: "true"
415
+ },
416
+ {
417
+ module: "parameter",
418
+ property: "active",
419
+ type: "boolean",
420
+ value: "true"
421
+ },
422
+ {
423
+ module: "translation",
424
+ property: "active",
425
+ type: "boolean",
426
+ value: "true"
427
+ },
428
+ {
429
+ module: "translation",
430
+ property: "aiEnabled",
431
+ type: "boolean",
432
+ value: "false"
433
+ },
434
+ {
435
+ module: "translation",
436
+ property: "aiApiKey",
437
+ type: "string",
438
+ value: null
439
+ },
440
+ {
441
+ module: "translation",
442
+ property: "aiModel",
443
+ type: "string",
444
+ value: "gpt-4o"
445
+ },
446
+ {
447
+ module: "slug",
448
+ property: "active",
449
+ type: "boolean",
450
+ value: "true"
451
+ },
452
+ {
453
+ module: "slug",
454
+ property: "showDefaultLanguage",
455
+ type: "boolean",
456
+ value: "false"
457
+ },
458
+ {
459
+ module: "slug",
460
+ property: "homepageContentId",
461
+ type: "string",
462
+ value: null
463
+ },
464
+ {
465
+ module: "slug",
466
+ property: "homepageContentModel",
467
+ type: "string",
468
+ value: null
469
+ },
470
+ {
471
+ module: "slug",
472
+ property: "homepageSlugStrategy",
473
+ type: "string",
474
+ value: "language"
475
+ },
476
+ {
477
+ module: "template",
478
+ property: "active",
479
+ type: "boolean",
480
+ value: "true"
481
+ },
482
+ {
483
+ module: "locale",
484
+ property: "active",
485
+ type: "boolean",
486
+ value: "true"
487
+ }
488
+ ];
489
+ for (const setting of defaultSettings) {
490
+ try {
491
+ const current = await strapi2.db.query(config2.uuid.app.setting).findOne({
492
+ where: {
493
+ module: setting.module,
494
+ property: setting.property
467
495
  }
468
- ]
469
- });
470
- } catch (e) {
496
+ });
497
+ if (current) continue;
498
+ await strapi2.db.query(config2.uuid.app.setting).create({ data: setting });
499
+ } catch (e) {
500
+ }
471
501
  }
472
502
  try {
473
503
  await strapi2.db.query(config2.uuid.modules.template).createMany({
@@ -512,12 +542,122 @@ const bootstrap = async ({ strapi: strapi2 }) => {
512
542
  };
513
543
  const destroy = ({ strapi: strapi2 }) => {
514
544
  };
545
+ const TABS_PLUGIN_KEY = "littlebox-strapi-suite";
546
+ const SYSTEM_KEYS = [
547
+ "id",
548
+ "documentId",
549
+ "locale",
550
+ "createdAt",
551
+ "updatedAt",
552
+ "publishedAt",
553
+ "createdBy",
554
+ "updatedBy",
555
+ "localizations"
556
+ ];
557
+ function toTabKey(name) {
558
+ return (name ?? "").normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/\s+/g, "_").replace(/[^a-z0-9_]/g, "").replace(/_+/g, "_").replace(/^_+|_+$/g, "");
559
+ }
560
+ function readTabs(pluginOptions2) {
561
+ const tabs = pluginOptions2?.[TABS_PLUGIN_KEY]?.tabs;
562
+ if (!Array.isArray(tabs)) return [];
563
+ return tabs.filter((tab) => tab && typeof tab.id === "string" && typeof tab.name === "string");
564
+ }
565
+ function readAttributeTabId(attribute) {
566
+ const id = attribute?.pluginOptions?.[TABS_PLUGIN_KEY]?.tab;
567
+ return typeof id === "string" && id !== "" ? id : null;
568
+ }
569
+ function buildTabGroups(tabs, attributes2, onConflict) {
570
+ const candidates = tabs.map((tab) => ({
571
+ tab,
572
+ key: toTabKey(tab.name),
573
+ fields: Object.entries(attributes2).filter(([, attribute]) => readAttributeTabId(attribute) === tab.id).map(([name]) => name)
574
+ })).filter((group) => group.fields.length > 0);
575
+ const reservedKeys = /* @__PURE__ */ new Set([...SYSTEM_KEYS, ...Object.keys(attributes2)]);
576
+ const usedKeys = /* @__PURE__ */ new Set();
577
+ return candidates.filter((group) => {
578
+ if (group.key === "" || reservedKeys.has(group.key) || usedKeys.has(group.key)) {
579
+ onConflict?.(group.tab, group.key);
580
+ return false;
581
+ }
582
+ usedKeys.add(group.key);
583
+ return true;
584
+ });
585
+ }
586
+ function groupEntryByTabs(entry, groups) {
587
+ if (!entry || typeof entry !== "object" || Array.isArray(entry) || groups.length === 0) {
588
+ return entry;
589
+ }
590
+ const fieldToKey = /* @__PURE__ */ new Map();
591
+ groups.forEach((group) => group.fields.forEach((field) => fieldToKey.set(field, group.key)));
592
+ const result = {};
593
+ const grouped = {};
594
+ Object.entries(entry).forEach(([name, value]) => {
595
+ const key = fieldToKey.get(name);
596
+ if (key === void 0) {
597
+ result[name] = value;
598
+ } else {
599
+ (grouped[key] ??= {})[name] = value;
600
+ }
601
+ });
602
+ groups.forEach((group) => {
603
+ if (grouped[group.key]) result[group.key] = grouped[group.key];
604
+ });
605
+ return result;
606
+ }
607
+ function groupDataByTabs(data, groups) {
608
+ if (groups.length === 0) return data;
609
+ return Array.isArray(data) ? data.map((entry) => groupEntryByTabs(entry, groups)) : groupEntryByTabs(data, groups);
610
+ }
611
+ function parseHandlerUid(handler) {
612
+ if (typeof handler !== "string") return null;
613
+ const match = handler.match(/^(.+)\.(find|findOne)$/);
614
+ return match ? match[1] : null;
615
+ }
616
+ function createContentTypeTabsGrouper(strapi2) {
617
+ const warned = /* @__PURE__ */ new Set();
618
+ return function groupByContentTypeTabs(uid, data) {
619
+ try {
620
+ const contentType = strapi2.contentType(uid);
621
+ if (!contentType) return data;
622
+ const tabs = readTabs(contentType.pluginOptions);
623
+ if (tabs.length === 0) return data;
624
+ const groups = buildTabGroups(tabs, contentType.attributes ?? {}, (tab, key) => {
625
+ const id = `${uid}:${tab.id}`;
626
+ if (warned.has(id)) return;
627
+ warned.add(id);
628
+ strapi2.log.warn(
629
+ `[littlebox-strapi-suite] Tab "${tab.name}" of ${uid} was not grouped: the key "${key}" is empty or conflicts with a field or another tab.`
630
+ );
631
+ });
632
+ return groupDataByTabs(data, groups);
633
+ } catch (error) {
634
+ strapi2.log.error(`[littlebox-strapi-suite] Could not group ${uid} data by tabs: ${error}`);
635
+ return data;
636
+ }
637
+ };
638
+ }
639
+ function createTabsMiddleware({ strapi: strapi2 }) {
640
+ const groupByContentTypeTabs = createContentTypeTabsGrouper(strapi2);
641
+ return async (ctx, next) => {
642
+ await next();
643
+ if (ctx.method !== "GET" || ctx.status !== 200) return;
644
+ const prefix = strapi2.config.get("api.rest.prefix", "/api");
645
+ if (!ctx.path?.startsWith(prefix)) return;
646
+ const body = ctx.body;
647
+ if (!body || typeof body !== "object" || body.data == null) return;
648
+ const uid = parseHandlerUid(ctx.state?.route?.handler);
649
+ if (!uid) return;
650
+ const data = groupByContentTypeTabs(uid, body.data);
651
+ if (data !== body.data) ctx.body = { ...body, data };
652
+ };
653
+ }
515
654
  const register = ({ strapi: strapi2 }) => {
516
655
  strapi2.customFields.register({
517
656
  name: "ltbslug",
518
657
  plugin: PLUGIN_ID,
519
658
  type: "uid"
520
659
  });
660
+ strapi2.server.use(createTabsMiddleware({ strapi: strapi2 }));
521
661
  };
522
662
  const kind$7 = "collectionType";
523
663
  const collectionName$7 = "ltb_st_app_setting";
@@ -1195,6 +1335,9 @@ const TranslationModuleController = ({ strapi: strapi2 }) => ({
1195
1335
  async adminBulkDelete() {
1196
1336
  return await strapi2.plugin(PLUGIN_ID).service("TranslationModuleService").adminBulkDelete();
1197
1337
  },
1338
+ async adminAiTranslate() {
1339
+ return await strapi2.plugin(PLUGIN_ID).service("AiTranslationModuleService").adminTranslate();
1340
+ },
1198
1341
  async getTranslations() {
1199
1342
  return await strapi2.plugin(PLUGIN_ID).service("TranslationModuleService").getTranslations();
1200
1343
  }
@@ -1210,6 +1353,11 @@ const LocalesModuleController = ({ strapi: strapi2 }) => ({
1210
1353
  };
1211
1354
  }
1212
1355
  });
1356
+ const AiTranslationModuleController = ({ strapi: strapi2 }) => ({
1357
+ async adminTranslateStrings() {
1358
+ return await strapi2.plugin(PLUGIN_ID).service("AiTranslationModuleService").adminTranslateStrings();
1359
+ }
1360
+ });
1213
1361
  const controllers = {
1214
1362
  SettingAppController,
1215
1363
  SlugModuleController,
@@ -1218,7 +1366,8 @@ const controllers = {
1218
1366
  MenuModuleController,
1219
1367
  ParameterModuleController,
1220
1368
  TranslationModuleController,
1221
- LocalesModuleController
1369
+ LocalesModuleController,
1370
+ AiTranslationModuleController
1222
1371
  };
1223
1372
  function getModuleName(url) {
1224
1373
  if (url.includes("/pages")) return "slug";
@@ -1493,6 +1642,22 @@ const adminAPIRoutes = [
1493
1642
  policies: ["admin::isAuthenticatedAdmin"]
1494
1643
  }
1495
1644
  },
1645
+ {
1646
+ method: "POST",
1647
+ path: "/admin/ai/strings",
1648
+ handler: "AiTranslationModuleController.adminTranslateStrings",
1649
+ config: {
1650
+ policies: ["admin::isAuthenticatedAdmin"]
1651
+ }
1652
+ },
1653
+ {
1654
+ method: "POST",
1655
+ path: "/admin/translations/actions/ai-translate",
1656
+ handler: "TranslationModuleController.adminAiTranslate",
1657
+ config: {
1658
+ policies: ["admin::isAuthenticatedAdmin"]
1659
+ }
1660
+ },
1496
1661
  {
1497
1662
  method: "POST",
1498
1663
  path: "/admin/translations/actions/delete",
@@ -1544,6 +1709,22 @@ const routes = {
1544
1709
  routes: contentAPIRoutes
1545
1710
  }
1546
1711
  };
1712
+ const SECRET_SETTINGS = [
1713
+ { module: "translation", property: "aiApiKey" }
1714
+ ];
1715
+ function isSecret(module, property) {
1716
+ return SECRET_SETTINGS.some((secret) => secret.module === module && secret.property === property);
1717
+ }
1718
+ function maskSecret(value) {
1719
+ if (!value) return null;
1720
+ if (value.length <= 8) return "********";
1721
+ return `${value.slice(0, 3)}${"*".repeat(8)}${value.slice(-4)}`;
1722
+ }
1723
+ function inferType(value) {
1724
+ if (typeof value === "boolean") return "boolean";
1725
+ if (typeof value === "number") return "number";
1726
+ return "string";
1727
+ }
1547
1728
  function parseSettings(data) {
1548
1729
  const typeParsers = {
1549
1730
  boolean: (value) => value === "true",
@@ -1553,7 +1734,7 @@ function parseSettings(data) {
1553
1734
  };
1554
1735
  const groupedByModule = data.reduce((acc, item) => {
1555
1736
  const parser = typeParsers[item.type] || ((v) => v);
1556
- const convertedValue = parser(item.value);
1737
+ const convertedValue = isSecret(item.module, item.property) ? maskSecret(item.value) : parser(item.value);
1557
1738
  let moduleObject = acc.find((obj) => obj.module === item.module);
1558
1739
  if (!moduleObject) {
1559
1740
  moduleObject = { module: item.module, settings: {} };
@@ -1571,18 +1752,39 @@ const SettingAppService = ({ strapi: strapi2 }) => ({
1571
1752
  const parsedSettings = parseSettings(settings);
1572
1753
  return parsedSettings || {};
1573
1754
  },
1755
+ async getRawValue(module, property) {
1756
+ const config2 = strapi2.config.get(`plugin::${PLUGIN_ID}`);
1757
+ const setting = await strapi2.db.query(config2.uuid.app.setting).findOne({
1758
+ where: { module, property }
1759
+ });
1760
+ return setting ? setting.value : null;
1761
+ },
1574
1762
  async update(ctx) {
1575
1763
  const config2 = strapi2.config.get(`plugin::${PLUGIN_ID}`);
1764
+ const { module, property, value } = ctx.request.body;
1576
1765
  const setting = await strapi2.db.query(config2.uuid.app.setting).findOne({
1577
1766
  where: {
1578
- module: ctx.request.body.module,
1579
- property: ctx.request.body.property
1767
+ module,
1768
+ property
1580
1769
  }
1581
1770
  });
1771
+ if (isSecret(module, property) && (value === null || value === void 0 || value === "")) {
1772
+ return setting;
1773
+ }
1774
+ if (!setting) {
1775
+ return await strapi2.db.query(config2.uuid.app.setting).create({
1776
+ data: {
1777
+ module,
1778
+ property,
1779
+ type: inferType(value),
1780
+ value: String(value)
1781
+ }
1782
+ });
1783
+ }
1582
1784
  return await strapi2.documents(config2.uuid.app.setting).update({
1583
1785
  documentId: setting.documentId,
1584
1786
  data: {
1585
- value: String(ctx.request.body.value),
1787
+ value: String(value),
1586
1788
  updated_by_id: ctx.state.user.id
1587
1789
  }
1588
1790
  });
@@ -1800,210 +2002,108 @@ async function findDocumentIdsAndFetchSlugs(params) {
1800
2002
  await Promise.all(promises);
1801
2003
  return params.document;
1802
2004
  }
1803
- const SlugModuleService = ({ strapi: strapi2 }) => ({
1804
- async adminGetAll() {
1805
- const ctx = strapi2.requestContext.get();
1806
- if (!ctx.query.locale) return [];
1807
- const config2 = strapi2.config.get(`plugin::${PLUGIN_ID}`);
1808
- const documents = await strapi2.db.query(config2.uuid.modules.slug).findMany({
1809
- where: {
1810
- locale: ctx.query.locale,
1811
- state: "published"
1812
- },
1813
- orderBy: {
1814
- id: "desc"
1815
- }
1816
- });
1817
- const publishedResults = [];
1818
- for (const document of documents) {
1819
- const content = await strapi2.documents(document.contentModel).findOne({
1820
- status: "published",
1821
- documentId: document.contentId,
1822
- locale: ctx.query.locale
1823
- });
1824
- if (content) {
1825
- document.contentTitle = content.title || `${content.documentId} | ${document.contentModel}`;
1826
- publishedResults.push(document);
1827
- }
1828
- }
1829
- return publishedResults || [];
1830
- },
1831
- async adminBulkDelete() {
1832
- const ctx = strapi2.requestContext.get();
1833
- if (!ctx.query.locale) return;
1834
- const body = ctx.request.body;
1835
- if (!body.contentIds) return;
1836
- const config2 = strapi2.config.get(`plugin::${PLUGIN_ID}`);
1837
- await strapi2.db.query(config2.uuid.modules.slug).deleteMany({
1838
- where: {
1839
- contentId: body.contentIds,
1840
- locale: ctx.query.locale
1841
- }
1842
- });
1843
- ctx.status = 204;
1844
- return;
1845
- },
1846
- async getPage() {
1847
- const ctx = strapi2.requestContext.get();
1848
- const config2 = strapi2.config.get(`plugin::${PLUGIN_ID}`);
1849
- const slug = ctx.query.slug.replace(/^\/|\/$/g, "");
1850
- const locales = await strapi2.plugin("i18n").service("locales").find();
1851
- const mappedLocales = locales.map((locale) => locale.code.toLowerCase());
1852
- const defaultLocale = await strapi2.plugin("i18n").service("locales").getDefaultLocale();
1853
- const settings = await strapi2.db.query(config2.uuid.app.setting).findMany({
1854
- where: {
1855
- module: "slug",
1856
- property: [
1857
- "showDefaultLanguage",
1858
- "homepageContentId",
1859
- "homepageContentModel",
1860
- "homepageSlugStrategy"
1861
- ]
1862
- }
1863
- });
1864
- const showDefaultLanguage = settings.find((setting) => setting.property === "showDefaultLanguage").value === "true";
1865
- const homepageContentId = settings.find(
1866
- (setting) => setting.property === "homepageContentId"
1867
- ).value;
1868
- const homepageSlugStrategy = settings.find(
1869
- (setting) => setting.property === "homepageSlugStrategy"
1870
- ).value;
1871
- const homepageContentModel = settings.find(
1872
- (setting) => setting.property === "homepageContentModel"
1873
- ).value;
1874
- let page;
1875
- if (homepageSlugStrategy === SLUG_LANGUAGE_STRATEGY && mappedLocales.includes(slug)) {
1876
- page = await strapi2.db.query(config2.uuid.modules.slug).findOne({
2005
+ const SlugModuleService = ({ strapi: strapi2 }) => {
2006
+ const groupByContentTypeTabs = createContentTypeTabsGrouper(strapi2);
2007
+ return {
2008
+ async adminGetAll() {
2009
+ const ctx = strapi2.requestContext.get();
2010
+ if (!ctx.query.locale) return [];
2011
+ const config2 = strapi2.config.get(`plugin::${PLUGIN_ID}`);
2012
+ const documents = await strapi2.db.query(config2.uuid.modules.slug).findMany({
1877
2013
  where: {
1878
- state: "published",
1879
- contentId: homepageContentId,
1880
- contentModel: homepageContentModel,
1881
- locale: slug
2014
+ locale: ctx.query.locale,
2015
+ state: "published"
2016
+ },
2017
+ orderBy: {
2018
+ id: "desc"
1882
2019
  }
1883
2020
  });
1884
- page.fullSlug = slug;
1885
- } else {
1886
- const pages = await strapi2.db.query(config2.uuid.modules.slug).findMany({
2021
+ const publishedResults = [];
2022
+ for (const document of documents) {
2023
+ const content = await strapi2.documents(document.contentModel).findOne({
2024
+ status: "published",
2025
+ documentId: document.contentId,
2026
+ locale: ctx.query.locale
2027
+ });
2028
+ if (content) {
2029
+ document.contentTitle = content.title || `${content.documentId} | ${document.contentModel}`;
2030
+ publishedResults.push(document);
2031
+ }
2032
+ }
2033
+ return publishedResults || [];
2034
+ },
2035
+ async adminBulkDelete() {
2036
+ const ctx = strapi2.requestContext.get();
2037
+ if (!ctx.query.locale) return;
2038
+ const body = ctx.request.body;
2039
+ if (!body.contentIds) return;
2040
+ const config2 = strapi2.config.get(`plugin::${PLUGIN_ID}`);
2041
+ await strapi2.db.query(config2.uuid.modules.slug).deleteMany({
1887
2042
  where: {
1888
- state: "published",
1889
- slug: slug.split("/")
2043
+ contentId: body.contentIds,
2044
+ locale: ctx.query.locale
1890
2045
  }
1891
2046
  });
1892
- pages.forEach((page2) => {
1893
- page2.fullSlug = buildFullSlug({ pages, page: page2, defaultLocale, showDefaultLanguage });
1894
- });
1895
- page = pages.find((page2) => page2.fullSlug === slug);
1896
- }
1897
- if (!page) {
1898
- ctx.status = 404;
2047
+ ctx.status = 204;
1899
2048
  return;
1900
- }
1901
- const properties = ctx.query.properties;
1902
- if (properties && properties.includes("attributes")) {
1903
- const attributes2 = await strapi2.db.query(config2.uuid.modules.attribute).findOne({
2049
+ },
2050
+ async getPage() {
2051
+ const ctx = strapi2.requestContext.get();
2052
+ const config2 = strapi2.config.get(`plugin::${PLUGIN_ID}`);
2053
+ const slug = ctx.query.slug.replace(/^\/|\/$/g, "");
2054
+ const locales = await strapi2.plugin("i18n").service("locales").find();
2055
+ const mappedLocales = locales.map((locale) => locale.code.toLowerCase());
2056
+ const defaultLocale = await strapi2.plugin("i18n").service("locales").getDefaultLocale();
2057
+ const settings = await strapi2.db.query(config2.uuid.app.setting).findMany({
1904
2058
  where: {
1905
- locale: page.locale,
1906
- contentId: page.contentId,
1907
- contentModel: page.contentModel,
1908
- state: "published"
2059
+ module: "slug",
2060
+ property: [
2061
+ "showDefaultLanguage",
2062
+ "homepageContentId",
2063
+ "homepageContentModel",
2064
+ "homepageSlugStrategy"
2065
+ ]
1909
2066
  }
1910
2067
  });
1911
- const template = attributes2 && attributes2.templateId ? await strapi2.db.query(config2.uuid.modules.template).findOne({
1912
- where: {
1913
- documentId: attributes2.templateId
1914
- }
1915
- }) : null;
1916
- page.attributes = {
1917
- template: template?.uid || "default",
1918
- priority: attributes2?.priority || "0.5",
1919
- frequency: attributes2?.frequency || "weekly",
1920
- ...attributes2?.parentContentId ? { parent: { id: attributes2.parentContentId, model: attributes2.parentContentModel } } : {}
1921
- };
1922
- }
1923
- const query = populateQueryFromContentType(strapi2, page.contentModel);
1924
- const document = await strapi2.documents(page.contentModel).findOne({
1925
- locale: page.locale,
1926
- populate: query,
1927
- status: "published",
1928
- documentId: page.contentId
1929
- });
1930
- await findDocumentIdsAndFetchSlugs({
1931
- document,
1932
- defaultLocale,
1933
- showDefaultLanguage
1934
- });
1935
- for (const localization of document.localizations) {
1936
- if (homepageSlugStrategy === SLUG_LANGUAGE_STRATEGY && localization.documentId === homepageContentId) {
1937
- localization.slug = localization.locale === defaultLocale ? "" : localization.locale.toLowerCase();
2068
+ const showDefaultLanguage = settings.find((setting) => setting.property === "showDefaultLanguage").value === "true";
2069
+ const homepageContentId = settings.find(
2070
+ (setting) => setting.property === "homepageContentId"
2071
+ ).value;
2072
+ const homepageSlugStrategy = settings.find(
2073
+ (setting) => setting.property === "homepageSlugStrategy"
2074
+ ).value;
2075
+ const homepageContentModel = settings.find(
2076
+ (setting) => setting.property === "homepageContentModel"
2077
+ ).value;
2078
+ let page;
2079
+ if (homepageSlugStrategy === SLUG_LANGUAGE_STRATEGY && mappedLocales.includes(slug)) {
2080
+ page = await strapi2.db.query(config2.uuid.modules.slug).findOne({
2081
+ where: {
2082
+ state: "published",
2083
+ contentId: homepageContentId,
2084
+ contentModel: homepageContentModel,
2085
+ locale: slug
2086
+ }
2087
+ });
2088
+ page.fullSlug = slug;
1938
2089
  } else {
1939
- localization.slug = await getSlugByDocumentId({
1940
- contentId: localization.documentId,
1941
- locale: localization.locale,
1942
- defaultLocale,
1943
- showDefaultLanguage,
1944
- strapi: strapi2
2090
+ const pages = await strapi2.db.query(config2.uuid.modules.slug).findMany({
2091
+ where: {
2092
+ state: "published",
2093
+ slug: slug.split("/")
2094
+ }
1945
2095
  });
2096
+ pages.forEach((page2) => {
2097
+ page2.fullSlug = buildFullSlug({ pages, page: page2, defaultLocale, showDefaultLanguage });
2098
+ });
2099
+ page = pages.find((page2) => page2.fullSlug === slug);
1946
2100
  }
1947
- }
1948
- delete document.createdBy;
1949
- delete document.updatedBy;
1950
- document.slug = page.fullSlug;
1951
- document.breadcrumbs = await buildBreadcrumbs({
1952
- strapi: strapi2,
1953
- page,
1954
- defaultLocale,
1955
- showDefaultLanguage,
1956
- homepageSlugStrategy,
1957
- homepageContentId,
1958
- homepageContentModel
1959
- });
1960
- return {
1961
- document,
1962
- ...page.attributes ? { attributes: page.attributes } : {}
1963
- };
1964
- },
1965
- async getPages() {
1966
- const ctx = strapi2.requestContext.get();
1967
- const properties = ctx.query.properties;
1968
- const config2 = strapi2.config.get(`plugin::${PLUGIN_ID}`);
1969
- const defaultLocale = await strapi2.plugin("i18n").service("locales").getDefaultLocale();
1970
- const settings = await strapi2.db.query(config2.uuid.app.setting).findMany({
1971
- where: {
1972
- module: "slug",
1973
- property: [
1974
- "showDefaultLanguage",
1975
- "homepageContentId",
1976
- "homepageContentModel",
1977
- "homepageSlugStrategy"
1978
- ]
1979
- }
1980
- });
1981
- const showDefaultLanguage = settings.find((setting) => setting.property === "showDefaultLanguage").value === "true";
1982
- const homepageContentId = settings.find(
1983
- (setting) => setting.property === "homepageContentId"
1984
- ).value;
1985
- const homepageContentModel = settings.find(
1986
- (setting) => setting.property === "homepageContentModel"
1987
- ).value;
1988
- const homepageSlugStrategy = settings.find(
1989
- (setting) => setting.property === "homepageSlugStrategy"
1990
- ).value;
1991
- const pages = await strapi2.db.query(config2.uuid.modules.slug).findMany({
1992
- where: {
1993
- state: "published"
1994
- }
1995
- });
1996
- pages.forEach((page) => {
1997
- if (homepageContentId === page.contentId && homepageContentModel === page.contentModel && defaultLocale === page.locale) {
1998
- page.fullSlug = "";
1999
- } else if (homepageContentId === page.contentId && homepageContentModel === page.contentModel && defaultLocale !== page.locale && homepageSlugStrategy === SLUG_LANGUAGE_STRATEGY) {
2000
- page.fullSlug = page.locale.toLowerCase();
2001
- } else {
2002
- page.fullSlug = buildFullSlug({ pages, page, defaultLocale, showDefaultLanguage });
2101
+ if (!page) {
2102
+ ctx.status = 404;
2103
+ return;
2003
2104
  }
2004
- });
2005
- if (properties && properties.includes("attributes")) {
2006
- for (const page of pages) {
2105
+ const properties = ctx.query.properties;
2106
+ if (properties && properties.includes("attributes")) {
2007
2107
  const attributes2 = await strapi2.db.query(config2.uuid.modules.attribute).findOne({
2008
2108
  where: {
2009
2109
  locale: page.locale,
@@ -2024,140 +2124,245 @@ const SlugModuleService = ({ strapi: strapi2 }) => ({
2024
2124
  ...attributes2?.parentContentId ? { parent: { id: attributes2.parentContentId, model: attributes2.parentContentModel } } : {}
2025
2125
  };
2026
2126
  }
2027
- }
2028
- const mappedPages = pages.map((page) => ({
2029
- ...page,
2030
- ...page.attributes ? { attributes: page.attributes } : {},
2031
- localizations: []
2032
- }));
2033
- const rootItems = mappedPages.filter((item) => item.locale === defaultLocale);
2034
- const mappedItems = rootItems.map((rootItem) => {
2035
- const relatedItems = mappedPages.filter(
2036
- (item) => item.contentId === rootItem.contentId && item.contentModel === rootItem.contentModel && item.locale !== defaultLocale
2037
- );
2127
+ const query = populateQueryFromContentType(strapi2, page.contentModel);
2128
+ const document = await strapi2.documents(page.contentModel).findOne({
2129
+ locale: page.locale,
2130
+ populate: query,
2131
+ status: "published",
2132
+ documentId: page.contentId
2133
+ });
2134
+ await findDocumentIdsAndFetchSlugs({
2135
+ document,
2136
+ defaultLocale,
2137
+ showDefaultLanguage
2138
+ });
2139
+ for (const localization of document.localizations) {
2140
+ if (homepageSlugStrategy === SLUG_LANGUAGE_STRATEGY && localization.documentId === homepageContentId) {
2141
+ localization.slug = localization.locale === defaultLocale ? "" : localization.locale.toLowerCase();
2142
+ } else {
2143
+ localization.slug = await getSlugByDocumentId({
2144
+ contentId: localization.documentId,
2145
+ locale: localization.locale,
2146
+ defaultLocale,
2147
+ showDefaultLanguage,
2148
+ strapi: strapi2
2149
+ });
2150
+ }
2151
+ }
2152
+ delete document.createdBy;
2153
+ delete document.updatedBy;
2154
+ document.slug = page.fullSlug;
2155
+ document.breadcrumbs = await buildBreadcrumbs({
2156
+ strapi: strapi2,
2157
+ page,
2158
+ defaultLocale,
2159
+ showDefaultLanguage,
2160
+ homepageSlugStrategy,
2161
+ homepageContentId,
2162
+ homepageContentModel
2163
+ });
2038
2164
  return {
2039
- id: rootItem.id,
2040
- documentId: rootItem.contentId,
2041
- slug: rootItem.fullSlug,
2042
- locale: rootItem.locale,
2043
- createdAt: rootItem.updatedAt,
2044
- updatedAt: rootItem.updatedAt,
2045
- publishedAt: rootItem.updatedAt,
2046
- ...rootItem.attributes ? { attributes: rootItem.attributes } : {},
2047
- localizations: relatedItems.map((item) => ({
2048
- id: item.id,
2049
- documentId: item.contentId,
2050
- slug: item.fullSlug,
2051
- locale: item.locale,
2052
- createdAt: item.updatedAt,
2053
- updatedAt: item.updatedAt,
2054
- publishedAt: item.updatedAt,
2055
- ...item.attributes ? { attributes: item.attributes } : {}
2056
- }))
2165
+ document: groupByContentTypeTabs(page.contentModel, document),
2166
+ ...page.attributes ? { attributes: page.attributes } : {}
2057
2167
  };
2058
- });
2059
- return mappedItems;
2060
- },
2061
- async getHomePage() {
2062
- const ctx = strapi2.requestContext.get();
2063
- const config2 = strapi2.config.get(`plugin::${PLUGIN_ID}`);
2064
- const defaultLocale = await strapi2.plugin("i18n").service("locales").getDefaultLocale();
2065
- const settings = await strapi2.db.query(config2.uuid.app.setting).findMany({
2066
- where: {
2067
- module: "slug",
2068
- property: [
2069
- "showDefaultLanguage",
2070
- "homepageContentId",
2071
- "homepageContentModel",
2072
- "homepageSlugStrategy"
2073
- ]
2074
- }
2075
- });
2076
- const showDefaultLanguage = settings.find((setting) => setting.property === "showDefaultLanguage").value === "true";
2077
- const homepageContentId = settings.find(
2078
- (setting) => setting.property === "homepageContentId"
2079
- ).value;
2080
- const homepageContentModel = settings.find(
2081
- (setting) => setting.property === "homepageContentModel"
2082
- ).value;
2083
- const homepageSlugStrategy = settings.find(
2084
- (setting) => setting.property === "homepageSlugStrategy"
2085
- ).value;
2086
- const page = await strapi2.db.query(config2.uuid.modules.slug).findOne({
2087
- where: {
2088
- state: "published",
2089
- contentId: homepageContentId,
2090
- contentModel: homepageContentModel,
2091
- locale: defaultLocale
2092
- }
2093
- });
2094
- if (!page) {
2095
- ctx.status = 404;
2096
- return;
2097
- }
2098
- const properties = ctx.query.properties;
2099
- if (properties && properties.includes("attributes")) {
2100
- const attributes2 = await strapi2.db.query(config2.uuid.modules.attribute).findOne({
2168
+ },
2169
+ async getPages() {
2170
+ const ctx = strapi2.requestContext.get();
2171
+ const properties = ctx.query.properties;
2172
+ const config2 = strapi2.config.get(`plugin::${PLUGIN_ID}`);
2173
+ const defaultLocale = await strapi2.plugin("i18n").service("locales").getDefaultLocale();
2174
+ const settings = await strapi2.db.query(config2.uuid.app.setting).findMany({
2175
+ where: {
2176
+ module: "slug",
2177
+ property: [
2178
+ "showDefaultLanguage",
2179
+ "homepageContentId",
2180
+ "homepageContentModel",
2181
+ "homepageSlugStrategy"
2182
+ ]
2183
+ }
2184
+ });
2185
+ const showDefaultLanguage = settings.find((setting) => setting.property === "showDefaultLanguage").value === "true";
2186
+ const homepageContentId = settings.find(
2187
+ (setting) => setting.property === "homepageContentId"
2188
+ ).value;
2189
+ const homepageContentModel = settings.find(
2190
+ (setting) => setting.property === "homepageContentModel"
2191
+ ).value;
2192
+ const homepageSlugStrategy = settings.find(
2193
+ (setting) => setting.property === "homepageSlugStrategy"
2194
+ ).value;
2195
+ const pages = await strapi2.db.query(config2.uuid.modules.slug).findMany({
2101
2196
  where: {
2102
- locale: page.locale,
2103
- contentId: page.contentId,
2104
- contentModel: page.contentModel,
2105
2197
  state: "published"
2106
2198
  }
2107
2199
  });
2108
- const template = attributes2 && attributes2.templateId ? await strapi2.db.query(config2.uuid.modules.template).findOne({
2200
+ pages.forEach((page) => {
2201
+ if (homepageContentId === page.contentId && homepageContentModel === page.contentModel && defaultLocale === page.locale) {
2202
+ page.fullSlug = "";
2203
+ } else if (homepageContentId === page.contentId && homepageContentModel === page.contentModel && defaultLocale !== page.locale && homepageSlugStrategy === SLUG_LANGUAGE_STRATEGY) {
2204
+ page.fullSlug = page.locale.toLowerCase();
2205
+ } else {
2206
+ page.fullSlug = buildFullSlug({ pages, page, defaultLocale, showDefaultLanguage });
2207
+ }
2208
+ });
2209
+ if (properties && properties.includes("attributes")) {
2210
+ for (const page of pages) {
2211
+ const attributes2 = await strapi2.db.query(config2.uuid.modules.attribute).findOne({
2212
+ where: {
2213
+ locale: page.locale,
2214
+ contentId: page.contentId,
2215
+ contentModel: page.contentModel,
2216
+ state: "published"
2217
+ }
2218
+ });
2219
+ const template = attributes2 && attributes2.templateId ? await strapi2.db.query(config2.uuid.modules.template).findOne({
2220
+ where: {
2221
+ documentId: attributes2.templateId
2222
+ }
2223
+ }) : null;
2224
+ page.attributes = {
2225
+ template: template?.uid || "default",
2226
+ priority: attributes2?.priority || "0.5",
2227
+ frequency: attributes2?.frequency || "weekly",
2228
+ ...attributes2?.parentContentId ? { parent: { id: attributes2.parentContentId, model: attributes2.parentContentModel } } : {}
2229
+ };
2230
+ }
2231
+ }
2232
+ const mappedPages = pages.map((page) => ({
2233
+ ...page,
2234
+ ...page.attributes ? { attributes: page.attributes } : {},
2235
+ localizations: []
2236
+ }));
2237
+ const rootItems = mappedPages.filter((item) => item.locale === defaultLocale);
2238
+ const mappedItems = rootItems.map((rootItem) => {
2239
+ const relatedItems = mappedPages.filter(
2240
+ (item) => item.contentId === rootItem.contentId && item.contentModel === rootItem.contentModel && item.locale !== defaultLocale
2241
+ );
2242
+ return {
2243
+ id: rootItem.id,
2244
+ documentId: rootItem.contentId,
2245
+ slug: rootItem.fullSlug,
2246
+ locale: rootItem.locale,
2247
+ createdAt: rootItem.updatedAt,
2248
+ updatedAt: rootItem.updatedAt,
2249
+ publishedAt: rootItem.updatedAt,
2250
+ ...rootItem.attributes ? { attributes: rootItem.attributes } : {},
2251
+ localizations: relatedItems.map((item) => ({
2252
+ id: item.id,
2253
+ documentId: item.contentId,
2254
+ slug: item.fullSlug,
2255
+ locale: item.locale,
2256
+ createdAt: item.updatedAt,
2257
+ updatedAt: item.updatedAt,
2258
+ publishedAt: item.updatedAt,
2259
+ ...item.attributes ? { attributes: item.attributes } : {}
2260
+ }))
2261
+ };
2262
+ });
2263
+ return mappedItems;
2264
+ },
2265
+ async getHomePage() {
2266
+ const ctx = strapi2.requestContext.get();
2267
+ const config2 = strapi2.config.get(`plugin::${PLUGIN_ID}`);
2268
+ const defaultLocale = await strapi2.plugin("i18n").service("locales").getDefaultLocale();
2269
+ const settings = await strapi2.db.query(config2.uuid.app.setting).findMany({
2109
2270
  where: {
2110
- documentId: attributes2.templateId
2271
+ module: "slug",
2272
+ property: [
2273
+ "showDefaultLanguage",
2274
+ "homepageContentId",
2275
+ "homepageContentModel",
2276
+ "homepageSlugStrategy"
2277
+ ]
2111
2278
  }
2112
- }) : null;
2113
- page.attributes = {
2114
- template: template?.uid || "default",
2115
- priority: attributes2?.priority || "0.5",
2116
- frequency: attributes2?.frequency || "weekly",
2117
- ...attributes2?.parentContentId ? { parent: { id: attributes2.parentContentId, model: attributes2.parentContentModel } } : {}
2118
- };
2119
- }
2120
- const query = properties && properties.includes("content") ? populateQueryFromContentType(strapi2, page.contentModel) : { localizations: { populate: "*" } };
2121
- const document = await strapi2.documents(page.contentModel).findOne({
2122
- locale: page.locale,
2123
- populate: query,
2124
- status: "published",
2125
- documentId: page.contentId
2126
- });
2127
- await findDocumentIdsAndFetchSlugs({
2128
- document,
2129
- defaultLocale,
2130
- showDefaultLanguage
2131
- });
2132
- for (const localization of document.localizations) {
2133
- if (homepageSlugStrategy === SLUG_LANGUAGE_STRATEGY) {
2134
- localization.slug = localization.locale === defaultLocale ? "" : localization.locale.toLowerCase();
2135
- } else {
2136
- localization.slug = await getSlugByDocumentId({
2137
- contentId: localization.documentId,
2138
- locale: localization.locale,
2139
- defaultLocale,
2140
- showDefaultLanguage,
2141
- strapi: strapi2
2279
+ });
2280
+ const showDefaultLanguage = settings.find((setting) => setting.property === "showDefaultLanguage").value === "true";
2281
+ const homepageContentId = settings.find(
2282
+ (setting) => setting.property === "homepageContentId"
2283
+ ).value;
2284
+ const homepageContentModel = settings.find(
2285
+ (setting) => setting.property === "homepageContentModel"
2286
+ ).value;
2287
+ const homepageSlugStrategy = settings.find(
2288
+ (setting) => setting.property === "homepageSlugStrategy"
2289
+ ).value;
2290
+ const page = await strapi2.db.query(config2.uuid.modules.slug).findOne({
2291
+ where: {
2292
+ state: "published",
2293
+ contentId: homepageContentId,
2294
+ contentModel: homepageContentModel,
2295
+ locale: defaultLocale
2296
+ }
2297
+ });
2298
+ if (!page) {
2299
+ ctx.status = 404;
2300
+ return;
2301
+ }
2302
+ const properties = ctx.query.properties;
2303
+ if (properties && properties.includes("attributes")) {
2304
+ const attributes2 = await strapi2.db.query(config2.uuid.modules.attribute).findOne({
2305
+ where: {
2306
+ locale: page.locale,
2307
+ contentId: page.contentId,
2308
+ contentModel: page.contentModel,
2309
+ state: "published"
2310
+ }
2142
2311
  });
2312
+ const template = attributes2 && attributes2.templateId ? await strapi2.db.query(config2.uuid.modules.template).findOne({
2313
+ where: {
2314
+ documentId: attributes2.templateId
2315
+ }
2316
+ }) : null;
2317
+ page.attributes = {
2318
+ template: template?.uid || "default",
2319
+ priority: attributes2?.priority || "0.5",
2320
+ frequency: attributes2?.frequency || "weekly",
2321
+ ...attributes2?.parentContentId ? { parent: { id: attributes2.parentContentId, model: attributes2.parentContentModel } } : {}
2322
+ };
2143
2323
  }
2144
- }
2145
- delete document.createdBy;
2146
- delete document.updatedBy;
2147
- document.slug = "";
2148
- document.breadcrumbs = [
2149
- {
2150
- position: 1,
2151
- name: document.title,
2152
- item: ""
2324
+ const query = properties && properties.includes("content") ? populateQueryFromContentType(strapi2, page.contentModel) : { localizations: { populate: "*" } };
2325
+ const document = await strapi2.documents(page.contentModel).findOne({
2326
+ locale: page.locale,
2327
+ populate: query,
2328
+ status: "published",
2329
+ documentId: page.contentId
2330
+ });
2331
+ await findDocumentIdsAndFetchSlugs({
2332
+ document,
2333
+ defaultLocale,
2334
+ showDefaultLanguage
2335
+ });
2336
+ for (const localization of document.localizations) {
2337
+ if (homepageSlugStrategy === SLUG_LANGUAGE_STRATEGY) {
2338
+ localization.slug = localization.locale === defaultLocale ? "" : localization.locale.toLowerCase();
2339
+ } else {
2340
+ localization.slug = await getSlugByDocumentId({
2341
+ contentId: localization.documentId,
2342
+ locale: localization.locale,
2343
+ defaultLocale,
2344
+ showDefaultLanguage,
2345
+ strapi: strapi2
2346
+ });
2347
+ }
2153
2348
  }
2154
- ];
2155
- return {
2156
- document,
2157
- ...page.attributes ? { attributes: page.attributes } : {}
2158
- };
2159
- }
2160
- });
2349
+ delete document.createdBy;
2350
+ delete document.updatedBy;
2351
+ document.slug = "";
2352
+ document.breadcrumbs = [
2353
+ {
2354
+ position: 1,
2355
+ name: document.title,
2356
+ item: ""
2357
+ }
2358
+ ];
2359
+ return {
2360
+ document: groupByContentTypeTabs(page.contentModel, document),
2361
+ ...page.attributes ? { attributes: page.attributes } : {}
2362
+ };
2363
+ }
2364
+ };
2365
+ };
2161
2366
  async function fetchAdditionalData(params) {
2162
2367
  const content = await params.strapi.documents(params.record.contentModel).findOne({
2163
2368
  status: "published",
@@ -2646,7 +2851,7 @@ const ParameterModuleService = ({ strapi: strapi2 }) => ({
2646
2851
  return documents || [];
2647
2852
  }
2648
2853
  });
2649
- function groupByUid(items) {
2854
+ function groupByUid$1(items) {
2650
2855
  const groupedMap = items.reduce((acc, item) => {
2651
2856
  if (acc[item.uid]) {
2652
2857
  acc[item.uid].translations[item.locale] = item.translation;
@@ -2719,7 +2924,221 @@ const TranslationModuleService = ({ strapi: strapi2 }) => ({
2719
2924
  translation: "asc"
2720
2925
  }
2721
2926
  });
2722
- return documents ? groupByUid(documents) : [];
2927
+ return documents ? groupByUid$1(documents) : [];
2928
+ }
2929
+ });
2930
+ const REQUEST_TIMEOUT = 12e4;
2931
+ function groupByUid(items) {
2932
+ const groupedMap = items.reduce((acc, item) => {
2933
+ if (!acc[item.uid]) {
2934
+ acc[item.uid] = { uid: item.uid, translations: {} };
2935
+ }
2936
+ acc[item.uid].translations[item.locale] = item.translation;
2937
+ return acc;
2938
+ }, {});
2939
+ return Object.values(groupedMap);
2940
+ }
2941
+ function chunk(items, size) {
2942
+ const batches = [];
2943
+ for (let index2 = 0; index2 < items.length; index2 += size) {
2944
+ batches.push(items.slice(index2, index2 + size));
2945
+ }
2946
+ return batches;
2947
+ }
2948
+ function isFilled(value) {
2949
+ return typeof value === "string" && value.trim().length > 0;
2950
+ }
2951
+ function buildSystemPrompt(source, target) {
2952
+ return [
2953
+ `You are a professional translator and copywriter, a native speaker of ${target.name} (locale code ${target.code}), translating from ${source.name} (locale code ${source.code}).`,
2954
+ `The strings you receive are interface copy: labels, buttons, titles, menu entries, notifications and short messages shown to the users of a website or application.`,
2955
+ `Translate them so that a native ${target.name} speaker would never suspect the text was translated. Follow every rule below.`,
2956
+ ``,
2957
+ `1. Translate the meaning, never word by word. When the source uses an idiom, a saying, a metaphor or a play on words, replace it with the expression a native ${target.name} speaker would genuinely use in the same situation. Preserving the intent and the logic behind the sentence matters more than preserving its words. When no natural equivalent exists, write the plain, natural sentence that carries the same idea.`,
2958
+ `2. Do not use hyphens or dashes of any kind (-, –, —) as a stylistic device to join clauses, ideas or appositions. Rewrite the sentence instead, splitting it or using the connectors that are natural in ${target.name}. Hyphens are acceptable only when they are a mandatory part of the correct spelling of a word in ${target.name}.`,
2959
+ `3. Match the register and the tone of the source. Informal stays informal, formal stays formal, and the form of address must be the one standard for user interfaces in ${target.name}.`,
2960
+ `4. Stay close to the length of the source. Interface copy has to fit inside buttons and labels, so be concise and never add words the source does not have.`,
2961
+ `5. Preserve exactly, without translating: placeholders such as {name}, {{name}}, %s, %d, :param and $variable; HTML tags and entities; markdown syntax; URLs; email addresses; numbers; and brand or product names.`,
2962
+ `6. Preserve the capitalisation style of the source (sentence case, Title Case, ALL CAPS) adapted to what is correct in ${target.name}, and keep the leading and trailing punctuation, the ellipses and the question or exclamation marks.`,
2963
+ `7. Use the spelling, the vocabulary and the conventions of the ${target.name} variant identified by the code ${target.code}.`,
2964
+ `8. Never explain, comment or add anything, and never leave any part of the text in the source language.`,
2965
+ ``,
2966
+ `You receive a JSON object that maps keys to source strings. Return a JSON object with exactly the same keys, where each value is the translation of the corresponding source string. Return nothing else.`
2967
+ ].join("\n");
2968
+ }
2969
+ async function requestOpenAi(apiKey, model, systemPrompt, payload, withTemperature = true) {
2970
+ const controller = new AbortController();
2971
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT);
2972
+ try {
2973
+ const body = {
2974
+ model,
2975
+ response_format: { type: "json_object" },
2976
+ messages: [
2977
+ { role: "system", content: systemPrompt },
2978
+ { role: "user", content: JSON.stringify(payload) }
2979
+ ]
2980
+ };
2981
+ if (withTemperature) body.temperature = 0.3;
2982
+ const response = await fetch(OPENAI_CHAT_COMPLETIONS_URL, {
2983
+ method: "POST",
2984
+ headers: {
2985
+ "Content-Type": "application/json",
2986
+ Authorization: `Bearer ${apiKey}`
2987
+ },
2988
+ body: JSON.stringify(body),
2989
+ signal: controller.signal
2990
+ });
2991
+ if (!response.ok) {
2992
+ const error = await response.text();
2993
+ if (withTemperature && response.status === 400 && error.includes("temperature")) {
2994
+ clearTimeout(timeout);
2995
+ return requestOpenAi(apiKey, model, systemPrompt, payload, false);
2996
+ }
2997
+ throw new Error(`OpenAI request failed with status ${response.status}: ${error}`);
2998
+ }
2999
+ const data = await response.json();
3000
+ const content = data?.choices?.[0]?.message?.content;
3001
+ if (!content) throw new Error("OpenAI returned an empty response");
3002
+ return JSON.parse(content);
3003
+ } finally {
3004
+ clearTimeout(timeout);
3005
+ }
3006
+ }
3007
+ const AiTranslationModuleService = ({ strapi: strapi2 }) => ({
3008
+ async getLocales() {
3009
+ const locales = await strapi2.plugin("i18n").service("locales").find();
3010
+ return locales.map((locale) => ({ code: locale.code, name: locale.name }));
3011
+ },
3012
+ async getCredentials() {
3013
+ const settingService = strapi2.plugin(PLUGIN_ID).service("SettingAppService");
3014
+ const aiEnabled = await settingService.getRawValue(AI_TRANSLATION_MODULE, "aiEnabled");
3015
+ if (aiEnabled !== "true") return null;
3016
+ const apiKey = await settingService.getRawValue(AI_TRANSLATION_MODULE, "aiApiKey");
3017
+ if (!isFilled(apiKey)) return null;
3018
+ const storedModel = await settingService.getRawValue(AI_TRANSLATION_MODULE, "aiModel");
3019
+ return {
3020
+ apiKey,
3021
+ model: isFilled(storedModel) ? storedModel : AI_TRANSLATION_DEFAULT_MODEL
3022
+ };
3023
+ },
3024
+ async translateStrings(credentials, source, target, strings) {
3025
+ const translations = {};
3026
+ const errors = [];
3027
+ let failed = 0;
3028
+ const systemPrompt = buildSystemPrompt(source, target);
3029
+ const keys = Object.keys(strings).filter((key) => isFilled(strings[key]));
3030
+ for (const batch of chunk(keys, AI_TRANSLATION_BATCH_SIZE)) {
3031
+ const payload = batch.reduce((acc, key) => {
3032
+ acc[key] = strings[key];
3033
+ return acc;
3034
+ }, {});
3035
+ let result;
3036
+ try {
3037
+ result = await requestOpenAi(credentials.apiKey, credentials.model, systemPrompt, payload);
3038
+ } catch (e) {
3039
+ failed += batch.length;
3040
+ errors.push(`${target.code}: ${e.message}`);
3041
+ strapi2.log.error(`[${PLUGIN_ID}] AI translation failed for ${target.code}: ${e.message}`);
3042
+ continue;
3043
+ }
3044
+ for (const key of batch) {
3045
+ if (isFilled(result[key])) {
3046
+ translations[key] = result[key];
3047
+ } else {
3048
+ failed += 1;
3049
+ }
3050
+ }
3051
+ }
3052
+ return { translations, failed, errors };
3053
+ },
3054
+ async adminTranslate() {
3055
+ const ctx = strapi2.requestContext.get();
3056
+ const config2 = strapi2.config.get(`plugin::${PLUGIN_ID}`);
3057
+ const { sourceLocale, targetLocales, overwrite } = ctx.request.body;
3058
+ const credentials = await this.getCredentials();
3059
+ if (!credentials) {
3060
+ return ctx.badRequest("AI translations are disabled or the OpenAI API key is not set");
3061
+ }
3062
+ if (!isFilled(sourceLocale)) {
3063
+ return ctx.badRequest("A source locale is required");
3064
+ }
3065
+ const targets = (targetLocales || []).filter(
3066
+ (locale) => isFilled(locale) && locale !== sourceLocale
3067
+ );
3068
+ if (targets.length === 0) {
3069
+ return ctx.badRequest("At least one target locale is required");
3070
+ }
3071
+ const locales = await this.getLocales();
3072
+ const source = locales.find((locale) => locale.code === sourceLocale);
3073
+ if (!source) {
3074
+ return ctx.badRequest(`The locale ${sourceLocale} is not configured in Strapi`);
3075
+ }
3076
+ const query = strapi2.db.query(config2.uuid.modules.translation);
3077
+ const documents = await query.findMany({ select: ["id", "uid", "translation", "locale"] });
3078
+ const entries = groupByUid(documents).filter(
3079
+ (entry) => isFilled(entry.translations[source.code])
3080
+ );
3081
+ if (entries.length === 0) {
3082
+ return { translated: 0, skipped: 0, failed: 0, errors: [] };
3083
+ }
3084
+ let translated = 0;
3085
+ let skipped = 0;
3086
+ let failed = 0;
3087
+ const errors = [];
3088
+ for (const targetCode of targets) {
3089
+ const target = locales.find((locale) => locale.code === targetCode);
3090
+ if (!target) {
3091
+ errors.push(`The locale ${targetCode} is not configured in Strapi`);
3092
+ continue;
3093
+ }
3094
+ const pending = entries.filter(
3095
+ (entry) => overwrite || !isFilled(entry.translations[target.code])
3096
+ );
3097
+ skipped += entries.length - pending.length;
3098
+ if (pending.length === 0) continue;
3099
+ const strings = pending.reduce((acc, entry) => {
3100
+ acc[entry.uid] = entry.translations[source.code];
3101
+ return acc;
3102
+ }, {});
3103
+ const result = await this.translateStrings(credentials, source, target, strings);
3104
+ failed += result.failed;
3105
+ errors.push(...result.errors);
3106
+ for (const [uid, translation] of Object.entries(result.translations)) {
3107
+ const existing = await query.findOne({ where: { uid, locale: target.code } });
3108
+ if (existing) {
3109
+ await query.update({ where: { id: existing.id }, data: { translation } });
3110
+ } else {
3111
+ await query.create({ data: { uid, translation, locale: target.code } });
3112
+ }
3113
+ const entry = entries.find((item) => item.uid === uid);
3114
+ if (entry) entry.translations[target.code] = translation;
3115
+ translated += 1;
3116
+ }
3117
+ }
3118
+ return { translated, skipped, failed, errors };
3119
+ },
3120
+ async adminTranslateStrings() {
3121
+ const ctx = strapi2.requestContext.get();
3122
+ const { sourceLocale, targetLocale, strings } = ctx.request.body;
3123
+ const credentials = await this.getCredentials();
3124
+ if (!credentials) {
3125
+ return ctx.badRequest("AI translations are disabled or the OpenAI API key is not set");
3126
+ }
3127
+ if (!isFilled(sourceLocale) || !isFilled(targetLocale)) {
3128
+ return ctx.badRequest("A source locale and a target locale are required");
3129
+ }
3130
+ if (sourceLocale === targetLocale) {
3131
+ return ctx.badRequest("The source locale and the target locale must be different");
3132
+ }
3133
+ if (!strings || Object.keys(strings).length === 0) {
3134
+ return { translations: {}, failed: 0, errors: [] };
3135
+ }
3136
+ const locales = await this.getLocales();
3137
+ const source = locales.find((locale) => locale.code === sourceLocale);
3138
+ const target = locales.find((locale) => locale.code === targetLocale);
3139
+ if (!source) return ctx.badRequest(`The locale ${sourceLocale} is not configured in Strapi`);
3140
+ if (!target) return ctx.badRequest(`The locale ${targetLocale} is not configured in Strapi`);
3141
+ return await this.translateStrings(credentials, source, target, strings);
2723
3142
  }
2724
3143
  });
2725
3144
  const services = {
@@ -2729,7 +3148,8 @@ const services = {
2729
3148
  TemplateModuleService,
2730
3149
  MenuModuleService,
2731
3150
  ParameterModuleService,
2732
- TranslationModuleService
3151
+ TranslationModuleService,
3152
+ AiTranslationModuleService
2733
3153
  };
2734
3154
  const index = {
2735
3155
  register,