@strapi/data-transfer 5.55.1 → 5.57.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/directory/providers/source/index.js +3 -3
- package/dist/directory/providers/source/index.js.map +1 -1
- package/dist/directory/providers/source/index.mjs +2 -2
- package/dist/directory/providers/source/index.mjs.map +1 -1
- package/dist/engine/index.js +13 -8
- package/dist/engine/index.js.map +1 -1
- package/dist/engine/index.mjs +9 -4
- package/dist/engine/index.mjs.map +1 -1
- package/dist/engine/validation/provider.js +2 -2
- package/dist/engine/validation/provider.js.map +1 -1
- package/dist/engine/validation/provider.mjs +1 -1
- package/dist/engine/validation/provider.mjs.map +1 -1
- package/dist/engine/validation/schemas/index.js +4 -4
- package/dist/engine/validation/schemas/index.js.map +1 -1
- package/dist/engine/validation/schemas/index.mjs +3 -3
- package/dist/engine/validation/schemas/index.mjs.map +1 -1
- package/dist/file/providers/source/index.js +3 -3
- package/dist/file/providers/source/index.js.map +1 -1
- package/dist/file/providers/source/index.mjs +2 -2
- package/dist/file/providers/source/index.mjs.map +1 -1
- package/dist/strapi/providers/local-destination/index.js +1 -1
- package/dist/strapi/providers/local-destination/index.mjs +1 -1
- package/dist/strapi/providers/local-destination/strategies/restore/configuration.js +4 -4
- package/dist/strapi/providers/local-destination/strategies/restore/configuration.js.map +1 -1
- package/dist/strapi/providers/local-destination/strategies/restore/configuration.mjs +4 -4
- package/dist/strapi/providers/local-destination/strategies/restore/configuration.mjs.map +1 -1
- package/dist/strapi/providers/local-destination/strategies/restore/entities.js +1 -1
- package/dist/strapi/providers/local-destination/strategies/restore/entities.mjs +1 -1
- package/dist/strapi/providers/local-destination/strategies/restore/index.js +5 -5
- package/dist/strapi/providers/local-destination/strategies/restore/index.js.map +1 -1
- package/dist/strapi/providers/local-destination/strategies/restore/index.mjs +5 -3
- package/dist/strapi/providers/local-destination/strategies/restore/index.mjs.map +1 -1
- package/dist/strapi/providers/local-source/configuration.d.ts.map +1 -1
- package/dist/strapi/providers/local-source/configuration.js +4 -2
- package/dist/strapi/providers/local-source/configuration.js.map +1 -1
- package/dist/strapi/providers/local-source/configuration.mjs +4 -2
- package/dist/strapi/providers/local-source/configuration.mjs.map +1 -1
- package/dist/strapi/providers/local-source/entities.js +1 -1
- package/dist/strapi/providers/local-source/entities.mjs +1 -1
- package/dist/strapi/providers/local-source/index.js +1 -1
- package/dist/strapi/providers/local-source/index.mjs +1 -1
- package/dist/strapi/providers/remote-destination/index.js +2 -2
- package/dist/strapi/providers/remote-destination/index.js.map +1 -1
- package/dist/strapi/providers/remote-destination/index.mjs +1 -1
- package/dist/strapi/providers/remote-destination/index.mjs.map +1 -1
- package/dist/strapi/providers/remote-source/index.d.ts.map +1 -1
- package/dist/strapi/providers/remote-source/index.js +3 -2
- package/dist/strapi/providers/remote-source/index.js.map +1 -1
- package/dist/strapi/providers/remote-source/index.mjs +3 -2
- package/dist/strapi/providers/remote-source/index.mjs.map +1 -1
- package/dist/strapi/queries/entity.js +13 -13
- package/dist/strapi/queries/entity.js.map +1 -1
- package/dist/strapi/queries/entity.mjs +13 -13
- package/dist/strapi/queries/entity.mjs.map +1 -1
- package/dist/strapi/queries/link.js +7 -7
- package/dist/strapi/queries/link.js.map +1 -1
- package/dist/strapi/queries/link.mjs +3 -3
- package/dist/strapi/queries/link.mjs.map +1 -1
- package/dist/strapi/remote/handlers/pull.js +2 -3
- package/dist/strapi/remote/handlers/pull.js.map +1 -1
- package/dist/strapi/remote/handlers/pull.mjs +2 -3
- package/dist/strapi/remote/handlers/pull.mjs.map +1 -1
- package/dist/strapi/remote/handlers/push.js +2 -2
- package/dist/strapi/remote/handlers/push.mjs +2 -2
- package/dist/strapi/utils/project-settings-logos.js +2 -2
- package/dist/strapi/utils/project-settings-logos.js.map +1 -1
- package/dist/strapi/utils/project-settings-logos.mjs +2 -2
- package/dist/strapi/utils/project-settings-logos.mjs.map +1 -1
- package/dist/utils/components.d.ts.map +1 -1
- package/dist/utils/components.js +8 -8
- package/dist/utils/components.js.map +1 -1
- package/dist/utils/components.mjs +9 -9
- package/dist/utils/components.mjs.map +1 -1
- package/dist/utils/json.js +8 -6
- package/dist/utils/json.js.map +1 -1
- package/dist/utils/json.mjs +5 -3
- package/dist/utils/json.mjs.map +1 -1
- package/dist/utils/schema.d.ts.map +1 -1
- package/dist/utils/schema.js +2 -2
- package/dist/utils/schema.js.map +1 -1
- package/dist/utils/schema.mjs +2 -2
- package/dist/utils/schema.mjs.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project-settings-logos.js","sources":["../../../src/strapi/utils/project-settings-logos.ts"],"sourcesContent":["import { join } from 'path';\nimport { Readable } from 'stream';\nimport { pick } from 'lodash/fp';\nimport { readFile } from 'fs-extra';\nimport { lookup as lookupMimeType } from 'mime-types';\nimport * as webStream from 'stream/web';\nimport type { Core } from '@strapi/types';\n\nexport const PROJECT_SETTINGS_CORE_STORE_KEY = 'core_admin_project-settings';\n\nexport const PROJECT_SETTINGS_LOGO_FIELDS = ['menuLogo', 'authLogo'] as const;\n\nexport type ProjectSettingsLogoField = (typeof PROJECT_SETTINGS_LOGO_FIELDS)[number];\n\nexport type ProjectSettingsLogo = {\n name?: string;\n hash?: string;\n url?: string;\n width?: number;\n height?: number;\n ext?: string;\n size?: number;\n mime?: string;\n provider?: string;\n __transferBuffer?: string;\n};\n\nexport type ProjectSettingsStoreValue = {\n menuLogo?: ProjectSettingsLogo | null;\n authLogo?: ProjectSettingsLogo | null;\n};\n\nexport type CoreStoreRow = {\n key: string;\n value: unknown;\n [key: string]: unknown;\n};\n\n// The shape persisted back to core-store, matching what the admin project-settings\n// service stores (so the admin UI keeps behaving identically after a transfer).\nconst LOGO_PERSISTED_FIELDS = [\n 'name',\n 'hash',\n 'url',\n 'width',\n 'height',\n 'ext',\n 'size',\n 'provider',\n] as const;\n\nconst isProjectSettingsRow = (row: CoreStoreRow) => row.key === PROJECT_SETTINGS_CORE_STORE_KEY;\n\nconst getConfiguredUploadProvider = (strapi: Core.Strapi) =>\n (strapi.config.get('plugin::upload') as { provider?: string } | undefined)?.provider;\n\n// Admin logos with no provider were uploaded with the local provider (the default).\nconst isLocalProviderLogo = (logo: ProjectSettingsLogo) =>\n !logo.provider || logo.provider === 'local';\n\n// Best-effort mime type for a logo so that remote providers (S3, Cloudinary, …)\n// store the correct Content-Type and the image renders instead of downloading.\n// The admin does not persist the mime type, so it is reconstructed from the\n// file extension (falling back to the file name).\nconst getLogoMimeType = (logo: ProjectSettingsLogo): string | undefined => {\n const fromExt = logo.ext ? lookupMimeType(logo.ext) : false;\n if (fromExt) {\n return fromExt;\n }\n\n const fromName = logo.name ? lookupMimeType(logo.name) : false;\n if (fromName) {\n return fromName;\n }\n\n return undefined;\n};\n\n/**\n * Resolve the URL to read a non-local logo from during export.\n *\n * Mirrors the media-library asset export: when the file lives on the\n * currently-configured provider and that provider serves private files,\n * a signed URL is generated so the bytes can be fetched.\n */\nconst getRemoteLogoUrl = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n const { provider } = strapi.plugins.upload;\n const providerName = getConfiguredUploadProvider(strapi);\n\n if (\n logo.provider === providerName &&\n typeof provider?.isPrivate === 'function' &&\n typeof provider?.getSignedUrl === 'function' &&\n (await provider.isPrivate())\n ) {\n const { url } = await provider.getSignedUrl(logo);\n return url;\n }\n\n return logo.url;\n};\n\nconst logoLabel = (logo: ProjectSettingsLogo) => logo.name ?? logo.hash ?? 'unknown';\n\nconst readLocalLogoBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n const filepath = join(strapi.dirs.static.public, logo.url as string);\n\n try {\n const buffer = await readFile(filepath);\n return buffer.toString('base64');\n } catch (error) {\n const code =\n error && typeof error === 'object' && 'code' in error\n ? (error as NodeJS.ErrnoException).code\n : undefined;\n\n if (code === 'ENOENT') {\n strapi.log.warn(\n `[Data transfer] Admin logo \"${logoLabel(logo)}\" exists in project settings but no corresponding file was found to transfer. Path: ${filepath}`\n );\n return undefined;\n }\n\n throw error;\n }\n};\n\nconst readRemoteLogoBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n const url = await getRemoteLogoUrl(strapi, logo);\n const response = await strapi.fetch(url);\n\n if (response.status !== 200 || !response.body) {\n strapi.log.warn(\n `[Data transfer] Admin logo \"${logoLabel(logo)}\" exists in project settings but could not be fetched for transfer. URL: ${url} (status: ${response.status})`\n );\n return undefined;\n }\n\n const chunks: Uint8Array[] = [];\n\n for await (const chunk of Readable.fromWeb(\n response.body as webStream.ReadableStream<Uint8Array>\n )) {\n chunks.push(chunk);\n }\n\n return Buffer.concat(chunks).toString('base64');\n};\n\nconst readLogoTransferBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n if (!logo.url) {\n return undefined;\n }\n\n if (isLocalProviderLogo(logo)) {\n return readLocalLogoBuffer(strapi, logo);\n }\n\n return readRemoteLogoBuffer(strapi, logo);\n};\n\nconst enrichLogoForExport = async (\n strapi: Core.Strapi,\n logo: ProjectSettingsLogo | null | undefined\n) => {\n if (!logo?.url) {\n return logo;\n }\n\n const transferBuffer = await readLogoTransferBuffer(strapi, logo);\n\n if (!transferBuffer) {\n return logo;\n }\n\n return {\n ...logo,\n __transferBuffer: transferBuffer,\n };\n};\n\nexport const enrichProjectSettingsForExport = async (\n strapi: Core.Strapi,\n row: CoreStoreRow\n): Promise<CoreStoreRow> => {\n if (!isProjectSettingsRow(row)) {\n return row;\n }\n\n const settings = row.value as ProjectSettingsStoreValue;\n\n const [menuLogo, authLogo] = await Promise.all([\n enrichLogoForExport(strapi, settings.menuLogo),\n enrichLogoForExport(strapi, settings.authLogo),\n ]);\n\n return {\n ...row,\n value: {\n ...settings,\n menuLogo,\n authLogo,\n },\n };\n};\n\n/**\n * Re-upload a transferred logo to the destination's configured upload provider.\n *\n * The file is always re-uploaded through the destination provider, so the\n * persisted `url` and `provider` reflect the destination (matching how the\n * media-library asset restore behaves). A best-effort mime type is supplied so\n * remote providers serve the logo with the correct Content-Type.\n */\nconst uploadLogoFromTransferBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n if (!logo.__transferBuffer) {\n return logo;\n }\n\n const { __transferBuffer: transferBuffer, ...logoWithoutBuffer } = logo;\n const provider = getConfiguredUploadProvider(strapi);\n const mime = getLogoMimeType(logoWithoutBuffer);\n\n const file = {\n ...logoWithoutBuffer,\n ...(mime ? { mime } : {}),\n stream: Readable.from(Buffer.from(transferBuffer, 'base64')),\n provider,\n };\n\n await strapi.plugin('upload').provider.uploadStream(file);\n\n return pick(LOGO_PERSISTED_FIELDS, file);\n};\n\nexport const restoreProjectSettingsLogos = async (\n strapi: Core.Strapi,\n settings: ProjectSettingsStoreValue\n): Promise<ProjectSettingsStoreValue> => {\n const [menuLogo, authLogo] = await Promise.all([\n settings.menuLogo ? uploadLogoFromTransferBuffer(strapi, settings.menuLogo) : settings.menuLogo,\n settings.authLogo ? uploadLogoFromTransferBuffer(strapi, settings.authLogo) : settings.authLogo,\n ]);\n\n return {\n ...settings,\n menuLogo,\n authLogo,\n };\n};\n\nexport const restoreProjectSettingsRow = async (strapi: Core.Strapi, row: CoreStoreRow) => {\n if (!isProjectSettingsRow(row)) {\n return row;\n }\n\n return {\n ...row,\n value: await restoreProjectSettingsLogos(strapi, row.value as ProjectSettingsStoreValue),\n };\n};\n"],"names":["PROJECT_SETTINGS_CORE_STORE_KEY","LOGO_PERSISTED_FIELDS","isProjectSettingsRow","row","key","getConfiguredUploadProvider","strapi","config","get","provider","isLocalProviderLogo","logo","getLogoMimeType","fromExt","ext","lookupMimeType","fromName","name","undefined","getRemoteLogoUrl","plugins","upload","providerName","isPrivate","getSignedUrl","url","logoLabel","hash","readLocalLogoBuffer","filepath","join","dirs","static","public","buffer","readFile","toString","error","code","log","warn","readRemoteLogoBuffer","response","fetch","status","body","chunks","chunk","Readable","fromWeb","push","Buffer","concat","readLogoTransferBuffer","enrichLogoForExport","transferBuffer","__transferBuffer","enrichProjectSettingsForExport","settings","value","menuLogo","authLogo","Promise","all","uploadLogoFromTransferBuffer","logoWithoutBuffer","mime","file","stream","from","plugin","uploadStream","pick","restoreProjectSettingsLogos","restoreProjectSettingsRow"],"mappings":";;;;;;;;AAQO,MAAMA,kCAAkC;AA8B/C;AACA;AACA,MAAMC,qBAAAA,GAAwB;AAC5B,IAAA,MAAA;AACA,IAAA,MAAA;AACA,IAAA,KAAA;AACA,IAAA,OAAA;AACA,IAAA,QAAA;AACA,IAAA,KAAA;AACA,IAAA,MAAA;AACA,IAAA;AACD,CAAA;AAED,MAAMC,oBAAAA,GAAuB,CAACC,GAAAA,GAAsBA,GAAAA,CAAIC,GAAG,KAAKJ,+BAAAA;AAEhE,MAAMK,2BAAAA,GAA8B,CAACC,MAAAA,GAClCA,MAAAA,CAAOC,MAAM,CAACC,GAAG,CAAC,gBAAA,CAAA,EAAyDC,QAAAA;AAE9E;AACA,MAAMC,mBAAAA,GAAsB,CAACC,IAAAA,GAC3B,CAACA,KAAKF,QAAQ,IAAIE,IAAAA,CAAKF,QAAQ,KAAK,OAAA;AAEtC;AACA;AACA;AACA;AACA,MAAMG,kBAAkB,CAACD,IAAAA,GAAAA;AACvB,IAAA,MAAME,UAAUF,IAAAA,CAAKG,GAAG,GAAGC,gBAAAA,CAAeJ,IAAAA,CAAKG,GAAG,CAAA,GAAI,KAAA;AACtD,IAAA,IAAID,OAAAA,EAAS;QACX,OAAOA,OAAAA;AACT,IAAA;AAEA,IAAA,MAAMG,WAAWL,IAAAA,CAAKM,IAAI,GAAGF,gBAAAA,CAAeJ,IAAAA,CAAKM,IAAI,CAAA,GAAI,KAAA;AACzD,IAAA,IAAID,QAAAA,EAAU;QACZ,OAAOA,QAAAA;AACT,IAAA;IAEA,OAAOE,SAAAA;AACT,CAAA;AAEA;;;;;;IAOA,MAAMC,gBAAAA,GAAmB,OAAOb,MAAAA,EAAqBK,IAAAA,GAAAA;AACnD,IAAA,MAAM,EAAEF,QAAQ,EAAE,GAAGH,MA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AAAA,EAAQH,GAAAA,CAAIwD,KAAK;AAC5D,KAAA;AACF;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"project-settings-logos.js","sources":["../../../src/strapi/utils/project-settings-logos.ts"],"sourcesContent":["import { join } from 'path';\nimport { Readable } from 'stream';\nimport { pick } from 'lodash';\nimport { readFile } from 'fs-extra';\nimport { lookup as lookupMimeType } from 'mime-types';\nimport * as webStream from 'stream/web';\nimport type { Core } from '@strapi/types';\n\nexport const PROJECT_SETTINGS_CORE_STORE_KEY = 'core_admin_project-settings';\n\nexport const PROJECT_SETTINGS_LOGO_FIELDS = ['menuLogo', 'authLogo'] as const;\n\nexport type ProjectSettingsLogoField = (typeof PROJECT_SETTINGS_LOGO_FIELDS)[number];\n\nexport type ProjectSettingsLogo = {\n name?: string;\n hash?: string;\n url?: string;\n width?: number;\n height?: number;\n ext?: string;\n size?: number;\n mime?: string;\n provider?: string;\n __transferBuffer?: string;\n};\n\nexport type ProjectSettingsStoreValue = {\n menuLogo?: ProjectSettingsLogo | null;\n authLogo?: ProjectSettingsLogo | null;\n};\n\nexport type CoreStoreRow = {\n key: string;\n value: unknown;\n [key: string]: unknown;\n};\n\n// The shape persisted back to core-store, matching what the admin project-settings\n// service stores (so the admin UI keeps behaving identically after a transfer).\nconst LOGO_PERSISTED_FIELDS = [\n 'name',\n 'hash',\n 'url',\n 'width',\n 'height',\n 'ext',\n 'size',\n 'provider',\n] as const;\n\nconst isProjectSettingsRow = (row: CoreStoreRow) => row.key === PROJECT_SETTINGS_CORE_STORE_KEY;\n\nconst getConfiguredUploadProvider = (strapi: Core.Strapi) =>\n (strapi.config.get('plugin::upload') as { provider?: string } | undefined)?.provider;\n\n// Admin logos with no provider were uploaded with the local provider (the default).\nconst isLocalProviderLogo = (logo: ProjectSettingsLogo) =>\n !logo.provider || logo.provider === 'local';\n\n// Best-effort mime type for a logo so that remote providers (S3, Cloudinary, …)\n// store the correct Content-Type and the image renders instead of downloading.\n// The admin does not persist the mime type, so it is reconstructed from the\n// file extension (falling back to the file name).\nconst getLogoMimeType = (logo: ProjectSettingsLogo): string | undefined => {\n const fromExt = logo.ext ? lookupMimeType(logo.ext) : false;\n if (fromExt) {\n return fromExt;\n }\n\n const fromName = logo.name ? lookupMimeType(logo.name) : false;\n if (fromName) {\n return fromName;\n }\n\n return undefined;\n};\n\n/**\n * Resolve the URL to read a non-local logo from during export.\n *\n * Mirrors the media-library asset export: when the file lives on the\n * currently-configured provider and that provider serves private files,\n * a signed URL is generated so the bytes can be fetched.\n */\nconst getRemoteLogoUrl = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n const { provider } = strapi.plugins.upload;\n const providerName = getConfiguredUploadProvider(strapi);\n\n if (\n logo.provider === providerName &&\n typeof provider?.isPrivate === 'function' &&\n typeof provider?.getSignedUrl === 'function' &&\n (await provider.isPrivate())\n ) {\n const { url } = await provider.getSignedUrl(logo);\n return url;\n }\n\n return logo.url;\n};\n\nconst logoLabel = (logo: ProjectSettingsLogo) => logo.name ?? logo.hash ?? 'unknown';\n\nconst readLocalLogoBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n const filepath = join(strapi.dirs.static.public, logo.url as string);\n\n try {\n const buffer = await readFile(filepath);\n return buffer.toString('base64');\n } catch (error) {\n const code =\n error && typeof error === 'object' && 'code' in error\n ? (error as NodeJS.ErrnoException).code\n : undefined;\n\n if (code === 'ENOENT') {\n strapi.log.warn(\n `[Data transfer] Admin logo \"${logoLabel(logo)}\" exists in project settings but no corresponding file was found to transfer. Path: ${filepath}`\n );\n return undefined;\n }\n\n throw error;\n }\n};\n\nconst readRemoteLogoBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n const url = await getRemoteLogoUrl(strapi, logo);\n const response = await strapi.fetch(url);\n\n if (response.status !== 200 || !response.body) {\n strapi.log.warn(\n `[Data transfer] Admin logo \"${logoLabel(logo)}\" exists in project settings but could not be fetched for transfer. URL: ${url} (status: ${response.status})`\n );\n return undefined;\n }\n\n const chunks: Uint8Array[] = [];\n\n for await (const chunk of Readable.fromWeb(\n response.body as webStream.ReadableStream<Uint8Array>\n )) {\n chunks.push(chunk);\n }\n\n return Buffer.concat(chunks).toString('base64');\n};\n\nconst readLogoTransferBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n if (!logo.url) {\n return undefined;\n }\n\n if (isLocalProviderLogo(logo)) {\n return readLocalLogoBuffer(strapi, logo);\n }\n\n return readRemoteLogoBuffer(strapi, logo);\n};\n\nconst enrichLogoForExport = async (\n strapi: Core.Strapi,\n logo: ProjectSettingsLogo | null | undefined\n) => {\n if (!logo?.url) {\n return logo;\n }\n\n const transferBuffer = await readLogoTransferBuffer(strapi, logo);\n\n if (!transferBuffer) {\n return logo;\n }\n\n return {\n ...logo,\n __transferBuffer: transferBuffer,\n };\n};\n\nexport const enrichProjectSettingsForExport = async (\n strapi: Core.Strapi,\n row: CoreStoreRow\n): Promise<CoreStoreRow> => {\n if (!isProjectSettingsRow(row)) {\n return row;\n }\n\n const settings = row.value as ProjectSettingsStoreValue;\n\n const [menuLogo, authLogo] = await Promise.all([\n enrichLogoForExport(strapi, settings.menuLogo),\n enrichLogoForExport(strapi, settings.authLogo),\n ]);\n\n return {\n ...row,\n value: {\n ...settings,\n menuLogo,\n authLogo,\n },\n };\n};\n\n/**\n * Re-upload a transferred logo to the destination's configured upload provider.\n *\n * The file is always re-uploaded through the destination provider, so the\n * persisted `url` and `provider` reflect the destination (matching how the\n * media-library asset restore behaves). A best-effort mime type is supplied so\n * remote providers serve the logo with the correct Content-Type.\n */\nconst uploadLogoFromTransferBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n if (!logo.__transferBuffer) {\n return logo;\n }\n\n const { __transferBuffer: transferBuffer, ...logoWithoutBuffer } = logo;\n const provider = getConfiguredUploadProvider(strapi);\n const mime = getLogoMimeType(logoWithoutBuffer);\n\n const file = {\n ...logoWithoutBuffer,\n ...(mime ? { mime } : {}),\n stream: Readable.from(Buffer.from(transferBuffer, 'base64')),\n provider,\n };\n\n await strapi.plugin('upload').provider.uploadStream(file);\n\n return pick(file, LOGO_PERSISTED_FIELDS);\n};\n\nexport const restoreProjectSettingsLogos = async (\n strapi: Core.Strapi,\n settings: ProjectSettingsStoreValue\n): Promise<ProjectSettingsStoreValue> => {\n const [menuLogo, authLogo] = await Promise.all([\n settings.menuLogo ? uploadLogoFromTransferBuffer(strapi, settings.menuLogo) : settings.menuLogo,\n settings.authLogo ? uploadLogoFromTransferBuffer(strapi, settings.authLogo) : settings.authLogo,\n ]);\n\n return {\n ...settings,\n menuLogo,\n authLogo,\n };\n};\n\nexport const restoreProjectSettingsRow = async (strapi: Core.Strapi, row: CoreStoreRow) => {\n if (!isProjectSettingsRow(row)) {\n return row;\n }\n\n return {\n ...row,\n value: await restoreProjectSettingsLogos(strapi, row.value as ProjectSettingsStoreValue),\n };\n};\n"],"names":["PROJECT_SETTINGS_CORE_STORE_KEY","LOGO_PERSISTED_FIELDS","isProjectSettingsRow","row","key","getConfiguredUploadProvider","strapi","config","get","provider","isLocalProviderLogo","logo","getLogoMimeType","fromExt","ext","lookupMimeType","fromName","name","undefined","getRemoteLogoUrl","plugins","upload","providerName","isPrivate","getSignedUrl","url","logoLabel","hash","readLocalLogoBuffer","filepath","join","dirs","static","public","buffer","readFile","toString","error","code","log","warn","readRemoteLogoBuffer","response","fetch","status","body","chunks","chunk","Readable","fromWeb","push","Buffer","concat","readLogoTransferBuffer","enrichLogoForExport","transferBuffer","__transferBuffer","enrichProjectSettingsForExport","settings","value","menuLogo","authLogo","Promise","all","uploadLogoFromTransferBuffer","logoWithoutBuffer","mime","file","stream","from","plugin","uploadStream","pick","restoreProjectSettingsLogos","restoreProjectSettingsRow"],"mappings":";;;;;;;;AAQO,MAAMA,kCAAkC;AA8B/C;AACA;AACA,MAAMC,qBAAAA,GAAwB;AAC5B,IAAA,MAAA;AACA,IAAA,MAAA;AACA,IAAA,KAAA;AACA,IAAA,OAAA;AACA,IA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,IAAI,CAACd,cAAAA,EAAgB,QAAA,CAAA,CAAA;AAClD9C,QAAAA;AACF,KAAA;AAEA,IAAA,MAAMH,OAAOgE,MAAM,CAAC,UAAU7D,QAAQ,CAAC8D,YAAY,CAACJ,IAAAA,CAAAA;AAEpD,IAAA,OAAOK,OAAKL,IAAAA,EAAMlE,qBAAAA,CAAAA;AACpB,CAAA;AAEO,MAAMwE,2BAAAA,GAA8B,OACzCnE,MAAAA,EACAoD,QAAAA,GAAAA;AAEA,IAAA,MAAM,CAACE,QAAAA,EAAUC,QAAAA,CAAS,GAAG,MAAMC,OAAAA,CAAQC,GAAG,CAAC;QAC7CL,QAAAA,CAASE,QAAQ,GAAGI,4BAAAA,CAA6B1D,MAAAA,EAAQoD,SAASE,QAAQ,CAAA,GAAIF,SAASE,QAAQ;QAC/FF,QAAAA,CAASG,QAAQ,GAAGG,4BAAAA,CAA6B1D,MAAAA,EAAQoD,SAASG,QAAQ,CAAA,GAAIH,SAASG;AACxF,KAAA,CAAA;IAED,OAAO;AACL,QAAA,GAAGH,QAAQ;AACXE,QAAAA,QAAAA;AACAC,QAAAA;AACF,KAAA;AACF;AAEO,MAAMa,yBAAAA,GAA4B,OAAOpE,MAAAA,EAAqBH,GAAAA,GAAAA;IACnE,IAAI,CAACD,qBAAqBC,GAAAA,CAAAA,EAAM;QAC9B,OAAOA,GAAAA;AACT,IAAA;IAEA,OAAO;AACL,QAAA,GAAGA,GAAG;AACNwD,QAAAA,KAAAA,EAAO,MAAMc,2BAAAA,CAA4BnE,MAAAA,EAAQH,GAAAA,CAAIwD,KAAK;AAC5D,KAAA;AACF;;;;;;;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { join } from 'path';
|
|
2
2
|
import { Readable } from 'stream';
|
|
3
|
-
import { pick } from 'lodash
|
|
3
|
+
import { pick } from 'lodash';
|
|
4
4
|
import { readFile } from 'fs-extra';
|
|
5
5
|
import { lookup } from 'mime-types';
|
|
6
6
|
|
|
@@ -142,7 +142,7 @@ const enrichProjectSettingsForExport = async (strapi, row)=>{
|
|
|
142
142
|
provider
|
|
143
143
|
};
|
|
144
144
|
await strapi.plugin('upload').provider.uploadStream(file);
|
|
145
|
-
return pick(
|
|
145
|
+
return pick(file, LOGO_PERSISTED_FIELDS);
|
|
146
146
|
};
|
|
147
147
|
const restoreProjectSettingsLogos = async (strapi, settings)=>{
|
|
148
148
|
const [menuLogo, authLogo] = await Promise.all([
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project-settings-logos.mjs","sources":["../../../src/strapi/utils/project-settings-logos.ts"],"sourcesContent":["import { join } from 'path';\nimport { Readable } from 'stream';\nimport { pick } from 'lodash/fp';\nimport { readFile } from 'fs-extra';\nimport { lookup as lookupMimeType } from 'mime-types';\nimport * as webStream from 'stream/web';\nimport type { Core } from '@strapi/types';\n\nexport const PROJECT_SETTINGS_CORE_STORE_KEY = 'core_admin_project-settings';\n\nexport const PROJECT_SETTINGS_LOGO_FIELDS = ['menuLogo', 'authLogo'] as const;\n\nexport type ProjectSettingsLogoField = (typeof PROJECT_SETTINGS_LOGO_FIELDS)[number];\n\nexport type ProjectSettingsLogo = {\n name?: string;\n hash?: string;\n url?: string;\n width?: number;\n height?: number;\n ext?: string;\n size?: number;\n mime?: string;\n provider?: string;\n __transferBuffer?: string;\n};\n\nexport type ProjectSettingsStoreValue = {\n menuLogo?: ProjectSettingsLogo | null;\n authLogo?: ProjectSettingsLogo | null;\n};\n\nexport type CoreStoreRow = {\n key: string;\n value: unknown;\n [key: string]: unknown;\n};\n\n// The shape persisted back to core-store, matching what the admin project-settings\n// service stores (so the admin UI keeps behaving identically after a transfer).\nconst LOGO_PERSISTED_FIELDS = [\n 'name',\n 'hash',\n 'url',\n 'width',\n 'height',\n 'ext',\n 'size',\n 'provider',\n] as const;\n\nconst isProjectSettingsRow = (row: CoreStoreRow) => row.key === PROJECT_SETTINGS_CORE_STORE_KEY;\n\nconst getConfiguredUploadProvider = (strapi: Core.Strapi) =>\n (strapi.config.get('plugin::upload') as { provider?: string } | undefined)?.provider;\n\n// Admin logos with no provider were uploaded with the local provider (the default).\nconst isLocalProviderLogo = (logo: ProjectSettingsLogo) =>\n !logo.provider || logo.provider === 'local';\n\n// Best-effort mime type for a logo so that remote providers (S3, Cloudinary, …)\n// store the correct Content-Type and the image renders instead of downloading.\n// The admin does not persist the mime type, so it is reconstructed from the\n// file extension (falling back to the file name).\nconst getLogoMimeType = (logo: ProjectSettingsLogo): string | undefined => {\n const fromExt = logo.ext ? lookupMimeType(logo.ext) : false;\n if (fromExt) {\n return fromExt;\n }\n\n const fromName = logo.name ? lookupMimeType(logo.name) : false;\n if (fromName) {\n return fromName;\n }\n\n return undefined;\n};\n\n/**\n * Resolve the URL to read a non-local logo from during export.\n *\n * Mirrors the media-library asset export: when the file lives on the\n * currently-configured provider and that provider serves private files,\n * a signed URL is generated so the bytes can be fetched.\n */\nconst getRemoteLogoUrl = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n const { provider } = strapi.plugins.upload;\n const providerName = getConfiguredUploadProvider(strapi);\n\n if (\n logo.provider === providerName &&\n typeof provider?.isPrivate === 'function' &&\n typeof provider?.getSignedUrl === 'function' &&\n (await provider.isPrivate())\n ) {\n const { url } = await provider.getSignedUrl(logo);\n return url;\n }\n\n return logo.url;\n};\n\nconst logoLabel = (logo: ProjectSettingsLogo) => logo.name ?? logo.hash ?? 'unknown';\n\nconst readLocalLogoBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n const filepath = join(strapi.dirs.static.public, logo.url as string);\n\n try {\n const buffer = await readFile(filepath);\n return buffer.toString('base64');\n } catch (error) {\n const code =\n error && typeof error === 'object' && 'code' in error\n ? (error as NodeJS.ErrnoException).code\n : undefined;\n\n if (code === 'ENOENT') {\n strapi.log.warn(\n `[Data transfer] Admin logo \"${logoLabel(logo)}\" exists in project settings but no corresponding file was found to transfer. Path: ${filepath}`\n );\n return undefined;\n }\n\n throw error;\n }\n};\n\nconst readRemoteLogoBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n const url = await getRemoteLogoUrl(strapi, logo);\n const response = await strapi.fetch(url);\n\n if (response.status !== 200 || !response.body) {\n strapi.log.warn(\n `[Data transfer] Admin logo \"${logoLabel(logo)}\" exists in project settings but could not be fetched for transfer. URL: ${url} (status: ${response.status})`\n );\n return undefined;\n }\n\n const chunks: Uint8Array[] = [];\n\n for await (const chunk of Readable.fromWeb(\n response.body as webStream.ReadableStream<Uint8Array>\n )) {\n chunks.push(chunk);\n }\n\n return Buffer.concat(chunks).toString('base64');\n};\n\nconst readLogoTransferBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n if (!logo.url) {\n return undefined;\n }\n\n if (isLocalProviderLogo(logo)) {\n return readLocalLogoBuffer(strapi, logo);\n }\n\n return readRemoteLogoBuffer(strapi, logo);\n};\n\nconst enrichLogoForExport = async (\n strapi: Core.Strapi,\n logo: ProjectSettingsLogo | null | undefined\n) => {\n if (!logo?.url) {\n return logo;\n }\n\n const transferBuffer = await readLogoTransferBuffer(strapi, logo);\n\n if (!transferBuffer) {\n return logo;\n }\n\n return {\n ...logo,\n __transferBuffer: transferBuffer,\n };\n};\n\nexport const enrichProjectSettingsForExport = async (\n strapi: Core.Strapi,\n row: CoreStoreRow\n): Promise<CoreStoreRow> => {\n if (!isProjectSettingsRow(row)) {\n return row;\n }\n\n const settings = row.value as ProjectSettingsStoreValue;\n\n const [menuLogo, authLogo] = await Promise.all([\n enrichLogoForExport(strapi, settings.menuLogo),\n enrichLogoForExport(strapi, settings.authLogo),\n ]);\n\n return {\n ...row,\n value: {\n ...settings,\n menuLogo,\n authLogo,\n },\n };\n};\n\n/**\n * Re-upload a transferred logo to the destination's configured upload provider.\n *\n * The file is always re-uploaded through the destination provider, so the\n * persisted `url` and `provider` reflect the destination (matching how the\n * media-library asset restore behaves). A best-effort mime type is supplied so\n * remote providers serve the logo with the correct Content-Type.\n */\nconst uploadLogoFromTransferBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n if (!logo.__transferBuffer) {\n return logo;\n }\n\n const { __transferBuffer: transferBuffer, ...logoWithoutBuffer } = logo;\n const provider = getConfiguredUploadProvider(strapi);\n const mime = getLogoMimeType(logoWithoutBuffer);\n\n const file = {\n ...logoWithoutBuffer,\n ...(mime ? { mime } : {}),\n stream: Readable.from(Buffer.from(transferBuffer, 'base64')),\n provider,\n };\n\n await strapi.plugin('upload').provider.uploadStream(file);\n\n return pick(LOGO_PERSISTED_FIELDS, file);\n};\n\nexport const restoreProjectSettingsLogos = async (\n strapi: Core.Strapi,\n settings: ProjectSettingsStoreValue\n): Promise<ProjectSettingsStoreValue> => {\n const [menuLogo, authLogo] = await Promise.all([\n settings.menuLogo ? uploadLogoFromTransferBuffer(strapi, settings.menuLogo) : settings.menuLogo,\n settings.authLogo ? uploadLogoFromTransferBuffer(strapi, settings.authLogo) : settings.authLogo,\n ]);\n\n return {\n ...settings,\n menuLogo,\n authLogo,\n };\n};\n\nexport const restoreProjectSettingsRow = async (strapi: Core.Strapi, row: CoreStoreRow) => {\n if (!isProjectSettingsRow(row)) {\n return row;\n }\n\n return {\n ...row,\n value: await restoreProjectSettingsLogos(strapi, row.value as ProjectSettingsStoreValue),\n };\n};\n"],"names":["PROJECT_SETTINGS_CORE_STORE_KEY","LOGO_PERSISTED_FIELDS","isProjectSettingsRow","row","key","getConfiguredUploadProvider","strapi","config","get","provider","isLocalProviderLogo","logo","getLogoMimeType","fromExt","ext","lookupMimeType","fromName","name","undefined","getRemoteLogoUrl","plugins","upload","providerName","isPrivate","getSignedUrl","url","logoLabel","hash","readLocalLogoBuffer","filepath","join","dirs","static","public","buffer","readFile","toString","error","code","log","warn","readRemoteLogoBuffer","response","fetch","status","body","chunks","chunk","Readable","fromWeb","push","Buffer","concat","readLogoTransferBuffer","enrichLogoForExport","transferBuffer","__transferBuffer","enrichProjectSettingsForExport","settings","value","menuLogo","authLogo","Promise","all","uploadLogoFromTransferBuffer","logoWithoutBuffer","mime","file","stream","from","plugin","uploadStream","pick","restoreProjectSettingsLogos","restoreProjectSettingsRow"],"mappings":";;;;;;AAQO,MAAMA,kCAAkC;AA8B/C;AACA;AACA,MAAMC,qBAAAA,GAAwB;AAC5B,IAAA,MAAA;AACA,IAAA,MAAA;AACA,IAAA,KAAA;AACA,IAAA,OAAA;AACA,IAAA,QAAA;AACA,IAAA,KAAA;AACA,IAAA,MAAA;AACA,IAAA;AACD,CAAA;AAED,MAAMC,oBAAAA,GAAuB,CAACC,GAAAA,GAAsBA,GAAAA,CAAIC,GAAG,KAAKJ,+BAAAA;AAEhE,MAAMK,2BAAAA,GAA8B,CAACC,MAAAA,GAClCA,MAAAA,CAAOC,MAAM,CAACC,GAAG,CAAC,gBAAA,CAAA,EAAyDC,QAAAA;AAE9E;AACA,MAAMC,mBAAAA,GAAsB,CAACC,IAAAA,GAC3B,CAACA,KAAKF,QAAQ,IAAIE,IAAAA,CAAKF,QAAQ,KAAK,OAAA;AAEtC;AACA;AACA;AACA;AACA,MAAMG,kBAAkB,CAACD,IAAAA,GAAAA;AACvB,IAAA,MAAME,UAAUF,IAAAA,CAAKG,GAAG,GAAGC,MAAAA,CAAeJ,IAAAA,CAAKG,GAAG,CAAA,GAAI,KAAA;AACtD,IAAA,IAAID,OAAAA,EAAS;QACX,OAAOA,OAAAA;AACT,IAAA;AAEA,IAAA,MAAMG,WAAWL,IAAAA,CAAKM,IAAI,GAAGF,MAAAA,CAAeJ,IAAAA,CAAKM,IAAI,CAAA,GAAI,KAAA;AACzD,IAAA,IAAID,QAAAA,EAAU;QACZ,OAAOA,QAAAA;AACT,IAAA;IAEA,OAAOE,SAAAA;AACT,CAAA;AAEA;;;;;;IAOA,MAAMC,gBAAAA,GAAmB,OAAOb,MAAAA,EAAqBK,IAAAA,GAAAA;AACnD,IAAA,MAAM,EAAEF,QAAQ,EAAE,GAAGH,MAAAA,CAAOc,OAAO,CAACC,MAAM;AAC1C,IAAA,MAAMC,e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;;;"}
|
|
1
|
+
{"version":3,"file":"project-settings-logos.mjs","sources":["../../../src/strapi/utils/project-settings-logos.ts"],"sourcesContent":["import { join } from 'path';\nimport { Readable } from 'stream';\nimport { pick } from 'lodash';\nimport { readFile } from 'fs-extra';\nimport { lookup as lookupMimeType } from 'mime-types';\nimport * as webStream from 'stream/web';\nimport type { Core } from '@strapi/types';\n\nexport const PROJECT_SETTINGS_CORE_STORE_KEY = 'core_admin_project-settings';\n\nexport const PROJECT_SETTINGS_LOGO_FIELDS = ['menuLogo', 'authLogo'] as const;\n\nexport type ProjectSettingsLogoField = (typeof PROJECT_SETTINGS_LOGO_FIELDS)[number];\n\nexport type ProjectSettingsLogo = {\n name?: string;\n hash?: string;\n url?: string;\n width?: number;\n height?: number;\n ext?: string;\n size?: number;\n mime?: string;\n provider?: string;\n __transferBuffer?: string;\n};\n\nexport type ProjectSettingsStoreValue = {\n menuLogo?: ProjectSettingsLogo | null;\n authLogo?: ProjectSettingsLogo | null;\n};\n\nexport type CoreStoreRow = {\n key: string;\n value: unknown;\n [key: string]: unknown;\n};\n\n// The shape persisted back to core-store, matching what the admin project-settings\n// service stores (so the admin UI keeps behaving identically after a transfer).\nconst LOGO_PERSISTED_FIELDS = [\n 'name',\n 'hash',\n 'url',\n 'width',\n 'height',\n 'ext',\n 'size',\n 'provider',\n] as const;\n\nconst isProjectSettingsRow = (row: CoreStoreRow) => row.key === PROJECT_SETTINGS_CORE_STORE_KEY;\n\nconst getConfiguredUploadProvider = (strapi: Core.Strapi) =>\n (strapi.config.get('plugin::upload') as { provider?: string } | undefined)?.provider;\n\n// Admin logos with no provider were uploaded with the local provider (the default).\nconst isLocalProviderLogo = (logo: ProjectSettingsLogo) =>\n !logo.provider || logo.provider === 'local';\n\n// Best-effort mime type for a logo so that remote providers (S3, Cloudinary, …)\n// store the correct Content-Type and the image renders instead of downloading.\n// The admin does not persist the mime type, so it is reconstructed from the\n// file extension (falling back to the file name).\nconst getLogoMimeType = (logo: ProjectSettingsLogo): string | undefined => {\n const fromExt = logo.ext ? lookupMimeType(logo.ext) : false;\n if (fromExt) {\n return fromExt;\n }\n\n const fromName = logo.name ? lookupMimeType(logo.name) : false;\n if (fromName) {\n return fromName;\n }\n\n return undefined;\n};\n\n/**\n * Resolve the URL to read a non-local logo from during export.\n *\n * Mirrors the media-library asset export: when the file lives on the\n * currently-configured provider and that provider serves private files,\n * a signed URL is generated so the bytes can be fetched.\n */\nconst getRemoteLogoUrl = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n const { provider } = strapi.plugins.upload;\n const providerName = getConfiguredUploadProvider(strapi);\n\n if (\n logo.provider === providerName &&\n typeof provider?.isPrivate === 'function' &&\n typeof provider?.getSignedUrl === 'function' &&\n (await provider.isPrivate())\n ) {\n const { url } = await provider.getSignedUrl(logo);\n return url;\n }\n\n return logo.url;\n};\n\nconst logoLabel = (logo: ProjectSettingsLogo) => logo.name ?? logo.hash ?? 'unknown';\n\nconst readLocalLogoBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n const filepath = join(strapi.dirs.static.public, logo.url as string);\n\n try {\n const buffer = await readFile(filepath);\n return buffer.toString('base64');\n } catch (error) {\n const code =\n error && typeof error === 'object' && 'code' in error\n ? (error as NodeJS.ErrnoException).code\n : undefined;\n\n if (code === 'ENOENT') {\n strapi.log.warn(\n `[Data transfer] Admin logo \"${logoLabel(logo)}\" exists in project settings but no corresponding file was found to transfer. Path: ${filepath}`\n );\n return undefined;\n }\n\n throw error;\n }\n};\n\nconst readRemoteLogoBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n const url = await getRemoteLogoUrl(strapi, logo);\n const response = await strapi.fetch(url);\n\n if (response.status !== 200 || !response.body) {\n strapi.log.warn(\n `[Data transfer] Admin logo \"${logoLabel(logo)}\" exists in project settings but could not be fetched for transfer. URL: ${url} (status: ${response.status})`\n );\n return undefined;\n }\n\n const chunks: Uint8Array[] = [];\n\n for await (const chunk of Readable.fromWeb(\n response.body as webStream.ReadableStream<Uint8Array>\n )) {\n chunks.push(chunk);\n }\n\n return Buffer.concat(chunks).toString('base64');\n};\n\nconst readLogoTransferBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n if (!logo.url) {\n return undefined;\n }\n\n if (isLocalProviderLogo(logo)) {\n return readLocalLogoBuffer(strapi, logo);\n }\n\n return readRemoteLogoBuffer(strapi, logo);\n};\n\nconst enrichLogoForExport = async (\n strapi: Core.Strapi,\n logo: ProjectSettingsLogo | null | undefined\n) => {\n if (!logo?.url) {\n return logo;\n }\n\n const transferBuffer = await readLogoTransferBuffer(strapi, logo);\n\n if (!transferBuffer) {\n return logo;\n }\n\n return {\n ...logo,\n __transferBuffer: transferBuffer,\n };\n};\n\nexport const enrichProjectSettingsForExport = async (\n strapi: Core.Strapi,\n row: CoreStoreRow\n): Promise<CoreStoreRow> => {\n if (!isProjectSettingsRow(row)) {\n return row;\n }\n\n const settings = row.value as ProjectSettingsStoreValue;\n\n const [menuLogo, authLogo] = await Promise.all([\n enrichLogoForExport(strapi, settings.menuLogo),\n enrichLogoForExport(strapi, settings.authLogo),\n ]);\n\n return {\n ...row,\n value: {\n ...settings,\n menuLogo,\n authLogo,\n },\n };\n};\n\n/**\n * Re-upload a transferred logo to the destination's configured upload provider.\n *\n * The file is always re-uploaded through the destination provider, so the\n * persisted `url` and `provider` reflect the destination (matching how the\n * media-library asset restore behaves). A best-effort mime type is supplied so\n * remote providers serve the logo with the correct Content-Type.\n */\nconst uploadLogoFromTransferBuffer = async (strapi: Core.Strapi, logo: ProjectSettingsLogo) => {\n if (!logo.__transferBuffer) {\n return logo;\n }\n\n const { __transferBuffer: transferBuffer, ...logoWithoutBuffer } = logo;\n const provider = getConfiguredUploadProvider(strapi);\n const mime = getLogoMimeType(logoWithoutBuffer);\n\n const file = {\n ...logoWithoutBuffer,\n ...(mime ? { mime } : {}),\n stream: Readable.from(Buffer.from(transferBuffer, 'base64')),\n provider,\n };\n\n await strapi.plugin('upload').provider.uploadStream(file);\n\n return pick(file, LOGO_PERSISTED_FIELDS);\n};\n\nexport const restoreProjectSettingsLogos = async (\n strapi: Core.Strapi,\n settings: ProjectSettingsStoreValue\n): Promise<ProjectSettingsStoreValue> => {\n const [menuLogo, authLogo] = await Promise.all([\n settings.menuLogo ? uploadLogoFromTransferBuffer(strapi, settings.menuLogo) : settings.menuLogo,\n settings.authLogo ? uploadLogoFromTransferBuffer(strapi, settings.authLogo) : settings.authLogo,\n ]);\n\n return {\n ...settings,\n menuLogo,\n authLogo,\n };\n};\n\nexport const restoreProjectSettingsRow = async (strapi: Core.Strapi, row: CoreStoreRow) => {\n if (!isProjectSettingsRow(row)) {\n return row;\n }\n\n return {\n ...row,\n value: await restoreProjectSettingsLogos(strapi, row.value as ProjectSettingsStoreValue),\n };\n};\n"],"names":["PROJECT_SETTINGS_CORE_STORE_KEY","LOGO_PERSISTED_FIELDS","isProjectSettingsRow","row","key","getConfiguredUploadProvider","strapi","config","get","provider","isLocalProviderLogo","logo","getLogoMimeType","fromExt","ext","lookupMimeType","fromName","name","undefined","getRemoteLogoUrl","plugins","upload","providerName","isPrivate","getSignedUrl","url","logoLabel","hash","readLocalLogoBuffer","filepath","join","dirs","static","public","buffer","readFile","toString","error","code","log","warn","readRemoteLogoBuffer","response","fetch","status","body","chunks","chunk","Readable","fromWeb","push","Buffer","concat","readLogoTransferBuffer","enrichLogoForExport","transferBuffer","__transferBuffer","enrichProjectSettingsForExport","settings","value","menuLogo","authLogo","Promise","all","uploadLogoFromTransferBuffer","logoWithoutBuffer","mime","file","stream","from","plugin","uploadStream","pick","restoreProjectSettingsLogos","restoreProjectSettingsRow"],"mappings":";;;;;;AAQO,MAAMA,kCAAkC;AA8B/C;AACA;AACA,MAAMC,qBAAAA,GAAwB;AAC5B,IAAA,MAAA;AACA,IAAA,MAAA;AACA,IAAA,KAAA;AACA,IAAA,OAAA;AACA,IAAA,QAAA;AACA,IAAA,KAAA;AACA,IAAA,MAAA;AACA,IAAA;AAC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;AACF,KAAA;AAEA,IAAA,MAAMH,OAAOgE,MAAM,CAAC,UAAU7D,QAAQ,CAAC8D,YAAY,CAACJ,IAAAA,CAAAA;AAEpD,IAAA,OAAOK,KAAKL,IAAAA,EAAMlE,qBAAAA,CAAAA;AACpB,CAAA;AAEO,MAAMwE,2BAAAA,GAA8B,OACzCnE,MAAAA,EACAoD,QAAAA,GAAAA;AAEA,IAAA,MAAM,CAACE,QAAAA,EAAUC,QAAAA,CAAS,GAAG,MAAMC,OAAAA,CAAQC,GAAG,CAAC;QAC7CL,QAAAA,CAASE,QAAQ,GAAGI,4BAAAA,CAA6B1D,MAAAA,EAAQoD,SAASE,QAAQ,CAAA,GAAIF,SAASE,QAAQ;QAC/FF,QAAAA,CAASG,QAAQ,GAAGG,4BAAAA,CAA6B1D,MAAAA,EAAQoD,SAASG,QAAQ,CAAA,GAAIH,SAASG;AACxF,KAAA,CAAA;IAED,OAAO;AACL,QAAA,GAAGH,QAAQ;AACXE,QAAAA,QAAAA;AACAC,QAAAA;AACF,KAAA;AACF;AAEO,MAAMa,yBAAAA,GAA4B,OAAOpE,MAAAA,EAAqBH,GAAAA,GAAAA;IACnE,IAAI,CAACD,qBAAqBC,GAAAA,CAAAA,EAAM;QAC9B,OAAOA,GAAAA;AACT,IAAA;IAEA,OAAO;AACL,QAAA,GAAGA,GAAG;AACNwD,QAAAA,KAAAA,EAAO,MAAMc,2BAAAA,CAA4BnE,MAAAA,EAAQH,GAAAA,CAAIwD,KAAK;AAC5D,KAAA;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"components.d.ts","sourceRoot":"","sources":["../../src/utils/components.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"components.d.ts","sourceRoot":"","sources":["../../src/utils/components.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,IAAI,EAAS,MAAM,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAE7E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,MAAM,CAAC;IACtB,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC;CACrB,KAAG,mBAAmB,EAkFtB,CAAC;AAEF;;;GAGG;AACH,QAAA,MAAM,mBAAmB,GAAI,uCAK1B;IACD,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC;IACpB,IAAI,EAAE,GAAG,CAAC;IACV,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC;CACjC,KAAG,GAAG,CAAC,MAAM,GAAG,SAiChB,CAAC;AAEF,OAAO,EACL,iBAAiB,EACjB,aAAa,EACb,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,0BAA0B,EAC1B,mBAAmB,GACpB,CAAC"}
|
package/dist/utils/components.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var _ = require('lodash');
|
|
4
|
-
var fp = require('lodash/fp');
|
|
5
4
|
var utils = require('@strapi/utils');
|
|
6
5
|
|
|
7
6
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
@@ -12,7 +11,7 @@ const isDialectMySQL = ()=>strapi.db?.dialect.client === 'mysql';
|
|
|
12
11
|
function omitComponentData(contentType, data) {
|
|
13
12
|
const { attributes } = contentType;
|
|
14
13
|
const componentAttributes = Object.keys(attributes).filter((attributeName)=>utils.contentTypes.isComponentAttribute(attributes[attributeName]));
|
|
15
|
-
return
|
|
14
|
+
return _.omit(data, componentAttributes);
|
|
16
15
|
}
|
|
17
16
|
// NOTE: we could generalize the logic to allow CRUD of relation directly in the DB layer
|
|
18
17
|
const createComponents = async (uid, data)=>{
|
|
@@ -21,7 +20,7 @@ const createComponents = async (uid, data)=>{
|
|
|
21
20
|
const attributeNames = Object.keys(attributes);
|
|
22
21
|
for (const attributeName of attributeNames){
|
|
23
22
|
const attribute = attributes[attributeName];
|
|
24
|
-
if (!
|
|
23
|
+
if (!_.has(data, attributeName) || !utils.contentTypes.isComponentAttribute(attribute)) {
|
|
25
24
|
continue;
|
|
26
25
|
}
|
|
27
26
|
if (attribute.type === 'component') {
|
|
@@ -128,12 +127,13 @@ const deleteComponents = async (uid, entityToDelete, { loadComponents = true } =
|
|
|
128
127
|
const createComponent = async (uid, data)=>{
|
|
129
128
|
const model = strapi.getModel(uid);
|
|
130
129
|
const componentData = await createComponents(uid, data);
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
(payload)=>omitComponentData(model, payload), // ... and assign the newly created component instead
|
|
134
|
-
fp.assign(componentData));
|
|
130
|
+
// Remove predefined IDs and replace nested component data with the created components.
|
|
131
|
+
const dataWithoutComponents = omitComponentData(model, _.omit(data, 'id'));
|
|
135
132
|
return strapi.db.query(uid).create({
|
|
136
|
-
data:
|
|
133
|
+
data: {
|
|
134
|
+
...componentData,
|
|
135
|
+
...dataWithoutComponents
|
|
136
|
+
}
|
|
137
137
|
});
|
|
138
138
|
};
|
|
139
139
|
const deleteComponent = async (uid, componentToDelete)=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"components.js","sources":["../../src/utils/components.ts"],"sourcesContent":["import _ from 'lodash';\nimport { get, has, omit, pipe, assign } from 'lodash/fp';\n\nimport { contentTypes as contentTypesUtils, async, errors } from '@strapi/utils';\nimport type { Modules, UID, Data, Utils, Schema, Core } from '@strapi/types';\n\ntype LoadedComponents<TUID extends UID.Schema> = Data.Entity<\n TUID,\n Schema.AttributeNamesByType<TUID, 'component' | 'dynamiczone'>\n>;\n\ntype ComponentValue = Schema.Attribute.Value<\n Schema.Attribute.Component<UID.Component, false> | Schema.Attribute.Component<UID.Component, true>\n>;\n\ntype ComponentBody = {\n [key: string]: Schema.Attribute.Value<\n | Schema.Attribute.Component<UID.Component, false>\n | Schema.Attribute.Component<UID.Component, true>\n | Schema.Attribute.DynamicZone\n >;\n};\n\nconst isDialectMySQL = () => strapi.db?.dialect.client === 'mysql';\n\nfunction omitComponentData(\n contentType: Schema.ContentType,\n data: Modules.EntityService.Params.Data.Input<Schema.ContentType['uid']>\n): Partial<Modules.EntityService.Params.Data.Input<Schema.ContentType['uid']>>;\nfunction omitComponentData(\n contentType: Schema.Component,\n data: Modules.EntityService.Params.Data.Input<Schema.Component['uid']>\n): Partial<Modules.EntityService.Params.Data.Input<Schema.Component['uid']>>;\nfunction omitComponentData(\n contentType: Schema.ContentType | Schema.Component,\n data: Modules.EntityService.Params.Data.Input<Schema.ContentType['uid'] | Schema.Component['uid']>\n): Partial<\n Modules.EntityService.Params.Data.Input<Schema.ContentType['uid'] | Schema.Component['uid']>\n> {\n const { attributes } = contentType;\n const componentAttributes = Object.keys(attributes).filter((attributeName) =>\n contentTypesUtils.isComponentAttribute(attributes[attributeName])\n );\n\n return omit(componentAttributes, data);\n}\n\n// NOTE: we could generalize the logic to allow CRUD of relation directly in the DB layer\nconst createComponents = async <\n TUID extends UID.Schema,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n>(\n uid: TUID,\n data: TData\n) => {\n const { attributes = {} } = strapi.getModel(uid);\n\n const componentBody: ComponentBody = {};\n\n const attributeNames = Object.keys(attributes);\n\n for (const attributeName of attributeNames) {\n const attribute = attributes[attributeName];\n\n if (!has(attributeName, data) || !contentTypesUtils.isComponentAttribute(attribute)) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID, repeatable = false } = attribute;\n\n const componentValue = data[attributeName as keyof TData];\n\n if (componentValue === null) {\n continue;\n }\n\n if (repeatable === true) {\n if (!Array.isArray(componentValue)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n const components = (await async.map(\n componentValue,\n (value: any) => createComponent(componentUID, value),\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n )) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, true>>;\n\n componentBody[attributeName] = components.map(({ id }) => {\n return {\n id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n });\n } else {\n const component = await createComponent(\n componentUID,\n componentValue as Modules.EntityService.Params.Data.Input<UID.Component>\n );\n componentBody[attributeName] = {\n id: component.id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n }\n\n continue;\n }\n\n if (attribute.type === 'dynamiczone') {\n const dynamiczoneValues = data[\n attributeName as keyof TData\n ] as Modules.EntityService.Params.Attribute.GetValue<Schema.Attribute.DynamicZone>;\n\n if (!Array.isArray(dynamiczoneValues)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n const createDynamicZoneComponents = async (\n value: Utils.Array.Values<typeof dynamiczoneValues>\n ) => {\n const { id } = await createComponent(value.__component, value);\n return {\n id,\n __component: value.__component,\n __pivot: {\n field: attributeName,\n },\n };\n };\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n componentBody[attributeName] = await async.map(\n dynamiczoneValues,\n createDynamicZoneComponents,\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n );\n\n continue;\n }\n }\n\n return componentBody;\n};\n\nconst getComponents = async <TUID extends UID.Schema>(\n uid: TUID,\n entity: { id: Modules.EntityService.Params.Attribute.ID }\n): Promise<LoadedComponents<TUID>> => {\n const componentAttributes = contentTypesUtils.getComponentAttributes(strapi.getModel(uid));\n\n if (_.isEmpty(componentAttributes)) {\n return {} as LoadedComponents<TUID>;\n }\n\n return strapi.db.query(uid).load(entity, componentAttributes) as Promise<LoadedComponents<TUID>>;\n};\n\n/*\n delete old components\n create or update\n*/\nconst updateComponents = async <\n TUID extends UID.Schema,\n TData extends Partial<Modules.EntityService.Params.Data.Input<TUID>>,\n>(\n uid: TUID,\n entityToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n data: TData\n) => {\n const { attributes = {} } = strapi.getModel(uid);\n\n const componentBody: ComponentBody = {};\n\n for (const attributeName of Object.keys(attributes)) {\n const attribute = attributes[attributeName];\n\n if (!has(attributeName, data)) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID, repeatable = false } = attribute;\n\n const componentValue = data[\n attributeName as keyof TData\n ] as Schema.Attribute.Value<Schema.Attribute.Component>;\n\n await deleteOldComponents(uid, componentUID, entityToUpdate, attributeName, componentValue);\n\n if (repeatable === true) {\n if (!Array.isArray(componentValue)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n const components = (await async.map(\n componentValue,\n (value: any) => updateOrCreateComponent(componentUID, value),\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n )) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, true>>;\n\n componentBody[attributeName] = components.filter(_.negate(_.isNil)).map(({ id }) => {\n return {\n id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n });\n } else {\n const component = await updateOrCreateComponent(componentUID, componentValue);\n componentBody[attributeName] = component && {\n id: component.id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n }\n\n continue;\n }\n\n if (attribute.type === 'dynamiczone') {\n const dynamiczoneValues = data[\n attributeName as keyof TData\n ] as Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n await deleteOldDZComponents(uid, entityToUpdate, attributeName, dynamiczoneValues);\n\n if (!Array.isArray(dynamiczoneValues)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n componentBody[attributeName] = await async.map(\n dynamiczoneValues,\n async (value: any) => {\n const { id } = await updateOrCreateComponent(value.__component, value);\n\n return {\n id,\n __component: value.__component,\n __pivot: {\n field: attributeName,\n },\n };\n },\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n );\n\n continue;\n }\n }\n\n return componentBody;\n};\n\nconst pickStringifiedId = ({\n id,\n}: {\n id: Modules.EntityService.Params.Attribute.ID;\n}): Modules.EntityService.Params.Attribute.ID & string => {\n if (typeof id === 'string') {\n return id;\n }\n\n return `${id}`;\n};\n\nconst deleteOldComponents = async <TUID extends UID.Schema>(\n uid: TUID,\n componentUID: UID.Component,\n entityToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n attributeName: string,\n componentValue: Schema.Attribute.Value<Schema.Attribute.Component>\n) => {\n const previousValue = (await strapi.db\n .query(uid)\n .load(entityToUpdate, attributeName)) as ComponentValue;\n\n const idsToKeep = _.castArray(componentValue).filter(has('id')).map(pickStringifiedId);\n const allIds = _.castArray(previousValue).filter(has('id')).map(pickStringifiedId);\n\n idsToKeep.forEach((id) => {\n if (!allIds.includes(id)) {\n throw new errors.ApplicationError(\n `Some of the provided components in ${attributeName} are not related to the entity`\n );\n }\n });\n\n const idsToDelete = _.difference(allIds, idsToKeep);\n\n if (idsToDelete.length > 0) {\n for (const idToDelete of idsToDelete) {\n await deleteComponent(componentUID, { id: idToDelete });\n }\n }\n};\n\nconst deleteOldDZComponents = async <TUID extends UID.Schema>(\n uid: TUID,\n entityToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n attributeName: string,\n dynamiczoneValues: Schema.Attribute.Value<Schema.Attribute.DynamicZone>\n) => {\n const previousValue = (await strapi.db\n .query(uid)\n .load(entityToUpdate, attributeName)) as Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n const idsToKeep = _.castArray(dynamiczoneValues)\n .filter(has('id'))\n .map((v) => ({\n id: pickStringifiedId(v),\n __component: v.__component,\n }));\n\n const allIds = _.castArray(previousValue)\n .filter(has('id'))\n .map((v) => ({\n id: pickStringifiedId(v),\n __component: v.__component,\n }));\n\n idsToKeep.forEach(({ id, __component }) => {\n if (!allIds.find((el) => el.id === id && el.__component === __component)) {\n const err = new Error(\n `Some of the provided components in ${attributeName} are not related to the entity`\n );\n\n Object.assign(err, { status: 400 });\n throw err;\n }\n });\n\n type IdsToDelete = Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n const idsToDelete = allIds.reduce((acc, { id, __component: componentUID }) => {\n if (!idsToKeep.find((el) => el.id === id && el.__component === componentUID)) {\n acc.push({ id, __component: componentUID });\n }\n\n return acc;\n }, [] as IdsToDelete);\n\n if (idsToDelete.length > 0) {\n for (const idToDelete of idsToDelete) {\n const { id, __component: componentUID } = idToDelete;\n await deleteComponent(componentUID, { id });\n }\n }\n};\n\nconst deleteComponents = async <TUID extends UID.Schema, TEntity extends Data.Entity<TUID>>(\n uid: TUID,\n entityToDelete: TEntity,\n { loadComponents = true } = {}\n) => {\n const { attributes = {} } = strapi.getModel(uid);\n\n const attributeNames = Object.keys(attributes);\n\n for (const attributeName of attributeNames) {\n const attribute = attributes[attributeName];\n\n if (attribute.type === 'component' || attribute.type === 'dynamiczone') {\n let value;\n if (loadComponents) {\n value = await strapi.db.query(uid).load(entityToDelete, attributeName);\n } else {\n value = entityToDelete[attributeName as keyof TEntity];\n }\n\n if (!value) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID } = attribute;\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n await async.map(\n _.castArray(value),\n (subValue: any) => deleteComponent(componentUID, subValue),\n {\n concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity,\n }\n );\n } else {\n // delete dynamic zone components\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n await async.map(\n _.castArray(value),\n (subValue: any) => deleteComponent(subValue.__component, subValue),\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n );\n }\n\n continue;\n }\n }\n};\n\n/** *************************\n Component queries\n************************** */\n\n// components can have nested compos so this must be recursive\nconst createComponent = async <TUID extends UID.Component = UID.Component>(\n uid: TUID,\n data: Modules.EntityService.Params.Data.Input<TUID>\n) => {\n const model = strapi.getModel(uid) as Schema.Component;\n\n const componentData = await createComponents(uid, data);\n const transform = pipe(\n // Make sure we don't save the component with a pre-defined ID\n omit('id'),\n // Remove the component data from the original data object ...\n (payload) => omitComponentData(model, payload),\n // ... and assign the newly created component instead\n assign(componentData)\n );\n\n return strapi.db.query(uid).create({ data: transform(data) });\n};\n\n// components can have nested compos so this must be recursive\nconst updateComponent = async <TUID extends UID.Component>(\n uid: TUID,\n componentToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n data: Modules.EntityService.Params.Data.Input<TUID>\n) => {\n const model = strapi.getModel(uid) as Schema.Component;\n\n const componentData = await updateComponents(uid, componentToUpdate, data);\n\n return strapi.db.query(uid).update({\n where: {\n id: componentToUpdate.id,\n },\n data: Object.assign(omitComponentData(model, data), componentData),\n });\n};\n\nconst updateOrCreateComponent = <TUID extends UID.Component>(\n componentUID: TUID,\n value: Modules.EntityService.Params.Data.Input<TUID>\n) => {\n if (value === null) {\n return null;\n }\n\n // update\n if ('id' in value && typeof value.id !== 'undefined') {\n // TODO: verify the compo is associated with the entity\n return updateComponent(componentUID, { id: value.id }, value);\n }\n\n // create\n return createComponent(componentUID, value);\n};\n\nconst deleteComponent = async <TUID extends UID.Component>(\n uid: TUID,\n componentToDelete: Data.Component<TUID>\n) => {\n await deleteComponents(uid, componentToDelete);\n await strapi.db.query(uid).delete({ where: { id: componentToDelete.id } });\n};\n\ninterface IComponentIdMapping {\n uid: UID.Component;\n oldID: number;\n newID: number;\n}\n\n/**\n * Walk the source data and the newly created entity in parallel and collect\n * the [old ID, new ID] couple of every component instance found in both trees\n * (components & dynamic zones, including nested ones).\n *\n * Unlike a JSON diff, couples are also collected when the ID did not change,\n * so the result is an exhaustive map of every component instance that was\n * re-created with the entity.\n */\nconst collectComponentIdMappings = ({\n data,\n created,\n schema,\n strapi,\n}: {\n data: any;\n created: any;\n schema: Schema.Schema;\n strapi: Core.Strapi;\n}): IComponentIdMapping[] => {\n const mappings: IComponentIdMapping[] = [];\n\n const visitComponent = (uid: UID.Component, oldValue: any, newValue: any) => {\n if (!_.isObjectLike(oldValue) || !_.isObjectLike(newValue)) {\n return;\n }\n\n if (typeof oldValue.id === 'number' && typeof newValue.id === 'number') {\n mappings.push({ uid, oldID: oldValue.id, newID: newValue.id });\n }\n\n const componentSchema = strapi.getModel(uid);\n\n // Collect nested components & dynamic zones\n if (componentSchema) {\n visitSchema(componentSchema, oldValue, newValue);\n }\n };\n\n const visitSchema = (currentSchema: Schema.Schema, oldData: any, newData: any) => {\n if (!_.isObjectLike(oldData) || !_.isObjectLike(newData)) {\n return;\n }\n\n const { attributes = {} } = currentSchema;\n\n for (const [attributeName, attribute] of Object.entries(attributes)) {\n const oldValue = oldData[attributeName];\n const newValue = newData[attributeName];\n\n if (_.isNil(oldValue) || _.isNil(newValue)) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID, repeatable = false } = attribute;\n\n if (repeatable === true) {\n if (!Array.isArray(oldValue) || !Array.isArray(newValue)) {\n continue;\n }\n\n // Components are created (and thus populated back) in the same\n // order as the source data, pair them by index\n const length = Math.min(oldValue.length, newValue.length);\n\n for (let i = 0; i < length; i += 1) {\n visitComponent(componentUID, oldValue[i], newValue[i]);\n }\n } else {\n visitComponent(componentUID, oldValue, newValue);\n }\n }\n\n if (attribute.type === 'dynamiczone') {\n if (!Array.isArray(oldValue) || !Array.isArray(newValue)) {\n continue;\n }\n\n const length = Math.min(oldValue.length, newValue.length);\n\n for (let i = 0; i < length; i += 1) {\n const oldItem = oldValue[i];\n const newItem = newValue[i];\n const componentUID = oldItem?.__component;\n\n // Both items must reference the same dynamic zone component for the\n // ID couple to be meaningful\n if (!componentUID || (newItem?.__component && newItem.__component !== componentUID)) {\n continue;\n }\n\n visitComponent(componentUID, oldItem, newItem);\n }\n }\n }\n };\n\n visitSchema(schema, data, created);\n\n return mappings;\n};\n\n/**\n * Resolve the component UID of an entity's attribute based\n * on a given path (components & dynamic zones only)\n */\nconst resolveComponentUID = ({\n paths,\n strapi,\n data,\n contentType,\n}: {\n paths: string[];\n strapi: Core.Strapi;\n data: any;\n contentType: Schema.ContentType;\n}): UID.Schema | undefined => {\n let value: unknown = data;\n let cType:\n | Schema.ContentType\n | Schema.Component\n | ((...opts: any[]) => Schema.ContentType | Schema.Component) = contentType;\n for (const path of paths) {\n value = get(path, value);\n\n // Needed when the value of cType should be computed\n // based on the next value (eg: dynamic zones)\n if (typeof cType === 'function') {\n cType = cType(value);\n }\n\n if (path in cType.attributes) {\n const attribute: Schema.Attribute.AnyAttribute = cType.attributes[path];\n\n if (attribute.type === 'component') {\n cType = strapi.getModel(attribute.component);\n }\n\n if (attribute.type === 'dynamiczone') {\n cType = ({ __component }: { __component: UID.Component }) => strapi.getModel(__component);\n }\n }\n }\n\n if ('uid' in cType) {\n return cType.uid;\n }\n\n return undefined;\n};\n\nexport {\n omitComponentData,\n getComponents,\n createComponents,\n updateComponents,\n deleteComponents,\n deleteComponent,\n collectComponentIdMappings,\n resolveComponentUID,\n};\n"],"names":["isDialectMySQL","strapi","db","dialect","client","omitComponentData","contentType","data","attributes","componentAttributes","Object","keys","filter","attributeName","contentTypesUtils","isComponentAttribute","omit","createComponents","uid","getModel","componentBody","attributeNames","attribute","has","type","component","componentUID","repeatable","componentValue","Array","isArray","Error","components","async","map","value","createComponent","concurrency","inTransaction","Infinity","id","__pivot","field","component_type","dynamiczoneValues","createDynamicZoneComponents","__component","getComponents","entity","getComponentAttributes","_","isEmpty","query","load","deleteComponents","entityToDelete","loadComponents","castArray","subValue","deleteComponent","model","componentData","transform","pipe","payload","assign","create","componentToDelete","delete","where","collectComponentIdMappings","created","schema","mappings","visitComponent","oldValue","newValue","isObjectLike","push","oldID","newID","componentSchema","visitSchema","currentSchema","oldData","newData","entries","isNil","length","Math","min","i","oldItem","newItem"],"mappings":";;;;;;;;;;AAuBA,MAAMA,iBAAiB,IAAMC,MAAAA,CAAOC,EAAE,EAAEC,QAAQC,MAAAA,KAAW,OAAA;AAU3D,SAASC,iBAAAA,CACPC,WAAkD,EAClDC,IAAkG,EAAA;IAIlG,MAAM,EAAEC,UAAU,EAAE,GAAGF,WAAAA;AACvB,IAAA,MAAMG,mBAAAA,GAAsBC,MAAAA,CAAOC,IAAI,CAACH,YAAYI,MAAM,CAAC,CAACC,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AAYV,QAAQjE,IAAAA,EAAMgE,OAAAA,CAAAA;IAE1B,OAAOE,QAAAA;AACT;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"components.js","sources":["../../src/utils/components.ts"],"sourcesContent":["import _, { get, has, omit } from 'lodash';\n\nimport { contentTypes as contentTypesUtils, async, errors } from '@strapi/utils';\nimport type { Modules, UID, Data, Utils, Schema, Core } from '@strapi/types';\n\ntype LoadedComponents<TUID extends UID.Schema> = Data.Entity<\n TUID,\n Schema.AttributeNamesByType<TUID, 'component' | 'dynamiczone'>\n>;\n\ntype ComponentValue = Schema.Attribute.Value<\n Schema.Attribute.Component<UID.Component, false> | Schema.Attribute.Component<UID.Component, true>\n>;\n\ntype ComponentBody = {\n [key: string]: Schema.Attribute.Value<\n | Schema.Attribute.Component<UID.Component, false>\n | Schema.Attribute.Component<UID.Component, true>\n | Schema.Attribute.DynamicZone\n >;\n};\n\nconst isDialectMySQL = () => strapi.db?.dialect.client === 'mysql';\n\nfunction omitComponentData(\n contentType: Schema.ContentType,\n data: Modules.EntityService.Params.Data.Input<Schema.ContentType['uid']>\n): Partial<Modules.EntityService.Params.Data.Input<Schema.ContentType['uid']>>;\nfunction omitComponentData(\n contentType: Schema.Component,\n data: Modules.EntityService.Params.Data.Input<Schema.Component['uid']>\n): Partial<Modules.EntityService.Params.Data.Input<Schema.Component['uid']>>;\nfunction omitComponentData(\n contentType: Schema.ContentType | Schema.Component,\n data: Modules.EntityService.Params.Data.Input<Schema.ContentType['uid'] | Schema.Component['uid']>\n): Partial<\n Modules.EntityService.Params.Data.Input<Schema.ContentType['uid'] | Schema.Component['uid']>\n> {\n const { attributes } = contentType;\n const componentAttributes = Object.keys(attributes).filter((attributeName) =>\n contentTypesUtils.isComponentAttribute(attributes[attributeName])\n );\n\n return omit(data, componentAttributes);\n}\n\n// NOTE: we could generalize the logic to allow CRUD of relation directly in the DB layer\nconst createComponents = async <\n TUID extends UID.Schema,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n>(\n uid: TUID,\n data: TData\n) => {\n const { attributes = {} } = strapi.getModel(uid);\n\n const componentBody: ComponentBody = {};\n\n const attributeNames = Object.keys(attributes);\n\n for (const attributeName of attributeNames) {\n const attribute = attributes[attributeName];\n\n if (!has(data, attributeName) || !contentTypesUtils.isComponentAttribute(attribute)) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID, repeatable = false } = attribute;\n\n const componentValue = data[attributeName as keyof TData];\n\n if (componentValue === null) {\n continue;\n }\n\n if (repeatable === true) {\n if (!Array.isArray(componentValue)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n const components = (await async.map(\n componentValue,\n (value: any) => createComponent(componentUID, value),\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n )) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, true>>;\n\n componentBody[attributeName] = components.map(({ id }) => {\n return {\n id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n });\n } else {\n const component = await createComponent(\n componentUID,\n componentValue as Modules.EntityService.Params.Data.Input<UID.Component>\n );\n componentBody[attributeName] = {\n id: component.id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n }\n\n continue;\n }\n\n if (attribute.type === 'dynamiczone') {\n const dynamiczoneValues = data[\n attributeName as keyof TData\n ] as Modules.EntityService.Params.Attribute.GetValue<Schema.Attribute.DynamicZone>;\n\n if (!Array.isArray(dynamiczoneValues)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n const createDynamicZoneComponents = async (\n value: Utils.Array.Values<typeof dynamiczoneValues>\n ) => {\n const { id } = await createComponent(value.__component, value);\n return {\n id,\n __component: value.__component,\n __pivot: {\n field: attributeName,\n },\n };\n };\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n componentBody[attributeName] = await async.map(\n dynamiczoneValues,\n createDynamicZoneComponents,\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n );\n\n continue;\n }\n }\n\n return componentBody;\n};\n\nconst getComponents = async <TUID extends UID.Schema>(\n uid: TUID,\n entity: { id: Modules.EntityService.Params.Attribute.ID }\n): Promise<LoadedComponents<TUID>> => {\n const componentAttributes = contentTypesUtils.getComponentAttributes(strapi.getModel(uid));\n\n if (_.isEmpty(componentAttributes)) {\n return {} as LoadedComponents<TUID>;\n }\n\n return strapi.db.query(uid).load(entity, componentAttributes) as Promise<LoadedComponents<TUID>>;\n};\n\n/*\n delete old components\n create or update\n*/\nconst updateComponents = async <\n TUID extends UID.Schema,\n TData extends Partial<Modules.EntityService.Params.Data.Input<TUID>>,\n>(\n uid: TUID,\n entityToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n data: TData\n) => {\n const { attributes = {} } = strapi.getModel(uid);\n\n const componentBody: ComponentBody = {};\n\n for (const attributeName of Object.keys(attributes)) {\n const attribute = attributes[attributeName];\n\n if (!has(data, attributeName)) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID, repeatable = false } = attribute;\n\n const componentValue = data[\n attributeName as keyof TData\n ] as Schema.Attribute.Value<Schema.Attribute.Component>;\n\n await deleteOldComponents(uid, componentUID, entityToUpdate, attributeName, componentValue);\n\n if (repeatable === true) {\n if (!Array.isArray(componentValue)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n const components = (await async.map(\n componentValue,\n (value: any) => updateOrCreateComponent(componentUID, value),\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n )) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, true>>;\n\n componentBody[attributeName] = components.filter(_.negate(_.isNil)).map(({ id }) => {\n return {\n id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n });\n } else {\n const component = await updateOrCreateComponent(componentUID, componentValue);\n componentBody[attributeName] = component && {\n id: component.id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n }\n\n continue;\n }\n\n if (attribute.type === 'dynamiczone') {\n const dynamiczoneValues = data[\n attributeName as keyof TData\n ] as Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n await deleteOldDZComponents(uid, entityToUpdate, attributeName, dynamiczoneValues);\n\n if (!Array.isArray(dynamiczoneValues)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n componentBody[attributeName] = await async.map(\n dynamiczoneValues,\n async (value: any) => {\n const { id } = await updateOrCreateComponent(value.__component, value);\n\n return {\n id,\n __component: value.__component,\n __pivot: {\n field: attributeName,\n },\n };\n },\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n );\n\n continue;\n }\n }\n\n return componentBody;\n};\n\nconst pickStringifiedId = ({\n id,\n}: {\n id: Modules.EntityService.Params.Attribute.ID;\n}): Modules.EntityService.Params.Attribute.ID & string => {\n if (typeof id === 'string') {\n return id;\n }\n\n return `${id}`;\n};\n\nconst deleteOldComponents = async <TUID extends UID.Schema>(\n uid: TUID,\n componentUID: UID.Component,\n entityToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n attributeName: string,\n componentValue: Schema.Attribute.Value<Schema.Attribute.Component>\n) => {\n const previousValue = (await strapi.db\n .query(uid)\n .load(entityToUpdate, attributeName)) as ComponentValue;\n\n const idsToKeep = _.castArray(componentValue)\n .filter((component) => has(component, 'id'))\n .map(pickStringifiedId);\n const allIds = _.castArray(previousValue)\n .filter((component) => has(component, 'id'))\n .map(pickStringifiedId);\n\n idsToKeep.forEach((id) => {\n if (!allIds.includes(id)) {\n throw new errors.ApplicationError(\n `Some of the provided components in ${attributeName} are not related to the entity`\n );\n }\n });\n\n const idsToDelete = _.difference(allIds, idsToKeep);\n\n if (idsToDelete.length > 0) {\n for (const idToDelete of idsToDelete) {\n await deleteComponent(componentUID, { id: idToDelete });\n }\n }\n};\n\nconst deleteOldDZComponents = async <TUID extends UID.Schema>(\n uid: TUID,\n entityToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n attributeName: string,\n dynamiczoneValues: Schema.Attribute.Value<Schema.Attribute.DynamicZone>\n) => {\n const previousValue = (await strapi.db\n .query(uid)\n .load(entityToUpdate, attributeName)) as Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n const idsToKeep = _.castArray(dynamiczoneValues)\n .filter((component) => has(component, 'id'))\n .map((v) => ({\n id: pickStringifiedId(v),\n __component: v.__component,\n }));\n\n const allIds = _.castArray(previousValue)\n .filter((component) => has(component, 'id'))\n .map((v) => ({\n id: pickStringifiedId(v),\n __component: v.__component,\n }));\n\n idsToKeep.forEach(({ id, __component }) => {\n if (!allIds.find((el) => el.id === id && el.__component === __component)) {\n const err = new Error(\n `Some of the provided components in ${attributeName} are not related to the entity`\n );\n\n Object.assign(err, { status: 400 });\n throw err;\n }\n });\n\n type IdsToDelete = Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n const idsToDelete = allIds.reduce((acc, { id, __component: componentUID }) => {\n if (!idsToKeep.find((el) => el.id === id && el.__component === componentUID)) {\n acc.push({ id, __component: componentUID });\n }\n\n return acc;\n }, [] as IdsToDelete);\n\n if (idsToDelete.length > 0) {\n for (const idToDelete of idsToDelete) {\n const { id, __component: componentUID } = idToDelete;\n await deleteComponent(componentUID, { id });\n }\n }\n};\n\nconst deleteComponents = async <TUID extends UID.Schema, TEntity extends Data.Entity<TUID>>(\n uid: TUID,\n entityToDelete: TEntity,\n { loadComponents = true } = {}\n) => {\n const { attributes = {} } = strapi.getModel(uid);\n\n const attributeNames = Object.keys(attributes);\n\n for (const attributeName of attributeNames) {\n const attribute = attributes[attributeName];\n\n if (attribute.type === 'component' || attribute.type === 'dynamiczone') {\n let value;\n if (loadComponents) {\n value = await strapi.db.query(uid).load(entityToDelete, attributeName);\n } else {\n value = entityToDelete[attributeName as keyof TEntity];\n }\n\n if (!value) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID } = attribute;\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n await async.map(\n _.castArray(value),\n (subValue: any) => deleteComponent(componentUID, subValue),\n {\n concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity,\n }\n );\n } else {\n // delete dynamic zone components\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n await async.map(\n _.castArray(value),\n (subValue: any) => deleteComponent(subValue.__component, subValue),\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n );\n }\n\n continue;\n }\n }\n};\n\n/** *************************\n Component queries\n************************** */\n\n// components can have nested compos so this must be recursive\nconst createComponent = async <TUID extends UID.Component = UID.Component>(\n uid: TUID,\n data: Modules.EntityService.Params.Data.Input<TUID>\n) => {\n const model = strapi.getModel(uid) as Schema.Component;\n\n const componentData = await createComponents(uid, data);\n // Remove predefined IDs and replace nested component data with the created components.\n const dataWithoutComponents = omitComponentData(model, omit(data, 'id'));\n\n return strapi.db.query(uid).create({\n data: { ...componentData, ...dataWithoutComponents },\n });\n};\n\n// components can have nested compos so this must be recursive\nconst updateComponent = async <TUID extends UID.Component>(\n uid: TUID,\n componentToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n data: Modules.EntityService.Params.Data.Input<TUID>\n) => {\n const model = strapi.getModel(uid) as Schema.Component;\n\n const componentData = await updateComponents(uid, componentToUpdate, data);\n\n return strapi.db.query(uid).update({\n where: {\n id: componentToUpdate.id,\n },\n data: Object.assign(omitComponentData(model, data), componentData),\n });\n};\n\nconst updateOrCreateComponent = <TUID extends UID.Component>(\n componentUID: TUID,\n value: Modules.EntityService.Params.Data.Input<TUID>\n) => {\n if (value === null) {\n return null;\n }\n\n // update\n if ('id' in value && typeof value.id !== 'undefined') {\n // TODO: verify the compo is associated with the entity\n return updateComponent(componentUID, { id: value.id }, value);\n }\n\n // create\n return createComponent(componentUID, value);\n};\n\nconst deleteComponent = async <TUID extends UID.Component>(\n uid: TUID,\n componentToDelete: Data.Component<TUID>\n) => {\n await deleteComponents(uid, componentToDelete);\n await strapi.db.query(uid).delete({ where: { id: componentToDelete.id } });\n};\n\ninterface IComponentIdMapping {\n uid: UID.Component;\n oldID: number;\n newID: number;\n}\n\n/**\n * Walk the source data and the newly created entity in parallel and collect\n * the [old ID, new ID] couple of every component instance found in both trees\n * (components & dynamic zones, including nested ones).\n *\n * Unlike a JSON diff, couples are also collected when the ID did not change,\n * so the result is an exhaustive map of every component instance that was\n * re-created with the entity.\n */\nconst collectComponentIdMappings = ({\n data,\n created,\n schema,\n strapi,\n}: {\n data: any;\n created: any;\n schema: Schema.Schema;\n strapi: Core.Strapi;\n}): IComponentIdMapping[] => {\n const mappings: IComponentIdMapping[] = [];\n\n const visitComponent = (uid: UID.Component, oldValue: any, newValue: any) => {\n if (!_.isObjectLike(oldValue) || !_.isObjectLike(newValue)) {\n return;\n }\n\n if (typeof oldValue.id === 'number' && typeof newValue.id === 'number') {\n mappings.push({ uid, oldID: oldValue.id, newID: newValue.id });\n }\n\n const componentSchema = strapi.getModel(uid);\n\n // Collect nested components & dynamic zones\n if (componentSchema) {\n visitSchema(componentSchema, oldValue, newValue);\n }\n };\n\n const visitSchema = (currentSchema: Schema.Schema, oldData: any, newData: any) => {\n if (!_.isObjectLike(oldData) || !_.isObjectLike(newData)) {\n return;\n }\n\n const { attributes = {} } = currentSchema;\n\n for (const [attributeName, attribute] of Object.entries(attributes)) {\n const oldValue = oldData[attributeName];\n const newValue = newData[attributeName];\n\n if (_.isNil(oldValue) || _.isNil(newValue)) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID, repeatable = false } = attribute;\n\n if (repeatable === true) {\n if (!Array.isArray(oldValue) || !Array.isArray(newValue)) {\n continue;\n }\n\n // Components are created (and thus populated back) in the same\n // order as the source data, pair them by index\n const length = Math.min(oldValue.length, newValue.length);\n\n for (let i = 0; i < length; i += 1) {\n visitComponent(componentUID, oldValue[i], newValue[i]);\n }\n } else {\n visitComponent(componentUID, oldValue, newValue);\n }\n }\n\n if (attribute.type === 'dynamiczone') {\n if (!Array.isArray(oldValue) || !Array.isArray(newValue)) {\n continue;\n }\n\n const length = Math.min(oldValue.length, newValue.length);\n\n for (let i = 0; i < length; i += 1) {\n const oldItem = oldValue[i];\n const newItem = newValue[i];\n const componentUID = oldItem?.__component;\n\n // Both items must reference the same dynamic zone component for the\n // ID couple to be meaningful\n if (!componentUID || (newItem?.__component && newItem.__component !== componentUID)) {\n continue;\n }\n\n visitComponent(componentUID, oldItem, newItem);\n }\n }\n }\n };\n\n visitSchema(schema, data, created);\n\n return mappings;\n};\n\n/**\n * Resolve the component UID of an entity's attribute based\n * on a given path (components & dynamic zones only)\n */\nconst resolveComponentUID = ({\n paths,\n strapi,\n data,\n contentType,\n}: {\n paths: string[];\n strapi: Core.Strapi;\n data: any;\n contentType: Schema.ContentType;\n}): UID.Schema | undefined => {\n let value: unknown = data;\n let cType:\n | Schema.ContentType\n | Schema.Component\n | ((...opts: any[]) => Schema.ContentType | Schema.Component) = contentType;\n for (const path of paths) {\n value = get(value, path);\n\n // Needed when the value of cType should be computed\n // based on the next value (eg: dynamic zones)\n if (typeof cType === 'function') {\n cType = cType(value);\n }\n\n if (path in cType.attributes) {\n const attribute: Schema.Attribute.AnyAttribute = cType.attributes[path];\n\n if (attribute.type === 'component') {\n cType = strapi.getModel(attribute.component);\n }\n\n if (attribute.type === 'dynamiczone') {\n cType = ({ __component }: { __component: UID.Component }) => strapi.getModel(__component);\n }\n }\n }\n\n if ('uid' in cType) {\n return cType.uid;\n }\n\n return undefined;\n};\n\nexport {\n omitComponentData,\n getComponents,\n createComponents,\n updateComponents,\n deleteComponents,\n deleteComponent,\n collectComponentIdMappings,\n resolveComponentUID,\n};\n"],"names":["isDialectMySQL","strapi","db","dialect","client","omitComponentData","contentType","data","attributes","componentAttributes","Object","keys","filter","attributeName","contentTypesUtils","isComponentAttribute","omit","createComponents","uid","getModel","componentBody","attributeNames","attribute","has","type","component","componentUID","repeatable","componentValue","Array","isArray","Error","components","async","map","value","createComponent","concurrency","inTransaction","Infinity","id","__pivot","field","component_type","dynamiczoneValues","createDynamicZoneComponents","__component","getComponents","entity","getComponentAttributes","_","isEmpty","query","load","deleteComponents","entityToDelete","loadComponents","castArray","subValue","deleteComponent","model","componentData","dataWithoutComponents","create","componentToDelete","delete","where","collectComponentIdMappings","created","schema","mappings","visitComponent","oldValue","newValue","isObjectLike","push","oldID","newID","componentSchema","visitSchema","currentSchema","oldData","newData","entries","isNil","length","Math","min","i","oldItem","newItem"],"mappings":";;;;;;;;;AAsBA,MAAMA,iBAAiB,IAAMC,MAAAA,CAAOC,EAAE,EAAEC,QAAQC,MAAAA,KAAW,OAAA;AAU3D,SAASC,iBAAAA,CACPC,WAAkD,EAClDC,IAAkG,EAAA;IAIlG,MAAM,EAAEC,UAAU,EAAE,GAAGF,WAAAA;AACvB,IAAA,MAAMG,mBAAAA,GAAsBC,MAAAA,CAAOC,IAAI,CAACH,YAAYI,MAAM,CAAC,CAACC,aAAAA,GAC1DC,kBAAAA,CAAkBC,oBAAoB,CAACP,UAAU,CAACK,aAAAA,CAAc,CAAA,CAAA;AAGlE,IAAA,OAAOG,OAAKT,IAAAA,EAAME,mBAAAA,CAAAA;AACpB;AAEA;AACA,MAAMQ,gBAAAA,GAAmB,OAIvBC,GAAAA,EACAX,IAAAA,GAAAA;IAEA,MAAM,EAAEC,aAAa,EAAE,EAAE,GAAGP,MAAAA,CAAOkB,QAAQ,CAACD,GAAAA,CAAAA;AAE5C,IAAA,MAAME,gBAA+B,EAAC;IAEtC,MAAMC,cAAAA,GAAiBX,MAAAA,CAAOC,IAAI,CAACH,UAAAA,CAAAA;IAEnC,KAAK,MAAMK,iBAAiBQ,cAAAA,CAAgB;QAC1C,MAAMC,SAAAA,GAAYd,UAAU,CAACK,aAAAA,CAAc;QAE3C,IAAI,CAACU,MAAIhB,IAAAA,EAAMM,aAAAA,CAAAA,IAAkB,CAACC,kBAAAA,CAAkBC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AACf,SAASa,MAAM,EAAEZ,SAASY,MAAM,CAAA;AAExD,gBAAA,IAAK,IAAIG,CAAAA,GAAI,CAAA,EAAGA,CAAAA,GAAIH,MAAAA,EAAQG,KAAK,CAAA,CAAG;oBAClC,MAAMC,OAAAA,GAAUjB,QAAQ,CAACgB,CAAAA,CAAE;oBAC3B,MAAME,OAAAA,GAAUjB,QAAQ,CAACe,CAAAA,CAAE;AAC3B,oBAAA,MAAM9D,eAAe+D,OAAAA,EAAS3C,WAAAA;;;AAI9B,oBAAA,IAAI,CAACpB,YAAAA,IAAiBgE,OAAAA,EAAS5C,eAAe4C,OAAAA,CAAQ5C,WAAW,KAAKpB,YAAAA,EAAe;AACnF,wBAAA;AACF,oBAAA;AAEA6C,oBAAAA,cAAAA,CAAe7C,cAAc+D,OAAAA,EAASC,OAAAA,CAAAA;AACxC,gBAAA;AACF,YAAA;AACF,QAAA;AACF,IAAA,CAAA;AAEAX,IAAAA,WAAAA,CAAYV,QAAQ9D,IAAAA,EAAM6D,OAAAA,CAAAA;IAE1B,OAAOE,QAAAA;AACT;;;;;;;;;"}
|
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
import _ from 'lodash';
|
|
2
|
-
import { has, pipe, omit, assign } from 'lodash/fp';
|
|
1
|
+
import _, { has, omit } from 'lodash';
|
|
3
2
|
import { async, contentTypes } from '@strapi/utils';
|
|
4
3
|
|
|
5
4
|
const isDialectMySQL = ()=>strapi.db?.dialect.client === 'mysql';
|
|
6
5
|
function omitComponentData(contentType, data) {
|
|
7
6
|
const { attributes } = contentType;
|
|
8
7
|
const componentAttributes = Object.keys(attributes).filter((attributeName)=>contentTypes.isComponentAttribute(attributes[attributeName]));
|
|
9
|
-
return omit(
|
|
8
|
+
return omit(data, componentAttributes);
|
|
10
9
|
}
|
|
11
10
|
// NOTE: we could generalize the logic to allow CRUD of relation directly in the DB layer
|
|
12
11
|
const createComponents = async (uid, data)=>{
|
|
@@ -15,7 +14,7 @@ const createComponents = async (uid, data)=>{
|
|
|
15
14
|
const attributeNames = Object.keys(attributes);
|
|
16
15
|
for (const attributeName of attributeNames){
|
|
17
16
|
const attribute = attributes[attributeName];
|
|
18
|
-
if (!has(
|
|
17
|
+
if (!has(data, attributeName) || !contentTypes.isComponentAttribute(attribute)) {
|
|
19
18
|
continue;
|
|
20
19
|
}
|
|
21
20
|
if (attribute.type === 'component') {
|
|
@@ -122,12 +121,13 @@ const deleteComponents = async (uid, entityToDelete, { loadComponents = true } =
|
|
|
122
121
|
const createComponent = async (uid, data)=>{
|
|
123
122
|
const model = strapi.getModel(uid);
|
|
124
123
|
const componentData = await createComponents(uid, data);
|
|
125
|
-
|
|
126
|
-
omit('id')
|
|
127
|
-
(payload)=>omitComponentData(model, payload), // ... and assign the newly created component instead
|
|
128
|
-
assign(componentData));
|
|
124
|
+
// Remove predefined IDs and replace nested component data with the created components.
|
|
125
|
+
const dataWithoutComponents = omitComponentData(model, omit(data, 'id'));
|
|
129
126
|
return strapi.db.query(uid).create({
|
|
130
|
-
data:
|
|
127
|
+
data: {
|
|
128
|
+
...componentData,
|
|
129
|
+
...dataWithoutComponents
|
|
130
|
+
}
|
|
131
131
|
});
|
|
132
132
|
};
|
|
133
133
|
const deleteComponent = async (uid, componentToDelete)=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"components.mjs","sources":["../../src/utils/components.ts"],"sourcesContent":["import _ from 'lodash';\nimport { get, has, omit, pipe, assign } from 'lodash/fp';\n\nimport { contentTypes as contentTypesUtils, async, errors } from '@strapi/utils';\nimport type { Modules, UID, Data, Utils, Schema, Core } from '@strapi/types';\n\ntype LoadedComponents<TUID extends UID.Schema> = Data.Entity<\n TUID,\n Schema.AttributeNamesByType<TUID, 'component' | 'dynamiczone'>\n>;\n\ntype ComponentValue = Schema.Attribute.Value<\n Schema.Attribute.Component<UID.Component, false> | Schema.Attribute.Component<UID.Component, true>\n>;\n\ntype ComponentBody = {\n [key: string]: Schema.Attribute.Value<\n | Schema.Attribute.Component<UID.Component, false>\n | Schema.Attribute.Component<UID.Component, true>\n | Schema.Attribute.DynamicZone\n >;\n};\n\nconst isDialectMySQL = () => strapi.db?.dialect.client === 'mysql';\n\nfunction omitComponentData(\n contentType: Schema.ContentType,\n data: Modules.EntityService.Params.Data.Input<Schema.ContentType['uid']>\n): Partial<Modules.EntityService.Params.Data.Input<Schema.ContentType['uid']>>;\nfunction omitComponentData(\n contentType: Schema.Component,\n data: Modules.EntityService.Params.Data.Input<Schema.Component['uid']>\n): Partial<Modules.EntityService.Params.Data.Input<Schema.Component['uid']>>;\nfunction omitComponentData(\n contentType: Schema.ContentType | Schema.Component,\n data: Modules.EntityService.Params.Data.Input<Schema.ContentType['uid'] | Schema.Component['uid']>\n): Partial<\n Modules.EntityService.Params.Data.Input<Schema.ContentType['uid'] | Schema.Component['uid']>\n> {\n const { attributes } = contentType;\n const componentAttributes = Object.keys(attributes).filter((attributeName) =>\n contentTypesUtils.isComponentAttribute(attributes[attributeName])\n );\n\n return omit(componentAttributes, data);\n}\n\n// NOTE: we could generalize the logic to allow CRUD of relation directly in the DB layer\nconst createComponents = async <\n TUID extends UID.Schema,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n>(\n uid: TUID,\n data: TData\n) => {\n const { attributes = {} } = strapi.getModel(uid);\n\n const componentBody: ComponentBody = {};\n\n const attributeNames = Object.keys(attributes);\n\n for (const attributeName of attributeNames) {\n const attribute = attributes[attributeName];\n\n if (!has(attributeName, data) || !contentTypesUtils.isComponentAttribute(attribute)) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID, repeatable = false } = attribute;\n\n const componentValue = data[attributeName as keyof TData];\n\n if (componentValue === null) {\n continue;\n }\n\n if (repeatable === true) {\n if (!Array.isArray(componentValue)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n const components = (await async.map(\n componentValue,\n (value: any) => createComponent(componentUID, value),\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n )) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, true>>;\n\n componentBody[attributeName] = components.map(({ id }) => {\n return {\n id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n });\n } else {\n const component = await createComponent(\n componentUID,\n componentValue as Modules.EntityService.Params.Data.Input<UID.Component>\n );\n componentBody[attributeName] = {\n id: component.id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n }\n\n continue;\n }\n\n if (attribute.type === 'dynamiczone') {\n const dynamiczoneValues = data[\n attributeName as keyof TData\n ] as Modules.EntityService.Params.Attribute.GetValue<Schema.Attribute.DynamicZone>;\n\n if (!Array.isArray(dynamiczoneValues)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n const createDynamicZoneComponents = async (\n value: Utils.Array.Values<typeof dynamiczoneValues>\n ) => {\n const { id } = await createComponent(value.__component, value);\n return {\n id,\n __component: value.__component,\n __pivot: {\n field: attributeName,\n },\n };\n };\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n componentBody[attributeName] = await async.map(\n dynamiczoneValues,\n createDynamicZoneComponents,\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n );\n\n continue;\n }\n }\n\n return componentBody;\n};\n\nconst getComponents = async <TUID extends UID.Schema>(\n uid: TUID,\n entity: { id: Modules.EntityService.Params.Attribute.ID }\n): Promise<LoadedComponents<TUID>> => {\n const componentAttributes = contentTypesUtils.getComponentAttributes(strapi.getModel(uid));\n\n if (_.isEmpty(componentAttributes)) {\n return {} as LoadedComponents<TUID>;\n }\n\n return strapi.db.query(uid).load(entity, componentAttributes) as Promise<LoadedComponents<TUID>>;\n};\n\n/*\n delete old components\n create or update\n*/\nconst updateComponents = async <\n TUID extends UID.Schema,\n TData extends Partial<Modules.EntityService.Params.Data.Input<TUID>>,\n>(\n uid: TUID,\n entityToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n data: TData\n) => {\n const { attributes = {} } = strapi.getModel(uid);\n\n const componentBody: ComponentBody = {};\n\n for (const attributeName of Object.keys(attributes)) {\n const attribute = attributes[attributeName];\n\n if (!has(attributeName, data)) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID, repeatable = false } = attribute;\n\n const componentValue = data[\n attributeName as keyof TData\n ] as Schema.Attribute.Value<Schema.Attribute.Component>;\n\n await deleteOldComponents(uid, componentUID, entityToUpdate, attributeName, componentValue);\n\n if (repeatable === true) {\n if (!Array.isArray(componentValue)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n const components = (await async.map(\n componentValue,\n (value: any) => updateOrCreateComponent(componentUID, value),\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n )) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, true>>;\n\n componentBody[attributeName] = components.filter(_.negate(_.isNil)).map(({ id }) => {\n return {\n id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n });\n } else {\n const component = await updateOrCreateComponent(componentUID, componentValue);\n componentBody[attributeName] = component && {\n id: component.id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n }\n\n continue;\n }\n\n if (attribute.type === 'dynamiczone') {\n const dynamiczoneValues = data[\n attributeName as keyof TData\n ] as Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n await deleteOldDZComponents(uid, entityToUpdate, attributeName, dynamiczoneValues);\n\n if (!Array.isArray(dynamiczoneValues)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n componentBody[attributeName] = await async.map(\n dynamiczoneValues,\n async (value: any) => {\n const { id } = await updateOrCreateComponent(value.__component, value);\n\n return {\n id,\n __component: value.__component,\n __pivot: {\n field: attributeName,\n },\n };\n },\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n );\n\n continue;\n }\n }\n\n return componentBody;\n};\n\nconst pickStringifiedId = ({\n id,\n}: {\n id: Modules.EntityService.Params.Attribute.ID;\n}): Modules.EntityService.Params.Attribute.ID & string => {\n if (typeof id === 'string') {\n return id;\n }\n\n return `${id}`;\n};\n\nconst deleteOldComponents = async <TUID extends UID.Schema>(\n uid: TUID,\n componentUID: UID.Component,\n entityToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n attributeName: string,\n componentValue: Schema.Attribute.Value<Schema.Attribute.Component>\n) => {\n const previousValue = (await strapi.db\n .query(uid)\n .load(entityToUpdate, attributeName)) as ComponentValue;\n\n const idsToKeep = _.castArray(componentValue).filter(has('id')).map(pickStringifiedId);\n const allIds = _.castArray(previousValue).filter(has('id')).map(pickStringifiedId);\n\n idsToKeep.forEach((id) => {\n if (!allIds.includes(id)) {\n throw new errors.ApplicationError(\n `Some of the provided components in ${attributeName} are not related to the entity`\n );\n }\n });\n\n const idsToDelete = _.difference(allIds, idsToKeep);\n\n if (idsToDelete.length > 0) {\n for (const idToDelete of idsToDelete) {\n await deleteComponent(componentUID, { id: idToDelete });\n }\n }\n};\n\nconst deleteOldDZComponents = async <TUID extends UID.Schema>(\n uid: TUID,\n entityToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n attributeName: string,\n dynamiczoneValues: Schema.Attribute.Value<Schema.Attribute.DynamicZone>\n) => {\n const previousValue = (await strapi.db\n .query(uid)\n .load(entityToUpdate, attributeName)) as Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n const idsToKeep = _.castArray(dynamiczoneValues)\n .filter(has('id'))\n .map((v) => ({\n id: pickStringifiedId(v),\n __component: v.__component,\n }));\n\n const allIds = _.castArray(previousValue)\n .filter(has('id'))\n .map((v) => ({\n id: pickStringifiedId(v),\n __component: v.__component,\n }));\n\n idsToKeep.forEach(({ id, __component }) => {\n if (!allIds.find((el) => el.id === id && el.__component === __component)) {\n const err = new Error(\n `Some of the provided components in ${attributeName} are not related to the entity`\n );\n\n Object.assign(err, { status: 400 });\n throw err;\n }\n });\n\n type IdsToDelete = Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n const idsToDelete = allIds.reduce((acc, { id, __component: componentUID }) => {\n if (!idsToKeep.find((el) => el.id === id && el.__component === componentUID)) {\n acc.push({ id, __component: componentUID });\n }\n\n return acc;\n }, [] as IdsToDelete);\n\n if (idsToDelete.length > 0) {\n for (const idToDelete of idsToDelete) {\n const { id, __component: componentUID } = idToDelete;\n await deleteComponent(componentUID, { id });\n }\n }\n};\n\nconst deleteComponents = async <TUID extends UID.Schema, TEntity extends Data.Entity<TUID>>(\n uid: TUID,\n entityToDelete: TEntity,\n { loadComponents = true } = {}\n) => {\n const { attributes = {} } = strapi.getModel(uid);\n\n const attributeNames = Object.keys(attributes);\n\n for (const attributeName of attributeNames) {\n const attribute = attributes[attributeName];\n\n if (attribute.type === 'component' || attribute.type === 'dynamiczone') {\n let value;\n if (loadComponents) {\n value = await strapi.db.query(uid).load(entityToDelete, attributeName);\n } else {\n value = entityToDelete[attributeName as keyof TEntity];\n }\n\n if (!value) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID } = attribute;\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n await async.map(\n _.castArray(value),\n (subValue: any) => deleteComponent(componentUID, subValue),\n {\n concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity,\n }\n );\n } else {\n // delete dynamic zone components\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n await async.map(\n _.castArray(value),\n (subValue: any) => deleteComponent(subValue.__component, subValue),\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n );\n }\n\n continue;\n }\n }\n};\n\n/** *************************\n Component queries\n************************** */\n\n// components can have nested compos so this must be recursive\nconst createComponent = async <TUID extends UID.Component = UID.Component>(\n uid: TUID,\n data: Modules.EntityService.Params.Data.Input<TUID>\n) => {\n const model = strapi.getModel(uid) as Schema.Component;\n\n const componentData = await createComponents(uid, data);\n const transform = pipe(\n // Make sure we don't save the component with a pre-defined ID\n omit('id'),\n // Remove the component data from the original data object ...\n (payload) => omitComponentData(model, payload),\n // ... and assign the newly created component instead\n assign(componentData)\n );\n\n return strapi.db.query(uid).create({ data: transform(data) });\n};\n\n// components can have nested compos so this must be recursive\nconst updateComponent = async <TUID extends UID.Component>(\n uid: TUID,\n componentToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n data: Modules.EntityService.Params.Data.Input<TUID>\n) => {\n const model = strapi.getModel(uid) as Schema.Component;\n\n const componentData = await updateComponents(uid, componentToUpdate, data);\n\n return strapi.db.query(uid).update({\n where: {\n id: componentToUpdate.id,\n },\n data: Object.assign(omitComponentData(model, data), componentData),\n });\n};\n\nconst updateOrCreateComponent = <TUID extends UID.Component>(\n componentUID: TUID,\n value: Modules.EntityService.Params.Data.Input<TUID>\n) => {\n if (value === null) {\n return null;\n }\n\n // update\n if ('id' in value && typeof value.id !== 'undefined') {\n // TODO: verify the compo is associated with the entity\n return updateComponent(componentUID, { id: value.id }, value);\n }\n\n // create\n return createComponent(componentUID, value);\n};\n\nconst deleteComponent = async <TUID extends UID.Component>(\n uid: TUID,\n componentToDelete: Data.Component<TUID>\n) => {\n await deleteComponents(uid, componentToDelete);\n await strapi.db.query(uid).delete({ where: { id: componentToDelete.id } });\n};\n\ninterface IComponentIdMapping {\n uid: UID.Component;\n oldID: number;\n newID: number;\n}\n\n/**\n * Walk the source data and the newly created entity in parallel and collect\n * the [old ID, new ID] couple of every component instance found in both trees\n * (components & dynamic zones, including nested ones).\n *\n * Unlike a JSON diff, couples are also collected when the ID did not change,\n * so the result is an exhaustive map of every component instance that was\n * re-created with the entity.\n */\nconst collectComponentIdMappings = ({\n data,\n created,\n schema,\n strapi,\n}: {\n data: any;\n created: any;\n schema: Schema.Schema;\n strapi: Core.Strapi;\n}): IComponentIdMapping[] => {\n const mappings: IComponentIdMapping[] = [];\n\n const visitComponent = (uid: UID.Component, oldValue: any, newValue: any) => {\n if (!_.isObjectLike(oldValue) || !_.isObjectLike(newValue)) {\n return;\n }\n\n if (typeof oldValue.id === 'number' && typeof newValue.id === 'number') {\n mappings.push({ uid, oldID: oldValue.id, newID: newValue.id });\n }\n\n const componentSchema = strapi.getModel(uid);\n\n // Collect nested components & dynamic zones\n if (componentSchema) {\n visitSchema(componentSchema, oldValue, newValue);\n }\n };\n\n const visitSchema = (currentSchema: Schema.Schema, oldData: any, newData: any) => {\n if (!_.isObjectLike(oldData) || !_.isObjectLike(newData)) {\n return;\n }\n\n const { attributes = {} } = currentSchema;\n\n for (const [attributeName, attribute] of Object.entries(attributes)) {\n const oldValue = oldData[attributeName];\n const newValue = newData[attributeName];\n\n if (_.isNil(oldValue) || _.isNil(newValue)) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID, repeatable = false } = attribute;\n\n if (repeatable === true) {\n if (!Array.isArray(oldValue) || !Array.isArray(newValue)) {\n continue;\n }\n\n // Components are created (and thus populated back) in the same\n // order as the source data, pair them by index\n const length = Math.min(oldValue.length, newValue.length);\n\n for (let i = 0; i < length; i += 1) {\n visitComponent(componentUID, oldValue[i], newValue[i]);\n }\n } else {\n visitComponent(componentUID, oldValue, newValue);\n }\n }\n\n if (attribute.type === 'dynamiczone') {\n if (!Array.isArray(oldValue) || !Array.isArray(newValue)) {\n continue;\n }\n\n const length = Math.min(oldValue.length, newValue.length);\n\n for (let i = 0; i < length; i += 1) {\n const oldItem = oldValue[i];\n const newItem = newValue[i];\n const componentUID = oldItem?.__component;\n\n // Both items must reference the same dynamic zone component for the\n // ID couple to be meaningful\n if (!componentUID || (newItem?.__component && newItem.__component !== componentUID)) {\n continue;\n }\n\n visitComponent(componentUID, oldItem, newItem);\n }\n }\n }\n };\n\n visitSchema(schema, data, created);\n\n return mappings;\n};\n\n/**\n * Resolve the component UID of an entity's attribute based\n * on a given path (components & dynamic zones only)\n */\nconst resolveComponentUID = ({\n paths,\n strapi,\n data,\n contentType,\n}: {\n paths: string[];\n strapi: Core.Strapi;\n data: any;\n contentType: Schema.ContentType;\n}): UID.Schema | undefined => {\n let value: unknown = data;\n let cType:\n | Schema.ContentType\n | Schema.Component\n | ((...opts: any[]) => Schema.ContentType | Schema.Component) = contentType;\n for (const path of paths) {\n value = get(path, value);\n\n // Needed when the value of cType should be computed\n // based on the next value (eg: dynamic zones)\n if (typeof cType === 'function') {\n cType = cType(value);\n }\n\n if (path in cType.attributes) {\n const attribute: Schema.Attribute.AnyAttribute = cType.attributes[path];\n\n if (attribute.type === 'component') {\n cType = strapi.getModel(attribute.component);\n }\n\n if (attribute.type === 'dynamiczone') {\n cType = ({ __component }: { __component: UID.Component }) => strapi.getModel(__component);\n }\n }\n }\n\n if ('uid' in cType) {\n return cType.uid;\n }\n\n return undefined;\n};\n\nexport {\n omitComponentData,\n getComponents,\n createComponents,\n updateComponents,\n deleteComponents,\n deleteComponent,\n collectComponentIdMappings,\n resolveComponentUID,\n};\n"],"names":["isDialectMySQL","strapi","db","dialect","client","omitComponentData","contentType","data","attributes","componentAttributes","Object","keys","filter","attributeName","contentTypesUtils","isComponentAttribute","omit","createComponents","uid","getModel","componentBody","attributeNames","attribute","has","type","component","componentUID","repeatable","componentValue","Array","isArray","Error","components","async","map","value","createComponent","concurrency","inTransaction","Infinity","id","__pivot","field","component_type","dynamiczoneValues","createDynamicZoneComponents","__component","getComponents","entity","getComponentAttributes","_","isEmpty","query","load","deleteComponents","entityToDelete","loadComponents","castArray","subValue","deleteComponent","model","componentData","transform","pipe","payload","assign","create","componentToDelete","delete","where","collectComponentIdMappings","created","schema","mappings","visitComponent","oldValue","newValue","isObjectLike","push","oldID","newID","componentSchema","visitSchema","currentSchema","oldData","newData","entries","isNil","length","Math","min","i","oldItem","newItem"],"mappings":";;;;AAuBA,MAAMA,iBAAiB,IAAMC,MAAAA,CAAOC,EAAE,EAAEC,QAAQC,MAAAA,KAAW,OAAA;AAU3D,SAASC,iBAAAA,CACPC,WAAkD,EAClDC,IAAkG,EAAA;IAIl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AAehD,cAAckE,OAAAA,EAASC,OAAAA,CAAAA;AACxC,gBAAA;AACF,YAAA;AACF,QAAA;AACF,IAAA,CAAA;AAEAX,IAAAA,WAAAA,CAAYV,QAAQjE,IAAAA,EAAMgE,OAAAA,CAAAA;IAE1B,OAAOE,QAAAA;AACT;;;;"}
|
|
1
|
+
{"version":3,"file":"components.mjs","sources":["../../src/utils/components.ts"],"sourcesContent":["import _, { get, has, omit } from 'lodash';\n\nimport { contentTypes as contentTypesUtils, async, errors } from '@strapi/utils';\nimport type { Modules, UID, Data, Utils, Schema, Core } from '@strapi/types';\n\ntype LoadedComponents<TUID extends UID.Schema> = Data.Entity<\n TUID,\n Schema.AttributeNamesByType<TUID, 'component' | 'dynamiczone'>\n>;\n\ntype ComponentValue = Schema.Attribute.Value<\n Schema.Attribute.Component<UID.Component, false> | Schema.Attribute.Component<UID.Component, true>\n>;\n\ntype ComponentBody = {\n [key: string]: Schema.Attribute.Value<\n | Schema.Attribute.Component<UID.Component, false>\n | Schema.Attribute.Component<UID.Component, true>\n | Schema.Attribute.DynamicZone\n >;\n};\n\nconst isDialectMySQL = () => strapi.db?.dialect.client === 'mysql';\n\nfunction omitComponentData(\n contentType: Schema.ContentType,\n data: Modules.EntityService.Params.Data.Input<Schema.ContentType['uid']>\n): Partial<Modules.EntityService.Params.Data.Input<Schema.ContentType['uid']>>;\nfunction omitComponentData(\n contentType: Schema.Component,\n data: Modules.EntityService.Params.Data.Input<Schema.Component['uid']>\n): Partial<Modules.EntityService.Params.Data.Input<Schema.Component['uid']>>;\nfunction omitComponentData(\n contentType: Schema.ContentType | Schema.Component,\n data: Modules.EntityService.Params.Data.Input<Schema.ContentType['uid'] | Schema.Component['uid']>\n): Partial<\n Modules.EntityService.Params.Data.Input<Schema.ContentType['uid'] | Schema.Component['uid']>\n> {\n const { attributes } = contentType;\n const componentAttributes = Object.keys(attributes).filter((attributeName) =>\n contentTypesUtils.isComponentAttribute(attributes[attributeName])\n );\n\n return omit(data, componentAttributes);\n}\n\n// NOTE: we could generalize the logic to allow CRUD of relation directly in the DB layer\nconst createComponents = async <\n TUID extends UID.Schema,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n>(\n uid: TUID,\n data: TData\n) => {\n const { attributes = {} } = strapi.getModel(uid);\n\n const componentBody: ComponentBody = {};\n\n const attributeNames = Object.keys(attributes);\n\n for (const attributeName of attributeNames) {\n const attribute = attributes[attributeName];\n\n if (!has(data, attributeName) || !contentTypesUtils.isComponentAttribute(attribute)) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID, repeatable = false } = attribute;\n\n const componentValue = data[attributeName as keyof TData];\n\n if (componentValue === null) {\n continue;\n }\n\n if (repeatable === true) {\n if (!Array.isArray(componentValue)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n const components = (await async.map(\n componentValue,\n (value: any) => createComponent(componentUID, value),\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n )) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, true>>;\n\n componentBody[attributeName] = components.map(({ id }) => {\n return {\n id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n });\n } else {\n const component = await createComponent(\n componentUID,\n componentValue as Modules.EntityService.Params.Data.Input<UID.Component>\n );\n componentBody[attributeName] = {\n id: component.id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n }\n\n continue;\n }\n\n if (attribute.type === 'dynamiczone') {\n const dynamiczoneValues = data[\n attributeName as keyof TData\n ] as Modules.EntityService.Params.Attribute.GetValue<Schema.Attribute.DynamicZone>;\n\n if (!Array.isArray(dynamiczoneValues)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n const createDynamicZoneComponents = async (\n value: Utils.Array.Values<typeof dynamiczoneValues>\n ) => {\n const { id } = await createComponent(value.__component, value);\n return {\n id,\n __component: value.__component,\n __pivot: {\n field: attributeName,\n },\n };\n };\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n componentBody[attributeName] = await async.map(\n dynamiczoneValues,\n createDynamicZoneComponents,\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n );\n\n continue;\n }\n }\n\n return componentBody;\n};\n\nconst getComponents = async <TUID extends UID.Schema>(\n uid: TUID,\n entity: { id: Modules.EntityService.Params.Attribute.ID }\n): Promise<LoadedComponents<TUID>> => {\n const componentAttributes = contentTypesUtils.getComponentAttributes(strapi.getModel(uid));\n\n if (_.isEmpty(componentAttributes)) {\n return {} as LoadedComponents<TUID>;\n }\n\n return strapi.db.query(uid).load(entity, componentAttributes) as Promise<LoadedComponents<TUID>>;\n};\n\n/*\n delete old components\n create or update\n*/\nconst updateComponents = async <\n TUID extends UID.Schema,\n TData extends Partial<Modules.EntityService.Params.Data.Input<TUID>>,\n>(\n uid: TUID,\n entityToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n data: TData\n) => {\n const { attributes = {} } = strapi.getModel(uid);\n\n const componentBody: ComponentBody = {};\n\n for (const attributeName of Object.keys(attributes)) {\n const attribute = attributes[attributeName];\n\n if (!has(data, attributeName)) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID, repeatable = false } = attribute;\n\n const componentValue = data[\n attributeName as keyof TData\n ] as Schema.Attribute.Value<Schema.Attribute.Component>;\n\n await deleteOldComponents(uid, componentUID, entityToUpdate, attributeName, componentValue);\n\n if (repeatable === true) {\n if (!Array.isArray(componentValue)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n const components = (await async.map(\n componentValue,\n (value: any) => updateOrCreateComponent(componentUID, value),\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n )) as Schema.Attribute.Value<Schema.Attribute.Component<UID.Component, true>>;\n\n componentBody[attributeName] = components.filter(_.negate(_.isNil)).map(({ id }) => {\n return {\n id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n });\n } else {\n const component = await updateOrCreateComponent(componentUID, componentValue);\n componentBody[attributeName] = component && {\n id: component.id,\n __pivot: {\n field: attributeName,\n component_type: componentUID,\n },\n };\n }\n\n continue;\n }\n\n if (attribute.type === 'dynamiczone') {\n const dynamiczoneValues = data[\n attributeName as keyof TData\n ] as Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n await deleteOldDZComponents(uid, entityToUpdate, attributeName, dynamiczoneValues);\n\n if (!Array.isArray(dynamiczoneValues)) {\n throw new Error('Expected an array to create repeatable component');\n }\n\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n componentBody[attributeName] = await async.map(\n dynamiczoneValues,\n async (value: any) => {\n const { id } = await updateOrCreateComponent(value.__component, value);\n\n return {\n id,\n __component: value.__component,\n __pivot: {\n field: attributeName,\n },\n };\n },\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n );\n\n continue;\n }\n }\n\n return componentBody;\n};\n\nconst pickStringifiedId = ({\n id,\n}: {\n id: Modules.EntityService.Params.Attribute.ID;\n}): Modules.EntityService.Params.Attribute.ID & string => {\n if (typeof id === 'string') {\n return id;\n }\n\n return `${id}`;\n};\n\nconst deleteOldComponents = async <TUID extends UID.Schema>(\n uid: TUID,\n componentUID: UID.Component,\n entityToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n attributeName: string,\n componentValue: Schema.Attribute.Value<Schema.Attribute.Component>\n) => {\n const previousValue = (await strapi.db\n .query(uid)\n .load(entityToUpdate, attributeName)) as ComponentValue;\n\n const idsToKeep = _.castArray(componentValue)\n .filter((component) => has(component, 'id'))\n .map(pickStringifiedId);\n const allIds = _.castArray(previousValue)\n .filter((component) => has(component, 'id'))\n .map(pickStringifiedId);\n\n idsToKeep.forEach((id) => {\n if (!allIds.includes(id)) {\n throw new errors.ApplicationError(\n `Some of the provided components in ${attributeName} are not related to the entity`\n );\n }\n });\n\n const idsToDelete = _.difference(allIds, idsToKeep);\n\n if (idsToDelete.length > 0) {\n for (const idToDelete of idsToDelete) {\n await deleteComponent(componentUID, { id: idToDelete });\n }\n }\n};\n\nconst deleteOldDZComponents = async <TUID extends UID.Schema>(\n uid: TUID,\n entityToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n attributeName: string,\n dynamiczoneValues: Schema.Attribute.Value<Schema.Attribute.DynamicZone>\n) => {\n const previousValue = (await strapi.db\n .query(uid)\n .load(entityToUpdate, attributeName)) as Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n const idsToKeep = _.castArray(dynamiczoneValues)\n .filter((component) => has(component, 'id'))\n .map((v) => ({\n id: pickStringifiedId(v),\n __component: v.__component,\n }));\n\n const allIds = _.castArray(previousValue)\n .filter((component) => has(component, 'id'))\n .map((v) => ({\n id: pickStringifiedId(v),\n __component: v.__component,\n }));\n\n idsToKeep.forEach(({ id, __component }) => {\n if (!allIds.find((el) => el.id === id && el.__component === __component)) {\n const err = new Error(\n `Some of the provided components in ${attributeName} are not related to the entity`\n );\n\n Object.assign(err, { status: 400 });\n throw err;\n }\n });\n\n type IdsToDelete = Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n\n const idsToDelete = allIds.reduce((acc, { id, __component: componentUID }) => {\n if (!idsToKeep.find((el) => el.id === id && el.__component === componentUID)) {\n acc.push({ id, __component: componentUID });\n }\n\n return acc;\n }, [] as IdsToDelete);\n\n if (idsToDelete.length > 0) {\n for (const idToDelete of idsToDelete) {\n const { id, __component: componentUID } = idToDelete;\n await deleteComponent(componentUID, { id });\n }\n }\n};\n\nconst deleteComponents = async <TUID extends UID.Schema, TEntity extends Data.Entity<TUID>>(\n uid: TUID,\n entityToDelete: TEntity,\n { loadComponents = true } = {}\n) => {\n const { attributes = {} } = strapi.getModel(uid);\n\n const attributeNames = Object.keys(attributes);\n\n for (const attributeName of attributeNames) {\n const attribute = attributes[attributeName];\n\n if (attribute.type === 'component' || attribute.type === 'dynamiczone') {\n let value;\n if (loadComponents) {\n value = await strapi.db.query(uid).load(entityToDelete, attributeName);\n } else {\n value = entityToDelete[attributeName as keyof TEntity];\n }\n\n if (!value) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID } = attribute;\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n await async.map(\n _.castArray(value),\n (subValue: any) => deleteComponent(componentUID, subValue),\n {\n concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity,\n }\n );\n } else {\n // delete dynamic zone components\n // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1\n await async.map(\n _.castArray(value),\n (subValue: any) => deleteComponent(subValue.__component, subValue),\n { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }\n );\n }\n\n continue;\n }\n }\n};\n\n/** *************************\n Component queries\n************************** */\n\n// components can have nested compos so this must be recursive\nconst createComponent = async <TUID extends UID.Component = UID.Component>(\n uid: TUID,\n data: Modules.EntityService.Params.Data.Input<TUID>\n) => {\n const model = strapi.getModel(uid) as Schema.Component;\n\n const componentData = await createComponents(uid, data);\n // Remove predefined IDs and replace nested component data with the created components.\n const dataWithoutComponents = omitComponentData(model, omit(data, 'id'));\n\n return strapi.db.query(uid).create({\n data: { ...componentData, ...dataWithoutComponents },\n });\n};\n\n// components can have nested compos so this must be recursive\nconst updateComponent = async <TUID extends UID.Component>(\n uid: TUID,\n componentToUpdate: { id: Modules.EntityService.Params.Attribute.ID },\n data: Modules.EntityService.Params.Data.Input<TUID>\n) => {\n const model = strapi.getModel(uid) as Schema.Component;\n\n const componentData = await updateComponents(uid, componentToUpdate, data);\n\n return strapi.db.query(uid).update({\n where: {\n id: componentToUpdate.id,\n },\n data: Object.assign(omitComponentData(model, data), componentData),\n });\n};\n\nconst updateOrCreateComponent = <TUID extends UID.Component>(\n componentUID: TUID,\n value: Modules.EntityService.Params.Data.Input<TUID>\n) => {\n if (value === null) {\n return null;\n }\n\n // update\n if ('id' in value && typeof value.id !== 'undefined') {\n // TODO: verify the compo is associated with the entity\n return updateComponent(componentUID, { id: value.id }, value);\n }\n\n // create\n return createComponent(componentUID, value);\n};\n\nconst deleteComponent = async <TUID extends UID.Component>(\n uid: TUID,\n componentToDelete: Data.Component<TUID>\n) => {\n await deleteComponents(uid, componentToDelete);\n await strapi.db.query(uid).delete({ where: { id: componentToDelete.id } });\n};\n\ninterface IComponentIdMapping {\n uid: UID.Component;\n oldID: number;\n newID: number;\n}\n\n/**\n * Walk the source data and the newly created entity in parallel and collect\n * the [old ID, new ID] couple of every component instance found in both trees\n * (components & dynamic zones, including nested ones).\n *\n * Unlike a JSON diff, couples are also collected when the ID did not change,\n * so the result is an exhaustive map of every component instance that was\n * re-created with the entity.\n */\nconst collectComponentIdMappings = ({\n data,\n created,\n schema,\n strapi,\n}: {\n data: any;\n created: any;\n schema: Schema.Schema;\n strapi: Core.Strapi;\n}): IComponentIdMapping[] => {\n const mappings: IComponentIdMapping[] = [];\n\n const visitComponent = (uid: UID.Component, oldValue: any, newValue: any) => {\n if (!_.isObjectLike(oldValue) || !_.isObjectLike(newValue)) {\n return;\n }\n\n if (typeof oldValue.id === 'number' && typeof newValue.id === 'number') {\n mappings.push({ uid, oldID: oldValue.id, newID: newValue.id });\n }\n\n const componentSchema = strapi.getModel(uid);\n\n // Collect nested components & dynamic zones\n if (componentSchema) {\n visitSchema(componentSchema, oldValue, newValue);\n }\n };\n\n const visitSchema = (currentSchema: Schema.Schema, oldData: any, newData: any) => {\n if (!_.isObjectLike(oldData) || !_.isObjectLike(newData)) {\n return;\n }\n\n const { attributes = {} } = currentSchema;\n\n for (const [attributeName, attribute] of Object.entries(attributes)) {\n const oldValue = oldData[attributeName];\n const newValue = newData[attributeName];\n\n if (_.isNil(oldValue) || _.isNil(newValue)) {\n continue;\n }\n\n if (attribute.type === 'component') {\n const { component: componentUID, repeatable = false } = attribute;\n\n if (repeatable === true) {\n if (!Array.isArray(oldValue) || !Array.isArray(newValue)) {\n continue;\n }\n\n // Components are created (and thus populated back) in the same\n // order as the source data, pair them by index\n const length = Math.min(oldValue.length, newValue.length);\n\n for (let i = 0; i < length; i += 1) {\n visitComponent(componentUID, oldValue[i], newValue[i]);\n }\n } else {\n visitComponent(componentUID, oldValue, newValue);\n }\n }\n\n if (attribute.type === 'dynamiczone') {\n if (!Array.isArray(oldValue) || !Array.isArray(newValue)) {\n continue;\n }\n\n const length = Math.min(oldValue.length, newValue.length);\n\n for (let i = 0; i < length; i += 1) {\n const oldItem = oldValue[i];\n const newItem = newValue[i];\n const componentUID = oldItem?.__component;\n\n // Both items must reference the same dynamic zone component for the\n // ID couple to be meaningful\n if (!componentUID || (newItem?.__component && newItem.__component !== componentUID)) {\n continue;\n }\n\n visitComponent(componentUID, oldItem, newItem);\n }\n }\n }\n };\n\n visitSchema(schema, data, created);\n\n return mappings;\n};\n\n/**\n * Resolve the component UID of an entity's attribute based\n * on a given path (components & dynamic zones only)\n */\nconst resolveComponentUID = ({\n paths,\n strapi,\n data,\n contentType,\n}: {\n paths: string[];\n strapi: Core.Strapi;\n data: any;\n contentType: Schema.ContentType;\n}): UID.Schema | undefined => {\n let value: unknown = data;\n let cType:\n | Schema.ContentType\n | Schema.Component\n | ((...opts: any[]) => Schema.ContentType | Schema.Component) = contentType;\n for (const path of paths) {\n value = get(value, path);\n\n // Needed when the value of cType should be computed\n // based on the next value (eg: dynamic zones)\n if (typeof cType === 'function') {\n cType = cType(value);\n }\n\n if (path in cType.attributes) {\n const attribute: Schema.Attribute.AnyAttribute = cType.attributes[path];\n\n if (attribute.type === 'component') {\n cType = strapi.getModel(attribute.component);\n }\n\n if (attribute.type === 'dynamiczone') {\n cType = ({ __component }: { __component: UID.Component }) => strapi.getModel(__component);\n }\n }\n }\n\n if ('uid' in cType) {\n return cType.uid;\n }\n\n return undefined;\n};\n\nexport {\n omitComponentData,\n getComponents,\n createComponents,\n updateComponents,\n deleteComponents,\n deleteComponent,\n collectComponentIdMappings,\n resolveComponentUID,\n};\n"],"names":["isDialectMySQL","strapi","db","dialect","client","omitComponentData","contentType","data","attributes","componentAttributes","Object","keys","filter","attributeName","contentTypesUtils","isComponentAttribute","omit","createComponents","uid","getModel","componentBody","attributeNames","attribute","has","type","component","componentUID","repeatable","componentValue","Array","isArray","Error","components","async","map","value","createComponent","concurrency","inTransaction","Infinity","id","__pivot","field","component_type","dynamiczoneValues","createDynamicZoneComponents","__component","getComponents","entity","getComponentAttributes","_","isEmpty","query","load","deleteComponents","entityToDelete","loadComponents","castArray","subValue","deleteComponent","model","componentData","dataWithoutComponents","create","componentToDelete","delete","where","collectComponentIdMappings","created","schema","mappings","visitComponent","oldValue","newValue","isObjectLike","push","oldID","newID","componentSchema","visitSchema","currentSchema","oldData","newData","entries","isNil","length","Math","min","i","oldItem","newItem"],"mappings":";;;AAsBA,MAAMA,iBAAiB,IAAMC,MAAAA,CAAOC,EAAE,EAAEC,QAAQC,MAAAA,KAAW,OAAA;AAU3D,SAASC,iBAAAA,CACPC,WAAkD,EAClDC,IAAkG,EAAA;IAIlG,MAAM,EAAEC,UAAU,EAAE,GAAGF,WAAAA;AACvB,IAAA,MAAMG,mBAAAA,GAAsBC,MAAAA,CAAOC,IAAI,CAACH,YAAYI,MAAM,CAAC,CAACC,aAAAA,GAC1DC,YAAAA,CAAkBC,oBAAoB,CAACP,UAAU,CAACK,aAAAA,CAAc,CAAA,CAAA;AAGlE,IAAA,OAAOG,KAAKT,IAAAA,EAAME,mBAAAA,CAAAA;AACpB;AAEA;AACA,MAAMQ,gBAAAA,GAAmB,OAIvBC,GAAAA,EACAX,IAAAA,GAAAA;IAEA,MAAM,EAAEC,aAAa,EAAE,EAAE,GAAGP,MAAAA,CAAOkB,QAAQ,CAACD,GAAAA,CAAAA;AAE5C,IAAA,MAAME,gBAA+B,EAAC;IAEtC,MAAMC,cAAAA,GAAiBX,MAAAA,CAAOC,IAAI,CAACH,UAAAA,CAAAA;IAEnC,KAAK,MAAMK,iBAAiBQ,cAAAA,CAAgB;QAC1C,MAAMC,SAAAA,GAAYd,UAAU,C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C,QAAAA,CAAAA,EAAW;AACxD,oBAAA;AACF,gBAAA;gBAEA,MAAMY,MAAAA,GAASC,KAAKC,GAAG,CAACf,SAASa,MAAM,EAAEZ,SAASY,MAAM,CAAA;AAExD,gBAAA,IAAK,IAAIG,CAAAA,GAAI,CAAA,EAAGA,CAAAA,GAAIH,MAAAA,EAAQG,KAAK,CAAA,CAAG;oBAClC,MAAMC,OAAAA,GAAUjB,QAAQ,CAACgB,CAAAA,CAAE;oBAC3B,MAAME,OAAAA,GAAUjB,QAAQ,CAACe,CAAAA,CAAE;AAC3B,oBAAA,MAAM9D,eAAe+D,OAAAA,EAAS3C,WAAAA;;;AAI9B,oBAAA,IAAI,CAACpB,YAAAA,IAAiBgE,OAAAA,EAAS5C,eAAe4C,OAAAA,CAAQ5C,WAAW,KAAKpB,YAAAA,EAAe;AACnF,wBAAA;AACF,oBAAA;AAEA6C,oBAAAA,cAAAA,CAAe7C,cAAc+D,OAAAA,EAASC,OAAAA,CAAAA;AACxC,gBAAA;AACF,YAAA;AACF,QAAA;AACF,IAAA,CAAA;AAEAX,IAAAA,WAAAA,CAAYV,QAAQ9D,IAAAA,EAAM6D,OAAAA,CAAAA;IAE1B,OAAOE,QAAAA;AACT;;;;"}
|
package/dist/utils/json.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _ = require('lodash');
|
|
4
4
|
|
|
5
5
|
const createContext = ()=>({
|
|
6
6
|
path: []
|
|
@@ -50,9 +50,9 @@ const createContext = ()=>({
|
|
|
50
50
|
});
|
|
51
51
|
return diffs;
|
|
52
52
|
};
|
|
53
|
-
if (
|
|
53
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
54
54
|
let k = 0;
|
|
55
|
-
for (const [aItem, bItem] of
|
|
55
|
+
for (const [aItem, bItem] of _.zip(a, b)){
|
|
56
56
|
const kCtx = {
|
|
57
57
|
path: [
|
|
58
58
|
...path,
|
|
@@ -65,8 +65,10 @@ const createContext = ()=>({
|
|
|
65
65
|
}
|
|
66
66
|
return diffs;
|
|
67
67
|
}
|
|
68
|
-
if (
|
|
69
|
-
const keys =
|
|
68
|
+
if (_.isObject(a) && _.isObject(b)) {
|
|
69
|
+
const keys = [
|
|
70
|
+
...new Set(Object.keys(a).concat(Object.keys(b)))
|
|
71
|
+
];
|
|
70
72
|
for (const key of keys){
|
|
71
73
|
const aValue = a[key];
|
|
72
74
|
const bValue = b[key];
|
|
@@ -80,7 +82,7 @@ const createContext = ()=>({
|
|
|
80
82
|
}
|
|
81
83
|
return diffs;
|
|
82
84
|
}
|
|
83
|
-
if (!
|
|
85
|
+
if (!_.isEqual(a, b)) {
|
|
84
86
|
if (aType === 'undefined') {
|
|
85
87
|
return added();
|
|
86
88
|
}
|