From 0b7699d4f59e09d18803d2a14a7b70747618f6d7 Mon Sep 17 00:00:00 2001 From: David Vaclavek <49518842+david-vaclavek@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:45:45 +0100 Subject: [PATCH 1/3] fix: automated upload and deprecation send the same keys as the manual upload MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The create/update upload hook and the delete deprecation hook built their keys differently from the manual upload: - blocks fields were not projected to their text leaves, so saving an entry uploaded the raw AST (`type`, `bold`, `url`, … as source strings), - `getPickPaths` instead of `getPickPathsWithComponents` dropped every dynamic zone field, so saving never uploaded dynamic zone content, - entries excluded from translation were uploaded anyway. Both paths now use one `getUploadKeysForEntries`, and the hooks skip excluded entries. Co-Authored-By: Claude Opus 5.5 --- .../localazy-transfer-upload-service.ts | 33 ++-- ...picked-flatten-keys-for-hook-entry.test.ts | 146 ++++++++++++++++++ .../__tests__/transfer-round-trip.test.ts | 15 +- .../get-picked-flatten-keys-for-hook-entry.ts | 32 ++-- .../src/utils/get-upload-keys-for-entries.ts | 39 +++++ 5 files changed, 217 insertions(+), 48 deletions(-) create mode 100644 server/src/utils/__tests__/get-picked-flatten-keys-for-hook-entry.test.ts create mode 100644 server/src/utils/get-upload-keys-for-entries.ts diff --git a/server/src/services/localazy-transfer-upload-service.ts b/server/src/services/localazy-transfer-upload-service.ts index 264f989..1351e48 100644 --- a/server/src/services/localazy-transfer-upload-service.ts +++ b/server/src/services/localazy-transfer-upload-service.ts @@ -1,13 +1,11 @@ import type { Core } from '@strapi/strapi'; -import { flattenObject } from '../utils/flatten-object'; -import { projectBlocksFields } from '../utils/blocks-to-translatable'; +import { getUploadKeysForEntries } from '../utils/get-upload-keys-for-entries'; import { getCollectionsNames, findSetupModelByCollectionName, isCollectionTransferEnabled, getPickPathsWithComponents, } from '../utils/transfer-setup-utils'; -import { pickEntries } from '../utils/pick-entries'; import { getCharacterLimitsMetadata } from '../utils/get-character-limits-metadata'; import config from '../config'; import { isoStrapiToLocalazy } from '../utils/iso-locales-utils'; @@ -100,12 +98,6 @@ const LocalazyTransferUploadService = ({ strapi }: { strapi: Core.Strapi }) => ( continue; } - /** - * Contains the paths to the fields with the model uid. - * These paths will be used (selected) from the content and then uploaded to Localazy. - */ - const pickPathsWithUid = pickPaths.map((pickPath) => `${modelUid}.${pickPath}`); - // https://docs.strapi.io/dev-docs/api/document-service#examples-1; let entries = await strapi.documents(modelUid).findMany({ locUploadPLevel: 6, @@ -165,20 +157,15 @@ const LocalazyTransferUploadService = ({ strapi }: { strapi: Core.Strapi }) => ( */ entries = omitDeep(entries, ['locale', 'createdAt', 'updatedAt', 'publishedAt']); - entries.forEach((entry) => { - const projectedEntry = projectBlocksFields(entry, strapi.getModel(modelUid), (uid) => - strapi.getModel(uid as any) - ); - const flatten = flattenObject({ - [modelUid]: projectedEntry, - }); - // get only enabled fields; "__component" will be filtered out inside of the function - const pickedFlatten = pickEntries(flatten, pickPathsWithUid); - pickedFlattenStrapiContent = { - ...pickedFlattenStrapiContent, - ...pickedFlatten, - }; - }); + pickedFlattenStrapiContent = { + ...pickedFlattenStrapiContent, + ...getUploadKeysForEntries({ + entries, + modelUid, + transferSetupModelProps: currentTransferSetupModel, + getModel: (uid) => strapi.getModel(uid as any), + }), + }; // Add character limit metadata for fields that have maxLength defined in the content type schema const characterLimitsMetadata = getCharacterLimitsMetadata(pickedFlattenStrapiContent, modelUid); diff --git a/server/src/utils/__tests__/get-picked-flatten-keys-for-hook-entry.test.ts b/server/src/utils/__tests__/get-picked-flatten-keys-for-hook-entry.test.ts new file mode 100644 index 0000000..1d76809 --- /dev/null +++ b/server/src/utils/__tests__/get-picked-flatten-keys-for-hook-entry.test.ts @@ -0,0 +1,146 @@ +import getPickedFlattenKeysForHookEntry from '../get-picked-flatten-keys-for-hook-entry'; +import { getUploadKeysForEntries } from '../get-upload-keys-for-entries'; + +/** + * The automated upload (on create/update) and deprecation (on delete) must send exactly the keys + * the manual upload sends: blocks projected to their text leaves, dynamic zone fields included, + * and entries excluded from translation left out. + */ + +const uid = 'api::about.about'; +const documentId = 'about-doc'; + +const models: Record = { + [uid]: { + uid, + collectionName: 'about', + attributes: { + title: { type: 'string' }, + story: { type: 'blocks' }, + meta: { type: 'json' }, + seo: { type: 'component', repeatable: false, component: 'shared.seo' }, + beats: { type: 'dynamiczone', components: ['about.hero', 'about.timeline'] }, + }, + }, + 'shared.seo': { uid: 'shared.seo', attributes: { summary: { type: 'blocks' }, metaTitle: { type: 'string' } } }, + 'about.hero': { uid: 'about.hero', attributes: { chapter: { type: 'string' }, line: { type: 'blocks' } } }, + 'about.timeline': { + uid: 'about.timeline', + attributes: { stops: { type: 'component', repeatable: true, component: 'about.stop' } }, + }, + 'about.stop': { uid: 'about.stop', attributes: { label: { type: 'string' }, notes: { type: 'blocks' } } }, +}; + +const setupModel = { + __model__: true, + title: true, + story: true, + meta: true, + seo: { summary: true, metaTitle: true }, + beats: [ + { __component__: 'about.hero', chapter: true, line: true }, + { __component__: 'about.timeline', stops: { label: true, notes: true } }, + ], +}; + +const paragraph = (...children: any[]) => ({ type: 'paragraph', children }); +const entry = { + documentId, + locale: 'cs', + title: 'O mně', + story: [ + paragraph( + { type: 'text', text: 'Ahoj ' }, + { type: 'text', text: 'světe', bold: true }, + { type: 'link', url: 'https://localazy.com', children: [{ type: 'text', text: 'odkaz' }] } + ), + ], + meta: { og: { title: 'Titulek' } }, + seo: { id: 4, metaTitle: 'O mně | Web', summary: [paragraph({ type: 'text', text: 'Shrnutí' })] }, + beats: [ + { __component: 'about.hero', id: 1, chapter: 'Úvod', line: [paragraph({ type: 'text', text: 'Řádek' })] }, + { + __component: 'about.timeline', + id: 3, + stops: [{ id: 10, label: 'Děčín', notes: [paragraph({ type: 'text', text: 'Odtud pocházím.' })] }], + }, + ], +}; + +let excluded: string[] = []; + +jest.mock('../../core', () => ({ + getPluginSettingsService: () => ({ + getContentTransferSetup: async () => ({ has_setup: true, setup: [{ about: setupModel }] }), + }), + getLocalazyUserService: () => ({ getUser: async () => ({ accessToken: 'token', project: { id: 'project' } }) }), + getLocalazyPubAPIService: () => ({ + getProject: async () => ({ sourceLanguage: 1, languages: [{ id: 1, code: 'cs' }] }), + }), + getStrapiI18nService: () => ({ getLocales: async () => [{ code: 'cs', isDefault: true }] }), + getEntryExclusionService: () => ({ getContentTypeExclusions: async () => excluded }), +})); + +jest.mock('../../services/helpers/plugin-settings-service-helper', () => ({ + __esModule: true, + default: jest.fn().mockImplementation(() => ({ + setup: async () => undefined, + shouldAllowAutomatedCreatedTrigger: () => true, + shouldAllowAutomatedUpdatedTrigger: () => true, + shouldAllowDeprecateOnDeletion: () => true, + })), +})); + +describe('getPickedFlattenKeysForHookEntry', () => { + const originalStrapi = { ...(global as any).strapi }; + + beforeEach(() => { + excluded = []; + Object.assign((global as any).strapi, { + documents: jest.fn(() => ({ findOne: jest.fn(async () => JSON.parse(JSON.stringify(entry))) })), + getModel: (modelUid: string) => models[modelUid], + contentTypes: { [uid]: models[uid] }, + components: Object.fromEntries(Object.entries(models).filter(([key]) => key !== uid)), + }); + }); + + afterEach(() => { + Object.assign((global as any).strapi, originalStrapi); + }); + + const params = (action: string) => ({ + context: { action, contentType: { uid, collectionName: 'about' } } as any, + documentId, + locale: 'cs', + }); + + it.each(['create', 'update', 'delete'])('on %s, sends the same keys as the manual upload', async (action) => { + const result = await getPickedFlattenKeysForHookEntry(params(action)); + + const manualUploadKeys = getUploadKeysForEntries({ + entries: [entry], + modelUid: uid, + transferSetupModelProps: setupModel, + getModel: (modelUid) => models[modelUid], + }); + expect(result.pickedFlatten).toEqual(expect.objectContaining(manualUploadKeys)); + expect(Object.keys(result.pickedFlatten).filter((key) => !key.endsWith('[limit]'))).toEqual( + Object.keys(manualUploadKeys) + ); + + expect(result.pickedFlatten).toMatchObject({ + [`${uid}[${documentId}].story[0].children[1].text`]: 'světe', + [`${uid}[${documentId}].story[0].children[2].children[0].text`]: 'odkaz', + [`${uid}[${documentId}].seo[4].summary[0].children[0].text`]: 'Shrnutí', + [`${uid}[${documentId}].beats[1;about.hero].line[0].children[0].text`]: 'Řádek', + [`${uid}[${documentId}].beats[3;about.timeline].stops[10].notes[0].children[0].text`]: 'Odtud pocházím.', + }); + // blocks structure is never uploaded as text + expect(Object.keys(result.pickedFlatten).some((key) => /\.(type|bold|url)$/.test(key))).toBe(false); + }); + + it('skips entries excluded from translation', async () => { + excluded = [documentId]; + expect(await getPickedFlattenKeysForHookEntry(params('update'))).toBeUndefined(); + }); +}); diff --git a/server/src/utils/__tests__/transfer-round-trip.test.ts b/server/src/utils/__tests__/transfer-round-trip.test.ts index 8b89cd1..a7f691d 100644 --- a/server/src/utils/__tests__/transfer-round-trip.test.ts +++ b/server/src/utils/__tests__/transfer-round-trip.test.ts @@ -1,8 +1,5 @@ import { cloneDeep, isPlainObject } from 'lodash-es'; -import { projectBlocksFields } from '../blocks-to-translatable'; -import { flattenObject } from '../flatten-object'; -import { pickEntries } from '../pick-entries'; -import { getPickPathsWithComponents } from '../transfer-setup-utils'; +import { getUploadKeysForEntries } from '../get-upload-keys-for-entries'; import { collectDownloadedContent, DownloadedLocalazyKey } from '../collect-downloaded-content'; import { buildLocalizedCreateEntry } from '../build-localized-create-entry'; import { parsedLocalazyEntryToUpdateEntry } from '../parsed-localazy-entry-to-update-entry'; @@ -259,10 +256,12 @@ const normalize = (value: any): any => { // --------------------------------------------------------------------------------------------- const upload = (sourceEntry: any): Record => { - const projected = projectBlocksFields(sourceEntry, getModel(uid), getModel); - const flat = flattenObject({ [uid]: projected }); - const pickPaths = getPickPathsWithComponents(setupModel).map((path) => `${uid}.${path}`); - const picked = pickEntries(flat, pickPaths); + const picked = getUploadKeysForEntries({ + entries: [sourceEntry], + modelUid: uid, + transferSetupModelProps: setupModel, + getModel, + }); // Localazy stores no empty source strings return Object.fromEntries(Object.entries(picked).filter(([, v]) => typeof v === 'string' && v !== '')) as any; }; diff --git a/server/src/utils/get-picked-flatten-keys-for-hook-entry.ts b/server/src/utils/get-picked-flatten-keys-for-hook-entry.ts index a1007b3..7435f67 100644 --- a/server/src/utils/get-picked-flatten-keys-for-hook-entry.ts +++ b/server/src/utils/get-picked-flatten-keys-for-hook-entry.ts @@ -1,10 +1,9 @@ import { isoStrapiToLocalazy } from './iso-locales-utils'; import config from '../config'; import { omitDeep } from './omit-deep'; -import { flattenObject } from './flatten-object'; -import { pickEntries } from './pick-entries'; import { getCharacterLimitsMetadata } from './get-character-limits-metadata'; import { findSetupModelByCollectionName, getPickPaths } from './transfer-setup-utils'; +import { getUploadKeysForEntries } from './get-upload-keys-for-entries'; import PluginSettingsServiceHelper from '../services/helpers/plugin-settings-service-helper'; import { ContentTransferSetup } from '../models/plugin/content-transfer-setup'; import { UID } from '@strapi/strapi'; @@ -13,6 +12,7 @@ import { getStrapiI18nService, getLocalazyUserService, getLocalazyPubAPIService, + getEntryExclusionService, } from '../core'; import type { Context } from '@strapi/types/dist/modules/documents/middleware'; import type { HookParams } from '../models/plugin/hook-params'; @@ -167,7 +167,11 @@ export default async (params: HookParams) => { * Prepare the data structure and upload it to Localazy */ const modelUid = context.contentType.uid; - const entries = await getEventEntries(params); + // entries excluded from translation are not uploaded (nor deprecated), as in the manual upload + const excludedEntries = await getEntryExclusionService().getContentTypeExclusions(modelUid); + const entries = (await getEventEntries(params)).filter( + (entry) => !!entry && !excludedEntries.includes(entry.documentId) + ); if (entries.length === 0) { return; @@ -186,20 +190,14 @@ export default async (params: HookParams) => { strapi.log.warn(`No fields for collection ${contextModel} transfer are enabled.`); return; } - const pickPathsWithUid = pickPaths.map((pickPath) => `${modelUid}.${pickPath}`); - - // flatten Strapi content - let flatten = {}; - for (const reducedEntry of reducedEntries) { - flatten = { - ...flatten, - ...flattenObject({ - [modelUid]: reducedEntry, - }), - }; - } - // get only enabled fields; "__component" will be filtered out inside of the function - const pickedFlatten = pickEntries(flatten, pickPathsWithUid); + + // the same keys as the manual upload (blocks projected to text leaves, dynamic zones included) + const pickedFlatten = getUploadKeysForEntries({ + entries: reducedEntries, + modelUid, + transferSetupModelProps: currentTransferSetupModel, + getModel: (uid) => strapi.getModel(uid as any), + }); // Add character limit metadata for fields that have maxLength defined in the content type schema const characterLimitsMetadata = getCharacterLimitsMetadata(pickedFlatten, modelUid); diff --git a/server/src/utils/get-upload-keys-for-entries.ts b/server/src/utils/get-upload-keys-for-entries.ts new file mode 100644 index 0000000..f3bcd85 --- /dev/null +++ b/server/src/utils/get-upload-keys-for-entries.ts @@ -0,0 +1,39 @@ +import { flattenObject } from './flatten-object'; +import { pickEntries } from './pick-entries'; +import { projectBlocksFields } from './blocks-to-translatable'; +import { getPickPathsWithComponents } from './transfer-setup-utils'; + +type GetModel = (uid: string) => { attributes?: Record } | undefined; + +/** + * The Localazy keys (and source values) of the enabled fields of `entries`, as uploaded by both + * the manual upload and the automated upload/deprecation on create, update and delete: blocks + * fields are projected to their text leaves (see `projectBlocksFields`) and dynamic zone fields + * are picked per component (see `getPickPathsWithComponents`). + * + * @param transferSetupModelProps the model's entry of the Content Transfer Setup + */ +export const getUploadKeysForEntries = ({ + entries, + modelUid, + transferSetupModelProps, + getModel, +}: { + entries: any[]; + modelUid: string; + transferSetupModelProps: any; + getModel: GetModel; +}): Record => { + const pickPathsWithUid = getPickPathsWithComponents(transferSetupModelProps).map( + (pickPath) => `${modelUid}.${pickPath}` + ); + + let uploadKeys: Record = {}; + for (const entry of entries) { + const projectedEntry = projectBlocksFields(entry, getModel(modelUid), getModel); + const flatten = flattenObject({ [modelUid]: projectedEntry }); + // get only enabled fields; "__component" will be filtered out inside of the function + uploadKeys = { ...uploadKeys, ...pickEntries(flatten, pickPathsWithUid) }; + } + return uploadKeys; +}; From e86f770ea4f27d0e208b9c8ba2f6c996374c70c6 Mon Sep 17 00:00:00 2001 From: David Vaclavek <49518842+david-vaclavek@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:49:09 +0100 Subject: [PATCH 2/3] fix: webhook setup pre-fills the plugin's real webhook URL The dialog suggested `/api/localazy/public/transfer/download`, but the plugin's public route is `/localazy/public/transfer/download` (no `/api` prefix). Strapi answers the `/api` path with 405, so a webhook saved with the suggested URL never reached the plugin. Co-Authored-By: Claude Opus 5.5 --- admin/src/modules/plugin-settings/components/WebhookSetup.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/admin/src/modules/plugin-settings/components/WebhookSetup.tsx b/admin/src/modules/plugin-settings/components/WebhookSetup.tsx index 99baa48..38d7193 100644 --- a/admin/src/modules/plugin-settings/components/WebhookSetup.tsx +++ b/admin/src/modules/plugin-settings/components/WebhookSetup.tsx @@ -4,7 +4,8 @@ import { Box, Flex, Typography, Field, Button, Alert, Link, Loader, Dialog } fro import { Check, WarningCircle, Information, Link as LinkIcon } from '@strapi/icons'; import ProjectService from '../../@common/services/project-service'; -const WEBHOOK_PATH = '/api/localazy/public/transfer/download'; +// the plugin's public route (server/src/routes/localazy-public-transfer-routes.ts); not under `/api` +const WEBHOOK_PATH = '/localazy/public/transfer/download'; const LOCALAZY_DOCS_URL = 'https://localazy.com/docs/general/webhooks'; type WebhookState = 'loading' | 'configured' | 'not_configured'; From da3cd00e79442c6f2748aac639a31ebc743fa6c7 Mon Sep 17 00:00:00 2001 From: David Vaclavek <49518842+david-vaclavek@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:56:59 +0100 Subject: [PATCH 3/3] fix: automated upload works when the source language is not English The hooks looked for the default locale with `locales.find()` + `isDefault`, but Strapi's i18n service returns plain locale rows without `isDefault` (only its admin API adds it). The lookup always fell back to the plugin default `en`, so for any project with another source language every automated upload and deprecation stopped with "Source locales do not match". Use `getDefaultLocaleCode()`, as the manual upload does. Co-Authored-By: Claude Opus 5.5 --- .../get-picked-flatten-keys-for-hook-entry.test.ts | 6 +++++- .../src/utils/get-picked-flatten-keys-for-hook-entry.ts | 8 ++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/server/src/utils/__tests__/get-picked-flatten-keys-for-hook-entry.test.ts b/server/src/utils/__tests__/get-picked-flatten-keys-for-hook-entry.test.ts index 1d76809..45b2d7b 100644 --- a/server/src/utils/__tests__/get-picked-flatten-keys-for-hook-entry.test.ts +++ b/server/src/utils/__tests__/get-picked-flatten-keys-for-hook-entry.test.ts @@ -77,7 +77,11 @@ jest.mock('../../core', () => ({ getLocalazyPubAPIService: () => ({ getProject: async () => ({ sourceLanguage: 1, languages: [{ id: 1, code: 'cs' }] }), }), - getStrapiI18nService: () => ({ getLocales: async () => [{ code: 'cs', isDefault: true }] }), + // as Strapi's i18n returns them: locale rows carry no `isDefault`, the default comes separately + getStrapiI18nService: () => ({ + getLocales: async () => [{ code: 'en' }, { code: 'cs' }], + getDefaultLocaleCode: async () => 'cs', + }), getEntryExclusionService: () => ({ getContentTypeExclusions: async () => excluded }), })); diff --git a/server/src/utils/get-picked-flatten-keys-for-hook-entry.ts b/server/src/utils/get-picked-flatten-keys-for-hook-entry.ts index 7435f67..1b0483a 100644 --- a/server/src/utils/get-picked-flatten-keys-for-hook-entry.ts +++ b/server/src/utils/get-picked-flatten-keys-for-hook-entry.ts @@ -144,11 +144,11 @@ export default async (params: HookParams) => { const projectSourceLanguageCode = sourceLanguage.code; // Strapi default locale not compatible with project source language - const strapiLocales = await StrapiI18nService.getLocales(); - const defaultLocale = strapiLocales.find((locale) => locale.isDefault); + // `locales.find()` returns plain rows without `isDefault`; ask i18n for the default locale itself + const strapiDefaultLocaleCode = await StrapiI18nService.getDefaultLocaleCode(); - const strapiDefaultLocale = defaultLocale - ? isoStrapiToLocalazy(defaultLocale.code) + const strapiDefaultLocale = strapiDefaultLocaleCode + ? isoStrapiToLocalazy(strapiDefaultLocaleCode) : config.default.LOCALAZY_DEFAULT_LOCALE; if (strapiDefaultLocale !== projectSourceLanguageCode) { strapi.log.warn("Localazy Plugin: Source locales do not match; the operation won't proceed");