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