@strapi/data-transfer 5.30.0 → 5.31.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/engine/errors.js.map +1 -1
- package/dist/engine/errors.mjs.map +1 -1
- package/dist/engine/index.js.map +1 -1
- package/dist/engine/index.mjs.map +1 -1
- package/dist/engine/validation/provider.js.map +1 -1
- package/dist/engine/validation/provider.mjs.map +1 -1
- package/dist/errors/base.js.map +1 -1
- package/dist/errors/base.mjs.map +1 -1
- package/dist/errors/providers.js.map +1 -1
- package/dist/errors/providers.mjs.map +1 -1
- package/dist/file/providers/destination/index.js.map +1 -1
- package/dist/file/providers/destination/index.mjs.map +1 -1
- package/dist/file/providers/destination/utils.js.map +1 -1
- package/dist/file/providers/destination/utils.mjs.map +1 -1
- package/dist/file/providers/source/index.js.map +1 -1
- package/dist/file/providers/source/index.mjs.map +1 -1
- package/dist/strapi/providers/local-destination/index.js.map +1 -1
- package/dist/strapi/providers/local-destination/index.mjs.map +1 -1
- package/dist/strapi/providers/local-destination/strategies/restore/configuration.js.map +1 -1
- package/dist/strapi/providers/local-destination/strategies/restore/configuration.mjs.map +1 -1
- package/dist/strapi/providers/local-source/assets.js.map +1 -1
- package/dist/strapi/providers/local-source/assets.mjs.map +1 -1
- package/dist/strapi/providers/local-source/index.js.map +1 -1
- package/dist/strapi/providers/local-source/index.mjs.map +1 -1
- package/dist/strapi/providers/remote-destination/index.js.map +1 -1
- package/dist/strapi/providers/remote-destination/index.mjs.map +1 -1
- package/dist/strapi/providers/remote-source/index.js.map +1 -1
- package/dist/strapi/providers/remote-source/index.mjs.map +1 -1
- package/dist/strapi/providers/utils.js.map +1 -1
- package/dist/strapi/providers/utils.mjs.map +1 -1
- package/dist/strapi/queries/link.js.map +1 -1
- package/dist/strapi/queries/link.mjs.map +1 -1
- package/dist/strapi/remote/handlers/abstract.d.ts +1 -0
- package/dist/strapi/remote/handlers/abstract.d.ts.map +1 -1
- package/dist/strapi/remote/handlers/pull.js.map +1 -1
- package/dist/strapi/remote/handlers/pull.mjs.map +1 -1
- package/dist/strapi/remote/handlers/push.js.map +1 -1
- package/dist/strapi/remote/handlers/push.mjs.map +1 -1
- package/dist/strapi/remote/handlers/utils.js.map +1 -1
- package/dist/strapi/remote/handlers/utils.mjs.map +1 -1
- package/dist/utils/diagnostic.js.map +1 -1
- package/dist/utils/diagnostic.mjs.map +1 -1
- package/dist/utils/encryption/decrypt.d.ts +3 -3
- package/dist/utils/encryption/decrypt.d.ts.map +1 -1
- package/dist/utils/encryption/decrypt.js +1 -1
- package/dist/utils/encryption/decrypt.js.map +1 -1
- package/dist/utils/encryption/decrypt.mjs +1 -1
- package/dist/utils/encryption/decrypt.mjs.map +1 -1
- package/dist/utils/encryption/encrypt.d.ts +3 -3
- package/dist/utils/encryption/encrypt.d.ts.map +1 -1
- package/dist/utils/encryption/encrypt.js +1 -1
- package/dist/utils/encryption/encrypt.js.map +1 -1
- package/dist/utils/encryption/encrypt.mjs +1 -1
- package/dist/utils/encryption/encrypt.mjs.map +1 -1
- package/dist/utils/providers.js.map +1 -1
- package/dist/utils/providers.mjs.map +1 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","sources":["../../../../src/file/providers/destination/utils.ts"],"sourcesContent":["import { Writable } from 'stream';\nimport { posix } from 'path';\nimport tar from 'tar-stream';\n\n/**\n * Create a file path factory for a given path & prefix.\n * Upon being called, the factory will return a file path for a given index\n */\nexport const createFilePathFactory =\n (type: string) =>\n (fileIndex = 0): string => {\n // always write tar files with posix paths so we have a standard format for paths regardless of system\n return posix.join(\n // \"{type}\" directory\n type,\n // \"${type}_XXXXX.jsonl\" file\n `${type}_${String(fileIndex).padStart(5, '0')}.jsonl`\n );\n };\n\nexport const createTarEntryStream = (\n archive: tar.Pack,\n pathFactory: (index?: number) => string,\n maxSize = 2.56e8\n) => {\n let fileIndex = 0;\n let buffer = '';\n\n const flush = async () => {\n if (!buffer) {\n return;\n }\n\n fileIndex += 1;\n const name = pathFactory(fileIndex);\n const size = buffer.length;\n\n await new Promise<void>((resolve, reject) => {\n archive.entry({ name, size }, buffer, (err) => {\n if (err) {\n reject(err);\n }\n\n resolve();\n });\n });\n\n buffer = '';\n };\n\n const push = (chunk: string | Buffer) => {\n buffer += chunk;\n };\n\n return new Writable({\n async destroy(err, callback) {\n await flush();\n callback(err);\n },\n\n async write(chunk, _encoding, callback) {\n const size = chunk.length;\n\n if (chunk.length > maxSize) {\n callback(new Error(`payload too large: ${chunk.length}>${maxSize}`));\n return;\n }\n\n if (buffer.length + size > maxSize) {\n await flush();\n }\n\n push(chunk);\n\n callback(null);\n },\n });\n};\n"],"names":["createFilePathFactory","type","fileIndex","posix","join","String","padStart","createTarEntryStream","archive","pathFactory","maxSize","buffer","flush","name","size","length","Promise","resolve","reject","entry","err","push","chunk","Writable","destroy","callback","write","_encoding","Error"],"mappings":";;;AAIA;;;AAGC,IACYA,MAAAA,qBAAAA,GACX,CAACC,IACD,GAAA,CAACC,YAAY,CAAC,GAAA;;QAEZ,OAAOC,KAAAA,CAAMC,IAAI;AAEfH,QAAAA,IAAAA;QAEA,
|
|
1
|
+
{"version":3,"file":"utils.mjs","sources":["../../../../src/file/providers/destination/utils.ts"],"sourcesContent":["import { Writable } from 'stream';\nimport { posix } from 'path';\nimport tar from 'tar-stream';\n\n/**\n * Create a file path factory for a given path & prefix.\n * Upon being called, the factory will return a file path for a given index\n */\nexport const createFilePathFactory =\n (type: string) =>\n (fileIndex = 0): string => {\n // always write tar files with posix paths so we have a standard format for paths regardless of system\n return posix.join(\n // \"{type}\" directory\n type,\n // \"${type}_XXXXX.jsonl\" file\n `${type}_${String(fileIndex).padStart(5, '0')}.jsonl`\n );\n };\n\nexport const createTarEntryStream = (\n archive: tar.Pack,\n pathFactory: (index?: number) => string,\n maxSize = 2.56e8\n) => {\n let fileIndex = 0;\n let buffer = '';\n\n const flush = async () => {\n if (!buffer) {\n return;\n }\n\n fileIndex += 1;\n const name = pathFactory(fileIndex);\n const size = buffer.length;\n\n await new Promise<void>((resolve, reject) => {\n archive.entry({ name, size }, buffer, (err) => {\n if (err) {\n reject(err);\n }\n\n resolve();\n });\n });\n\n buffer = '';\n };\n\n const push = (chunk: string | Buffer) => {\n buffer += chunk;\n };\n\n return new Writable({\n async destroy(err, callback) {\n await flush();\n callback(err);\n },\n\n async write(chunk, _encoding, callback) {\n const size = chunk.length;\n\n if (chunk.length > maxSize) {\n callback(new Error(`payload too large: ${chunk.length}>${maxSize}`));\n return;\n }\n\n if (buffer.length + size > maxSize) {\n await flush();\n }\n\n push(chunk);\n\n callback(null);\n },\n });\n};\n"],"names":["createFilePathFactory","type","fileIndex","posix","join","String","padStart","createTarEntryStream","archive","pathFactory","maxSize","buffer","flush","name","size","length","Promise","resolve","reject","entry","err","push","chunk","Writable","destroy","callback","write","_encoding","Error"],"mappings":";;;AAIA;;;AAGC,IACYA,MAAAA,qBAAAA,GACX,CAACC,IACD,GAAA,CAACC,YAAY,CAAC,GAAA;;QAEZ,OAAOC,KAAAA,CAAMC,IAAI;AAEfH,QAAAA,IAAAA;QAEA,CAAGA,EAAAA,IAAAA,CAAK,CAAC,EAAEI,MAAOH,CAAAA,SAAAA,CAAAA,CAAWI,QAAQ,CAAC,CAAA,EAAG,GAAK,CAAA,CAAA,MAAM,CAAC,CAAA;;MAI9CC,oBAAuB,GAAA,CAClCC,OACAC,EAAAA,WAAAA,EACAC,UAAU,MAAM,GAAA;AAEhB,IAAA,IAAIR,SAAY,GAAA,CAAA;AAChB,IAAA,IAAIS,MAAS,GAAA,EAAA;AAEb,IAAA,MAAMC,KAAQ,GAAA,UAAA;AACZ,QAAA,IAAI,CAACD,MAAQ,EAAA;AACX,YAAA;AACF;QAEAT,SAAa,IAAA,CAAA;AACb,QAAA,MAAMW,OAAOJ,WAAYP,CAAAA,SAAAA,CAAAA;QACzB,MAAMY,IAAAA,GAAOH,OAAOI,MAAM;QAE1B,MAAM,IAAIC,OAAc,CAAA,CAACC,OAASC,EAAAA,MAAAA,GAAAA;AAChCV,YAAAA,OAAAA,CAAQW,KAAK,CAAC;AAAEN,gBAAAA,IAAAA;AAAMC,gBAAAA;AAAK,aAAA,EAAGH,QAAQ,CAACS,GAAAA,GAAAA;AACrC,gBAAA,IAAIA,GAAK,EAAA;oBACPF,MAAOE,CAAAA,GAAAA,CAAAA;AACT;AAEAH,gBAAAA,OAAAA,EAAAA;AACF,aAAA,CAAA;AACF,SAAA,CAAA;QAEAN,MAAS,GAAA,EAAA;AACX,KAAA;AAEA,IAAA,MAAMU,OAAO,CAACC,KAAAA,GAAAA;QACZX,MAAUW,IAAAA,KAAAA;AACZ,KAAA;AAEA,IAAA,OAAO,IAAIC,QAAS,CAAA;QAClB,MAAMC,OAAAA,CAAAA,CAAQJ,GAAG,EAAEK,QAAQ,EAAA;YACzB,MAAMb,KAAAA,EAAAA;YACNa,QAASL,CAAAA,GAAAA,CAAAA;AACX,SAAA;AAEA,QAAA,MAAMM,KAAMJ,CAAAA,CAAAA,KAAK,EAAEK,SAAS,EAAEF,QAAQ,EAAA;YACpC,MAAMX,IAAAA,GAAOQ,MAAMP,MAAM;YAEzB,IAAIO,KAAAA,CAAMP,MAAM,GAAGL,OAAS,EAAA;gBAC1Be,QAAS,CAAA,IAAIG,KAAM,CAAA,CAAC,mBAAmB,EAAEN,MAAMP,MAAM,CAAC,CAAC,EAAEL,OAAS,CAAA,CAAA,CAAA,CAAA;AAClE,gBAAA;AACF;AAEA,YAAA,IAAIC,MAAOI,CAAAA,MAAM,GAAGD,IAAAA,GAAOJ,OAAS,EAAA;gBAClC,MAAME,KAAAA,EAAAA;AACR;YAEAS,IAAKC,CAAAA,KAAAA,CAAAA;YAELG,QAAS,CAAA,IAAA,CAAA;AACX;AACF,KAAA,CAAA;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/file/providers/source/index.ts"],"sourcesContent":["import type { Readable } from 'stream';\n\nimport zip from 'zlib';\nimport path from 'path';\nimport { pipeline, PassThrough } from 'stream';\nimport fs from 'fs-extra';\nimport tar from 'tar';\nimport { isEmpty, keyBy } from 'lodash/fp';\nimport { chain } from 'stream-chain';\nimport { parser } from 'stream-json/jsonl/Parser';\nimport type { Struct } from '@strapi/types';\n\nimport type { IAsset, IMetadata, ISourceProvider, ProviderType, IFile } from '../../../../types';\nimport type { IDiagnosticReporter } from '../../../utils/diagnostic';\n\nimport * as utils from '../../../utils';\nimport { ProviderInitializationError, ProviderTransferError } from '../../../errors/providers';\nimport { isFilePathInDirname, isPathEquivalent, unknownPathToPosix } from './utils';\n\ntype StreamItemArray = Parameters<typeof chain>[0];\n\n/**\n * Constant for the metadata file path\n */\nconst METADATA_FILE_PATH = 'metadata.json';\n\n/**\n * Provider options\n */\nexport interface ILocalFileSourceProviderOptions {\n file: {\n path: string; // the file to load\n };\n\n encryption: {\n enabled: boolean; // if the file is encrypted (and should be decrypted)\n key?: string; // the key to decrypt the file\n };\n\n compression: {\n enabled: boolean; // if the file is compressed (and should be decompressed)\n };\n}\n\nexport const createLocalFileSourceProvider = (options: ILocalFileSourceProviderOptions) => {\n return new LocalFileSourceProvider(options);\n};\n\nclass LocalFileSourceProvider implements ISourceProvider {\n type: ProviderType = 'source';\n\n name = 'source::local-file';\n\n options: ILocalFileSourceProviderOptions;\n\n #metadata?: IMetadata;\n\n #diagnostics?: IDiagnosticReporter;\n\n constructor(options: ILocalFileSourceProviderOptions) {\n this.options = options;\n\n const { encryption } = this.options;\n\n if (encryption.enabled && encryption.key === undefined) {\n throw new Error('Missing encryption key');\n }\n }\n\n #reportInfo(message: string) {\n this.#diagnostics?.report({\n details: {\n createdAt: new Date(),\n message,\n origin: 'file-source-provider',\n },\n kind: 'info',\n });\n }\n\n /**\n * Pre flight checks regarding the provided options, making sure that the file can be opened (decrypted, decompressed), etc.\n */\n async bootstrap(diagnostics: IDiagnosticReporter) {\n this.#diagnostics = diagnostics;\n const { path: filePath } = this.options.file;\n\n try {\n // Read the metadata to ensure the file can be parsed\n await this.#loadMetadata();\n // TODO: we might also need to read the schema.jsonl files & implements a custom stream-check\n } catch (e) {\n if (this.options?.encryption?.enabled) {\n throw new ProviderInitializationError(\n `Key is incorrect or the file '${filePath}' is not a valid Strapi data file.`\n );\n }\n throw new ProviderInitializationError(`File '${filePath}' is not a valid Strapi data file.`);\n }\n\n if (!this.#metadata) {\n throw new ProviderInitializationError('Could not load metadata from Strapi data file.');\n }\n }\n\n async #loadMetadata() {\n const backupStream = this.#getBackupStream();\n this.#metadata = await this.#parseJSONFile<IMetadata>(backupStream, METADATA_FILE_PATH);\n }\n\n async #loadAssetMetadata(path: string) {\n const backupStream = this.#getBackupStream();\n return this.#parseJSONFile<IFile>(backupStream, path);\n }\n\n async getMetadata() {\n this.#reportInfo('getting metadata');\n if (!this.#metadata) {\n await this.#loadMetadata();\n }\n\n return this.#metadata ?? null;\n }\n\n async getSchemas() {\n this.#reportInfo('getting schemas');\n const schemaCollection = await utils.stream.collect<Struct.Schema>(\n this.createSchemasReadStream()\n );\n\n if (isEmpty(schemaCollection)) {\n throw new ProviderInitializationError('Could not load schemas from Strapi data file.');\n }\n\n // Group schema by UID\n const schemas = keyBy('uid', schemaCollection);\n\n // Transform to valid JSON\n return utils.schema.schemasToValidJSON(schemas);\n }\n\n createEntitiesReadStream(): Readable {\n this.#reportInfo('creating entities read stream');\n return this.#streamJsonlDirectory('entities');\n }\n\n createSchemasReadStream(): Readable {\n this.#reportInfo('creating schemas read stream');\n return this.#streamJsonlDirectory('schemas');\n }\n\n createLinksReadStream(): Readable {\n this.#reportInfo('creating links read stream');\n return this.#streamJsonlDirectory('links');\n }\n\n createConfigurationReadStream(): Readable {\n this.#reportInfo('creating configuration read stream');\n // NOTE: TBD\n return this.#streamJsonlDirectory('configuration');\n }\n\n createAssetsReadStream(): Readable | Promise<Readable> {\n const inStream = this.#getBackupStream();\n const outStream = new PassThrough({ objectMode: true });\n const loadAssetMetadata = this.#loadAssetMetadata.bind(this);\n this.#reportInfo('creating assets read stream');\n\n pipeline(\n [\n inStream,\n new tar.Parse({\n // find only files in the assets/uploads folder\n filter(filePath, entry) {\n if (entry.type !== 'File') {\n return false;\n }\n return isFilePathInDirname('assets/uploads', filePath);\n },\n async onentry(entry) {\n const { path: filePath, size = 0 } = entry;\n const normalizedPath = unknownPathToPosix(filePath);\n const file = path.basename(normalizedPath);\n let metadata;\n try {\n metadata = await loadAssetMetadata(`assets/metadata/${file}.json`);\n } catch (error) {\n throw new Error(`Failed to read metadata for ${file}`);\n }\n const asset: IAsset = {\n metadata,\n filename: file,\n filepath: normalizedPath,\n stats: { size },\n stream: entry as unknown as Readable,\n };\n outStream.write(asset);\n },\n }),\n ],\n () => outStream.end()\n );\n\n return outStream;\n }\n\n #getBackupStream() {\n const { file, encryption, compression } = this.options;\n\n const streams: StreamItemArray = [];\n\n try {\n streams.push(fs.createReadStream(file.path));\n } catch (e) {\n throw new Error(`Could not read backup file path provided at \"${this.options.file.path}\"`);\n }\n\n if (encryption.enabled && encryption.key) {\n streams.push(utils.encryption.createDecryptionCipher(encryption.key));\n }\n\n if (compression.enabled) {\n streams.push(zip.createGunzip());\n }\n\n return chain(streams);\n }\n\n // `directory` must be posix formatted path\n #streamJsonlDirectory(directory: string) {\n const inStream = this.#getBackupStream();\n\n const outStream = new PassThrough({ objectMode: true });\n\n pipeline(\n [\n inStream,\n new tar.Parse({\n filter(filePath, entry) {\n if (entry.type !== 'File') {\n return false;\n }\n\n return isFilePathInDirname(directory, filePath);\n },\n\n async onentry(entry) {\n const transforms = [\n // JSONL parser to read the data chunks one by one (line by line)\n parser({\n checkErrors: true,\n }),\n // The JSONL parser returns each line as key/value\n (line: { key: string; value: object }) => line.value,\n ];\n\n const stream = entry.pipe(chain(transforms));\n\n try {\n for await (const chunk of stream) {\n outStream.write(chunk);\n }\n } catch (e: unknown) {\n outStream.destroy(\n new ProviderTransferError(\n `Error parsing backup files from backup file ${entry.path}: ${\n (e as Error).message\n }`,\n {\n details: {\n error: e,\n },\n }\n )\n );\n }\n },\n }),\n ],\n async () => {\n // Manually send the 'end' event to the out stream\n // once every entry has finished streaming its content\n outStream.end();\n }\n );\n\n return outStream;\n }\n\n // For collecting an entire JSON file then parsing it, not for streaming JSONL\n async #parseJSONFile<T extends object>(fileStream: Readable, filePath: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n pipeline(\n [\n fileStream,\n // Custom backup archive parsing\n new tar.Parse({\n /**\n * Filter the parsed entries to only keep the one that matches the given filepath\n */\n filter(entryPath, entry) {\n if (entry.type !== 'File') {\n return false;\n }\n\n return isPathEquivalent(entryPath, filePath);\n },\n\n async onentry(entry) {\n // Collect all the content of the entry file\n const content = await entry.collect();\n\n try {\n // Parse from buffer array to string to JSON\n const parsedContent = JSON.parse(Buffer.concat(content).toString());\n\n // Resolve the Promise with the parsed content\n resolve(parsedContent);\n } catch (e) {\n reject(e);\n } finally {\n // Cleanup (close the stream associated to the entry)\n entry.destroy();\n }\n },\n }),\n ],\n () => {\n // If the promise hasn't been resolved and we've parsed all\n // the archive entries, then the file doesn't exist\n reject(new Error(`File \"${filePath}\" not found`));\n }\n );\n });\n }\n}\n"],"names":["METADATA_FILE_PATH","createLocalFileSourceProvider","options","LocalFileSourceProvider","bootstrap","diagnostics","path","filePath","file","loadMetadata","e","encryption","enabled","ProviderInitializationError","metadata","getMetadata","reportInfo","getSchemas","schemaCollection","utils","createSchemasReadStream","isEmpty","schemas","keyBy","createEntitiesReadStream","streamJsonlDirectory","createLinksReadStream","createConfigurationReadStream","createAssetsReadStream","inStream","getBackupStream","outStream","PassThrough","objectMode","loadAssetMetadata","bind","pipeline","tar","Parse","filter","entry","type","isFilePathInDirname","onentry","size","normalizedPath","unknownPathToPosix","basename","error","Error","asset","filename","filepath","stats","stream","write","end","constructor","name","key","undefined","message","report","details","createdAt","Date","origin","kind","backupStream","parseJSONFile","compression","streams","push","fs","createReadStream","zip","createGunzip","chain","directory","transforms","parser","checkErrors","line","value","pipe","chunk","destroy","ProviderTransferError","fileStream","Promise","resolve","reject","entryPath","isPathEquivalent","content","collect","parsedContent","JSON","parse","Buffer","concat","toString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA;;AAEC,IACD,MAAMA,kBAAqB,GAAA,eAAA;AAoBpB,MAAMC,gCAAgC,CAACC,OAAAA,GAAAA;AAC5C,IAAA,OAAO,IAAIC,uBAAwBD,CAAAA,OAAAA,CAAAA;AACrC;AASE,IAAA,SAAA,iBAAA,8BAAA,CAAA,WAAA,CAAA,EAEA,YAYA,iBAAA,8BAAA,CAAA,cAAA,CAAA,EAAA,WAAA,iBAAA,8BAAA,CAAA,aAAA,CAAA,EAoCM,aAKA,iBAAA,8BAAA,CAAA,eAAA,CAAA,EAAA,kBAAA,iBAAA,8BAAA,CAAA,oBAAA,CAAA,EAgGN;AAuBA,qBA6DM,iBAAA,8BAAA,CAAA,uBAAA,CAAA,EAAA,cAAA,iBAAA,8BAAA,CAAA,gBAAA,CAAA;AAlPR,MAAMC,uBAAAA,CAAAA;AAgCJ;;MAGA,MAAMC,SAAUC,CAAAA,WAAgC,EAAE;QAChD,+BAAA,CAAA,IAAI,EAAEA,YAAAA,CAAAA,CAAAA,YAAcA,CAAAA,GAAAA,WAAAA;QACpB,MAAM,EAAEC,MAAMC,QAAQ,EAAE,GAAG,IAAI,CAACL,OAAO,CAACM,IAAI;QAE5C,IAAI;;YAEF,MAAM,+BAAA,CAAA,IAAI,EAAEC,aAAAA,CAAAA,CAAAA,aAAAA,CAAAA,EAAAA;;AAEd,SAAA,CAAE,OAAOC,CAAG,EAAA;AACV,YAAA,IAAI,IAAI,CAACR,OAAO,EAAES,YAAYC,OAAS,EAAA;AACrC,gBAAA,MAAM,IAAIC,qCACR,CAAA,CAAC,8BAA8B,EAAEN,QAAAA,CAAS,kCAAkC,CAAC,CAAA;AAEjF;AACA,YAAA,MAAM,IAAIM,qCAA4B,CAAA,CAAC,MAAM,EAAEN,QAAA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AASC,EAAAA,MAAAA,GAAAA;QAC9BvD,iBACE,CAAA;AACEoD,YAAAA,UAAAA;;YAEA,IAAInD,GAAAA,CAAIC,KAAK,CAAC;AACZ;;gBAGAC,MAAAA,CAAAA,CAAOqD,SAAS,EAAEpD,KAAK,EAAA;oBACrB,IAAIA,KAAAA,CAAMC,IAAI,KAAK,MAAQ,EAAA;wBACzB,OAAO,KAAA;AACT;AAEA,oBAAA,OAAOoD,uBAAiBD,SAAWrF,EAAAA,QAAAA,CAAAA;AACrC,iBAAA;AAEA,gBAAA,MAAMoC,SAAQH,KAAK,EAAA;;oBAEjB,MAAMsD,OAAAA,GAAU,MAAMtD,KAAAA,CAAMuD,OAAO,EAAA;oBAEnC,IAAI;;wBAEF,MAAMC,aAAAA,GAAgBC,KAAKC,KAAK,CAACC,OAAOC,MAAM,CAACN,SAASO,QAAQ,EAAA,CAAA;;wBAGhEX,OAAQM,CAAAA,aAAAA,CAAAA;AACV,qBAAA,CAAE,OAAOtF,CAAG,EAAA;wBACViF,MAAOjF,CAAAA,CAAAA,CAAAA;qBACC,QAAA;;AAER8B,wBAAAA,KAAAA,CAAM8C,OAAO,EAAA;AACf;AACF;AACF,aAAA;SACD,EACD,IAAA;;;AAGEK,YAAAA,MAAAA,CAAO,IAAI1C,KAAM,CAAA,CAAC,MAAM,EAAE1C,QAAAA,CAAS,WAAW,CAAC,CAAA,CAAA;AACjD,SAAA,CAAA;AAEJ,KAAA,CAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/file/providers/source/index.ts"],"sourcesContent":["import type { Readable } from 'stream';\n\nimport zip from 'zlib';\nimport path from 'path';\nimport { pipeline, PassThrough } from 'stream';\nimport fs from 'fs-extra';\nimport tar from 'tar';\nimport { isEmpty, keyBy } from 'lodash/fp';\nimport { chain } from 'stream-chain';\nimport { parser } from 'stream-json/jsonl/Parser';\nimport type { Struct } from '@strapi/types';\n\nimport type { IAsset, IMetadata, ISourceProvider, ProviderType, IFile } from '../../../../types';\nimport type { IDiagnosticReporter } from '../../../utils/diagnostic';\n\nimport * as utils from '../../../utils';\nimport { ProviderInitializationError, ProviderTransferError } from '../../../errors/providers';\nimport { isFilePathInDirname, isPathEquivalent, unknownPathToPosix } from './utils';\n\ntype StreamItemArray = Parameters<typeof chain>[0];\n\n/**\n * Constant for the metadata file path\n */\nconst METADATA_FILE_PATH = 'metadata.json';\n\n/**\n * Provider options\n */\nexport interface ILocalFileSourceProviderOptions {\n file: {\n path: string; // the file to load\n };\n\n encryption: {\n enabled: boolean; // if the file is encrypted (and should be decrypted)\n key?: string; // the key to decrypt the file\n };\n\n compression: {\n enabled: boolean; // if the file is compressed (and should be decompressed)\n };\n}\n\nexport const createLocalFileSourceProvider = (options: ILocalFileSourceProviderOptions) => {\n return new LocalFileSourceProvider(options);\n};\n\nclass LocalFileSourceProvider implements ISourceProvider {\n type: ProviderType = 'source';\n\n name = 'source::local-file';\n\n options: ILocalFileSourceProviderOptions;\n\n #metadata?: IMetadata;\n\n #diagnostics?: IDiagnosticReporter;\n\n constructor(options: ILocalFileSourceProviderOptions) {\n this.options = options;\n\n const { encryption } = this.options;\n\n if (encryption.enabled && encryption.key === undefined) {\n throw new Error('Missing encryption key');\n }\n }\n\n #reportInfo(message: string) {\n this.#diagnostics?.report({\n details: {\n createdAt: new Date(),\n message,\n origin: 'file-source-provider',\n },\n kind: 'info',\n });\n }\n\n /**\n * Pre flight checks regarding the provided options, making sure that the file can be opened (decrypted, decompressed), etc.\n */\n async bootstrap(diagnostics: IDiagnosticReporter) {\n this.#diagnostics = diagnostics;\n const { path: filePath } = this.options.file;\n\n try {\n // Read the metadata to ensure the file can be parsed\n await this.#loadMetadata();\n // TODO: we might also need to read the schema.jsonl files & implements a custom stream-check\n } catch (e) {\n if (this.options?.encryption?.enabled) {\n throw new ProviderInitializationError(\n `Key is incorrect or the file '${filePath}' is not a valid Strapi data file.`\n );\n }\n throw new ProviderInitializationError(`File '${filePath}' is not a valid Strapi data file.`);\n }\n\n if (!this.#metadata) {\n throw new ProviderInitializationError('Could not load metadata from Strapi data file.');\n }\n }\n\n async #loadMetadata() {\n const backupStream = this.#getBackupStream();\n this.#metadata = await this.#parseJSONFile<IMetadata>(backupStream, METADATA_FILE_PATH);\n }\n\n async #loadAssetMetadata(path: string) {\n const backupStream = this.#getBackupStream();\n return this.#parseJSONFile<IFile>(backupStream, path);\n }\n\n async getMetadata() {\n this.#reportInfo('getting metadata');\n if (!this.#metadata) {\n await this.#loadMetadata();\n }\n\n return this.#metadata ?? null;\n }\n\n async getSchemas() {\n this.#reportInfo('getting schemas');\n const schemaCollection = await utils.stream.collect<Struct.Schema>(\n this.createSchemasReadStream()\n );\n\n if (isEmpty(schemaCollection)) {\n throw new ProviderInitializationError('Could not load schemas from Strapi data file.');\n }\n\n // Group schema by UID\n const schemas = keyBy('uid', schemaCollection);\n\n // Transform to valid JSON\n return utils.schema.schemasToValidJSON(schemas);\n }\n\n createEntitiesReadStream(): Readable {\n this.#reportInfo('creating entities read stream');\n return this.#streamJsonlDirectory('entities');\n }\n\n createSchemasReadStream(): Readable {\n this.#reportInfo('creating schemas read stream');\n return this.#streamJsonlDirectory('schemas');\n }\n\n createLinksReadStream(): Readable {\n this.#reportInfo('creating links read stream');\n return this.#streamJsonlDirectory('links');\n }\n\n createConfigurationReadStream(): Readable {\n this.#reportInfo('creating configuration read stream');\n // NOTE: TBD\n return this.#streamJsonlDirectory('configuration');\n }\n\n createAssetsReadStream(): Readable | Promise<Readable> {\n const inStream = this.#getBackupStream();\n const outStream = new PassThrough({ objectMode: true });\n const loadAssetMetadata = this.#loadAssetMetadata.bind(this);\n this.#reportInfo('creating assets read stream');\n\n pipeline(\n [\n inStream,\n new tar.Parse({\n // find only files in the assets/uploads folder\n filter(filePath, entry) {\n if (entry.type !== 'File') {\n return false;\n }\n return isFilePathInDirname('assets/uploads', filePath);\n },\n async onentry(entry) {\n const { path: filePath, size = 0 } = entry;\n const normalizedPath = unknownPathToPosix(filePath);\n const file = path.basename(normalizedPath);\n let metadata;\n try {\n metadata = await loadAssetMetadata(`assets/metadata/${file}.json`);\n } catch (error) {\n throw new Error(`Failed to read metadata for ${file}`);\n }\n const asset: IAsset = {\n metadata,\n filename: file,\n filepath: normalizedPath,\n stats: { size },\n stream: entry as unknown as Readable,\n };\n outStream.write(asset);\n },\n }),\n ],\n () => outStream.end()\n );\n\n return outStream;\n }\n\n #getBackupStream() {\n const { file, encryption, compression } = this.options;\n\n const streams: StreamItemArray = [];\n\n try {\n streams.push(fs.createReadStream(file.path));\n } catch (e) {\n throw new Error(`Could not read backup file path provided at \"${this.options.file.path}\"`);\n }\n\n if (encryption.enabled && encryption.key) {\n streams.push(utils.encryption.createDecryptionCipher(encryption.key));\n }\n\n if (compression.enabled) {\n streams.push(zip.createGunzip());\n }\n\n return chain(streams);\n }\n\n // `directory` must be posix formatted path\n #streamJsonlDirectory(directory: string) {\n const inStream = this.#getBackupStream();\n\n const outStream = new PassThrough({ objectMode: true });\n\n pipeline(\n [\n inStream,\n new tar.Parse({\n filter(filePath, entry) {\n if (entry.type !== 'File') {\n return false;\n }\n\n return isFilePathInDirname(directory, filePath);\n },\n\n async onentry(entry) {\n const transforms = [\n // JSONL parser to read the data chunks one by one (line by line)\n parser({\n checkErrors: true,\n }),\n // The JSONL parser returns each line as key/value\n (line: { key: string; value: object }) => line.value,\n ];\n\n const stream = entry.pipe(chain(transforms));\n\n try {\n for await (const chunk of stream) {\n outStream.write(chunk);\n }\n } catch (e: unknown) {\n outStream.destroy(\n new ProviderTransferError(\n `Error parsing backup files from backup file ${entry.path}: ${\n (e as Error).message\n }`,\n {\n details: {\n error: e,\n },\n }\n )\n );\n }\n },\n }),\n ],\n async () => {\n // Manually send the 'end' event to the out stream\n // once every entry has finished streaming its content\n outStream.end();\n }\n );\n\n return outStream;\n }\n\n // For collecting an entire JSON file then parsing it, not for streaming JSONL\n async #parseJSONFile<T extends object>(fileStream: Readable, filePath: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n pipeline(\n [\n fileStream,\n // Custom backup archive parsing\n new tar.Parse({\n /**\n * Filter the parsed entries to only keep the one that matches the given filepath\n */\n filter(entryPath, entry) {\n if (entry.type !== 'File') {\n return false;\n }\n\n return isPathEquivalent(entryPath, filePath);\n },\n\n async onentry(entry) {\n // Collect all the content of the entry file\n const content = await entry.collect();\n\n try {\n // Parse from buffer array to string to JSON\n const parsedContent = JSON.parse(Buffer.concat(content).toString());\n\n // Resolve the Promise with the parsed content\n resolve(parsedContent);\n } catch (e) {\n reject(e);\n } finally {\n // Cleanup (close the stream associated to the entry)\n entry.destroy();\n }\n },\n }),\n ],\n () => {\n // If the promise hasn't been resolved and we've parsed all\n // the archive entries, then the file doesn't exist\n reject(new Error(`File \"${filePath}\" not found`));\n }\n );\n });\n }\n}\n"],"names":["METADATA_FILE_PATH","createLocalFileSourceProvider","options","LocalFileSourceProvider","bootstrap","diagnostics","path","filePath","file","e","encryption","enabled","ProviderInitializationError","getMetadata","getSchemas","schemaCollection","utils","createSchemasReadStream","isEmpty","schemas","keyBy","createEntitiesReadStream","createLinksReadStream","createConfigurationReadStream","createAssetsReadStream","inStream","outStream","PassThrough","objectMode","loadAssetMetadata","bind","pipeline","tar","Parse","filter","entry","type","isFilePathInDirname","onentry","size","normalizedPath","unknownPathToPosix","basename","metadata","error","Error","asset","filename","filepath","stats","stream","write","end","name","key","undefined","message","report","details","createdAt","Date","origin","kind","backupStream","compression","streams","push","fs","createReadStream","zip","createGunzip","chain","directory","transforms","parser","checkErrors","line","value","pipe","chunk","destroy","ProviderTransferError","fileStream","Promise","resolve","reject","entryPath","isPathEquivalent","content","collect","parsedContent","JSON","parse","Buffer","concat","toString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA;;AAEC,IACD,MAAMA,kBAAqB,GAAA,eAAA;AAoBpB,MAAMC,gCAAgC,CAACC,OAAAA,GAAAA;AAC5C,IAAA,OAAO,IAAIC,uBAAwBD,CAAAA,OAAAA,CAAAA;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A;oBAEnC,IAAI;;wBAEF,MAAMC,aAAAA,GAAgBC,KAAKC,KAAK,CAACC,OAAOC,MAAM,CAACN,SAASO,QAAQ,EAAA,CAAA;;wBAGhEX,OAAQM,CAAAA,aAAAA,CAAAA;AACV,qBAAA,CAAE,OAAOjF,CAAG,EAAA;wBACV4E,MAAO5E,CAAAA,CAAAA,CAAAA;qBACC,QAAA;;AAER0B,wBAAAA,KAAAA,CAAM6C,OAAO,EAAA;AACf;AACF;AACF,aAAA;SACD,EACD,IAAA;;;AAGEK,YAAAA,MAAAA,CAAO,IAAIxC,KAAM,CAAA,CAAC,MAAM,EAAEtC,QAAAA,CAAS,WAAW,CAAC,CAAA,CAAA;AACjD,SAAA,CAAA;AAEJ,KAAA,CAAA;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../../../src/file/providers/source/index.ts"],"sourcesContent":["import type { Readable } from 'stream';\n\nimport zip from 'zlib';\nimport path from 'path';\nimport { pipeline, PassThrough } from 'stream';\nimport fs from 'fs-extra';\nimport tar from 'tar';\nimport { isEmpty, keyBy } from 'lodash/fp';\nimport { chain } from 'stream-chain';\nimport { parser } from 'stream-json/jsonl/Parser';\nimport type { Struct } from '@strapi/types';\n\nimport type { IAsset, IMetadata, ISourceProvider, ProviderType, IFile } from '../../../../types';\nimport type { IDiagnosticReporter } from '../../../utils/diagnostic';\n\nimport * as utils from '../../../utils';\nimport { ProviderInitializationError, ProviderTransferError } from '../../../errors/providers';\nimport { isFilePathInDirname, isPathEquivalent, unknownPathToPosix } from './utils';\n\ntype StreamItemArray = Parameters<typeof chain>[0];\n\n/**\n * Constant for the metadata file path\n */\nconst METADATA_FILE_PATH = 'metadata.json';\n\n/**\n * Provider options\n */\nexport interface ILocalFileSourceProviderOptions {\n file: {\n path: string; // the file to load\n };\n\n encryption: {\n enabled: boolean; // if the file is encrypted (and should be decrypted)\n key?: string; // the key to decrypt the file\n };\n\n compression: {\n enabled: boolean; // if the file is compressed (and should be decompressed)\n };\n}\n\nexport const createLocalFileSourceProvider = (options: ILocalFileSourceProviderOptions) => {\n return new LocalFileSourceProvider(options);\n};\n\nclass LocalFileSourceProvider implements ISourceProvider {\n type: ProviderType = 'source';\n\n name = 'source::local-file';\n\n options: ILocalFileSourceProviderOptions;\n\n #metadata?: IMetadata;\n\n #diagnostics?: IDiagnosticReporter;\n\n constructor(options: ILocalFileSourceProviderOptions) {\n this.options = options;\n\n const { encryption } = this.options;\n\n if (encryption.enabled && encryption.key === undefined) {\n throw new Error('Missing encryption key');\n }\n }\n\n #reportInfo(message: string) {\n this.#diagnostics?.report({\n details: {\n createdAt: new Date(),\n message,\n origin: 'file-source-provider',\n },\n kind: 'info',\n });\n }\n\n /**\n * Pre flight checks regarding the provided options, making sure that the file can be opened (decrypted, decompressed), etc.\n */\n async bootstrap(diagnostics: IDiagnosticReporter) {\n this.#diagnostics = diagnostics;\n const { path: filePath } = this.options.file;\n\n try {\n // Read the metadata to ensure the file can be parsed\n await this.#loadMetadata();\n // TODO: we might also need to read the schema.jsonl files & implements a custom stream-check\n } catch (e) {\n if (this.options?.encryption?.enabled) {\n throw new ProviderInitializationError(\n `Key is incorrect or the file '${filePath}' is not a valid Strapi data file.`\n );\n }\n throw new ProviderInitializationError(`File '${filePath}' is not a valid Strapi data file.`);\n }\n\n if (!this.#metadata) {\n throw new ProviderInitializationError('Could not load metadata from Strapi data file.');\n }\n }\n\n async #loadMetadata() {\n const backupStream = this.#getBackupStream();\n this.#metadata = await this.#parseJSONFile<IMetadata>(backupStream, METADATA_FILE_PATH);\n }\n\n async #loadAssetMetadata(path: string) {\n const backupStream = this.#getBackupStream();\n return this.#parseJSONFile<IFile>(backupStream, path);\n }\n\n async getMetadata() {\n this.#reportInfo('getting metadata');\n if (!this.#metadata) {\n await this.#loadMetadata();\n }\n\n return this.#metadata ?? null;\n }\n\n async getSchemas() {\n this.#reportInfo('getting schemas');\n const schemaCollection = await utils.stream.collect<Struct.Schema>(\n this.createSchemasReadStream()\n );\n\n if (isEmpty(schemaCollection)) {\n throw new ProviderInitializationError('Could not load schemas from Strapi data file.');\n }\n\n // Group schema by UID\n const schemas = keyBy('uid', schemaCollection);\n\n // Transform to valid JSON\n return utils.schema.schemasToValidJSON(schemas);\n }\n\n createEntitiesReadStream(): Readable {\n this.#reportInfo('creating entities read stream');\n return this.#streamJsonlDirectory('entities');\n }\n\n createSchemasReadStream(): Readable {\n this.#reportInfo('creating schemas read stream');\n return this.#streamJsonlDirectory('schemas');\n }\n\n createLinksReadStream(): Readable {\n this.#reportInfo('creating links read stream');\n return this.#streamJsonlDirectory('links');\n }\n\n createConfigurationReadStream(): Readable {\n this.#reportInfo('creating configuration read stream');\n // NOTE: TBD\n return this.#streamJsonlDirectory('configuration');\n }\n\n createAssetsReadStream(): Readable | Promise<Readable> {\n const inStream = this.#getBackupStream();\n const outStream = new PassThrough({ objectMode: true });\n const loadAssetMetadata = this.#loadAssetMetadata.bind(this);\n this.#reportInfo('creating assets read stream');\n\n pipeline(\n [\n inStream,\n new tar.Parse({\n // find only files in the assets/uploads folder\n filter(filePath, entry) {\n if (entry.type !== 'File') {\n return false;\n }\n return isFilePathInDirname('assets/uploads', filePath);\n },\n async onentry(entry) {\n const { path: filePath, size = 0 } = entry;\n const normalizedPath = unknownPathToPosix(filePath);\n const file = path.basename(normalizedPath);\n let metadata;\n try {\n metadata = await loadAssetMetadata(`assets/metadata/${file}.json`);\n } catch (error) {\n throw new Error(`Failed to read metadata for ${file}`);\n }\n const asset: IAsset = {\n metadata,\n filename: file,\n filepath: normalizedPath,\n stats: { size },\n stream: entry as unknown as Readable,\n };\n outStream.write(asset);\n },\n }),\n ],\n () => outStream.end()\n );\n\n return outStream;\n }\n\n #getBackupStream() {\n const { file, encryption, compression } = this.options;\n\n const streams: StreamItemArray = [];\n\n try {\n streams.push(fs.createReadStream(file.path));\n } catch (e) {\n throw new Error(`Could not read backup file path provided at \"${this.options.file.path}\"`);\n }\n\n if (encryption.enabled && encryption.key) {\n streams.push(utils.encryption.createDecryptionCipher(encryption.key));\n }\n\n if (compression.enabled) {\n streams.push(zip.createGunzip());\n }\n\n return chain(streams);\n }\n\n // `directory` must be posix formatted path\n #streamJsonlDirectory(directory: string) {\n const inStream = this.#getBackupStream();\n\n const outStream = new PassThrough({ objectMode: true });\n\n pipeline(\n [\n inStream,\n new tar.Parse({\n filter(filePath, entry) {\n if (entry.type !== 'File') {\n return false;\n }\n\n return isFilePathInDirname(directory, filePath);\n },\n\n async onentry(entry) {\n const transforms = [\n // JSONL parser to read the data chunks one by one (line by line)\n parser({\n checkErrors: true,\n }),\n // The JSONL parser returns each line as key/value\n (line: { key: string; value: object }) => line.value,\n ];\n\n const stream = entry.pipe(chain(transforms));\n\n try {\n for await (const chunk of stream) {\n outStream.write(chunk);\n }\n } catch (e: unknown) {\n outStream.destroy(\n new ProviderTransferError(\n `Error parsing backup files from backup file ${entry.path}: ${\n (e as Error).message\n }`,\n {\n details: {\n error: e,\n },\n }\n )\n );\n }\n },\n }),\n ],\n async () => {\n // Manually send the 'end' event to the out stream\n // once every entry has finished streaming its content\n outStream.end();\n }\n );\n\n return outStream;\n }\n\n // For collecting an entire JSON file then parsing it, not for streaming JSONL\n async #parseJSONFile<T extends object>(fileStream: Readable, filePath: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n pipeline(\n [\n fileStream,\n // Custom backup archive parsing\n new tar.Parse({\n /**\n * Filter the parsed entries to only keep the one that matches the given filepath\n */\n filter(entryPath, entry) {\n if (entry.type !== 'File') {\n return false;\n }\n\n return isPathEquivalent(entryPath, filePath);\n },\n\n async onentry(entry) {\n // Collect all the content of the entry file\n const content = await entry.collect();\n\n try {\n // Parse from buffer array to string to JSON\n const parsedContent = JSON.parse(Buffer.concat(content).toString());\n\n // Resolve the Promise with the parsed content\n resolve(parsedContent);\n } catch (e) {\n reject(e);\n } finally {\n // Cleanup (close the stream associated to the entry)\n entry.destroy();\n }\n },\n }),\n ],\n () => {\n // If the promise hasn't been resolved and we've parsed all\n // the archive entries, then the file doesn't exist\n reject(new Error(`File \"${filePath}\" not found`));\n }\n );\n });\n }\n}\n"],"names":["METADATA_FILE_PATH","createLocalFileSourceProvider","options","LocalFileSourceProvider","bootstrap","diagnostics","path","filePath","file","loadMetadata","e","encryption","enabled","ProviderInitializationError","metadata","getMetadata","reportInfo","getSchemas","schemaCollection","utils","createSchemasReadStream","isEmpty","schemas","keyBy","createEntitiesReadStream","streamJsonlDirectory","createLinksReadStream","createConfigurationReadStream","createAssetsReadStream","inStream","getBackupStream","outStream","PassThrough","objectMode","loadAssetMetadata","bind","pipeline","tar","Parse","filter","entry","type","isFilePathInDirname","onentry","size","normalizedPath","unknownPathToPosix","basename","error","Error","asset","filename","filepath","stats","stream","write","end","constructor","name","key","undefined","message","report","details","createdAt","Date","origin","kind","backupStream","parseJSONFile","compression","streams","push","fs","createReadStream","zip","createGunzip","chain","directory","transforms","parser","checkErrors","line","value","pipe","chunk","destroy","ProviderTransferError","fileStream","Promise","resolve","reject","entryPath","isPathEquivalent","content","collect","parsedContent","JSON","parse","Buffer","concat","toString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA;;AAEC,IACD,MAAMA,kBAAqB,GAAA,eAAA;AAoBpB,MAAMC,gCAAgC,CAACC,OAAAA,GAAAA;AAC5C,IAAA,OAAO,IAAIC,uBAAwBD,CAAAA,OAAAA,CAAAA;AACrC;AASE,IAAA,SAAA,iBAAA,8BAAA,CAAA,WAAA,CAAA,EAEA,YAYA,iBAAA,8BAAA,CAAA,cAAA,CAAA,EAAA,WAAA,iBAAA,8BAAA,CAAA,aAAA,CAAA,EAoCM,aAKA,iBAAA,8BAAA,CAAA,eAAA,CAAA,EAAA,kBAAA,iBAAA,8BAAA,CAAA,oBAAA,CAAA,EAgGN;AAuBA,qBA6DM,iBAAA,8BAAA,CAAA,uBAAA,CAAA,EAAA,cAAA,iBAAA,8BAAA,CAAA,gBAAA,CAAA;AAlPR,MAAMC,uBAAA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BACC,QAAA;;AAER8B,wBAAAA,KAAAA,CAAM8C,OAAO,EAAA;AACf;AACF;AACF,aAAA;SACD,EACD,IAAA;;;AAGEK,YAAAA,MAAAA,CAAO,IAAI1C,KAAM,CAAA,CAAC,MAAM,EAAE1C,QAAAA,CAAS,WAAW,CAAC,CAAA,CAAA;AACjD,SAAA,CAAA;AAEJ,KAAA,CAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../../../src/file/providers/source/index.ts"],"sourcesContent":["import type { Readable } from 'stream';\n\nimport zip from 'zlib';\nimport path from 'path';\nimport { pipeline, PassThrough } from 'stream';\nimport fs from 'fs-extra';\nimport tar from 'tar';\nimport { isEmpty, keyBy } from 'lodash/fp';\nimport { chain } from 'stream-chain';\nimport { parser } from 'stream-json/jsonl/Parser';\nimport type { Struct } from '@strapi/types';\n\nimport type { IAsset, IMetadata, ISourceProvider, ProviderType, IFile } from '../../../../types';\nimport type { IDiagnosticReporter } from '../../../utils/diagnostic';\n\nimport * as utils from '../../../utils';\nimport { ProviderInitializationError, ProviderTransferError } from '../../../errors/providers';\nimport { isFilePathInDirname, isPathEquivalent, unknownPathToPosix } from './utils';\n\ntype StreamItemArray = Parameters<typeof chain>[0];\n\n/**\n * Constant for the metadata file path\n */\nconst METADATA_FILE_PATH = 'metadata.json';\n\n/**\n * Provider options\n */\nexport interface ILocalFileSourceProviderOptions {\n file: {\n path: string; // the file to load\n };\n\n encryption: {\n enabled: boolean; // if the file is encrypted (and should be decrypted)\n key?: string; // the key to decrypt the file\n };\n\n compression: {\n enabled: boolean; // if the file is compressed (and should be decompressed)\n };\n}\n\nexport const createLocalFileSourceProvider = (options: ILocalFileSourceProviderOptions) => {\n return new LocalFileSourceProvider(options);\n};\n\nclass LocalFileSourceProvider implements ISourceProvider {\n type: ProviderType = 'source';\n\n name = 'source::local-file';\n\n options: ILocalFileSourceProviderOptions;\n\n #metadata?: IMetadata;\n\n #diagnostics?: IDiagnosticReporter;\n\n constructor(options: ILocalFileSourceProviderOptions) {\n this.options = options;\n\n const { encryption } = this.options;\n\n if (encryption.enabled && encryption.key === undefined) {\n throw new Error('Missing encryption key');\n }\n }\n\n #reportInfo(message: string) {\n this.#diagnostics?.report({\n details: {\n createdAt: new Date(),\n message,\n origin: 'file-source-provider',\n },\n kind: 'info',\n });\n }\n\n /**\n * Pre flight checks regarding the provided options, making sure that the file can be opened (decrypted, decompressed), etc.\n */\n async bootstrap(diagnostics: IDiagnosticReporter) {\n this.#diagnostics = diagnostics;\n const { path: filePath } = this.options.file;\n\n try {\n // Read the metadata to ensure the file can be parsed\n await this.#loadMetadata();\n // TODO: we might also need to read the schema.jsonl files & implements a custom stream-check\n } catch (e) {\n if (this.options?.encryption?.enabled) {\n throw new ProviderInitializationError(\n `Key is incorrect or the file '${filePath}' is not a valid Strapi data file.`\n );\n }\n throw new ProviderInitializationError(`File '${filePath}' is not a valid Strapi data file.`);\n }\n\n if (!this.#metadata) {\n throw new ProviderInitializationError('Could not load metadata from Strapi data file.');\n }\n }\n\n async #loadMetadata() {\n const backupStream = this.#getBackupStream();\n this.#metadata = await this.#parseJSONFile<IMetadata>(backupStream, METADATA_FILE_PATH);\n }\n\n async #loadAssetMetadata(path: string) {\n const backupStream = this.#getBackupStream();\n return this.#parseJSONFile<IFile>(backupStream, path);\n }\n\n async getMetadata() {\n this.#reportInfo('getting metadata');\n if (!this.#metadata) {\n await this.#loadMetadata();\n }\n\n return this.#metadata ?? null;\n }\n\n async getSchemas() {\n this.#reportInfo('getting schemas');\n const schemaCollection = await utils.stream.collect<Struct.Schema>(\n this.createSchemasReadStream()\n );\n\n if (isEmpty(schemaCollection)) {\n throw new ProviderInitializationError('Could not load schemas from Strapi data file.');\n }\n\n // Group schema by UID\n const schemas = keyBy('uid', schemaCollection);\n\n // Transform to valid JSON\n return utils.schema.schemasToValidJSON(schemas);\n }\n\n createEntitiesReadStream(): Readable {\n this.#reportInfo('creating entities read stream');\n return this.#streamJsonlDirectory('entities');\n }\n\n createSchemasReadStream(): Readable {\n this.#reportInfo('creating schemas read stream');\n return this.#streamJsonlDirectory('schemas');\n }\n\n createLinksReadStream(): Readable {\n this.#reportInfo('creating links read stream');\n return this.#streamJsonlDirectory('links');\n }\n\n createConfigurationReadStream(): Readable {\n this.#reportInfo('creating configuration read stream');\n // NOTE: TBD\n return this.#streamJsonlDirectory('configuration');\n }\n\n createAssetsReadStream(): Readable | Promise<Readable> {\n const inStream = this.#getBackupStream();\n const outStream = new PassThrough({ objectMode: true });\n const loadAssetMetadata = this.#loadAssetMetadata.bind(this);\n this.#reportInfo('creating assets read stream');\n\n pipeline(\n [\n inStream,\n new tar.Parse({\n // find only files in the assets/uploads folder\n filter(filePath, entry) {\n if (entry.type !== 'File') {\n return false;\n }\n return isFilePathInDirname('assets/uploads', filePath);\n },\n async onentry(entry) {\n const { path: filePath, size = 0 } = entry;\n const normalizedPath = unknownPathToPosix(filePath);\n const file = path.basename(normalizedPath);\n let metadata;\n try {\n metadata = await loadAssetMetadata(`assets/metadata/${file}.json`);\n } catch (error) {\n throw new Error(`Failed to read metadata for ${file}`);\n }\n const asset: IAsset = {\n metadata,\n filename: file,\n filepath: normalizedPath,\n stats: { size },\n stream: entry as unknown as Readable,\n };\n outStream.write(asset);\n },\n }),\n ],\n () => outStream.end()\n );\n\n return outStream;\n }\n\n #getBackupStream() {\n const { file, encryption, compression } = this.options;\n\n const streams: StreamItemArray = [];\n\n try {\n streams.push(fs.createReadStream(file.path));\n } catch (e) {\n throw new Error(`Could not read backup file path provided at \"${this.options.file.path}\"`);\n }\n\n if (encryption.enabled && encryption.key) {\n streams.push(utils.encryption.createDecryptionCipher(encryption.key));\n }\n\n if (compression.enabled) {\n streams.push(zip.createGunzip());\n }\n\n return chain(streams);\n }\n\n // `directory` must be posix formatted path\n #streamJsonlDirectory(directory: string) {\n const inStream = this.#getBackupStream();\n\n const outStream = new PassThrough({ objectMode: true });\n\n pipeline(\n [\n inStream,\n new tar.Parse({\n filter(filePath, entry) {\n if (entry.type !== 'File') {\n return false;\n }\n\n return isFilePathInDirname(directory, filePath);\n },\n\n async onentry(entry) {\n const transforms = [\n // JSONL parser to read the data chunks one by one (line by line)\n parser({\n checkErrors: true,\n }),\n // The JSONL parser returns each line as key/value\n (line: { key: string; value: object }) => line.value,\n ];\n\n const stream = entry.pipe(chain(transforms));\n\n try {\n for await (const chunk of stream) {\n outStream.write(chunk);\n }\n } catch (e: unknown) {\n outStream.destroy(\n new ProviderTransferError(\n `Error parsing backup files from backup file ${entry.path}: ${\n (e as Error).message\n }`,\n {\n details: {\n error: e,\n },\n }\n )\n );\n }\n },\n }),\n ],\n async () => {\n // Manually send the 'end' event to the out stream\n // once every entry has finished streaming its content\n outStream.end();\n }\n );\n\n return outStream;\n }\n\n // For collecting an entire JSON file then parsing it, not for streaming JSONL\n async #parseJSONFile<T extends object>(fileStream: Readable, filePath: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n pipeline(\n [\n fileStream,\n // Custom backup archive parsing\n new tar.Parse({\n /**\n * Filter the parsed entries to only keep the one that matches the given filepath\n */\n filter(entryPath, entry) {\n if (entry.type !== 'File') {\n return false;\n }\n\n return isPathEquivalent(entryPath, filePath);\n },\n\n async onentry(entry) {\n // Collect all the content of the entry file\n const content = await entry.collect();\n\n try {\n // Parse from buffer array to string to JSON\n const parsedContent = JSON.parse(Buffer.concat(content).toString());\n\n // Resolve the Promise with the parsed content\n resolve(parsedContent);\n } catch (e) {\n reject(e);\n } finally {\n // Cleanup (close the stream associated to the entry)\n entry.destroy();\n }\n },\n }),\n ],\n () => {\n // If the promise hasn't been resolved and we've parsed all\n // the archive entries, then the file doesn't exist\n reject(new Error(`File \"${filePath}\" not found`));\n }\n );\n });\n }\n}\n"],"names":["METADATA_FILE_PATH","createLocalFileSourceProvider","options","LocalFileSourceProvider","bootstrap","diagnostics","path","filePath","file","e","encryption","enabled","ProviderInitializationError","getMetadata","getSchemas","schemaCollection","utils","createSchemasReadStream","isEmpty","schemas","keyBy","createEntitiesReadStream","createLinksReadStream","createConfigurationReadStream","createAssetsReadStream","inStream","outStream","PassThrough","objectMode","loadAssetMetadata","bind","pipeline","tar","Parse","filter","entry","type","isFilePathInDirname","onentry","size","normalizedPath","unknownPathToPosix","basename","metadata","error","Error","asset","filename","filepath","stats","stream","write","end","name","key","undefined","message","report","details","createdAt","Date","origin","kind","backupStream","compression","streams","push","fs","createReadStream","zip","createGunzip","chain","directory","transforms","parser","checkErrors","line","value","pipe","chunk","destroy","ProviderTransferError","fileStream","Promise","resolve","reject","entryPath","isPathEquivalent","content","collect","parsedContent","JSON","parse","Buffer","concat","toString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA;;AAEC,IACD,MAAMA,kBAAqB,GAAA,eAAA;AAoBpB,MAAMC,gCAAgC,CAACC,OAAAA,GAAAA;AAC5C,IAAA,OAAO,IAAIC,uBAAwBD,CAAAA,OAAAA,CAAAA;AACrC;AASE,IAAA,SAAA,iBAAA,8BAAA,CAAA,WAAA,CAAA,EAEA,YAYA,iBAAA,8BAAA,CAAA,cAAA,CAAA,EAAA,WAAA,iBAAA,8BAAA,CAAA,aAAA,CAAA,EAoCM,aAKA,iBAAA,8BAAA,CAAA,eAAA,CAAA,EAAA,kBAAA,iBAAA,8BAAA,CAAA,oBAAA,CAAA,EAgGN;AAuBA,qBA6DM,iBAAA,8BAAA,CAAA,uBAAA,CAAA,EAAA,cAAA,iBAAA,8BAAA,CAAA,gBAAA,CAAA;AAlPR,MAAMC,uBAAAA,CAAAA;AAgCJ;;MAGA,MAAMC,SAAUC,CAAAA,WAAgC,EAAE;QAChD,+BAAA,CAAA,IAAI,EAAC,YAAA,CAAA,CAAA,YAAeA,CAAAA,GAAAA,WAAAA;QACpB,MAAM,EAAEC,MAAMC,QAAQ,EAAE,GAAG,IAAI,CAACL,OAAO,CAACM,IAAI;QAE5C,IAAI;;YAEF,MAAM,+BAAA,CAAA,IAAI,EAAC,aAAA,CAAA,CAAA,aAAA,CAAA,EAAA;;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A;IAGF,OAAO1B,SAAAA;AACT;AAGA,eAAA,aAAA,CAAuCwD,UAAoB,EAAE3E,QAAgB,EAAA;IAC3E,OAAO,IAAI4E,OAAW,CAAA,CAACC,OAASC,EAAAA,MAAAA,GAAAA;QAC9BtD,QACE,CAAA;AACEmD,YAAAA,UAAAA;;YAEA,IAAIlD,GAAAA,CAAIC,KAAK,CAAC;AACZ;;gBAGAC,MAAAA,CAAAA,CAAOoD,SAAS,EAAEnD,KAAK,EAAA;oBACrB,IAAIA,KAAAA,CAAMC,IAAI,KAAK,MAAQ,EAAA;wBACzB,OAAO,KAAA;AACT;AAEA,oBAAA,OAAOmD,iBAAiBD,SAAW/E,EAAAA,QAAAA,CAAAA;AACrC,iBAAA;AAEA,gBAAA,MAAM+B,SAAQH,KAAK,EAAA;;oBAEjB,MAAMqD,OAAAA,GAAU,MAAMrD,KAAAA,CAAMsD,OAAO,EAAA;oBAEnC,IAAI;;wBAEF,MAAMC,aAAAA,GAAgBC,KAAKC,KAAK,CAACC,OAAOC,MAAM,CAACN,SAASO,QAAQ,EAAA,CAAA;;wBAGhEX,OAAQM,CAAAA,aAAAA,CAAAA;AACV,qBAAA,CAAE,OAAOjF,CAAG,EAAA;wBACV4E,MAAO5E,CAAAA,CAAAA,CAAAA;qBACC,QAAA;;AAER0B,wBAAAA,KAAAA,CAAM6C,OAAO,EAAA;AACf;AACF;AACF,aAAA;SACD,EACD,IAAA;;;AAGEK,YAAAA,MAAAA,CAAO,IAAIxC,KAAM,CAAA,CAAC,MAAM,EAAEtC,QAAAA,CAAS,WAAW,CAAC,CAAA,CAAA;AACjD,SAAA,CAAA;AAEJ,KAAA,CAAA;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/strapi/providers/local-destination/index.ts"],"sourcesContent":["import { Writable, Readable } from 'stream';\nimport path from 'path';\nimport * as fse from 'fs-extra';\nimport type { Knex } from 'knex';\nimport type { Core, Struct } from '@strapi/types';\nimport type {\n IAsset,\n IDestinationProvider,\n IFile,\n IMetadata,\n ProviderType,\n Transaction,\n} from '../../../../types';\nimport type { IDiagnosticReporter } from '../../../utils/diagnostic';\n\nimport { restore } from './strategies';\nimport * as utils from '../../../utils';\nimport {\n ProviderInitializationError,\n ProviderTransferError,\n ProviderValidationError,\n} from '../../../errors/providers';\nimport { assertValidStrapi } from '../../../utils/providers';\n\nexport const VALID_CONFLICT_STRATEGIES = ['restore'];\nexport const DEFAULT_CONFLICT_STRATEGY = 'restore';\n\nexport interface ILocalStrapiDestinationProviderOptions {\n getStrapi(): Core.Strapi | Promise<Core.Strapi>; // return an initialized instance of Strapi\n\n autoDestroy?: boolean; // shut down the instance returned by getStrapi() at the end of the transfer\n restore?: restore.IRestoreOptions; // erase data in strapi database before transfer; required if strategy is 'restore'\n strategy: 'restore'; // conflict management strategy; only the restore strategy is available at this time\n}\n\nclass LocalStrapiDestinationProvider implements IDestinationProvider {\n name = 'destination::local-strapi';\n\n type: ProviderType = 'destination';\n\n options: ILocalStrapiDestinationProviderOptions;\n\n strapi?: Core.Strapi;\n\n transaction?: Transaction;\n\n uploadsBackupDirectoryName: string;\n\n onWarning?: ((message: string) => void) | undefined;\n\n #diagnostics?: IDiagnosticReporter;\n\n /**\n * The entities mapper is used to map old entities to their new IDs\n */\n #entitiesMapper: { [type: string]: { [id: number]: number } };\n\n constructor(options: ILocalStrapiDestinationProviderOptions) {\n this.options = options;\n this.#entitiesMapper = {};\n this.uploadsBackupDirectoryName = `uploads_backup_${Date.now()}`;\n }\n\n async bootstrap(diagnostics?: IDiagnosticReporter): Promise<void> {\n this.#diagnostics = diagnostics;\n this.#validateOptions();\n this.strapi = await this.options.getStrapi();\n if (!this.strapi) {\n throw new ProviderInitializationError('Could not access local strapi');\n }\n this.strapi.db.lifecycles.disable();\n this.transaction = utils.transaction.createTransaction(this.strapi);\n }\n\n // TODO: either move this to restore strategy, or restore strategy should given access to these instead of repeating the logic possibly in a different way\n #areAssetsIncluded = () => {\n return this.options.restore?.assets;\n };\n\n #isContentTypeIncluded = (type: string) => {\n const notIncluded =\n this.options.restore?.entities?.include &&\n !this.options.restore?.entities?.include?.includes(type);\n const excluded =\n this.options.restore?.entities?.exclude &&\n this.options.restore?.entities.exclude.includes(type);\n\n return !excluded && !notIncluded;\n };\n\n #reportInfo(message: string) {\n this.#diagnostics?.report({\n details: {\n createdAt: new Date(),\n message,\n origin: 'local-destination-provider',\n },\n kind: 'info',\n });\n }\n\n async close(): Promise<void> {\n const { autoDestroy } = this.options;\n assertValidStrapi(this.strapi);\n this.transaction?.end();\n this.strapi.db.lifecycles.enable();\n // Basically `!== false` but more deterministic\n if (autoDestroy === undefined || autoDestroy === true) {\n await this.strapi?.destroy();\n }\n }\n\n #validateOptions() {\n this.#reportInfo('validating options');\n if (!VALID_CONFLICT_STRATEGIES.includes(this.options.strategy)) {\n throw new ProviderValidationError(`Invalid strategy ${this.options.strategy}`, {\n check: 'strategy',\n strategy: this.options.strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n\n // require restore options when using restore\n if (this.options.strategy === 'restore' && !this.options.restore) {\n throw new ProviderValidationError('Missing restore options');\n }\n }\n\n async #deleteFromRestoreOptions() {\n assertValidStrapi(this.strapi);\n if (!this.options.restore) {\n throw new ProviderValidationError('Missing restore options');\n }\n this.#reportInfo('deleting record ');\n return restore.deleteRecords(this.strapi, this.options.restore);\n }\n\n async #deleteAllAssets(trx?: Knex.Transaction) {\n assertValidStrapi(this.strapi);\n this.#reportInfo('deleting all assets');\n // if we're not restoring files, don't touch the files\n if (!this.#areAssetsIncluded()) {\n return;\n }\n\n const stream: Readable = this.strapi.db\n // Create a query builder instance (default type is 'select')\n .queryBuilder('plugin::upload.file')\n // Fetch all columns\n .select('*')\n // Attach the transaction\n .transacting(trx)\n // Get a readable stream\n .stream();\n\n // TODO use bulk delete when exists in providers\n for await (const file of stream) {\n await this.strapi.plugin('upload').provider.delete(file);\n if (file.formats) {\n for (const fileFormat of Object.values(file.formats)) {\n await this.strapi.plugin('upload').provider.delete(fileFormat);\n }\n }\n }\n\n this.#reportInfo('deleted all assets');\n }\n\n async rollback() {\n this.#reportInfo('Rolling back transaction');\n await this.transaction?.rollback();\n this.#reportInfo('Rolled back transaction');\n }\n\n async beforeTransfer() {\n if (!this.strapi) {\n throw new Error('Strapi instance not found');\n }\n\n await this.transaction?.attach(async (trx) => {\n try {\n if (this.options.strategy === 'restore') {\n await this.#handleAssetsBackup();\n await this.#deleteAllAssets(trx);\n await this.#deleteFromRestoreOptions();\n }\n } catch (error) {\n throw new Error(`restore failed ${error}`);\n }\n });\n }\n\n getMetadata(): IMetadata {\n this.#reportInfo('getting metadata');\n assertValidStrapi(this.strapi, 'Not able to get Schemas');\n const strapiVersion = this.strapi.config.get<string>('info.strapi');\n const createdAt = new Date().toISOString();\n\n return {\n createdAt,\n strapi: {\n version: strapiVersion,\n },\n };\n }\n\n getSchemas(): Record<string, Struct.Schema> {\n this.#reportInfo('getting schema');\n assertValidStrapi(this.strapi, 'Not able to get Schemas');\n\n const schemas = utils.schema.schemasToValidJSON({\n ...this.strapi.contentTypes,\n ...this.strapi.components,\n });\n\n return utils.schema.mapSchemasValues(schemas);\n }\n\n createEntitiesWriteStream(): Writable {\n assertValidStrapi(this.strapi, 'Not able to import entities');\n this.#reportInfo('creating entities stream');\n const { strategy } = this.options;\n\n const updateMappingTable = (type: string, oldID: number, newID: number) => {\n if (!this.#entitiesMapper[type]) {\n this.#entitiesMapper[type] = {};\n }\n\n Object.assign(this.#entitiesMapper[type], { [oldID]: newID });\n };\n\n if (strategy === 'restore') {\n return restore.createEntitiesWriteStream({\n strapi: this.strapi,\n updateMappingTable,\n transaction: this.transaction,\n });\n }\n\n throw new ProviderValidationError(`Invalid strategy ${this.options.strategy}`, {\n check: 'strategy',\n strategy: this.options.strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n\n async #handleAssetsBackup() {\n assertValidStrapi(this.strapi, 'Not able to create the assets backup');\n\n // if we're not restoring assets, don't back them up because they won't be touched\n if (!this.#areAssetsIncluded()) {\n return;\n }\n\n if (this.strapi.config.get<{ provider: string }>('plugin::upload').provider === 'local') {\n this.#reportInfo('creating assets backup directory');\n const assetsDirectory = path.join(this.strapi.dirs.static.public, 'uploads');\n const backupDirectory = path.join(\n this.strapi.dirs.static.public,\n this.uploadsBackupDirectoryName\n );\n\n try {\n // Check access before attempting to do anything\n await fse.access(\n assetsDirectory,\n // eslint-disable-next-line no-bitwise\n fse.constants.W_OK | fse.constants.R_OK | fse.constants.F_OK\n );\n // eslint-disable-next-line no-bitwise\n await fse.access(path.join(assetsDirectory, '..'), fse.constants.W_OK | fse.constants.R_OK);\n\n await fse.move(assetsDirectory, backupDirectory);\n await fse.mkdir(assetsDirectory);\n // Create a .gitkeep file to ensure the directory is not empty\n await fse.outputFile(path.join(assetsDirectory, '.gitkeep'), '');\n this.#reportInfo(`created assets backup directory ${backupDirectory}`);\n } catch (err) {\n throw new ProviderTransferError(\n 'The backup folder for the assets could not be created inside the public folder. Please ensure Strapi has write permissions on the public directory',\n {\n code: 'ASSETS_DIRECTORY_ERR',\n }\n );\n }\n return backupDirectory;\n }\n }\n\n async #removeAssetsBackup() {\n assertValidStrapi(this.strapi, 'Not able to remove Assets');\n // if we're not restoring assets, don't back them up because they won't be touched\n if (!this.#areAssetsIncluded()) {\n return;\n }\n // TODO: this should catch all thrown errors and bubble it up to engine so it can be reported as a non-fatal diagnostic message telling the user they may need to manually delete assets\n if (this.strapi.config.get<{ provider: string }>('plugin::upload').provider === 'local') {\n this.#reportInfo('removing assets backup');\n assertValidStrapi(this.strapi);\n const backupDirectory = path.join(\n this.strapi.dirs.static.public,\n this.uploadsBackupDirectoryName\n );\n await fse.rm(backupDirectory, { recursive: true, force: true });\n this.#reportInfo('successfully removed assets backup');\n }\n }\n\n // TODO: Move this logic to the restore strategy\n async createAssetsWriteStream(): Promise<Writable> {\n assertValidStrapi(this.strapi, 'Not able to stream Assets');\n this.#reportInfo('creating assets write stream');\n if (!this.#areAssetsIncluded()) {\n throw new ProviderTransferError(\n 'Attempting to transfer assets when `assets` is not set in restore options'\n );\n }\n\n const removeAssetsBackup = this.#removeAssetsBackup.bind(this);\n const strapi = this.strapi;\n const transaction = this.transaction;\n const fileEntitiesMapper = this.#entitiesMapper['plugin::upload.file'];\n\n const restoreMediaEntitiesContent = this.#isContentTypeIncluded('plugin::upload.file');\n\n return new Writable({\n objectMode: true,\n async final(next) {\n // Delete the backup folder\n await removeAssetsBackup();\n next();\n },\n async write(chunk: IAsset, _encoding, callback) {\n await transaction?.attach(async () => {\n const uploadData = {\n ...chunk.metadata,\n stream: Readable.from(chunk.stream),\n buffer: chunk?.buffer,\n };\n\n const provider = strapi.config.get<{ provider: string }>('plugin::upload').provider;\n\n const fileId = fileEntitiesMapper?.[uploadData.id];\n if (!fileId) {\n return callback(new Error(`File ID not found for ID: ${uploadData.id}`));\n }\n\n try {\n await strapi.plugin('upload').provider.uploadStream(uploadData);\n\n // if we're not supposed to transfer the associated entities, stop here\n if (!restoreMediaEntitiesContent) {\n return callback();\n }\n\n // Files formats are stored within the parent file entity\n if (uploadData?.type) {\n const entry: IFile = await strapi.db.query('plugin::upload.file').findOne({\n where: { id: fileId },\n });\n if (!entry) {\n throw new Error('file not found');\n }\n const specificFormat = entry?.formats?.[uploadData.type];\n if (specificFormat) {\n specificFormat.url = uploadData.url;\n }\n await strapi.db.query('plugin::upload.file').update({\n where: { id: entry.id },\n data: {\n formats: entry.formats,\n provider,\n },\n });\n return callback();\n }\n\n const entry: IFile = await strapi.db.query('plugin::upload.file').findOne({\n where: { id: fileId },\n });\n if (!entry) {\n throw new Error('file not found');\n }\n entry.url = uploadData.url;\n await strapi.db.query('plugin::upload.file').update({\n where: { id: entry.id },\n data: {\n url: entry.url,\n provider,\n },\n });\n return callback();\n } catch (error) {\n return callback(new Error(`Error while uploading asset ${chunk.filename} ${error}`));\n }\n });\n },\n });\n }\n\n async createConfigurationWriteStream(): Promise<Writable> {\n assertValidStrapi(this.strapi, 'Not able to stream Configurations');\n this.#reportInfo('creating configuration write stream');\n const { strategy } = this.options;\n\n if (strategy === 'restore') {\n return restore.createConfigurationWriteStream(this.strapi, this.transaction);\n }\n\n throw new ProviderValidationError(`Invalid strategy ${strategy}`, {\n check: 'strategy',\n strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n\n async createLinksWriteStream(): Promise<Writable> {\n this.#reportInfo('creating links write stream');\n if (!this.strapi) {\n throw new Error('Not able to stream links. Strapi instance not found');\n }\n\n const { strategy } = this.options;\n const mapID = (uid: string, id: number): number | undefined => this.#entitiesMapper[uid]?.[id];\n\n if (strategy === 'restore') {\n return restore.createLinksWriteStream(mapID, this.strapi, this.transaction, this.onWarning);\n }\n\n throw new ProviderValidationError(`Invalid strategy ${strategy}`, {\n check: 'strategy',\n strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n}\n\nexport const createLocalStrapiDestinationProvider = (\n options: ILocalStrapiDestinationProviderOptions\n) => {\n return new LocalStrapiDestinationProvider(options);\n};\n"],"names":["VALID_CONFLICT_STRATEGIES","DEFAULT_CONFLICT_STRATEGY","LocalStrapiDestinationProvider","bootstrap","diagnostics","validateOptions","strapi","options","getStrapi","ProviderInitializationError","db","lifecycles","disable","transaction","utils","close","autoDestroy","assertValidStrapi","end","enable","undefined","destroy","rollback","reportInfo","beforeTransfer","Error","attach","trx","strategy","handleAssetsBackup","deleteAllAssets","deleteFromRestoreOptions","error","getMetadata","strapiVersion","config","get","createdAt","Date","toISOString","version","getSchemas","schemas","contentTypes","components","createEntitiesWriteStream","updateMappingTable","type","oldID","newID","entitiesMapper","Object","assign","restore","ProviderValidationError","check","validStrategies","createAssetsWriteStream","areAssetsIncluded","ProviderTransferError","removeAssetsBackup","bind","fileEntitiesMapper","restoreMediaEntitiesContent","isContentTypeIncluded","Writable","objectMode","final","next","write","chunk","_encoding","callback","uploadData","metadata","stream","Readable","from","buffer","provider","fileId","id","plugin","uploadStream","entry","query","findOne","where","specificFormat","formats","url","update","data","filename","createConfigurationWriteStream","createLinksWriteStream","mapID","uid","onWarning","constructor","name","assets","notIncluded","entities","include","includes","excluded","exclude","uploadsBackupDirectoryName","now","message","report","details","origin","kind","queryBuilder","select","transacting","file","delete","fileFormat","values","assetsDirectory","path","join","dirs","static","public","backupDirectory","fse","access","constants","W_OK","R_OK","F_OK","move","mkdir","outputFile","err","code","rm","recursive","force","createLocalStrapiDestinationProvider"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAwBaA,yBAA4B,GAAA;AAAC,IAAA;;AACnC,MAAMC,4BAA4B;IAyBvC,YAEA,iBAAA,8BAAA,CAAA,cAAA,CAAA;;AAEC,MACD;AAoBA,kBAAA,iBAAA,8BAAA,CAAA,oBAAA,CAAA,EAIA,sBAWA,iBAAA,8BAAA,CAAA,wBAAA,CAAA,EAAA,WAAA,iBAAA,8BAAA,CAAA,aAAA,CAAA,EAsBA,gBAgBM,iBAAA,8BAAA,CAAA,kBAAA,CAAA,EAAA,yBAAA,iBAAA,8BAAA,CAAA,2BAAA,CAAA,EASA,qFA6GA,mBA2CA,iBAAA,8BAAA,CAAA,qBAAA,CAAA,EAAA,mBAAA,iBAAA,8BAAA,CAAA,qBAAA,CAAA;AA9PR,MAAMC,8BAAAA,CAAAA;IA4BJ,MAAMC,SAAAA,CAAUC,WAAiC,EAAiB;QAChE,+BAAA,CAAA,IAAI,EAAEA,YAAAA,CAAAA,CAAAA,YAAcA,CAAAA,GAAAA,WAAAA;QACpB,+BAAA,CAAA,IAAI,EAAEC,gBAAAA,CAAAA,CAAAA,gBAAAA,CAAAA,EAAAA;QACN,IAAI,CAACC,MAAM,GAAG,MAAM,IAAI,CAACC,OAAO,CAACC,SAAS,EAAA;AAC1C,QAAA,IAAI,CAAC,IAAI,CAACF,MAAM,EAAE;AAChB,YAAA,MAAM,IAAIG,qCAA4B,CAAA,+BAAA,CAAA;AACxC;A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A,CAAAA;AAC5C;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/strapi/providers/local-destination/index.ts"],"sourcesContent":["import { Writable, Readable } from 'stream';\nimport path from 'path';\nimport * as fse from 'fs-extra';\nimport type { Knex } from 'knex';\nimport type { Core, Struct } from '@strapi/types';\nimport type {\n IAsset,\n IDestinationProvider,\n IFile,\n IMetadata,\n ProviderType,\n Transaction,\n} from '../../../../types';\nimport type { IDiagnosticReporter } from '../../../utils/diagnostic';\n\nimport { restore } from './strategies';\nimport * as utils from '../../../utils';\nimport {\n ProviderInitializationError,\n ProviderTransferError,\n ProviderValidationError,\n} from '../../../errors/providers';\nimport { assertValidStrapi } from '../../../utils/providers';\n\nexport const VALID_CONFLICT_STRATEGIES = ['restore'];\nexport const DEFAULT_CONFLICT_STRATEGY = 'restore';\n\nexport interface ILocalStrapiDestinationProviderOptions {\n getStrapi(): Core.Strapi | Promise<Core.Strapi>; // return an initialized instance of Strapi\n\n autoDestroy?: boolean; // shut down the instance returned by getStrapi() at the end of the transfer\n restore?: restore.IRestoreOptions; // erase data in strapi database before transfer; required if strategy is 'restore'\n strategy: 'restore'; // conflict management strategy; only the restore strategy is available at this time\n}\n\nclass LocalStrapiDestinationProvider implements IDestinationProvider {\n name = 'destination::local-strapi';\n\n type: ProviderType = 'destination';\n\n options: ILocalStrapiDestinationProviderOptions;\n\n strapi?: Core.Strapi;\n\n transaction?: Transaction;\n\n uploadsBackupDirectoryName: string;\n\n onWarning?: ((message: string) => void) | undefined;\n\n #diagnostics?: IDiagnosticReporter;\n\n /**\n * The entities mapper is used to map old entities to their new IDs\n */\n #entitiesMapper: { [type: string]: { [id: number]: number } };\n\n constructor(options: ILocalStrapiDestinationProviderOptions) {\n this.options = options;\n this.#entitiesMapper = {};\n this.uploadsBackupDirectoryName = `uploads_backup_${Date.now()}`;\n }\n\n async bootstrap(diagnostics?: IDiagnosticReporter): Promise<void> {\n this.#diagnostics = diagnostics;\n this.#validateOptions();\n this.strapi = await this.options.getStrapi();\n if (!this.strapi) {\n throw new ProviderInitializationError('Could not access local strapi');\n }\n this.strapi.db.lifecycles.disable();\n this.transaction = utils.transaction.createTransaction(this.strapi);\n }\n\n // TODO: either move this to restore strategy, or restore strategy should given access to these instead of repeating the logic possibly in a different way\n #areAssetsIncluded = () => {\n return this.options.restore?.assets;\n };\n\n #isContentTypeIncluded = (type: string) => {\n const notIncluded =\n this.options.restore?.entities?.include &&\n !this.options.restore?.entities?.include?.includes(type);\n const excluded =\n this.options.restore?.entities?.exclude &&\n this.options.restore?.entities.exclude.includes(type);\n\n return !excluded && !notIncluded;\n };\n\n #reportInfo(message: string) {\n this.#diagnostics?.report({\n details: {\n createdAt: new Date(),\n message,\n origin: 'local-destination-provider',\n },\n kind: 'info',\n });\n }\n\n async close(): Promise<void> {\n const { autoDestroy } = this.options;\n assertValidStrapi(this.strapi);\n this.transaction?.end();\n this.strapi.db.lifecycles.enable();\n // Basically `!== false` but more deterministic\n if (autoDestroy === undefined || autoDestroy === true) {\n await this.strapi?.destroy();\n }\n }\n\n #validateOptions() {\n this.#reportInfo('validating options');\n if (!VALID_CONFLICT_STRATEGIES.includes(this.options.strategy)) {\n throw new ProviderValidationError(`Invalid strategy ${this.options.strategy}`, {\n check: 'strategy',\n strategy: this.options.strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n\n // require restore options when using restore\n if (this.options.strategy === 'restore' && !this.options.restore) {\n throw new ProviderValidationError('Missing restore options');\n }\n }\n\n async #deleteFromRestoreOptions() {\n assertValidStrapi(this.strapi);\n if (!this.options.restore) {\n throw new ProviderValidationError('Missing restore options');\n }\n this.#reportInfo('deleting record ');\n return restore.deleteRecords(this.strapi, this.options.restore);\n }\n\n async #deleteAllAssets(trx?: Knex.Transaction) {\n assertValidStrapi(this.strapi);\n this.#reportInfo('deleting all assets');\n // if we're not restoring files, don't touch the files\n if (!this.#areAssetsIncluded()) {\n return;\n }\n\n const stream: Readable = this.strapi.db\n // Create a query builder instance (default type is 'select')\n .queryBuilder('plugin::upload.file')\n // Fetch all columns\n .select('*')\n // Attach the transaction\n .transacting(trx)\n // Get a readable stream\n .stream();\n\n // TODO use bulk delete when exists in providers\n for await (const file of stream) {\n await this.strapi.plugin('upload').provider.delete(file);\n if (file.formats) {\n for (const fileFormat of Object.values(file.formats)) {\n await this.strapi.plugin('upload').provider.delete(fileFormat);\n }\n }\n }\n\n this.#reportInfo('deleted all assets');\n }\n\n async rollback() {\n this.#reportInfo('Rolling back transaction');\n await this.transaction?.rollback();\n this.#reportInfo('Rolled back transaction');\n }\n\n async beforeTransfer() {\n if (!this.strapi) {\n throw new Error('Strapi instance not found');\n }\n\n await this.transaction?.attach(async (trx) => {\n try {\n if (this.options.strategy === 'restore') {\n await this.#handleAssetsBackup();\n await this.#deleteAllAssets(trx);\n await this.#deleteFromRestoreOptions();\n }\n } catch (error) {\n throw new Error(`restore failed ${error}`);\n }\n });\n }\n\n getMetadata(): IMetadata {\n this.#reportInfo('getting metadata');\n assertValidStrapi(this.strapi, 'Not able to get Schemas');\n const strapiVersion = this.strapi.config.get<string>('info.strapi');\n const createdAt = new Date().toISOString();\n\n return {\n createdAt,\n strapi: {\n version: strapiVersion,\n },\n };\n }\n\n getSchemas(): Record<string, Struct.Schema> {\n this.#reportInfo('getting schema');\n assertValidStrapi(this.strapi, 'Not able to get Schemas');\n\n const schemas = utils.schema.schemasToValidJSON({\n ...this.strapi.contentTypes,\n ...this.strapi.components,\n });\n\n return utils.schema.mapSchemasValues(schemas);\n }\n\n createEntitiesWriteStream(): Writable {\n assertValidStrapi(this.strapi, 'Not able to import entities');\n this.#reportInfo('creating entities stream');\n const { strategy } = this.options;\n\n const updateMappingTable = (type: string, oldID: number, newID: number) => {\n if (!this.#entitiesMapper[type]) {\n this.#entitiesMapper[type] = {};\n }\n\n Object.assign(this.#entitiesMapper[type], { [oldID]: newID });\n };\n\n if (strategy === 'restore') {\n return restore.createEntitiesWriteStream({\n strapi: this.strapi,\n updateMappingTable,\n transaction: this.transaction,\n });\n }\n\n throw new ProviderValidationError(`Invalid strategy ${this.options.strategy}`, {\n check: 'strategy',\n strategy: this.options.strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n\n async #handleAssetsBackup() {\n assertValidStrapi(this.strapi, 'Not able to create the assets backup');\n\n // if we're not restoring assets, don't back them up because they won't be touched\n if (!this.#areAssetsIncluded()) {\n return;\n }\n\n if (this.strapi.config.get<{ provider: string }>('plugin::upload').provider === 'local') {\n this.#reportInfo('creating assets backup directory');\n const assetsDirectory = path.join(this.strapi.dirs.static.public, 'uploads');\n const backupDirectory = path.join(\n this.strapi.dirs.static.public,\n this.uploadsBackupDirectoryName\n );\n\n try {\n // Check access before attempting to do anything\n await fse.access(\n assetsDirectory,\n // eslint-disable-next-line no-bitwise\n fse.constants.W_OK | fse.constants.R_OK | fse.constants.F_OK\n );\n // eslint-disable-next-line no-bitwise\n await fse.access(path.join(assetsDirectory, '..'), fse.constants.W_OK | fse.constants.R_OK);\n\n await fse.move(assetsDirectory, backupDirectory);\n await fse.mkdir(assetsDirectory);\n // Create a .gitkeep file to ensure the directory is not empty\n await fse.outputFile(path.join(assetsDirectory, '.gitkeep'), '');\n this.#reportInfo(`created assets backup directory ${backupDirectory}`);\n } catch (err) {\n throw new ProviderTransferError(\n 'The backup folder for the assets could not be created inside the public folder. Please ensure Strapi has write permissions on the public directory',\n {\n code: 'ASSETS_DIRECTORY_ERR',\n }\n );\n }\n return backupDirectory;\n }\n }\n\n async #removeAssetsBackup() {\n assertValidStrapi(this.strapi, 'Not able to remove Assets');\n // if we're not restoring assets, don't back them up because they won't be touched\n if (!this.#areAssetsIncluded()) {\n return;\n }\n // TODO: this should catch all thrown errors and bubble it up to engine so it can be reported as a non-fatal diagnostic message telling the user they may need to manually delete assets\n if (this.strapi.config.get<{ provider: string }>('plugin::upload').provider === 'local') {\n this.#reportInfo('removing assets backup');\n assertValidStrapi(this.strapi);\n const backupDirectory = path.join(\n this.strapi.dirs.static.public,\n this.uploadsBackupDirectoryName\n );\n await fse.rm(backupDirectory, { recursive: true, force: true });\n this.#reportInfo('successfully removed assets backup');\n }\n }\n\n // TODO: Move this logic to the restore strategy\n async createAssetsWriteStream(): Promise<Writable> {\n assertValidStrapi(this.strapi, 'Not able to stream Assets');\n this.#reportInfo('creating assets write stream');\n if (!this.#areAssetsIncluded()) {\n throw new ProviderTransferError(\n 'Attempting to transfer assets when `assets` is not set in restore options'\n );\n }\n\n const removeAssetsBackup = this.#removeAssetsBackup.bind(this);\n const strapi = this.strapi;\n const transaction = this.transaction;\n const fileEntitiesMapper = this.#entitiesMapper['plugin::upload.file'];\n\n const restoreMediaEntitiesContent = this.#isContentTypeIncluded('plugin::upload.file');\n\n return new Writable({\n objectMode: true,\n async final(next) {\n // Delete the backup folder\n await removeAssetsBackup();\n next();\n },\n async write(chunk: IAsset, _encoding, callback) {\n await transaction?.attach(async () => {\n const uploadData = {\n ...chunk.metadata,\n stream: Readable.from(chunk.stream),\n buffer: chunk?.buffer,\n };\n\n const provider = strapi.config.get<{ provider: string }>('plugin::upload').provider;\n\n const fileId = fileEntitiesMapper?.[uploadData.id];\n if (!fileId) {\n return callback(new Error(`File ID not found for ID: ${uploadData.id}`));\n }\n\n try {\n await strapi.plugin('upload').provider.uploadStream(uploadData);\n\n // if we're not supposed to transfer the associated entities, stop here\n if (!restoreMediaEntitiesContent) {\n return callback();\n }\n\n // Files formats are stored within the parent file entity\n if (uploadData?.type) {\n const entry: IFile = await strapi.db.query('plugin::upload.file').findOne({\n where: { id: fileId },\n });\n if (!entry) {\n throw new Error('file not found');\n }\n const specificFormat = entry?.formats?.[uploadData.type];\n if (specificFormat) {\n specificFormat.url = uploadData.url;\n }\n await strapi.db.query('plugin::upload.file').update({\n where: { id: entry.id },\n data: {\n formats: entry.formats,\n provider,\n },\n });\n return callback();\n }\n\n const entry: IFile = await strapi.db.query('plugin::upload.file').findOne({\n where: { id: fileId },\n });\n if (!entry) {\n throw new Error('file not found');\n }\n entry.url = uploadData.url;\n await strapi.db.query('plugin::upload.file').update({\n where: { id: entry.id },\n data: {\n url: entry.url,\n provider,\n },\n });\n return callback();\n } catch (error) {\n return callback(new Error(`Error while uploading asset ${chunk.filename} ${error}`));\n }\n });\n },\n });\n }\n\n async createConfigurationWriteStream(): Promise<Writable> {\n assertValidStrapi(this.strapi, 'Not able to stream Configurations');\n this.#reportInfo('creating configuration write stream');\n const { strategy } = this.options;\n\n if (strategy === 'restore') {\n return restore.createConfigurationWriteStream(this.strapi, this.transaction);\n }\n\n throw new ProviderValidationError(`Invalid strategy ${strategy}`, {\n check: 'strategy',\n strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n\n async createLinksWriteStream(): Promise<Writable> {\n this.#reportInfo('creating links write stream');\n if (!this.strapi) {\n throw new Error('Not able to stream links. Strapi instance not found');\n }\n\n const { strategy } = this.options;\n const mapID = (uid: string, id: number): number | undefined => this.#entitiesMapper[uid]?.[id];\n\n if (strategy === 'restore') {\n return restore.createLinksWriteStream(mapID, this.strapi, this.transaction, this.onWarning);\n }\n\n throw new ProviderValidationError(`Invalid strategy ${strategy}`, {\n check: 'strategy',\n strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n}\n\nexport const createLocalStrapiDestinationProvider = (\n options: ILocalStrapiDestinationProviderOptions\n) => {\n return new LocalStrapiDestinationProvider(options);\n};\n"],"names":["VALID_CONFLICT_STRATEGIES","DEFAULT_CONFLICT_STRATEGY","LocalStrapiDestinationProvider","bootstrap","diagnostics","strapi","options","getStrapi","ProviderInitializationError","db","lifecycles","disable","transaction","utils","close","autoDestroy","assertValidStrapi","end","enable","undefined","destroy","rollback","beforeTransfer","Error","attach","trx","strategy","error","getMetadata","strapiVersion","config","get","createdAt","Date","toISOString","version","getSchemas","schemas","contentTypes","components","createEntitiesWriteStream","updateMappingTable","type","oldID","newID","Object","assign","restore","ProviderValidationError","check","validStrategies","createAssetsWriteStream","ProviderTransferError","removeAssetsBackup","bind","fileEntitiesMapper","restoreMediaEntitiesContent","Writable","objectMode","final","next","write","chunk","_encoding","callback","uploadData","metadata","stream","Readable","from","buffer","provider","fileId","id","plugin","uploadStream","entry","query","findOne","where","specificFormat","formats","url","update","data","filename","createConfigurationWriteStream","createLinksWriteStream","mapID","uid","onWarning","name","assets","notIncluded","entities","include","includes","excluded","exclude","uploadsBackupDirectoryName","now","message","report","details","origin","kind","queryBuilder","select","transacting","file","delete","fileFormat","values","assetsDirectory","path","join","dirs","static","public","backupDirectory","fse","access","constants","W_OK","R_OK","F_OK","move","mkdir","outputFile","err","code","rm","recursive","force","createLocalStrapiDestinationProvider"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAwBaA,yBAA4B,GAAA;AAAC,IAAA;;AACnC,MAAMC,4BAA4B;IAyBvC,YAEA,iBAAA,8BAAA,CAAA,cAAA,CAAA;;AAEC,MACD;AAoBA,kBAAA,iBAAA,8BAAA,CAAA,oBAAA,CAAA,EAIA,sBAWA,iBAAA,8BAAA,CAAA,wBAAA,CAAA,EAAA,WAAA,iBAAA,8BAAA,CAAA,aAAA,CAAA,EAsBA,gBAgBM,iBAAA,8BAAA,CAAA,kBAAA,CAAA,EAAA,yBAAA,iBAAA,8BAAA,CAAA,2BAAA,CAAA,EASA,qFA6GA,mBA2CA,iBAAA,8BAAA,CAAA,qBAAA,CAAA,EAAA,mBAAA,iBAAA,8BAAA,CAAA,qBAAA,CAAA;AA9PR,MAAMC,8BAAAA,CAAAA;IA4BJ,MAAMC,SAAAA,CAAUC,WAAiC,EAAiB;QAChE,+BAAA,CAAA,IAAI,EAAC,YAAA,CAAA,CAAA,YAAeA,CAAAA,GAAAA,WAAAA;QACpB,+BAAA,CAAA,IAAI,EAAC,gBAAA,CAAA,CAAA,gBAAA,CAAA,EAAA;QACL,IAAI,CAACC,MAAM,GAAG,MAAM,IAAI,CAACC,OAAO,CAACC,SAAS,EAAA;AAC1C,QAAA,IAAI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EAAEM,eAAiB,CAAA,CAAA,CAAA;AACvE,SAAA,CAAE,OAAOU,GAAK,EAAA;YACZ,MAAM,IAAI7E,gCACR,oJACA,EAAA;gBACE8E,IAAM,EAAA;AACR,aAAA,CAAA;AAEJ;QACA,OAAOX,eAAAA;AACT;AACF;AAEA,eAAA,kBAAA,GAAA;IACEvG,6BAAkB,CAAA,IAAI,CAACX,MAAM,EAAE,2BAAA,CAAA;;AAE/B,IAAA,IAAI,CAAC,+BAAA,CAAA,IAAI,EAAC,oBAAA,kBAAsB,CAAA,EAAA,EAAA;AAC9B,QAAA;AACF;;IAEA,IAAI,IAAI,CAACA,MAAM,CAACyB,MAAM,CAACC,GAAG,CAAuB,gBAAA,CAAA,CAAkBwC,QAAQ,KAAK,OAAS,EAAA;QACvF,+BAAA,CAAA,IAAI,EAAC,WAAA,CAAA,CAAA,WAAY,CAAA,CAAA,wBAAA,CAAA;QACjBvD,6BAAkB,CAAA,IAAI,CAACX,MAAM,CAAA;AAC7B,QAAA,MAAMkH,kBAAkBL,IAAKC,CAAAA,IAAI,CAC/B,IAAI,CAAC9G,MAAM,CAAC+G,IAAI,CAACC,MAAM,CAACC,MAAM,EAC9B,IAAI,CAACnB,0BAA0B,CAAA;QAEjC,MAAMqB,cAAAA,CAAIW,EAAE,CAACZ,eAAiB,EAAA;YAAEa,SAAW,EAAA,IAAA;YAAMC,KAAO,EAAA;AAAK,SAAA,CAAA;QAC7D,+BAAA,CAAA,IAAI,EAAC,WAAA,CAAA,CAAA,WAAY,CAAA,CAAA,oCAAA,CAAA;AACnB;AACF;AAmIK,MAAMC,uCAAuC,CAClDhI,OAAAA,GAAAA;AAEA,IAAA,OAAO,IAAIJ,8BAA+BI,CAAAA,OAAAA,CAAAA;AAC5C;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../../../src/strapi/providers/local-destination/index.ts"],"sourcesContent":["import { Writable, Readable } from 'stream';\nimport path from 'path';\nimport * as fse from 'fs-extra';\nimport type { Knex } from 'knex';\nimport type { Core, Struct } from '@strapi/types';\nimport type {\n IAsset,\n IDestinationProvider,\n IFile,\n IMetadata,\n ProviderType,\n Transaction,\n} from '../../../../types';\nimport type { IDiagnosticReporter } from '../../../utils/diagnostic';\n\nimport { restore } from './strategies';\nimport * as utils from '../../../utils';\nimport {\n ProviderInitializationError,\n ProviderTransferError,\n ProviderValidationError,\n} from '../../../errors/providers';\nimport { assertValidStrapi } from '../../../utils/providers';\n\nexport const VALID_CONFLICT_STRATEGIES = ['restore'];\nexport const DEFAULT_CONFLICT_STRATEGY = 'restore';\n\nexport interface ILocalStrapiDestinationProviderOptions {\n getStrapi(): Core.Strapi | Promise<Core.Strapi>; // return an initialized instance of Strapi\n\n autoDestroy?: boolean; // shut down the instance returned by getStrapi() at the end of the transfer\n restore?: restore.IRestoreOptions; // erase data in strapi database before transfer; required if strategy is 'restore'\n strategy: 'restore'; // conflict management strategy; only the restore strategy is available at this time\n}\n\nclass LocalStrapiDestinationProvider implements IDestinationProvider {\n name = 'destination::local-strapi';\n\n type: ProviderType = 'destination';\n\n options: ILocalStrapiDestinationProviderOptions;\n\n strapi?: Core.Strapi;\n\n transaction?: Transaction;\n\n uploadsBackupDirectoryName: string;\n\n onWarning?: ((message: string) => void) | undefined;\n\n #diagnostics?: IDiagnosticReporter;\n\n /**\n * The entities mapper is used to map old entities to their new IDs\n */\n #entitiesMapper: { [type: string]: { [id: number]: number } };\n\n constructor(options: ILocalStrapiDestinationProviderOptions) {\n this.options = options;\n this.#entitiesMapper = {};\n this.uploadsBackupDirectoryName = `uploads_backup_${Date.now()}`;\n }\n\n async bootstrap(diagnostics?: IDiagnosticReporter): Promise<void> {\n this.#diagnostics = diagnostics;\n this.#validateOptions();\n this.strapi = await this.options.getStrapi();\n if (!this.strapi) {\n throw new ProviderInitializationError('Could not access local strapi');\n }\n this.strapi.db.lifecycles.disable();\n this.transaction = utils.transaction.createTransaction(this.strapi);\n }\n\n // TODO: either move this to restore strategy, or restore strategy should given access to these instead of repeating the logic possibly in a different way\n #areAssetsIncluded = () => {\n return this.options.restore?.assets;\n };\n\n #isContentTypeIncluded = (type: string) => {\n const notIncluded =\n this.options.restore?.entities?.include &&\n !this.options.restore?.entities?.include?.includes(type);\n const excluded =\n this.options.restore?.entities?.exclude &&\n this.options.restore?.entities.exclude.includes(type);\n\n return !excluded && !notIncluded;\n };\n\n #reportInfo(message: string) {\n this.#diagnostics?.report({\n details: {\n createdAt: new Date(),\n message,\n origin: 'local-destination-provider',\n },\n kind: 'info',\n });\n }\n\n async close(): Promise<void> {\n const { autoDestroy } = this.options;\n assertValidStrapi(this.strapi);\n this.transaction?.end();\n this.strapi.db.lifecycles.enable();\n // Basically `!== false` but more deterministic\n if (autoDestroy === undefined || autoDestroy === true) {\n await this.strapi?.destroy();\n }\n }\n\n #validateOptions() {\n this.#reportInfo('validating options');\n if (!VALID_CONFLICT_STRATEGIES.includes(this.options.strategy)) {\n throw new ProviderValidationError(`Invalid strategy ${this.options.strategy}`, {\n check: 'strategy',\n strategy: this.options.strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n\n // require restore options when using restore\n if (this.options.strategy === 'restore' && !this.options.restore) {\n throw new ProviderValidationError('Missing restore options');\n }\n }\n\n async #deleteFromRestoreOptions() {\n assertValidStrapi(this.strapi);\n if (!this.options.restore) {\n throw new ProviderValidationError('Missing restore options');\n }\n this.#reportInfo('deleting record ');\n return restore.deleteRecords(this.strapi, this.options.restore);\n }\n\n async #deleteAllAssets(trx?: Knex.Transaction) {\n assertValidStrapi(this.strapi);\n this.#reportInfo('deleting all assets');\n // if we're not restoring files, don't touch the files\n if (!this.#areAssetsIncluded()) {\n return;\n }\n\n const stream: Readable = this.strapi.db\n // Create a query builder instance (default type is 'select')\n .queryBuilder('plugin::upload.file')\n // Fetch all columns\n .select('*')\n // Attach the transaction\n .transacting(trx)\n // Get a readable stream\n .stream();\n\n // TODO use bulk delete when exists in providers\n for await (const file of stream) {\n await this.strapi.plugin('upload').provider.delete(file);\n if (file.formats) {\n for (const fileFormat of Object.values(file.formats)) {\n await this.strapi.plugin('upload').provider.delete(fileFormat);\n }\n }\n }\n\n this.#reportInfo('deleted all assets');\n }\n\n async rollback() {\n this.#reportInfo('Rolling back transaction');\n await this.transaction?.rollback();\n this.#reportInfo('Rolled back transaction');\n }\n\n async beforeTransfer() {\n if (!this.strapi) {\n throw new Error('Strapi instance not found');\n }\n\n await this.transaction?.attach(async (trx) => {\n try {\n if (this.options.strategy === 'restore') {\n await this.#handleAssetsBackup();\n await this.#deleteAllAssets(trx);\n await this.#deleteFromRestoreOptions();\n }\n } catch (error) {\n throw new Error(`restore failed ${error}`);\n }\n });\n }\n\n getMetadata(): IMetadata {\n this.#reportInfo('getting metadata');\n assertValidStrapi(this.strapi, 'Not able to get Schemas');\n const strapiVersion = this.strapi.config.get<string>('info.strapi');\n const createdAt = new Date().toISOString();\n\n return {\n createdAt,\n strapi: {\n version: strapiVersion,\n },\n };\n }\n\n getSchemas(): Record<string, Struct.Schema> {\n this.#reportInfo('getting schema');\n assertValidStrapi(this.strapi, 'Not able to get Schemas');\n\n const schemas = utils.schema.schemasToValidJSON({\n ...this.strapi.contentTypes,\n ...this.strapi.components,\n });\n\n return utils.schema.mapSchemasValues(schemas);\n }\n\n createEntitiesWriteStream(): Writable {\n assertValidStrapi(this.strapi, 'Not able to import entities');\n this.#reportInfo('creating entities stream');\n const { strategy } = this.options;\n\n const updateMappingTable = (type: string, oldID: number, newID: number) => {\n if (!this.#entitiesMapper[type]) {\n this.#entitiesMapper[type] = {};\n }\n\n Object.assign(this.#entitiesMapper[type], { [oldID]: newID });\n };\n\n if (strategy === 'restore') {\n return restore.createEntitiesWriteStream({\n strapi: this.strapi,\n updateMappingTable,\n transaction: this.transaction,\n });\n }\n\n throw new ProviderValidationError(`Invalid strategy ${this.options.strategy}`, {\n check: 'strategy',\n strategy: this.options.strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n\n async #handleAssetsBackup() {\n assertValidStrapi(this.strapi, 'Not able to create the assets backup');\n\n // if we're not restoring assets, don't back them up because they won't be touched\n if (!this.#areAssetsIncluded()) {\n return;\n }\n\n if (this.strapi.config.get<{ provider: string }>('plugin::upload').provider === 'local') {\n this.#reportInfo('creating assets backup directory');\n const assetsDirectory = path.join(this.strapi.dirs.static.public, 'uploads');\n const backupDirectory = path.join(\n this.strapi.dirs.static.public,\n this.uploadsBackupDirectoryName\n );\n\n try {\n // Check access before attempting to do anything\n await fse.access(\n assetsDirectory,\n // eslint-disable-next-line no-bitwise\n fse.constants.W_OK | fse.constants.R_OK | fse.constants.F_OK\n );\n // eslint-disable-next-line no-bitwise\n await fse.access(path.join(assetsDirectory, '..'), fse.constants.W_OK | fse.constants.R_OK);\n\n await fse.move(assetsDirectory, backupDirectory);\n await fse.mkdir(assetsDirectory);\n // Create a .gitkeep file to ensure the directory is not empty\n await fse.outputFile(path.join(assetsDirectory, '.gitkeep'), '');\n this.#reportInfo(`created assets backup directory ${backupDirectory}`);\n } catch (err) {\n throw new ProviderTransferError(\n 'The backup folder for the assets could not be created inside the public folder. Please ensure Strapi has write permissions on the public directory',\n {\n code: 'ASSETS_DIRECTORY_ERR',\n }\n );\n }\n return backupDirectory;\n }\n }\n\n async #removeAssetsBackup() {\n assertValidStrapi(this.strapi, 'Not able to remove Assets');\n // if we're not restoring assets, don't back them up because they won't be touched\n if (!this.#areAssetsIncluded()) {\n return;\n }\n // TODO: this should catch all thrown errors and bubble it up to engine so it can be reported as a non-fatal diagnostic message telling the user they may need to manually delete assets\n if (this.strapi.config.get<{ provider: string }>('plugin::upload').provider === 'local') {\n this.#reportInfo('removing assets backup');\n assertValidStrapi(this.strapi);\n const backupDirectory = path.join(\n this.strapi.dirs.static.public,\n this.uploadsBackupDirectoryName\n );\n await fse.rm(backupDirectory, { recursive: true, force: true });\n this.#reportInfo('successfully removed assets backup');\n }\n }\n\n // TODO: Move this logic to the restore strategy\n async createAssetsWriteStream(): Promise<Writable> {\n assertValidStrapi(this.strapi, 'Not able to stream Assets');\n this.#reportInfo('creating assets write stream');\n if (!this.#areAssetsIncluded()) {\n throw new ProviderTransferError(\n 'Attempting to transfer assets when `assets` is not set in restore options'\n );\n }\n\n const removeAssetsBackup = this.#removeAssetsBackup.bind(this);\n const strapi = this.strapi;\n const transaction = this.transaction;\n const fileEntitiesMapper = this.#entitiesMapper['plugin::upload.file'];\n\n const restoreMediaEntitiesContent = this.#isContentTypeIncluded('plugin::upload.file');\n\n return new Writable({\n objectMode: true,\n async final(next) {\n // Delete the backup folder\n await removeAssetsBackup();\n next();\n },\n async write(chunk: IAsset, _encoding, callback) {\n await transaction?.attach(async () => {\n const uploadData = {\n ...chunk.metadata,\n stream: Readable.from(chunk.stream),\n buffer: chunk?.buffer,\n };\n\n const provider = strapi.config.get<{ provider: string }>('plugin::upload').provider;\n\n const fileId = fileEntitiesMapper?.[uploadData.id];\n if (!fileId) {\n return callback(new Error(`File ID not found for ID: ${uploadData.id}`));\n }\n\n try {\n await strapi.plugin('upload').provider.uploadStream(uploadData);\n\n // if we're not supposed to transfer the associated entities, stop here\n if (!restoreMediaEntitiesContent) {\n return callback();\n }\n\n // Files formats are stored within the parent file entity\n if (uploadData?.type) {\n const entry: IFile = await strapi.db.query('plugin::upload.file').findOne({\n where: { id: fileId },\n });\n if (!entry) {\n throw new Error('file not found');\n }\n const specificFormat = entry?.formats?.[uploadData.type];\n if (specificFormat) {\n specificFormat.url = uploadData.url;\n }\n await strapi.db.query('plugin::upload.file').update({\n where: { id: entry.id },\n data: {\n formats: entry.formats,\n provider,\n },\n });\n return callback();\n }\n\n const entry: IFile = await strapi.db.query('plugin::upload.file').findOne({\n where: { id: fileId },\n });\n if (!entry) {\n throw new Error('file not found');\n }\n entry.url = uploadData.url;\n await strapi.db.query('plugin::upload.file').update({\n where: { id: entry.id },\n data: {\n url: entry.url,\n provider,\n },\n });\n return callback();\n } catch (error) {\n return callback(new Error(`Error while uploading asset ${chunk.filename} ${error}`));\n }\n });\n },\n });\n }\n\n async createConfigurationWriteStream(): Promise<Writable> {\n assertValidStrapi(this.strapi, 'Not able to stream Configurations');\n this.#reportInfo('creating configuration write stream');\n const { strategy } = this.options;\n\n if (strategy === 'restore') {\n return restore.createConfigurationWriteStream(this.strapi, this.transaction);\n }\n\n throw new ProviderValidationError(`Invalid strategy ${strategy}`, {\n check: 'strategy',\n strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n\n async createLinksWriteStream(): Promise<Writable> {\n this.#reportInfo('creating links write stream');\n if (!this.strapi) {\n throw new Error('Not able to stream links. Strapi instance not found');\n }\n\n const { strategy } = this.options;\n const mapID = (uid: string, id: number): number | undefined => this.#entitiesMapper[uid]?.[id];\n\n if (strategy === 'restore') {\n return restore.createLinksWriteStream(mapID, this.strapi, this.transaction, this.onWarning);\n }\n\n throw new ProviderValidationError(`Invalid strategy ${strategy}`, {\n check: 'strategy',\n strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n}\n\nexport const createLocalStrapiDestinationProvider = (\n options: ILocalStrapiDestinationProviderOptions\n) => {\n return new LocalStrapiDestinationProvider(options);\n};\n"],"names":["VALID_CONFLICT_STRATEGIES","DEFAULT_CONFLICT_STRATEGY","LocalStrapiDestinationProvider","bootstrap","diagnostics","validateOptions","strapi","options","getStrapi","ProviderInitializationError","db","lifecycles","disable","transaction","utils","close","autoDestroy","assertValidStrapi","end","enable","undefined","destroy","rollback","reportInfo","beforeTransfer","Error","attach","trx","strategy","handleAssetsBackup","deleteAllAssets","deleteFromRestoreOptions","error","getMetadata","strapiVersion","config","get","createdAt","Date","toISOString","version","getSchemas","schemas","contentTypes","components","createEntitiesWriteStream","updateMappingTable","type","oldID","newID","entitiesMapper","Object","assign","restore","ProviderValidationError","check","validStrategies","createAssetsWriteStream","areAssetsIncluded","ProviderTransferError","removeAssetsBackup","bind","fileEntitiesMapper","restoreMediaEntitiesContent","isContentTypeIncluded","Writable","objectMode","final","next","write","chunk","_encoding","callback","uploadData","metadata","stream","Readable","from","buffer","provider","fileId","id","plugin","uploadStream","entry","query","findOne","where","specificFormat","formats","url","update","data","filename","createConfigurationWriteStream","createLinksWriteStream","mapID","uid","onWarning","constructor","name","assets","notIncluded","entities","include","includes","excluded","exclude","uploadsBackupDirectoryName","now","message","report","details","origin","kind","queryBuilder","select","transacting","file","delete","fileFormat","values","assetsDirectory","path","join","dirs","static","public","backupDirectory","fse","access","constants","W_OK","R_OK","F_OK","move","mkdir","outputFile","err","code","rm","recursive","force","createLocalStrapiDestinationProvider"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;MAwBaA,yBAA4B,GAAA;AAAC,IAAA;;AACnC,MAAMC,4BAA4B;IAyBvC,YAEA,iBAAA,8BAAA,CAAA,cAAA,CAAA;;AAEC,MACD;AAoBA,kBAAA,iBAAA,8BAAA,CAAA,oBAAA,CAAA,EAIA,sBAWA,iBAAA,8BAAA,CAAA,wBAAA,CAAA,EAAA,WAAA,iBAAA,8BAAA,CAAA,aAAA,CAAA,EAsBA,gBAgBM,iBAAA,8BAAA,CAAA,kBAAA,CAAA,EAAA,yBAAA,iBAAA,8BAAA,CAAA,2BAAA,CAAA,EASA,qFA6GA,mBA2CA,iBAAA,8BAAA,CAAA,qBAAA,CAAA,EAAA,mBAAA,iBAAA,8BAAA,CAAA,qBAAA,CAAA;AA9PR,MAAMC,8BAAAA,CAAAA;IA4BJ,MAAMC,SAAAA,CAAUC,WAAiC,EAAiB;QAChE,+BAAA,CAAA,IAAI,EAAEA,YAAAA,CAAAA,CAAAA,YAAcA,CAAAA,GAAAA,WAAAA;QACpB,+BAAA,CAAA,IAAI,EAAEC,gBAAAA,CAAAA,CAAAA,gBAAAA,CAAAA,EAAAA;QACN,IAAI,CAACC,MAAM,GAAG,MAAM,IAAI,CAACC,OAAO,CAACC,SAAS,EAAA;AAC1C,QAAA,IAAI,CAAC,IAAI,CAACF,MAAM,EAAE;AAChB,YAAA,MAAM,IAAIG,2BA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,IAAIL,8BAA+BK,CAAAA,OAAAA,CAAAA;AAC5C;;;;"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../../../src/strapi/providers/local-destination/index.ts"],"sourcesContent":["import { Writable, Readable } from 'stream';\nimport path from 'path';\nimport * as fse from 'fs-extra';\nimport type { Knex } from 'knex';\nimport type { Core, Struct } from '@strapi/types';\nimport type {\n IAsset,\n IDestinationProvider,\n IFile,\n IMetadata,\n ProviderType,\n Transaction,\n} from '../../../../types';\nimport type { IDiagnosticReporter } from '../../../utils/diagnostic';\n\nimport { restore } from './strategies';\nimport * as utils from '../../../utils';\nimport {\n ProviderInitializationError,\n ProviderTransferError,\n ProviderValidationError,\n} from '../../../errors/providers';\nimport { assertValidStrapi } from '../../../utils/providers';\n\nexport const VALID_CONFLICT_STRATEGIES = ['restore'];\nexport const DEFAULT_CONFLICT_STRATEGY = 'restore';\n\nexport interface ILocalStrapiDestinationProviderOptions {\n getStrapi(): Core.Strapi | Promise<Core.Strapi>; // return an initialized instance of Strapi\n\n autoDestroy?: boolean; // shut down the instance returned by getStrapi() at the end of the transfer\n restore?: restore.IRestoreOptions; // erase data in strapi database before transfer; required if strategy is 'restore'\n strategy: 'restore'; // conflict management strategy; only the restore strategy is available at this time\n}\n\nclass LocalStrapiDestinationProvider implements IDestinationProvider {\n name = 'destination::local-strapi';\n\n type: ProviderType = 'destination';\n\n options: ILocalStrapiDestinationProviderOptions;\n\n strapi?: Core.Strapi;\n\n transaction?: Transaction;\n\n uploadsBackupDirectoryName: string;\n\n onWarning?: ((message: string) => void) | undefined;\n\n #diagnostics?: IDiagnosticReporter;\n\n /**\n * The entities mapper is used to map old entities to their new IDs\n */\n #entitiesMapper: { [type: string]: { [id: number]: number } };\n\n constructor(options: ILocalStrapiDestinationProviderOptions) {\n this.options = options;\n this.#entitiesMapper = {};\n this.uploadsBackupDirectoryName = `uploads_backup_${Date.now()}`;\n }\n\n async bootstrap(diagnostics?: IDiagnosticReporter): Promise<void> {\n this.#diagnostics = diagnostics;\n this.#validateOptions();\n this.strapi = await this.options.getStrapi();\n if (!this.strapi) {\n throw new ProviderInitializationError('Could not access local strapi');\n }\n this.strapi.db.lifecycles.disable();\n this.transaction = utils.transaction.createTransaction(this.strapi);\n }\n\n // TODO: either move this to restore strategy, or restore strategy should given access to these instead of repeating the logic possibly in a different way\n #areAssetsIncluded = () => {\n return this.options.restore?.assets;\n };\n\n #isContentTypeIncluded = (type: string) => {\n const notIncluded =\n this.options.restore?.entities?.include &&\n !this.options.restore?.entities?.include?.includes(type);\n const excluded =\n this.options.restore?.entities?.exclude &&\n this.options.restore?.entities.exclude.includes(type);\n\n return !excluded && !notIncluded;\n };\n\n #reportInfo(message: string) {\n this.#diagnostics?.report({\n details: {\n createdAt: new Date(),\n message,\n origin: 'local-destination-provider',\n },\n kind: 'info',\n });\n }\n\n async close(): Promise<void> {\n const { autoDestroy } = this.options;\n assertValidStrapi(this.strapi);\n this.transaction?.end();\n this.strapi.db.lifecycles.enable();\n // Basically `!== false` but more deterministic\n if (autoDestroy === undefined || autoDestroy === true) {\n await this.strapi?.destroy();\n }\n }\n\n #validateOptions() {\n this.#reportInfo('validating options');\n if (!VALID_CONFLICT_STRATEGIES.includes(this.options.strategy)) {\n throw new ProviderValidationError(`Invalid strategy ${this.options.strategy}`, {\n check: 'strategy',\n strategy: this.options.strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n\n // require restore options when using restore\n if (this.options.strategy === 'restore' && !this.options.restore) {\n throw new ProviderValidationError('Missing restore options');\n }\n }\n\n async #deleteFromRestoreOptions() {\n assertValidStrapi(this.strapi);\n if (!this.options.restore) {\n throw new ProviderValidationError('Missing restore options');\n }\n this.#reportInfo('deleting record ');\n return restore.deleteRecords(this.strapi, this.options.restore);\n }\n\n async #deleteAllAssets(trx?: Knex.Transaction) {\n assertValidStrapi(this.strapi);\n this.#reportInfo('deleting all assets');\n // if we're not restoring files, don't touch the files\n if (!this.#areAssetsIncluded()) {\n return;\n }\n\n const stream: Readable = this.strapi.db\n // Create a query builder instance (default type is 'select')\n .queryBuilder('plugin::upload.file')\n // Fetch all columns\n .select('*')\n // Attach the transaction\n .transacting(trx)\n // Get a readable stream\n .stream();\n\n // TODO use bulk delete when exists in providers\n for await (const file of stream) {\n await this.strapi.plugin('upload').provider.delete(file);\n if (file.formats) {\n for (const fileFormat of Object.values(file.formats)) {\n await this.strapi.plugin('upload').provider.delete(fileFormat);\n }\n }\n }\n\n this.#reportInfo('deleted all assets');\n }\n\n async rollback() {\n this.#reportInfo('Rolling back transaction');\n await this.transaction?.rollback();\n this.#reportInfo('Rolled back transaction');\n }\n\n async beforeTransfer() {\n if (!this.strapi) {\n throw new Error('Strapi instance not found');\n }\n\n await this.transaction?.attach(async (trx) => {\n try {\n if (this.options.strategy === 'restore') {\n await this.#handleAssetsBackup();\n await this.#deleteAllAssets(trx);\n await this.#deleteFromRestoreOptions();\n }\n } catch (error) {\n throw new Error(`restore failed ${error}`);\n }\n });\n }\n\n getMetadata(): IMetadata {\n this.#reportInfo('getting metadata');\n assertValidStrapi(this.strapi, 'Not able to get Schemas');\n const strapiVersion = this.strapi.config.get<string>('info.strapi');\n const createdAt = new Date().toISOString();\n\n return {\n createdAt,\n strapi: {\n version: strapiVersion,\n },\n };\n }\n\n getSchemas(): Record<string, Struct.Schema> {\n this.#reportInfo('getting schema');\n assertValidStrapi(this.strapi, 'Not able to get Schemas');\n\n const schemas = utils.schema.schemasToValidJSON({\n ...this.strapi.contentTypes,\n ...this.strapi.components,\n });\n\n return utils.schema.mapSchemasValues(schemas);\n }\n\n createEntitiesWriteStream(): Writable {\n assertValidStrapi(this.strapi, 'Not able to import entities');\n this.#reportInfo('creating entities stream');\n const { strategy } = this.options;\n\n const updateMappingTable = (type: string, oldID: number, newID: number) => {\n if (!this.#entitiesMapper[type]) {\n this.#entitiesMapper[type] = {};\n }\n\n Object.assign(this.#entitiesMapper[type], { [oldID]: newID });\n };\n\n if (strategy === 'restore') {\n return restore.createEntitiesWriteStream({\n strapi: this.strapi,\n updateMappingTable,\n transaction: this.transaction,\n });\n }\n\n throw new ProviderValidationError(`Invalid strategy ${this.options.strategy}`, {\n check: 'strategy',\n strategy: this.options.strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n\n async #handleAssetsBackup() {\n assertValidStrapi(this.strapi, 'Not able to create the assets backup');\n\n // if we're not restoring assets, don't back them up because they won't be touched\n if (!this.#areAssetsIncluded()) {\n return;\n }\n\n if (this.strapi.config.get<{ provider: string }>('plugin::upload').provider === 'local') {\n this.#reportInfo('creating assets backup directory');\n const assetsDirectory = path.join(this.strapi.dirs.static.public, 'uploads');\n const backupDirectory = path.join(\n this.strapi.dirs.static.public,\n this.uploadsBackupDirectoryName\n );\n\n try {\n // Check access before attempting to do anything\n await fse.access(\n assetsDirectory,\n // eslint-disable-next-line no-bitwise\n fse.constants.W_OK | fse.constants.R_OK | fse.constants.F_OK\n );\n // eslint-disable-next-line no-bitwise\n await fse.access(path.join(assetsDirectory, '..'), fse.constants.W_OK | fse.constants.R_OK);\n\n await fse.move(assetsDirectory, backupDirectory);\n await fse.mkdir(assetsDirectory);\n // Create a .gitkeep file to ensure the directory is not empty\n await fse.outputFile(path.join(assetsDirectory, '.gitkeep'), '');\n this.#reportInfo(`created assets backup directory ${backupDirectory}`);\n } catch (err) {\n throw new ProviderTransferError(\n 'The backup folder for the assets could not be created inside the public folder. Please ensure Strapi has write permissions on the public directory',\n {\n code: 'ASSETS_DIRECTORY_ERR',\n }\n );\n }\n return backupDirectory;\n }\n }\n\n async #removeAssetsBackup() {\n assertValidStrapi(this.strapi, 'Not able to remove Assets');\n // if we're not restoring assets, don't back them up because they won't be touched\n if (!this.#areAssetsIncluded()) {\n return;\n }\n // TODO: this should catch all thrown errors and bubble it up to engine so it can be reported as a non-fatal diagnostic message telling the user they may need to manually delete assets\n if (this.strapi.config.get<{ provider: string }>('plugin::upload').provider === 'local') {\n this.#reportInfo('removing assets backup');\n assertValidStrapi(this.strapi);\n const backupDirectory = path.join(\n this.strapi.dirs.static.public,\n this.uploadsBackupDirectoryName\n );\n await fse.rm(backupDirectory, { recursive: true, force: true });\n this.#reportInfo('successfully removed assets backup');\n }\n }\n\n // TODO: Move this logic to the restore strategy\n async createAssetsWriteStream(): Promise<Writable> {\n assertValidStrapi(this.strapi, 'Not able to stream Assets');\n this.#reportInfo('creating assets write stream');\n if (!this.#areAssetsIncluded()) {\n throw new ProviderTransferError(\n 'Attempting to transfer assets when `assets` is not set in restore options'\n );\n }\n\n const removeAssetsBackup = this.#removeAssetsBackup.bind(this);\n const strapi = this.strapi;\n const transaction = this.transaction;\n const fileEntitiesMapper = this.#entitiesMapper['plugin::upload.file'];\n\n const restoreMediaEntitiesContent = this.#isContentTypeIncluded('plugin::upload.file');\n\n return new Writable({\n objectMode: true,\n async final(next) {\n // Delete the backup folder\n await removeAssetsBackup();\n next();\n },\n async write(chunk: IAsset, _encoding, callback) {\n await transaction?.attach(async () => {\n const uploadData = {\n ...chunk.metadata,\n stream: Readable.from(chunk.stream),\n buffer: chunk?.buffer,\n };\n\n const provider = strapi.config.get<{ provider: string }>('plugin::upload').provider;\n\n const fileId = fileEntitiesMapper?.[uploadData.id];\n if (!fileId) {\n return callback(new Error(`File ID not found for ID: ${uploadData.id}`));\n }\n\n try {\n await strapi.plugin('upload').provider.uploadStream(uploadData);\n\n // if we're not supposed to transfer the associated entities, stop here\n if (!restoreMediaEntitiesContent) {\n return callback();\n }\n\n // Files formats are stored within the parent file entity\n if (uploadData?.type) {\n const entry: IFile = await strapi.db.query('plugin::upload.file').findOne({\n where: { id: fileId },\n });\n if (!entry) {\n throw new Error('file not found');\n }\n const specificFormat = entry?.formats?.[uploadData.type];\n if (specificFormat) {\n specificFormat.url = uploadData.url;\n }\n await strapi.db.query('plugin::upload.file').update({\n where: { id: entry.id },\n data: {\n formats: entry.formats,\n provider,\n },\n });\n return callback();\n }\n\n const entry: IFile = await strapi.db.query('plugin::upload.file').findOne({\n where: { id: fileId },\n });\n if (!entry) {\n throw new Error('file not found');\n }\n entry.url = uploadData.url;\n await strapi.db.query('plugin::upload.file').update({\n where: { id: entry.id },\n data: {\n url: entry.url,\n provider,\n },\n });\n return callback();\n } catch (error) {\n return callback(new Error(`Error while uploading asset ${chunk.filename} ${error}`));\n }\n });\n },\n });\n }\n\n async createConfigurationWriteStream(): Promise<Writable> {\n assertValidStrapi(this.strapi, 'Not able to stream Configurations');\n this.#reportInfo('creating configuration write stream');\n const { strategy } = this.options;\n\n if (strategy === 'restore') {\n return restore.createConfigurationWriteStream(this.strapi, this.transaction);\n }\n\n throw new ProviderValidationError(`Invalid strategy ${strategy}`, {\n check: 'strategy',\n strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n\n async createLinksWriteStream(): Promise<Writable> {\n this.#reportInfo('creating links write stream');\n if (!this.strapi) {\n throw new Error('Not able to stream links. Strapi instance not found');\n }\n\n const { strategy } = this.options;\n const mapID = (uid: string, id: number): number | undefined => this.#entitiesMapper[uid]?.[id];\n\n if (strategy === 'restore') {\n return restore.createLinksWriteStream(mapID, this.strapi, this.transaction, this.onWarning);\n }\n\n throw new ProviderValidationError(`Invalid strategy ${strategy}`, {\n check: 'strategy',\n strategy,\n validStrategies: VALID_CONFLICT_STRATEGIES,\n });\n }\n}\n\nexport const createLocalStrapiDestinationProvider = (\n options: ILocalStrapiDestinationProviderOptions\n) => {\n return new LocalStrapiDestinationProvider(options);\n};\n"],"names":["VALID_CONFLICT_STRATEGIES","DEFAULT_CONFLICT_STRATEGY","LocalStrapiDestinationProvider","bootstrap","diagnostics","strapi","options","getStrapi","ProviderInitializationError","db","lifecycles","disable","transaction","utils","close","autoDestroy","assertValidStrapi","end","enable","undefined","destroy","rollback","beforeTransfer","Error","attach","trx","strategy","error","getMetadata","strapiVersion","config","get","createdAt","Date","toISOString","version","getSchemas","schemas","contentTypes","components","createEntitiesWriteStream","updateMappingTable","type","oldID","newID","Object","assign","restore","ProviderValidationError","check","validStrategies","createAssetsWriteStream","ProviderTransferError","removeAssetsBackup","bind","fileEntitiesMapper","restoreMediaEntitiesContent","Writable","objectMode","final","next","write","chunk","_encoding","callback","uploadData","metadata","stream","Readable","from","buffer","provider","fileId","id","plugin","uploadStream","entry","query","findOne","where","specificFormat","formats","url","update","data","filename","createConfigurationWriteStream","createLinksWriteStream","mapID","uid","onWarning","name","assets","notIncluded","entities","include","includes","excluded","exclude","uploadsBackupDirectoryName","now","message","report","details","origin","kind","queryBuilder","select","transacting","file","delete","fileFormat","values","assetsDirectory","path","join","dirs","static","public","backupDirectory","fse","access","constants","W_OK","R_OK","F_OK","move","mkdir","outputFile","err","code","rm","recursive","force","createLocalStrapiDestinationProvider"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;MAwBaA,yBAA4B,GAAA;AAAC,IAAA;;AACnC,MAAMC,4BAA4B;IAyBvC,YAEA,iBAAA,8BAAA,CAAA,cAAA,CAAA;;AAEC,MACD;AAoBA,kBAAA,iBAAA,8BAAA,CAAA,oBAAA,CAAA,EAIA,sBAWA,iBAAA,8BAAA,CAAA,wBAAA,CAAA,EAAA,WAAA,iBAAA,8BAAA,CAAA,aAAA,CAAA,EAsBA,gBAgBM,iBAAA,8BAAA,CAAA,kBAAA,CAAA,EAAA,yBAAA,iBAAA,8BAAA,CAAA,2BAAA,CAAA,EASA,qFA6GA,mBA2CA,iBAAA,8BAAA,CAAA,qBAAA,CAAA,EAAA,mBAAA,iBAAA,8BAAA,CAAA,qBAAA,CAAA;AA9PR,MAAMC,8BAAAA,CAAAA;IA4BJ,MAAMC,SAAAA,CAAUC,WAAiC,EAAiB;QAChE,+BAAA,CAAA,IAAI,EAAC,YAAA,CAAA,CAAA,YAAeA,CAAAA,GAAAA,WAAAA;QACpB,+BAAA,CAAA,IAAI,EAAC,gBAAA,CAAA,CAAA,gBAAA,CAAA,EAAA;QACL,IAAI,CAACC,MAAM,GAAG,MAAM,IAAI,CAACC,OAAO,CAACC,SAAS,EAAA;AAC1C,QAAA,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gC,EAAEM,eAAiB,CAAA,CAAA,CAAA;AACvE,SAAA,CAAE,OAAOU,GAAK,EAAA;YACZ,MAAM,IAAI7E,sBACR,oJACA,EAAA;gBACE8E,IAAM,EAAA;AACR,aAAA,CAAA;AAEJ;QACA,OAAOX,eAAAA;AACT;AACF;AAEA,eAAA,kBAAA,GAAA;IACEvG,iBAAkB,CAAA,IAAI,CAACX,MAAM,EAAE,2BAAA,CAAA;;AAE/B,IAAA,IAAI,CAAC,+BAAA,CAAA,IAAI,EAAC,oBAAA,kBAAsB,CAAA,EAAA,EAAA;AAC9B,QAAA;AACF;;IAEA,IAAI,IAAI,CAACA,MAAM,CAACyB,MAAM,CAACC,GAAG,CAAuB,gBAAA,CAAA,CAAkBwC,QAAQ,KAAK,OAAS,EAAA;QACvF,+BAAA,CAAA,IAAI,EAAC,WAAA,CAAA,CAAA,WAAY,CAAA,CAAA,wBAAA,CAAA;QACjBvD,iBAAkB,CAAA,IAAI,CAACX,MAAM,CAAA;AAC7B,QAAA,MAAMkH,kBAAkBL,IAAKC,CAAAA,IAAI,CAC/B,IAAI,CAAC9G,MAAM,CAAC+G,IAAI,CAACC,MAAM,CAACC,MAAM,EAC9B,IAAI,CAACnB,0BAA0B,CAAA;QAEjC,MAAMqB,GAAAA,CAAIW,EAAE,CAACZ,eAAiB,EAAA;YAAEa,SAAW,EAAA,IAAA;YAAMC,KAAO,EAAA;AAAK,SAAA,CAAA;QAC7D,+BAAA,CAAA,IAAI,EAAC,WAAA,CAAA,CAAA,WAAY,CAAA,CAAA,oCAAA,CAAA;AACnB;AACF;AAmIK,MAAMC,uCAAuC,CAClDhI,OAAAA,GAAAA;AAEA,IAAA,OAAO,IAAIJ,8BAA+BI,CAAAA,OAAAA,CAAAA;AAC5C;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configuration.js","sources":["../../../../../../src/strapi/providers/local-destination/strategies/restore/configuration.ts"],"sourcesContent":["import { Writable } from 'stream';\nimport { omit } from 'lodash/fp';\nimport chalk from 'chalk';\nimport type { Core } from '@strapi/types';\nimport { ProviderTransferError } from '../../../../../errors/providers';\nimport { IConfiguration, Transaction } from '../../../../../../types';\n\nconst omitInvalidCreationAttributes = omit(['id']);\n\nconst restoreCoreStore = async <T extends { value: unknown }>(strapi: Core.Strapi, values: T) => {\n const data = omitInvalidCreationAttributes(values);\n return strapi.db.query('strapi::core-store').create({\n data: {\n ...data,\n value: JSON.stringify(data.value),\n },\n });\n};\n\nconst restoreWebhooks = async <T extends { value: unknown }>(strapi: Core.Strapi, values: T) => {\n const data = omitInvalidCreationAttributes(values);\n return strapi.db.query('strapi::webhook').create({ data });\n};\n\nexport const restoreConfigs = async (strapi: Core.Strapi, config: IConfiguration) => {\n if (config.type === 'core-store') {\n return restoreCoreStore(strapi, config.value as { value: unknown });\n }\n\n if (config.type === 'webhook') {\n return restoreWebhooks(strapi, config.value as { value: unknown });\n }\n};\n\nexport const createConfigurationWriteStream = async (\n strapi: Core.Strapi,\n transaction?: Transaction\n) => {\n return new Writable({\n objectMode: true,\n async write<T extends { id: number }>(\n config: IConfiguration<T>,\n _encoding: BufferEncoding,\n callback: (error?: Error | null) => void\n ) {\n await transaction?.attach(async () => {\n try {\n await restoreConfigs(strapi, config);\n } catch (error) {\n return callback(\n new ProviderTransferError(\n `Failed to import ${chalk.yellowBright(config.type)} (${chalk.greenBright(\n config.value.id\n )}`\n )\n );\n }\n callback();\n });\n },\n });\n};\n"],"names":["omitInvalidCreationAttributes","omit","restoreCoreStore","strapi","values","data","db","query","create","value","JSON","stringify","restoreWebhooks","restoreConfigs","config","type","createConfigurationWriteStream","transaction","Writable","objectMode","write","_encoding","callback","attach","error","ProviderTransferError","chalk","yellowBright","greenBright","id"],"mappings":";;;;;;;AAOA,MAAMA,gCAAgCC,OAAK,CAAA;AAAC,IAAA;AAAK,CAAA,CAAA;AAEjD,MAAMC,gBAAAA,GAAmB,OAAqCC,MAAqBC,EAAAA,MAAAA,GAAAA;AACjF,IAAA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BACd,OAAOF,QAAAA,CACL,IAAIG,+BACF,CAAA,CAAC,iBAAiB,EAAEC,KAAAA,CAAMC,YAAY,CAACb,
|
|
1
|
+
{"version":3,"file":"configuration.js","sources":["../../../../../../src/strapi/providers/local-destination/strategies/restore/configuration.ts"],"sourcesContent":["import { Writable } from 'stream';\nimport { omit } from 'lodash/fp';\nimport chalk from 'chalk';\nimport type { Core } from '@strapi/types';\nimport { ProviderTransferError } from '../../../../../errors/providers';\nimport { IConfiguration, Transaction } from '../../../../../../types';\n\nconst omitInvalidCreationAttributes = omit(['id']);\n\nconst restoreCoreStore = async <T extends { value: unknown }>(strapi: Core.Strapi, values: T) => {\n const data = omitInvalidCreationAttributes(values);\n return strapi.db.query('strapi::core-store').create({\n data: {\n ...data,\n value: JSON.stringify(data.value),\n },\n });\n};\n\nconst restoreWebhooks = async <T extends { value: unknown }>(strapi: Core.Strapi, values: T) => {\n const data = omitInvalidCreationAttributes(values);\n return strapi.db.query('strapi::webhook').create({ data });\n};\n\nexport const restoreConfigs = async (strapi: Core.Strapi, config: IConfiguration) => {\n if (config.type === 'core-store') {\n return restoreCoreStore(strapi, config.value as { value: unknown });\n }\n\n if (config.type === 'webhook') {\n return restoreWebhooks(strapi, config.value as { value: unknown });\n }\n};\n\nexport const createConfigurationWriteStream = async (\n strapi: Core.Strapi,\n transaction?: Transaction\n) => {\n return new Writable({\n objectMode: true,\n async write<T extends { id: number }>(\n config: IConfiguration<T>,\n _encoding: BufferEncoding,\n callback: (error?: Error | null) => void\n ) {\n await transaction?.attach(async () => {\n try {\n await restoreConfigs(strapi, config);\n } catch (error) {\n return callback(\n new ProviderTransferError(\n `Failed to import ${chalk.yellowBright(config.type)} (${chalk.greenBright(\n config.value.id\n )}`\n )\n );\n }\n callback();\n });\n },\n });\n};\n"],"names":["omitInvalidCreationAttributes","omit","restoreCoreStore","strapi","values","data","db","query","create","value","JSON","stringify","restoreWebhooks","restoreConfigs","config","type","createConfigurationWriteStream","transaction","Writable","objectMode","write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AAAA,CAAAA,MAAyB,EACzBO,SAAyB,EACzBC,QAAwC,EAAA;AAExC,YAAA,MAAML,aAAaM,MAAO,CAAA,UAAA;gBACxB,IAAI;AACF,oBAAA,MAAMV,eAAeV,MAAQW,EAAAA,MAAAA,CAAAA;AAC/B,iBAAA,CAAE,OAAOU,KAAO,EAAA;oBACd,OAAOF,QAAAA,CACL,IAAIG,+BACF,CAAA,CAAC,iBAAiB,EAAEC,KAAAA,CAAMC,YAAY,CAACb,MAAAA,CAAOC,IAAI,CAAE,CAAA,EAAE,EAAEW,KAAME,CAAAA,WAAW,CACvEd,MAAOL,CAAAA,KAAK,CAACoB,EAAE,CACd,CAAA,CAAA,CAAA,CAAA;AAGT;AACAP,gBAAAA,QAAAA,EAAAA;AACF,aAAA,CAAA;AACF;AACF,KAAA,CAAA;AACF;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configuration.mjs","sources":["../../../../../../src/strapi/providers/local-destination/strategies/restore/configuration.ts"],"sourcesContent":["import { Writable } from 'stream';\nimport { omit } from 'lodash/fp';\nimport chalk from 'chalk';\nimport type { Core } from '@strapi/types';\nimport { ProviderTransferError } from '../../../../../errors/providers';\nimport { IConfiguration, Transaction } from '../../../../../../types';\n\nconst omitInvalidCreationAttributes = omit(['id']);\n\nconst restoreCoreStore = async <T extends { value: unknown }>(strapi: Core.Strapi, values: T) => {\n const data = omitInvalidCreationAttributes(values);\n return strapi.db.query('strapi::core-store').create({\n data: {\n ...data,\n value: JSON.stringify(data.value),\n },\n });\n};\n\nconst restoreWebhooks = async <T extends { value: unknown }>(strapi: Core.Strapi, values: T) => {\n const data = omitInvalidCreationAttributes(values);\n return strapi.db.query('strapi::webhook').create({ data });\n};\n\nexport const restoreConfigs = async (strapi: Core.Strapi, config: IConfiguration) => {\n if (config.type === 'core-store') {\n return restoreCoreStore(strapi, config.value as { value: unknown });\n }\n\n if (config.type === 'webhook') {\n return restoreWebhooks(strapi, config.value as { value: unknown });\n }\n};\n\nexport const createConfigurationWriteStream = async (\n strapi: Core.Strapi,\n transaction?: Transaction\n) => {\n return new Writable({\n objectMode: true,\n async write<T extends { id: number }>(\n config: IConfiguration<T>,\n _encoding: BufferEncoding,\n callback: (error?: Error | null) => void\n ) {\n await transaction?.attach(async () => {\n try {\n await restoreConfigs(strapi, config);\n } catch (error) {\n return callback(\n new ProviderTransferError(\n `Failed to import ${chalk.yellowBright(config.type)} (${chalk.greenBright(\n config.value.id\n )}`\n )\n );\n }\n callback();\n });\n },\n });\n};\n"],"names":["omitInvalidCreationAttributes","omit","restoreCoreStore","strapi","values","data","db","query","create","value","JSON","stringify","restoreWebhooks","restoreConfigs","config","type","createConfigurationWriteStream","transaction","Writable","objectMode","write","_encoding","callback","attach","error","ProviderTransferError","chalk","yellowBright","greenBright","id"],"mappings":";;;;;AAOA,MAAMA,gCAAgCC,IAAK,CAAA;AAAC,IAAA;AAAK,CAAA,CAAA;AAEjD,MAAMC,gBAAAA,GAAmB,OAAqCC,MAAqBC,EAAAA,MAAAA,GAAAA;AACjF,IAAA,MAAMC,OAAOL,6BAA8BI,CAAAA,MAAAA,CAAAA;AAC3C,IAAA,OAAOD,OAAOG,EAAE,CAACC,KAAK,CAAC,oBAAA,CAAA,CAAsBC,MAAM,CAAC;QAClDH,IAAM,EAAA;AACJ,YAAA,GAAGA,IAAI;AACPI,YAAAA,KAAAA,EAAOC,IAAKC,CAAAA,SAAS,CAACN,IAAAA,CAAKI,KAAK;AAClC;AACF,KAAA,CAAA;AACF,CAAA;AAEA,MAAMG,eAAAA,GAAkB,OAAqCT,MAAqBC,EAAAA,MAAAA,GAAAA;AAChF,IAAA,MAAMC,OAAOL,6BAA8BI,CAAAA,MAAAA,CAAAA;AAC3C,IAAA,OAAOD,OAAOG,EAAE,CAACC,KAAK,CAAC,iBAAA,CAAA,CAAmBC,MAAM,CAAC;AAAEH,QAAAA;AAAK,KAAA,CAAA;AAC1D,CAAA;AAEO,MAAMQ,cAAiB,GAAA,OAAOV,MAAqBW,EAAAA,MAAAA,GAAAA;IACxD,IAAIA,MAAAA,CAAOC,IAAI,KAAK,YAAc,EAAA;QAChC,OAAOb,gBAAAA,CAAiBC,MAAQW,EAAAA,MAAAA,CAAOL,KAAK,CAAA;AAC9C;IAEA,IAAIK,MAAAA,CAAOC,IAAI,KAAK,SAAW,EAAA;QAC7B,OAAOH,eAAAA,CAAgBT,MAAQW,EAAAA,MAAAA,CAAOL,KAAK,CAAA;AAC7C;AACF;AAEO,MAAMO,8BAAiC,GAAA,OAC5Cb,MACAc,EAAAA,WAAAA,GAAAA;AAEA,IAAA,OAAO,IAAIC,QAAS,CAAA;QAClBC,UAAY,EAAA,IAAA;AACZ,QAAA,MAAMC,KACJN,CAAAA,CAAAA,MAAyB,EACzBO,SAAyB,EACzBC,QAAwC,EAAA;AAExC,YAAA,MAAML,aAAaM,MAAO,CAAA,UAAA;gBACxB,IAAI;AACF,oBAAA,MAAMV,eAAeV,MAAQW,EAAAA,MAAAA,CAAAA;AAC/B,iBAAA,CAAE,OAAOU,KAAO,EAAA;oBACd,OAAOF,QAAAA,CACL,IAAIG,qBACF,CAAA,CAAC,iBAAiB,EAAEC,KAAAA,CAAMC,YAAY,CAACb,
|
|
1
|
+
{"version":3,"file":"configuration.mjs","sources":["../../../../../../src/strapi/providers/local-destination/strategies/restore/configuration.ts"],"sourcesContent":["import { Writable } from 'stream';\nimport { omit } from 'lodash/fp';\nimport chalk from 'chalk';\nimport type { Core } from '@strapi/types';\nimport { ProviderTransferError } from '../../../../../errors/providers';\nimport { IConfiguration, Transaction } from '../../../../../../types';\n\nconst omitInvalidCreationAttributes = omit(['id']);\n\nconst restoreCoreStore = async <T extends { value: unknown }>(strapi: Core.Strapi, values: T) => {\n const data = omitInvalidCreationAttributes(values);\n return strapi.db.query('strapi::core-store').create({\n data: {\n ...data,\n value: JSON.stringify(data.value),\n },\n });\n};\n\nconst restoreWebhooks = async <T extends { value: unknown }>(strapi: Core.Strapi, values: T) => {\n const data = omitInvalidCreationAttributes(values);\n return strapi.db.query('strapi::webhook').create({ data });\n};\n\nexport const restoreConfigs = async (strapi: Core.Strapi, config: IConfiguration) => {\n if (config.type === 'core-store') {\n return restoreCoreStore(strapi, config.value as { value: unknown });\n }\n\n if (config.type === 'webhook') {\n return restoreWebhooks(strapi, config.value as { value: unknown });\n }\n};\n\nexport const createConfigurationWriteStream = async (\n strapi: Core.Strapi,\n transaction?: Transaction\n) => {\n return new Writable({\n objectMode: true,\n async write<T extends { id: number }>(\n config: IConfiguration<T>,\n _encoding: BufferEncoding,\n callback: (error?: Error | null) => void\n ) {\n await transaction?.attach(async () => {\n try {\n await restoreConfigs(strapi, config);\n } catch (error) {\n return callback(\n new ProviderTransferError(\n `Failed to import ${chalk.yellowBright(config.type)} (${chalk.greenBright(\n config.value.id\n )}`\n )\n );\n }\n callback();\n });\n },\n });\n};\n"],"names":["omitInvalidCreationAttributes","omit","restoreCoreStore","strapi","values","data","db","query","create","value","JSON","stringify","restoreWebhooks","restoreConfigs","config","type","createConfigurationWriteStream","transaction","Writable","objectMode","write","_encoding","callback","attach","error","ProviderTransferError","chalk","yellowBright","greenBright","id"],"mappings":";;;;;AAOA,MAAMA,gCAAgCC,IAAK,CAAA;AAAC,IAAA;AAAK,CAAA,CAAA;AAEjD,MAAMC,gBAAAA,GAAmB,OAAqCC,MAAqBC,EAAAA,MAAAA,GAAAA;AACjF,IAAA,MAAMC,OAAOL,6BAA8BI,CAAAA,MAAAA,CAAAA;AAC3C,IAAA,OAAOD,OAAOG,EAAE,CAACC,KAAK,CAAC,oBAAA,CAAA,CAAsBC,MAAM,CAAC;QAClDH,IAAM,EAAA;AACJ,YAAA,GAAGA,IAAI;AACPI,YAAAA,KAAAA,EAAOC,IAAKC,CAAAA,SAAS,CAACN,IAAAA,CAAKI,KAAK;AAClC;AACF,KAAA,CAAA;AACF,CAAA;AAEA,MAAMG,eAAAA,GAAkB,OAAqCT,MAAqBC,EAAAA,MAAAA,GAAAA;AAChF,IAAA,MA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